text
stringlengths
8
6.88M
/* * (C) Copyright 2016-2018 Ben Karsin, Nodari Sitchinava * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include<stdio.h> #include<iostream> #include<fstream> #include<vector> #include<cmath> #include<random> #include<algorithm> #include "../params.h" #include "sortRowMajor.hxx" // Used for testing different size base cases #define SQUARES 1 #define COLS 32 // Print column-major __device__ void printSmem(int* smem) { if(threadIdx.x==0) { for(int j=0; j<(W); j++) { for(int i=0; i<(COLS)*SQUARES; i++) { printf("%d ", smem[j+i*(W)]); } printf("\n"); } printf("\n"); } __syncthreads(); } void printResult(int* data) { for(int j=0; j<W; j++) { for(int i=0; i<ELTS*SQUARES; i++) { printf("%d ", data[j*ELTS*SQUARES+i]); } printf("\n"); } } /* Main basecase sorting Kernel */ template<typename T, fptr_t f> __global__ void squareSort(T* data, int N) { T regs[ELTS]; int blockOffset = (N/gridDim.x)*blockIdx.x; for(int sec = 0; sec < (N/gridDim.x); sec += M*(THREADS/W)) { for(int i=0; i<ELTS; i++) { regs[i] = data[blockOffset + sec + (i*THREADS) + threadIdx.x]; } int tid = threadIdx.x%W; int warpId = threadIdx.x/W; int warpOffset = warpId*ELTS*W; __shared__ T sData[M]; // Code that is needed for base case larger than 1024. // TODO: generalize for either 1024, 2048, or 4096 base case without changing code... /* sortSquareRowMajor(regs, warpId%2); warpSwap2(regs, sData, (warpId<(warpId^2))); warpSwap4(regs, sData); transposeSquares(regs, sData+warpOffset); for(int i=0; i<ELTS; i++) { data[blockOffset + sec + warpOffset + W*i + tid] = sData[threadIdx.x*W + (tid+i)%W]; } */ sortSquareRowMajor<T,f>(regs, false); // Warps within a block use the same shared memory, so they have to take turns transposing // This lets us have more warps and increases performance! for(int i=0; i<warpId; i++) __syncthreads(); // transpose in shared memory then write to global transposeSquares<T>(regs, sData); for(int i=0; i<ELTS; i++) { data[blockOffset + sec + warpOffset + W*i + tid] = sData[tid*W + (tid+i)%W]; } for(int i=(THREADS/W)-1; i>warpId; i--) // Wait for other warps to catch back up __syncthreads(); } }
#include <iostream> using namespace std; int input; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> input; int sCount = 0; int maxLine = 1; while(true){ maxLine += 6 * sCount; if(input <= maxLine){ break; } sCount++; } cout << sCount+1 << endl; return 0; }
#include <bits/stdc++.h> #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ); template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; using ll = long long; int main(){ int n, m; cin >> n >> m; vector<int> a(m), b(m); rep(i, m) cin >> a[i] >> b[i]; int k; cin >> k; vector<int> c(k), d(k); rep(i, k) cin >> c[i] >> d[i]; int ans = 0; for(int bit=0; bit<(1<<k); bit++){ vector<bool> check(n+1); rep(i, k){ if((bit>>i) & 1) check[c[i]] = true; else check[d[i]] = true; } int tmp = 0; rep(i, m) tmp += (check[a[i]] && check[b[i]]); chmax(ans, tmp); } cout << ans << endl; }
//--------------------------------------------------------------------------- #ifndef SearchToolH #define SearchToolH //--------------------------------------------------------------------------- #define MAX_BUFFER 0x2000 #define SINGLE_WILDCARD 0x0100 // '??' Sign #define COMPLEX_WILDCARD 0x0101 // '%%' Sign //--------------------------------------------------------------------------- class CSearchEngine { private: DWORD m_nPatternLength; WORD m_wWildcardPattern[MAX_BUFFER]; BYTE m_cNormalPattern[MAX_BUFFER]; private: static WORD WINAPI HexToInt(WORD wCh); static DWORD WINAPI WildcardSearch(LPVOID pBuffer, DWORD nLength, LPWORD pwWildcardPattern, DWORD nPatternLength, DWORD &nResultLength); static DWORD WINAPI BinarySearch(LPVOID pBuffer, DWORD nLength, LPVOID pPattern, DWORD nPatternLength); BOOL WINAPI WildcardPatternPreprocess(LPSTR pWildcardPattern); BOOL WINAPI NormalPatternPreprocess(LPSTR pPattern); public: CSearchEngine(VOID); ~CSearchEngine(VOID); LPVOID WINAPI WildcardSearch(LPVOID pBuffer, DWORD nLength, LPSTR pWildcardPattern, LPDWORD pResultLength = NULL); LPVOID WINAPI NormalSearch(LPVOID pBuffer, DWORD nLength, LPVOID pPattern, DWORD nPatternLength); LPVOID WINAPI NormalSearch(LPVOID pBuffer, DWORD nLength, LPSTR pPattern); }; //--------------------------------------------------------------------------- #endif
#include <fstream> #include <sstream> #include <unistd.h> #include <bcm2835.h> using namespace std; std::string slurp(const char *filename) { std::ifstream in; in.open(filename, std::ifstream::in | std::ifstream::binary); std::stringstream sstr; sstr << in.rdbuf(); in.close(); return sstr.str(); } void dac_write(uint16_t value) { if(value>4095) value=4095; value |= 0b0011000000000000; char buf[2]; buf[0] = value >>8; buf[1] = value & 0xff; bcm2835_spi_writenb(buf, 2); } int main() { string song{slurp("song16k.raw")}; bcm2835_init(); bcm2835_spi_begin(); bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_64); // ~ 4 MHz bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_16); bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_1024); // 390kHz on Pi3. Works //bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_512); bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default // set rising edge detection for gpio 21, pyhsical 40 int trigger = 21; bcm2835_gpio_fsel(trigger, BCM2835_GPIO_FSEL_INPT); //bcm2835_gpio_ren(trigger); //int i = 0; for(unsigned char c : song) { //while(!bcm2835_gpio_eds(trigger)) usleep(10); // time to put out a new value //printf("."); //fflush(stdout); //bcm2835_gpio_set_eds(trigger); // clearing event detection so we can be triggered again while(bcm2835_gpio_lev(trigger) == HIGH); #if 0 dac_write((uint16_t) c << 4); #else bcm2835_spi_writenb((char*) &c, 1); #endif while(bcm2835_gpio_lev(trigger) == LOW); //dac_write(i); //i = 1 - i; //bcm2835_delayMicroseconds(125); } bcm2835_gpio_clr_ren(trigger); bcm2835_spi_end(); bcm2835_close(); return 0; }
// #include <SFML/Graphics.hpp> #include "SFML-2.5.1-macos-clang/include/SFML/Graphics.hpp" /* The RectButton class are rectangular buttons. In this programme, it will be * used for the different cleanup functions. This is why the class will be used * directly in scene.cpp. */ class RectButton { public: /* This constructor is used to initialise the different buttons in * the Scene class constructor */ RectButton(); /* Currently unused */ RectButton(float x, float y, float w, float h, sf::Color fillCol, sf::Color outlineCol, std::string idletext, std::string runtext, sf::Font f, float textsize); /* Initialises all the class variables for the button * Arguments: float x, y - top left and top right point for the button * idleText - text to display when not being run * All other arguments should be self-explanatory * Returns: void */ void setAttr(float x, float y, float w, float h, sf::Color fillCol, sf::Color outlineCol, std::string idletext, std::string runtext, sf::Font f, float textsize); /* Checks if button is pressed * Arguments: float x, float y - coordinates of user's click * Returns: true - if user has clicked the button * false - otherwise */ bool checkPressed(float x, float y); /* Draws the button to the window specified */ void draw(sf::RenderWindow &window); /* To be called after programme has finished running. The button will * revert back to the idle text and change its colours */ void finish(void); private: bool pressed; float topLeftX, topLeftY; float width, height; float textSize; std::string rawIdText, rawRunText; sf::Font font; sf::Color colour, borderCol; sf::Text idleText, runText; sf::RectangleShape rect; void init(void); };
#include "Singletom.h" Singleton *Singleton::_instance = 0; Singleton::Singleton() { std::cout << "Singleton..........." << std::endl; } Singleton::~Singleton() { } Singleton *Singleton::Instance() { if (!_instance) { _instance = new Singleton(); } return _instance; }
#pragma once #include <map> #include <vector> #include <mutex> #include "../../system.hpp" #include "test.h" namespace sbg { struct Group; struct GroupContainer; struct CollisionEngine : Engine { CollisionEngine(); void execute(Time time) override; void add(std::shared_ptr<Entity> object, std::vector<Group*> groups, std::vector<Group*> collisionGroups); void remove(std::weak_ptr<Entity> object); protected: bool findByGroup(Group* group, std::pair<const std::weak_ptr<Entity>, std::pair<std::vector<Group*>, std::vector<Group*>>>& object); std::mutex _inserting; std::mutex _changeTests; void makeObjectList(); std::map<std::weak_ptr<Entity>, std::pair<std::vector<Group*>, std::vector<Group*>>, std::owner_less<std::weak_ptr<Entity>>> _objects; bool _listClean; std::vector<Test> _tests; }; }
/** @file midl.c * @brief ldap bdb back-end ID List functions */ /* $OpenLDAP$ */ /* This work is part of OpenLDAP Software <http://www.openldap.org/>. * * Copyright 2000-2018 The OpenLDAP Foundation. * Portions Copyright 2001-2018 Howard Chu, Symas Corp. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include <limits.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include "midl.h" /** @defgroup internal LMDB Internals * @{ */ /** @defgroup idls ID List Management * @{ */ #define CMP(x,y) ( (x) < (y) ? -1 : (x) > (y) ) unsigned mdb_midl_search( MDB_IDL ids, MDB_ID id ) { /* * binary search of id in ids * if found, returns position of id * if not found, returns first position greater than id */ unsigned base = 0; unsigned cursor = 1; int val = 0; unsigned n = ids[0]; while( 0 < n ) { unsigned pivot = n >> 1; cursor = base + pivot + 1; val = CMP( ids[cursor], id ); if( val < 0 ) { n = pivot; } else if ( val > 0 ) { base = cursor; n -= pivot + 1; } else { return cursor; } } if( val > 0 ) { ++cursor; } return cursor; } #if 0 /* superseded by append/sort */ int mdb_midl_insert( MDB_IDL ids, MDB_ID id ) { unsigned x, i; x = mdb_midl_search( ids, id ); assert( x > 0 ); if( x < 1 ) { /* internal error */ return -2; } if ( x <= ids[0] && ids[x] == id ) { /* duplicate */ assert(0); return -1; } if ( ++ids[0] >= MDB_IDL_DB_MAX ) { /* no room */ --ids[0]; return -2; } else { /* insert id */ for (i=ids[0]; i>x; i--) ids[i] = ids[i-1]; ids[x] = id; } return 0; } #endif MDB_IDL mdb_midl_alloc(int num) { MDB_IDL ids = malloc((num+2) * sizeof(MDB_ID)); if (ids) { *ids++ = num; *ids = 0; } return ids; } void mdb_midl_free(MDB_IDL ids) { if (ids) free(ids-1); } void mdb_midl_shrink( MDB_IDL *idp ) { MDB_IDL ids = *idp; if (*(--ids) > MDB_IDL_UM_MAX && (ids = realloc(ids, (MDB_IDL_UM_MAX+2) * sizeof(MDB_ID)))) { *ids++ = MDB_IDL_UM_MAX; *idp = ids; } } static int mdb_midl_grow( MDB_IDL *idp, int num ) { MDB_IDL idn = *idp-1; /* grow it */ idn = realloc(idn, (*idn + num + 2) * sizeof(MDB_ID)); if (!idn) return ENOMEM; *idn++ += num; *idp = idn; return 0; } int mdb_midl_need( MDB_IDL *idp, unsigned num ) { MDB_IDL ids = *idp; num += ids[0]; if (num > ids[-1]) { num = (num + num/4 + (256 + 2)) & -256; if (!(ids = realloc(ids-1, num * sizeof(MDB_ID)))) return ENOMEM; *ids++ = num - 2; *idp = ids; } return 0; } int mdb_midl_append( MDB_IDL *idp, MDB_ID id ) { MDB_IDL ids = *idp; /* Too big? */ if (ids[0] >= ids[-1]) { if (mdb_midl_grow(idp, MDB_IDL_UM_MAX)) return ENOMEM; ids = *idp; } ids[0]++; ids[ids[0]] = id; return 0; } int mdb_midl_append_list( MDB_IDL *idp, MDB_IDL app ) { MDB_IDL ids = *idp; /* Too big? */ if (ids[0] + app[0] >= ids[-1]) { if (mdb_midl_grow(idp, app[0])) return ENOMEM; ids = *idp; } memcpy(&ids[ids[0]+1], &app[1], app[0] * sizeof(MDB_ID)); ids[0] += app[0]; return 0; } int mdb_midl_append_range( MDB_IDL *idp, MDB_ID id, unsigned n ) { MDB_ID *ids = *idp, len = ids[0]; /* Too big? */ if (len + n > ids[-1]) { if (mdb_midl_grow(idp, n | MDB_IDL_UM_MAX)) return ENOMEM; ids = *idp; } ids[0] = len + n; ids += len; while (n) ids[n--] = id++; return 0; } void mdb_midl_xmerge( MDB_IDL idl, MDB_IDL merge ) { MDB_ID old_id, merge_id, i = merge[0], j = idl[0], k = i+j, total = k; idl[0] = (MDB_ID)-1; /* delimiter for idl scan below */ old_id = idl[j]; while (i) { merge_id = merge[i--]; for (; old_id < merge_id; old_id = idl[--j]) idl[k--] = old_id; idl[k--] = merge_id; } idl[0] = total; } /* Quicksort + Insertion sort for small arrays */ #define SMALL 8 #define MIDL_SWAP(a,b) { itmp=(a); (a)=(b); (b)=itmp; } void mdb_midl_sort( MDB_IDL ids ) { /* Max possible depth of int-indexed tree * 2 items/level */ int istack[sizeof(int)*CHAR_BIT * 2]; int i,j,k,l,ir,jstack; MDB_ID a, itmp; ir = (int)ids[0]; l = 1; jstack = 0; for(;;) { if (ir - l < SMALL) { /* Insertion sort */ for (j=l+1;j<=ir;j++) { a = ids[j]; for (i=j-1;i>=1;i--) { if (ids[i] >= a) break; ids[i+1] = ids[i]; } ids[i+1] = a; } if (jstack == 0) break; ir = istack[jstack--]; l = istack[jstack--]; } else { k = (l + ir) >> 1; /* Choose median of left, center, right */ MIDL_SWAP(ids[k], ids[l+1]); if (ids[l] < ids[ir]) { MIDL_SWAP(ids[l], ids[ir]); } if (ids[l+1] < ids[ir]) { MIDL_SWAP(ids[l+1], ids[ir]); } if (ids[l] < ids[l+1]) { MIDL_SWAP(ids[l], ids[l+1]); } i = l+1; j = ir; a = ids[l+1]; for(;;) { do i++; while(ids[i] > a); do j--; while(ids[j] < a); if (j < i) break; MIDL_SWAP(ids[i],ids[j]); } ids[l+1] = ids[j]; ids[j] = a; jstack += 2; if (ir-i+1 >= j-l) { istack[jstack] = ir; istack[jstack-1] = i; ir = j-1; } else { istack[jstack] = j-1; istack[jstack-1] = l; l = i; } } } } unsigned mdb_mid2l_search( MDB_ID2L ids, MDB_ID id ) { /* * binary search of id in ids * if found, returns position of id * if not found, returns first position greater than id */ unsigned base = 0; unsigned cursor = 1; int val = 0; unsigned n = (unsigned)ids[0].mid; while( 0 < n ) { unsigned pivot = n >> 1; cursor = base + pivot + 1; val = CMP( id, ids[cursor].mid ); if( val < 0 ) { n = pivot; } else if ( val > 0 ) { base = cursor; n -= pivot + 1; } else { return cursor; } } if( val > 0 ) { ++cursor; } return cursor; } int mdb_mid2l_insert( MDB_ID2L ids, MDB_ID2 *id ) { unsigned x, i; x = mdb_mid2l_search( ids, id->mid ); if( x < 1 ) { /* internal error */ return -2; } if ( x <= ids[0].mid && ids[x].mid == id->mid ) { /* duplicate */ return -1; } if ( ids[0].mid >= MDB_IDL_UM_MAX ) { /* too big */ return -2; } else { /* insert id */ ids[0].mid++; for (i=(unsigned)ids[0].mid; i>x; i--) ids[i] = ids[i-1]; ids[x] = *id; } return 0; } int mdb_mid2l_append( MDB_ID2L ids, MDB_ID2 *id ) { /* Too big? */ if (ids[0].mid >= MDB_IDL_UM_MAX) { return -2; } ids[0].mid++; ids[ids[0].mid] = *id; return 0; } #ifdef MDB_VL32 unsigned mdb_mid3l_search( MDB_ID3L ids, MDB_ID id ) { /* * binary search of id in ids * if found, returns position of id * if not found, returns first position greater than id */ unsigned base = 0; unsigned cursor = 1; int val = 0; unsigned n = (unsigned)ids[0].mid; while( 0 < n ) { unsigned pivot = n >> 1; cursor = base + pivot + 1; val = CMP( id, ids[cursor].mid ); if( val < 0 ) { n = pivot; } else if ( val > 0 ) { base = cursor; n -= pivot + 1; } else { return cursor; } } if( val > 0 ) { ++cursor; } return cursor; } int mdb_mid3l_insert( MDB_ID3L ids, MDB_ID3 *id ) { unsigned x, i; x = mdb_mid3l_search( ids, id->mid ); if( x < 1 ) { /* internal error */ return -2; } if ( x <= ids[0].mid && ids[x].mid == id->mid ) { /* duplicate */ return -1; } /* insert id */ ids[0].mid++; for (i=(unsigned)ids[0].mid; i>x; i--) ids[i] = ids[i-1]; ids[x] = *id; return 0; } #endif /* MDB_VL32 */ /** @} */ /** @} */
#include "vmManager.h" #include "swapManager.h" #include "system.h" #include "fifo.h" #include "lru.h" VMManager::VMManager(){ swapMgr = new SwapManager(); // policy = new FIFO(); // policy = new LRU(); policy = new LRU(); // no pages in physical memory for( int i = 0; i < NumPhysPages; i++ ){ activePageMap[i] = -1; activePages[i] = NULL; } //activePages = { 0 }; } VMManager::~VMManager(){ delete swapMgr; delete policy; } // allocates a swap page int VMManager::getPage(){ return swapMgr->allocPage(); } // writes to swap bool VMManager::writePage( int pPage, char* buffer, int size, int offset){ return swapMgr->writePage( pPage, buffer, size, offset ); } // swaps a swap page into physical memory, clearing room and writing // victim to swap if necessary. int VMManager::swap( TranslationEntry* newPage ){ // get page number to load int pPage; int sPage = newPage->physicalPage; int oldPage = -1; //Part of code is deleted here. // swap new page in DEBUG( 'v', "Swapping out page %d, swapping in swap page %d to physical page %d\n", oldPage, sPage, pPage ); swapMgr->swap( pPage, sPage ); activePageMap[ pPage ] = sPage; activePages[ pPage ] = newPage; printf("L [%d]: [%d] -> [%d]\n", currentThread->space->pcb->pid, oldPage, pPage); return pPage; } void VMManager::copy( int fromPage, int toPage ){ swapMgr->copy( fromPage, toPage ); } // translate a swap page into a physical page and swaps a non-active page in. int VMManager::getPhysicalPage( TranslationEntry* page ){ int sPage = page->physicalPage; for( int i = 0; i < NumPhysPages; i++ ){ if( activePageMap[i] == sPage ) return i; } // the page is not active, so swap return swap( page ); } // remove page from active map, clear in swap mgr void VMManager::clearPage( int sPage ){ int pPage; DEBUG( 'v', "Clearing page %d\n", pPage ); for( pPage = 0; pPage < NumPhysPages; pPage++ ){ if( activePageMap[ pPage ] == sPage ){ activePageMap[ pPage ] = -1; activePages[ pPage ] = 0; break; } } memManager->clearPage( pPage ); swapMgr->clearPage( sPage ); policy->clearPage( pPage ); } // return the number of free swap sectors int VMManager::getFreePageCount(){ return swapMgr->getFreePageCount(); } void VMManager::markPage( int pPage ){ policy->markPage( pPage ); } //added funcs /* bool AddPage(TranslationEntry* page, SpaceId pid, char* buffer, int size); bool AddPage(TranslationEntry* page, SpaceId pid,int size); bool GetPage(TranslationEntry* page, SpaceId pid, char* buffer, int size); void CopyPage(TranslationEntry* page, SpaceId oldPID, SpaceId newPID); void RemovePages(SpaceId pid); void Mark(TranslationEntry* page); int free() {swapMgr->free();} */ bool VMManager::AddPage(TranslationEntry* page, SpaceId pid, char* buffer, int size) { printf("Z %d: %d\n", pid, page->virtualPage); return swapMgr->addPage(page, pid, buffer, size); } bool VMManager::AddPage(TranslationEntry* page, SpaceId pid, int size) { printf("Z %d: %d\n", pid, page->virtualPage); return swapMgr->addPage(page, pid,size); } void VMManager::RemovePages(SpaceId pid) { //lru->RemovePage(pid); policy->RemovePage(pid); swapMgr->removePages(pid); } bool VMManager::GetPage(TranslationEntry* page, SpaceId pid, char* buffer, int size) { DEBUG('3', "in getPage.. pid: %i\n", pid); if (swapMgr->findPage(pid, page->virtualPage, buffer) != NULL) { return true; } return false; } void VMManager::CopyPage(TranslationEntry* page, SpaceId oldPID, SpaceId newPID) { char buffer[PageSize]; DEBUG('3', "in copy page.. old pid: %i new pid: %i\n", oldPID, newPID); swapMgr->findPage(oldPID, page->virtualPage, buffer); swapMgr->addPage(page, newPID, buffer, PageSize); } void VMManager::Swap(int vpn, SpaceId pid) { int proc_kill; TranslationEntry* page = new TranslationEntry(); // No swap necessary, we have enough memory available //if (memory->freePages() != 0) { if(memManager->getAvailable() != 0){ int phys_page = memManager->getPage(); DEBUG('q', "Swapping into main memory page %d\n", phys_page); char* paddr = machine->mainMemory + phys_page*PageSize; page = swapMgr->findPage(pid, vpn, paddr); //DEBUG('q', "In vm->swap: phys_page %i \n", phys_page); page->physicalPage = phys_page; //DEBUG('q', "In vm->swap: vpn%i pid%i\n", vpn, pid); //lru->AddPage(page,pid); policy->AddPage(page, pid); printf("L %d: %d -> %d\n", pid, vpn, phys_page); ///DEBUG('3', "L %d: %d -> %d\n", pid, vpn, phys_page); } else { // Assumption is, if its in main memory, // its in the swap file as well //proc_kill = lru->tail_pid(); proc_kill = policy->tail_pid(); //TranslationEntry* victim = lru->GetLRU(); TranslationEntry* victim = policy->GetLRU(); DEBUG('q', "Finding a victim to swap out of main memory page %d\n", victim->physicalPage); victim->valid = false; char* paddr = machine->mainMemory + victim->physicalPage*PageSize; if (victim->dirty) { //DEBUG('3', "S %d: %d\n", pid, victim->physicalPage); printf("S %d: %d\n", pid, victim->physicalPage); swapMgr->writePage(pid, victim->virtualPage, paddr); } else { //DEBUG('3', "E %d: %d\n", pid, victim->physicalPage); printf("E %d: %d\n", pid, victim->physicalPage); } page = swapMgr->findPage(pid, vpn, paddr); page->physicalPage = victim->physicalPage; //lru->AddPage(page,pid); //lru->Remove_LRU_Page(); policy->AddPage(page, pid); policy->Remove_LRU_Page(); } page->valid = true; page->dirty = false; }
#include <stdio.h> int main(){ int b; printf("What integer do you want to convert? "); scanf("%d", &b); printf("%d 의 ASCII 값: %c\n", b, b); }
#include <iostream> #include <stdlib.h> using namespace std; #define MAX 500000 int A[MAX]; void maxHeapify(int i, int H){ int l, r, largest, tmp; l = i * 2; r = i * 2 + 1; if(l <= H && A[i] < A[l]) largest = l; else largest = i; if(r <= H && A[r] > A[largest]) largest = r; if(largest != i){ tmp = A[largest]; A[largest] = A[i]; A[i] = tmp; maxHeapify(largest, H); } } void buildMaxHeap(int H){ for(int i = H/2; i>0; i--) maxHeapify(i, H); } int main(void){ int H; cin >> H; for(int i=1; i<=H; i++){ cin >> A[i]; } buildMaxHeap(H); for(int i=1; i<=H; i++) cout << " " << A[i]; cout << endl; return 0; }
#include "StdAfx.h" #include "BonePacking.h" BonePacking::BonePacking(void) { } BonePacking::~BonePacking(void) { }
#include "Model.hpp" #include "Helper.hpp" #include "Integrator.hpp" #include <fstream> #include "Log.hpp" #include <sstream> #include <math.h> #include <dcosmology.h> ModelInterface::ModelInterface(map<string,double> params) : CosmoBasis(params) {} ModelInterface::~ModelInterface() {} double ModelInterface::Pkz_interp(double k, double z, int Pk_index) { return 0; } double ModelInterface::T21_interp(double z, int Tb_index) { return 0; } double ModelInterface::q_interp(double z, int q_index) { return 0; } double ModelInterface::r_interp(double z) { return 0; } double ModelInterface::Hf_interp(double z) { return 0; } double ModelInterface::H_interp(double z, int q_index) { return 0; } double ModelInterface::qp_interp(double z, int q_index) { return 0; } double ModelInterface::fz_interp(double z, int Tb_index) { return 0; } double ModelInterface::hubble_h(int q_index) { return 0; } int ModelInterface::Pkz_size() { return 0; } int ModelInterface::Tb_size() { return 0; } int ModelInterface::q_size() { return 0; } string ModelInterface::give_modelID() { return modelID; } void ModelInterface::set_Santos_params(double *alpha, double *beta,\ double *gamma, double *RLy, int Tb_index) {} void ModelInterface::update(map<string, double> params, int *Pk_index, int *Tb_index, int *q_index) {} void ModelInterface::writePK_T21_q() {} void ModelInterface::update_Pkz(map<string, double> params, int *Pk_index) {} void ModelInterface::update_T21(map<string, double> params, int *Tb_index) {} void ModelInterface::update_q(map<string, double> params, int *q_index) {} /************************/ /* Code for ModelParent */ /************************/ template<typename T21> ModelParent<T21>::ModelParent(map<string,double> params) : ModelInterface(params) {} template<typename T21> double ModelParent<T21>::Pkz_interp(double k, double z, int Pk_index) { //spline2dinterpolant interp; //#pragma omp critical //{ //interp = Pkz_interpolators[Pk_index].interpolator; //} if (Pk_index >= Pkz_interpolators.size()) cout << "ERROR in PKZ" << endl; return spline2dcalc(Pkz_interpolators[Pk_index].interpolator, k, z); } template<typename T21> double ModelParent<T21>::T21_interp(double z, int Tb_index) { //spline1dinterpolant interp; //#pragma omp critical //{ //interp = Tb_interpolators[Tb_index].interpolator; //} // The factor of 1000 is so I get the result in mK. if (Tb_index >= Tb_interpolators.size()) cout << "ERROR in Tb" << endl; return spline1dcalc(Tb_interpolators[Tb_index].interpolator,z); } template<typename T21> double ModelParent<T21>::q_interp(double z, int q_index) { //spline1dinterpolant interp; //#pragma omp critical //{ //interp = q_interpolators[q_index].interpolator; //} if (q_index >= q_interpolators.size()) cout << "ERROR in Q" << endl; return spline1dcalc(q_interpolators[q_index].interpolator,z); } template<typename T21> double ModelParent<T21>::r_interp(double z) { return q_interp(z, 0); } template<typename T21> double ModelParent<T21>::Hf_interp(double z) { if (q_interpolators.size() == 0) cout << "ERROR in HF" << endl; return spline1dcalc(q_interpolators[0].interpolator_Hf,z); } template<typename T21> double ModelParent<T21>::H_interp(double z, int q_index) { //spline1dinterpolant interp; //#pragma omp critical //{ // interp = q_interpolators[q_index].interpolator_Hf; //} if (q_index >= q_interpolators.size()) cout << "ERROR in H" << endl; return spline1dcalc(q_interpolators[q_index].interpolator_Hf,z); } template<typename T21> double ModelParent<T21>::qp_interp(double z, int q_index) { //spline1dinterpolant interp; //#pragma omp critical //{ // interp = q_interpolators[q_index].interpolator_qp; //} if (q_index >= q_interpolators.size()) cout << "ERROR in QP" << endl; return spline1dcalc(q_interpolators[q_index].interpolator_qp,z); } template<typename T21> double ModelParent<T21>::fz_interp(double z, int Tb_index) { //spline1dinterpolant interp; //#pragma omp critical //{ //interp = Tb_interpolators[Tb_index].fz_interpolator; //} if (Tb_index >= Tb_interpolators.size()) cout << "ERROR in FZ" << endl; return spline1dcalc(Tb_interpolators[Tb_index].fz_interpolator,z); } template<typename T21> double ModelParent<T21>::hubble_h(int q_index) { double h; if (q_index >= q_interpolators.size()) cout << "ERROR in h" << endl; //#pragma omp critical //{ h = q_interpolators[q_index].h; //} return h; } template<typename T21> void ModelParent<T21>::update(map<string, double> params, int *Pk_index, int *Tb_index, int *q_index) { try { //#pragma omp critical //{ update_Pkz(params, Pk_index); update_T21(params, Tb_index); update_q(params, q_index); //} } catch(alglib::ap_error e) { log<LOG_ERROR>("---- Error: %1%") % e.msg.c_str(); } } template<typename T21> void ModelParent<T21>::writePK_T21_q() { ofstream pk, q, t21; pk.open("PKZ.dat"); q.open("Q.dat"); t21.open("T21.dat"); for (int i = 0; i < 10000; i++) { double k = 0.001 + i*0.001; pk << k << " " << Pkz_interp(k,7,0) << endl; } pk.close(); for (int i = 0; i < 1000; i++) { double z = 7 + i*0.001; q << z << " " << q_interp(z,0) << endl; } q.close(); for (int i = 0; i < 1000; i++) { double z = 0.1 + i*0.1; t21 << z << " " << T21_interp(z,0) << endl; } t21.close(); } template<typename T21> int ModelParent<T21>::Pkz_size() { return Pkz_interpolators.size(); } template<typename T21> int ModelParent<T21>::Tb_size() { return Tb_interpolators.size(); } template<typename T21> int ModelParent<T21>::q_size() { return q_interpolators.size(); } /////////////////////////////////////////////////////////////////////////////// /* Code for CAMB_ARES */ /////////////////////////////////////////////////////////////////////////////// Model_CAMB_ARES::Model_CAMB_ARES(map<string,double> params, int *Pk_index, int *Tb_index, int *q_index) : ModelParent(params) { zmin_Ml = fiducial_params["zmin"]; zmax_Ml = fiducial_params["zmax"]; zsteps_Ml = fiducial_params["zsteps"]; modelID = "CAMB_ARES"; stepsize_Ml = abs(this->zmax_Ml - this->zmin_Ml)/(double)this->zsteps_Ml; CAMB = new CAMB_CALLER; log<LOG_BASIC>("... precalculating q ..."); update_q(fiducial_params, q_index); log<LOG_BASIC>("... q done ..."); log<LOG_BASIC>("... precalculating Pkz ..."); update_Pkz(fiducial_params, Pk_index); log<LOG_BASIC>("... Pkz done ..."); log<LOG_BASIC>("... precalculating 21cm interface ..."); log<LOG_BASIC>("... -> ARES for 21cm signal ..."); //AresInterface I; //ARES = &I; ARES = new AresInterface(); update_T21(fiducial_params, Tb_index); log<LOG_BASIC>("... 21cm interface built ..."); log<LOG_BASIC>("... Model_CAMB_ARES built ..."); } Model_CAMB_ARES::~Model_CAMB_ARES() { delete CAMB; delete ARES; } void Model_CAMB_ARES::update_Pkz(map<string,double> params, int *Pk_index) { bool do_calc = true; for (unsigned int i = 0; i < Pkz_interpolators.size(); ++i) { if (params["ombh2"] == Pkz_interpolators[i].ombh2 &&\ params["omnuh2"] == Pkz_interpolators[i].omnuh2 &&\ params["omch2"] == Pkz_interpolators[i].omch2 &&\ params["omk"] == Pkz_interpolators[i].omk &&\ params["hubble"] == Pkz_interpolators[i].hubble &&\ params["T_CMB"] == Pkz_interpolators[i].tcmb &&\ params["w_DE"] == Pkz_interpolators[i].w_DE &&\ params["n_s"] == Pkz_interpolators[i].n_s &&\ params["A_s"] == Pkz_interpolators[i].A_s &&\ params["tau_reio"] == Pkz_interpolators[i].tau &&\ params["omega_lambda"] == Pkz_interpolators[i].omega_lambda){ log<LOG_VERBOSE>("Found precalculated Pkz"); do_calc = false; *Pk_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating Pkz from scratch"); Pk_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.tcmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; interp.n_s = params["n_s"]; interp.A_s = params["A_s"]; interp.tau = params["tau_reio"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; CAMB->call(params); vector<double> vk = CAMB->get_k_values(); vector<vector<double>> Pz = CAMB->get_Pz_values(); double z_stepsize = (params["zmax"] - params["zmin"])/(params["Pk_steps"] - 1); vector<double> vz, vP; for (unsigned int i = 0; i < Pz.size(); ++i) { vz.push_back(params["zmin"] + i * z_stepsize); vP.insert(vP.end(), Pz[i].begin(), Pz[i].end()); } real_1d_array matterpowerspectrum_k, matterpowerspectrum_z, matterpowerspectrum_P; matterpowerspectrum_k.setlength(vk.size()); matterpowerspectrum_z.setlength(vz.size()); matterpowerspectrum_P.setlength(vP.size()); for (unsigned int i = 0; i < vk.size(); i++){ matterpowerspectrum_k[i] = vk[i]; } for (unsigned int i = 0; i < vP.size(); i++){ matterpowerspectrum_P[i] = vP[i]; } for (unsigned int i = 0; i < vz.size(); i++){ matterpowerspectrum_z[i] = vz[i]; } spline2dinterpolant interpolator; spline2dbuildbilinearv(matterpowerspectrum_k, vk.size(),matterpowerspectrum_z, vz.size(),\ matterpowerspectrum_P, 1, interpolator); interp.interpolator = interpolator; Pkz_interpolators.push_back(interp); *Pk_index = Pkz_interpolators.size() - 1; log<LOG_VERBOSE>("Pkz update done"); log<LOG_DEBUG>("Model_CAMB_ARES::update_Pkz: Pkz has been updated using the following parameters:"); log<LOG_DEBUG>("ombh2 = %1%, omnuh2 = %2%, omch2 = %3%,\n \ omk = %4%, hubble = %5%, tcmb = %6%,\n \ w_DE = %7%, n_s = %8%, A_s = %9%, tau = %10%.")\ % interp.ombh2 % interp.omnuh2 % interp.omch2 %\ interp.omk % interp.hubble % interp.tcmb % interp.w_DE %\ interp.n_s % interp.A_s % interp.tau; } } void Model_CAMB_ARES::update_T21(map<string,double> params, int *Tb_index) { bool do_calc = true; for (unsigned int i = 0; i < Tb_interpolators.size(); ++i) { if (params["ombh2"] == Tb_interpolators[i].ombh2 &&\ params["omnuh2"] == Tb_interpolators[i].omnuh2 &&\ params["omch2"] == Tb_interpolators[i].omch2 &&\ params["omk"] == Tb_interpolators[i].omk &&\ params["hubble"] == Tb_interpolators[i].hubble &&\ params["sigma8"] == Tb_interpolators[i].s8 &&\ params["T_CMB"] == Tb_interpolators[i].T_CMB &&\ params["n_s"] == Tb_interpolators[i].n_s &&\ params["fstar"] == Tb_interpolators[i].fstar &&\ params["fesc"] == Tb_interpolators[i].fesc &&\ params["nion"] == Tb_interpolators[i].nion &&\ params["fx"] == Tb_interpolators[i].fX &&\ params["omega_lambda"] == Tb_interpolators[i].omega_lambda) { /* **** These parameters aren't part of the fiducial parameter * set, or, as is the case for w_DE, aren't used by ARES. params["Tmin"] == Tb_interpolators[i].Tmin &&\ params["w_DE"] == Tb_interpolators[i].w_DE &&\ params["Nlw"] == Tb_interpolators[i].Nlw &&\ params["cX"] == Tb_interpolators[i].cX &&\ params["HeByMass"] == Tb_interpolators[i].HeByMass */ log<LOG_VERBOSE>("found precalculated Ares"); do_calc = false; *Tb_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating T21 from scratch"); Tb_interpolator_ares interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.s8 = params["sigma8"]; interp.T_CMB = params["T_CMB"]; interp.n_s = params["n_s"]; interp.fstar = params["fstar"]; interp.fesc = params["fesc"]; interp.nion = params["nion"]; interp.fX = params["fx"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; interp.w_DE = -1; //params["w_DE"]; interp.Tmin = -1; //params["Tmin"]; interp.Nlw = -1; //params["Nlw"]; interp.cX = -1; //params["cX"]; interp.HeByMass = -1; //params["HeByMass"]; log<LOG_VERBOSE>("Ares is being updated"); ARES->updateAres(params); vector<double> vz, vTb; ARES->getTb(&vz, &vTb); real_1d_array Ares_z, Ares_Tb; Ares_z.setlength(vz.size()); Ares_Tb.setlength(vTb.size()); for (unsigned int i = 0; i < vz.size(); i++){ Ares_z[i] = vz[i]; } for (unsigned int i = 0; i < vTb.size(); i++){ Ares_Tb[i] = vTb[i]; } spline1dinterpolant interpolator; spline1dbuildcubic(Ares_z, Ares_Tb, interpolator); interp.interpolator = interpolator; Tb_interpolators.push_back(interp); *Tb_index = Tb_interpolators.size() - 1; log<LOG_VERBOSE>("Ares dTb update done"); } } void Model_CAMB_ARES::update_q(map<string,double> params, int *q_index) { bool limber = false; if (params["limber"] == 1.0) limber = true; // We first update q and then q' if the limber approximation is being used.. bool do_calc = true; for (unsigned int i = 0; i < q_interpolators.size(); ++i) { if (params["ombh2"] == q_interpolators[i].ombh2 &&\ params["omnuh2"] == q_interpolators[i].omnuh2 &&\ params["omch2"] == q_interpolators[i].omch2 &&\ params["omk"] == q_interpolators[i].omk &&\ params["hubble"] == q_interpolators[i].hubble &&\ params["T_CMB"] == q_interpolators[i].t_cmb &&\ params["w_DE"] == q_interpolators[i].w_DE &&\ params["omega_lambda"] == q_interpolators[i].omega_lambda) { log<LOG_VERBOSE>("Found precalculated q"); do_calc = false; *q_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating q from scratch"); q_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.t_cmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; interp.omk = params["omk"]; interp.omega_lambda = 0; } else { use_non_physical = true; interp.omk = 0; interp.omega_lambda = params["omega_lambda"]; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double D_H2 = c / (1000.0 * H_02); double w2 = params["w_DE"]; real_1d_array xs, ys, qps, hs; xs.setlength(this->zsteps_Ml+1); ys.setlength(this->zsteps_Ml+1); qps.setlength(this->zsteps_Ml+1); hs.setlength(this->zsteps_Ml+1); double h = 10e-4; double z; for (int n = 0; n <= this->zsteps_Ml; ++n) { z = this->zmin_Ml + n * this->stepsize_Ml; xs[n] = z; auto integrand = [&](double zp) { return 1/sqrt(O_Lambda * pow(1+zp,3*(1+w2)) + O_R2 * pow(1+zp,4) +\ O_M2 * pow(1+zp,3) + O_k2 * pow(1+zp,2)); }; double Z = integrate(integrand, 0.0, z, 1000, simpson()); if (limber) { double dc1 = integrate(integrand, 0.0, z+2*h, 1000, simpson()); double dc2 = integrate(integrand, 0.0, z+h, 1000, simpson()); double dc3 = integrate(integrand, 0.0, z-h, 1000, simpson()); double dc4 = integrate(integrand, 0.0, z-2*h, 1000, simpson()); qps[n] = abs(D_H2 * (-dc1 + 8 * dc2 - 8 * dc3 + dc4)); } ys[n] = D_H2 * Z; hs[n] = H_02 * sqrt(O_Lambda * pow(1+z,3*(1+w2)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2)); } spline1dinterpolant interpolator, interpolator_Hf, interpolator_qp; try { spline1dbuildlinear(xs,ys,interpolator); } catch(alglib::ap_error e){ log<LOG_ERROR>("---- Error in q(z): %1%") % e.msg.c_str(); } try { spline1dbuildlinear(xs,hs,interpolator_Hf); } catch(alglib::ap_error e){ log<LOG_ERROR>("---- Error in H(z): %1%") % e.msg.c_str(); } try { spline1dbuildlinear(xs,qps,interpolator_qp); } catch(alglib::ap_error e){ log<LOG_ERROR>("---- Error in q_prime(z): %1%") % e.msg.c_str(); } // If limber == false, the qp_interpolator will just be empty but that // is fine because it won't be used in that case. interp.h = h2; interp.interpolator = interpolator; interp.interpolator_Hf = interpolator_Hf; interp.interpolator_qp = interpolator_qp; q_interpolators.push_back(interp); *q_index = q_interpolators.size() - 1; log<LOG_VERBOSE>(" -- Calculating q is done --"); } } /////////////////////////////////////////////////////////////////////////////// /* Code for CAMB_G21 */ /////////////////////////////////////////////////////////////////////////////// Model_CAMB_G21::Model_CAMB_G21(map<string,double> params,\ int *Pk_index, int *Tb_index, int *q_index) : ModelParent(params) { zmin_Ml = fiducial_params["zmin"]; zmax_Ml = fiducial_params["zmax"]; zsteps_Ml = fiducial_params["zsteps"]; stepsize_Ml = abs(this->zmax_Ml - this->zmin_Ml)/(double)this->zsteps_Ml; modelID = "CAMB_G21"; CAMB = new CAMB_CALLER; log<LOG_BASIC>("... precalculating q ..."); update_q(fiducial_params, q_index); log<LOG_BASIC>("... q done ..."); log<LOG_BASIC>("... precalculating Pkz ..."); update_Pkz(fiducial_params, Pk_index); log<LOG_BASIC>("... Pkz done ..."); log<LOG_BASIC>("... precalculating 21cm interface ..."); log<LOG_BASIC>("... -> G21 for 21cm signal ..."); G21 = new Global21cmInterface(); update_T21(fiducial_params, Tb_index); log<LOG_BASIC>("... 21cm interface built ..."); log<LOG_BASIC>("... Model_CAMB_ARES built ..."); } Model_CAMB_G21::~Model_CAMB_G21() { delete CAMB; delete G21; } void Model_CAMB_G21::update_Pkz(map<string,double> params, int *Pk_index) { bool do_calc = true; for (unsigned int i = 0; i < Pkz_interpolators.size(); ++i) { if (params["ombh2"] == Pkz_interpolators[i].ombh2 &&\ params["omnuh2"] == Pkz_interpolators[i].omnuh2 &&\ params["omch2"] == Pkz_interpolators[i].omch2 &&\ params["omk"] == Pkz_interpolators[i].omk &&\ params["hubble"] == Pkz_interpolators[i].hubble &&\ params["T_CMB"] == Pkz_interpolators[i].tcmb &&\ params["w_DE"] == Pkz_interpolators[i].w_DE &&\ params["n_s"] == Pkz_interpolators[i].n_s &&\ params["A_s"] == Pkz_interpolators[i].A_s &&\ params["tau_reio"] == Pkz_interpolators[i].tau &&\ params["omega_lambda"] == Pkz_interpolators[i].omega_lambda ){ log<LOG_VERBOSE>("Found precalculated Pkz"); do_calc = false; *Pk_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating Pkz from scratch"); Pk_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.tcmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; interp.n_s = params["n_s"]; interp.A_s = params["A_s"]; interp.tau = params["tau_reio"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; CAMB->call(params); vector<double> vk = CAMB->get_k_values(); vector<vector<double>> Pz = CAMB->get_Pz_values(); double z_stepsize = (params["zmax"] - params["zmin"])/(params["Pk_steps"] - 1); vector<double> vz, vP; for (unsigned int i = 0; i < Pz.size(); ++i) { vz.push_back(params["zmin"] + i * z_stepsize); vP.insert(vP.end(), Pz[i].begin(), Pz[i].end()); } real_1d_array matterpowerspectrum_k, matterpowerspectrum_z, matterpowerspectrum_P; matterpowerspectrum_k.setlength(vk.size()); matterpowerspectrum_z.setlength(vz.size()); matterpowerspectrum_P.setlength(vP.size()); for (unsigned int i = 0; i < vk.size(); i++){ matterpowerspectrum_k[i] = vk[i]; } for (unsigned int i = 0; i < vP.size(); i++){ matterpowerspectrum_P[i] = vP[i]; } for (unsigned int i = 0; i < vz.size(); i++){ matterpowerspectrum_z[i] = vz[i]; } spline2dinterpolant interpolator; spline2dbuildbilinearv(matterpowerspectrum_k, vk.size(),matterpowerspectrum_z, vz.size(),\ matterpowerspectrum_P, 1, interpolator); interp.interpolator = interpolator; Pkz_interpolators.push_back(interp); *Pk_index = Pkz_interpolators.size() - 1; log<LOG_VERBOSE>("Pkz update done"); } } void Model_CAMB_G21::update_T21(map<string,double> params, int *Tb_index) { bool do_calc = true; for (unsigned int i = 0; i < Tb_interpolators.size(); ++i) { if (params["ombh2"] == Tb_interpolators[i].ombh2 &&\ params["omnuh2"] == Tb_interpolators[i].omnuh2 &&\ params["omch2"] == Tb_interpolators[i].omch2 &&\ params["omk"] == Tb_interpolators[i].omk &&\ params["hubble"] == Tb_interpolators[i].hubble &&\ params["sigma8"] == Tb_interpolators[i].s8 &&\ params["T_CMB"] == Tb_interpolators[i].T_CMB &&\ params["n_s"] == Tb_interpolators[i].n_s &&\ params["fstar"] == Tb_interpolators[i].fstar &&\ params["fesc"] == Tb_interpolators[i].fesc &&\ params["nion"] == Tb_interpolators[i].nion &&\ params["fx"] == Tb_interpolators[i].fx &&\ params["flya"] == Tb_interpolators[i].flya &&\ params["w_DE"] == Tb_interpolators[i].w_DE) { log<LOG_VERBOSE>("found precalculated G21"); do_calc = false; *Tb_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating T21 from scratch"); Tb_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.s8 = params["sigma8"]; interp.T_CMB = params["T_CMB"]; interp.n_s = params["n_s"]; interp.fstar = params["fstar"]; interp.fesc = params["fesc"]; interp.nion = params["nion"]; interp.fx = params["fx"]; interp.flya = params["flya"]; interp.w_DE = params["w_DE"]; G21->updateGlobal21cm(params); vector<double> vz, vTb; G21->getTb(&vz, &vTb); real_1d_array g21_z, g21_Tb; g21_z.setlength(vz.size()); g21_Tb.setlength(vTb.size()); for (unsigned int i = 0; i < vz.size(); i++){ g21_z[i] = vz[i]; } for (unsigned int i = 0; i < vTb.size(); i++){ g21_Tb[i] = vTb[i]; } spline1dinterpolant interpolator; spline1dbuildcubic(g21_z, g21_Tb, interpolator); interp.interpolator = interpolator; Tb_interpolators.push_back(interp); *Tb_index = Tb_interpolators.size() - 1; log<LOG_VERBOSE>("T21 update done"); } } void Model_CAMB_G21::update_q(map<string,double> params, int *q_index) { bool limber = false; if (params["limber"] == 1.0) limber = true; // We first update q and then q' if the limber approximation is being used.. bool do_calc = true; for (unsigned int i = 0; i < q_interpolators.size(); ++i) { if (params["ombh2"] == q_interpolators[i].ombh2 &&\ params["omnuh2"] == q_interpolators[i].omnuh2 &&\ params["omch2"] == q_interpolators[i].omch2 &&\ params["omk"] == q_interpolators[i].omk &&\ params["hubble"] == q_interpolators[i].hubble &&\ params["T_CMB"] == q_interpolators[i].t_cmb &&\ params["w_DE"] == q_interpolators[i].w_DE &&\ params["omega_lambda"] == q_interpolators[i].omega_lambda) { log<LOG_VERBOSE>("Found precalculated q"); do_calc = false; *q_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating q from scratch"); q_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.t_cmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; interp.omk = params["omk"]; interp.omega_lambda = 0; } else { use_non_physical = true; interp.omk = 0; interp.omega_lambda = params["omega_lambda"]; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double D_H2 = c / (1000.0 * H_02); double w2 = params["w_DE"]; real_1d_array xs, ys, qps, hs; xs.setlength(this->zsteps_Ml+1); ys.setlength(this->zsteps_Ml+1); qps.setlength(this->zsteps_Ml+1); hs.setlength(this->zsteps_Ml+1); double h = 10e-4; double z; for (int n = 0; n <= this->zsteps_Ml; ++n) { z = this->zmin_Ml + n * this->stepsize_Ml; xs[n] = z; auto integrand = [&](double zp) { return 1/sqrt(O_Lambda * pow(1+zp,3*(1+w2)) + O_R2 * pow(1+zp,4) +\ O_M2 * pow(1+zp,3) + O_k2 * pow(1+zp,2)); }; double Z = integrate(integrand, 0.0, z, 1000, simpson()); if (limber) { double dc1 = integrate(integrand, 0.0, z+2*h, 1000, simpson()); double dc2 = integrate(integrand, 0.0, z+h, 1000, simpson()); double dc3 = integrate(integrand, 0.0, z-h, 1000, simpson()); double dc4 = integrate(integrand, 0.0, z-2*h, 1000, simpson()); qps[n] = abs(D_H2 * (-dc1 + 8 * dc2 - 8 * dc3 + dc4)); } else qps[n] = (double)n; ys[n] = D_H2 * Z; hs[n] = H_02 * sqrt(O_Lambda * pow(1+z,3*(1+w2)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2)); } spline1dinterpolant interpolator, interpolator_Hf, interpolator_qp; spline1dbuildlinear(xs,ys,interpolator); spline1dbuildlinear(xs,hs,interpolator_Hf); spline1dbuildlinear(xs,qps,interpolator_qp); // If limber == false, the qp_interpolator will just be empty but that // is fine because it won't be used in that case. interp.h = h2; interp.interpolator = interpolator; interp.interpolator_Hf = interpolator_Hf; interp.interpolator_qp = interpolator_qp; q_interpolators.push_back(interp); *q_index = q_interpolators.size() - 1; log<LOG_VERBOSE>("q update done"); } } ///////////////////////////////////////////////////////////////////////////////// /* Code for Santos 2006 */ ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Note that this is the model Santos et al. 2006 use as their Fiducial model // // and so it is only valid in a redshift range of z in [15, 25]. // ///////////////////////////////////////////////////////////////////////////////// Model_Santos2006::Model_Santos2006(map<string, double> params,\ int *Pk_index, int *Tb_index, int *q_index) : ModelParent(params) { //Changing fiducial values to the ones they have used. map<string, double> new_params = give_fiducial_params(); new_params["omch2"] = 0.1277; new_params["ombh2"] = 0.02229; new_params["hubble"] = 73.2; new_params["n_s"] = 0.958; new_params["A_s"] = 1.562e-9; new_params["tau_reio"] = 0.089 ; set_fiducial_params(new_params); zmin_Ml = fiducial_params["zmin"]; zmax_Ml = fiducial_params["zmax"]; zsteps_Ml = fiducial_params["zsteps"]; stepsize_Ml = abs(this->zmax_Ml - this->zmin_Ml)/(double)this->zsteps_Ml; CAMB = new CAMB_CALLER; modelID = "Santos2006"; log<LOG_BASIC>("... precalculating q ..."); update_q(fiducial_params, q_index); log<LOG_BASIC>("... q done ..."); log<LOG_BASIC>("... precalculating Pkz ..."); update_Pkz(fiducial_params, Pk_index); log<LOG_BASIC>("... Pkz done ..."); log<LOG_BASIC>("... precalculating 21cm interface ..."); log<LOG_BASIC>("... -> Santos Model for 21cm signal ..."); update_T21(fiducial_params, Tb_index); log<LOG_BASIC>("... 21cm interface built ..."); log<LOG_BASIC>("... Model_Santos2006 built ..."); } Model_Santos2006::~Model_Santos2006() { delete CAMB; } void Model_Santos2006::update_Pkz(map<string,double> params, int *Pk_index) { bool do_calc = true; for (unsigned int i = 0; i < Pkz_interpolators.size(); ++i) { if (params["ombh2"] == Pkz_interpolators[i].ombh2 &&\ params["omnuh2"] == Pkz_interpolators[i].omnuh2 &&\ params["omch2"] == Pkz_interpolators[i].omch2 &&\ params["omk"] == Pkz_interpolators[i].omk &&\ params["hubble"] == Pkz_interpolators[i].hubble &&\ params["T_CMB"] == Pkz_interpolators[i].tcmb &&\ params["w_DE"] == Pkz_interpolators[i].w_DE &&\ params["n_s"] == Pkz_interpolators[i].n_s &&\ params["A_s"] == Pkz_interpolators[i].A_s &&\ params["tau_reio"] == Pkz_interpolators[i].tau &&\ params["omega_lambda"] == Pkz_interpolators[i].omega_lambda){ log<LOG_VERBOSE>("Found precalculated Pkz"); do_calc = false; *Pk_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating Pkz from scratch"); Pk_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.tcmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; interp.n_s = params["n_s"]; interp.A_s = params["A_s"]; interp.tau = params["tau_reio"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; CAMB->call(params); vector<double> vk = CAMB->get_k_values(); vector<vector<double>> Pz = CAMB->get_Pz_values(); double z_stepsize = (params["zmax"] - params["zmin"])/(params["Pk_steps"] - 1); vector<double> vz, vP; for (unsigned int i = 0; i < Pz.size(); ++i) { vz.push_back(params["zmin"] + i * z_stepsize); vP.insert(vP.end(), Pz[i].begin(), Pz[i].end()); } real_1d_array matterpowerspectrum_k, matterpowerspectrum_z, matterpowerspectrum_P; matterpowerspectrum_k.setlength(vk.size()); matterpowerspectrum_z.setlength(vz.size()); matterpowerspectrum_P.setlength(vP.size()); for (unsigned int i = 0; i < vk.size(); i++){ matterpowerspectrum_k[i] = vk[i]; } for (unsigned int i = 0; i < vP.size(); i++){ matterpowerspectrum_P[i] = vP[i]; } for (unsigned int i = 0; i < vz.size(); i++){ matterpowerspectrum_z[i] = vz[i]; } spline2dinterpolant interpolator; spline2dbuildbilinearv(matterpowerspectrum_k, vk.size(),matterpowerspectrum_z, vz.size(),\ matterpowerspectrum_P, 1, interpolator); interp.interpolator = interpolator; Pkz_interpolators.push_back(interp); *Pk_index = Pkz_interpolators.size() - 1; log<LOG_VERBOSE>("Pkz update done"); } } void Model_Santos2006::update_T21(map<string,double> params, int *Tb_index) { bool do_calc = true; for (unsigned int i = 0; i < Tb_interpolators.size(); ++i) { if (params["ombh2"] == Tb_interpolators[i].ombh2 &&\ params["omnuh2"] == Tb_interpolators[i].omnuh2 &&\ params["omch2"] == Tb_interpolators[i].omch2 &&\ params["hubble"] == Tb_interpolators[i].hubble &&\ params["T_CMB"] == Tb_interpolators[i].t_cmb &&\ params["omk"] == Tb_interpolators[i].omk &&\ params["alpha"] == Tb_interpolators[i].alpha &&\ params["beta"] == Tb_interpolators[i].beta &&\ params["gamma"] == Tb_interpolators[i].gamma &&\ params["RLy"] == Tb_interpolators[i].RLy &&\ params["omega_lambda"] == Tb_interpolators[i].omega_lambda) { log<LOG_VERBOSE>("found precalculated Analytic 21cm Signal"); do_calc = false; *Tb_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating T21 from scratch"); ofstream file; Tb_interpolator_Santos interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.omk = params["omk"]; interp.t_cmb = params["T_CMB"]; interp.alpha = params["alpha"]; interp.beta = params["beta"]; interp.gamma = params["gamma"]; interp.RLy = params["RLy"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; file.open("output/t21_analytic.dat"); vector<double> vz, vTb, vfz; double zmin; if (params["zmin"] - 2 < 0) zmin = 0; else zmin = params["zmin"] - 2; double zmax = params["zmax"] + 2; double stepsize = 0.05; log<LOG_DEBUG>("Tc is being interpolated between zmin = %1% and zmax = %2%") % zmin % zmax; int steps = abs(zmax - zmin)/stepsize; for (int i = 0; i < steps; i++) { double z = zmin + i*stepsize; vz.push_back(z); double dTb = t21(z, params); vTb.push_back(dTb); double f = fz(z, params); vfz.push_back(f); } real_1d_array t21_z, t21_Tb, t21_fz; t21_z.setlength(vz.size()); t21_Tb.setlength(vTb.size()); t21_fz.setlength(vfz.size()); for (unsigned int i = 0; i < vz.size(); i++){ t21_z[i] = vz[i]; t21_Tb[i] = vTb[i]; t21_fz[i] = vfz[i]; file << vz[i] << " " << vTb[i] << endl; } file.close(); spline1dinterpolant interpolator; try { spline1dbuildcubic(t21_z, t21_Tb, interpolator); } catch(alglib::ap_error e){ log<LOG_ERROR>("---- Error in Tb: %1%.") % e.msg.c_str(); } interp.interpolator = interpolator; spline1dinterpolant fz_interpolator; try { spline1dbuildcubic(t21_z, t21_fz, fz_interpolator); } catch(alglib::ap_error e){ log<LOG_ERROR>("---- Error in fz: %1%") % e.msg.c_str(); } interp.fz_interpolator = fz_interpolator; Tb_interpolators.push_back(interp); *Tb_index = Tb_interpolators.size() - 1; log<LOG_VERBOSE>("T21 update done"); } } void Model_Santos2006::update_q(map<string,double> params, int *q_index) { bool limber = false; if (params["limber"] == 1.0) limber = true; // We first update q and then q' if the limber approximation is being used.. bool do_calc = true; for (unsigned int i = 0; i < q_interpolators.size(); ++i) { if (params["ombh2"] == q_interpolators[i].ombh2 &&\ params["omnuh2"] == q_interpolators[i].omnuh2 &&\ params["omch2"] == q_interpolators[i].omch2 &&\ params["omk"] == q_interpolators[i].omk &&\ params["hubble"] == q_interpolators[i].hubble &&\ params["T_CMB"] == q_interpolators[i].t_cmb &&\ params["w_DE"] == q_interpolators[i].w_DE &&\ params["omega_lambda"] == q_interpolators[i].omega_lambda ){ log<LOG_VERBOSE>("Found precalculated q"); do_calc = false; *q_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating q from scratch"); q_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.t_cmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; interp.omk = params["omk"]; interp.omega_lambda = 0; } else { use_non_physical = true; interp.omk = 0; interp.omega_lambda = params["omega_lambda"]; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double D_H2 = c / (1000.0 * H_02); double w2 = params["w_DE"]; real_1d_array xs, ys, qps, hs; xs.setlength(this->zsteps_Ml+1); ys.setlength(this->zsteps_Ml+1); qps.setlength(this->zsteps_Ml+1); hs.setlength(this->zsteps_Ml+1); double h = 10e-4; double z; for (int n = 0; n <= this->zsteps_Ml; ++n) { z = this->zmin_Ml + n * this->stepsize_Ml; xs[n] = z; auto integrand = [&](double zp) { return 1/sqrt(O_Lambda * pow(1+zp,3*(1+w2)) + O_R2 * pow(1+zp,4) +\ O_M2 * pow(1+zp,3) + O_k2 * pow(1+zp,2)); }; double Z = integrate(integrand, 0.0, z, 1000, simpson()); if (limber) { double dc1 = integrate(integrand, 0.0, z+2*h, 1000, simpson()); double dc2 = integrate(integrand, 0.0, z+h, 1000, simpson()); double dc3 = integrate(integrand, 0.0, z-h, 1000, simpson()); double dc4 = integrate(integrand, 0.0, z-2*h, 1000, simpson()); qps[n] = abs(D_H2 * (-dc1 + 8 * dc2 - 8 * dc3 + dc4)); } else qps[n] = (double)n; ys[n] = D_H2 * Z; hs[n] = H_02 * sqrt(O_Lambda * pow(1+z,3*(1+w2)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2)); } spline1dinterpolant interpolator, interpolator_Hf, interpolator_qp; spline1dbuildlinear(xs,ys,interpolator); spline1dbuildlinear(xs,hs,interpolator_Hf); spline1dbuildlinear(xs,qps,interpolator_qp); // If limber == false, the qp_interpolator will just be empty but that // is fine because it won't be used in that case. interp.h = h2; interp.interpolator = interpolator; interp.interpolator_Hf = interpolator_Hf; interp.interpolator_qp = interpolator_qp; q_interpolators.push_back(interp); *q_index = q_interpolators.size() - 1; log<LOG_VERBOSE>("q update done"); } } void Model_Santos2006::set_Santos_params(double *alpha, double *beta,\ double *gamma, double *RLy, int Tb_index) { *alpha = Tb_interpolators[Tb_index].alpha; *beta = Tb_interpolators[Tb_index].beta; *gamma = Tb_interpolators[Tb_index].gamma; *RLy = Tb_interpolators[Tb_index].RLy; } ////// //double Model_Santos2006:: // This uses the frequency in MHz! double Model_Santos2006::z_from_nu(double nu) { return (1420.0/nu - 1.0); } double Model_Santos2006::t21(double z, map<string,double> params) { //double z = z_from_nu(nu); double tc = Tc(z, params); return tc; } double Model_Santos2006::fz(double z, map<string,double> params) { // This is taken from Ned Wright's cosmology tutorial section 3.5 Growth of linear perturbations // Lahav et al 1991; // It is just f(z) = O_M(z)^(4/7) double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (params.find("omega_lambda") == params.end()){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double w_DE = params["w_DE"]; double Ez_sq = O_Lambda * pow(1+z, 3*(1+w_DE)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2); double num = O_M2 * pow(1+z,3); double frac = num/Ez_sq; double exponent = 4.0/7.0; double res = pow(frac,exponent); return res; } double Model_Santos2006::Tk(double z) { double A = 397.85/(145.0*145.0); return A * pow(1+z,2); } // This is in mK!! double Model_Santos2006::Tc(double z, map<string,double> params) { //Assuming fully neutral IGM. double xHI = 1.0; double ombh2 = params["ombh2"]; double omch2 = params["omch2"]; double h_local; if (params.find("omega_lambda") == params.end()){ h_local = params["hubble"]/100.0; } else { h_local = sqrt((params["ombh2"] + params["omch2"] + params["omnuh2"])/\ (1.0-params["omega_lambda"]-params["omk"])); } return 23 * xHI * (0.7/h_local) * (ombh2/0.02) * sqrt((0.15/omch2)*((1.0+z)/10.0)); } void Model_Santos2006::writeTc(string name) { ofstream file(name); for (int i = 0; i < 1000; i++) { file << 0.1+i * 0.1 << " " << Tc(0.1+i*0.1, this->give_fiducial_params()) << endl; } } void Model_Santos2006::update_gamma(map<string,double> params) { } double Model_Santos2006::gamma(double z, map<string,double> params) { return 0; } double Model_Santos2006::y_tot(double z, map<string,double> params) { return 0; } ///////////////////////////////////////////////////////////////////////////////// /* Code for Santos ARES */ ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // Note that this is the model Santos et al. 2006 use as their Fiducial model // // and so it is only valid in a redshift range of z in [15, 25]. // ///////////////////////////////////////////////////////////////////////////////// // This means that the only difference between this and CAMB_ARES is that the // // Cosmological Parameters that are used by default are different. CAMB_ARES // // uses the parameters specified in the params.ini file, whereas this model // // uses the parameters stated in the Santos paper. // ///////////////////////////////////////////////////////////////////////////////// // Therefore, only use this model when trying to recover the results of that // // paper. // ///////////////////////////////////////////////////////////////////////////////// Model_Santos_ARES::Model_Santos_ARES(map<string, double> params,\ int *Pk_index, int *Tb_index, int *q_index) : ModelParent(params) { //Changing fiducial values to the ones they have used. map<string, double> new_params = give_fiducial_params(); new_params["omch2"] = 0.1277; new_params["ombh2"] = 0.02229; new_params["hubble"] = 73.2; new_params["n_s"] = 0.958; new_params["A_s"] = 1.562e-9; new_params["tau_reio"] = 0.089 ; set_fiducial_params(new_params); zmin_Ml = fiducial_params["zmin"]; zmax_Ml = fiducial_params["zmax"]; zsteps_Ml = fiducial_params["zsteps"]; stepsize_Ml = abs(this->zmax_Ml - this->zmin_Ml)/(double)this->zsteps_Ml; CAMB = new CAMB_CALLER; modelID = "SantosARES"; log<LOG_BASIC>("... precalculating q ..."); update_q(fiducial_params, q_index); log<LOG_BASIC>("... q done ..."); log<LOG_BASIC>("... precalculating Pkz ..."); update_Pkz(fiducial_params, Pk_index); log<LOG_BASIC>("... Pkz done ..."); log<LOG_BASIC>("... precalculating 21cm interface ..."); log<LOG_BASIC>("... -> ARES Model for 21cm signal ..."); ARES = new AresInterface(); update_T21(fiducial_params, Tb_index); log<LOG_BASIC>("... 21cm interface built ..."); log<LOG_BASIC>("... Model_Santos_ARES built ..."); } Model_Santos_ARES::~Model_Santos_ARES() { delete CAMB; delete ARES; } void Model_Santos_ARES::update_Pkz(map<string,double> params, int *Pk_index) { bool do_calc = true; for (unsigned int i = 0; i < Pkz_interpolators.size(); ++i) { if (params["ombh2"] == Pkz_interpolators[i].ombh2 &&\ params["omnuh2"] == Pkz_interpolators[i].omnuh2 &&\ params["omch2"] == Pkz_interpolators[i].omch2 &&\ params["omk"] == Pkz_interpolators[i].omk &&\ params["hubble"] == Pkz_interpolators[i].hubble &&\ params["T_CMB"] == Pkz_interpolators[i].tcmb &&\ params["w_DE"] == Pkz_interpolators[i].w_DE &&\ params["n_s"] == Pkz_interpolators[i].n_s &&\ params["A_s"] == Pkz_interpolators[i].A_s &&\ params["tau_reio"] == Pkz_interpolators[i].tau &&\ params["omega_lambda"] == Pkz_interpolators[i].omega_lambda){ log<LOG_VERBOSE>("Found precalculated Pkz"); do_calc = false; *Pk_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating Pkz from scratch"); Pk_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.tcmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; interp.n_s = params["n_s"]; interp.A_s = params["A_s"]; interp.tau = params["tau_reio"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; CAMB->call(params); vector<double> vk = CAMB->get_k_values(); vector<vector<double>> Pz = CAMB->get_Pz_values(); double z_stepsize = (params["zmax"] - params["zmin"])/(params["Pk_steps"] - 1); vector<double> vz, vP; for (unsigned int i = 0; i < Pz.size(); ++i) { vz.push_back(params["zmin"] + i * z_stepsize); vP.insert(vP.end(), Pz[i].begin(), Pz[i].end()); } real_1d_array matterpowerspectrum_k, matterpowerspectrum_z, matterpowerspectrum_P; matterpowerspectrum_k.setlength(vk.size()); matterpowerspectrum_z.setlength(vz.size()); matterpowerspectrum_P.setlength(vP.size()); for (unsigned int i = 0; i < vk.size(); i++){ matterpowerspectrum_k[i] = vk[i]; } for (unsigned int i = 0; i < vP.size(); i++){ matterpowerspectrum_P[i] = vP[i]; } for (unsigned int i = 0; i < vz.size(); i++){ matterpowerspectrum_z[i] = vz[i]; } spline2dinterpolant interpolator; spline2dbuildbicubicv(matterpowerspectrum_k, vk.size(),matterpowerspectrum_z, vz.size(),\ matterpowerspectrum_P, 1, interpolator); interp.interpolator = interpolator; Pkz_interpolators.push_back(interp); *Pk_index = Pkz_interpolators.size() - 1; log<LOG_VERBOSE>("Pkz update done"); } } void Model_Santos_ARES::update_T21(map<string,double> params, int *Tb_index) { bool do_calc = true; for (unsigned int i = 0; i < Tb_interpolators.size(); ++i) { if (params["ombh2"] == Tb_interpolators[i].ombh2 &&\ params["omnuh2"] == Tb_interpolators[i].omnuh2 &&\ params["omch2"] == Tb_interpolators[i].omch2 &&\ params["omk"] == Tb_interpolators[i].omk &&\ params["hubble"] == Tb_interpolators[i].hubble &&\ params["sigma8"] == Tb_interpolators[i].s8 &&\ params["T_CMB"] == Tb_interpolators[i].T_CMB &&\ params["n_s"] == Tb_interpolators[i].n_s &&\ params["fstar"] == Tb_interpolators[i].fstar &&\ params["fesc"] == Tb_interpolators[i].fesc &&\ params["nion"] == Tb_interpolators[i].nion &&\ params["fx"] == Tb_interpolators[i].fX &&\ params["omega_lambda"] == Tb_interpolators[i].omega_lambda) { /* **** These parameters aren't part of the fiducial parameter * set, or, as is the case for w_DE, aren't used by ARES. params["Tmin"] == Tb_interpolators[i].Tmin &&\ params["w_DE"] == Tb_interpolators[i].w_DE &&\ params["Nlw"] == Tb_interpolators[i].Nlw &&\ params["cX"] == Tb_interpolators[i].cX &&\ params["HeByMass"] == Tb_interpolators[i].HeByMass */ log<LOG_VERBOSE>("found precalculated Ares"); do_calc = false; *Tb_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating T21 from scratch"); Tb_interpolator_Santos_ARES interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.s8 = params["sigma8"]; interp.T_CMB = params["T_CMB"]; interp.n_s = params["n_s"]; interp.fstar = params["fstar"]; interp.fesc = params["fesc"]; interp.nion = params["nion"]; interp.fX = params["fx"]; interp.alpha = params["alpha"]; interp.beta = params["beta"]; interp.gamma = params["gamma"]; interp.RLy = params["RLy"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; interp.w_DE = -1; //params["w_DE"]; interp.Tmin = -1; //params["Tmin"]; interp.Nlw = -1; //params["Nlw"]; interp.cX = -1; //params["cX"]; interp.HeByMass = -1; //params["HeByMass"]; log<LOG_VERBOSE>("Ares is being updated"); ARES->updateAres(params); vector<double> vz, vTb, vfz; ARES->getTb(&vz, &vTb); for (int i = 0; i<vz.size(); i++) { double z = vz[i]; double f = fz(z, params); vfz.push_back(f); } real_1d_array Ares_z, Ares_Tb, Ares_fz; Ares_z.setlength(vz.size()); Ares_Tb.setlength(vTb.size()); Ares_fz.setlength(vfz.size()); for (unsigned int i = 0; i < vz.size(); i++){ Ares_z[i] = vz[i]; Ares_fz[i] = vfz[i]; } for (unsigned int i = 0; i < vTb.size(); i++){ Ares_Tb[i] = vTb[i]; } spline1dinterpolant interpolator; spline1dbuildcubic(Ares_z, Ares_Tb, interpolator); interp.interpolator = interpolator; spline1dinterpolant fz_interpolator; try { spline1dbuildcubic(Ares_z, Ares_fz, fz_interpolator); } catch(alglib::ap_error e){ log<LOG_ERROR>("---- Error in fz: %1%") % e.msg.c_str(); } interp.fz_interpolator = fz_interpolator; Tb_interpolators.push_back(interp); *Tb_index = Tb_interpolators.size() - 1; log<LOG_VERBOSE>("Ares dTb update done"); } } void Model_Santos_ARES::update_q(map<string,double> params, int *q_index) { bool limber = false; if (params["limber"] == 1.0) limber = true; // We first update q and then q' if the limber approximation is being used.. bool do_calc = true; for (unsigned int i = 0; i < q_interpolators.size(); ++i) { if (params["ombh2"] == q_interpolators[i].ombh2 &&\ params["omnuh2"] == q_interpolators[i].omnuh2 &&\ params["omch2"] == q_interpolators[i].omch2 &&\ params["omk"] == q_interpolators[i].omk &&\ params["hubble"] == q_interpolators[i].hubble &&\ params["T_CMB"] == q_interpolators[i].t_cmb &&\ params["w_DE"] == q_interpolators[i].w_DE &&\ params["omega_lambda"] == q_interpolators[i].omega_lambda ){ log<LOG_VERBOSE>("Found precalculated q"); do_calc = false; *q_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating q from scratch"); q_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.t_cmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; interp.omk = params["omk"]; interp.omega_lambda = 0; } else { use_non_physical = true; interp.omk = 0; interp.omega_lambda = params["omega_lambda"]; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double D_H2 = c / (1000.0 * H_02); double w2 = params["w_DE"]; real_1d_array xs, ys, qps, hs; xs.setlength(this->zsteps_Ml+1); ys.setlength(this->zsteps_Ml+1); qps.setlength(this->zsteps_Ml+1); hs.setlength(this->zsteps_Ml+1); double h = 10e-4; double z; for (int n = 0; n <= this->zsteps_Ml; ++n) { z = this->zmin_Ml + n * this->stepsize_Ml; xs[n] = z; auto integrand = [&](double zp) { return 1/sqrt(O_Lambda * pow(1+zp,3*(1+w2)) + O_R2 * pow(1+zp,4) +\ O_M2 * pow(1+zp,3) + O_k2 * pow(1+zp,2)); }; double Z = integrate(integrand, 0.0, z, 1000, simpson()); if (limber) { double dc1 = integrate(integrand, 0.0, z+2*h, 1000, simpson()); double dc2 = integrate(integrand, 0.0, z+h, 1000, simpson()); double dc3 = integrate(integrand, 0.0, z-h, 1000, simpson()); double dc4 = integrate(integrand, 0.0, z-2*h, 1000, simpson()); qps[n] = abs(D_H2 * (-dc1 + 8 * dc2 - 8 * dc3 + dc4)); } else qps[n] = (double)n; ys[n] = D_H2 * Z; hs[n] = H_02 * sqrt(O_Lambda * pow(1+z,3*(1+w2)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2)); } spline1dinterpolant interpolator, interpolator_Hf, interpolator_qp; spline1dbuildlinear(xs,ys,interpolator); spline1dbuildlinear(xs,hs,interpolator_Hf); spline1dbuildlinear(xs,qps,interpolator_qp); // If limber == false, the qp_interpolator will just be empty but that // is fine because it won't be used in that case. interp.h = h2; interp.interpolator = interpolator; interp.interpolator_Hf = interpolator_Hf; interp.interpolator_qp = interpolator_qp; q_interpolators.push_back(interp); *q_index = q_interpolators.size() - 1; log<LOG_VERBOSE>("q update done"); } } void Model_Santos_ARES::set_Santos_params(double *alpha, double *beta,\ double *gamma, double *RLy, int Tb_index) { *alpha = Tb_interpolators[Tb_index].alpha; *beta = Tb_interpolators[Tb_index].beta; *gamma = Tb_interpolators[Tb_index].gamma; *RLy = Tb_interpolators[Tb_index].RLy; } ////// //double Model_Santos2006:: // This uses the frequency in MHz! double Model_Santos_ARES::z_from_nu(double nu) { return (1420.0/nu - 1.0); } double Model_Santos_ARES::t21(double z, map<string,double> params) { //double z = z_from_nu(nu); double tc = Tc(z, params); return tc; } double Model_Santos_ARES::fz(double z, map<string,double> params) { // This is taken from Ned Wright's cosmology tutorial section 3.5 Growth of linear perturbations // Lahav et al 1991; // It is just f(z) = O_M(z)^(4/7) double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (params.find("omega_lambda") == params.end()){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double w_DE = params["w_DE"]; double Ez_sq = O_Lambda * pow(1+z, 3*(1+w_DE)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2); double num = O_M2 * pow(1+z,3); double frac = num/Ez_sq; double exponent = 4.0/7.0; double res = pow(frac,exponent); return res; } double Model_Santos_ARES::Tk(double z) { double A = 397.85/(145.0*145.0); return A * pow(1+z,2); } // This is in mK!! double Model_Santos_ARES::Tc(double z, map<string,double> params) { //Assuming fully neutral IGM. double xHI = 1.0; double ombh2 = params["ombh2"]; double omch2 = params["omch2"]; double h_local; if (params.find("omega_lambda") == params.end()){ h_local = params["hubble"]/100.0; } else { h_local = sqrt((params["ombh2"] + params["omch2"] + params["omnuh2"])/\ (1.0-params["omega_lambda"]-params["omk"])); } return 23 * xHI * (0.7/h_local) * (ombh2/0.02) * sqrt((0.15/omch2)*((1+z)/10.0)); } void Model_Santos_ARES::update_gamma(map<string,double> params) { } double Model_Santos_ARES::gamma(double z, map<string,double> params) { return 0; } double Model_Santos_ARES::y_tot(double z, map<string,double> params) { return 0; } ///////////////////////////////////////////////////////////////////////////////// /* Code for Intensity Mapping */ ///////////////////////////////////////////////////////////////////////////////// Model_Intensity_Mapping::Model_Intensity_Mapping(map<string, double> params,\ int *Pk_index, int *Tb_index, int *q_index) : ModelParent(params) { log<LOG_BASIC>(">>> Beginning to build Model_Intensity_Mapping <<<"); //Changing fiducial values to the ones they have used. map<string, double> new_params = give_fiducial_params(); set_fiducial_params(new_params); zmin_Ml = fiducial_params["zmin"]; zmax_Ml = fiducial_params["zmax"]; zsteps_Ml = fiducial_params["zsteps"]; stepsize_Ml = abs(this->zmax_Ml - this->zmin_Ml)/(double)this->zsteps_Ml; CAMB = new CAMB_CALLER; modelID = "IM"; log<LOG_BASIC>("... precalculating q ..."); update_q(fiducial_params, q_index); log<LOG_BASIC>("... q done ..."); log<LOG_BASIC>("... precalculating Pkz ..."); update_Pkz(fiducial_params, Pk_index); log<LOG_BASIC>("... Pkz done ..."); log<LOG_BASIC>("... precalculating 21cm interface ..."); log<LOG_BASIC>("... -> IM Model for 21cm signal ..."); update_T21(fiducial_params, Tb_index); /*update_hmf(fiducial_params); double z = 0; auto integrand = [&](double M) { return interp_dndm(M,z) * pow(M,0.6); }; double M_low = 1E9; double M_high = 1E12; double stepsize = M_low/10; int steps = (M_high-M_low)/stepsize; double integral = integrate(integrand, M_low, M_high, steps, simpson()); // units of M_SUN/MPc^3 double rho_0 = 1.5*1E-7; double Om_HI = 4.86*1E-4; double hh = fiducial_params["hubble"]/100.0; M_normalization = rho_0 * Om_HI / (hh*hh*hh*hh*integral); */ log<LOG_BASIC>("... 21cm interface built ..."); log<LOG_BASIC>("^^^ Model_Intensity_Mapping built ^^^"); } Model_Intensity_Mapping::~Model_Intensity_Mapping() { delete CAMB; } void Model_Intensity_Mapping::update_Pkz(map<string,double> params, int *Pk_index) { bool do_calc = true; for (unsigned int i = 0; i < Pkz_interpolators.size(); ++i) { if (params["ombh2"] == Pkz_interpolators[i].ombh2 &&\ params["omnuh2"] == Pkz_interpolators[i].omnuh2 &&\ params["omch2"] == Pkz_interpolators[i].omch2 &&\ params["omk"] == Pkz_interpolators[i].omk &&\ params["hubble"] == Pkz_interpolators[i].hubble &&\ params["T_CMB"] == Pkz_interpolators[i].tcmb &&\ params["w_DE"] == Pkz_interpolators[i].w_DE &&\ params["n_s"] == Pkz_interpolators[i].n_s &&\ params["A_s"] == Pkz_interpolators[i].A_s &&\ params["tau_reio"] == Pkz_interpolators[i].tau &&\ params["omega_lambda"] == Pkz_interpolators[i].omega_lambda){ log<LOG_VERBOSE>("Found precalculated Pkz"); do_calc = false; *Pk_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating Pkz from scratch"); Pk_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.omk = params["omk"]; interp.hubble = params["hubble"]; interp.tcmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; interp.n_s = params["n_s"]; interp.A_s = params["A_s"]; interp.tau = params["tau_reio"]; if (params.find("omega_lambda") == params.end()) interp.omega_lambda = 0; else interp.omega_lambda = params["omega_lambda"]; /*typedef map<string, double>::const_iterator Iter; for (Iter i = params.begin(); i != params.end();i++) { cout << "key: " << i->first << endl; cout << "value: " << i->second << endl; }*/ CAMB->call(params); vector<double> vk = CAMB->get_k_values(); vector<vector<double>> Pz = CAMB->get_Pz_values(); double z_stepsize = (params["zmax"] - params["zmin"])/(params["Pk_steps"] - 1); vector<double> vz, vP; for (unsigned int i = 0; i < Pz.size(); ++i) { vz.push_back(params["zmin"] + i * z_stepsize); vP.insert(vP.end(), Pz[i].begin(), Pz[i].end()); } real_1d_array matterpowerspectrum_k, matterpowerspectrum_z, matterpowerspectrum_P; matterpowerspectrum_k.setlength(vk.size()); matterpowerspectrum_z.setlength(vz.size()); matterpowerspectrum_P.setlength(vP.size()); for (unsigned int i = 0; i < vk.size(); i++){ matterpowerspectrum_k[i] = vk[i]; } for (unsigned int i = 0; i < vP.size(); i++){ matterpowerspectrum_P[i] = vP[i]; } for (unsigned int i = 0; i < vz.size(); i++){ matterpowerspectrum_z[i] = vz[i]; } spline2dinterpolant interpolator; spline2dbuildbicubicv(matterpowerspectrum_k, vk.size(),matterpowerspectrum_z, vz.size(),\ matterpowerspectrum_P, 1, interpolator); interp.interpolator = interpolator; Pkz_interpolators.push_back(interp); *Pk_index = Pkz_interpolators.size() - 1; log<LOG_VERBOSE>("Pkz update done"); } } void Model_Intensity_Mapping::update_T21(map<string,double> params, int *Tb_index) { bool do_calc = true; for (unsigned int i = 0; i < Tb_interpolators.size(); ++i) { if (params["ombh2"] == Tb_interpolators[i].ombh2 &&\ params["omnuh2"] == Tb_interpolators[i].omnuh2 &&\ params["omch2"] == Tb_interpolators[i].omch2 &&\ params["omk"] == Tb_interpolators[i].omk &&\ params["hubble"] == Tb_interpolators[i].hubble &&\ params["T_CMB"] == Tb_interpolators[i].T_CMB &&\ params["w_DE"] == Tb_interpolators[i].w_DE &&\ params["n_s"] == Tb_interpolators[i].n_s &&\ params["A_s"] == Tb_interpolators[i].A_s &&\ params["omega_lambda"] == Tb_interpolators[i].omega_lambda ){ log<LOG_VERBOSE>("Found precalculated T21"); do_calc = false; *Tb_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating T21 from scratch"); Tb_interpolator_IM interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.T_CMB = params["T_CMB"]; interp.w_DE = params["w_DE"]; interp.n_s = params["n_s"]; interp.A_s = params["A_s"]; if (params.find("omega_lambda") == params.end()) { interp.omk = params["omk"]; interp.omega_lambda = 0; } else { interp.omk = 0; interp.omega_lambda = params["omega_lambda"]; } double zmin_IM = params["IM_zlow"]; double zmax_IM = params["IM_zhigh"]; double zbin_size = params["zbin_size"]; int zsteps_IM = (zmax_IM - zmin_IM)/zbin_size; real_1d_array xs, dTb; xs.setlength(zsteps_IM+1); dTb.setlength(zsteps_IM+1); double z; CAMB->call(params); double omLambda = params["omega_lambda"]; double hub = params["hubble"]/100.0; double omM = params["omch2"]/(hub*hub); double omb = params["ombh2"] / (hub*hub); double n_s = params["n_s"]; double s8 = CAMB->get_sigma8(); //cout << " ------------------ " << s8 << endl; double omnu = params["omnuh2"] / (hub*hub); Cosmology cosmo(omM,omLambda,omb,hub,s8,n_s,omnu); // computing the normalization integral here, as it is only needed once. auto integrand = [&](double X) { double M_HI = exp(0.6*X); double dndm = cosmo.dndlMSheth(0.8,exp(X)); //double b = cosmo.biasPS(0.8,exp(X)); double b = biasmST(exp(X),0.8, &cosmo); return M_HI * dndm * b; }; double M_min = 1e10 * pow(1+0.8,-1.5); double M_max = pow(200,3)/pow(30,3)*1e10 * pow(1+0.8, -1.5); double I = integrate(integrand, log(M_min), log(M_max), 50, simpson()); ///////// for (int n = 0; n <= zsteps_IM; n++) { z = zmin_IM + n * zbin_size; xs[n] = z; dTb[n] = Tb(params, z, &cosmo, I); } spline1dinterpolant interpolator; spline1dbuildlinear(xs,dTb,interpolator); // If limber == false, the qp_interpolator will just be empty but that // is fine because it won't be used in that case. interp.interpolator = interpolator; Tb_interpolators.push_back(interp); *Tb_index = Tb_interpolators.size() - 1; if (*Tb_index == 0) { ofstream file("OmegaHI.dat"); for (int i = 0; i < 50; i++) { double z = i* 0.1; double OmHI = Omega_HI(z, &cosmo, I); file << z << " " << OmHI << endl; } } log<LOG_VERBOSE>("T21 update done"); } } void Model_Intensity_Mapping::update_q(map<string,double> params, int *q_index) { bool limber = false; if (params["limber"] == 1.0) limber = true; // We first update q and then q' if the limber approximation is being used.. bool do_calc = true; for (unsigned int i = 0; i < q_interpolators.size(); ++i) { if (params["ombh2"] == q_interpolators[i].ombh2 &&\ params["omnuh2"] == q_interpolators[i].omnuh2 &&\ params["omch2"] == q_interpolators[i].omch2 &&\ params["omk"] == q_interpolators[i].omk &&\ params["hubble"] == q_interpolators[i].hubble &&\ params["T_CMB"] == q_interpolators[i].t_cmb &&\ params["w_DE"] == q_interpolators[i].w_DE &&\ params["omega_lambda"] == q_interpolators[i].omega_lambda ){ log<LOG_VERBOSE>("Found precalculated q"); do_calc = false; *q_index = i; break; } } if (do_calc) { log<LOG_VERBOSE>("Calculating q from scratch"); q_interpolator interp; interp.ombh2 = params["ombh2"]; interp.omnuh2 = params["omnuh2"]; interp.omch2 = params["omch2"]; interp.hubble = params["hubble"]; interp.t_cmb = params["T_CMB"]; interp.w_DE = params["w_DE"]; bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; interp.omk = params["omk"]; interp.omega_lambda = 0; } else { use_non_physical = true; interp.omk = 0; interp.omega_lambda = params["omega_lambda"]; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double D_H2 = c / (1000.0 * H_02); double w2 = params["w_DE"]; real_1d_array xs, ys, qps, hs; xs.setlength(this->zsteps_Ml+1); ys.setlength(this->zsteps_Ml+1); qps.setlength(this->zsteps_Ml+1); hs.setlength(this->zsteps_Ml+1); double h = 10e-4; double z; for (int n = 0; n <= this->zsteps_Ml; ++n) { z = this->zmin_Ml + n * this->stepsize_Ml; xs[n] = z; auto integrand = [&](double zp) { return 1/sqrt(O_Lambda * pow(1+zp,3*(1+w2)) + O_R2 * pow(1+zp,4) +\ O_M2 * pow(1+zp,3) + O_k2 * pow(1+zp,2)); }; double Z = integrate(integrand, 0.0, z, 1000, simpson()); if (limber) { double dc1 = integrate(integrand, 0.0, z+2*h, 1000, simpson()); double dc2 = integrate(integrand, 0.0, z+h, 1000, simpson()); double dc3 = integrate(integrand, 0.0, z-h, 1000, simpson()); double dc4 = integrate(integrand, 0.0, z-2*h, 1000, simpson()); qps[n] = abs(D_H2 * (-dc1 + 8 * dc2 - 8 * dc3 + dc4)); } else qps[n] = (double)n; ys[n] = D_H2 * Z; hs[n] = H_02 * sqrt(O_Lambda * pow(1+z,3*(1+w2)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2)); } spline1dinterpolant interpolator, interpolator_Hf, interpolator_qp; spline1dbuildlinear(xs,ys,interpolator); spline1dbuildlinear(xs,hs,interpolator_Hf); spline1dbuildlinear(xs,qps,interpolator_qp); // If limber == false, the qp_interpolator will just be empty but that // is fine because it won't be used in that case. interp.h = h2; interp.interpolator = interpolator; interp.interpolator_Hf = interpolator_Hf; interp.interpolator_qp = interpolator_qp; q_interpolators.push_back(interp); *q_index = q_interpolators.size() - 1; log<LOG_VERBOSE>("q update done"); } } //in micro_K double Model_Intensity_Mapping::Tb(map<string,double> params, double z, Cosmology* cosmo, double Norm) { bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; } else { use_non_physical = true; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } double w2 = params["w_DE"]; double Hz = H_02 * sqrt(O_Lambda * pow(1+z,3*(1+w2)) + O_R2 * pow(1+z,4) +\ O_M2 * pow(1+z,3) + O_k2 * pow(1+z,2)); // //TODO: need to make Omega_Hi dependent on the cosmo_params. Currently it is not // //this->update_hmf(params); // //TODO // Update some container that that holds the halo mass function // at this redshift which is needed to compute Omega double OmHI = Omega_HI(z, cosmo, Norm); double h = h2;// this->give_fiducial_params("hubble")/100.0; double H0 = H_02;//Hf_interp(0); double H = Hz;//Hf_interp(z); //formula is for micro Kelvin, so we multiply by 0.001 to get mK. return 0.001 * 566.0 * h * (H0/H) * (OmHI/0.003) * (1.0+z) * (1.0+z); } double Model_Intensity_Mapping::M_HI(double M, double z) { return M_normalization * pow(M,0.6); // values from table 1 in Padmanabhan 2016 /*double alpha; if (z<1) alpha = 0.15; else if (z<1.5) alpha = 0.15; else if (z<2) alpha = 0.3; else if (z<2.3) alpha = 0.3; else if (z<3) alpha = 0.3; else if (z<4) alpha = 0.3; else alpha = 0.48; // p497 of Loeb&Furlanetto has Yp = 0.24 double Yp = 0.24; double h = this->current_params["hubble"] / 100.0; double O_b = this->current_params["ombh2"] / pow(h,2); double O_cdm2 = this->current_params["omch2"] / pow(h,2); double O_nu2 = this->current_params["omnuh2"] / pow(h,2); double O_M = O_b + O_cdm2 + O_nu2; double F_Hc = (1-Yp) * O_b / O_M; double v_M = 30.0 * sqrt(1+z) * pow(M/1E10, 1.0/3.0); double v0 = 30; double v1 = 200; return alpha * F_Hc * M * exp(-pow(v0/v_M,3) - pow(v_M/v1,3)); */ } double Model_Intensity_Mapping::Omega_HI(double z, Cosmology* cosmo, double Norm) { //TODO: I am right now just fitting a function to their figure, // the code below uses hmf, but that is dependent on which fitting // model the code hmf_for_LISW.py uses. // // This function reproduces figure 20 from bull et al 2015 exactly bool approx = false; if (approx) return (-0.000062667) * (z-3) * (z-3) + 0.00105; else { double OmTimesb = 0.62 * 1e-3; auto integrand = [&](double X) { double M_HI = exp(0.6*X); double dndm = nmST(exp(X),z,cosmo); return M_HI * dndm; }; double M_min = 1e10 * pow(1+z,-1.5); double M_max = pow(200,3)/pow(30,3)*1e10 * pow(1+z, -1.5); double II = integrate(integrand, log(M_min), log(M_max), 50, simpson()); double res = OmTimesb*II/Norm; return res; } //TODO: need to make Omega_Hi dependent on the cosmo_params. Currently it is not /* auto integrand = [&](double M) { return interp_dndm(M,z) * M_HI(M,z); }; // M_low and M_max are the M_range given through hmf_for_LISW.py // we take 99% towards the edges so there is no interpolation issue // Since the HMF is very steep it should be sufficient to just go up // one order of magnitude in the integration. Most of the signal comes // from the low M regime. double M_low = 1E9; double M_high = 1E12; double stepsize = M_low/10; int steps = (M_high-M_low)/stepsize; double rho_z = integrate(integrand, M_low, M_high, steps, simpson()); // units of M_SUN/MPc^3 double rho_0 = 1.5*1E-7; // need to multiply by h^4 to get the units right double h = this->current_params["hubble"]/100.0; double h4 = h*h*h*h; return rho_z*h4/(rho_0); */ } void Model_Intensity_Mapping::update_hmf(map<string,double> params) { //call a python function that calculates the hmf at the necessary z. bool use_non_physical; if (params.find("omega_lambda") == params.end()) { use_non_physical = false; } else { use_non_physical = true; } // TODO: Do this in a way that works with parallelism.... // UPDATE D_C to use the above parameters. double T_CMB2, H_02, h2, O_b2, O_cdm2, O_nu2, O_nu_rel2; double O_gamma2, O_R2, O_k2, O_M2, O_Lambda, O_tot2; T_CMB2 = params["T_CMB"]; H_02 = params["hubble"]; h2 = H_02 / 100.0; O_b2 = params["ombh2"] / pow(h2,2); O_cdm2 = params["omch2"] / pow(h2,2); O_nu2 = params["omnuh2"] / pow(h2,2); O_gamma2 = pow(pi,2) * pow(T_CMB2/11605.0,4) /\ (15.0*8.098*pow(10,-11)*pow(h2,2)); O_nu_rel2 = O_gamma2 * 3.0 * 7.0/8.0 * pow(4.0/11.0, 4.0/3.0); O_R2 = O_gamma2 + O_nu_rel2; O_M2 = O_b2 + O_cdm2 + O_nu2; if (!use_non_physical){ O_k2 = params["omk"]; O_tot2 = 1.0 - O_k2; O_Lambda = O_tot2 - O_M2 - O_R2; } else { O_Lambda = params["omega_lambda"]; O_k2 = 1 - O_Lambda - O_R2 - O_M2; } //contains M values vector<double> vM; vector<vector<double>> dndm_z; int z_steps = 10; double z_stepsize = abs(params["IM_zlow"] - params["IM_zhigh"])/((double)z_steps); vector<double> vz, vdndm; for (int i = 0; i < z_steps; i++) { // for each z run hmf and read in the file. double z = params["IM_zlow"] + i * z_stepsize; stringstream command; command << "python hmf_for_LISW.py --omega_m_0 " << O_M2 << " --omega_b_0 " << O_b2 <<\ " --omega_l_0 " << O_Lambda << " --hubble_0 " << H_02 << " --cmb_temp_0 " << T_CMB2 <<\ " --redshift " << z << " --Mmin " << 5 << " --Mmax " << 16; char* command_buff = new char[command.str().length() + 1]; strcpy(command_buff, command.str().c_str()); int r = system(command_buff); (void)r; //read the data into container. ifstream infile("hmf.dat", ios::in); vector<double> xs,ys; double a,b; while (infile >> a >> b) { if (i == 0) xs.push_back(a); ys.push_back(b); } if (i == 0) vM = xs; dndm_z.push_back(ys); } for (unsigned int i = 0; i < dndm_z.size(); ++i) { vz.push_back(params["IM_zlow"] + i * z_stepsize); vdndm.insert(vdndm.end(), dndm_z[i].begin(), dndm_z[i].end()); } real_1d_array dndm, zs, Ms; Ms.setlength(vM.size()); zs.setlength(vz.size()); dndm.setlength(vdndm.size()); for (unsigned int i = 0; i < vM.size(); i++){ Ms[i] = vM[i]; } for (unsigned int i = 0; i < vdndm.size(); i++){ dndm[i] = vdndm[i]; } for (unsigned int i = 0; i < vz.size(); i++){ zs[i] = vz[i]; } spline2dbuildbilinearv(Ms, vM.size(),zs, vz.size(), dndm, 1, interpolator_hmf); } double Model_Intensity_Mapping::interp_dndm(double M, double z) { return spline2dcalc(interpolator_hmf, M, z); } /** TESTCLASSES **/ TEST_Model_Intensity_Mapping::TEST_Model_Intensity_Mapping(map<string, double> params,\ int *Pk_index, int *Tb_index, int *q_index) : Model_Intensity_Mapping(params,Pk_index,Tb_index,q_index) {} TEST_Model_Intensity_Mapping::~TEST_Model_Intensity_Mapping() {} double TEST_Model_Intensity_Mapping::q_interp(double z, int q_index) { double om1 = q_interpolators[q_index].ombh2; double om2 = q_interpolators[q_index].omch2; return z + (om1*om1) - (1.0/om2); }
#include "GamePch.h" #include "Chase.h" #include "Common.h" #include "Component\Separation.h" #include "IKObject.h" #include "IKComponent.h" #include "GameUtils.h" extern bool g_bDebugAIBehaviors; static bool s_bDrawDebugAIChasingInfo = false; void Chase::LoadFromXML(tinyxml2::XMLElement* data) { const char* targetTag = data->Attribute("target_tag"); if (targetTag) m_TargetTag = WSID(targetTag); m_StopDistance = 4.0f; data->QueryFloatAttribute("stop_dist", &m_StopDistance); m_Speed = 1.0f; data->QueryFloatAttribute("speed", &m_Speed); m_RepathFreq = 1.0f; data->QueryFloatAttribute( "repath_freq", &m_RepathFreq ); const char* runAnim = data->Attribute( "run_anim" ); m_Run = WSID(runAnim); m_AnimSpeed = 1.0f; data->QueryFloatAttribute( "anim_speed", &m_AnimSpeed ); m_WaypointAgent = nullptr; m_Motor = nullptr; m_Separation = nullptr; } void Chase::Init(Hourglass::Entity* entity) { m_Target = Hourglass::Entity::FindByTag( m_TargetTag ); m_WaypointAgent = entity->GetComponent<hg::WaypointAgent>(); XMVECTOR targetPos = m_Target->GetTransform()->GetWorldPosition(); XMVECTOR worldPos = entity->GetTransform()->GetWorldPosition(); XMVECTOR targetDir; XMVECTOR vToTarget = targetDir = targetPos - worldPos; vToTarget = XMVectorSetY( vToTarget, 0.0f ); hg::Ray ray( Vector3( worldPos ) + Vector3::Up, targetDir, 20.0f ); Vector3 hit; hg::Entity* hitEntity; if (hg::g_Physics.RayCast( ray, &hitEntity, &hit, nullptr, ~COLLISION_ENEMY_MASK )) { m_Pursuit = (hitEntity == m_Target); } if (!m_Pursuit) { m_WaypointAgent->Continue(); m_WaypointAgent->SetDestination( targetPos ); } else { m_WaypointAgent->Cease(); } m_Timer = 4.0f; if (m_Motor == nullptr) { m_Motor = entity->GetComponent<hg::Motor>(); } if (m_Motor) { m_Motor->SetMoveEnabled( true ); m_Motor->SetEnabled( true ); } if (m_Separation == nullptr) { m_Separation = entity->GetComponent<hg::Separation>(); } hg::Animation* anim = entity->GetComponent<hg::Animation>(); if (anim) anim->Play( m_Run, m_AnimSpeed ); } Hourglass::IBehavior::Result Chase::Update(Hourglass::Entity* entity) { if (g_bDebugAIBehaviors) { hg::DevTextRenderer::DrawText_WorldSpace("Chase", entity->GetPosition()); Vector3 pos = entity->GetTransform()->GetWorldPosition(); Vector3 v1 = entity->GetTransform()->Right(); Vector3 v2 = entity->GetTransform()->Up(); Vector3 v3 = entity->GetTransform()->Forward(); hg::DebugRenderer::DrawLine(pos, pos + v1, Vector4(1, 0, 0, 1), Vector4(1, 0, 0, 1)); hg::DebugRenderer::DrawLine(pos, pos + v2, Vector4(0, 1, 0, 1), Vector4(0, 1, 0, 1)); hg::DebugRenderer::DrawLine(pos, pos + v3, Vector4(0, 0, 1, 1), Vector4(0, 0, 1, 1)); } if (!m_Target || !entity) return IBehavior::kFAILURE; XMVECTOR targetPos = m_Target->GetTransform()->GetWorldPosition(); XMVECTOR worldPos = entity->GetTransform()->GetWorldPosition(); XMVECTOR targetDir; XMVECTOR vToTarget = targetDir = targetPos - worldPos; vToTarget = XMVectorSetY(vToTarget, 0.0f); float lenSq; XMStoreFloat(&lenSq, XMVector3LengthSq(vToTarget)); if (lenSq <= m_StopDistance * m_StopDistance && GameUtils::AI_CanSeePlayer(entity, m_Target, Vector3(0, 1, 0))) { m_Motor->SetMoveEnabled( false ); return IBehavior::kSUCCESS; } float dt = hg::g_Time.Delta(); m_Timer += dt; if (m_Timer >= m_RepathFreq) { m_Timer = 0.0f; m_WaypointAgent->SetDestination( targetPos ); } Vector3 moveVec; // we will move one way or another // Only move when dynamic collider is available hg::DynamicCollider* col = entity->GetComponent<hg::DynamicCollider>(); if (!col) return IBehavior::kFAILURE; //if(m_Target->GetTag() == SID(; hg::Ray ray( Vector3(worldPos) + Vector3::Up, targetDir, 20.0f ); Vector3 hit; hg::Entity* hitEntity; bool hitPlayer = false; if (s_bDrawDebugAIChasingInfo) hg::DebugRenderer::DrawLine(worldPos, worldPos + XMVector3Normalize(vToTarget) * 20.0f, Vector4(1.0f, 0.0f, 0.0f, 1.0f), Vector4(1.0f, 0.0f, 0.0f, 1.0f)); if (hg::g_Physics.RayCast( ray, &hitEntity, &hit, nullptr, ~COLLISION_ENEMY_MASK )) { if (s_bDrawDebugAIChasingInfo) hg::DebugRenderer::DrawLine(entity->GetTransform()->GetWorldPosition(), hitEntity->GetTransform()->GetWorldPosition()); if (hitEntity == m_Target) { Vector3 plannarDir = ray.Direction; plannarDir.y = 0.0f; //plannarDir.Normalize(); XMStoreFloat3( &moveVec, plannarDir * m_Speed * dt ); hitPlayer = true; if (!m_Pursuit) { m_WaypointAgent->Cease(); } m_Pursuit = true; } else { if (m_Pursuit) { m_WaypointAgent->Continue(); } m_Pursuit = false; } } if (!hitPlayer) { Vector3 desiredDirection = m_WaypointAgent->GetDesiredDirection(); desiredDirection.y = 0.0f; //desiredDirection.Normalize(); XMStoreFloat3( &moveVec, desiredDirection * m_Speed * dt ); if (m_Motor) { moveVec.Normalize(); m_Motor->SetDesiredForward( desiredDirection ); if (m_Separation) m_Separation->SetDesiredMove(moveVec); else m_Motor->SetDesiredMove(moveVec); } } else if( m_Motor ) { moveVec.Normalize(); vToTarget = XMVector3Normalize( vToTarget ); m_Motor->SetDesiredForward( vToTarget ); if (m_Separation) m_Separation->SetDesiredMove(moveVec); else m_Motor->SetDesiredMove(moveVec); } return IBehavior::kRUNNING; } Hourglass::IBehavior* Chase::MakeCopy() const { Chase* copy = (Chase*)IBehavior::Create(SID(Chase)); copy->m_Speed = m_Speed; copy->m_StopDistance = m_StopDistance; copy->m_TargetTag = m_TargetTag; copy->m_RepathFreq = m_RepathFreq; copy->m_Timer = m_Timer; copy->m_Run = m_Run; copy->m_Motor = nullptr; copy->m_Separation = nullptr; copy->m_WaypointAgent = nullptr; copy->m_AnimSpeed = m_AnimSpeed; return copy; }
#include <Poco/Exception.h> #include "util/ArgsParser.h" using namespace std; using namespace Poco; using namespace BeeeOn; ArgsParser::ArgsParser( const string &whitespace, const char quote, const char escape): m_whitespace(whitespace), m_quote(quote), m_escape(escape) { if (whitespace.find(quote) != string::npos) throw InvalidArgumentException("quote must not be in whitespace list"); if (whitespace.find(escape) != string::npos) throw InvalidArgumentException("escape must not be in whitespace list"); if (escape == quote) throw InvalidArgumentException("escape must be different from quote"); } const vector<string> &ArgsParser::parse(const string &input) { return parse(input, m_args); } vector<string> &ArgsParser::parse(const string &input, vector<string> &args) { enum State { S_INIT, S_SYMBOL, S_QUOTE_OPEN, S_QUOTE_CLOSE, S_QUOTE_ESCAPE }; State state = S_INIT; string current; args.clear(); for (const char c : input) { switch (state) { case S_INIT: if (m_whitespace.find(c) != string::npos) break; if (c == m_quote) { state = S_QUOTE_OPEN; break; } current += c; state = S_SYMBOL; break; case S_SYMBOL: if (m_whitespace.find(c) != string::npos) { state = S_INIT; args.push_back(current); current.clear(); break; } current += c; break; case S_QUOTE_OPEN: if (c == m_quote) { state = S_QUOTE_CLOSE; args.push_back(current); current.clear(); break; } else if (c == m_escape) { state = S_QUOTE_ESCAPE; break; } current += c; break; case S_QUOTE_CLOSE: if (m_whitespace.find(c) != string::npos) { state = S_INIT; break; } throw SyntaxException( "expected a whitespace after closing quote"); case S_QUOTE_ESCAPE: // we can escape a quote symbol or escape an escape symbol if (c == m_quote || c == m_escape) { current += c; state = S_QUOTE_OPEN; break; } throw SyntaxException("unfinished escape character on: " + c); } } if (state == S_QUOTE_OPEN) throw SyntaxException("unfinished quotation"); if (state == S_QUOTE_ESCAPE) throw SyntaxException("unfinished escape inside quotation"); if (state == S_SYMBOL) args.push_back(current); return args; } size_t ArgsParser::count() const { return m_args.size(); } const string &ArgsParser::at(const size_t index) const { return m_args.at(index); }
#ifndef BASE_SCHEDULING_TASK_LOOP_FOR_IO_H_ #define BASE_SCHEDULING_TASK_LOOP_FOR_IO_H_ // This file is just for bringing in platform-specific implementations of // TaskLoopForIO, and merging them into a single type. Users of TaskLoopForIO // should include this file, and it will "give" them the right TaskLoopForIO // depending on the platform they're on. It is inspired by // https://source.chromium.org/chromium/chromium/src/+/master:base/message_loop/message_pump_for_io.h. // // It is tempting to try and create one abstract interface to unify all // platform-specific implementations of TaskLoopForIO, especially to ensure they // all adhere to the same API contract, however it occurred to me that they will // all not actually have the same APIs. For example, SocketReader currently // deals in terms of file descriptors, but on Windows we'll have to use HANDLEs // or something. In that case, the SocketReader API is not the same across // platforms, so users of TaskLoopForIO will have to also base their usage of // TaskLoopForIO off of the existence of platform-specific compiler directives. // Luckily there will only be a small set of direct users of these kinds of // platform-specific APIs. // // Note that it actually is possible to generalize the TaskLoopForIO API surface // even across platforms, if we create platform-specific implementations of a // "platform handle" concept, which itself has platform-specific code to // conditionally deal in terms of POSIX file descriptors, Windows HANDLEs, or // what have you, all while maintaining a platform agnostic API that // TaskLoopForIO can understand. This would be worth looking into once we expand // to Windows, if we ever do. #include "base/build_config.h" #if defined(OS_MACOS) #include "base/scheduling/task_loop_for_io_mac.h" // TODO(domfarolino): Implement an IO task loop for Linux, and maybe even it // will be general enough for both platforms. #endif namespace base { #if defined(OS_MACOS) using TaskLoopForIO = TaskLoopForIOMac; #elif defined(OS_LINUX) // using TaskLoopForIO = TaskLoopForIOLinux; #error This platform does not support TaskLoopForIO just yet #endif } // namespace base #endif // BASE_SCHEDULING_TASK_LOOP_FOR_IO_H_
/* * FieldAnalyse.h * * Created on: 12/feb/2012 * Author: jetmir */ #ifndef FIELDANALYSE_H_ #define FIELDANALYSE_H_ #include <iostream> #include <math.h> #include <mqueue.h> #include "cv.h" #include "highgui.h" #include "Utils.h" #include "ThreadAnalyse.h" #define BALL_F 5 using namespace std; using namespace cv; class FieldAnalyse { public: FieldAnalyse(); virtual ~FieldAnalyse(); void Launch(); protected: /* Boîte aux lettres de communication entre Com et Robot */ mqd_t bal_com_robot; /* Boîte aux lettres de communication entre Video et Robot */ mqd_t bal_video_robot; /* Boîte aux lettres de communication entre Robot et IA */ mqd_t bal_robot_ia; CvMat* mmat; Position balle_h[5]; bool buffer_full; int ball_frame; int white[6], blue[6], red[6]; ThreadAnalyse *kephD_t, *kephG_t, *balle_t; Field kephD, kephG, balle; CvCapture * capture; IplImage *img, *warped, *treat,*terrain; Robot r1,r2; Balle palla; void Allocate_imgs(); void compute_Warp(); void setup_colors(char *color, int *color_r); /* Identifiant du thread */ pthread_t thread; /* Boucle principal du thread */ void run(); /* Méthode obligatoire pour exécuter le thread */ static void* exec(void* analyse_thread); }; #endif /* FIELDANALYSE_H_ */
// Robert Fus // CSCI 6626 - Object-Orientated Principles & Practices // Program 3: Board // File: Board.cpp // 9/21/2019 #include "Board.hpp" //---------------------------------------------------------------- Board::Board(int n, ifstream& strm, int nType) : N(n), data(strm) { cout << "Board Constructing" << endl; cout << n << endl; if(!data.is_open()) { throw StreamFiles(strm); } getPuzzle(n, strm); } //---------------------------------------------------------------- Board::~Board() { delete[] brd; cout << "Destructed Board" << endl; } //---------------------------------------------------------------- void Board::getPuzzle(int n, ifstream& strm) { char ch; brd = new Square[n * n]; for (int j = 1; j <= n; j++) { for (int k = 1; k <= n; k++) { data >> ch; if ((ch >= '1' && ch <= '9') || ch == left) { Square Sq(ch, j, k); sub(j, k) = Sq; } if (k == 9) cout << "\n"; } if (j == 10 && !data.eof()) throw StreamFiles(strm); } makeClusters(); } //---------------------------------------------------------------- Square& Board::sub(int j, int k) { int sub = (j - 1) * N + (k - 1); return brd[sub]; } //---------------------------------------------------------------- char Board::getMarkChar(int j, int k) const{ int sub =(j- 1) * N + (k - 1); return brd[sub].getValue(); } //---------------------------------------------------------------- string Board::getPossibilityString(int j, int k) const{ string possListStr; short possList = brd[(j - 1) * N + (k - 1)].getPossList(); for(int n = 1; n <= N; n++) { short mask = 1 << n; if((possList & mask) == 0) { possListStr.push_back('-'); } else { possListStr.append(to_string(n)); } } possListStr.push_back(' '); possListStr.push_back(' '); return possListStr; } //---------------------------------------------------------------- State Board::getSquare(int n) const { return brd[n]; } //---------------------------------------------------------------- void Board::makeClusters() { short j, k; for(j = 1; j <= N;j++) { createRow(j); } for(k = 1; k <= N; k++) { createColumn(k); } } //---------------------------------------------------------------- void Board::createRow(short j) { Square* rows[N]; for(short p = j; p<= j ; p++) { for(short q = 1; q<= N; q++) { rows[q-1] = &sub(p,q); } clusters.push_back(new Cluster(row, rows, N)); } } //---------------------------------------------------------------- void Board::createColumn(short k) { Square* cols[N]; for(short q = k; q <= k; q++) { for(short p =1; p <= N; p++) { cols[p-1] = &sub(p,q); } clusters.push_back(new Cluster(col, cols, N)); } } //---------------------------------------------------------------- ostream& Board::print(ostream& out) { for(int n = 0; n < N*N; n++){ out << brd[n]; } printCluster(out); return out; } //---------------------------------------------------------------- ostream& Board::printCluster(ostream& out) { for (Cluster* cl : clusters) { out << *cl << endl; } return out; } //---------------------------------------------------------------- void Board::mark() { short row, col; char ch; try { cout << "What is the row you want to mark?" << endl; cin >> row; cout << "What is the column you want to mark?" << endl; cin >> col; cout << sub(row, col); cout << "What number do you want to input?" << endl; cin >> ch; if(row < 1 || row > 9 || col < 1 || col > 9 ) { throw GameValues(row, col, ch); } sub(row, col).mark(ch); sub(row, col).getValue(); } catch (GameValues& ex) { ex.print(); } } //---------------------------------------------------------------- void Board::restoreState(Frame *frame) { State* states = frame->getState(); for(int n = 0; n < N*N; n++ ) { (State&) brd[n] = states[n]; } } //---------------------------------------------------------------- DiagBoard::DiagBoard(int n, ifstream &strm) : TradBoard(n, strm, 29) { DiagBoardClust(); DiagBoardOne(); DiagBoardTwo(); } //---------------------------------------------------------------- void DiagBoard::DiagBoardOne() { Square* diagOne[N]; int count = 0; for(int sub = 0; sub < N*N; sub+=10){ diagOne[count] = &brd[sub]; count++; } clusters.push_back(new Cluster(diag, diagOne, N)); } //---------------------------------------------------------------- void DiagBoard::DiagBoardTwo() { Square* diagTwo[N]; int count = 0; for(int sub = 8; sub < N*N; sub+=8){ diagTwo[count] = &brd[sub]; count++; } clusters.push_back(new Cluster(diag, diagTwo, N)); } //---------------------------------------------------------------- void DiagBoard::DiagBoardClust() { short j,k; for(j = 1; j <= N; j+=3){ for(k = 1; k <= N; k+=3){ Square* boxes[N]; int count = 0; for(int row = j; row <= j +2 ; row++){ for(int cell = k; cell <= k+2; cell++){ boxes[count] = &sub(row,cell); count++; } } Cluster* clust = new Cluster(box, boxes, N); clusters.push_back(clust); for(int n = 0; n < N; n++) { boxes[n]->addCluster(clust); clust->shoop(boxes[n]->getValue()); } } } } //---------------------------------------------------------------- SixyBoard::SixyBoard(int n, ifstream &strm) : Board(n, strm, 29) { HSixyBoard(); VSixyBoard(); } //---------------------------------------------------------------- void SixyBoard::VSixyBoard() { short j, k; for (j = 1; j <= N; j += 2) { for (k = 1; k <= N; k += 3) { Square* boxes[N]; int count = 0; for (int row = j; row <= j + 1; row++) { for (int cell = k; cell <= k + 2; cell++) { boxes[count] = &sub(row, cell); count++; } } Cluster *clust = new Cluster(vBox, boxes, N); clusters.push_back(clust); for (int n = 0; n < N; n++) { boxes[n]->addCluster(clust); clust->shoop(boxes[n]->getValue()); } } } } //---------------------------------------------------------------- void SixyBoard::HSixyBoard() { short j, k; for (j = 1; j <= N; j += 3) { for (k = 1; k <= N; k += 2) { Square* boxes[N]; int count = 0; for (int row = j; row <= j + 3 ; row++) { for (int cell = k; cell <= k + 1; cell++) { boxes[count] = &sub(row, cell); count++; } } Cluster *clust = new Cluster(hBox, boxes, N); clusters.push_back(clust); for (int n = 0; n < N; n++) { boxes[n]->addCluster(clust); clust->shoop(boxes[n]->getValue()); } } } } //---------------------------------------------------------------- TradBoard::TradBoard(int n, ifstream &strm, int nType) : Board(n, strm, 29) { short j,k; for(j = 1; j <= N; j+=3){ for(k = 1; k <= N; k+=3){ Square* boxes[N]; int count = 0; for(int row = j; row <= j +2 ; row++){ for(int cell = k; cell <= k+2; cell++){ boxes[count] = &sub(row,cell); count++; } } Cluster* clust = new Cluster(box, boxes, N); clusters.push_back(clust); for(int n = 0; n < N; n++) { boxes[n]->addCluster(clust); clust->shoop(boxes[n]->getValue()); } } } }
#include "DeleteUser.h" boost::property_tree::ptree DeleteUser::execute(std::shared_ptr<Controller> controller) { return controller->deleteUser(commandParams); } DeleteUser::DeleteUser(boost::property_tree::ptree &params) : BaseCommand("DelteChat") { commandParams = params; }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "12250" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif map <string,string> table; table["HELLO"] = "ENGLISH"; table["HOLA"] = "SPANISH"; table["HALLO"] = "GERMAN"; table["BONJOUR"] = "FRENCH"; table["CIAO"] = "ITALIAN"; table["ZDRAVSTVUJTE"] = "RUSSIAN"; string str; int kase = 1; while( cin >> str && str != "#" ){ printf("Case %d: ", kase++ ); if( table[str] != "" ) cout << table[str] << endl; else cout << "UNKNOWN" << endl; } return 0; }
#include <iostream> #include <random> #include <vector> #include <stdio.h> #include <conio.h> #include <stdbool.h> #include <Windows.h> using namespace std; #include <time.h> bool gameOver; //游戏结束标志 bool gameWin; //游戏胜利标志 bool stop; //暂停标志 bool hit; //方向键按下标志 //边界 const int width = 50; const int height = 20; //蛇的坐标,食物坐标和分数 int x, y, fruitX, fruitY, score; //蛇每�?点的坐标 vector<int> tailX, tailY; //蛇的默认长度 int ntail; enum Direction { KEEP = 0, LEFT, RIGHT, UP, DOWN, }; Direction Dir; //开始菜单 void menu() { int a; cout << "--------------------------------" << endl; cout << "| snack |" << endl; cout << "| 1.new game |" << endl; cout << "| 2.show look |" << endl; cout << "| 3.quit |" << endl; cout << "--------------------------------" << endl; cout << "-->select:"; cin >> a; switch (a) { case 1: stop = false; break; case 2: cout << "width:" << width << "height:" << height << endl; stop = true; break; case 3: gameOver = true; return; default: break; } } //初始化 void setup() { //根据当前时间设置随机数 srand(time(NULL)); Dir = KEEP; gameOver = false; //游戏结束标志 gameWin = false; stop = true; //暂停标志 hit = false; //方向键按下标志 //初始化蛇身坐标 tailX.clear(); tailY.clear(); tailX.resize(200); tailY.resize(200); //蛇的默认长度 ntail = 3; //蛇的起始位置 x = width / 2; y = height / 2; //食物的位置 fruitX = rand() % width+1; fruitY = rand() % height; score = 0; } //绘制界面 void draw() { if (stop == true) { return; } system("cls"); //清屏 cout << "score:" << score << endl; //line 1 for (int i = 0; i <= width + 1; i++) //width+bound,bound=2 { cout << "-"; } cout << endl; //center for (int p = 0; p <height; p++) //高度 { for (int q = 0; q <= width+1; q++) //宽度 { if (q == 0 || q == width + 1) //bound,|占用了2宽度 { cout << "|"; } else { if (p == fruitY && q == fruitX) //食物的随机坐标,食物范围fruitX=[1,width],fruitY=[0,height-1] { cout << 0; } else { bool print = false; for (int i = 0; i < ntail; i++) //搜索蛇的坐标是否包括该点 { if (tailX[i] == q && tailY[i] == p) { cout << "*"; print = true; } } if (!print) cout << " "; } } } cout << endl; } //last line for (int i = 0; i <= width + 1; i++) { cout << "-"; } } //按键输入控制 void input() { /* bool key = false; int time = 0; while (time < 30) { Sleep(5); if (kbhit()) { key = true; break; } time++; } */ if (_kbhit()) //检测是否有键盘按下 { //_getch(); //因为上下左右键是两个字节,先把第一个字节接收,然后用后一个字节判断 switch (_getch()) //如果按的是数字键盘,就不用接收第一个字节了 { case '4': case 75: //左键 if (Dir == RIGHT) break; Dir = LEFT; hit = true; break; case '8': case 72: //上键 if (Dir == DOWN) break; Dir = UP; hit = true; break; case '5': //下键 case 80: if (Dir == UP) break; Dir = DOWN; hit = true; break; case '6': case 77: //右键 if (Dir == LEFT) break; Dir = RIGHT; hit = true; break; case 'x': case 27: //ESE gameOver = true; break; case 32: //空格 stop = !stop; break; default: cout << endl << "unused key" << endl; stop = true; break; } } else if (!hit && stop == false) //没有按方向键也没有stop时的起始运动方向 { x++; //起始向右运动 } } //判断蛇长度 void logic() { if (stop == true) { return; //疑问 } //根据方向来改变x,y switch (Dir) { case UP: y--; //注意y为高度,上意味着减少高度 break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } if (x < 0 || x > width || y < 0 || y > height) { gameOver = true; //clearscreen system("cls"); } for (int i = 1; i < ntail - 1; i++) { if (tailX[i] == x && tailY[i] == y) { gameOver = true; break; } } if (x == fruitX && y == fruitY) { //吃了食物,长度加1 ntail++; score += 10; //更新下个食物位置 fruitX = rand() % width+1; fruitY = rand() % height; } //win condition if (score > 100) { gameWin = true; } //遍历整条蛇的长度,body往后面的空间移动 for (int i = ntail - 1; i > 0; i--) { tailX[i] = tailX[i - 1]; tailY[i] = tailY[i - 1]; } //重新获取当前位置 tailX[0] = x; tailY[0] = y; } void GameOver() { system("cls"); cout << "--------------------------------------------" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "| GameOver |" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "--------------------------------------------" << endl; } void GameWin() { system("cls"); cout << "--------------------------------------------" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "| GameWin! |" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "--------------------------------------------" << endl; } int main() { bool quit = false; while (!quit) { setup(); menu(); logic(); draw(); //loop吃蛇画面 while (!gameOver && !gameWin) { input(); logic(); draw(); Sleep(100); } if (gameOver) { GameOver(); } else { GameWin(); } cout << "really quit(1)?:" << endl; cin >> quit; if (quit) { return 0; } else { system("cls"); } system("pause"); } return 0; }
#pragma once #include "../Common/Transform.h" class GameObject { protected: class Transform* transform; int stride; // ΗΡ »ηΐΜΑξ DWORD FVF; LPDIRECT3DVERTEXBUFFER9 vb; LPDIRECT3DINDEXBUFFER9 ib; public: GameObject(); ~GameObject(); virtual void Init(); virtual void Release(); virtual void Update(); virtual void Render(); Transform * GetTransform() { return transform; } };
#ifndef INFIXVISITOR_H_ #define INFIXVISITOR_H_ #include <iostream> class InfixVisitor : public PrePostVisitor { public: void PreVisit (Object&) { std::cout << "("; } void Visit (Object& object) { std::cout << object; } void PostVisit (Object&) { std::cout << ")"; } }; #endif /*INFIXVISITOR_H_*/
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include "CryptoNoteCore/CryptoNoteBasic.h" #include "crypto/crypto.h" namespace cn { class ISerializer; /************************************************************************/ /* */ /************************************************************************/ class AccountBase { public: AccountBase(); void generate(); static void generateViewFromSpend(crypto::SecretKey &, crypto::SecretKey &, crypto::PublicKey &); const AccountKeys& getAccountKeys() const; void setAccountKeys(const AccountKeys& keys); uint64_t get_createtime() const { return m_creation_timestamp; } void set_createtime(uint64_t val) { m_creation_timestamp = val; } void serialize(ISerializer& s); template <class t_archive> inline void serialize(t_archive &a, const unsigned int /*ver*/) { a & m_keys; a & m_creation_timestamp; } private: void setNull(); AccountKeys m_keys; uint64_t m_creation_timestamp; }; }
#include "stdafx.h" #include <commctrl.h> #include "window.h" #include "rom_file.h" HINSTANCE kInstance; void GetErrorMessage(std::string& message, DWORD code) { message.clear(); if (!code) { code = GetLastError(); } TCHAR *lpMsg; DWORD msgLen; msgLen = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsg, 0, NULL ); if (!msgLen) { return ; } message.append(lpMsg, msgLen); LocalFree(lpMsg); } Window::Window() { hwnd_ = NULL; child_window_ = false; panel_ = NULL; } Window::Window(HWND hwnd) { hwnd_ = hwnd; child_window_ = true; panel_ = NULL; } Window::~Window() { if (!child_window_) { Destroy(); } DestroyPanel(); } bool Window::Create(LPCSTR lpClassName, LPCSTR lpWindowName, DWORD dwExStyles, DWORD dwStyles, int x, int y, int width, int height, HMENU menu, Window *parent) { Destroy(); HWND hParent = NULL; child_window_ = false; if (parent) { hParent = parent->GetHWND(); } hwnd_ = CreateWindowEx(dwExStyles, lpClassName, lpWindowName, dwStyles, x, y, width, height, hParent, menu, kInstance, this); if (hwnd_ != NULL) { SetWindowLong(hwnd_, GWL_USERDATA, (LONG) this); } return hwnd_ != NULL; } void Window::OnCreate() { } void Window::OnSize(WORD width, WORD height) { if (panel_) { panel_->OnSize(width, height); } } void Window::OnCommand(DWORD id, DWORD code) { if (panel_) { panel_->OnCommand(id, code); } } void Window::OnMouseDown(DWORD key, int x, int y) { if (panel_) { panel_->OnMouseDown(key, x, y); } } void Window::OnMouseUp(DWORD key, int x, int y) { if (panel_) { panel_->OnMouseUp(key, x, y); } } void Window::OnMouseMove(int x, int y) { if (panel_) { panel_->OnMouseMove(x, y); } } void Window::OnMouseDoubleClick(DWORD key, int x, int y) { if (panel_) { panel_->OnMouseDoubleClick(key, x, y); } } bool Window::OnKeyDown(DWORD key_code) { if (panel_) { return panel_->OnKeyDown(key_code); } return false; } bool Window::OnQueryCursor(DWORD dwHitTest, const POINT& pt) { if (panel_) { return panel_->OnQueryCursor(dwHitTest, pt); } return false; } void Window::OnPaint(HDC hdc, const RECT& rcPaint) { if (panel_) { panel_->OnPaint(hdc, rcPaint); } } void Window::OnPaintArea(const RECT& pos, HDC hdc) { if (panel_) { panel_->OnPaintArea(pos, hdc); } } bool Window::OnEraseBackground(HDC hdc) { if (panel_) { return panel_->OnEraseBackground(hdc); } return false; } bool Window::OnDrawItem(DWORD id, DRAWITEMSTRUCT* item) { if (panel_) { return panel_->OnDrawItem(id, item); } return false; } bool Window::OnMesureItem(DWORD id, MEASUREITEMSTRUCT* mesure) { if (panel_) { return panel_->OnMesureItem(id, mesure); } return false; } void Window::OnTimer(DWORD id) { if (panel_) { panel_->OnTimer(id); } } LRESULT Window::OnMessage(UINT msg, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; switch (msg) { case WM_SIZE: OnSize(LOWORD(lParam), HIWORD(lParam)); return 0; case WM_COMMAND: OnCommand(LOWORD(wParam), HIWORD(wParam)); return 0; case WM_PAINT: hdc = BeginPaint(hwnd_, &ps); OnPaint(hdc, ps.rcPaint); EndPaint(hwnd_, &ps); return 0; case WM_ERASEBKGND: if (OnEraseBackground((HDC) wParam)) { return 0; } break ; case WM_LBUTTONDOWN: OnMouseDown(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_LBUTTONUP: OnMouseUp(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_MOUSEMOVE: OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_LBUTTONDBLCLK: OnMouseDoubleClick(wParam, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); return 0; case WM_KEYDOWN: if (OnKeyDown(wParam)) { return 0; } break ; case WM_SETCURSOR: { DWORD cursor_pos = GetMessagePos(); POINT pt = { GET_X_LPARAM(cursor_pos), GET_Y_LPARAM(cursor_pos) }; ScreenToClient(hwnd_, &pt); if (OnQueryCursor(LOWORD(lParam), pt)) { return TRUE; } } break; case WM_DRAWITEM: if (OnDrawItem(wParam, (LPDRAWITEMSTRUCT) lParam)) { return TRUE; } break ; case WM_MEASUREITEM: if (OnMesureItem(wParam, (LPMEASUREITEMSTRUCT) lParam)) { return TRUE; } break ; case WM_TIMER: OnTimer(wParam); break ; case WM_NCDESTROY: hwnd_ = NULL; break ; } if (panel_) { return panel_->OnMessage(msg, wParam, lParam); } return DefWindowProc(hwnd_, msg, wParam, lParam); } void Window::SetPanel(Panel *panel) { DestroyPanel(); panel_ = panel; if (panel_) { panel_->hwnd_ = hwnd_; panel_->parent_ = this; panel_->child_window_ = true; panel_->OnCreate(); } } void Window::SetPosition(int x, int y, int width, int height) { SetWindowPos(hwnd_, NULL, x, y, width, height, SWP_NOZORDER); } void Window::SetSize(int width, int height) { SetWindowPos(hwnd_, NULL, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER); } void Window::SetDefaultFont() { SendMessage(hwnd_, WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT), FALSE ); } void Window::SetRedraw(bool redraw) { UINT flag = redraw ? 1 : 0; SendMessage(hwnd_, WM_SETREDRAW, flag, 0); } bool Window::SetClipboardData(const TCHAR *format, Buffer& src_buf) { if (!OpenClipboard(hwnd_)) { return false; } UINT uFormat = RegisterClipboardFormat(format); UINT mem_size = src_buf.GetDataSize(); if (mem_size > 10000) { CloseClipboard(); return false; } HGLOBAL hClipData = GlobalAlloc(GMEM_MOVEABLE, mem_size); if (hClipData == NULL) { CloseClipboard(); return false; } BYTE *data = (BYTE*) GlobalLock(hClipData); if (data == NULL) { GlobalFree(hClipData); CloseClipboard(); return false; } src_buf.Read(0, data, mem_size); GlobalUnlock(hClipData); ::SetClipboardData(uFormat, hClipData); CloseClipboard(); return true; } void Window::Show() { ShowWindow(hwnd_, SW_SHOW); } void Window::Hide() { ShowWindow(hwnd_, SW_HIDE); } void Window::SetFocus() { ::SetFocus(hwnd_); } void Window::Invalidate(const RECT *rect) { InvalidateRect(hwnd_, rect, FALSE); } void Window::Redraw() { RedrawWindow(hwnd_, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN); } void Window::Update() { UpdateWindow(hwnd_); } void Window::CaptureMouse() { SetCapture(hwnd_); } void Window::ReleaseMouse() { ReleaseCapture(); } void Window::Destroy() { if (!hwnd_) { return ; } DestroyWindow(hwnd_); hwnd_ = NULL; } void Window::DestroyPanel() { if (!panel_) { return ; } panel_->OnDestroy(); delete panel_; panel_ = NULL; } HWND Window::GetHWND() { return hwnd_; } HDC Window::GetDC() { return ::GetDC(hwnd_); } void Window::DestroyDC(HDC hdc) { ReleaseDC(hwnd_, hdc); } void Window::GetRect(RECT& rect) { GetClientRect(hwnd_, &rect); } int Window::GetText(TCHAR *dst_buffer, int dst_buffer_count) { return GetWindowText(hwnd_, dst_buffer, dst_buffer_count); } LRESULT CALLBACK Window::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { Window *self; self = (Window*) GetWindowLong(hwnd, GWL_USERDATA); if (msg == WM_CREATE) { CREATESTRUCT *ccs = (LPCREATESTRUCT) lParam; self = (Window*) ccs->lpCreateParams; if (self) { self->OnCreate(); return 0; } } if (!self) { return DefWindowProc(hwnd, msg, wParam, lParam); } return self->OnMessage(msg, wParam, lParam); } bool Window::Register(LPCSTR lpClassName, HBRUSH hbrBackground, HICON hIcon, DWORD style) { WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = hbrBackground; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = hIcon; wc.hInstance = kInstance; wc.lpfnWndProc = Window::WndProc; wc.lpszClassName = lpClassName; wc.lpszMenuName = NULL; wc.style = style; return RegisterClass(&wc) != NULL; } RedrawRegion::RedrawRegion(Window& window) : window_(window) { invalidated_ = false; } RedrawRegion::~RedrawRegion() { if (invalidated_) { window_.Update(); } } void RedrawRegion::Invalidate(const RECT *rect) { window_.Invalidate(rect); invalidated_ = true; } ToolbarWindow::ToolbarWindow() { toolbar_img_ = NULL; disabled_img_ = NULL; } ToolbarWindow::~ToolbarWindow() { DestroyToolbarImg(); } bool ToolbarWindow::Create(DWORD dwExStyles, DWORD dwStyles, DWORD id, Window& parent) { dwStyles |= WS_CHILD; if (!Window::Create(TOOLBARCLASSNAME, NULL, dwExStyles, dwStyles, 0, 0, 0, 0, (HMENU) id, &parent)) { return false; } SendMessage(hwnd_, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), NULL); return true; } int ToolbarWindow::AddBitmap(DWORD count, LPTBADDBITMAP bitmaps) { return SendMessage(hwnd_, TB_ADDBITMAP, 0, (LPARAM) bitmaps); } bool ToolbarWindow::AddButtons(DWORD count, LPTBBUTTON buttons) { return SendMessage(hwnd_, TB_ADDBUTTONS, count, (LPARAM) buttons) == TRUE; } bool ToolbarWindow::DeleteButton(DWORD index) { return SendMessage(hwnd_, TB_DELETEBUTTON, index, 0) != FALSE; } void ToolbarWindow::AutoSize() { SendMessage(hwnd_, TB_AUTOSIZE, 0, 0); } void ToolbarWindow::SetMaxTextRows(DWORD rows) { SendMessage(hwnd_, TB_SETMAXTEXTROWS, rows, 0); } void ToolbarWindow::SetImgList(HIMAGELIST hToolImg, HIMAGELIST hDiabledImg) { DestroyToolbarImg(); if (hToolImg) { toolbar_img_ = hToolImg; } if (hDiabledImg) { disabled_img_ = hDiabledImg; } SendMessage(hwnd_, TB_SETIMAGELIST, 0, (LPARAM) hToolImg); SendMessage(hwnd_, TB_SETDISABLEDIMAGELIST, 0, (LPARAM) hDiabledImg); } void ToolbarWindow::DestroyToolbarImg() { if (toolbar_img_) { ImageList_Destroy(toolbar_img_); toolbar_img_ = NULL; } if (disabled_img_) { ImageList_Destroy(disabled_img_); disabled_img_ = NULL; } } StatusWindow::StatusWindow() { } StatusWindow::~StatusWindow() { } bool StatusWindow::Create(DWORD dwExStyles, DWORD dwStyles, DWORD id, Window& parent) { dwStyles |= WS_CHILD; return Window::Create(STATUSCLASSNAME, NULL, dwExStyles, dwStyles, 0, 0, 0, 0, (HMENU) id, &parent); } void StatusWindow::SetParts(DWORD count, int *partsWidth) { SendMessage(hwnd_, SB_SETPARTS, count, (LPARAM) partsWidth); } void StatusWindow::AutoSize() { SendMessage(hwnd_, WM_SIZE, 0, 0); } PickFileWindow::PickFileWindow(std::string& path, const TCHAR *filters, const TCHAR *def_ext) : path_(path), def_ext_(def_ext) { filters_ = filters; } PickFileWindow::~PickFileWindow() { } bool PickFileWindow::Open(const TCHAR* title, Window *parent) { TCHAR path[MAX_PATH] = {}, file_name[64]; OPENFILENAME ofn = {}; ofn.lStructSize = sizeof(ofn); if (parent) { ofn.hwndOwner = parent->GetHWND(); } ofn.hInstance = kInstance; ofn.lpstrFilter = filters_; ofn.lpstrFile = path; ofn.nMaxFile = MAX_PATH; ofn.lpstrFileTitle = file_name; ofn.nMaxFileTitle = 64; ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = def_ext_; if (title) { ofn.lpstrTitle = title; } if (!GetOpenFileName(&ofn)) { return false; } path_.clear(); path_.append(ofn.lpstrFile, ofn.nMaxFile); return true; } bool ListBox::Create(DWORD id, DWORD dwExStyles, DWORD dwStyles, int x, int y, int width, int height, Window& parent) { dwStyles |= WS_CHILD; return Window::Create(WC_LISTBOX, NULL, dwExStyles, dwStyles, x, y, width, height, (HMENU) id, &parent); } int ListBox::AddString(const TCHAR *str) { return SendMessage(hwnd_, LB_ADDSTRING, 0, (LPARAM) str ); } DWORD ListBox::GetItemData(int index) { return SendMessage(hwnd_, LB_GETITEMDATA, index, 0 ); } int ListBox::SetItemData(int index, DWORD value) { return SendMessage(hwnd_, LB_SETITEMDATA, index, value ); } int ListBox::GetSelIndex() { return SendMessage(hwnd_, LB_GETCURSEL, 0, 0); } void ListBox::SetCount(UINT count) { SendMessage(hwnd_, LB_SETCOUNT, count, 0 ); } void ListBox::SetSel(int index) { SendMessage(hwnd_, LB_SETCURSEL, index, 0); } bool ListView::Create(DWORD id, DWORD dwExStyles, DWORD dwStyles, int x, int y, int width, int height, Window& parent ) { dwStyles |= WS_CHILD; return Window::Create(WC_LISTVIEW, NULL, dwExStyles, dwStyles, x, y, width, height, (HMENU) id, &parent); } void ListView::SetCount(UINT count) { SendMessage(hwnd_, LVM_SETITEMCOUNT, count, 0); } bool TreeView::Create(DWORD id, DWORD dwExStyles, DWORD dwStyles, int x, int y, int width, int height, Window& parent) { dwStyles |= WS_CHILD; return Window::Create(WC_TREEVIEW, NULL, dwExStyles, dwStyles, x, y, width, height, (HMENU) id, &parent); } HTREEITEM TreeView::InsertItem(TVINSERTSTRUCT *tvinsert) { return (HTREEITEM) TreeView_InsertItem(hwnd_, tvinsert); } void TreeView::DeleteAll() { SendMessage(hwnd_, TVM_DELETEITEM, 0, (LPARAM) TVI_ROOT); }
#include <iostream> using ll = long long; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int l; std::cin >> l; std::string s; std::cin >> s; constexpr ll r = 31; constexpr ll m = 1234567891; ll h{}; for (int i = 0; i < s.size(); ++i) { ll res = s[i] - 'a' + 1; ll now = r; int t = i; while (t) { if (t & 1) { res *= now; res %= m; } t >>= 1; now *= now; now %= m; } h += res; h %= m; } std::cout << h << '\n'; return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ vector<int>v; int n,num; scanf("%d",&n); for(int i = 0; i<n; ++i){ scanf("%d",&num); vector<int>::iterator iV = lower_bound(v.begin(),v.end(),num); if(v.end() == iV) v.push_back(num); else v[iV-v.begin()] = num; } printf("LIS = %d\n",v.size()); }
// Created on: 1993-09-28 // Created by: Bruno DUMORTIER // 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 _GeomFill_HeaderFile #define _GeomFill_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Convert_ParameterisationType.hxx> #include <Standard_Real.hxx> #include <TColgp_Array1OfPnt.hxx> #include <TColStd_Array1OfReal.hxx> #include <Standard_Boolean.hxx> #include <TColgp_Array1OfVec.hxx> #include <Standard_Integer.hxx> #include <TColStd_Array1OfInteger.hxx> class Geom_Surface; class Geom_Curve; class gp_Vec; class gp_Pnt; //! Tools and Data to filling Surface and Sweep Surfaces class GeomFill { public: DEFINE_STANDARD_ALLOC //! Builds a ruled surface between the two curves, Curve1 and Curve2. Standard_EXPORT static Handle(Geom_Surface) Surface (const Handle(Geom_Curve)& Curve1, const Handle(Geom_Curve)& Curve2); Standard_EXPORT static void GetCircle (const Convert_ParameterisationType TConv, const gp_Vec& ns1, const gp_Vec& ns2, const gp_Vec& nplan, const gp_Pnt& pt1, const gp_Pnt& pt2, const Standard_Real Rayon, const gp_Pnt& Center, TColgp_Array1OfPnt& Poles, TColStd_Array1OfReal& Weigths); Standard_EXPORT static Standard_Boolean GetCircle (const Convert_ParameterisationType TConv, const gp_Vec& ns1, const gp_Vec& ns2, const gp_Vec& dn1w, const gp_Vec& dn2w, const gp_Vec& nplan, const gp_Vec& dnplan, const gp_Pnt& pts1, const gp_Pnt& pts2, const gp_Vec& tang1, const gp_Vec& tang2, const Standard_Real Rayon, const Standard_Real DRayon, const gp_Pnt& Center, const gp_Vec& DCenter, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths); Standard_EXPORT static Standard_Boolean GetCircle (const Convert_ParameterisationType TConv, const gp_Vec& ns1, const gp_Vec& ns2, const gp_Vec& dn1w, const gp_Vec& dn2w, const gp_Vec& d2n1w, const gp_Vec& d2n2w, const gp_Vec& nplan, const gp_Vec& dnplan, const gp_Vec& d2nplan, const gp_Pnt& pts1, const gp_Pnt& pts2, const gp_Vec& tang1, const gp_Vec& tang2, const gp_Vec& Dtang1, const gp_Vec& Dtang2, const Standard_Real Rayon, const Standard_Real DRayon, const Standard_Real D2Rayon, const gp_Pnt& Center, const gp_Vec& DCenter, const gp_Vec& D2Center, TColgp_Array1OfPnt& Poles, TColgp_Array1OfVec& DPoles, TColgp_Array1OfVec& D2Poles, TColStd_Array1OfReal& Weigths, TColStd_Array1OfReal& DWeigths, TColStd_Array1OfReal& D2Weigths); Standard_EXPORT static void GetShape (const Standard_Real MaxAng, Standard_Integer& NbPoles, Standard_Integer& NbKnots, Standard_Integer& Degree, Convert_ParameterisationType& TypeConv); Standard_EXPORT static void Knots (const Convert_ParameterisationType TypeConv, TColStd_Array1OfReal& TKnots); Standard_EXPORT static void Mults (const Convert_ParameterisationType TypeConv, TColStd_Array1OfInteger& TMults); Standard_EXPORT static void GetMinimalWeights (const Convert_ParameterisationType TConv, const Standard_Real AngleMin, const Standard_Real AngleMax, TColStd_Array1OfReal& Weigths); //! Used by the generical classes to determine //! Tolerance for approximation Standard_EXPORT static Standard_Real GetTolerance (const Convert_ParameterisationType TConv, const Standard_Real AngleMin, const Standard_Real Radius, const Standard_Real AngularTol, const Standard_Real SpatialTol); }; #endif // _GeomFill_HeaderFile
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct student { string name; string sno; int grade; }; int main(int argc, char const *argv[]) { int n; scanf("%d", &n); student max, min; max.grade = -1; min.grade = 0x7fffffff; for (int i = 0; i < n; ++i) { student temp; cin >> temp.name >> temp.sno >> temp.grade; if ( temp.grade > max.grade ) { max.name = temp.name; max.sno = temp.sno; max.grade = temp.grade; } if( temp.grade < min.grade ) { min.name = temp.name; min.sno = temp.sno; min.grade = temp.grade; } } cout << max.name << " " << max.sno << endl; cout << min.name << " " << min.sno << endl; return 0; }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * 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 SKLAND_WAYLAND_REGION_HPP_ #define SKLAND_WAYLAND_REGION_HPP_ #include "compositor.hpp" namespace skland { namespace wayland { class Region { friend class Surface; Region(const Region &) = delete; Region &operator=(const Region &) = delete; public: Region() : wl_region_(nullptr) {} ~Region() { if (wl_region_) wl_region_destroy(wl_region_); } void Setup(const Compositor &compositor) { Destroy(); wl_region_ = wl_compositor_create_region(compositor.wl_compositor_); } void Destroy() { if (wl_region_) { wl_region_destroy(wl_region_); wl_region_ = nullptr; } } void Add(int32_t x, int32_t y, int32_t width, int32_t height) const { wl_region_add(wl_region_, x, y, width, height); } void Subtract(int32_t x, int32_t y, int32_t width, int32_t height) const { wl_region_subtract(wl_region_, x, y, width, height); } void SetUserData(void *user_data) { wl_region_set_user_data(wl_region_, user_data); } void *GetUserData() const { return wl_region_get_user_data(wl_region_); } uint32_t GetVersion() const { return wl_region_get_version(wl_region_); } bool IsValid() const { return nullptr != wl_region_; } private: struct wl_region *wl_region_; }; } } #endif // SKLAND_WAYLAND_REGION_HPP_
#include<bits/stdc++.h> using namespace std; #define maxn 1000005 #define Mod 1000000007 using ll=long long; ll p[maxn]; ll q[maxn]; void init(){ ll s=1; p[0]=1; for(int i=1;i<=1e6+1;i++){ s=s*2%Mod; p[i]=p[i-1]+s; } } int main(){ init(); string s; cin>>s; int sz=s.size(); int cnt=0; ll ans=0; for(int i=0;i<sz;i++){ if(s[i]=='a') cnt++; if(s[i]=='b'){ ans=(ans+p[cnt-1])%Mod; } } cout<<ans<<"\n"; return 0; }
/*Complete the function(s) below*/ // Special Stack void push(stack<int> s,int a) { //add code here. if(s.empty()) { s.push(a); s.push(a); return; } if(a < s.top()) { s.push(a); s.push(a); return; } int min_value = s.top(); s.push(a); s.push(min_value); return; } bool isFull(stack<int> s,int n) { //add code here. if(s.size() >= 2*n) return 1; return 0; } bool isEmpty(stack<int> s) { //add code here. if(s.size() == 0) return 1; return 0; } int pop(stack<int> s) { //add code here. if(s.size() == 0) return -1; s.pop(); int ele = s.top(); s.pop(); return ele; } int getMin(stack<int> s) { //add code here. return s.top(); }
#pragma once #include <SFML/Graphics.hpp> #include <map> namespace CAE { enum class ico_t { Editor_Delete = 0, Editor_Add, Folder, File_img, File_txt, Refresh, Magic, Save, Create, Move, Hand, Arrow, Selection }; class IcoHolder { private: static std::map<ico_t, sf::Texture> ico; sf::Texture create(std::string_view path) { sf::Texture t; t.loadFromFile(path.data()); return t; }; public: IcoHolder() { ico[ico_t::Editor_Add] = create(".\\data\\ico\\addico.png"); ico[ico_t::Editor_Delete] = create(".\\data\\ico\\trash.png"); ico[ico_t::Folder] = create(".\\data\\ico\\folder.png"); ico[ico_t::Refresh] = create(".\\data\\ico\\refresh.png"); ico[ico_t::Magic] = create(".\\data\\ico\\magic.png"); ico[ico_t::Save] = create(".\\data\\ico\\save.png"); ico[ico_t::Create] = create(".\\data\\ico\\create.png"); ico[ico_t::Move] = create(".\\data\\ico\\move.png"); ico[ico_t::Hand] = create(".\\data\\ico\\hand.png"); ico[ico_t::File_img] = create(".\\data\\ico\\file_img.png"); ico[ico_t::File_txt] = create(".\\data\\ico\\file_txt.png"); ico[ico_t::Arrow] = create(".\\data\\ico\\arrow.png"); ico[ico_t::Selection] = create(".\\data\\ico\\select.png"); } const sf::Texture& getTexture(ico_t type) const { return ico[type]; } static const sf::Texture& getTexture_s(ico_t type) { return ico[type]; } }; }
#pragma once #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> #include "utils/log.hpp" #include "utils/assert.hpp" #include <map> #include <functional> #include <exception> #include <chrono> using namespace std; using namespace chrono; using namespace google::protobuf; namespace proto { template <typename T, typename BASE> class processor { public: static void register_proto_handler(const Descriptor *descriptor, function<void(T *, const BASE *)> handler) { handlers_[descriptor] = handler; } bool has_handler(T *t, const BASE *proto) const { const Reflection *reflection = proto->GetReflection(); vector<const FieldDescriptor *> fields; reflection->ListFields(*proto, &fields); if (fields.size() > 2 || fields.size() < 1) { ELOG << *t << " got proto with " << fields.size() << " fields"; return false; } const Descriptor *desc = fields.back()->message_type(); return handlers_.count(desc) > 0; } void process(T *t, const BASE *proto) { const Reflection *reflection = proto->GetReflection(); vector<const FieldDescriptor *> fields; reflection->ListFields(*proto, &fields); if (fields.size() > 2 || fields.size() < 1) { ELOG << *t << " got proto with " << fields.size() << " fields"; return; } const Descriptor *desc = fields.back()->message_type(); if (handlers_.count(desc) <= 0) { return; } if (ignore_min_frequency_.count(desc) == 0 && min_frequency_ > system_clock::duration::zero()) { auto now = system_clock::now(); if (last_proto_times_.count(desc) > 0 && now - last_proto_times_.at(desc) < min_frequency_) { return; } last_proto_times_[desc] = now; } if (process_msg_cb_) { process_msg_cb_(desc, proto->ByteSize()); } try { handlers_[desc](t, proto); } catch(const exception& e) { ELOG << e.what() << "\nproto:\n" << proto->DebugString(); } } void set_proto_min_frequency(const system_clock::duration& du) { min_frequency_ = du; } void add_ignore_min_frequency(const Descriptor *desc) { ignore_min_frequency_.insert(desc); } function<void(const Descriptor *, size_t)> process_msg_cb_; private: static map<const Descriptor *, function<void(T *, const BASE *)>> handlers_; system_clock::duration min_frequency_ = system_clock::duration::zero(); map<const Descriptor *, system_clock::time_point> last_proto_times_; set<const Descriptor *> ignore_min_frequency_; }; template <typename T, typename BASE> map<const Descriptor *, function<void(T *, const BASE *)>> processor<T, BASE>::handlers_; }
#include "Timerfd.h" #include <assert.h> #include <stdlib.h> #include <sys/timerfd.h> #include "Logger.h" namespace chatty { namespace net { int create_timerfd() { int fd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); if (fd < 0) { LOGERROR << "timerfd_create error" << std::endl; exit(-1); } return fd; } void set_timerfd(int fd, int start_time, int interval) { assert(fd > 0); struct itimerspec new_val; ::memset(&new_val, 0, sizeof new_val); new_val.it_value.tv_sec = start_time; new_val.it_interval.tv_sec = interval; if (::timerfd_settime(fd, 0, &new_val, NULL) != 0) { LOGERROR << "timerfd_settime error" << std::endl; exit(-1); } } } // namespace net } // namespace chatty
#include "mythread.h" #include <QtCore> #include <QDebug> MyThread::MyThread() { } MyThread::~MyThread() { }
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> #include <memory> #include <valarray> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; while (scanf("%d", &n) != EOF) { vector<int> so(n+1, 0), ta(n+1, 0); for (int i = 1; i <= n; i++) scanf("%d", &so[i]); for (int i = 1; i <= n; i++) scanf("%d", &ta[i]); int i = 1, j = 1; for (i; i < n && ta[i] <= ta[i + 1]; i++); for (j = i + 1; j <= n && so[j] == ta[j]; j++); if (j == n + 1) { printf("Insertion Sort\n"); sort(ta.begin() + 1, ta.begin() + i + 2); } else { printf("Heap Sort\n"); int index = n; for (index; index > 1 && ta[index] >= ta[index - 1]; index--); swap(ta[1], ta[index]); for (int i = 1; 2 * i < index;) { int child = 2 * i; if (child + 1 < index && ta[child] < ta[child+1]) child++; if (ta[i] < ta[child]) { swap(ta[i], ta[child]); i = child; } else break; } } for (int i = 1; i < ta.size(); i++) { if (i != 1) printf(" "); printf("%d", ta[i]); } printf("\n"); } return 0; }
#include "catch.hpp" #include <Parser.hpp> #include <iostream> TEST_CASE("Test Parser", "[Parser]") { }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- ** ** Copyright (C) 2005-2007 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 SVG_SUPPORT #include "modules/svg/src/animation/svganimationschedule.h" #include "modules/svg/src/animation/svganimationworkplace.h" #include "modules/svg/src/animation/svganimationinterval.h" #include "modules/svg/src/animation/svgtimingarguments.h" #include "modules/svg/src/animation/svganimationarguments.h" #include "modules/svg/src/svgpch.h" #include "modules/svg/src/SVGVector.h" #include "modules/svg/src/SVGTimeValue.h" #include "modules/svg/src/SVGUtils.h" #include "modules/svg/src/SVGDocumentContext.h" #include "modules/svg/src/SVGTimedElementContext.h" #include "modules/svg/src/SVGManagerImpl.h" #include "modules/svg/src/AttrValueStore.h" SVGAnimationSchedule::SVGAnimationSchedule() : current_interval(NULL), previous_interval(NULL) { activation_time = SVGAnimationTime::Indefinite(); packed_init = 0; packed.instance_lists_dirty = 1; } SVGAnimationSchedule::~SVGAnimationSchedule() { UINT32 i=0; for (;i<syncbase_time_objects.GetCount();i++) SVGObject::DecRef(syncbase_time_objects.Get(i)); for (i=0;i<repeat_time_objects.GetCount();i++) SVGObject::DecRef(repeat_time_objects.Get(i)); OP_DELETE(current_interval); OP_DELETE(previous_interval); } void SVGAnimationSchedule::DiscardCurrentInterval() { OP_DELETE(current_interval); current_interval = NULL; } OP_STATUS SVGAnimationSchedule::UpdateIntervals(SVGAnimationWorkplace* animation_workplace, SVGTimingInterface* timing_if, SVGTimingArguments &timing_arguments) { SVG_ANIMATION_TIME document_time = animation_workplace->DocumentTime(); if (packed.instance_lists_dirty) { RebuildInstanceLists(timing_arguments); if (packed.is_computing_dependant) return OpStatus::OK; if (current_interval != NULL) { if (current_interval->Begin() > document_time) /* The interval hasn't begun yet, we recalculate it based on the new instance lists */ DiscardCurrentInterval(); if (current_interval && document_time < current_interval->End()) { OP_ASSERT(current_interval->Begin() <= document_time); /* The current interval has begun, the active duration may have changed. */ SVG_ANIMATION_TIME active_duration; SVG_ANIMATION_TIME repeat_duration; SVG_ANIMATION_TIME current_end_time = CalculateActiveDuration(timing_arguments, active_duration, repeat_duration, current_interval->Begin()); if (SVGAnimationTime::IsUnresolved(current_end_time)) { // We could not calculate the active duration this // time, throw away this interval. DiscardCurrentInterval(); RETURN_IF_ERROR(NotifyDependingElements(animation_workplace, NULL)); } else { // Adjust the end time but keep the local // invariant that end time is larger than the // document time, in order to not disrupt the // event dispatching. current_end_time = MAX(current_end_time, document_time + 1); if (current_interval->End() != current_end_time) { current_interval->SetEnd(current_end_time); RETURN_IF_ERROR(NotifyDependingElements(animation_workplace, current_interval)); } } } } } BOOL should_calculate_next_interval = CheckCurrentInterval(animation_workplace, timing_arguments); if (should_calculate_next_interval) { SVGAnimationInterval* new_interval = NULL; SVG_ANIMATION_TIME begin_past_time = current_interval ? current_interval->End() : SVGAnimationTime::Earliest(); SVG_ANIMATION_TIME end_past_time = document_time; RETURN_IF_ERROR(CalculateNextInterval(begin_past_time, end_past_time, timing_arguments, new_interval)); if (new_interval != NULL) { PushInterval(new_interval); RETURN_IF_ERROR(NotifyDependingElements(animation_workplace, new_interval)); SVG_ANIMATION_NOTIFY_NEW_INTERVAL(animation_workplace, timing_if, &timing_arguments, new_interval); } } return OpStatus::OK; } OP_BOOLEAN SVGAnimationSchedule::CommitIntervals(SVGAnimationWorkplace* animation_workplace, SVG_ANIMATION_TIME document_time, BOOL send_events, SVG_ANIMATION_TIME elapsed_time, BOOL at_prezero, SVGTimingInterface* timing_if, SVGTimingArguments &timing_arguments) { // The current interval is now final, send events if (elapsed_time > 0 || at_prezero) DispatchEvents(animation_workplace, document_time, timing_if, timing_arguments, elapsed_time, send_events, at_prezero); BOOL has_switched_interval = GetActiveInterval(document_time - elapsed_time) != GetActiveInterval(document_time); OP_BOOLEAN ret = packed.has_new_interval || has_switched_interval ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE; packed.has_new_interval = 0; return ret; } OP_STATUS SVGAnimationSchedule::Reset(SVGTimingArguments &timing_arguments) { OP_DELETE(current_interval); current_interval = NULL; OP_DELETE(previous_interval); previous_interval = NULL; packed.one_interval_started = 0; packed.instance_lists_dirty = 0; return RebuildInstanceLists(timing_arguments); } OP_STATUS SVGAnimationSchedule::CalculateNextInterval(SVG_ANIMATION_TIME begin_past_time, SVG_ANIMATION_TIME end_past_time, SVGTimingArguments &timing_arguments, SVGAnimationInterval*& new_interval) { while(TRUE) { SVG_ANIMATION_TIME current_begin_time = begin_instance_list.FirstEqualOrPast(begin_past_time); OP_ASSERT(!SVGAnimationTime::IsIndefinite(current_begin_time)); // No indefinte values in begin instance list allowed if (SVGAnimationTime::IsUnresolved(current_begin_time)) // No more intervals { return OpStatus::OK; } SVG_ANIMATION_TIME active_duration; SVG_ANIMATION_TIME repeat_duration; SVG_ANIMATION_TIME current_end_time = CalculateActiveDuration(timing_arguments, active_duration, repeat_duration, current_begin_time); if (SVGAnimationTime::IsUnresolved(current_end_time)) { // No valid interval left OP_ASSERT(new_interval == NULL || !"We should not return an interval"); return OpStatus::OK; } else if (current_end_time >= end_past_time) { new_interval = OP_NEW(SVGAnimationInterval, (current_begin_time, current_end_time, repeat_duration, timing_arguments.simple_duration)); return new_interval ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } else { begin_past_time = current_end_time; } } } OP_STATUS SVGAnimationSchedule::RebuildInstanceLists(SVGTimingArguments &timing_arguments) { begin_instance_list.Clear(); end_instance_list.Clear(); SVGRestartType restart_type = timing_arguments.restart_type; unsigned i=0; for (;i<extra_begin_instance_list.GetCount();i++) RETURN_IF_ERROR(AddBeginInstance(extra_begin_instance_list[i], restart_type)); for (i=0;i<extra_end_instance_list.GetCount();i++) RETURN_IF_ERROR(end_instance_list.Add(extra_end_instance_list[i])); if (SVGAnimationTime::IsNumeric(activation_time)) RETURN_IF_ERROR(AddBeginInstance(activation_time, restart_type)); if (timing_arguments.packed.begin_is_empty) { AddBeginInstance(0, restart_type); } else if (SVGVector *begin_list = timing_arguments.GetBeginList()) { for (UINT32 i=0;i<begin_list->GetCount();i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(begin_list->Get(i)); SVGAnimationInstanceList tmp_list; RETURN_IF_MEMORY_ERROR(time_value->GetInstanceTimes(tmp_list, FALSE)); for (unsigned i=0;i<tmp_list.GetCount();i++) RETURN_IF_ERROR(AddBeginInstance(tmp_list[i], restart_type)); } } if (SVGVector *end_list = timing_arguments.GetEndList()) { for (UINT32 i=0;i<end_list->GetCount();i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(end_list->Get(i)); RETURN_IF_MEMORY_ERROR(time_value->GetInstanceTimes(end_instance_list, TRUE)); } } packed.instance_lists_dirty = 0; return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::AddBeginInstance(SVG_ANIMATION_TIME instance, SVGRestartType restart_type) { BOOL allow_add = TRUE; if (restart_type == SVGRESTART_WHENNOTACTIVE) { if (current_interval != NULL) { if (current_interval->IsInside(instance)) { allow_add = FALSE; } } } else if (restart_type == SVGRESTART_NEVER && packed.one_interval_started) { allow_add = FALSE; } if (allow_add) { return begin_instance_list.Add(instance); } else { return OpStatus::OK; } } void SVGAnimationSchedule::PushInterval(SVGAnimationInterval* animation_interval) { OP_ASSERT(animation_interval != NULL); if (current_interval != NULL) { OP_DELETE(previous_interval); previous_interval = current_interval; } packed.has_new_interval = 1; current_interval = animation_interval; } SVG_ANIMATION_TIME SVGAnimationSchedule::CalculateActiveDuration(SVGTimingArguments &timing_arguments, SVG_ANIMATION_TIME &active_duration, SVG_ANIMATION_TIME &repeating_duration, SVG_ANIMATION_TIME current_begin_time) { active_duration = SVGAnimationTime::Indefinite(); SVG_ANIMATION_TIME simple_duration = timing_arguments.simple_duration; SVG_ANIMATION_TIME repeat_duration = timing_arguments.repeat_duration; SVGRepeatCount repeat_count = timing_arguments.repeat_count; if (repeat_count.IsIndefinite() || SVGAnimationTime::IsIndefinite(repeat_duration)) { /* do nothing */ } else if (SVGAnimationTime::IsNumeric(simple_duration)) { /* We have a definite simple duration */ if (SVGAnimationTime::IsUnresolved(repeat_duration) && repeat_count.IsUnspecified()) { active_duration = simple_duration; } else if (repeat_count.IsValue() && SVGAnimationTime::IsNumeric(repeat_duration)) { SVG_ANIMATION_TIME tmp = (SVG_ANIMATION_TIME)(simple_duration * repeat_count.value); active_duration = MIN(tmp, repeat_duration); } else if (SVGAnimationTime::IsNumeric(repeat_duration)) { active_duration = repeat_duration; } else if (repeat_count.IsValue()) { active_duration = (SVG_ANIMATION_TIME)(simple_duration * repeat_count.value); } } else if (SVGAnimationTime::IsNumeric(repeat_duration)) active_duration = repeat_duration; repeating_duration = active_duration; /* active_duration here is very much like the IAD in http://www.w3.org/TR/2005/REC-SMIL2-20051213/smil-timing.html#q82 */ /* By looking at end instances we acquire PAD */ /* This part of the function calculates the end time of the active duration beginning in 'current_begin_time' and with length 'active_duration'. */ SVG_ANIMATION_TIME current_end_time = end_instance_list.FirstPast(current_begin_time); if (SVGAnimationTime::IsNumeric(current_end_time)) { SVG_ANIMATION_TIME duration = current_end_time - current_begin_time; active_duration = MIN(active_duration, duration); } /* NOTE: If there is an end-list, and the end list has no time values that have pending conditions, we must not allow the interval. Unallowed intervals are signaled with an unresolved end value. */ if (timing_arguments.GetEndList() && SVGAnimationTime::IsUnresolved(current_end_time) && !HasEndPendingConditions(timing_arguments.GetEndList()) && end_instance_list.GetCount() > 0) { active_duration = SVGAnimationTime::Unresolved(); } if (!SVGAnimationTime::IsUnresolved(active_duration)) { /* Finally, for valid active_durations, compute AD by trimming with max and min values. 'max' limits the repeating duration, 'min' does not. */ if (active_duration > timing_arguments.active_duration_max) { OP_ASSERT(repeating_duration >= active_duration); repeating_duration = active_duration = timing_arguments.active_duration_max; } else if (active_duration < timing_arguments.active_duration_min) active_duration = timing_arguments.active_duration_min; } if (SVGAnimationTime::IsNumeric(active_duration)) return current_begin_time + active_duration; else return active_duration; } SVGAnimationInterval * SVGAnimationSchedule::GetActiveInterval(SVG_ANIMATION_TIME document_time) const { if (current_interval != NULL && (!previous_interval || current_interval->Begin() <= document_time)) return current_interval; else return previous_interval; } SVG_ANIMATION_TIME SVGAnimationSchedule::GetNextBeginTime(SVG_ANIMATION_TIME document_time, SVGAnimationArguments &animation_arguments) { SVGAnimationInterval *fill_freeze_interval = animation_arguments.fill_mode == SVGANIMATEFILL_FREEZE ? previous_interval : NULL; if (fill_freeze_interval) { // If we have both have an interval for "freezing" animations // and one upcoming, select the begin time depending on the // current document time. if (current_interval && current_interval->Begin() <= document_time) return current_interval->Begin(); else return fill_freeze_interval->Begin(); } else if (current_interval) return current_interval->Begin(); else return SVGAnimationTime::Indefinite(); } SVGAnimationInterval * SVGAnimationSchedule::GetIntervalBefore(SVG_ANIMATION_TIME animation_time) { SVGAnimationInterval *intervals[2] = { current_interval, previous_interval }; for (int i = 0;i < 2;i++) if (intervals[i] != NULL && intervals[i]->End() >= animation_time) return intervals[i]; return NULL; } OP_STATUS SVGAnimationSchedule::DispatchEvents(SVGAnimationWorkplace *animation_workplace, SVG_ANIMATION_TIME document_time, SVGTimingInterface* timing_if, SVGTimingArguments &timing_arguments, SVG_ANIMATION_TIME elapsed_time, BOOL send_events, BOOL at_prezero) { SVGAnimationInterval *active_interval = GetActiveInterval(document_time); if (!active_interval) return OpStatus::OK; HTML_Element *timed_element = timing_if->GetElement(); SVG_ANIMATION_TIME previous_document_time = document_time - elapsed_time; SVGAnimationInterval *possibly_ended_interval = GetIntervalBefore(document_time); if (possibly_ended_interval && possibly_ended_interval->End() > previous_document_time && possibly_ended_interval->End() <= document_time) { if (send_events) { RETURN_IF_ERROR(animation_workplace->SendEvent(ENDEVENT, timed_element)); RETURN_IF_ERROR(DoTimedElementCallback(TIMED_ELEMENT_END, timing_if, timing_arguments)); } } if ((active_interval->Begin() <= document_time && active_interval->Begin() > previous_document_time) || (at_prezero && active_interval->Begin() == 0)) // special-case for time equals zero { if (send_events) { RETURN_IF_ERROR(animation_workplace->SendEvent(BEGINEVENT, timed_element)); RETURN_IF_ERROR(DoTimedElementCallback(TIMED_ELEMENT_BEGIN, timing_if, timing_arguments)); } packed.one_interval_started = 1; } SVG_ANIMATION_TIME simple_duration = active_interval->SimpleDuration(); if (SVGAnimationTime::IsNumeric(simple_duration)) { // repeat SVG_ANIMATION_TIME delta = simple_duration; SVG_ANIMATION_TIME B = active_interval->Begin(); SVG_ANIMATION_TIME E = active_interval->End() - 1; SVG_ANIMATION_TIME a = MIN(E, MAX(B, previous_document_time + 1)); SVG_ANIMATION_TIME b = MAX(B, MIN(E, document_time)); SVG_ANIMATION_TIME alpha = a - B; SVG_ANIMATION_TIME x = delta - (alpha % delta); for (SVG_ANIMATION_TIME q = (a + x); q <= b; q+=delta) { unsigned repetition = (unsigned)((q - B) / delta); for (unsigned i=0;i<repeat_time_objects.GetCount();i++) { SVGTimeObject *repeat_time_value = repeat_time_objects.Get(i); if (repetition == repeat_time_value->GetRepetition()) { repeat_time_value->AddInstanceTime(q + repeat_time_value->GetOffset()); if (SVGTimingInterface *notifier = repeat_time_value->GetNotifier()) { notifier->AnimationSchedule().MarkInstanceListsAsDirty(); animation_workplace->MarkIntervalsDirty(); } } } if (send_events) { RETURN_IF_ERROR(animation_workplace->SendEvent(REPEATEVENT, repetition, timed_element)); RETURN_IF_ERROR(DoTimedElementCallback(TIMED_ELEMENT_REPEAT, timing_if, timing_arguments)); } } } return OpStatus::OK; } SVG_ANIMATION_TIME SVGAnimationSchedule::NextIntervalTime(const SVGTimingArguments &timing_arguments, SVG_ANIMATION_TIME document_time, BOOL at_prezero) { SVG_ANIMATION_TIME next_interval_change = SVGAnimationTime::Indefinite(); OP_ASSERT(!packed.instance_lists_dirty); if (current_interval != NULL) { if (current_interval->Begin() > document_time) { next_interval_change = current_interval->Begin(); } else if (current_interval->End() > document_time) { if (SVGAnimationTime::IsNumeric(current_interval->SimpleDuration())) { SVG_ANIMATION_TIME alpha = document_time - current_interval->Begin(); OP_ASSERT(alpha >= 0); SVG_ANIMATION_TIME delta = current_interval->SimpleDuration(); SVG_ANIMATION_TIME x = delta - (alpha % delta); OP_ASSERT(x > 0); next_interval_change = MIN(x + document_time, current_interval->End()); } else { next_interval_change = current_interval->End(); } } } next_interval_change = MIN(next_interval_change, begin_instance_list.FirstPast(document_time)); return next_interval_change; } SVG_ANIMATION_TIME SVGAnimationSchedule::NextAnimationTime(const SVGTimingArguments &timing_arguments, SVG_ANIMATION_TIME document_time) { SVG_ANIMATION_TIME next_animation_time = SVGAnimationTime::Indefinite(); if (current_interval != NULL) { if (current_interval->Begin() > document_time) { next_animation_time = current_interval->Begin(); } else if (current_interval->End() > document_time) { if (SVGAnimationTime::IsNumeric(current_interval->SimpleDuration())) { next_animation_time = document_time; } else if (SVGAnimationTime::IsNumeric(current_interval->End())) { next_animation_time = MIN(next_animation_time, current_interval->End()); } } } next_animation_time = MIN(next_animation_time, begin_instance_list.FirstPast(document_time)); return next_animation_time; } BOOL SVGAnimationSchedule::IsActive(SVG_ANIMATION_TIME document_time) { SVGAnimationInterval *active_interval = GetActiveInterval(document_time); return (active_interval != NULL && active_interval->Begin() <= document_time); } BOOL SVGAnimationSchedule::IsActive(SVG_ANIMATION_TIME document_time, const SVGAnimationArguments& animation_arguments) { SVGAnimationInterval *active_interval = GetActiveInterval(document_time); return active_interval && active_interval->IsActive(document_time, animation_arguments.fill_mode); } BOOL SVGAnimationSchedule::CheckCurrentInterval(SVGAnimationWorkplace* animation_workplace, SVGTimingArguments& timing_arguments) { SVG_ANIMATION_TIME document_time = animation_workplace->DocumentTime(); SVGRestartType restart_type = timing_arguments.restart_type; if (packed.one_interval_started && restart_type == SVGRESTART_NEVER) return FALSE; if (current_interval == NULL) return TRUE; if (current_interval->End() <= document_time) return TRUE; /* "If restart is set to "always", then the current interval will * end early if there is an instance time in the begin list that * is before (i.e. earlier than) the defined end for the current * interval. Ending in this manner will also send a changed time * notice to all time dependents for the current interval * end." */ if (restart_type == SVGRESTART_ALWAYS) { SVG_ANIMATION_TIME next_begin = begin_instance_list.FirstPast(current_interval->Begin()); if (next_begin <= document_time) { current_interval->SetEnd(next_begin); OpStatus::Ignore(NotifyDependingElements(animation_workplace, current_interval)); return TRUE; } } return FALSE; } OP_STATUS SVGAnimationSchedule::SetupTimeDependency(SVGAnimationWorkplace* animation_workplace, SVGTimeObject* time_value, HTML_Element *timed_element, HTML_Element *default_target_element) { OP_ASSERT(time_value != NULL); SVGDocumentContext *doc_ctx = animation_workplace->GetSVGDocumentContext(); const uni_char* rel = time_value->GetElementId(); HTML_Element *target_element = NULL; if (rel != NULL) { target_element = SVGUtils::FindElementById(doc_ctx->GetLogicalDocument(), rel); // In the candidate recommendation to SVG 1.0 there were a possible value "prev.end" that // referred to the previous animation element in document order. That was not included // in SVG 1.0 but is supported by Adobe and used by some SVG:s still. We warn but support // it for now. Might be removed in the future. if (!target_element && uni_str_eq(rel, "prev")) { SVG_NEW_ERROR(timed_element); SVG_REPORT_ERROR((UNI_L("The value 'prev' is obsolete as time dependency and was removed before the SVG 1.0 specification. Use an id instead."))); target_element = timed_element->Pred(); while (target_element && !SVGUtils::IsTimedElement(target_element)) { target_element = target_element->Pred(); } } } else { target_element = default_target_element; } if (target_element != NULL) { OP_STATUS res = time_value->RegisterTimeValue(doc_ctx, target_element); // timing_interface time_value->SetNotifier(AttrValueStore::GetSVGTimingInterface(timed_element)); return res; } else { if (rel != NULL && animation_workplace->HasTimelineStarted()) { SVG_NEW_ERROR(timed_element); SVG_REPORT_ERROR((UNI_L("Time dependency to unknown element: '%s'"), rel)); } return OpSVGStatus::INVALID_ANIMATION; } } OP_STATUS SVGAnimationSchedule::AddSyncbase(SVGTimeObject* sbase) { OP_ASSERT (sbase != NULL); INT32 idx = syncbase_time_objects.Find(sbase); if (idx == -1) { RETURN_IF_MEMORY_ERROR(syncbase_time_objects.Add(sbase)); SVGObject::IncRef(sbase); } return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::AddRepeat(SVGTimeObject* rtv) { OP_ASSERT (rtv != NULL); INT32 idx = repeat_time_objects.Find(rtv); if (idx == -1) { RETURN_IF_MEMORY_ERROR(repeat_time_objects.Add(rtv)); SVGObject::IncRef(rtv); } return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::NotifyDependingElements(SVGAnimationWorkplace* animation_workplace, SVGAnimationInterval* interval) { for (UINT32 i=0;i<syncbase_time_objects.GetCount();i++) { SVGTimeObject *sbase = syncbase_time_objects.Get(i); OP_ASSERT(sbase != NULL); if (interval != NULL) { SVG_ANIMATION_TIME now; if (sbase->GetSyncbaseEvent() == SVGSYNCBASE_BEGIN) { now = interval->Begin() + sbase->GetOffset(); } else if (sbase->GetSyncbaseEvent() == SVGSYNCBASE_END && SVGAnimationTime::IsNumeric(interval->End())) { now = interval->End() + sbase->GetOffset(); } else { // Unknown syncbase, ignore. continue; } RETURN_IF_ERROR(sbase->AddInstanceTime(now)); } if (SVGTimingInterface *notifier = sbase->GetNotifier()) { packed.is_computing_dependant = 1; if (SVGAnimationListItem* dependant = animation_workplace->LookupItem(notifier->GetElement())) { notifier->AnimationSchedule().MarkInstanceListsAsDirty(); dependant->UpdateIntervals(animation_workplace); } packed.is_computing_dependant = 0; } } return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::BeginElement(SVGAnimationWorkplace *animation_workplace, SVG_ANIMATION_TIME offset) { SVG_ANIMATION_TIME time_to_add = animation_workplace->VirtualDocumentTime() + offset; RETURN_IF_ERROR(extra_begin_instance_list.Add(time_to_add)); packed.instance_lists_dirty = 1; return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::EndElement(SVGAnimationWorkplace *animation_workplace, SVG_ANIMATION_TIME offset) { SVG_ANIMATION_TIME time_to_add = animation_workplace->VirtualDocumentTime() + offset; RETURN_IF_ERROR(extra_end_instance_list.Add(time_to_add)); packed.instance_lists_dirty = 1; return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::RegisterTimeValues(SVGAnimationWorkplace* animation_workplace, SVGTimingInterface* timing_if, SVGTimingArguments& timing_arguments, HTML_Element* default_target_element) { if (SVGVector *begin_list = timing_arguments.GetBeginList()) { for (UINT32 i=0;i<begin_list->GetCount();i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(begin_list->Get(i)); OP_STATUS status = SetupTimeDependency(animation_workplace, time_value, timing_if->GetElement(), default_target_element); RETURN_IF_MEMORY_ERROR(status); if (OpStatus::IsError(status)) { packed.in_syncbase_error = 1; animation_workplace->AddElementInTimeValueError(timing_if->GetElement()); } } } if (SVGVector *end_list = timing_arguments.GetEndList()) { for (UINT32 i=0;i<end_list->GetCount();i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(end_list->Get(i)); OP_STATUS status = SetupTimeDependency(animation_workplace, time_value, timing_if->GetElement(), default_target_element); RETURN_IF_MEMORY_ERROR(status); if (OpStatus::IsError(status)) { packed.in_syncbase_error = 1; animation_workplace->AddElementInTimeValueError(timing_if->GetElement()); } } } return OpStatus::OK; } void SVGAnimationSchedule::UnregisterTimeValues(SVGAnimationWorkplace *animation_workplace, SVGTimingInterface* timing_if, SVGTimingArguments &timing_arguments, HTML_Element* target_element) { SVGDocumentContext* doc_ctx = animation_workplace->GetSVGDocumentContext(); OP_ASSERT(doc_ctx); if (SVGVector *begin_list = timing_arguments.GetBeginList()) for (UINT32 i=0;i<begin_list->GetCount();i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(begin_list->Get(i)); time_value->UnregisterTimeValue(doc_ctx, target_element); } if (SVGVector *end_list = timing_arguments.GetEndList()) for (UINT32 i=0;i<end_list->GetCount();i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(end_list->Get(i)); time_value->UnregisterTimeValue(doc_ctx, target_element); } } OP_STATUS SVGAnimationSchedule::Prepare(SVGAnimationWorkplace *animation_workplace, SVGTimingInterface* timing_if, SVGTimingArguments& timing_arguments, HTML_Element* default_target_element) { if (!packed.prepared_called) { packed.prepared_called = 1; RETURN_IF_ERROR(DoTimedElementCallback(TIMED_ELEMENT_PREPARE, timing_if, timing_arguments)); RETURN_IF_ERROR(RegisterTimeValues(animation_workplace, timing_if, timing_arguments, default_target_element)); } return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::Destroy(SVGAnimationWorkplace* animation_workplace, SVGTimingInterface* timing_if, SVGTimingArguments &timing_arguments, HTML_Element* target_element) { UnregisterTimeValues(animation_workplace, timing_if, timing_arguments, target_element); packed.prepared_called = 0; packed.instance_lists_dirty = 1; return OpStatus::OK; } OP_STATUS SVGAnimationSchedule::DoTimedElementCallback(TimedElementCallbackType callback_type, SVGTimingInterface* timing_if, SVGTimingArguments &timing_arguments) { OP_ASSERT(SVGUtils::IsTimedElement(timing_if->GetElement()) || timing_if->GetElement()->IsMatchingType(Markup::SVGE_DISCARD, NS_SVG)); OP_ASSERT(timing_if); switch(callback_type) { case TIMED_ELEMENT_BEGIN: return timing_if->OnIntervalBegin(); case TIMED_ELEMENT_END: return timing_if->OnIntervalEnd(); case TIMED_ELEMENT_PREPARE: return timing_if->OnPrepare(); case TIMED_ELEMENT_REPEAT: return timing_if->OnIntervalRepeat(); default: OP_ASSERT(!"Not reached"); return OpStatus::ERR; } } /* static */ BOOL SVGAnimationSchedule::HasEndPendingConditions(SVGVector *end_list) { OP_ASSERT(end_list != NULL); OP_ASSERT(end_list->VectorType() == SVGOBJECT_TIME); for (unsigned i=0; i<end_list->GetCount(); i++) { SVGTimeObject* time_value = static_cast<SVGTimeObject *>(end_list->Get(i)); if (time_value->TimeType() == SVGTIME_EVENT || time_value->TimeType() == SVGTIME_ACCESSKEY || time_value->TimeType() == SVGTIME_REPEAT) { return TRUE; } } return FALSE; } BOOL SVGAnimationSchedule::HasDependant(SVGAnimationSchedule *schedule) { if (schedule == this) return TRUE; if (packed.is_computing_dependant) return FALSE; packed.is_computing_dependant = 1; BOOL ret = FALSE; for (UINT32 i=0; i<syncbase_time_objects.GetCount(); i++) { SVGTimeObject *sbase = syncbase_time_objects.Get(i); OP_ASSERT(sbase != NULL); if (SVGTimingInterface *notifier = sbase->GetNotifier()) if (notifier->AnimationSchedule().HasDependant(schedule)) { ret = TRUE; break; } } packed.is_computing_dependant = 0; return ret; } OP_STATUS SVGAnimationSchedule::HandleAccessKey(uni_char access_key, SVG_ANIMATION_TIME document_time, HTML_Element *focused_element) { for (int i = 0; i < 2; i++) { Markup::AttrType attr = i ? Markup::SVGA_END : Markup::SVGA_BEGIN; SVGVector* list; AttrValueStore::GetVector(focused_element, attr, list); if (!list) continue; UINT32 count = list->GetCount(); for (UINT32 i=0;i<count;i++) { SVGTimeObject* time_val = static_cast<SVGTimeObject*>(list->Get(i)); if (time_val->TimeType() == SVGTIME_ACCESSKEY) { if (access_key == uni_toupper(time_val->GetAccessKey())) { // Process it SVG_ANIMATION_TIME clk = document_time + time_val->GetOffset(); RETURN_IF_ERROR(time_val->AddInstanceTime(clk)); } } } packed.instance_lists_dirty = 1; } return OpStatus::OK; } #endif // SVG_SUPPORT
#include<bits/stdc++.h> using namespace std; struct node{ int to,w; }; vector<node> e[300000]; long long dis[300000],ans=0; int n; bool f=0; inline void ins(int u,int v,int w){ e[u].push_back((node){v,w}); } void readit(){ int k; scanf("%d%d",&n,&k); for (int i=1;i<=k;i++){ int x,a,b; scanf("%d%d%d",&x,&a,&b); switch (x){ case 1:ins(a,b,0);ins(b,a,0);break; case 2:if (a==b) f=1;ins(a,b,1);break; case 3:ins(b,a,0);break; case 4:if (a==b) f=1;ins(b,a,1);break; case 5:ins(a,b,0);break; } } } void writeit(){ if (f) printf("-1\n"); else printf("%lld\n",ans); } bool spfa(){ queue<int> q; int time[300000]; bool inq[300000]; dis[0]=0; inq[0]=1; time[0]=1; q.push(0); while (!q.empty()){ int u=q.front(); q.pop(); inq[u]=0; for (int i=0;i<e[u].size();i++){ node &eui=e[u][i]; int v=eui.to; if (dis[u]+eui.w>dis[v]){ dis[v]=dis[u]+eui.w; if (!inq[v]){ q.push(v); inq[v]=1; if (++time[v]>=n) return 1; } } } } return 0; } void count(){ for (int i=1;i<=n;i++) ans+=dis[i]; } void work(){ for (int i=1;i<=n;i++) ins(0,i,1); f=spfa(); if (!f) count(); } int main(){ readit(); if (!f) work(); writeit(); return 0; }
#ifndef AFX_SCENE_H_ #define AFX_SCENE_H_ #include <stdio.h> #include <vector> #include <string> using namespace std; class Model { class Vec3 { public: double ptr[3]; void set(double *v) { for (size_t i = 0; i<3; i++) ptr[i] = v[i]; } inline double& operator[](size_t index) { return ptr[index]; } }; public: string objFile_; double angle_; Vec3 scale_; Vec3 rotate_; Vec3 transfer_; }; class Scene { public: size_t mTotal_; vector<Model> mList_; Model getModel(const string& objFile); Scene(); Scene(const char* sceneFile); ~Scene(); void loadScene(const char* sceneFile); }; #endif
#include "DetectMemoryLeak.h" #include "CollisionManager.h" #include "PlayerInfo\PlayerInfo.h" #include "LevelStuff\QuadTree.h" #include "LevelStuff\Level.h" bool CollisionManager::CheckPointToSphereCollision(Vector3 point, EntityBase * ThatEntity) { if (!ThatEntity->HasCollider()) { std::cout << "Entity does not have Collider" << std::endl; return false; } GenericEntity* thatSphere = dynamic_cast<GenericEntity*>(ThatEntity); if (!thatSphere->HasSphere()) { std::cout << "Entity does not have Bounding Sphere" << std::endl; return false; } if (DistanceSquaredBetween(point, thatSphere->GetPosition() < thatSphere->GetRadius() * thatSphere->GetRadius())) return true; return false; } bool CollisionManager::CheckSphereCollision(EntityBase * ThisEntity, EntityBase * ThatEntity) { if (!ThisEntity->HasCollider() || !ThatEntity->HasCollider()) { std::cout << "1 or more Entities does not have Collider" << std::endl; return false; } GenericEntity* thisSphere = dynamic_cast<GenericEntity*>(ThisEntity); GenericEntity* thatSphere = dynamic_cast<GenericEntity*>(ThatEntity); if (!thatSphere->HasSphere() || !thisSphere->HasSphere()) { std::cout << "1 or more Entities does not have Bounding Sphere" << std::endl; return false; } float totalRadius = thatSphere->GetRadius() + thisSphere->GetRadius(); if (DistanceSquaredBetween(thatSphere->GetPosition(), thisSphere->GetPosition()) < totalRadius * totalRadius) { return true; } return false; } bool CollisionManager::CheckAABBCollision(EntityBase * ThisEntity, EntityBase * ThatEntity) { if (!ThatEntity->HasCollider() || !ThisEntity->HasCollider()) { //std::cout << "1 or more Entities does not have Collider" << std::endl; return false; } GenericEntity* thisHitbox = dynamic_cast<GenericEntity*>(ThisEntity); GenericEntity* thatHitbox = dynamic_cast<GenericEntity*>(ThatEntity); if (!thisHitbox->HasAABB() || !thatHitbox->HasAABB()){ //std::cout << "1 or more Entities does not have AABB" << std::endl; return false; } return (thisHitbox->GetMinAABB().x <= thatHitbox->GetMaxAABB().x && thisHitbox->GetMaxAABB().x >= thatHitbox->GetMinAABB().x) && (thisHitbox->GetMinAABB().y <= thatHitbox->GetMaxAABB().y && thisHitbox->GetMaxAABB().y >= thatHitbox->GetMinAABB().y); } bool CollisionManager::CheckPointToAABBCollision(Vector3 point, EntityBase * ThatEntity) { if (!ThatEntity->HasCollider()) { std::cout << "Entity does not have Collider" << std::endl; return false; } GenericEntity* thatHitbox = dynamic_cast<GenericEntity*>(ThatEntity); if (!thatHitbox->HasAABB()) { std::cout << "Entity does not have AABB" << std::endl; return false; } return (point.x <= thatHitbox->GetMaxAABB().x && point.x >= thatHitbox->GetMinAABB().x) && (point.y <= thatHitbox->GetMaxAABB().y && point.y >= thatHitbox->GetMinAABB().y); } bool CollisionManager::UI_CheckAABBCollision(Vector3 point, UIElement * ThatElement) { if (!ThatElement->HasCollider()) { std::cout << "Entity does not have Collider" << std::endl; return false; } UIElement* thatHitbox = dynamic_cast<UIElement*>(ThatElement); if (!thatHitbox->HasAABB()) { std::cout << "Entity does not have AABB" << std::endl; return false; } return (point.x <= thatHitbox->GetMaxAABB().x && point.x >= thatHitbox->GetMinAABB().x) && (point.y <= thatHitbox->GetMaxAABB().y && point.y >= thatHitbox->GetMinAABB().y); // Would check Z but 2d game so w/e (removed for all) } void CollisionManager::Update(std::list<EntityBase*> collisionList, int totalFrontEntities) { std::list<EntityBase*>::iterator it, end; int index = 0; end = collisionList.end(); QuadTree quadTree(0, 0, Level::GetInstance()->getMapWidth(), Level::GetInstance()->getMapHeight(), 0, 2); //QuadTree quadTree(0, 800, 600, 0, 3); vector<EntityBase*> getNearestObj; quadTree.clear(); for (it = collisionList.begin(); it != end; ++it) quadTree.addObject(*it); for (it = collisionList.begin(); it != end; ++it) { if (!(*it)->IsActive()) continue; if (index > totalFrontEntities) break; getNearestObj = quadTree.getObjectsAt((*it)->GetPosition().x, (*it)->GetPosition().y); for (std::vector<EntityBase*>::iterator it2 = getNearestObj.begin(); it2 != getNearestObj.end(); ++it2) { if (!(*it2)->IsActive()) continue; // do your checks here if (CheckAABBCollision(*it, *it2)) { GenericEntity* thisEntity = dynamic_cast<GenericEntity*>(*it); GenericEntity* thatEntity = dynamic_cast<GenericEntity*>(*it2); //create collison response code to settle what to do thisEntity->CollisionResponse(thatEntity); } } ++index; } getNearestObj.clear(); getNearestObj = quadTree.getObjectsAt(Player::GetInstance()->GetPos().x, Player::GetInstance()->GetPos().y); for (std::vector<EntityBase*>::iterator it3 = getNearestObj.begin(); it3 != getNearestObj.end(); ++it3) { if (CheckAABBCollision(Player::GetInstance(), *it3)) { GenericEntity* thatEntity = dynamic_cast<GenericEntity*>(*it3); Player::GetInstance()->CollisionResponse(thatEntity); } } getNearestObj.clear(); } CollisionManager::CollisionManager() { } CollisionManager::~CollisionManager() { }
#ifndef __Core__GUserCtlrManager__ #define __Core__GUserCtlrManager__ #include "GActorCtlrManager.h" class GnIButton; class GnInterfaceGroup; class GInterfaceLayer; class GUserCtlrManager : public GActorCtlrManager { static const gtuint NUM_BUTTON = 4; private: GInterfaceLayer* mpInterfaceLayer; GActorController* mpUserCtlr; GnInterfaceGroup* mpButtonGroup; GnMemberSlot2<GUserCtlrManager, GnInterface*, GnIInputEvent*> mMoveInputEvent; GnMemberSlot2<GUserCtlrManager, GnInterface*, GnIInputEvent*> mSkillInputEvent; public: static GUserCtlrManager* CreateActorCtlrManager(GLayer* pActorLayer, GLayer* pInterfaceLayer); public: virtual ~GUserCtlrManager(); public: void Update(float fDeltaTime); void Init(); gint32 GetUserCurrentHP(); protected: GUserCtlrManager(GLayer* pActorLayer, GLayer* pInterfaceLayer); void UpdateBackgroundLayer(); protected: void Move(GnInterface* pInterface, GnIInputEvent* pEvent); void SkillInput(GnInterface* pInterface, GnIInputEvent* pEvent); }; #endif
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; int A[33]; bool flag[33]; int B[33]; int main(){ int T; scanf("%d",&T); while(T--){ int n; scanf("%d",&n); char str[5]; for(int i=0;i<n;i++){ scanf("%s",str); if(str[0]>=2&&str[0]<='9')A[i]=(str[0]-'0')*10; if(str[0]=='T')A[i]=100; if(str[0]=='J')A[i]=110; if(str[0]=='Q')A[i]=120; if(str[0]=='K')A[i]=130; if(str[0]=='A')A[i]=140; if(str[1]=='H')A[i]+=4; if(str[1]=='S')A[i]+=3; if(str[1]=='D')A[i]+=2; if(str[1]=='C')A[i]+=1; } for(int i=0;i<n;i++){ scanf("%s",str); if(str[0]>=2&&str[0]<='9')B[i]=(str[0]-'0')*10; if(str[0]=='T')B[i]=100; if(str[0]=='J')B[i]=110; if(str[0]=='Q')B[i]=120; if(str[0]=='K')B[i]=130; if(str[0]=='A')B[i]=140; if(str[1]=='H')B[i]+=4; if(str[1]=='S')B[i]+=3; if(str[1]=='D')B[i]+=2; if(str[1]=='C')B[i]+=1; } sort(B,B+n); memset(flag,0,sizeof(flag)); for(int i=0;i<n;i++){ int maxx=0; int pos=-1; for(int j=0;j<n;j++){ if(flag[j])continue; if(B[i]>A[j]&&A[j]>maxx){ maxx=A[j]; pos=j; } } if(pos!=-1)flag[pos]=true; } int cnt=0; for(int i=0;i<n;i++)if(flag[i])cnt++; printf("%d\n",cnt); } return 0; }
// DataStructure.h : Include file for standard system include files, // or project specific include files. #pragma once #include <iostream> // Class #include "Stack.cpp"
#ifndef _CONVERT2GRAY_HPP_ #define _CONVERT2GRAY_HPP_ #include<ros/ros.h> #include<iostream> #include<nav_msgs/Odometry.h> #include<sensor_msgs/Imu.h> #include<geometry_msgs/Pose.h> #include<geometry_msgs/PoseStamped.h> #include <nav_msgs/OccupancyGrid.h> #include <nav_msgs/GridCells.h> #include<message_filters/subscriber.h> #include<message_filters/sync_policies/approximate_time.h> #include <tf/transform_datatypes.h> #include <tf/transform_broadcaster.h> #include <opencv2/opencv.hpp> static const std::string OPENCV_WINDOW = "Image window"; static const std::string OPENCV_WINDOWS = "Gray window"; #define cell_filter 30 using namespace std; class Gray{ private: ros::Publisher map_pub; cv::Mat input_image; cv::Mat gray_image; cv::Mat edge_image; string input_path; double min,max; float R; nav_msgs::OccupancyGrid grid_map; public: Gray(ros::NodeHandle n,ros::NodeHandle priv_nh); void process(); void setparam(nav_msgs::OccupancyGrid *map,cv::Mat image); void create_obstacle_map(cv::Mat edge_png, nav_msgs::OccupancyGrid *map_); }; #endif
#ifndef _BetCallProc_H_ #define _BetCallProc_H_ #include "BaseProcess.h" class Table; class Player; class BetCallProc :public BaseProcess { public: BetCallProc(); virtual ~BetCallProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ; private: int sendCallInfoToPlayers(Player* player, Table* table, Player* betcallplayer, int64_t betmoney,Player* nextplayer,short seq); int PushCardToUser(Table* table); int sendCardInfo(Table* table,Player* player); }; #endif
#include <iberbar/RHI/OpenGL/VertexDeclaration.h> #include <iberbar/RHI/OpenGL/Device.h> #include <iberbar/RHI/OpenGL/ShaderProgram.h> #include <iberbar/RHI/OpenGL/Types.h> iberbar::RHI::OpenGL::CVertexDeclaration::CVertexDeclaration( CDevice* pDevice, const UVertexElement* pVertexElements, uint32 nVertexElementsCount, uint32 nStride ) : IVertexDeclaration( pVertexElements, nVertexElementsCount, nStride ) , m_pDevice( pDevice ) , m_pGLVertexAttributes( nullptr ) , m_nGLVertexAttributesCount( 0 ) { m_pDevice->AddRef(); } iberbar::RHI::OpenGL::CVertexDeclaration::~CVertexDeclaration() { SAFE_DELETE_ARRAY( m_pGLVertexAttributes ); UNKNOWN_SAFE_RELEASE_NULL( m_pDevice ); } void iberbar::RHI::OpenGL::CVertexDeclaration::Initial( CShaderProgram* pShader ) { m_nGLVertexAttributesCount = m_nVertexElementsCount; m_pGLVertexAttributes = new UGLVertexAttribute[ m_nVertexElementsCount ]; memset( m_pGLVertexAttributes, 0, sizeof( UGLVertexAttribute ) * m_nGLVertexAttributesCount ); std::string strAttrName; const UVertexElement* pRHIVertexElement = nullptr; for ( uint32 i = 0; i < m_nVertexElementsCount; i++ ) { pRHIVertexElement = &m_pVertexElements[ i ]; ConvertVertexAttrName( strAttrName, pRHIVertexElement->nSemantic, pRHIVertexElement->nSemanticIndex ); m_pGLVertexAttributes[ i ].nLocation = pShader->GetAttributeLocation( strAttrName.c_str() ); m_pGLVertexAttributes[ i ].nOffset = pRHIVertexElement->nOffset; ConvertVertexFormat( pRHIVertexElement->nFormat, &m_pGLVertexAttributes[ i ].nSize, &m_pGLVertexAttributes[ i ].nType ); if ( pRHIVertexElement->nFormat == UVertexFormat::COLOR ) m_pGLVertexAttributes[ i ].bNormallized = true; } }
/* * Lanq(Lan Quick) * Solodov A. N. (hotSAN) * 2016 * LqThreadBase - Thread implementation. */ #include "LqOs.h" #include "LqThreadBase.hpp" #include "LqDfltRef.hpp" #include "LqStr.h" #include "LqSbuf.h" #include "LqErr.h" #if defined(LQPLATFORM_WINDOWS) #include <Windows.h> #include <process.h> static int __GetRealPrior(LqThreadPriorEnm p) { switch(p) { case LQTHREAD_PRIOR_IDLE: return THREAD_PRIORITY_IDLE; case LQTHREAD_PRIOR_LOWER: return THREAD_PRIORITY_LOWEST; case LQTHREAD_PRIOR_LOW: return THREAD_PRIORITY_BELOW_NORMAL; case LQTHREAD_PRIOR_NORMAL: return THREAD_PRIORITY_NORMAL; case LQTHREAD_PRIOR_HIGH: return THREAD_PRIORITY_ABOVE_NORMAL; case LQTHREAD_PRIOR_HIGHER: return THREAD_PRIORITY_HIGHEST; case LQTHREAD_PRIOR_REALTIME: return THREAD_PRIORITY_TIME_CRITICAL; default: return THREAD_PRIORITY_NORMAL; } } static LqThreadPriorEnm __GetPrior(int Code) { switch(Code) { case THREAD_PRIORITY_IDLE: return LQTHREAD_PRIOR_IDLE; case THREAD_PRIORITY_LOWEST: return LQTHREAD_PRIOR_LOWER; case THREAD_PRIORITY_BELOW_NORMAL: return LQTHREAD_PRIOR_LOW; case THREAD_PRIORITY_NORMAL: return LQTHREAD_PRIOR_NORMAL; case THREAD_PRIORITY_ABOVE_NORMAL: return LQTHREAD_PRIOR_HIGH; case THREAD_PRIORITY_HIGHEST: return LQTHREAD_PRIOR_HIGHER; case THREAD_PRIORITY_TIME_CRITICAL: return LQTHREAD_PRIOR_REALTIME; default: return LQTHREAD_PRIOR_NONE; } } thread_local char* NameThread = nullptr; static int pthread_setname_np(DWORD dwThreadID, const char* threadName) { static const DWORD MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // _Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; #pragma warning(push) #pragma warning(disable: 6320 6322) __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except(EXCEPTION_EXECUTE_HANDLER) {} #pragma warning(pop) NameThread = LqStrDuplicate(threadName); return 0; } static int pthread_getname_np(DWORD dwThreadID, char* StrBufDest, size_t Len) { if(NameThread != nullptr) LqStrCopyMax(StrBufDest, NameThread, Len); else return -1; return 0; } #else #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <sys/time.h> #include <string.h> static int __GetRealPrior(LqThreadPriorEnm p) { switch(p) { case LQTHREAD_PRIOR_IDLE: return 45; case LQTHREAD_PRIOR_LOWER: return 51; case LQTHREAD_PRIOR_LOW: return 57; case LQTHREAD_PRIOR_NORMAL: return 63; case LQTHREAD_PRIOR_HIGH: return 69; case LQTHREAD_PRIOR_HIGHER: return 75; case LQTHREAD_PRIOR_REALTIME: return 81; default: return 63; } } static LqThreadPriorEnm __GetPrior(int Code) { switch(Code) { case 45: return LQTHREAD_PRIOR_IDLE; case 51: return LQTHREAD_PRIOR_LOWER; case 57: return LQTHREAD_PRIOR_LOW; case 63: return LQTHREAD_PRIOR_NORMAL; case 69: return LQTHREAD_PRIOR_HIGH; case 75: return LQTHREAD_PRIOR_HIGHER; case 81: return LQTHREAD_PRIOR_REALTIME; default: return LQTHREAD_PRIOR_NONE; } } #if defined(LQPLATFORM_ANDROID) thread_local char* NameThread = nullptr; #endif #endif LqThreadBase::LqThreadBase(const char* NewName): IsShouldEnd(true), Priority(LQTHREAD_PRIOR_NONE), AffinMask(0), UserData(nullptr), ThreadHandler(0), CurThreadId(-((intptr_t)1)), ExitHandler([](void*) {}), EnterHandler([](void*) {}) { IsStarted = false; if(NewName != nullptr) Name = LqStrDuplicate(NewName); else Name = nullptr; } LqThreadBase::~LqThreadBase() { ExitThreadSync(); if(Name != nullptr) free(Name); } LqThreadPriorEnm LqThreadBase::GetPriority() const { return Priority; } bool LqThreadBase::SetPriority(LqThreadPriorEnm New) { bool Res = true; StartThreadLocker.LockWrite(); if(Priority != New) { Priority = New; if(IsThreadRunning()) { #if defined(LQPLATFORM_WINDOWS) SetThreadPriority((HANDLE)NativeHandle(), __GetRealPrior(Priority)); #else sched_param schedparams; schedparams.sched_priority = __GetRealPrior(Priority); pthread_setschedparam(NativeHandle(), SCHED_OTHER, &schedparams); #endif } else { lq_errno_set(ENOENT); Res = false; } } StartThreadLocker.UnlockWrite(); return Res; } uint64_t LqThreadBase::GetAffinity() const { return AffinMask; } uintptr_t LqThreadBase::NativeHandle() const { #if defined(LQPLATFORM_WINDOWS) return ThreadHandler; #else return CurThreadId; #endif } bool LqThreadBase::SetAffinity(uint64_t Mask) { bool Res = true; StartThreadLocker.LockWrite(); if(AffinMask != Mask) { AffinMask = Mask; if(IsThreadRunning()) { #if defined(LQPLATFORM_WINDOWS) SetThreadAffinityMask((HANDLE)NativeHandle(), Mask); #elif !defined(LQPLATFORM_ANDROID) pthread_setaffinity_np(NativeHandle(), sizeof(Mask), (const cpu_set_t*)&Mask); #endif } else { lq_errno_set(ENOENT); Res = false; } } StartThreadLocker.UnlockWrite(); return Res; } void LqThreadBase::WaitEnd() const { bool IsNotOut = true; if(IsThisThread()) return; while(IsNotOut) { StartThreadLocker.LockWriteYield(); IsNotOut = IsThreadRunning(); StartThreadLocker.UnlockWrite(); } } #ifdef LQPLATFORM_WINDOWS unsigned __stdcall LqThreadBase::BeginThreadHelper(void* ProcData) #else void* LqThreadBase::BeginThreadHelper(void* ProcData) #endif { LqThreadBase* This = (LqThreadBase*)ProcData; This->IsStarted = true; This->StartThreadLocker.LockWrite(); // #if defined(LQPLATFORM_WINDOWS) pthread_setname_np(This->ThreadId(), This->Name); #elif defined(LQPLATFORM_LINUX) || defined(LQPLATFORM_ANDROID) pthread_setname_np(pthread_self(), This->Name); #elif defined(LQPLATFORM_FREEBSD) pthread_setname_np(pthread_self(), This->Name, nullptr); #elif defined(LQPLATFORM_APPLE) pthread_setname_np(This->Name); #endif if(This->Priority == LQTHREAD_PRIOR_NONE) { #if defined(LQPLATFORM_WINDOWS) This->Priority = __GetPrior(GetThreadPriority(GetCurrentThread())); #else sched_param schedparams; pthread_getschedparam(pthread_self(), LqDfltPtr(), &schedparams); This->Priority = __GetPrior(schedparams.sched_priority); #endif } else { #if defined(LQPLATFORM_WINDOWS) SetThreadPriority(GetCurrentThread(), __GetRealPrior(This->Priority)); #else sched_param schedparams; schedparams.sched_priority = __GetRealPrior(This->Priority); pthread_setschedparam(pthread_self(), SCHED_OTHER, &schedparams); #endif } if(This->AffinMask == 0) { #if defined(LQPLATFORM_WINDOWS) GROUP_AFFINITY ga = {0}; GetThreadGroupAffinity(GetCurrentThread(), &ga); This->AffinMask = ga.Mask; #elif !defined(LQPLATFORM_ANDROID) pthread_getaffinity_np(pthread_self(), sizeof(This->AffinMask), (cpu_set_t*)&This->AffinMask); #endif } else { #if defined(LQPLATFORM_WINDOWS) SetThreadAffinityMask(GetCurrentThread(), This->AffinMask); #elif !defined(LQPLATFORM_ANDROID) pthread_setaffinity_np(pthread_self(), sizeof(This->AffinMask), (const cpu_set_t*)&This->AffinMask); #endif } This->StartThreadLocker.UnlockWrite(); This->EnterHandler(This->UserData); //Call user defined handler //Enter main func This->BeginThread(); #ifdef LQPLATFORM_WINDOWS if(NameThread != nullptr) { free(NameThread); NameThread = nullptr; } #endif This->ExitHandler(This->UserData); This->StartThreadLocker.LockWrite(); #ifdef LQPLATFORM_WINDOWS CloseHandle((HANDLE)This->ThreadHandler); #endif This->CurThreadId = -((intptr_t)1); This->ThreadHandler = 0; This->StartThreadLocker.UnlockWrite(); #ifdef LQPLATFORM_WINDOWS return 0; #else return NULL; #endif } int LqThreadBase::GetName(intptr_t Id, char* DestBuf, size_t Len) { #if !defined(LQPLATFORM_ANDROID) return pthread_getname_np(Id, DestBuf, Len); #else return -1; #endif } bool LqThreadBase::StartThreadAsync() { bool Res = true; StartThreadLocker.LockWrite(); if(IsThreadRunning()) { StartThreadLocker.UnlockWrite(); lq_errno_set(EALREADY); return false; } IsShouldEnd = false; IsStarted = false; #ifdef LQPLATFORM_WINDOWS unsigned threadID; uintptr_t Handler = _beginthreadex(NULL, 0, BeginThreadHelper, this, 0, &threadID); CurThreadId = threadID; ThreadHandler = Handler; if(Handler == -1L) { switch(errno) { case EAGAIN: lq_errno_set(EAGAIN); break; case EINVAL: lq_errno_set(EINVAL); break; case EACCES: lq_errno_set(EACCES); break; } #else pthread_t threadID = 0; int Err = pthread_create(&threadID, NULL, BeginThreadHelper, this); CurThreadId = threadID; if(Err != 0) { #endif Res = false; CurThreadId = -((intptr_t)1); ThreadHandler = 0; } StartThreadLocker.UnlockWrite(); return Res; } bool LqThreadBase::StartThreadSync() { bool Res = true; StartThreadLocker.LockWrite(); if(IsThreadRunning()) { StartThreadLocker.UnlockWrite(); lq_errno_set(EALREADY); return false; } IsShouldEnd = false; IsStarted = false; #ifdef LQPLATFORM_WINDOWS unsigned threadID; uintptr_t Handler = _beginthreadex(NULL, 0, BeginThreadHelper, this, 0, &threadID); CurThreadId = threadID; ThreadHandler = Handler; if(Handler == -1L) { switch(errno) { case EAGAIN: lq_errno_set(EAGAIN); break; case EINVAL: lq_errno_set(EINVAL); break; case EACCES: lq_errno_set(EACCES); break; } #else pthread_t threadID = 0; int Err = pthread_create(&threadID, NULL, BeginThreadHelper, this); CurThreadId = threadID; if(Err != 0){ #endif Res = false; CurThreadId = -((intptr_t)1); ThreadHandler = 0; } else { while(!IsStarted) LqThreadYield(); } StartThreadLocker.UnlockWrite(); return Res; } bool LqThreadBase::IsThisThread() const { #ifdef LQPLATFORM_WINDOWS return GetCurrentThreadId() == CurThreadId; #else return pthread_equal(pthread_self(), CurThreadId); #endif } bool LqThreadBase::ExitThreadAsync() { bool r = true; StartThreadLocker.LockWrite(); if(IsThreadRunning()) { IsShouldEnd = true; if(!IsThisThread()) NotifyThread(); } else { lq_errno_set(ENOENT); r = false; } StartThreadLocker.UnlockWrite(); return r; } bool LqThreadBase::ExitThreadSync() { bool Res; if(Res = ExitThreadAsync()) { WaitEnd(); } return Res; } LqString LqThreadBase::DebugInfo() const { const char* Prior; switch(Priority) { case LQTHREAD_PRIOR_IDLE: Prior = "idle"; break; case LQTHREAD_PRIOR_LOWER: Prior = "lower"; break; case LQTHREAD_PRIOR_LOW:Prior = "low"; break; case LQTHREAD_PRIOR_NONE: case LQTHREAD_PRIOR_NORMAL: Prior = "normal"; break; case LQTHREAD_PRIOR_HIGH: Prior = "high"; break; case LQTHREAD_PRIOR_HIGHER: Prior = "higher"; break; case LQTHREAD_PRIOR_REALTIME: Prior = "realtime"; break; default: Prior = "unknown"; } char Buf[1024]; LqFbuf_snprintf ( Buf, sizeof(Buf), "--------------\n" "Thread id: %llu\n" "Is work: %c\n" "Priority: %s\n" "Affinity mask: 0x%016llx\n", (unsigned long long)ThreadId(), (char)((IsThreadRunning()) ? '1' : '0'), Prior, AffinMask ); return Buf; }
// P155 #include <iostream> #include <cstdlib> #include <string> #include <sstream> using namespace std; const int maxn = 100000 + 10; int in_order[maxn], post_order[maxn], lch[maxn], rch[maxn]; int best = 0, best_sum = 100000; int n; int read_list(int* a) { string line; if (!getline(cin, line)) return false; stringstream ss(line); n = 0; int x; while (ss >> x) a[n++] = x; return n > 0; } int build(int lo1, int hi1, int lo2, int hi2) { if (lo1 > hi1) return 0; int root = post_order[hi2]; int p = lo1; while (in_order[p] != root) ++p; int cnt = p - lo1; lch[root] = build(lo1, p - 1, lo2, lo2 + cnt - 1); rch[root] = build(p + 1, hi2, lo2 + cnt, hi2); return root; } void dfs(int r, int sum) { sum += r; if (!lch[r] && !rch[r]) { if (sum < best_sum || (sum == best_sum && r < best)) { best = r, best_sum = sum; } } if (lch[r]) dfs(lch[r], sum); if (rch[r]) dfs(rch[r], sum); } int main() { // while (read_list(in_order)) { // read_list(post_order); // build(0, n - 1, 0, n - 1); // best_sum = 1000000; // dfs(post_order[n - 1], 0); // cout << best << "\n"; // } string line; if (!getline(cin, line)) cout << "None" << endl; else cout << line << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Manuela Hutter (manuelah) */ #ifndef QUICK_ACTION_CREATOR_H #define QUICK_ACTION_CREATOR_H #include "adjunct/quick_toolkit/creators/QuickUICreator.h" class OpInputAction; /* * @brief Creates an OpInputAction object based on a ParserNode definition, for actions specified as a map. * @see QuickUICreator * * To be used like this: * * ParserNode node = // get it from somewhere, e.g. DialogReader * QuickActionCreator creator; * RETURN_IF_ERROR(creator.Init(node)); * OpInputAction * action; * RETURN_IF_ERROR(creator.CreateInputAction(action)); */ class QuickActionCreator : public QuickUICreator { public: QuickActionCreator(ParserLogger& log) : QuickUICreator(log) {} /* * Traverses the attributes of the ParserNode and creates the action and all its sub-actions. * Object owned by the caller. * @returns Error if OOM or ill-defined parser nodes. */ OP_STATUS CreateInputAction(OpAutoPtr<OpInputAction>& action); }; #endif // QUICK_ACTION_CREATOR_H
#include <vector> #include <iostream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> #include <queue> #include <fstream> #include <ext/hash_map> #include <ext/hash_set> #include <time.h> #include "bitboard.h" #define MIN(a,b) ((a)<(b)?(a):(b)) #define MAX(a,b) ((a)>(b)?(a):(b)) #define INF (10000) #define BF (7) #define WINDOW (10) #define PLI pair<unsigned long long, unsigned int> using namespace std; using namespace __gnu_cxx; namespace __gnu_cxx { template<typename T1, typename T2> struct hash<pair<T1, T2> > { size_t operator()(const pair<T1, T2> &pr) const { return hash<T1>()(pr.first)*19+hash<T2>()(pr.second)*11+5; } }; template<> struct hash<unsigned long long> { size_t operator()(const unsigned long long &pr) const { return hash<unsigned int>()(pr>>32)*19+hash<unsigned int>()(pr&((1LL<<32)-1))*11+5; } }; } /* class bitboard { unsigned int WP; unsigned int BP; unsigned int K; unsigned int MU3; unsigned int MD3; unsigned int MU5; unsigned int MD5; unsigned int CENTRE; unsigned int MASK_ROW7; unsigned int MASK_ROW6; unsigned int MASK_ROW5; unsigned int MASK_ROW4; unsigned int MASK_ROW3; unsigned int MASK_ROW2; unsigned int MASK_ROW1; unsigned int MASK_ROW0; unsigned int MASK_COL1; unsigned int MASK_COL8; unsigned int MASK_DCORNER1; unsigned int MASK_DCORNER2; int highbit[1<<16]; int bitcount[1<<16]; unsigned long long jumps; unsigned int visited; public : void display(unsigned int); bitboard(); int evaluateboardwhite(); int evaluateboardblack(); int countbits(unsigned int); int precountbits(unsigned int); unsigned int getwhite(); unsigned int getblack(); unsigned int getkings(); void setkings(unsigned int); void setwhite(unsigned int); void setblack(unsigned int); void domovewhite(int,int); void domoveblack(int,int); void dojumpwhite(int,int); void dojumpblack(int,int); unsigned int getmoverswhite(); unsigned int getmoversblack(); unsigned int getjumperswhite(); unsigned int getjumpersblack(); void getmoveswhite(int *, int &); void getmovesblack(int *, int &); void getjumpswhite(unsigned long long *, int &); void getjumpsblack(unsigned long long *, int &); bool jumpswhite(short int, int, int, int &); bool jumpsblack(short int, int, int, int &); int highestbit(unsigned int); int lowestbit(unsigned int); void debug(); unsigned int reversebits(unsigned int); };*/ /*unsigned int bitboard :: reversebits(unsigned int bitpattern) { bitpattern = ((bitpattern & 0xaaaaaaaa) >> 1) | ((bitpattern & 0x55555555) << 1); bitpattern = ((bitpattern & 0xcccccccc) >> 2) | ((bitpattern & 0x33333333) << 2); bitpattern = ((bitpattern & 0xf0f0f0f0) >> 4) | ((bitpattern & 0x0f0f0f0f) << 4); bitpattern = ((bitpattern & 0xff00ff00) >> 8) | ((bitpattern & 0x00ff00ff) << 8); bitpattern = ((bitpattern & 0xffff0000) >> 16) | ((bitpattern & 0x0000ffff) << 16); return bitpattern; }*/ class PLAY { bitboard BOARD; int color; int MOVE; int POS; long long betacutoffs; long long states; hash_map< PLI, int> H; hash_map< PLI, short int> betacutoff; bool WIN; int DEPTH; int MAXDEPTH; int TIME; int starttime; int endtime; double totaltime; int lastpos,lastmove,lastadvantage; public : PLAY(); int playalphabeta(int , int, bool, short int, short int,int); void undomove(int, int, int); void playaswhite(); void playcompwhite(); void playplayerblack(); void playasblack(); void playcompblack(); void playplayerwhite(); }; inline void PLAY :: playcompwhite() { if(BOARD.getjumperswhite()) { BOARD.dojumpwhite(POS,MOVE); BOARD.display(0); } else { BOARD.domovewhite(POS,MOVE); BOARD.display(0); } } inline void PLAY :: playcompblack() { if(BOARD.getjumpersblack()) { BOARD.dojumpblack(POS,MOVE); BOARD.display(0); } else { BOARD.domoveblack(POS,MOVE); BOARD.display(0); } } inline void PLAY :: playplayerblack() { int i,j,b; int move[20]; int pos[20]; int counter=0; int initpos; int t[20],sz=0; unsigned long long tt[10]; int ttsz=0; counter=0; int m; int p,pt; if(BOARD.getjumpersblack()) { BOARD.getjumpsblack(tt,ttsz); for(i=0;i<ttsz;i++) { pt=tt[i]%100; tt[i]/=100; while(tt[i]) { cout<<(++counter)<<"."<<pt<<" TO "; pos[counter]=pt; p=pt; m=tt[i]%10000; tt[i]/=10000; move[counter]=m; while(m) { if(m%10>5) { if(m==8 || m==6) { cout<<(p-4)<<" "; p-=4; } else { if((p/2)%2) { cout<<(p-5)<<" "; p-=5; } else { cout<<(p-3)<<" "; p-=3; } } cout<<((p-((m%10)-3)))<<" "; p-=((m%10)-3); } else { if(m==3 || m==5) { cout<<(p+4)<<" "; p+=4; } else { if((p/2)%2) { cout<<(p+3)<<" "; p+=3; } else { cout<<(p+5)<<" "; p+=5; } } cout<<(m%10+p)<<" "; p+=m%10; } m/=10; } cout<<endl; } cout<<endl; } cout<<"Enter your move :"; cin>>b; BOARD.dojumpblack(pos[b],move[b]); BOARD.display(0); } else { BOARD.getmovesblack(t,sz); for(i=0;i<sz;i++) { initpos=t[i]%100; t[i]/=100; while(t[i]) { cout<<(++counter)<<". "<<initpos<<" TO "; pos[counter]=initpos; move[counter]=t[i]%10; if(t[i]%10>5) cout<<(initpos-(t[i]%10-3))<<" "; else cout<<(initpos+(t[i]%10))<<" "; t[i]/=10; cout<<endl; } } cout<<endl; cout<<"Enter your move: "; cin>>b; BOARD.domoveblack(pos[b],move[b]); BOARD.display(0); } } inline void PLAY :: playplayerwhite() { int i,j,b; int move[20]; int pos[20]; int counter=0; int initpos; int t[20],sz=0; unsigned long long tt[10]; int ttsz=0; counter=0; int m; int p,pt; if(BOARD.getjumperswhite()) { BOARD.getjumpswhite(tt,ttsz); for(i=0;i<ttsz;i++) { pt=tt[i]%100; tt[i]/=100; while(tt[i]) { cout<<(++counter)<<"."<<pt<<" TO "; pos[counter]=pt; p=pt; m=tt[i]%10000; tt[i]/=10000; move[counter]=m; while(m) { if(m%10>5) { if(m==8 || m==6) { cout<<(p-4)<<" "; p-=4; } else { if((p/2)%2) { cout<<(p-5)<<" "; p-=5; } else { cout<<(p-3)<<" "; p-=3; } } cout<<((p-((m%10)-3)))<<" "; p-=((m%10)-3); } else { if(m==3 || m==5) { cout<<(p+4)<<" "; p+=4; } else { if((p/2)%2) { cout<<(p+3)<<" "; p+=3; } else { cout<<(p+5)<<" "; p+=5; } } cout<<(m%10+p)<<" "; p+=m%10; } m/=10; } cout<<endl; } cout<<endl; } cout<<"Enter your move :"; cin>>b; BOARD.dojumpwhite(pos[b],move[b]); BOARD.display(0); } else { BOARD.getmoveswhite(t,sz); for(i=0;i<sz;i++) { initpos=t[i]%100; t[i]/=100; while(t[i]) { cout<<(++counter)<<". "<<initpos<<" TO "; pos[counter]=initpos; move[counter]=t[i]%10; if(t[i]%10>5) cout<<(initpos-(t[i]%10-3))<<" "; else cout<<(initpos+(t[i]%10))<<" "; t[i]/=10; cout<<endl; } } cout<<endl; cout<<"Enter your move: "; cin>>b; BOARD.domovewhite(pos[b],move[b]); BOARD.display(0); } } inline void PLAY :: playaswhite() { int advantage; int alpha,beta; int count; while(1) { states=0; DEPTH=12; totaltime=0; if(BOARD.getmoverswhite()==0 && BOARD.getjumperswhite()==0) { cout<<"You have WON!!!"<<endl; break; } cout<<"Calculating next move "; MAXDEPTH=0; advantage=playalphabeta(-INF,INF,1,DEPTH,0,0); DEPTH+=2; do { alpha=advantage-WINDOW; beta=advantage+WINDOW; starttime=clock(); count=0; while(count<100) { H.clear(); MAXDEPTH=0; advantage=playalphabeta(alpha,beta,1,DEPTH,0,0); if(advantage<alpha || advantage>beta) { alpha=advantage-WINDOW; beta=advantage+WINDOW; } else break; count++; } endtime=clock(); DEPTH+=2; H.clear(); if((endtime-starttime)*BF+(int)(totaltime+0.5)*CLOCKS_PER_SEC>TIME*CLOCKS_PER_SEC) { totaltime+=((double)(endtime-starttime)/CLOCKS_PER_SEC); break; } totaltime+=((double)(endtime-starttime)/CLOCKS_PER_SEC); }while(TIME-(totaltime)>1e-9 && DEPTH<=100); cout<<endl<<"Computer has an advantage of : "<<advantage<<endl; cout<<"Time : "<<totaltime<<"s"<<endl; cout<<"Depth : "<<(DEPTH-2)<<endl; cout<<"Maxdepth : "<<MAXDEPTH<<endl; if(advantage>=INF) WIN=1; playcompwhite(); if(BOARD.getmoversblack()==0 && BOARD.getjumpersblack()==0) { cout<<"You have LOST!!!"<<endl; break; } cout<<"Your move options : "<<endl; playplayerblack(); } } inline void PLAY :: playasblack() { int advantage,alpha,beta,count; BOARD.display(0); while(1) { DEPTH=12; totaltime=0; if(BOARD.getmoverswhite()==0 && BOARD.getjumperswhite()==0) { cout<<"You have LOST!!!"<<endl; break; } cout<<"Your move options : "<<endl; playplayerwhite(); if(BOARD.getmoversblack()==0 && BOARD.getjumpersblack()==0) { cout<<"You have WON!!!"<<endl; break; } cout<<"Calculating next move "; MAXDEPTH=0; advantage=playalphabeta(-INF,INF,0,DEPTH,0,0); DEPTH+=2; do { alpha=advantage-WINDOW; beta=advantage+WINDOW; starttime=clock(); count=0; while(count<100) { H.clear(); MAXDEPTH=0; advantage=playalphabeta(alpha,beta,0,DEPTH,0,0); if(advantage<alpha) { alpha=advantage-WINDOW; beta=advantage+WINDOW; } else break; count++; } endtime=clock(); DEPTH+=2; H.clear(); if((endtime-starttime)*BF+(int)(totaltime+0.5)*CLOCKS_PER_SEC>TIME*CLOCKS_PER_SEC) { totaltime+=((double)(endtime-starttime)/CLOCKS_PER_SEC); break; } totaltime+=((double)(endtime-starttime)/CLOCKS_PER_SEC); }while(TIME-(totaltime)>1e-9 && DEPTH<=100); cout<<endl<<"Computer has an advantage of : "<<advantage<<endl; cout<<"Time : "<<totaltime<<"s"<<endl; cout<<"Depth : "<<(DEPTH-2)<<endl; cout<<"Maxdepth : "<<MAXDEPTH<<endl; if(advantage>=INF) WIN=1; playcompblack(); } } PLAY :: PLAY() { BOARD.display(0); int choice; int ch[]={1,5,10,20,30}; cout<<"Enter the color you wish to play with : "<<endl; cout<<"1. WHITE"<<endl; cout<<"2. BLACK"<<endl; cin>>color; color--; if(color) cout<<endl<<"You play as Black in this game"<<endl; else cout<<endl<<"You play as White in this game"<<endl; WIN=0; cout<<"Enter time per move for computer : "<<endl; cout<<"1. 1s\n2. 5s\n3. 10s\n4. 20s\n5. 30s"<<endl; cin>>choice; TIME=ch[choice-1]; if(color) playaswhite(); else playasblack(); } inline void PLAY :: undomove(int W,int B,int K) { BOARD.setwhite(W); BOARD.setblack(B); BOARD.setkings(K); } int PLAY :: playalphabeta(int alpha,int beta, bool color, short int depth, short int extra, int d) { MAXDEPTH=MAX(MAXDEPTH,d); if(depth==((DEPTH/2)+2) && !WIN) { int temp=playalphabeta(alpha,beta,color,(DEPTH/4)+1,extra,d+1); if(temp<alpha-100 || temp>beta+100) return temp; } if(depth==0 && color && (BOARD.getjumperswhite()==0 || extra>4)) return (BOARD.evaluateboardwhite()-BOARD.evaluateboardblack()); else if(depth==0 && !color && (BOARD.getjumpersblack()==0 || extra>4)) return (BOARD.evaluateboardblack()-BOARD.evaluateboardwhite()); unsigned int W=BOARD.getwhite(); unsigned int B=BOARD.getblack(); unsigned int K=BOARD.getkings(); unsigned int W1=W; unsigned int B1=B; int adjust=0; if(WIN) adjust=3*(18-depth); if(!color) { W1=BOARD.reversebits(W); B1=BOARD.reversebits(B); } unsigned long long WB=((long long)W1<<32)+B1; PLI hash(WB,K); if(depth+(DEPTH/4)<DEPTH && betacutoff.find(hash)!=betacutoff.end() && betacutoff[hash]>=beta) return betacutoff[hash]+adjust; if(H.find(hash)!=H.end()) { if(depth<=(H[hash]>>16)) return (((H[hash])&((1<<16)-1))-11000)+adjust; } int localalpha=alpha,bestvalue=-INF,i,j; int pos,move,value; unsigned long long tt[10]; int ttsz=0; int t[20],sz=0; int moves=0; unsigned long long jumpslist; int moveslist; if(color) { if(BOARD.getjumperswhite()) { BOARD.getjumpswhite(tt,ttsz); for(i=0;i<ttsz;i++) { jumpslist=tt[i]; pos=jumpslist%100; jumpslist/=100; while(jumpslist) { move=jumpslist%10000; jumpslist/=10000; if(ttsz==1 && jumpslist==0 && depth==DEPTH) { MOVE=move; POS=pos; return 0; } BOARD.dojumpwhite(pos,move); if(depth==0 && ttsz==1 && jumpslist==0) value=-playalphabeta(-beta,-localalpha,!color,depth,extra,d+1); else if(depth==0) value=-playalphabeta(-beta,-localalpha,!color,depth,extra+1,d+1); else value=-playalphabeta(-beta,-localalpha,!color,depth-1,extra,d+1); undomove(W,B,K); if(!moves && depth==DEPTH) { MOVE=move; POS=pos; } bestvalue=MAX(value,bestvalue); if(bestvalue>=beta) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } if(depth>=(DEPTH/2)+2) betacutoff[hash]=bestvalue; else if(depth>2 && H.size()<=9999999) H[hash]=((int)depth<<16)+bestvalue+11000; return bestvalue+adjust; } if(bestvalue>localalpha) { if(depth==DEPTH) { MOVE=move; POS=pos; } moves++; localalpha=bestvalue; } } } } else { BOARD.getmoveswhite(t,sz); for(i=0;i<sz;i++) { moveslist=t[i]; pos=moveslist%100; moveslist/=100; while(moveslist) { move=moveslist%10; moveslist/=10; BOARD.domovewhite(pos,move); value=-playalphabeta(-beta,-localalpha,!color,depth-1,extra,d+1); undomove(W,B,K); if(depth==DEPTH) cout<<"."<<flush; if(!moves && depth==DEPTH) { MOVE=move; POS=pos; } bestvalue=MAX(value,bestvalue); if(bestvalue>=beta) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } if(depth>=(DEPTH/2)+2) betacutoff[hash]=bestvalue; else if(depth>2 && H.size()<=9999999) H[hash]=((int)depth<<16)+bestvalue+11000; return bestvalue+adjust; } if(bestvalue>localalpha) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } localalpha=bestvalue; } } } } } else { if(BOARD.getjumpersblack()) { BOARD.getjumpsblack(tt,ttsz); for(i=0;i<ttsz;i++) { jumpslist=tt[i]; pos=jumpslist%100; jumpslist/=100; while(jumpslist) { move=jumpslist%10000; jumpslist/=10000; if(ttsz==1 && jumpslist==0 && depth==DEPTH) { MOVE=move; POS=pos; return 0; } BOARD.dojumpblack(pos,move); if(depth==0 && ttsz==1 && jumpslist==0) value=-playalphabeta(-beta,-localalpha,!color,depth,extra,d+1); else if(depth==0) value=-playalphabeta(-beta,-localalpha,!color,depth,extra+1,d+1); else value=-playalphabeta(-beta,-localalpha,!color,depth-1,extra,d+1); undomove(W,B,K); if(!moves && depth==DEPTH) { MOVE=move; POS=pos; } bestvalue=MAX(bestvalue,value); if(bestvalue>=beta) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } if(depth>=(DEPTH/2)+2) betacutoff[hash]=bestvalue; else if(depth>2 && H.size()<=9999999) H[hash]=((int)depth<<16)+bestvalue+11000; return bestvalue+adjust; } if(bestvalue>localalpha) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } localalpha=bestvalue; } } } } else { BOARD.getmovesblack(t,sz); for(i=0;i<sz;i++) { moveslist=t[i]; pos=moveslist%100; moveslist/=100; while(moveslist) { move=moveslist%10; moveslist/=10; BOARD.domoveblack(pos,move); value=-playalphabeta(-beta,-localalpha,!color,depth-1,extra,d+1); undomove(W,B,K); if(depth==DEPTH) cout<<"."<<flush; if(!moves && depth==DEPTH) { MOVE=move; POS=pos; } bestvalue=MAX(value,bestvalue); if(bestvalue>=beta) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } if(depth>=(DEPTH/2)+2) betacutoff[hash]=bestvalue; else if(depth>2 && H.size()<=9999999) H[hash]=((int)depth<<16)+bestvalue+11000; return bestvalue+adjust; } if(bestvalue>localalpha) { moves++; if(depth==DEPTH) { MOVE=move; POS=pos; } localalpha=bestvalue; } } } } } if(bestvalue==-INF) return bestvalue+adjust; else { if(depth>2 && H.size()<=9999999) H[hash]=(depth<<16)+bestvalue+11000; return bestvalue+adjust; } } /* inline int bitboard :: evaluateboardwhite() { int value=0; unsigned int control=0; unsigned int temp=0; unsigned int empty=~(WP|BP); unsigned int mobility=((((WP&(~K))<<4)&empty) | (((WP&(~K))<<3)&(empty&MU3)) | (((WP&(~K))<<5)&(empty&MU5))); unsigned int lastrow=(((empty>>4)&(MASK_ROW6)) | (((empty&MU3)>>3)&(MASK_ROW6)) | (((empty&MU5)>>5)&(MASK_ROW6))); temp=((WP&(~K))<<4)&empty; control=((((empty&MU3)>>3)&temp) | (((empty&MU5)>>5)&temp)); value+=countbits(control)*15; temp=(((WP&(~K))<<3)&(empty&MU3) | ((WP&(~K))<<5)&(empty&MU5)); control=((empty>>4)&temp); value+=countbits(control)*15; value+=countbits((WP&MASK_ROW0))*15; value+=countbits((WP&(~K))&lastrow)*100; value+=countbits(WP)*200; value+=countbits(WP&K)*250; value+=countbits(WP&CENTRE)*20; value+=countbits((WP&(~K))&MASK_ROW6)*36; value+=countbits((WP&(~K))&MASK_ROW5)*25; value+=countbits((WP&(~K))&MASK_ROW4)*16; value+=countbits((WP&(~K))&MASK_ROW3)*9; value+=countbits((WP&(~K))&MASK_ROW2)*4; value+=countbits((WP&(~K))&MASK_ROW1); value+=countbits((WP&K)&MASK_ROW0)*(-20); value+=countbits((WP&K)&MASK_ROW7)*(-20); value+=countbits((WP&K)&MASK_COL1)*(-20); value+=countbits((WP&K)&MASK_COL8)*(-20); value+=countbits(mobility)*15; value+=countbits((WP&(~K))&(MASK_COL1|MASK_COL8))*(-10); return value; } inline int bitboard :: evaluateboardblack() { int value=0; unsigned int control=0; unsigned int temp=0; unsigned int empty=~(WP|BP); unsigned int mobility=((((BP&(~K))>>4)&empty) | (((BP&(~K))>>3)&(empty&MD3)) | (((BP&(~K))>>5)&(empty&MD5))); unsigned int lastrow=(((empty<<4)&(MASK_ROW1)) | (((empty&MD3)<<3)&(MASK_ROW1)) | (((empty&MD5)<<5)&(MASK_ROW1))); temp=((BP&(~K))>>4)&empty; control=((((empty&MD3)<<3)&temp) | (((empty&MD5)<<5)&temp)); value+=countbits(control)*15; temp=(((BP&(~K))>>3)&(empty&MD3) | ((BP&(~K))>>5)&(empty&MD5)); control=((empty<<4)&temp); value+=countbits(control)*15; value+=countbits((BP&MASK_ROW7))*15; value+=countbits((BP&(~K))&lastrow)*100; value+=countbits(BP)*200; value+=countbits(BP&K)*250; value+=countbits(BP&CENTRE)*20; value+=countbits((BP&(~K))&MASK_ROW6); value+=countbits((BP&(~K))&MASK_ROW5)*4; value+=countbits((BP&(~K))&MASK_ROW4)*9; value+=countbits((BP&(~K))&MASK_ROW3)*16; value+=countbits((BP&(~K))&MASK_ROW2)*25; value+=countbits((BP&(~K))&MASK_ROW1)*36; value+=countbits((BP&K)&MASK_ROW0)*(-20); value+=countbits((BP&K)&MASK_ROW7)*(-20); value+=countbits((BP&K)&MASK_COL1)*(-20); value+=countbits((BP&K)&MASK_COL8)*(-20); value+=countbits(mobility)*15; value+=countbits((BP&(~K))&(MASK_COL1|MASK_COL8))*(-10); return value; } inline int bitboard :: precountbits(unsigned int bitpattern) { int ret=0; int pos; while(bitpattern) { pos=highestbit(bitpattern); bitpattern&=(~(1<<pos)); ret++; } return ret; } inline int bitboard :: countbits(unsigned int bitpattern) { return bitcount[bitpattern&((1<<16)-1)]+bitcount[bitpattern>>16]; } inline unsigned int bitboard :: getwhite() { return WP; } inline unsigned int bitboard :: getblack() { return BP; } inline void bitboard :: setwhite(unsigned int W) { WP=W; } inline void bitboard :: setblack(unsigned int B) { BP=B; } inline unsigned int bitboard :: getkings() { return K; } inline void bitboard :: setkings(unsigned int k) { K=k; } inline void bitboard :: dojumpwhite(int pos, int move) { while(move) { int m=move%10; move/=10; if(m>5) { if(m==8 || m==6) { domovewhite(pos,7); pos-=4; } else { if(((BP&MD5)<<5)&(1<<pos)) { domovewhite(pos,8); pos-=5; } else { domovewhite(pos,6); pos-=3; } } domovewhite(pos,m); pos-=(m-3); } else { if(m==3 || m==5) { domovewhite(pos,4); pos+=4; } else { if(((BP&MU5)>>5)&(1<<pos)) { domovewhite(pos,5); pos+=5; } else { domovewhite(pos,3); pos+=3; } } domovewhite(pos,m); pos+=m; } } } inline void bitboard :: dojumpblack(int pos, int move) { while(move) { int m=move%10; move/=10; if(m>5) { if(m==8 || m==6) { domoveblack(pos,7); pos-=4; } else { if(((WP&MD5)<<5)&(1<<pos)) { domoveblack(pos,8); pos-=5; } else { domoveblack(pos,6); pos-=3; } } domoveblack(pos,m); pos-=(m-3); } else { if(m==3 || m==5) { domoveblack(pos,4); pos+=4; } else { if(((WP&MU5)>>5)&(1<<pos)) { domoveblack(pos,5); pos+=5; } else { domoveblack(pos,3); pos+=3; } } domoveblack(pos,m); pos+=m; } } } inline void bitboard :: domovewhite(int pos, int move) { if(move>5) { move-=3; WP&=(~(1<<pos)); K&=(~(1<<pos)); WP|=(1<<(pos-move)); K|=(1<<(pos-move)); BP&=(~(1<<(pos-move))); } else { if((1<<pos)&K) { WP&=(~(1<<pos)); K&=(~(1<<pos)); WP|=(1<<(pos+move)); K|=(1<<(pos+move)); BP&=(~(1<<(pos+move))); } else { WP&=(~(1<<pos)); WP|=(1<<(pos+move)); BP&=(~(1<<(pos+move))); if(pos+move>=28) K|=(1<<(pos+move)); else K&=(~(1<<(pos+move))); } } } inline void bitboard :: domoveblack(int pos, int move) { if(move>5) { move-=3; if((1<<pos)&K) { BP&=(~(1<<pos)); K&=(~(1<<pos)); BP|=(1<<(pos-move)); K|=(1<<(pos-move)); WP&=(~(1<<(pos-move))); } else { BP&=(~(1<<pos)); BP|=(1<<(pos-move)); if(pos-move<=3) K|=(1<<(pos-move)); else K&=(~(1<<(pos-move))); WP&=(~(1<<(pos-move))); } } else { BP&=(~(1<<pos)); K&=(~(1<<pos)); BP|=(1<<(pos+move)); K|=(1<<(pos+move)); WP&=(~(1<<(pos+move))); } } bool bitboard :: jumpswhite(short int pos,int seq,int pow,int &in) { unsigned int test=1<<pos,tempmask,empty=~(WP|BP); unsigned int k=1<<in; bool end=1; if((visited)&(1<<pos)) return 1; visited|=(1<<pos); tempmask=(empty>>4)&BP; if(tempmask) { if(((tempmask&MU3)>>3)&test) end&=jumpswhite(pos+7,pow*4+seq,pow*10,in); if(((tempmask&MU5)>>5)&test) end&=jumpswhite(pos+9,pow*4+seq,pow*10,in); } tempmask=((empty&MU3)>>3)&BP; if(tempmask) { if(((tempmask)>>4)&test) end&=jumpswhite(pos+7,pow*3+seq,pow*10,in); } tempmask=((empty&MU5)>>5)&BP; if(tempmask) { if(((tempmask)>>4)&test) end&=jumpswhite(pos+9,pow*5+seq,pow*10,in); } if(k&K) { tempmask=(empty<<4)&BP; if(tempmask) { if(((tempmask&MD3)<<3)&test) end&=jumpswhite(pos-7,pow*7+seq,pow*10,in); if(((tempmask&MD5)<<5)&test) end&=jumpswhite(pos-9,pow*7+seq,pow*10,in); } tempmask=((empty&MD3)<<3)&BP; if(tempmask) { if(((tempmask)<<4)&test) end&=jumpswhite(pos-7,pow*6+seq,pow*10,in); } tempmask=((empty&MD5)<<5)&BP; if(tempmask) { if(((tempmask)<<4)&test) end&=jumpswhite(pos-9,pow*8+seq,pow*10,in); } } if(end) { if(jumps<(1ULL<<63)/10000) { jumps*=10000; jumps+=seq; } } return 0; } bool bitboard :: jumpsblack(short int pos,int seq,int pow,int &in) { unsigned int test=1<<pos,tempmask,empty=~(WP|BP); unsigned int k=1<<in; if((visited)&(1<<pos)) return 1; visited|=(1<<pos); tempmask=(empty<<4)&WP; bool end=1; if(tempmask) { if(((tempmask&MD3)<<3)&test) end&=jumpsblack(pos-7,pow*7+seq,pow*10,in); if(((tempmask&MD5)<<5)&test) end&=jumpsblack(pos-9,pow*7+seq,pow*10,in); } tempmask=((empty&MD3)<<3)&WP; if(tempmask) { if(((tempmask)<<4)&test) end&=jumpsblack(pos-7,pow*6+seq,pow*10,in); } tempmask=((empty&MD5)<<5)&WP; if(tempmask) { if(((tempmask)<<4)&test) end&=jumpsblack(pos-9,pow*8+seq,pow*10,in); } if(k&K) { tempmask=(empty>>4)&WP; if(tempmask) { if(((tempmask&MU3)>>3)&test) end&=jumpsblack(pos+7,pow*4+seq,pow*10,in); if(((tempmask&MU5)>>5)&test) end&=jumpsblack(pos+9,pow*4+seq,pow*10,in); } tempmask=((empty&MU3)>>3)&WP; if(tempmask) { if(((tempmask)>>4)&test) end&=jumpsblack(pos+7,pow*3+seq,pow*10,in); } tempmask=((empty&MU5)>>5)&WP; if(tempmask) { if(((tempmask)>>4)&test) end&=jumpsblack(pos+9,pow*5+seq,pow*10,in); } } if(end) { if(jumps<(1ULL<<63)/10000) { jumps*=10000; jumps+=seq; } } return 0; } inline void bitboard :: getjumpswhite(unsigned long long *ret, int &size) { unsigned int empty=~(WP|BP); unsigned int movers=getjumperswhite(); int bit; bool temp; while(movers) { int temp=0; unsigned int tempmask=0; bit=highestbit(movers); unsigned int test=1<<bit; movers&=(~(test)); visited=0; jumps=0; temp=jumpswhite(bit,0,1,bit); jumps=jumps*100+bit; ret[size++]=jumps; } } inline void bitboard :: getjumpsblack(unsigned long long *ret, int &size) { unsigned int empty=~(WP|BP); unsigned int movers=getjumpersblack(); int bit; bool temp; while(movers) { int temp=0; unsigned int tempmask=0; bit=lowestbit(movers); unsigned int test=1<<bit; movers&=(~(test)); jumps=0; visited=0; temp=jumpsblack(bit,0,1,bit); jumps=jumps*100+bit; ret[size++]=jumps; } } inline void bitboard :: getmoveswhite(int *ret, int &size) { unsigned int empty=~(WP|BP); unsigned int movers=getmoverswhite(); int bit; while(movers) { int temp=0; bit=highestbit(movers); unsigned int test=1<<bit; movers&=(~(test)); if((empty>>4)&test) temp=temp*10+4; if(((empty&MU3)>>3)&test) temp=temp*10+3; if(((empty&MU5)>>5)&test) temp=temp*10+5; if((test)&K) { if((empty<<4)&test) temp=temp*10+7; if(((empty&MD3)<<3)&test) temp=temp*10+6; if(((empty&MD5)<<5)&test) temp=temp*10+8; } temp=temp*100+bit; ret[size++]=temp; } } inline void bitboard :: getmovesblack(int *ret, int &size) { unsigned int empty=~(WP|BP); unsigned int movers=getmoversblack(); int bit; while(movers) { int temp=0; bit=lowestbit(movers); unsigned int test=1<<bit; movers&=(~(test)); if((empty<<4)&test) temp=temp*10+7; if(((empty&MD3)<<3)&test) temp=temp*10+6; if(((empty&MD5)<<5)&test) temp=temp*10+8; if((test)&K) { if(((empty&MU3)>>3)&test) temp=temp*10+3; if(((empty&MU5)>>5)&test) temp=temp*10+5; if((empty>>4)&test) temp=temp*10+4; } temp=temp*100+bit; ret[size++]=temp; } } inline unsigned int bitboard :: getjumperswhite() { unsigned int empty=~(WP|BP); unsigned int WK=WP&K; unsigned int movers=0; unsigned int temp=0; temp=(empty>>4)&BP; if(temp) movers|=((((temp&MU3)>>3)&WP) | (((temp&MU5)>>5)&WP)); temp=(((empty&MU3)>>3)&BP) | (((empty&MU5)>>5)&BP); if(temp) movers|=((temp>>4)&WP); if(WK) { temp=(empty<<4)&BP; if(temp) movers|=((((temp&MD3)<<3)&WK) | (((temp&MD5)<<5)&WK)); temp=(((empty&MD3)<<3)&BP) | (((empty&MD5)<<5)&BP); if(temp) movers|=((temp<<4)&WK); } return movers; } inline unsigned int bitboard :: getjumpersblack() { unsigned int empty=~(WP|BP); unsigned int BK=BP&K; unsigned int movers=0; unsigned int temp=0; temp=(empty<<4)&WP; if(temp) movers|=((((temp&MD3)<<3)&BP) | (((temp&MD5)<<5)&BP)); temp=(((empty&MD3)<<3)&WP) | (((empty&MD5)<<5)&WP); if(temp) movers|=((temp<<4)&BP); if(BK) { temp=(empty>>4)&WP; if(temp) movers|=((((temp&MU3)>>3)&BK) | (((temp&MU5)>>5)&BK)); temp=(((empty&MU3)>>3)&WP) | (((empty&MU5)>>5)&WP); if(temp) movers|=((temp>>4)&BK); } return movers; } inline int bitboard :: lowestbit(unsigned int bitpattern) { bitpattern=reversebits(bitpattern); return 31-highestbit(bitpattern); } inline int bitboard :: highestbit(unsigned int bitpattern) { if((bitpattern>>16) & 65535) return highbit[(bitpattern>>16) & 65535]+16; if(bitpattern & 65535) return highbit[bitpattern & 65535]; return 0; } inline unsigned int bitboard :: getmoverswhite() { unsigned int empty=~(WP|BP); unsigned int WK=WP&K; unsigned int movers=0; movers|=((empty>>4)&WP); movers|=(((empty&MU3)>>3)&WP); movers|=(((empty&MU5)>>5)&WP); if(WK) { movers|=((empty<<4)&WK); movers|=(((empty&MD3)<<3)&WK); movers|=(((empty&MD5)<<5)&WK); } return movers; } inline unsigned int bitboard :: getmoversblack() { unsigned int empty=~(WP|BP); unsigned int BK=BP&K; unsigned int movers=0; movers|=((empty<<4)&BP); movers|=(((empty&MD3)<<3)&BP); movers|=(((empty&MD5)<<5)&BP); if(BK) { movers|=((empty>>4)&BK); movers|=(((empty&MU3)>>3)&BK); movers|=(((empty&MU5)>>5)&BK); } return movers; } void bitboard :: debug() { int b,m; int i,j; int t[20],sz; display(WP|BP); while(1) { sz=0; vector <unsigned long long> tt; if(getjumperswhite()) { getjumpswhite(tt); for(i=0;i<tt.size();i++) cout<<tt[i]<<endl; cin>>b>>m; dojumpwhite(b,m); display(WP|BP); } else { getmoveswhite(t,sz); for(i=0;i<sz;i++) cout<<t[i]<<" "; cout<<endl; cin>>b>>m; domovewhite(b,m); display(WP|BP); } tt.clear(); sz=0; if(getjumpersblack()) { getjumpsblack(tt); for(i=0;i<tt.size();i++) cout<<tt[i]<<endl; cin>>b>>m; dojumpblack(b,m); display(WP|BP); } else { getmovesblack(t,sz); for(i=0;i<sz;i++) cout<<t[i]<<" "; cout<<endl; cin>>b>>m; domoveblack(b,m); display(WP|BP); } } } bitboard :: bitboard() { WP=0xfff; BP=(0xfff)<<20; K=0; MU3=0x70707070; MD3=0x0e0e0e0e; MU5=0x0e0e0e00; MD5=0x00707070; CENTRE=0x42000; MASK_ROW7=(0xf)<<28; MASK_ROW6=(0xf)<<24; MASK_ROW5=(0xf)<<20; MASK_ROW4=(0xf)<<16; MASK_ROW3=(0xf)<<12; MASK_ROW2=(0xf)<<8; MASK_ROW1=(0xf)<<4; MASK_ROW0=0xf; MASK_COL1=(0x01010101); MASK_COL8=(0x80808080); MASK_DCORNER1=(0x88)<<24; MASK_DCORNER2=(0x88); int i,j; j=0; for(i=1;i<(1<<16);i++) { if(i==(1<<(j+1))) j++; highbit[i]=j; } for(i=0;i<(1<<16);i++) bitcount[i]=precountbits(i); } void bitboard :: display(unsigned int bitpattern) { int i,j; int pos; int t; for(i=0;i<8;i++) { cout<<endl; for(j=0,t=0;j<8;j++) { if(((i*8+j)/8)%2==0 && j%2==0) { cout<<"#"<<" "; continue; } if(((i*8+j)/8)%2!=0 && j%2!=0) { cout<<"#"<<" "; continue; } pos=28-(4*i)+t; t++; if(((1<<pos)&(WP&(~K)))!=0) cout<<"w"<<" "; else if(((1<<pos)&WP)!=0) cout<<"W"<<" "; else if(((1<<pos)&(BP&(~K)))!=0) cout<<"b"<<" "; else if(((1<<pos)&BP)!=0) cout<<"B"<<" "; else cout<<"."<<" "; } cout<<" "; for(j=0,t=0;j<8;j++) { if(((i*8+j)/8)%2==0 && j%2==0) { cout<<"#"<<" "; continue; } if(((i*8+j)/8)%2!=0 && j%2!=0) { cout<<"#"<<" "; continue; } pos=28-(4*i)+t; t++; if(pos/10==0) cout<<"0"; cout<<pos<<" "; } } cout<<endl; }*/ int main() { PLAY OBJ; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef SPEED_DIAL_THUMBNAIL_H #define SPEED_DIAL_THUMBNAIL_H #include "adjunct/quick/speeddial/SpeedDialListener.h" #include "adjunct/quick/thumbnails/GenericThumbnail.h" #include "adjunct/quick/managers/AnimationManager.h" class DesktopSpeedDial; class OpSpeedDialView; class SpeedDialThumbnail : public GenericThumbnail, public SpeedDialEntryListener, public QuickAnimationListener { public: SpeedDialThumbnail(); static OP_STATUS Construct(SpeedDialThumbnail** obj); OP_STATUS SetEntry(const DesktopSpeedDial* entry); const DesktopSpeedDial* GetEntry() const { return m_entry; } virtual void AnimateThumbnailIn(); virtual void AnimateThumbnailOut(bool use_undo); virtual void GetRequiredThumbnailSize(INT32& width, INT32& height); OpSpeedDialView* GetParentOpSpeedDial() const; // SpeedDialEntryListener virtual void OnSpeedDialUIChanged(const DesktopSpeedDial &sd) { OpStatus::Ignore(OnContentChanged()); } virtual void OnSpeedDialExpired(); virtual void OnSpeedDialEntryScaleChanged(); // OpWidget virtual void OnDeleted(); virtual void OnMouseMove(const OpPoint& point); virtual void OnMouseLeave(); virtual void OnMouseDown(const OpPoint& point, MouseButton button, UINT8 nclicks); virtual void OnMouseUp(const OpPoint& point, MouseButton button, UINT8 nclicks); virtual void OnCaptureLost(); // OpWidgetListener virtual void OnDragStart(OpWidget* widget, INT32 pos, INT32 x, INT32 y); virtual void OnFocusChanged(OpWidget *widget, FOCUS_REASON reason ); // OpInputContext virtual BOOL OnInputAction(OpInputAction* action); virtual void SetFocus(FOCUS_REASON reason); // QuickAnimationListener virtual void OnAnimationComplete(OpWidget *anim_target, int callback_param); private: /** * Get another SpeedDialThumbnail in the same parent that is intersecting a fair * amount with this one. */ SpeedDialThumbnail* GetDropThumbnail(); /** * Start drag'n'drop mode. * * @return @c true iff drag is possible */ bool StartDragging(INT32 x, INT32 y); /** * Stop inline dragging (moving to rearrange dials) */ void StopDragging(); bool IsDragging() const { return m_drag_object != NULL; } const DesktopSpeedDial* m_entry; DesktopDragObject* m_drag_object; OpPoint m_mousedown_point; bool m_mouse_down_active; // true when MouseDown has been called }; #endif // SPEED_DIAL_THUMBNAIL_H
#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdint.h> #include <list.h> #include <node.h> #include <reader.h> #include <parser.h> #include <ll.h> #include <context.h> #include <logger.h> /* extern Context* context; extern Logger* ll_logger; NodeDescriptor ll_exit(NodeDescriptor i) { static Logger* logger = new Logger(ll_logger, "exit"); delete context; int val = *i.base<int*>(); printf("Exit with value %d\n", val); exit(val); return NodeDescriptor(); } NodeDescriptor ll_open(NodeDescriptor i) { static Logger* logger = new Logger(ll_logger, "open"); int straddr = *(i.base<int*>()); int oflags = *(i.base<int*>()+1); NodeDescriptor strn = i.getNode(straddr); int ret = open(strn->base<char*>(), oflags); Node* retn = new Node(i->node, 4); *(retn->base<int*>()) = ret; return NodeDescriptor(retn); } NodeDescriptor ll_close(NodeDescriptor i) { static Logger* logger = new Logger(ll_logger, "close"); int fd = *(i->base<int*>()); int ret = close(fd); Node* retn = new Node(i, 4); *(retn->base<int*>()) = ret; return new NodeDescriptor(retn); } NodeDescriptor ll_read(NodeDescriptor i) { static Logger* logger = new Logger(ll_logger, "read"); int fd = *(i->base<int*>()); iref_t bufaddr = *(i->base<int*>()+1); NodeDescriptor bufn = i->getNode(bufaddr); if(bufn == NULL) { logger->log(lerror, "invalid buffer"); return NULL; } int len = bufn->size(); if(i->size() == 12) { len = *(i->base<int*>()+2); if(len > bufn->size()) { logger->log(lerror, "buffer too small"); return NULL; } } int ret = read(fd, bufn->base<void*>(), len); Node* retn = new Node(i, 4); *(retn->base<int*>()) = ret; return new NodeDescriptor(retn); } NodeDescriptor ll_write(NodeDescriptor i) { static Logger* logger = new Logger(ll_logger, "write"); int fd = *(i->base<int*>()); iref_t bufaddr = *(i->base<int*>()+1); NodeDescriptor bufn = i->getNode(bufaddr); if(bufn == NULL) { logger->log(lerror, "invalid buffer (addr: 0x%x)", bufaddr); return NULL; } int len = bufn->size(); if(i->size() == 12) { len = *(i->base<int*>()+2); if(len > bufn->size()) { logger->log(lerror, "buffer too small"); return NULL; } } int ret = write(fd, bufn->base<void*>(), len); Node* retn = new Node(i, 4); *(retn->base<int*>()) = ret; return new NodeDescriptor(retn); } NodeDescriptor ll_set(NodeDescriptor i) { int* v = i->base<int*>(); NodeDescriptor dest = i->getNode(v[0]); NodeDescriptor src = i->getNode(v[1]); //printf("set: %x, %x\n", dest, src); //printf("size a: %d, b: %d\n", dest->size(), src->size()); if(dest->size() >= src->size()) memcpy(dest->base<void*>(), src->base<void*>(), src->size()); else printf("set: error: wrong size\n"); return NULL; } NodeDescriptor ll_create(NodeDescriptor i) { size_t size = *(i->base<size_t*>()); Node* n = new Node(i, size); i->autoMap(n); return new NodeDescriptor(n); } NodeDescriptor ll_inc(NodeDescriptor i) { NodeDescriptor v = ll_res(i); *(v->base<int*>()) = *(v->base<int*>()) + 1; return v; } NodeDescriptor ll_dec(NodeDescriptor i) { NodeDescriptor v = ll_res(i); *(v->base<int*>()) = *(v->base<int*>()) - 1; return v; } NodeDescriptor ll_addi(NodeDescriptor i) { NodeDescriptor list = ll_res(i); int len = list->size() / 4; int* v = list->base<int*>(); Node* o = new Node(i, 4); i->autoMap(o); int* a = o->base<int*>(); *a = 0; while(len-- > 0) *a += *v++; return new NodeDescriptor(o); } NodeDescriptor ll_subi(NodeDescriptor i) { NodeDescriptor list = ll_res(i); int len = list->size() / 4; int* v = list->base<int*>(); Node* o = new Node(i, 4); i->autoMap(o); int* a = o->base<int*>(); *a = *v; v += 1; while(--len > 0) { *a -= *v; v += 1; } return new NodeDescriptor(o); } NodeDescriptor ll_muli(NodeDescriptor i) { NodeDescriptor list = ll_res(i); int len = list->size() / 4; int* v = list->base<int*>(); Node* o = new Node(i, 4); i->autoMap(o); int* a = o->base<int*>(); *a = *v; v += 1; while(--len > 0) { *a *= *v; v += 1; } return new NodeDescriptor(o); } NodeDescriptor ll_divi(NodeDescriptor i) { NodeDescriptor list = ll_res(i); int len = list->size() / 4; int* v = list->base<int*>(); Node* o = new Node(i, 4); i->autoMap(o); int* a = o->base<int*>(); *a = *v; v += 1; while(--len > 0) { *a /= *v; v += 1; } return new NodeDescriptor(o); } NodeDescriptor ll_eqi(NodeDescriptor i) { int* v = i->base<int*>(); Node* n = new Node(1); //i->addNode(n); *n->base<int*>() = (v[0] == v[1]) ? 1 : 0; return new NodeDescriptor(n); } NodeDescriptor ll_lti(NodeDescriptor i) { int* v = i->base<int*>(); Node* n = new Node(1); *n->base<int*>() = (v[0] < v[1]) ? 1 : 0; return new NodeDescriptor(n); } NodeDescriptor ll_gti(NodeDescriptor i) { int* v = i->base<int*>(); Node* n = new Node(1); *n->base<int*>() = (v[0] > v[1]) ? 1 : 0; return new NodeDescriptor(n); } NodeDescriptor ll_cond(NodeDescriptor i) { char* cond = i->base<char*>(); int* v = (int*) (i->base<uintptr_t>() + 1); Node* r = new Node(i, sizeof(iref_t)); if(*cond) { *(r->base<iref_t*>()) = v[0]; return new NodeDescriptor(r); } else { if(i->size() == 9) { *(r->base<iref_t*>()) = v[1]; return new NodeDescriptor(r); } } return NULL; } */
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; char st[30],ss[30]; int main() { int T; scanf("%d",&T); while (T--) { scanf("%s",st+2);st[0] = st[1] = '0'; int n = strlen(st),len = n-2,cnt4 = 0,cnt7 = 0,big = 0; ss[0] = ss[1] = '0'; if (n%2 == 1) {ss[1] = '4';cnt4++;len++;big = 1;} for (int i = 2;i < n; i++) { if (!big) { if (st[i] <= '4' && cnt4 < len/2) {ss[i] = '4';cnt4++;} else if (st[i] <= '7' && cnt7 < len/2) {ss[i] = '7';cnt7++;} else { int it = i-1; while (ss[it] == '7') it--; if (ss[it] == '0') {ss[it] = ss[it-1] = '4';cnt4+=2;len+=2;} else {ss[it] = '7';cnt4--;} i = it; } if (ss[i] > st[i]) big = 1; } else { if (cnt4 < len/2) {ss[i] = '4';cnt4++;} else ss[i] = '7'; } } ss[n] = '\0'; if (ss[1] == '0') printf("%s\n",ss+2); else if (ss[0] == '0') printf("%s\n",ss+1); else printf("%s\n",ss); } return 0; }
#include <stdio.h> /*************** * function bubble_sort() * * A int type of arrary * len int type of A length * ****************/ void bubble_sort(int A[],int len){ int i,j,temp; // element from first to last-1 for(i=0;i<len-1;i++){ //element from last to first+1 for(j=len-1;j>i;j--){ //exchange A[j] A[j-1] if(A[j]<A[j-1]){ temp=A[j]; A[j]=A[j-1]; A[j-1]=temp; } } } } int main() { int A[10],i=0,len; char c; while (1) { scanf("%d",&A[i]); c=getchar(); if(c=='\n') break; i++; } //use bubble_sort() len=i+1; bubble_sort(A,len); //output has sorted of A for(i=0;i<len;i++) printf("%d ",A[i]); return 0; } /************************************** * * input 5 2 4 7 1 3 2 6 9 8 * * output 1 2 2 3 4 5 6 7 8 9 ***************************************/
////////////////////////////////////////////////////////////////////// ///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/>. // /////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "mainmenu.h" //annyonig to read CMainMenu::CMainMenu(irr::IrrlichtDevice *graphics,irrklang::ISoundEngine *sound) { //setup GUI font and other stuff gui::IGUISkin *skin = graphics->getGUIEnvironment()->createSkin(gui::EGST_WINDOWS_METALLIC); graphics->getGUIEnvironment()->setSkin(skin); gui::IGUIFont *micro = graphics->getGUIEnvironment()->getFont("res/font/verdana_micro.xml"); gui::IGUIFont *menu_font= graphics->getGUIEnvironment()->getFont("res/font/large.xml"); gui::IGUIFont *astro= graphics->getGUIEnvironment()->getFont("res/font/system.xml"); graphics->getGUIEnvironment()->getSkin()->setFont(astro); //setup colors for gui for (s32 i=0; i<gui::EGDC_COUNT ; i++) { video::SColor col = graphics->getGUIEnvironment()->getSkin()->getColor((gui::EGUI_DEFAULT_COLOR)i); col.setAlpha(208); col.setBlue(128); col.setGreen(118); col.setRed(108); graphics->getGUIEnvironment()->getSkin()->setColor((gui::EGUI_DEFAULT_COLOR)i, col); } graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_BUTTON_TEXT,video::SColor(255,255,255,255)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_HIGH_LIGHT_TEXT,video::SColor(255,255,255,255)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_3D_DARK_SHADOW,video::SColor(128,40,50,60)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_3D_SHADOW,video::SColor(128,80,90,100)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_ACTIVE_BORDER,video::SColor(255,145,155,165)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_INACTIVE_BORDER,video::SColor(128,80,90,100)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_GRAY_TEXT,video::SColor(128,40,50,60)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_WINDOW_SYMBOL,video::SColor(255,255,255,255)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_INACTIVE_CAPTION, video::SColor(255,200,200,200)); graphics->getGUIEnvironment()->getSkin()->setColor(gui::EGDC_ACTIVE_CAPTION, video::SColor(255,250,250,250)); //important to set up menu core::dimension2d<u32> t = graphics->getVideoDriver()->getScreenSize(); //Create logo logo = graphics->getGUIEnvironment()->addImage(graphics->getVideoDriver()->getTexture("res/menu/lost_horizons_logo.png"),core::position2d<s32>(t.Width/2-256,0)); graphics->setWindowCaption(L"Lost Horizons"); //create menu buttons control=graphics->getGUIEnvironment()->addGUIElement("context",0); newgame = graphics->getGUIEnvironment()->addButton(core::rect<int>(t.Width/2-50,t.Height/2+20,t.Width/2+50,t.Height/2+40),control,0,L"New Game"); loadgame = graphics->getGUIEnvironment()->addButton(core::rect<int>(t.Width/2-50,t.Height/2+60,t.Width/2+50,t.Height/2+80),control,0,L"Load Game"); options = graphics->getGUIEnvironment()->addButton(core::rect<int>(t.Width/2-50,t.Height/2+100,t.Width/2+50,t.Height/2+120),control,0,L"Options"); quit = graphics->getGUIEnvironment()->addButton(core::rect<int>(t.Width/2-50,t.Height/2+140,t.Width/2+50,t.Height/2+160),control,0,L"Quit"); //setup camera for menu scene cam = graphics->getSceneManager()->addCameraSceneNode(); cam->setPosition(vector3df(0,0,0)); cam->setFarValue(5000000); //sun* menustar = new sun(graphics,core::vector3df(-20000,500,70000)); //create sun for menu background corona=graphics->getSceneManager()->addBillboardSceneNode(0,dimension2d<f32>(50000,50000),vector3df(-20000,500,70000)); corona->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/particlewhite.bmp")); corona->setMaterialFlag(video::EMF_LIGHTING, false); corona->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); scene::IBillboardSceneNode *corona3 = graphics->getSceneManager()->addBillboardSceneNode(corona,dimension2d<f32>(130000,110000),vector3df(0,0,0)); corona3->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/engine_corona.png")); corona3->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); //setup menu background scene::ISceneNode *skybox = graphics->getSceneManager()->addSkyBoxSceneNode( graphics->getVideoDriver()->getTexture("res/textures/skyboxes/3/space_top3.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/3/space_bottom4.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/3/space_left2.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/3/space_right1.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/3/space_front5.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/3/space_back6.jpg")); graphics->getSceneManager()->setAmbientLight(video::SColor(64,64,64,64)); nebula = graphics->getSceneManager()->addParticleSystemSceneNode(false,cam); scene::IParticleSphereEmitter *em = nebula->createSphereEmitter(vector3df(-800,0,100),10,vector3df(0.02,0,0),1,1,SColor(255,200,220,225),SColor(255,200,220,225),15000,25000,0,dimension2df(500,500),dimension2df(2000,2000)); nebula->setEmitter(em); em->drop(); nebula->setMaterialFlag(video::EMF_LIGHTING,false); nebula->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/fog.pcx")); nebula->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); scene::IParticleAffector *af = nebula->createFadeOutParticleAffector(); nebula->addAffector(af); af->drop(); asteroids = graphics->getSceneManager()->addAnimatedMeshSceneNode(graphics->getSceneManager()->getMesh("res/models/planets/asteroid.x")); asteroids->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/roid.jpg")); asteroids->setPosition(vector3df(-20000,0,60000)); asteroids->setScale(vector3df(8,8,8)); } void CMainMenu::remove() { delete this; } //delete everything CMainMenu::~CMainMenu() { corona->remove(); cam->remove(); newgame->remove(); loadgame->remove(); options->remove(); quit->remove(); logo->remove(); nebula->remove(); asteroids->remove(); } //used in the graphics loop in order to detect if buttons were pressed gui::IGUIButton *CMainMenu::getNewButton() { return newgame; } gui::IGUIButton *CMainMenu::getLoadgame() { return loadgame; } gui::IGUIButton *CMainMenu::getOptions() { return options; } gui::IGUIButton *CMainMenu::getQuit() { return quit; }
#include "square.h" #include <cmath> #include <cassert> square::square(const point& p1, const point& p2, const point& p3, const point& p4): p1_(p1), p2_(p2), p3_(p3), p4_(p4) {} square::square(std::istream& is) { is >> p1_.x >> p1_.y >> p2_.x >> p2_.y >> p3_.x >> p3_.y >> p4_.x >> p4_.y; assert(((p2_.x - p1_.x)*(p4_.x - p1_.x))+((p2_.y - p1_.y)*(p4_.y - p1_.y)) == 0); assert(((p3_.x - p2_.x)*(p1_.x - p2_.x))+((p3_.y - p2_.y)*(p1_.y - p2_.y)) == 0); assert(((p4_.x - p3_.x)*(p2_.x - p3_.x))+((p4_.y - p3_.y)*(p2_.y - p3_.y)) == 0); assert((p2_.x - p1_.x) == (p1_.y - p4_.y)); assert((p3_.x - p2_.x) == (p2_.y - p1_.y)); assert((p4_.x - p3_.x) == (p3_.y - p2_.y)); } point square::center() { return {(p1_.x + p2_.x + p3_.x + p4_.x) * 0.25, (p1_.y + p2_.y + p3_.y + p4_.y) * 0.25}; } double square::area() { const double ds1 = p1_.x - p2_.x; const double ds2 = p4_.x - p1_.x; return std::abs(ds1 * ds1 + ds2 * ds2); } void square::print(std::ostream& os){ os << "Square [" << p1_ << "] [" << p2_ << "] [" << p3_ << "] [" << p4_ << "]"; }
# include <iostream> using namespace std; double convertTemp(double); void greet(void); int main() { //greet(); double fahrTemp, celsTemp; cout << "Enter today's temperature in Fahrenheit: "; cin >> fahrTemp; celsTemp = convertTemp(fahrTemp); //cout << "The converted Temperature in Celsius is: " << celsTemp << endl; printf("The converted Temperature in Celsius is: %.2f \n\n", celsTemp); system("pause"); return 0; } double convertTemp(double fahr) { //double f = (1.8 * c) + 32; //double c = (F - 32) / 1.8; return ((fahr - 32.0) / 1.8 ); }
/* https://www.codechef.com/OCT14/problems/CHEFGR/ */ #pragma warning(disable:4786) #define _CRT_SECURE_NO_WARNINGS #pragma comment(linker, "/stack:16777216") #include <bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(false); #define endl '\n' #define gc getchar_unlocked #define file freopen("iceparticle.in","r",stdin); #define terminate exit (EXIT_FAILURE) #define os_iterator ostream_iterator<data> screen(cout,endl) #define output(vec) copy(vec.begin(),vec.end(),screen) #define memory(dt,fill,length) memset ((dt),(fill),(length)) #define MAX int(1e9) + 7; #define timer 0 typedef vector<int> vec; typedef vector<vec> vvec; typedef long long ll; typedef vector<ll> vecll; typedef vector<vecll> vvecll; typedef char character; typedef int data; typedef pair<data, data> pint; typedef vector<pint> vpint; typedef float decimal; inline ll input() { register int c = gc(); ll x = 0; ll neg = 0; for(; ((c<48 || c>57) && c != '-'); c = gc()); if(c == '-') { neg = 1; c = gc(); } for(; c>47 && c<58 ; c = gc()) x = (x<<1) + (x<<3) + c - 48; return (neg)? -x:x; } inline void process() { int t=input(); int n,var; int m; int temp; while(t--) { n=input(); m=input(); vector<int> vec(n); int max=0; for( int i=0; i < n; i++){ vec.at(i)=input(); if(vec.at(i) > max) max=vec.at(i); } temp=0; for( int i=0; i< n; i++ ) temp+=max-vec.at(i); if(n==1) cout << "Yes" << endl; else if( m > temp) { var=(m-temp)%n; if(var == 0) cout << "Yes" << endl; else cout << "No" << endl; } else if(temp==m) cout << "Yes" << endl; else cout << "No" << endl; vec.clear(); } } int main (int argc, char * const argv[]) { if(timer) { decimal bios_memsize; clock_t execution; execution=clock(); process(); bios_memsize=(clock()-execution)/(decimal)CLOCKS_PER_SEC; printf("[%.4f] sec\n",bios_memsize); } process(); return 0; }
#include <iostream> #include <vector> #include <algorithm> #include <memory.h> using namespace std; int cnt = 0; //防止重复访问 bool visit[22][22]; bool DFS(char Perimeters[22][22], int clickX, int clickY) { if (!visit[clickX][clickY]) { visit[clickX][clickY] = true; if (Perimeters[clickX][clickY] != 'X') { //cnt++; return false; } else { //cnt = cnt + 4; //右上 DFS(Perimeters, clickX + 1, clickY + 1); DFS(Perimeters, clickX + 1, clickY - 1); DFS(Perimeters, clickX - 1, clickY + 1); DFS(Perimeters, clickX - 1, clickY - 1); //如果右边不存在,那么周长加一 if (!DFS(Perimeters, clickX + 1, clickY)) { //std::cout << clickX << ";" << clickY << std::endl; cnt++; } if (!DFS(Perimeters, clickX - 1, clickY)) { //std::cout << clickX << ";" << clickY << std::endl; cnt++; } if (!DFS(Perimeters, clickX, clickY + 1)) { //std::cout << clickX << ";" << clickY << std::endl; cnt++; } if (!DFS(Perimeters, clickX, clickY - 1)) { //std::cout << clickX << ";" << clickY << std::endl; cnt++; } return true; } } else { //如果已经被探测过,且不是X,返回false if (Perimeters[clickX][clickY] != 'X') { //cnt++; return false; } return true; } } int main() { int N, M, clickX, clickY; std::vector<int> result; while (true) { cnt = 0; char Perimeters[22][22]; memset(Perimeters, 0, sizeof(Perimeters)); memset(visit, false, sizeof(visit)); cin >> N >> M >> clickX >> clickY; if (N == 0 || M == 0) { break; } for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { cin >> Perimeters[i][j]; } } DFS(Perimeters, clickX, clickY); result.push_back(cnt); } for (int i = 0; i < result.size(); i++) { std::cout << result[i] << std::endl; } return 0; }
// Created by: DAUTRY Philippe // Copyright (c) 1997-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 _TDF_Transaction_HeaderFile #define _TDF_Transaction_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <TCollection_AsciiString.hxx> class TDF_Data; class TDF_Delta; //! This class offers services to open, commit or //! abort a transaction in a more secure way than //! using Data from TDF. If you forget to close a //! transaction, it will be automatically aborted at //! the destruction of this object, at the closure of //! its scope. //! //! In case of catching errors, the effect will be the //! same: aborting transactions until the good current //! one. class TDF_Transaction { public: DEFINE_STANDARD_ALLOC //! Creates an empty transaction context, unable to be //! opened. Standard_EXPORT TDF_Transaction(const TCollection_AsciiString& aName = ""); //! Creates a transaction context on <aDF>, ready to //! be opened. Standard_EXPORT TDF_Transaction(const Handle(TDF_Data)& aDF, const TCollection_AsciiString& aName = ""); //! Aborts all the transactions on <myDF> and sets //! <aDF> to build a transaction context on <aDF>, //! ready to be opened. Standard_EXPORT void Initialize (const Handle(TDF_Data)& aDF); //! If not yet done, opens a new transaction on //! <myDF>. Returns the index of the just opened //! transaction. //! //! It raises DomainError if the transaction is //! already open, and NullObject if there is no //! current Data framework. Standard_EXPORT Standard_Integer Open(); //! Commits the transactions until AND including the //! current opened one. Standard_EXPORT Handle(TDF_Delta) Commit (const Standard_Boolean withDelta = Standard_False); //! Aborts the transactions until AND including the //! current opened one. Standard_EXPORT void Abort(); ~TDF_Transaction() { Abort(); } //! Returns the Data from TDF. Handle(TDF_Data) Data() const; //! Returns the number of the transaction opened by <me>. Standard_Integer Transaction() const; //! Returns the transaction name. const TCollection_AsciiString& Name() const; //! Returns true if the transaction is open. Standard_Boolean IsOpen() const; //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; private: //! Private to avoid copy. TDF_Transaction(const TDF_Transaction& aTrans); TDF_Transaction& operator= (const TDF_Transaction& theOther); private: Handle(TDF_Data) myDF; TCollection_AsciiString myName; Standard_Integer myUntilTransaction; }; #include <TDF_Transaction.lxx> #endif // _TDF_Transaction_HeaderFile
#include "Scene.h" #include "SnowPlane.h" #include <API/Code/Graphics/Image/Image.h> #include <API/Code/Aero/Aero.h> Scene::Scene() : m_Ball( 0.1f, 50, 50 ), m_Lantern( "../../../Data/Projects/Snow/Lantern/Lantern.ply" ), m_MooMoo( "../../../Data/Projects/Snow/MooMoo/spot_triangulated.obj" ), m_MooMooTexture( "../../../Data/Projects/Snow/MooMoo/spot_texture.png" ), m_FenceBack( "../../../Data/Projects/Snow/Fence/Fence.ply" ), m_FenceLeft( "../../../Data/Projects/Snow/Fence/Fence.ply" ), m_LeftBoot( "../../../Data/Projects/Snow/Boots/LeftBoot.obj" ), m_RightBoot( "../../../Data/Projects/Snow/Boots/RightBoot.obj" ), m_BootsTrajectoryLeft( { { 0.8f, 0.27f, 0.7f }, { 0.6f, 0.34f, 0.7f }, { 0.4f, 0.27f, 0.7f }, { 0.2f, 0.34f, 0.7f }, { 0.0f, 0.27f, 0.7f }, { -0.2f, 0.34f, 0.7f }, { -0.4f, 0.27f, 0.7f }, { -0.6f, 0.34f, 0.7f }, { -0.8f, 0.27f, 0.7f } }, { { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f } } ), m_BootsTrajectoryRight( { { 0.8f, 0.34f, 0.7f }, { 0.6f, 0.27f, 0.7f }, { 0.4f, 0.34f, 0.7f }, { 0.2f, 0.27f, 0.7f }, { 0.0f, 0.34f, 0.7f }, { -0.2f, 0.27f, 0.7f }, { -0.4f, 0.34f, 0.7f }, { -0.6f, 0.27f, 0.7f }, { -0.8f, 0.34f, 0.7f } }, { { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.4f, 0.0f, 0.0f } } ), m_BootsAnimTime( 0.0f ), m_BootsAnimTotalTime( 10.0f ) { m_ObjectsMat.SetName( "Objects Mat" ); m_ObjectsMat.GetRoughness().SetValue( 1.0f ); m_ObjectsMat.GetApplyGammaCorrection().SetValue( False ); m_ObjectsMat.GetAmbientOcclusion().SetValue( 1.0f ); m_ObjectsMat.GetAmbientStrength().SetValue( 0.015f ); m_Ball.SetName( "Ball" ); m_Ball.SetMaterial( m_ObjectsMat ); m_Ball.SetPosition( 0.0f, 0.32f, 0.0f ); m_Ball.SetBlendMode( ae::BlendMode::BlendNone ); m_Lantern.SetName( "Lantern" ); m_Lantern.SetMaterial( m_ObjectsMat ); m_Lantern.SetPosition( -0.8f, 0.2f, -0.8f ); m_Lantern.SetScale( 0.4f, 0.4f, 0.4f ); m_Lantern.SetBlendMode( ae::BlendMode::BlendNone ); m_MooMoo.SetName( "Moo Moo" ); m_MooMoo.SetPosition( -0.55f, 0.42f, -0.7f ); m_MooMoo.SetRotation( 0.0f, ae::Math::Pi(), 0.0f ); m_MooMoo.Scale( 0.2f, 0.2f, 0.2f ); m_MooMoo.SetBlendMode( ae::BlendMode::BlendNone ); m_MooMoo.GetMaterial().GetParameter<ae::ShaderParameterTextureBool>( ae::Material::DefaultParameters::DiffuseTexture )->SetTexture( &m_MooMooTexture ); m_FenceBack.SetName( "Fence Back" ); m_FenceBack.SetPosition( 0.0f, 0.2f, -0.8f ); m_FenceBack.SetScale( 0.4f, 0.4f, 0.4f ); m_FenceBack.SetMaterial( m_ObjectsMat ); m_FenceBack.SetBlendMode( ae::BlendMode::BlendNone ); m_FenceLeft.SetName( "Fence Left" ); m_FenceLeft.SetPosition( -0.8f, 0.2f, 0.0f ); m_FenceLeft.SetRotation( 0.0f, ae::Math::PiDivBy2(), 0.0f ); m_FenceLeft.SetScale( 0.4f, 0.4f, 0.4f ); m_FenceLeft.SetMaterial( m_ObjectsMat ); m_FenceLeft.SetBlendMode( ae::BlendMode::BlendNone ); m_LeftBoot.SetName( "Left Boot" ); m_LeftBoot.SetScale( 0.05f, 0.05f, 0.05f ); m_LeftBoot.SetPosition( 0.8f, 0.29f, 0.8f ); m_LeftBoot.SetBlendMode( ae::BlendMode::BlendNone ); m_RightBoot.SetName( "Right Boot" ); m_RightBoot.SetScale( 0.05f, 0.05f, 0.05f ); m_RightBoot.SetPosition( 0.8f, 0.29f, 0.8f ); m_RightBoot.SetBlendMode( ae::BlendMode::BlendNone ); m_LanternLight.SetName( "Lantern Light" ); m_LanternLight.SetRadius( 1.5f ); m_LanternLight.SetIntensity( 1.5f ); m_LanternLight.SetColor( ae::Color( 0.922f, 0.870f, 0.483f ) ); m_AmbientLight.SetName( "Ambient Light" ); m_AmbientLight.SetRotation( ae::Math::DegToRad_Const( 130.0f ), 0.0f, 0.0f ); m_AmbientLight.SetIntensity( 0.8f ); m_AmbientLight.SetColor( ae::Color( 0.8f, 0.619f, 0.662f ) ); } void Scene::RenderDepthPass( ae::Renderer& _Renderer, const ae::Material& _DepthMaterial, ae::Camera& _Camera ) { _Renderer.Draw( m_Ball, _DepthMaterial, &_Camera ); _Renderer.Draw( m_Lantern, _DepthMaterial, &_Camera ); _Renderer.Draw( m_MooMoo, _DepthMaterial, &_Camera ); _Renderer.Draw( m_FenceBack, _DepthMaterial, &_Camera ); _Renderer.Draw( m_FenceLeft, _DepthMaterial, &_Camera ); _Renderer.Draw( m_LeftBoot, _DepthMaterial, &_Camera ); _Renderer.Draw( m_RightBoot, _DepthMaterial, &_Camera ); } void Scene::RenderColorPass( ae::Renderer& _Renderer ) { if( m_LanternLight.IsEnabled() ) { m_LanternLight.SetPosition( m_Lantern.GetPosition() + ae::Vector3( 0.0f, 0.7f, 0.0f ) ); m_LanternLight.SetEnabled( False ); _Renderer.Draw( m_Lantern ); m_LanternLight.SetEnabled( True ); } else _Renderer.Draw( m_Lantern ); _Renderer.Draw( m_Ball ); _Renderer.Draw( m_MooMoo ); _Renderer.Draw( m_FenceBack ); _Renderer.Draw( m_FenceLeft ); _Renderer.Draw( m_LeftBoot ); _Renderer.Draw( m_RightBoot ); } void Scene::UpdateBootsAnim() { m_BootsAnimTime += Aero.GetDeltaTime(); m_BootsAnimTime = ae::Math::Modulo( m_BootsAnimTime, m_BootsAnimTotalTime ); float InterpParam = ae::Math::Remap( m_BootsAnimTime, 0.0f, m_BootsAnimTotalTime, m_BootsTrajectoryLeft.GetTimeMin(), m_BootsTrajectoryLeft.GetTimeMax() ); m_LeftBoot.SetPosition( m_BootsTrajectoryLeft.GetPointAtParam( InterpParam ) ); m_RightBoot.SetPosition( m_BootsTrajectoryRight.GetPointAtParam( InterpParam ) ); }
// Created on: 1995-06-13 // Created by: Jacques GOUSSARD // Copyright (c) 1995-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 _BRepFeat_StatusError_HeaderFile #define _BRepFeat_StatusError_HeaderFile //! Describes the error. enum BRepFeat_StatusError { BRepFeat_OK, BRepFeat_BadDirect, BRepFeat_BadIntersect, BRepFeat_EmptyBaryCurve, BRepFeat_EmptyCutResult, BRepFeat_FalseSide, BRepFeat_IncDirection, BRepFeat_IncSlidFace, BRepFeat_IncParameter, BRepFeat_IncTypes, BRepFeat_IntervalOverlap, BRepFeat_InvFirstShape, BRepFeat_InvOption, BRepFeat_InvShape, BRepFeat_LocOpeNotDone, BRepFeat_LocOpeInvNotDone, BRepFeat_NoExtFace, BRepFeat_NoFaceProf, BRepFeat_NoGluer, BRepFeat_NoIntersectF, BRepFeat_NoIntersectU, BRepFeat_NoParts, BRepFeat_NoProjPt, BRepFeat_NotInitialized, BRepFeat_NotYetImplemented, BRepFeat_NullRealTool, BRepFeat_NullToolF, BRepFeat_NullToolU }; #endif // _BRepFeat_StatusError_HeaderFile
#ifndef DNA_ANALYZER_PROJECT_HELP_H #define DNA_ANALYZER_PROJECT_HELP_H #include "Icommand.h" class Help:public IcontrolCommands { public: /*virtual*/~Help(){} /*virtual*/std::string run(Iwriter &writer, Ireader& reader, dataDNA& containerDna, const Paramcommand& param); static void initializeMapAbout(); private: static std::map<std::string, std::string> m_mapAbout; bool isValid(const Paramcommand& param); }; #endif //DNA_ANALYZER_PROJECT_HELP_H
// Author: WangZhan -> wangzhan.1985@gmail.com #pragma once class ScopedHandle { public: ScopedHandle() : m_handle(NULL) {} ScopedHandle(HANDLE handle) : m_handle(handle) {} ~ScopedHandle() { if (m_handle) { CloseHandle(m_handle); m_handle = NULL; } } operator HANDLE () { return m_handle; } void Set(HANDLE handle) { m_handle = handle; } HANDLE Get() const { return m_handle; } private: HANDLE m_handle; };
// Generated from D:/4IF/PLD-COMP/Compilateur01\fichierAntlr.g4 by ANTLR 4.7 #pragma once #include "antlr4-runtime.h" class fichierAntlrParser : public antlr4::Parser { public: enum { T__0 = 1, T__1 = 2, T__2 = 3, T__3 = 4, T__4 = 5, T__5 = 6, T__6 = 7, T__7 = 8, T__8 = 9, T__9 = 10, T__10 = 11, T__11 = 12, T__12 = 13, T__13 = 14, T__14 = 15, T__15 = 16, T__16 = 17, T__17 = 18, T__18 = 19, T__19 = 20, T__20 = 21, T__21 = 22, T__22 = 23, T__23 = 24, T__24 = 25, T__25 = 26, T__26 = 27, T__27 = 28, T__28 = 29, T__29 = 30, T__30 = 31, T__31 = 32, T__32 = 33, T__33 = 34, T__34 = 35, T__35 = 36, T__36 = 37, T__37 = 38, T__38 = 39, T__39 = 40, T__40 = 41, T__41 = 42, T__42 = 43, T__43 = 44, T__44 = 45, T__45 = 46, T__46 = 47, T__47 = 48, T__48 = 49, Include = 50, EspaceBlanc = 51, CommentaireBlock = 52, CommentaireLigne = 53, NOM = 54, LETTRE = 55, CHIFFRE = 56, NOMBRE = 57, CHAR = 58, SYMBOLE = 59 }; enum { RuleProgramme = 0, RuleMain = 1, RuleFonction = 2, RuleParametre = 3, RuleVariable = 4, RuleAffectation = 5, RuleExpr = 6, RuleReturn_ = 7, RuleBreak_ = 8, RuleInstruction = 9, RuleBloc = 10, RuleDeclaration = 11, RuleStructure_if = 12, RuleElse_ = 13, RuleStructure_while = 14, RuleType_var = 15, RuleType_fonction = 16 }; fichierAntlrParser(antlr4::TokenStream *input); ~fichierAntlrParser(); virtual std::string getGrammarFileName() const override; virtual const antlr4::atn::ATN& getATN() const override { return _atn; }; virtual const std::vector<std::string>& getTokenNames() const override { return _tokenNames; }; // deprecated: use vocabulary instead. virtual const std::vector<std::string>& getRuleNames() const override; virtual antlr4::dfa::Vocabulary& getVocabulary() const override; class ProgrammeContext; class MainContext; class FonctionContext; class ParametreContext; class VariableContext; class AffectationContext; class ExprContext; class Return_Context; class Break_Context; class InstructionContext; class BlocContext; class DeclarationContext; class Structure_ifContext; class Else_Context; class Structure_whileContext; class Type_varContext; class Type_fonctionContext; class ProgrammeContext : public antlr4::ParserRuleContext { public: ProgrammeContext(antlr4::ParserRuleContext *parent, size_t invokingState); ProgrammeContext() : antlr4::ParserRuleContext() { } void copyFrom(ProgrammeContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Programme_normalContext : public ProgrammeContext { public: Programme_normalContext(ProgrammeContext *ctx); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); std::vector<FonctionContext *> fonction(); FonctionContext* fonction(size_t i); std::vector<MainContext *> main(); MainContext* main(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; ProgrammeContext* programme(); class MainContext : public antlr4::ParserRuleContext { public: MainContext(antlr4::ParserRuleContext *parent, size_t invokingState); MainContext() : antlr4::ParserRuleContext() { } void copyFrom(MainContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Main_parametrevoidContext : public MainContext { public: Main_parametrevoidContext(MainContext *ctx); Type_fonctionContext *type_fonction(); BlocContext *bloc(); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Main_sansparametreContext : public MainContext { public: Main_sansparametreContext(MainContext *ctx); Type_fonctionContext *type_fonction(); BlocContext *bloc(); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Main_avecparametreContext : public MainContext { public: Main_avecparametreContext(MainContext *ctx); Type_fonctionContext *type_fonction(); ParametreContext *parametre(); BlocContext *bloc(); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; MainContext* main(); class FonctionContext : public antlr4::ParserRuleContext { public: FonctionContext(antlr4::ParserRuleContext *parent, size_t invokingState); FonctionContext() : antlr4::ParserRuleContext() { } void copyFrom(FonctionContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Fonction_avecparametreContext : public FonctionContext { public: Fonction_avecparametreContext(FonctionContext *ctx); Type_fonctionContext *type_fonction(); antlr4::tree::TerminalNode *NOM(); ParametreContext *parametre(); BlocContext *bloc(); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Fonction_parametrevoidContext : public FonctionContext { public: Fonction_parametrevoidContext(FonctionContext *ctx); Type_fonctionContext *type_fonction(); antlr4::tree::TerminalNode *NOM(); BlocContext *bloc(); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Fonction_sansparametreContext : public FonctionContext { public: Fonction_sansparametreContext(FonctionContext *ctx); Type_fonctionContext *type_fonction(); antlr4::tree::TerminalNode *NOM(); BlocContext *bloc(); std::vector<DeclarationContext *> declaration(); DeclarationContext* declaration(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; FonctionContext* fonction(); class ParametreContext : public antlr4::ParserRuleContext { public: ParametreContext(antlr4::ParserRuleContext *parent, size_t invokingState); ParametreContext() : antlr4::ParserRuleContext() { } void copyFrom(ParametreContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Parametre_tableauContext : public ParametreContext { public: Parametre_tableauContext(ParametreContext *ctx); Type_varContext *type_var(); antlr4::tree::TerminalNode *NOM(); antlr4::tree::TerminalNode *CHIFFRE(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Parametre_normalContext : public ParametreContext { public: Parametre_normalContext(ParametreContext *ctx); Type_varContext *type_var(); antlr4::tree::TerminalNode *NOM(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; ParametreContext* parametre(); class VariableContext : public antlr4::ParserRuleContext { public: VariableContext(antlr4::ParserRuleContext *parent, size_t invokingState); VariableContext() : antlr4::ParserRuleContext() { } void copyFrom(VariableContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Variable_simpleContext : public VariableContext { public: Variable_simpleContext(VariableContext *ctx); antlr4::tree::TerminalNode *NOM(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Variable_tableauContext : public VariableContext { public: Variable_tableauContext(VariableContext *ctx); antlr4::tree::TerminalNode *NOM(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; VariableContext* variable(); class AffectationContext : public antlr4::ParserRuleContext { public: AffectationContext(antlr4::ParserRuleContext *parent, size_t invokingState); AffectationContext() : antlr4::ParserRuleContext() { } void copyFrom(AffectationContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Affectation_plusegalContext : public AffectationContext { public: Affectation_plusegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_plusplusavantContext : public AffectationContext { public: Affectation_plusplusavantContext(AffectationContext *ctx); VariableContext *variable(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_ouegalContext : public AffectationContext { public: Affectation_ouegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_supegalContext : public AffectationContext { public: Affectation_supegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_plusplusapresContext : public AffectationContext { public: Affectation_plusplusapresContext(AffectationContext *ctx); VariableContext *variable(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_divegalContext : public AffectationContext { public: Affectation_divegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_foisegalContext : public AffectationContext { public: Affectation_foisegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_moinsmoinsapresContext : public AffectationContext { public: Affectation_moinsmoinsapresContext(AffectationContext *ctx); VariableContext *variable(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_pourcentegalContext : public AffectationContext { public: Affectation_pourcentegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_egalContext : public AffectationContext { public: Affectation_egalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_etegalContext : public AffectationContext { public: Affectation_etegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_moinsmoinsavantContext : public AffectationContext { public: Affectation_moinsmoinsavantContext(AffectationContext *ctx); VariableContext *variable(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_infegalContext : public AffectationContext { public: Affectation_infegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Affectation_moinsegalContext : public AffectationContext { public: Affectation_moinsegalContext(AffectationContext *ctx); VariableContext *variable(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; AffectationContext* affectation(); class ExprContext : public antlr4::ParserRuleContext { public: ExprContext(antlr4::ParserRuleContext *parent, size_t invokingState); ExprContext() : antlr4::ParserRuleContext() { } void copyFrom(ExprContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Expr_infegalContext : public ExprContext { public: Expr_infegalContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_nombreContext : public ExprContext { public: Expr_nombreContext(ExprContext *ctx); antlr4::tree::TerminalNode *NOMBRE(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_diffegalContext : public ExprContext { public: Expr_diffegalContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_vagueContext : public ExprContext { public: Expr_vagueContext(ExprContext *ctx); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_etContext : public ExprContext { public: Expr_etContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_infContext : public ExprContext { public: Expr_infContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_parentheseContext : public ExprContext { public: Expr_parentheseContext(ExprContext *ctx); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_additionContext : public ExprContext { public: Expr_additionContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_ouContext : public ExprContext { public: Expr_ouContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_supContext : public ExprContext { public: Expr_supContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_etetContext : public ExprContext { public: Expr_etetContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_infinfContext : public ExprContext { public: Expr_infinfContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_fonctionContext : public ExprContext { public: Expr_fonctionContext(ExprContext *ctx); antlr4::tree::TerminalNode *NOM(); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_charContext : public ExprContext { public: Expr_charContext(ExprContext *ctx); antlr4::tree::TerminalNode *CHAR(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_egalegalContext : public ExprContext { public: Expr_egalegalContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_chiffreContext : public ExprContext { public: Expr_chiffreContext(ExprContext *ctx); antlr4::tree::TerminalNode *CHIFFRE(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_variableContext : public ExprContext { public: Expr_variableContext(ExprContext *ctx); VariableContext *variable(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_ououContext : public ExprContext { public: Expr_ououContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_divisionContext : public ExprContext { public: Expr_divisionContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_modContext : public ExprContext { public: Expr_modContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_supegalContext : public ExprContext { public: Expr_supegalContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_soustractionContext : public ExprContext { public: Expr_soustractionContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_affectationContext : public ExprContext { public: Expr_affectationContext(ExprContext *ctx); AffectationContext *affectation(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_exclamationContext : public ExprContext { public: Expr_exclamationContext(ExprContext *ctx); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_multiplicationContext : public ExprContext { public: Expr_multiplicationContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_supsupContext : public ExprContext { public: Expr_supsupContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Expr_chapeauContext : public ExprContext { public: Expr_chapeauContext(ExprContext *ctx); std::vector<ExprContext *> expr(); ExprContext* expr(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; ExprContext* expr(); ExprContext* expr(int precedence); class Return_Context : public antlr4::ParserRuleContext { public: Return_Context(antlr4::ParserRuleContext *parent, size_t invokingState); Return_Context() : antlr4::ParserRuleContext() { } void copyFrom(Return_Context *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Return_normalContext : public Return_Context { public: Return_normalContext(Return_Context *ctx); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Return_Context* return_(); class Break_Context : public antlr4::ParserRuleContext { public: Break_Context(antlr4::ParserRuleContext *parent, size_t invokingState); Break_Context() : antlr4::ParserRuleContext() { } void copyFrom(Break_Context *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Break_normalContext : public Break_Context { public: Break_normalContext(Break_Context *ctx); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Break_Context* break_(); class InstructionContext : public antlr4::ParserRuleContext { public: InstructionContext(antlr4::ParserRuleContext *parent, size_t invokingState); InstructionContext() : antlr4::ParserRuleContext() { } void copyFrom(InstructionContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Instruction_exprContext : public InstructionContext { public: Instruction_exprContext(InstructionContext *ctx); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Instruction_whileContext : public InstructionContext { public: Instruction_whileContext(InstructionContext *ctx); Structure_whileContext *structure_while(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Instruction_returnContext : public InstructionContext { public: Instruction_returnContext(InstructionContext *ctx); Return_Context *return_(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Instruction_breakContext : public InstructionContext { public: Instruction_breakContext(InstructionContext *ctx); Break_Context *break_(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Instruction_ifContext : public InstructionContext { public: Instruction_ifContext(InstructionContext *ctx); Structure_ifContext *structure_if(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; InstructionContext* instruction(); class BlocContext : public antlr4::ParserRuleContext { public: BlocContext(antlr4::ParserRuleContext *parent, size_t invokingState); BlocContext() : antlr4::ParserRuleContext() { } void copyFrom(BlocContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Bloc_normalContext : public BlocContext { public: Bloc_normalContext(BlocContext *ctx); std::vector<InstructionContext *> instruction(); InstructionContext* instruction(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; BlocContext* bloc(); class DeclarationContext : public antlr4::ParserRuleContext { public: DeclarationContext(antlr4::ParserRuleContext *parent, size_t invokingState); DeclarationContext() : antlr4::ParserRuleContext() { } void copyFrom(DeclarationContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Declaration_tableauContext : public DeclarationContext { public: Declaration_tableauContext(DeclarationContext *ctx); Type_varContext *type_var(); antlr4::tree::TerminalNode *NOM(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Declaration_definitionContext : public DeclarationContext { public: Declaration_definitionContext(DeclarationContext *ctx); Type_varContext *type_var(); antlr4::tree::TerminalNode *NOM(); ExprContext *expr(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Declaration_normaleContext : public DeclarationContext { public: Declaration_normaleContext(DeclarationContext *ctx); Type_varContext *type_var(); std::vector<antlr4::tree::TerminalNode *> NOM(); antlr4::tree::TerminalNode* NOM(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Declaration_definitiontableau_charContext : public DeclarationContext { public: Declaration_definitiontableau_charContext(DeclarationContext *ctx); Type_varContext *type_var(); antlr4::tree::TerminalNode *NOM(); ExprContext *expr(); std::vector<antlr4::tree::TerminalNode *> CHAR(); antlr4::tree::TerminalNode* CHAR(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; class Declaration_definitiontableau_nombreContext : public DeclarationContext { public: Declaration_definitiontableau_nombreContext(DeclarationContext *ctx); Type_varContext *type_var(); antlr4::tree::TerminalNode *NOM(); ExprContext *expr(); std::vector<antlr4::tree::TerminalNode *> NOMBRE(); antlr4::tree::TerminalNode* NOMBRE(size_t i); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; DeclarationContext* declaration(); class Structure_ifContext : public antlr4::ParserRuleContext { public: Structure_ifContext(antlr4::ParserRuleContext *parent, size_t invokingState); Structure_ifContext() : antlr4::ParserRuleContext() { } void copyFrom(Structure_ifContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Structureif_normalContext : public Structure_ifContext { public: Structureif_normalContext(Structure_ifContext *ctx); ExprContext *expr(); Else_Context *else_(); BlocContext *bloc(); InstructionContext *instruction(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Structure_ifContext* structure_if(); class Else_Context : public antlr4::ParserRuleContext { public: Else_Context(antlr4::ParserRuleContext *parent, size_t invokingState); Else_Context() : antlr4::ParserRuleContext() { } void copyFrom(Else_Context *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Else_normalContext : public Else_Context { public: Else_normalContext(Else_Context *ctx); BlocContext *bloc(); InstructionContext *instruction(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Else_Context* else_(); class Structure_whileContext : public antlr4::ParserRuleContext { public: Structure_whileContext(antlr4::ParserRuleContext *parent, size_t invokingState); Structure_whileContext() : antlr4::ParserRuleContext() { } void copyFrom(Structure_whileContext *context); using antlr4::ParserRuleContext::copyFrom; virtual size_t getRuleIndex() const override; }; class Structurewhile_normalContext : public Structure_whileContext { public: Structurewhile_normalContext(Structure_whileContext *ctx); ExprContext *expr(); BlocContext *bloc(); InstructionContext *instruction(); virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Structure_whileContext* structure_while(); class Type_varContext : public antlr4::ParserRuleContext { public: Type_varContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Type_varContext* type_var(); class Type_fonctionContext : public antlr4::ParserRuleContext { public: Type_fonctionContext(antlr4::ParserRuleContext *parent, size_t invokingState); virtual size_t getRuleIndex() const override; virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override; }; Type_fonctionContext* type_fonction(); virtual bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override; bool exprSempred(ExprContext *_localctx, size_t predicateIndex); private: static std::vector<antlr4::dfa::DFA> _decisionToDFA; static antlr4::atn::PredictionContextCache _sharedContextCache; static std::vector<std::string> _ruleNames; static std::vector<std::string> _tokenNames; static std::vector<std::string> _literalNames; static std::vector<std::string> _symbolicNames; static antlr4::dfa::Vocabulary _vocabulary; static antlr4::atn::ATN _atn; static std::vector<uint16_t> _serializedATN; struct Initializer { Initializer(); }; static Initializer _init; };
#pragma once #include <QNetworkReply> #include <QNetworkRequest> #include <QObject> #include <QSslConfiguration> #include <QJsonObject> #include "RequestType.h" /** * @brief Класс обеспечивает Rest API * * Реализация взята с https://habrahabr.ru/post/314932/ */ class Requester : public QObject { Q_OBJECT public: Requester(const QString& host = "localhost", uint port = 5432, QSslConfiguration *sslConfiguration = nullptr); virtual ~Requester() noexcept; /** * @brief Метод инициализирует объект класса * @param host - адрес хоста * @param port - номер порта * @param sslConfiguration - ssl конфигурация для доступа по https */ void init(const QString& host, uint port, QSslConfiguration *sslConfiguration = nullptr); /** * @brief Метод отправляет запрос на сервер * @param api - API запроса * @param type - тип запроса * @param json - отправляемый объект в формате JSON */ void sendRequest(const QString &api, RequestType type = RequestType::GET, const QJsonObject &json = QJsonObject()); signals: void success(const QJsonObject &response); void success(const QJsonArray &response); void success(); void failure(const QString &errorString); private slots: void onReplyReceived(QNetworkReply *reply); private: QNetworkRequest createRequest(const QString &apiStr); QNetworkReply* sendCustomRequest(QNetworkRequest &request, const QString &type, const QByteArray &byteArray); struct Implementation; Implementation *pimpl; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; -*- ** ** Copyright (C) 2002-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifdef UPNP_SUPPORT #ifndef UPNP_UTIL_H_ #define UPNP_UTIL_H_ #include "modules/upnp/upnp_references.h" // Keeps track of the last error; REMEMBER to initialize ops to OpStatus::OK! #define LAST_ERROR(ops, call) { OP_STATUS ops_new=call; if(OpStatus::IsError(ops_new)) ops=ops_new; } // Search type used for discovering IGD devices, like routers #define UPNP_DISCOVERY_IGD_SEARCH_TYPE "urn:schemas-upnp-org:device:InternetGatewayDevice:1" // Search type used for discovering every root device, like routers #define UPNP_DISCOVERY_ROOT_SEARCH_TYPE "upnp:rootdevice" // Search type used for discovering an Opera Unite device #define UPNP_DISCOVERY_OPERA_SEARCH_TYPE "urn:opera-com:device:OperaUnite:1" // Search type used for discovering an Opera Dragonfly instance #define UPNP_DISCOVERY_DRAGONFLY_SEARCH_TYPE "urn:opera-com:device:OperaDragonfly:1" // IGD Discovery message (always the same): port 1900, UDP address 239.255.255.250 //#define UPNP_DISCOVERY_IGD_MESSAGE "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nST:urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\nMAN:\"ssdp:discover\"\r\nMX:3\r\nUser-Agent:Opera Unite\r\n\r\n" // IGD Discovery message (always the same): port 1900, UDP address 239.255.255.250 //#define UPNP_DISCOVERY_UNITE_MESSAGE "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nST:urn:opera-com:device:OperaUnite:1\r\nMAN:\"ssdp:discover\"\r\nMX:3\r\nUser-Agent:Opera Unite\r\n\r\n" // Root Device Discovery message (always the same): port 1900, UDP address 239.255.255.250 //#define UPNP_DISCOVERY_ROOT_MESSAGE "M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nST:upnp:rootdevice\r\nMAN:\"ssdp:discover\"\r\nMX:3\r\nUser-Agent:Opera Unite\r\n\r\n" // IGD Discovery Address #define UPNP_DISCOVERY_ADDRESS UNI_L("239.255.255.250") // IGD Discovery Port #define UPNP_DISCOVERY_PORT 1900 // IGD Service urn of WANIPConnection #define UPNP_WANIPCONNECTION UNI_L("urn:schemas-upnp-org:service:WANIPConnection:1") // IGD Service urn of WANPPPConnection #define UPNP_WANPPPCONNECTION UNI_L("urn:schemas-upnp-org:service:WANPPPConnection:1") // Lease duration of the port mapping entries (0 means forever) #define UPNP_PORT_MAPPING_LEASE 0/*(7*86400)*/ // Time (ms) that needs to be passed after a succesfull descrption phase before trying another one (UPnP sends a lot of NOTIFY messages at the same time, so we don't want to try subsequent ones) #define UPNP_NOTIFY_THRESHOLD_MS 10000 // Time (ms) that needs to be passed after an M-SEARCH before answering again #define UPNP_MSEARCH_THRESHOLD_MS 1500 // Time (ms) to wait before checking the number of the network cards (0== disabled) #define DELAY_NETWORK_CARD_CHECK_MS 60000 // Time (ms) to wait before retry to open the port (0== disabled) #define DELAY_REPROCESS_UPNP 0 /*1800000*/ // Time (ms) to wait before signaling that no UPnP devices are present (UPnP specifications talks about 3 seconds) (0== disabled) #define DELAY_UPNP_TIMEOUT 3000 // Time between periodic advertises (12 minutes, 30 minutes is the advertised period) (0== disabled) #ifdef _DEBUG #define DELAY_UPNP_ADVERTISE 30000 /*1800000*/ #else #define DELAY_UPNP_ADVERTISE 720000 #endif // Delay between every attempt of the first advertise #define DELAY_FIRST_ADVERTISE 3000 #ifdef _DEBUG // Time between checks to remove expired devices #define UPNP_DEVICE_EXPIRE_CHECK_MS 30000 // Postpone the first check (UPnP ask for at least 1800 seconds, so we can wait a bit before start) // 0 turn off the check #define DELAY_UPNP_FIRST_EXPIRE_CHECK_MS 15000 #else // Time between checks to remove expired devices #define UPNP_DEVICE_EXPIRE_CHECK_MS 300000 // Postpone the first check (UPnP ask for at least 1800 seconds, so we can wait a bit before start) // 0 turn off the check #define DELAY_UPNP_FIRST_EXPIRE_CHECK_MS 1200000 #endif // UPnP Namespace #define _XML_ATT_XMLNS_ UNI_L("urn:schemas-upnp-org:device-1-0"), NULL, // Message sent to verify the NetworkCards #define MSG_UPNP_CHECK_NETWORK_CARDS 1 // Message sent to redo the UPnP process #define MSG_UPNP_RECONNECT 2 // Timeout: check if there are UPnP devices #define MSG_UPNP_TIMEOUT 3 // Periodic advertise #define MSG_UPNP_SERVICES_ADVERTISE 4 // First advertise #define MSG_UPNP_FIRST_SERVICES_ADVERTISE 5 // Used to delay the notification of a Services provider #define MSG_UPNP_BROADCAST_NOTIFY 6 // Check if some devices are expired #define MSG_UPNP_CHECK_EXPIRE 7 /// Private key common to every instance of Opera, used to "authenticate" devices. /// This is a temporary solution to the Authentication problem // FIXME: generate an SSL certificate for every widget and add HTTPS #define UPNP_OPERA_PRIVATE_KEY "_OUPK_*&^%!@9#$s4'" /** Identify the search target requested on a M-SEARCH message */ enum SearchTargetMode { /** Search for upnp:rootdevice*/ SearchRootDevice, /** Search for the DeviceType (class of devices) */ SearchDeviceType, /** Search for the exact device */ SearchUUID, /** No match for this device */ SearchNoMatch }; /** Identify how much we can trust the identity of an Opera Instance discovered with UPnP */ enum TrustLevel { /** The Unite Instance tried to authenticate but was unable. It's probably an hack attempt, so it will be removed */ TRUST_ERROR, /** The level of trust is unknown (this is a temporary state) */ TRUST_UNKNOWN, /** This program did not answer to challenge: old snapshot of Unite? */ TRUST_UNTRUSTED, /** This is the normale level of trust for Unite 1.0 (the private key is UPNP_OPERA_PRIVATE_KEY) */ TRUST_PRIVATE_KEY, /** This level is not available now. Among other things, it requires Unite to have a different certificate for each installation */ TRUST_CERTIFICATE }; // Debug modes, used to simulate missing capabilities enum UPNPDebugModes { UPNP_DBG_NO_ROUTED=1, UPNP_DBG_NO_NAT=2, UPNP_DBG_NO_IP_CONN=4, UPNP_DBG_NO_PPP_CONN=8, UPNP_DBG_NO_PORT=16, UPNP_DBG_NO_ROUTED2=32, UPNP_DBG_NO_NAT2=64 }; // Error codes for UPnP class UPnPStatus: public OpStatus { public: enum { ERROR_UDP_SOCKET_ADDRESS_NOT_CREATED = USER_ERROR + 0, ERROR_UDP_SOCKET_NOT_CREATED = USER_ERROR + 1, ERROR_UDP_SOCKET_ADDRESS_ERROR = USER_ERROR + 2, ERROR_UDP_CONNECTION_FAILED = USER_ERROR + 3, ERROR_UDP_BIND_FAILED = USER_ERROR + 4, ERROR_UDP_SEND_FAILED = USER_ERROR + 5, ERROR_TCP_WRONGDEVICE = USER_ERROR + 100, ERROR_TCP_LOAD_DESCRIPTION_FAILED = USER_ERROR + 101 }; }; // Reason to start the port opening process (mainly for debugging purposes) enum UDPReason { // Unknown reason UDP_REASON_UNDEFINED=0, // A new IGD device has been discovered UDP_REASON_DISCOVERY=1, // The location has changed UDP_REASON_SSDP_ALIVE_LOCATION=2, // A new ssdp:alive message, after that the threshold time is expired UDP_REASON_SSDP_ALIVE_THRESHOLD=3, // The device is no longer available UDP_REASON_SSDP_BYEBYE=4, }; #endif #endif
// Copyright (c) 2016 peposso All Rights Reserved. // Released under the MIT license #pragma once #include <sys/stat.h> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <algorithm> #include <iterator> #include <vector> #include <tuple> #include <atomic> #include <mutex> #include <list> #include <unordered_map> #include <clocale> #include <utility> #include <memory> #ifdef _WIN32 #include <windows.h> #include <wincon.h> #endif #include <boost/optional.hpp> // NOLINT // macros #define XLSXCONVERTER_UTILS_DISABLE_ANY(...) \ xlsxconverter::utils::enable_if_t< \ !xlsxconverter::utils::anytypeof<__VA_ARGS__>::value> = nullptr #define XLSXCONVERTER_UTILS_ENABLE_ANY(...) \ xlsxconverter::utils::enable_if_t< \ xlsxconverter::utils::anytypeof<__VA_ARGS__>::value> = nullptr #define XLSXCONVERTER_UTILS_EXCEPTION(...) \ xlsxconverter::utils::exception( \ __VA_ARGS__, "\n at ", __FILE__, ':', __LINE__, " in ", __func__) namespace xlsxconverter { namespace utils { template<bool B, class T, class F> using conditional_t = typename std::conditional<B, T, F>::type; template<bool B> using enable_if_t = typename std::enable_if<B, std::nullptr_t>::type; template<size_t I, class T> using tuple_element_t = typename std::tuple_element<I, T>::type; template<class T, class Tuple, size_t I> struct anytypeof_ { static const bool value = std::is_same<T, tuple_element_t<I, Tuple>>::value ? true : anytypeof_<T, Tuple, I-1>::value; }; template<class T, class Tuple> struct anytypeof_<T, Tuple, 0> { static const bool value = std::is_same<T, tuple_element_t<0, Tuple>>::value; }; template<class T, class...A> struct anytypeof : anytypeof_<T, std::tuple<A...> , sizeof...(A)-1> {}; inline std::vector<std::string> split(const std::string& str, char delim) { std::istringstream ss(str); std::string item; std::vector<std::string> result; while (std::getline(ss, item, delim)) { result.push_back(item); } if (result.empty()) result.resize(1); return result; } template<class...A> std::vector<std::string> split(const std::string& str, char delim, A...a) { std::vector<std::string> result; for (auto& item : split(str, delim)) { for (auto& child : split(item, a...)) { result.push_back(child); } } return result; } template<class T> void sscat_detail_(std::stringstream& ss, const T& t) { ss << t; } template<class T, class...A> void sscat_detail_(std::stringstream& ss, const T& t, const A&...a) { ss << t; sscat_detail_(ss, a...); } template<class...A> std::string sscat(const A&...a) { auto ss = std::stringstream(); sscat_detail_(ss, a...); return ss.str(); } struct exception : public std::runtime_error { template<class...A> explicit exception(A...a) : std::runtime_error(sscat(a...).c_str()) {} }; struct spinlock { enum State {Locked, UnLocked}; std::atomic<State> state_; inline spinlock() : state_(UnLocked) {} inline void lock() { while (state_.exchange(Locked, std::memory_order_acquire) == Locked) {} } inline void unlock() { state_.store(UnLocked, std::memory_order_release); } }; inline spinlock& logging_lock() { static spinlock logging_lock; return logging_lock; } #ifdef _WIN32 inline std::vector<WCHAR> u8tow(const std::string& str) { size_t size = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); std::vector<WCHAR> buf; buf.resize(size + 1); ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &buf[0], size + 1); buf[size] = '\0'; return buf; } inline HANDLE stderr_handle() { static HANDLE hStderr; if (hStderr == nullptr) hStderr = GetStdHandle(STD_ERROR_HANDLE); return hStderr; } #endif template<class...A> void log(const A&...a) { auto s = sscat(a..., '\n'); std::lock_guard<spinlock> lock(logging_lock()); std::cout << s; } template<class...A> void logerr(const A&...a) { auto s = sscat(a..., '\n'); std::lock_guard<spinlock> lock(logging_lock()); #ifdef _WIN32 auto wc = u8tow(s); CONSOLE_SCREEN_BUFFER_INFO scrInfo; DWORD size; HANDLE h = GetStdHandle(STD_ERROR_HANDLE); bool ok = GetConsoleScreenBufferInfo(h, &scrInfo); if (ok) SetConsoleTextAttribute(h, FOREGROUND_RED | FOREGROUND_INTENSITY); if (!WriteConsoleW(h, wc.data(), wc.size(), &size, nullptr)) { std::cerr << "\e[31m" << s << "\e[m"; } if (ok) SetConsoleTextAttribute(h, scrInfo.wAttributes); #else std::cerr << "\e[31m" << s << "\e[m"; #endif } struct u8to32iter { struct iterator : public std::iterator<std::input_iterator_tag, uint32_t> { size_t index = 0; std::string& str; uint32_t value; inline iterator(std::string& str, size_t index) : str(str), index(index) {} inline uint32_t operator*() { if (index >= str.size()) { index = str.size(); return 0; } uint32_t c0 = str[index]; switch (width_(c0)) { case 1: { return c0; } case 2: { uint32_t c1 = check_(str[index+1]); return ((c0 & 0x1F) << 6) | (c1 & 0x3F); } case 3: { uint32_t c1 = check_(str[index+1]); uint32_t c2 = check_(str[index+2]); return ((c0 & 0x0F) << 12) | ((c1 & 0x3F) << 6) | (c2 & 0x3F); } case 4: { uint32_t c1 = check_(str[index+1]); uint32_t c2 = check_(str[index+2]); uint32_t c3 = check_(str[index+3]); // upper 5bit c0 = ((c0 & 0x7) << 2) | ((c1 >> 4) & 0x3); if (c0 > 0x10) { throw exception("invalid utf8"); } return (c0 << 16) | ((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F); } } throw exception(""); } inline iterator& operator++() { if (index >= str.size()) { index = str.size(); return *this; } index += width_(str[index]); if (index > str.size()) { index = str.size(); } return *this; } inline bool operator!=(const iterator& it) { return index != it.index || str != it.str; } inline uint8_t check_(uint8_t c) { if ((c & 0xc0) != 0x80) { throw 0; } return c; } inline int width_(uint8_t c) { if ((c & 0x80) == 0) { // U+0000 - U+007F return 1; } else if ((c & 0xE0) == 0xC0) { // U+0080 - U+07FF return 2; } else if ((c & 0xF0) == 0xE0) { // U+0800 - U+FFFF return 3; } else if (0xF0 <= c && c <= 0xF4) { // U+10000 - U+10FFFF return 4; } else { throw exception("invalid utf8 charactor c=0x", std::hex, static_cast<int>(c), std::dec); } } }; std::string str; inline explicit u8to32iter(const std::string& str) : str(str) {} inline iterator begin() { return iterator(str, 0); } inline iterator end() { return iterator(str, str.size()); } }; inline std::tuple<bool, uint16_t, uint16_t> u32to16char(uint32_t c0) { if ((c0 & ~0xFFFF) == 0) { return std::make_tuple(false, c0, 0); } // sarrogate pair uint16_t c1 = 0xD800 | ((((c0 & 0x1F0000) - 0x010000) | (c0 & 0x00FC00)) >> 10); uint16_t c2 = 0xDC00 | (c0 & 0x0003FF); return std::make_tuple(true, c1, c2); } template<class T, class M = std::mutex> struct mutex_list { struct not_found : public std::exception {}; M mutex; std::list<T> list; inline mutex_list() : mutex(), list() {} inline void push_back(T t) { std::lock_guard<M> lock(mutex); list.push_back(std::move(t)); } inline boost::optional<T> move_front() { std::lock_guard<M> lock(mutex); if (list.empty()) return boost::none; T t = std::move(list.front()); list.pop_front(); return t; } inline boost::optional<T> move_back() { std::lock_guard<M> lock(mutex); if (list.empty()) return boost::none; T t = std::move(list.back()); list.pop_back(); return t; } inline bool empty() { std::lock_guard<M> lock(mutex); return list.empty(); } inline size_t size() { std::lock_guard<M> lock(mutex); return list.size(); } template<class F> bool any(F f) { std::lock_guard<M> lock(mutex); for (auto& e : list) { if (f(e)) return true; } return false; } template<class F> T& get(F f) { std::lock_guard<M> lock(mutex); for (auto& e : list) { if (f(e)) return e; } throw not_found(); } }; template<class K, class V, class M = std::mutex> struct mutex_map { M mutex; std::unordered_map<K, V> map; inline mutex_map() : mutex(), map() {} inline void emplace(K k, V v) { std::lock_guard<M> lock(mutex); map.emplace(k, v); } inline V& emplace_ref(K k, V&& v) { std::lock_guard<M> lock(mutex); map.emplace(k, std::move(v)); const auto& it = map.find(k); return it->second; } inline boost::optional<V> get(const K& k) { std::lock_guard<M> lock(mutex); auto it = map.find(k); if (it == map.end()) return boost::none; return it->second; } inline boost::optional<V&> getref(const K& k) { std::lock_guard<M> lock(mutex); const auto& it = map.find(k); if (it == map.end()) return boost::none; return it->second; } inline bool has(const K& k) { std::lock_guard<M> lock(mutex); const auto& it = map.find(k); return it != map.end(); } inline bool empty() { std::lock_guard<M> lock(mutex); return map.empty(); } inline V add(K k, V v) { std::lock_guard<M> lock(mutex); auto it = map.find(k); if (it == map.end()) { map.emplace(k, v); return v; } it->second += v; return it->second; } inline void erase(std::function<bool(K, V)> f) { std::lock_guard<M> lock(mutex); for (auto it = map.begin(); it != map.end();) { if (f(it->first, it->second)) { it = map.erase(it); } else { ++it; } } } }; template<class K, class V> struct shared_cache { // using M = utils::spinlock; using M = std::mutex; struct Value { std::shared_ptr<V> v; std::unique_ptr<M> mutex; inline Value() :v(nullptr), mutex(std::unique_ptr<M>(new M)) {} }; M mutex; std::unordered_map<K, Value> map; template<class...A> std::shared_ptr<V> get_or_emplace(K k, A...a) { Value* value; { std::lock_guard<M> lock(mutex); auto it = map.find(k); if (it != map.end()) { if (it->second.v.get() == nullptr) { value = &it->second; } else { return it->second.v; } } else { auto em = map.emplace(std::piecewise_construct, std::make_tuple(k), std::make_tuple()); value = &em.first->second; } } std::lock_guard<M> value_lock(*value->mutex); if (value->v.get() != nullptr) { return value->v; } value->v = std::make_shared<V>(a...); return value->v; } }; inline bool isdigits(const std::string& s) { for (auto c : s) { if (c < '0' || '9' < c) return false; } return true; } inline bool isdecimal(const std::string& s) { if (s.empty()) return false; if (s[0] == '+' || s[0] == '-') { return isdigits(s.substr(1)); } return isdigits(s); } } // namespace utils } // namespace xlsxconverter
#include <bits/stdc++.h> #define ll long long #define ull unsigned long long #define FOR(i,n) for(ll i=0;i<n;i++) #define FOR1(i,n) for(ll i=1;i<n;i++) #define FORn1(i,n) for(ll i=1;i<=n;i++) #define FORmap(i,mp) for(auto i=mp.begin();i!=mp.end();i++) #define vll vector<ll> #define vs vector<string> #define pb(x) push_back(x) #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define mod 1000000007 using namespace std; int main() { // your code goes here fast; ll t; cin>>t; while(t--) { map<ll,ll> mp; ll n,m; cin>>n>>m; ll d[n],v[n]; FOR(i,n) { cin>>d[i]>>v[i]; if(mp[d[i]]==0) mp[d[i]]=v[i]; else mp[d[i]]=max(mp[d[i]],v[i]); } vector<ll> p; FORmap(i,mp) { p.pb(i->second); } sort(p.begin(),p.end(), greater<ll>()); ll res=p[0]+p[1]; cout<<res<<endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- ** ** Copyright (C) 1995-1999 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_XPATHRESULT #define DOM_XPATHRESULT #ifdef DOM3_XPATH #include "modules/dom/src/domobj.h" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/util/adt/opvector.h" #include "modules/xpath/xpath.h" class DOM_Document; class DOM_Node; class XPathNode; class DOM_XPathResult : public DOM_Object, public DOM_MutationListener { private: OP_STATUS EnsureTypeAndFirstResult(); protected: DOM_XPathResult(DOM_Document *document, XMLTreeAccessor *tree, XPathExpression::Evaluate *xpathresult); XMLTreeAccessor *tree; HTML_Element *rootelement; XPathExpression::Evaluate *xpathresult; unsigned result_type; // Bitfield with XPathExpression::Evaluate::Type bits unsigned snapshot_length; DOM_Document *document; BOOL invalid, check_changes; OpVector<DOM_Node> nodes; OP_STATUS Initialize(); OP_STATUS AddNode(XPathNode *xpathnode); public: virtual ~DOM_XPathResult(); static OP_STATUS Make(DOM_XPathResult *&domresult, DOM_Document *document, XMLTreeAccessor *tree, XPathExpression::Evaluate *xpathresult); virtual ES_GetState GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_XPATHRESULT || DOM_Object::IsA(type); } virtual void GCTrace(); // From DOM_MutationListener virtual OP_STATUS OnAfterInsert(HTML_Element *child, DOM_Runtime *origining_runtime); virtual OP_STATUS OnBeforeRemove(HTML_Element *child, DOM_Runtime *origining_runtime); virtual OP_STATUS OnAfterValueModified(HTML_Element *element, const uni_char *new_value, ValueModificationType type, unsigned offset, unsigned length1, unsigned length2, DOM_Runtime *origining_runtime); virtual OP_STATUS OnAttrModified(HTML_Element *element, const uni_char *name, int ns_idx, DOM_Runtime *origining_runtime); OP_STATUS SetValue(XMLTreeAccessor *tree, XPathExpression::Evaluate *xpathresult); XPathExpression::Evaluate *GetValue() { return xpathresult; } BOOL IsInvalid() { return !xpathresult || invalid; } unsigned GetCount() { return nodes.GetCount(); } DOM_Node *GetNode(unsigned index) { return nodes.Get(index); } static void ConstructXPathResultObjectL(ES_Object *object, DOM_Runtime *runtime); static OP_STATUS GetDOMNode(DOM_Node *&domnode, XPathNode *xpathnode, DOM_Document *document); DOM_DECLARE_FUNCTION_WITH_DATA(getNode); // iterateNext and snapshotItem enum { FUNCTIONS_WITH_DATA_ARRAY_SIZE = 3 }; enum { // Constant numbers are from the DOM3 XPath specification // XPathResultType // const unsigned short ANY_TYPE = 0; // const unsigned short NUMBER_TYPE = 1; // const unsigned short STRING_TYPE = 2; // const unsigned short BOOLEAN_TYPE = 3; // const unsigned short UNORDERED_NODE_ITERATOR_TYPE = 4; // const unsigned short ORDERED_NODE_ITERATOR_TYPE = 5; // const unsigned short UNORDERED_NODE_SNAPSHOT_TYPE = 6; // const unsigned short ORDERED_NODE_SNAPSHOT_TYPE = 7; // const unsigned short ANY_UNORDERED_NODE_TYPE = 8; // const unsigned short FIRST_ORDERED_NODE_TYPE = 9; ANY_TYPE = 0, NUMBER_TYPE = 1, STRING_TYPE = 2, BOOLEAN_TYPE = 3, UNORDERED_NODE_ITERATOR_TYPE = 4, ORDERED_NODE_ITERATOR_TYPE = 5, UNORDERED_NODE_SNAPSHOT_TYPE = 6, ORDERED_NODE_SNAPSHOT_TYPE = 7, ANY_UNORDERED_NODE_TYPE = 8, FIRST_ORDERED_NODE_TYPE = 9 }; }; #endif // DOM3_XPATH #endif // DOM_XPATHRESULT
#include <iostream> #include <queue> #include <tuple> #include <vector> using namespace std; using ll = long long; class UnionFind { public: explicit UnionFind(int N) : V_NUM(N) { par.resize(V_NUM); rank.resize(V_NUM); num.resize(V_NUM); for (int i = 0; i < V_NUM; ++i) { par[i] = i; } fill(rank.begin(), rank.end(), 0); fill(num.begin(), num.end(), 1); } int find(int x) { if (par[x] == x) { return x; } else { return par[x] = find(par[x]); } } void unite(int x, int y) { x = find(x); y = find(y); if (x == y) return; if (rank[x] < rank[y]) swap(x, y); num[x] += num[y]; par[y] = x; if (rank[x] == rank[y]) ++rank[x]; } bool same(int x, int y) { return find(x) == find(y); } bool ispar(int x) { return x == find(x); } int size(int x) { return num[find(x)]; } const int INF = 1 << 25; int V_NUM; vector<int> par, rank, num; }; int main() { int N, M, K; cin >> N >> M >> K; int x[K]; for (int i = 0; i < K; ++i) { cin >> x[i]; --x[i]; } priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> path; for (int i = 0; i < M; ++i) { int u, v, w; cin >> u >> v >> w; path.push(make_tuple(w, u - 1, v - 1)); } UnionFind uf(N); int itr = 1; // x[0]とx[itr]が非連結 while (!path.empty()) { int w, u, v; tie(w, u, v) = path.top(); path.pop(); uf.unite(u, v); for (; itr < K; ++itr) { if (!uf.same(x[0], x[itr])) break; } if (itr == K) { for (int i = 0; i < K; ++i) { cout << w << " "; } cout << endl; break; } } return 0; }
#include <iostream> #include <vector> using namespace std; #define MAX 200001 vector<int> edges[MAX]; bool visited[MAX]; bool dfs(int u) { bool ans = true; visited[u] = true; if(edges[u].size() != 2) ans = false; for(auto v : edges[u]) if(!visited[v]) ans = ans & dfs(v); return ans; } int main() { int n, m, a, b; cin >> n >> m; for(int i = 0; i < m; i++) { cin >> a >> b; edges[a].push_back(b); edges[b].push_back(a); } int ans = 0; for(int u = 1; u <= n; u++) { if(!visited[u]) ans += dfs(u); } cout << ans << endl; }
///////////////////////////////////////////////////////////////////// // Copyright Yibo Zhu 2017 // 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) ///////////////////////////////////////////////////////////////////// #pragma once #if ((defined(__clang__) || defined(__GNUC__)) && __cplusplus < 201103L) || \ (defined(_MSC_VER) && _MSC_VER < 1800) #error This library needs at least a C++11 compliant compiler #endif #include <climits> #include <cstdint> #include <memory> #include <string> template <typename T> static constexpr T getBitmask(unsigned int const bits) { return static_cast<T>(-(bits != 0)) & (static_cast<T>(-1) >> ((sizeof(T) * CHAR_BIT) - bits)); } #if __cplusplus >= 201402L || (defined(_MSC_VER) && _MSC_VER >= 1910) // c++14 impl static constexpr unsigned int getSetBitsCount(std::uint64_t n) { unsigned int count{0}; while (n) { n &= (n - 1); count++; } return count; } static constexpr unsigned int getShiftBitsCount(uint64_t n) { // requires c++14 unsigned int count{0}; if (n == 0) return count; while ((n & 0x1) == 0) { n >>= 1; ++count; } return count; } #elif __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800) // c++11 impl static constexpr unsigned int getSetBitsCount(std::uint64_t n) { return n == 0 ? 0 : 1 + getSetBitsCount(n & (n - 1)); } static constexpr unsigned int getShiftBitsCount(uint64_t n) { return n == 0 ? 0 : ((n & 0x1) == 0 ? 1 + getShiftBitsCount(n >> 1) : 0); } #if (__cplusplus == 201103L) && (defined(__clang__) || defined(__GNUC__)) namespace std { // for c+11 template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } // namespace std #endif #else #error This library needs at least a C++11 compliant compiler #endif // for exception construction inline std::string getErrorMsg(std::string const &message, char const *file, char const *function, std::size_t line) { return std::string{} + file + "(" + std::to_string(line) + "): [" + function + "] " + message; } #define ERROR_MSG(...) getErrorMsg(__VA_ARGS__, __FILE__, __func__, __LINE__) #ifdef _WIN32 #ifndef NOMINMAX #define NOMINMAX #endif #include <stdlib.h> #include <windows.h> static size_t cache_line_size() { size_t line_size = 0; DWORD buffer_size = 0; DWORD i = 0; SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buffer = 0; GetLogicalProcessorInformation(0, &buffer_size); buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION *)malloc(buffer_size); GetLogicalProcessorInformation(&buffer[0], &buffer_size); for (i = 0; i != buffer_size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i) { if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == 1) { line_size = buffer[i].Cache.LineSize; break; } } free(buffer); return line_size; } #elif defined(__linux__) #include <unistd.h> static size_t cache_line_size() { size_t line_size = sysconf(_SC_LEVEL1_DCACHE_LINESIZE); return line_size; } #elif defined(__APPLE__) #include <sys/sysctl.h> static size_t cache_line_size() { size_t line_size = 0; size_t size_of_linesize = sizeof(line_size); sysctlbyname("hw.cachelinesize", &line_size, &size_of_linesize, 0, 0); return line_size; } #else #error unsupported platform #endif
/* * ·´×ªµ¥´Ê */ #include <bits/stdc++.h> using namespace std; class Solution{ public: void exchange_part(string &s,int i){ _reverse(s,0,i); _reverse(s,i+1,s.size()-1); reverse(s.begin(),s.end()); } private: void _reverse(string &s,int start,int end){ while(start <= end){ char temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } } }; int main(){ string s = "ABCDE"; Solution handle; handle.exchange_part(s,2); printf("%s\n",s.c_str()); return 0; }
#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; // sort:O(N log N) search:O(N) int deceitfulWar(vector<int> Naomi, vector<int> Ken) { sort(Naomi.begin(), Naomi.end(), greater<int>()); sort(Ken.begin(), Ken.end(), greater<int>()); int N = (int)Naomi.size(); int res = 0; int n = N; int j = 0; for (int i=0; i<n && j<N; ++i,++j) { if (Naomi[i] > Ken[j]) ++res; else --i, --n; } return res; } // sort:O(N log N) search:O(N) int war(vector<int> Naomi, vector<int> Ken) { sort(Naomi.begin(), Naomi.end()); sort(Ken.begin(), Ken.end()); int N = (int)Naomi.size(); int res = 0; int j = 0; for (int i=0; i<N && j<N; ++i,++j) { while (j < N && Naomi[i] > Ken[j]) { ++res; ++j; } } return res; } pair<int, int> calc(vector<int> &Naomi, vector<int> &Ken) { return pair<int, int>( deceitfulWar(Naomi, Ken), war(Naomi, Ken) ); } int main() { ifstream ifs("/GoogleCodeJam/dat.txt"); int Number; ifs >> Number; const int SIZE = 1000000; for (int i=1; i<=Number; ++i) { int N; ifs >> N; vector<int> Naomi(N),Ken(N); double v; for (int i=0; i<N; ++i) { ifs >> v; Naomi[i] = SIZE*v; } for (int i=0; i<N; ++i) { ifs >> v; Ken[i] = SIZE*v; } pair<int, int> p = calc(Naomi, Ken); printf("Case #%d: %d %d\n",i, p.first, p.second); } return 0; }
/** * @brief This will test if the Button passed in parameters has been pressed and change values accordingly * * @param PassedPressedButton Which button has to be pressed to make - * @param PassedPressedButtonPlus Which button has to be pressed to do + * @param PassedRepeatAllowed Can this value be changed by holding down the Button? * @param PassedValueToChange Pointer pointing to the Value which should be changed * @param PassedMinAllowed The minimal value possible * @param PassedMaxAllowed The maximal value allowed * @param PassedSlowScaling The number of increments to do when doing a simle press * @param PassedFastScaling The number of increments if fast scaling. Only needed when @p PassedRepeatAllowed is set to true */ void ChangeParamMain(uint8_t PassedPressedButton, uint8_t PassedPressedButtonPlus, bool PassedRepeatAllowed, uint8_t *PassedValueToChange, uint8_t PassedMinAllowed, uint8_t PassedMaxAllowed, uint8_t PassedSlowScaling, uint8_t PassedFastScaling ) { //Test if the Button has been Pressed if (ReadValues.ButtonPressed == PassedPressedButton && (ReadValues.newValues || (ReadValues.Repeat && PassedRepeatAllowed))) { //Do Fast Scaling when holding down the Button if (ReadValues.Repeat == 1) { if (*PassedValueToChange > (PassedMinAllowed+PassedFastScaling) ) { *PassedValueToChange = *PassedValueToChange - PassedFastScaling; #if defined(DEBUGMODE) Serial.print("---- "); #endif } else { *PassedValueToChange = PassedMinAllowed; #if defined(DEBUGMODE) Serial.print("oo "); #endif } } else //Slow scaling { if (*PassedValueToChange > (PassedMinAllowed + PassedSlowScaling)) { *PassedValueToChange = *PassedValueToChange - PassedSlowScaling; #if defined(DEBUGMODE) Serial.print("-- "); #endif } else { *PassedValueToChange = PassedMinAllowed; #if defined(DEBUGMODE) Serial.print("oo "); #endif } } SettingsNow.ChangesToEffectMade = true; #if defined(DEBUGMODE) Serial.print("ChangeParam | :"); Serial.println(*PassedValueToChange); #endif //show status update SettingsNow.ShowACK = 1; SettingsNow.ShowPercentage = *PassedValueToChange * (255/PassedMaxAllowed); ReadValues.newValues = 0; } //Test if the + Button has been Pressed if (ReadValues.ButtonPressed == PassedPressedButtonPlus && (ReadValues.newValues || (ReadValues.Repeat && PassedRepeatAllowed))) { //Do Fast Scaling when holding down the Button if (ReadValues.Repeat == 1) { if (*PassedValueToChange < (PassedMaxAllowed - PassedFastScaling)) { *PassedValueToChange = *PassedValueToChange + PassedFastScaling; #if defined(DEBUGMODE) Serial.print("---- "); #endif } else { *PassedValueToChange = PassedMaxAllowed; #if defined(DEBUGMODE) Serial.print("oo "); #endif } } else //Slow scaling { if (*PassedValueToChange < (PassedMaxAllowed - PassedSlowScaling)) { *PassedValueToChange = *PassedValueToChange + PassedSlowScaling; #if defined(DEBUGMODE) Serial.print("-- "); #endif } else { *PassedValueToChange = PassedMaxAllowed; #if defined(DEBUGMODE) Serial.print("oo "); #endif } } SettingsNow.ChangesToEffectMade = true; #if defined(DEBUGMODE) Serial.print("ChangeParam | :"); Serial.println(*PassedValueToChange); #endif //show status update SettingsNow.ShowACK = 1; SettingsNow.ShowPercentage = *PassedValueToChange * (255 / PassedMaxAllowed); ReadValues.newValues = 0; } }
#include "KeyboardInterface.h" #include <iostream> conf::Dir KeyboardInterface::get_direction() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) return conf::Dir::UP_RIGHT; else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) return conf::Dir::DOWN_RIGHT; else return conf::Dir::RIGHT; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) return conf::Dir::UP_LEFT; else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) return conf::Dir::DOWN_LEFT; else return conf::Dir::LEFT; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { return conf::Dir::UP; } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { return conf::Dir::DOWN; } return conf::Dir::NONE; } bool KeyboardInterface::get_shoot() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) return true; return false; }
//------------------------------------------------------------------------------ // <copyright file="KinectParams.h" company="UNAM"> // Copyright (c) Universidad Nacional Autónoma de México. // </copyright> //------------------------------------------------------------------------------ #include <wx/slider.h> #include <wx/stattext.h> #include <wx/sizer.h> #include <wx/log.h> namespace wxExtra { /// Use EVT_SLIDER_FLOAT_COMBO to be notified when the slider changed value. wxDECLARE_EVENT(EVT_SLIDER_FLOAT_COMBO, wxCommandEvent); /// <summary> /// Constructor /// </summary> class wxSliderFloatCombo : public wxControl { private: float m_rangeMin; float m_rangeMax; float m_value; // format an integer value as string static wxString Format(float n) { return wxString::Format(wxT("%.2f"), n); } static unsigned int valueToInt(float value) { return (unsigned int)(value * 1000); } static float intToFloatValue(unsigned int i) { return ((float)i) / 1000; } void OnSliderChange(wxCommandEvent& event); wxDECLARE_EVENT_TABLE(); public: /// <summary> /// Constructor /// </summary> /// <param name="parent">parent window</param> /// <param name="id">id of this control, it can be used to catch its events</param> /// <param name="minValue">slider minimum value</param> /// <param name="maxValue">slider maximum value</param> /// <param name="label">label text</param> wxSliderFloatCombo(wxWindow* parent, wxWindowID id, float value, float minValue, float maxValue, wxString label); virtual float GetValue() const; private: wxSlider* m_pSlider; wxStaticText* m_pTextMin; wxStaticText* m_pTextMax; wxStaticText* m_pTextVal; }; }
#ifndef UNOPNODE_H #define UNOPNODE_H #include <vector> #include <string> #include <iostream> #include "Node.hpp" using namespace std; class UnOpNode : public Node { private: Node *expression = nullptr; string op; public: UnOpNode(const string &op, Node *expression); void printTree() override; string printCheck(ClassNode *classNode) override; }; #endif
#include "resource.h" #include "logger.h" std::string_view sim::infra::IResource::PowerStateToString(PowerState state) { switch (state) { case sim::infra::IResource::PowerState::kOff: return "OFF"; case sim::infra::IResource::PowerState::kRunning: return "RUNNING"; case sim::infra::IResource::PowerState::kTurningOn: return "TURNING_ON"; case sim::infra::IResource::PowerState::kTurningOff: return "TURNING_OFF"; case sim::infra::IResource::PowerState::kFailure: return "FAILURE"; default: abort(); } } #define CHECK_POWER_STATE(expected, extra_text) \ if (power_state_ != (expected)) { \ ACTOR_LOG_ERROR("{}: current power state is {} but expected {}", \ extra_text, PowerStateToString(power_state_), \ PowerStateToString(expected)); \ SetPowerState(PowerState::kFailure); \ return; \ } void sim::infra::IResource::HandleEvent(const events::Event* event) { auto resource_event = dynamic_cast<const ResourceEvent*>(event); if (!resource_event) { ACTOR_LOG_ERROR("Received invalid event"); return; } switch (resource_event->type) { case ResourceEventType::kBoot: StartBoot(resource_event); break; case ResourceEventType::kReboot: StartReboot(resource_event); break; case ResourceEventType::kBootFinished: CompleteBoot(resource_event); break; case ResourceEventType::kShutdown: StartShutdown(resource_event); break; case ResourceEventType::kShutdownFinished: CompleteShutdown(resource_event); break; default: { ACTOR_LOG_ERROR("Received event with invalid type"); break; } } } void sim::infra::IResource::StartBoot(const ResourceEvent* resource_event) { if (power_state_ == PowerState::kFailure) { ACTOR_LOG_ERROR("I am failed"); } else if (power_state_ == PowerState::kOff) { SetPowerState(PowerState::kTurningOn); for (auto component : components_) { auto boot_component_event = events::MakeEvent<ResourceEvent>( component, resource_event->happen_time + startup_delay_, nullptr); boot_component_event->type = ResourceEventType::kBoot; schedule_event(boot_component_event, false); } auto boot_finished_event = events::MakeEvent<ResourceEvent>( GetUUID(), resource_event->happen_time + startup_delay_, nullptr); boot_finished_event->type = ResourceEventType::kBootFinished; schedule_event(boot_finished_event, false); } else { ACTOR_LOG_INFO("Already ON"); } } void sim::infra::IResource::StartShutdown(const ResourceEvent* resource_event) { // switch state to kTurningOff and schedule kShutdownFinished event if (power_state_ == PowerState::kOff) { ACTOR_LOG_INFO("Already OFF"); } else { SetPowerState(PowerState::kTurningOff); for (auto component : components_) { auto shutdown_component_event = events::MakeEvent<ResourceEvent>( component, resource_event->happen_time + shutdown_delay_, nullptr); shutdown_component_event->type = ResourceEventType::kShutdown; schedule_event(shutdown_component_event, false); } auto shutdown_finished_event = events::MakeEvent<ResourceEvent>( GetUUID(), resource_event->happen_time + shutdown_delay_, nullptr); shutdown_finished_event->type = ResourceEventType::kShutdownFinished; schedule_event(shutdown_finished_event, false); } } void sim::infra::IResource::StartReboot(const ResourceEvent* resource_event) { } void sim::infra::IResource::CompleteBoot(const ResourceEvent* resource_event) { // switch state to kRunning CHECK_POWER_STATE(PowerState::kTurningOn, "BootFinished Event Handler"); SetPowerState(PowerState::kRunning); } void sim::infra::IResource::CompleteShutdown(const ResourceEvent* resource_event) { // switch state to kOff CHECK_POWER_STATE(PowerState::kTurningOff, "ShutdownFinished Event Handler"); SetPowerState(PowerState::kOff); } sim::TimeInterval sim::infra::IResource::GetStartupDelay() const { return startup_delay_; } void sim::infra::IResource::SetStartupDelay(TimeInterval startup_delay) { startup_delay_ = startup_delay; } sim::TimeInterval sim::infra::IResource::GetRebootDelay() const { return reboot_delay_; } void sim::infra::IResource::SetRebootDelay(TimeInterval reboot_delay) { reboot_delay_ = reboot_delay; } sim::TimeInterval sim::infra::IResource::GetShutdownDelay() const { return shutdown_delay_; } void sim::infra::IResource::SetShutdownDelay(TimeInterval shutdown_delay) { shutdown_delay_ = shutdown_delay; } sim::EnergyCount sim::infra::IResource::GetEnergyPerTickConst() const { return energy_per_tick_const_; } void sim::infra::IResource::SetEnergyPerTickConst( sim::EnergyCount energy_per_tick_const) { energy_per_tick_const_ = energy_per_tick_const; } void sim::infra::IResource::SetPowerState(PowerState new_state) { power_state_ = new_state; ACTOR_LOG_INFO("State changed to {}", PowerStateToString(new_state)); }
#pragma once #include "./Relays/Relay.h" namespace Codingfield { namespace Brew { namespace Actuators { class PwmRelay { public: PwmRelay(Relays::Relay* relay, Relays::States idleState, Relays::States activateState); virtual ~PwmRelay() = default; void Activate(); void Deactivate(); bool IsActivated() const; void Period(uint32_t p); uint32_t Period() const; void Consign(uint32_t p); uint32_t Consign() const; void MinimumActivatedTime(uint32_t m); uint32_t MinimumActivatedTime() const; void MinimumIdleTime(uint32_t m); uint32_t MinimumIdleTime() const; uint32_t TotalActivatedTime() const; // Should be called periodically. The calling period will // determine the period of the PWM void Update(); void Reset(); private: Relays::Relay* actualRelay = nullptr; uint32_t period = 1000; uint32_t consign = 500; uint32_t newConsign = 500; uint32_t value = 0; uint32_t minActivatedTime = 0; // Once activated, keep it activated at least during this time uint32_t activatedTime = 0; uint32_t minIdleTime = 0; // Once idling, keep it idle at least during this time uint32_t idleTime = 0; Relays::States idleState = Relays::States::Open; Relays::States activateState = Relays::States::Closed; bool activated = false; uint32_t totalActivatedTime = 0; }; } } }
#include <Adafruit_NeoPixel.h> #include <Signaling.h> #include <UpdateData.h> Signaling Strip(16, 6, NEO_RGBW + NEO_KHZ800); UpdateData Pattern1; UpdateData Pattern2; UpdateData Pattern4; UpdateData Pattern3; UpdateData Pattern5; void setup() { // put your setup code here, to run once: Serial.begin(115200); Strip.begin(); /* Pattern1.pattern = RAINBOW_CYCLE; Pattern1.direction = FORWARD; Pattern1.startTime = 0; Pattern1.cycles = 100; Pattern1.Index = 0; Pattern1.brightness = 255; //Pattern1.status = false; Pattern1.complete = false; Pattern1.Interval = 3; //change every 100 ms Pattern1.lastUpdate = 0; Pattern1.totalsteps=255; Pattern1.group[0] = 0; Pattern1.group[1] = 1; Pattern1.group[2] = 2; Pattern1.group[3] = 6; Pattern1.groupLength = 4; Pattern2.pattern = THEATER_CHASE; Pattern2.direction = FORWARD; Pattern2.startTime = 3; Pattern2.on_time = 5; Pattern2.Index = 0; Pattern2.brightness = 255; // Pattern2.status = false; Pattern2.complete = false; Pattern2.Interval = 500; //change every 200 ms Pattern2.lastUpdate = 0; Pattern2.totalsteps=5; Pattern2.Color1 = Strip.Color(255,255,0); Pattern2.Color2 = Strip.Color(0,0,50); Pattern2.group[0] = 5; Pattern2.group[1] = 6; Pattern2.group[2] = 7; Pattern2.group[3] = 8; Pattern2.group[4] = 9; Pattern2.groupLength = 5;*/ Pattern3.pattern = SCANNER; Pattern3.direction = FORWARD; Pattern3.startTime = 3; Pattern3.on_time = 5; Pattern3.Index = 0; Pattern3.brightness = 255; // Pattern2.status = false; Pattern3.complete = false; Pattern3.Interval = 500; //change every 200 ms Pattern3.lastUpdate = 0; Pattern3.groupLength=5; Pattern3.Color1 = Strip.Color(255,0,0); // Pattern3.Color2 = Strip.Color(0,0,50); Pattern3.group[0] = 11; Pattern3.group[1] = 12; Pattern3.group[2] = 13; Pattern3.group[3] = 14; Pattern3.group[4] = 15; Pattern3.totalsteps = (Pattern3.groupLength-1)*2; /* Pattern4.pattern = PULSATING; Pattern4.direction = FORWARD; Pattern4.startTime = 3; Pattern4.on_time = 5; Pattern4.Index = 0; Pattern4.brightness = 255; // Pattern2.status = false; Pattern4.complete = false; Pattern4.Interval = 500; //change every 200 ms Pattern4.lastUpdate = 0; Pattern4.groupLength=5; Pattern4.Color1 = Strip.Color(255,255,0); Pattern4.Color2 = Strip.Color(0,0,50); Pattern4.group[0] = 11; Pattern4.group[1] = 12; Pattern4.group[2] = 13; Pattern4.group[3] = 14; Pattern4.group[4] = 15; Pattern4.LedState = true; Pattern4.totalsteps = Pattern4.groupLength; Pattern5.pattern = STEP; Pattern5.direction = FORWARD; Pattern5.startTime = 0; Pattern5.on_time = 1000; Pattern5.off_time = 3000; Pattern5.Index = 0; Pattern5.brightness = 255; // Pattern2.status = false; Pattern5.complete = false; Pattern5.Interval = 1000; //change every 200 ms Pattern5.lastUpdate = 0; Pattern5.groupLength=5; Pattern5.Color1 = Strip.Color(255,255,0); Pattern5.Color2 = Strip.Color(0,0,50); Pattern5.group[0] = 1; Pattern5.group[1] = 2; Pattern5.group[2] = 3; Pattern5.group[3] = 4; Pattern5.group[4] = 5; Pattern5.totalsteps = Pattern5.groupLength; Pattern5.pattern = BLINK; Pattern5.direction = FORWARD; Pattern5.startTime = 0; Pattern5.on_time = 1000; Pattern5.off_time = 3000; Pattern5.Index = 0; Pattern5.brightness = 255; // Pattern2.status = false; Pattern5.complete = false; Pattern5.Interval = 1000; //change every 200 ms Pattern5.lastUpdate = 0; Pattern5.groupLength=5; Pattern5.Color1 = Strip.Color(255,255,0); Pattern5.Color2 = Strip.Color(0,0,50); Pattern5.group[0] = 1; Pattern5.group[1] = 2; Pattern5.group[2] = 3; Pattern5.group[3] = 4; Pattern5.group[4] = 5; Pattern5.totalsteps = Pattern5.groupLength; Pattern5.pattern = ON_AND_OFF; Pattern5.direction = FORWARD; Pattern5.startTime = 0; Pattern5.on_time = 1000; Pattern5.off_time = 3000; Pattern5.Index = 0; Pattern5.brightness = 255; // Pattern2.status = false; Pattern5.complete = false; Pattern5.Interval = 3000; //change every 200 ms Pattern5.lastUpdate = 0; Pattern5.groupLength=5; Pattern5.Color1 = Strip.Color(255,255,0); Pattern5.Color2 = Strip.Color(0,0,50); Pattern5.group[0] = 1; Pattern5.group[1] = 2; Pattern5.group[2] = 3; Pattern5.group[3] = 4; Pattern5.group[4] = 5; Pattern5.totalsteps = Pattern5.groupLength;*/ Pattern5.pattern = LOADING; Pattern5.direction = FORWARD; Pattern5.startTime = 0; Pattern5.on_time = 1000; Pattern5.off_time = 3000; Pattern5.Index = 0; Pattern5.brightness = 255; // Pattern2.status = false; Pattern5.complete = false; Pattern5.Interval = 500; //change every 200 ms Pattern5.lastUpdate = 0; Pattern5.groupLength=5; Pattern5.Color1 = Strip.Color(100,255,0); Pattern5.Color2 = Strip.Color(0,0,50); Pattern5.group[0] = 1; Pattern5.group[1] = 2; Pattern5.group[2] = 3; Pattern5.group[3] = 4; Pattern5.group[4] = 5; Pattern5.totalsteps = 500 ; } void loop() { // put your main code here, to run repeatedly: // Strip.Update(&Pattern1); //Strip.Update(&Pattern2); Strip.Update(&Pattern3); Strip.Update(&Pattern5); }
#include "StdAfx.h" #include "FEUnit.h" #include <stdlib.h> FEUnit::FEUnit(char _face, int _skin, int _team, StatBlock* _stats, int _range, WEAPON_TYPE _weapon_type, int _weapon_accuracy, int _weapon_crit, string _name) : Creature(_face, _skin) { player = _team; stats = _stats; range = _range; weapon_type = _weapon_type; weapon_accuracy = _weapon_accuracy; weapon_crit = _weapon_crit; name = _name; } FEUnit::~FEUnit(void) { } bool FEUnit::attack(FEUnit* enemy, bool counter) { //assume range is checked elsewhere int enemy_dr = enemy->getDamageReduction(weapon_type); int enemy_avoid = enemy->getAvoid(weapon_type); int base_damage = getBaseDamage(); int base_accuracy = getBaseAccuracy(); bool enemy_killed = false; if(enemy_dr >= base_damage) return enemy_killed; //attack has no effect if(enemy_avoid >= base_accuracy) return enemy_killed; //never hit //roll to hit int toHitRoll = ( (rand() % 100) + (rand() % 100) ) / 2; //using dynamic hit if(toHitRoll <= (base_accuracy - enemy_avoid)) { //hit int total_damage = base_damage - enemy_dr; int crit_chance = getBaseCritChance() - enemy->getStats().luck; if( ( rand() % 100) <= crit_chance ) total_damage *= 2; enemy_killed = enemy->modifyHP(-total_damage); if(enemy_killed) delete enemy; else { bool killed_by_counter = false; if (!counter) killed_by_counter = enemy->attack(this, true); if(!killed_by_counter && stats->speed >= enemy->getStats().speed + 4) //double attack for high speed { toHitRoll = ( (rand() % 100) + (rand() % 100) ) / 2; //using dynamic hit if(toHitRoll <= (base_accuracy - enemy_avoid)) { int total_damage = base_damage - enemy_dr; int crit_chance = getBaseCritChance() - enemy->getStats().luck; if( ( rand() % 100) <= crit_chance ) total_damage *= 2; bool enemy_killed = enemy->modifyHP(-total_damage); if(enemy_killed) delete enemy; } } } } return enemy_killed; } int FEUnit::getTeam() { return player; } bool FEUnit::getIsActive() { return isActive; } ColorChar FEUnit::getColorChar() { ColorChar retVal = Creature::getColorChar(); if(!isActive) { retVal.color = 0; //black when inactive } return retVal; } void FEUnit::activate() { isActive = true; } void FEUnit::deactivate() { isActive = false; } StatBlock FEUnit::getStats() { return *stats; } int FEUnit::getRange() { return range; } string FEUnit::getName() { return name; } int FEUnit::getDamageReduction(WEAPON_TYPE against) { int dr; switch(against) { case SWORD: dr = stats->defense; if(weapon_type == AXE) dr += 1; else if(weapon_type == LANCE) dr -= 1; break; case AXE: dr = stats->defense; if(weapon_type == LANCE) dr += 1; else if(weapon_type == SWORD) dr -= 1; break; case LANCE: dr = stats->defense; if(weapon_type == SWORD) dr += 1; else if(weapon_type == AXE) dr -= 1; break; case BOW: dr = stats->defense; break; case ANIMA: dr = stats->resist; if(weapon_type == LIGHT) dr += 1; else if(weapon_type == DARK) dr -= 1; break; case LIGHT: dr = stats->resist; if(weapon_type == DARK) dr += 1; else if(weapon_type == ANIMA) dr -= 1; break; case DARK: dr = stats->resist; if(weapon_type == ANIMA) dr += 1; else if(weapon_type == LIGHT) dr -= 1; break; case STAFF: dr = 0; break; } return dr; } int FEUnit::getAvoid(WEAPON_TYPE against) { int avoid = stats->luck + ( 2 * stats->speed); switch(against) { case SWORD: if(weapon_type == AXE) avoid += 15; else if(weapon_type == LANCE) avoid -= 15; break; case AXE: if(weapon_type == LANCE) avoid += 15; else if(weapon_type == SWORD) avoid -= 15; break; case LANCE: if(weapon_type == SWORD) avoid += 15; else if(weapon_type == AXE) avoid -= 15; break; case BOW: break; case ANIMA: if(weapon_type == LIGHT) avoid += 15; else if(weapon_type == DARK) avoid -= 15; break; case LIGHT: if(weapon_type == DARK) avoid += 15; else if(weapon_type == ANIMA) avoid -= 15; break; case DARK: if(weapon_type == ANIMA) avoid += 15; else if(weapon_type == LIGHT) avoid -= 15; break; case STAFF: break; } return avoid; } int FEUnit::getBaseDamage() { int base_damage; if(weapon_type == SWORD || weapon_type == LANCE || weapon_type == AXE || weapon_type == BOW) base_damage = stats->strength; else if(weapon_type == ANIMA || weapon_type == LIGHT || weapon_type == DARK || weapon_type == STAFF) base_damage = stats->magic; return base_damage; } int FEUnit::getBaseAccuracy() { return stats->luck + (2 * stats->skill) + weapon_accuracy; } int FEUnit::getBaseCritChance() { return stats->skill /2 + weapon_crit; } bool FEUnit::modifyHP(int change) { stats->current_hp += change; if(stats->current_hp >= stats->max_hp) stats->current_hp = stats->max_hp; if(stats->current_hp <= 0) return true; else return false; }
#include "SpritePropertiesWidget.hpp" #include "ui_SpritePropertiesWidget.h" #include "PropertyWidget.hpp" #include <SpriteInstance.hpp> using namespace Maint; SpritePropertiesWidget::SpritePropertiesWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SpritePropertiesWidget), _sprite(NULL) { ui->setupUi(this); SetFieldsEnabled(false); } SpritePropertiesWidget::~SpritePropertiesWidget() { delete ui; } void SpritePropertiesWidget::SetSprite(SpriteInstance *instance) { if(_sprite != instance) { SetFieldsEnabled(instance != NULL); } _sprite = NULL; SetFields(instance); _sprite = instance; } /* * * Private Slots * */ void SpritePropertiesWidget::ApplyFieldsToSprite() { if(_sprite == NULL) { return; } _sprite->x = ui->xBox->value(); _sprite->y = ui->yBox->value(); _sprite->width = ui->widthBox->value(); _sprite->height = ui->heightBox->value(); _sprite->SetName(ui->nameBox->text().toStdString()); SpritePropertiesChanged(); } void SpritePropertiesWidget::ShowPropertiesEditor() { if(_sprite == NULL) { return; } PropertyWidget dialog(this); dialog.SetProperties(_sprite->Properties()); if(dialog.exec() == dialog.Accepted) { _sprite->SetProperties(dialog.GetProperties()); } } /* * * Private * */ void SpritePropertiesWidget::SetFields(SpriteInstance *sprite) { if(sprite == NULL) { return; } ui->nameBox->setText(sprite->Name().c_str()); ui->xBox->setValue(sprite->x); ui->yBox->setValue(sprite->y); ui->widthBox->setValue(sprite->width); ui->heightBox->setValue(sprite->height); } void SpritePropertiesWidget::SetFieldsEnabled(bool enabled) { ui->nameBox->setDisabled(!enabled); ui->xBox->setDisabled(!enabled); ui->yBox->setDisabled(!enabled); ui->widthBox->setDisabled(!enabled); ui->heightBox->setDisabled(!enabled); }
#include <bits/stdc++.h> #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define all(x) (x).begin(),(x).end() #define rall(x) (x).rbegin(),(x).rend() #define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ); template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; using ll = long long; int main(){ ll n, t; cin >> n >> t; vector<ll> a(n), b(n), c(n); rep(i, n) cin >> a[i] >> b[i] >> c[i]; using P = pair<ll, ll>; vector<P> events; rep(i, n){ events.push_back(P{a[i]-1, c[i]}); events.push_back(P{b[i], -c[i]}); } sort(all(events)); ll ans = 0, fee = 0, left = 0; for(auto [x, cost]: events){ if(x != left){ ans += min(t, fee) * (x - left); left = x; } fee += cost; } cout << ans << endl; }
/** * @file np_arctan2_f4_hw.cc * @author Gerbrand De Laender * @date 07/04/2021 * @version 1.0 * * @brief E091103, Master thesis * * @section DESCRIPTION * * Element-wise arc tangent of x1/x2 choosing the quadrant correctly. * Single precision (f4) implementation. * */ #include <hls_math.h> #include "np_arctan2_f4.h" #include "stream.h" void np_arctan2_f4_hw(stream_t &X1, stream_t &X2, stream_t &OUT, len_t stream_len) { #pragma HLS INTERFACE axis port=X1 #pragma HLS INTERFACE axis port=X2 #pragma HLS INTERFACE axis port=OUT #pragma HLS INTERFACE s_axilite port=stream_len #pragma HLS INTERFACE s_axilite port=return for(int i = 0; i < stream_len; i++) { #pragma HLS PIPELINE II=1 np_t a = pop_stream<np_t, channel_t>(X1.read()); np_t b = pop_stream<np_t, channel_t>(X2.read()); OUT << push_stream<np_t, channel_t>(hls::atan2(a, b), i == (stream_len - 1)); } }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * 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" #include "modules/inputmanager/inputmanager_module.h" #include "modules/inputmanager/inputmanager.h" void InputmanagerModule::InitL(const OperaInitInfo &info) { m_input_manager = OP_NEW_L(OpInputManager, ()); LEAVE_IF_ERROR(m_input_manager->Construct()); #ifndef HAS_COMPLEX_GLOBALS // The list of action strings is generated by the hardcore module, // but since we are the client, we run the initializer and own // the array. extern void init_s_action_strings(); init_s_action_strings(); #endif // !HAS_COMPLEX_GLOBALS } void InputmanagerModule::Destroy() { OP_DELETE(m_input_manager); m_input_manager = NULL; }
#include<iostream> #include<vector> #include<string> #include<utility> #include<set> #include<unordered_map> using namespace std; int main(){ // Vector: Dyanamic array (Resize is allowed) //we don't want to declare the size of vector and pushing element using push_back vector<int> v; for(int i=0;i<5;i++){ v.push_back(i+1); } //way to declare iterator vector<int>::iterator it; // begin points to first element of vector and end() points to next position of last element of vector for(it=v.begin();it!=v.end();it++){ cout<<*it<<endl; } //Another way by declaring the size of vector and inserting elememt like array vector<char> v1(5); for(int j=0;j<v1.size();j++){ v1[j]=char(65+j); } vector<char>::iterator it1; for(it1=v1.begin();it1!=v1.end();it1++){ cout<<*it1<<endl; } // Find the min element cout << "\nMin Element = "<< *min_element(v.begin(), v.end()); // Find the max element cout << "\nMax Element = " << *max_element(v.begin(), v.end()); //sorting vector sort(v.begin(), v.end()); // String (Resize is not allowed) string s = "Parikh"; string s2(s); //it will copy same string s as s2 string s1(s,2,4); //it will take character from index 2 to next 4 characters from s cout<<s<<endl; cout<<s1<<endl; cout<<s2<<endl; string s3 = s.substr(2,4); //it will take character from index 2 to next 4 characters from s cout<<s3<<endl; if(s1.compare(s2) == 0){ cout<<s1 <<"is equal to " << s2<<endl; }else{ cout<<s1 <<"is not equal to " << s2<<endl; } // Pair #include<utility> pair<int,char> p; p = make_pair(2,'b'); pair<int,char> p2(1,'a'); cout<<p.first << " " << p.second<<endl; cout<<p2.first << " " << p2.second<<endl; // Set set<int> s4; int arr[] = {1,2,3,4,5,6,5}; for(int i=0;i<7;i++){ s4.insert(arr[i]); } set<int>::iterator it4; for(it4=s4.begin();it4!=s4.end();it4++){ cout<<*it4<<endl; } if(s4.find(5) == s4.end()){ cout<<"Element not found"<<endl; }else{ cout<<"Element found"<<endl; } // Map int arr[] = {1,2,3,4,5,6,5}; //we can use map or unordered_map (unorrderd_map uses hash so avrg toc is O(1)) unordered_map<int,int> m; for(int i=0;i<7;i++){ m[arr[i]] = m[arr[i]]+1; } unordered_map<int,int>::iterator it; for(it=m.begin();it!=m.end();it++){ cout<<it->first << " :" << it->second<<endl; } cout<<endl; m.erase(1); for(it=m.begin();it!=m.end();it++){ cout<<it->first << " :" << it->second<<endl; } return 0; }
#include<bits/stdc++.h> using namespace std; main() { string s1, s2; while(cin>>s1>>s2) { for(int i=0; i<s1.size(); i++) { if(s1[i]<'a') s1[i]+=32; if(s2[i]<'a') s2[i]+=32; } if(s1==s2) cout<<0<<endl; if(s1<s2) cout<<-1<<endl; if(s1>s2) cout<<1<<endl; } return 0; }
/* -*- 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. */ #ifndef DOM_EXTENSIONS_BROWSERTABGROUPS_H #define DOM_EXTENSIONS_BROWSERTABGROUPS_H #ifdef DOM_EXTENSIONS_TAB_API_SUPPORT #include "modules/dom/src/domobj.h" #include "modules/dom/src/extensions/domextensionsupport.h" #include "modules/windowcommander/OpTabAPIListener.h" #include "modules/dom/src/domsuspendcallback.h" #include "modules/dom/src/domasynccallback.h" /** Implementation of BrowserTabGroupManager interface of Windows/Tabs API. */ class DOM_BrowserTabGroupManager : public DOM_Object , public DOM_EventTargetOwner { public: static OP_STATUS Make(DOM_BrowserTabGroupManager*& new_obj, DOM_ExtensionSupport* extension, unsigned int window_id, DOM_Runtime* origining_runtime); virtual ~DOM_BrowserTabGroupManager(); DOM_DECLARE_FUNCTION(create); DOM_DECLARE_FUNCTION(getAll); enum { FUNCTIONS_create = 1, FUNCTIONS_getAll, FUNCTIONS_ARRAY_SIZE }; DOM_DECLARE_FUNCTION_WITH_DATA(accessEventListener); enum { FUNCTIONS_WITH_DATA_addEventListener= 1, FUNCTIONS_WITH_DATA_removeEventListener, FUNCTIONS_WITH_DATA_ARRAY_SIZE }; /* from DOM_Object */ virtual ES_GetState GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_PutState PutName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_GetState FetchPropertiesL(ES_PropertyEnumerator *enumerator, ES_Runtime* origining_runtime); virtual void GCTrace(); virtual BOOL IsA(int type) { return type == DOM_TYPE_BROWSER_TAB_GROUP_MANAGER || DOM_Object::IsA(type); } /* from DOM_EventTargetOwner */ virtual DOM_Object* GetOwnerObject() { return this; } OpTabAPIListener::TabAPIItemId GetWindowId() { return m_window_id; } void BeforeDestroy(); /**< Called by DOM_EnvirnomentImpl before it is destroyed. */ private: DOM_BrowserTabGroupManager(DOM_ExtensionSupport* extension_support, unsigned int window_id) : m_notifications(this) , m_has_registered_listener(FALSE) , m_window_id(window_id) , m_extension_support(extension_support) { } BOOL IsGlobalTabGroupsCollection() { return m_window_id == 0; } BOOL IsWindowTabGroupsCollection() { return m_window_id != 0; } OP_STATUS RegisterTabsListener(); /**< Registers m_notifications as listener for Window/Tab events. */ class ExtensionTabGroupNotifications : public OpTabAPIListener::ExtensionWindowTabActionListener { public: ExtensionTabGroupNotifications(DOM_BrowserTabGroupManager* owner) : m_owner(owner) { } virtual void OnBrowserWindowAction(ActionType action, OpTabAPIListener::TabAPIItemId window_id, ExtensionWindowTabActionListener::ActionData* data) { return; } virtual void OnTabAction(ActionType action, OpTabAPIListener::TabAPIItemId tab_id, unsigned int tab_window_id, ExtensionWindowTabActionListener::ActionData* data) { return; } virtual void OnTabGroupAction(ActionType action, OpTabAPIListener::TabAPIItemId tab_group_id, ExtensionWindowTabActionListener::ActionData* data); private: DOM_BrowserTabGroupManager* m_owner; }; friend class ExtensionTabGroupNotifications; ExtensionTabGroupNotifications m_notifications; /**< Listener for tab/window evens. */ BOOL m_has_registered_listener; /**< Set to TRUE after successfully registering a tab/window event listener. */ OpTabAPIListener::TabAPIItemId m_window_id; /**< The unique ID of a browser window if this is a tab group manager of a BrowserWindow or 0 if this is a global tab group manager. */ OpSmartPointerWithDelete<DOM_ExtensionSupport> m_extension_support; }; #endif // DOM_EXTENSIONS_TAB_API_SUPPORT #endif // DOM_EXTENSIONS_BROWSERTABGROUPS_H
#include "Bone_Animation.h" Bone_Animation::Bone_Animation() { } Bone_Animation::~Bone_Animation() { } void Bone_Animation::init() { root_position = { 2.0f,1.0f,2.0f }; // // roottop_position = { 2.0f, 1.5f, 2.0f }; root_upp_trans = { 0.0f, 2.0f, 0.0f }; root_upptop_trans = { 0.0f, 4.0f, 0.0f }; upptop_mid_trans = { 0.0f, 1.5f, 0.0f }; upptop_midtop_trans = { 0.0f, 3.0f, 0.0f }; midtop_bot_trans = { 0.0f, 1.0f, 0.0f }; scale_vector = { {1.0f,1.0f,1.0f}, {0.5f,4.0f,0.5f}, {0.5f,3.0f,0.5f}, {0.5f,2.0f,0.5f} }; rotation_degree_vector = { {0.0f,0.0f,0.0f}, {0.0f,0.0f,0.0f}, {0.0f,0.0f,0.0f}, {0.0f,0.0f,0.0f} }; colors = { {0.7f,0.0f,0.0f,1.0f}, {0.7f,0.7f,0.0f,1.0f}, {0.7f,0.0f,0.7f,1.0f}, {0.0f,0.7f,0.7f,1.0f} }; // // rotate_bones = rotation_degree_vector; } void Bone_Animation::update(float delta_time) { // // // rotate_bones; } void Bone_Animation::reset() { // // rotate_bones = rotation_degree_vector; }
#pragma once #include "indexhashtableentry.h" #include <string> #include <vector> namespace sdindex { // The Index represented as a hashtable class IndexHashtable { public: IndexHashtableEntry** hashtable = nullptr; IndexHashtable(int size = 100000); ~IndexHashtable(); int get_size(); // Adds the specified string to the index bool add_to_index(const std::string& word, const std::string& filename); // Adds the specified string to the index. <faster than the previous one> bool add_to_index(const std::string& word, int filenameIndex); // Checks whether the specified word exists in the index bool entry_exists(const std::string& word); // Returns the index of filename always >=0 int get_filename_index(const std::string& filename); // Returns the filename of the index std::string get_filename(int index); // Provides a copy of the index entry matching the word input IndexHashtableEntry* get_entry_copy(const std::string& word); // Returns a pointer reference to the entry matching the word input IndexHashtableEntry* get_entry(const std::string& word); // Loads an entry into the index bool load_entry(const std::string& id, const std::string& word, const std::string& occurences); // Loads a filename into the filenames vector void load_filename_entry(const std::string& filename); // Clears the index removing all entries void clear(); // Merges index with otherIndex (delete otherIndex after using merge, //it is assumed that both indexes contain different files) bool merge(IndexHashtable* otherIndex); // Provides a string containing all the data contained in the index std::string to_string(); protected: int size; // Contains the names of all files std::vector<std::string> filenames; // The hashfunction used to match words to hashvalues unsigned int hashfunction(const std::string& word); }; }
#include <bits/stdc++.h> using namespace std; const int kCost1 = 10;//直移一格消耗 const int kCost2 = 14;//横移一格消耗 struct Point{ int x,y;//x为横坐标,y为纵坐标 int F,G,H;//F=G+H Point *parent; Point(int _x,int _y):x(_x),y(_y),F(0),G(0),H(0),parent(NULL){} }; class Astar{ public: void InitAstar(vector<vector<int> > &maze); list<Point *> GetPath(Point &startPoint,Point &endPoint, bool isIgnoreCorner); private: Point *findPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner); bool isCanReach(const Point *point,const Point* target,bool isIgnorCorner); vector<Point*> getSurroundPoints(const Point *point,bool isIgnorCorner); Point* isInList(list<Point*> &pointList,const Point* point); Point* getLeastFPoint();//从开启列表中返回F值最小的节点 int calG(Point *temp_start,Point *point); int calH(Point *point,Point *end); int calF(Point *point); private: vector<vector<int> > maze; list<Point*> openList; list<Point*> closeList; }; void Astar::InitAstar(vector<vector<int> > &_maze){ maze = _maze; } int Astar::calG(Point *temp_start,Point *point){ int extraG = (abs(point->x - temp_start->x) + abs(point->y - temp_start->y) == 1? kCost1:kCost2); int parentG = point->parent == NULL? 0:point->parent->G; return extraG+parentG; } int Astar::calH(Point *point,Point *end){ return sqrt((double)(end->x-point->x)*(double)(end->x-point->x)+(double)(end->y-point->y)*(double)(end->y-point->y))*kCost1; } int Astar::calF(Point *point){ return point->G+point->H; } Point* Astar::getLeastFPoint(){ if(!openList.empty()){ Point *resPoint = openList.front(); list<Point*> ::iterator it; for(it = openList.begin(); it != openList.end(); ++it){ Point *p = *it; if(resPoint -> F < p->F){ resPoint = p; } } return resPoint; } return NULL; } Point *Astar::findPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner) { openList.push_back(new Point(startPoint.x,startPoint.y)); //置入起点,拷贝开辟一个节点,内外隔离 while(!openList.empty()) { Point *curPoint=getLeastFPoint(); //找到F值最小的点 openList.remove(curPoint); //从开启列表中删除 closeList.push_back(curPoint); //放到关闭列表 //1,找到当前周围八个格中可以通过的格子 vector<Point*> surroundPoints=getSurroundPoints(curPoint,isIgnoreCorner); for(int i=0; i<surroundPoints.size(); ++i) { Point *target = surroundPoints[i]; //2,对某一个格子,如果它不在开启列表中,加入到开启列表,设置当前格为其父节点,计算F G H if(!isInList(openList,target)) { target->parent=curPoint; target->G=calG(curPoint,target); target->H=calH(target,&endPoint); target->F=calF(target); openList.push_back(target); } //3,对某一个格子,它在开启列表中,计算G值, 如果比原来的大, 就什么都不做, 否则设置它的父节点为当前点,并更新G和F else { int tempG=calG(curPoint,target); if(tempG<target->G) { target->parent=curPoint; target->G=tempG; target->F=calF(target); } } Point *resPoint=isInList(openList,&endPoint); if(resPoint) return resPoint; //返回列表里的节点指针,不要用原来传入的endpoint指针,因为发生了深拷贝 } } return NULL; } std::list<Point *> Astar::GetPath(Point &startPoint,Point &endPoint,bool isIgnoreCorner) { Point *result=findPath(startPoint,endPoint,isIgnoreCorner); std::list<Point *> path; //返回路径,如果没找到路径,返回空链表 while(result) { path.push_front(result); result=result->parent; } // 清空临时开闭列表,防止重复执行GetPath导致结果异常 openList.clear(); closeList.clear(); return path; } Point *Astar::isInList(list<Point*> &pointList,const Point *point) { //判断某个节点是否在列表中,这里不能比较指针,因为每次加入列表是新开辟的节点,只能比较坐标 list<Point*> ::iterator it; for(it = pointList.begin(); it != pointList.end(); ++it){ Point *p = *it; if(p->x==point->x&&p->y==point->y) return p; } return NULL; } bool Astar::isCanReach(const Point *point,const Point *target,bool isIgnoreCorner) { if(target->x<0||target->x>maze.size()-1 ||target->y<0||target->y>maze[0].size()-1 ||maze[target->x][target->y]==1 ||target->x==point->x&&target->y==point->y ||isInList(closeList,target)) //如果点与当前节点重合、超出地图、是障碍物、或者在关闭列表中,返回false return false; else { if(abs(point->x-target->x)+abs(point->y-target->y)==1) //非斜角可以 return true; else { //斜对角要判断是否绊住 if(maze[point->x][target->y]==0&&maze[target->x][point->y]==0) return true; else return isIgnoreCorner; } } } std::vector<Point *> Astar::getSurroundPoints(const Point *point,bool isIgnoreCorner) { std::vector<Point *> surroundPoints; for(int x=point->x-1;x<=point->x+1;x++) for(int y=point->y-1;y<=point->y+1;y++) if(isCanReach(point,new Point(x,y),isIgnoreCorner)) surroundPoints.push_back(new Point(x,y)); return surroundPoints; } int main() { //初始化地图,用二维矩阵代表地图,1表示障碍物,0表示可通 vector<vector<int> > maze={ {1,1,1,1,1,1,1,1,1,1,1,1}, {1,0,0,1,1,0,1,0,0,0,0,1}, {1,0,0,1,1,0,0,0,0,0,0,1}, {1,0,0,0,0,0,1,0,0,1,1,1}, {1,1,1,0,0,0,0,0,1,1,0,1}, {1,1,0,1,0,0,0,0,0,0,0,1}, {1,0,1,0,0,0,0,1,0,0,0,1}, {1,1,1,1,1,1,1,1,1,1,1,1} }; Astar astar; astar.InitAstar(maze); //设置起始和结束点 Point start(1,1); Point end(6,10); //A*算法找寻路径 list<Point *> path=astar.GetPath(start,end,false); //打印 for(auto &p:path) cout<<'('<<p->x<<','<<p->y<<')'<<endl; system("pause"); return 0; }
#include "HUD.h" HUD::HUD() { strawberryCount = 0; cherryCount = 0; orangeCount = 0; hudBackground.objectId = PACMAN_SPRITESHEET::ID; hudBackground.objectRect = Rect{ SCREEN_HEIGHT, INITIAL_Y, HUD_WIDTH, SCREEN_HEIGHT }; hudBackground.objectSpriteRect = Rect{ (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_BACKGROUND, (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_BACKGROUND, PACMAN_SPRITESHEET::SPRITES_SIZE, PACMAN_SPRITESHEET::SPRITES_SIZE }; hudScoreID = new std::string[4]; hudScoreRect = new Rect[4]; for (int i = 0; i < 4; i++) { hudScoreID[i] = SCORE_0::ID; hudScoreRect[i].x = HUD_INFO::SCORE_INITIAL_X + i * HUD_INFO::SCORE_W; hudScoreRect[i].y = HUD_INFO::SCORE_INITIAL_Y; hudScoreRect[i].w = HUD_INFO::SCORE_W; hudScoreRect[i].h = HUD_INFO::SCORE_H; } hudXID = SCORE_X::ID; hudXRect[0] = Rect{ HUD_INFO::INITIAL_MULTIPLIER_X, HUD_INFO::INITIAL_STRAWBERRY_MULTIPLIER_Y, HUD_INFO::MULTIPLIER_X_SIZE , HUD_INFO::MULTIPLIER_Y_SIZE }; hudXRect[1] = Rect{ HUD_INFO::INITIAL_MULTIPLIER_X, HUD_INFO::INITIAL_CHERRY_MULTIPLIER_Y, HUD_INFO::MULTIPLIER_X_SIZE , HUD_INFO::MULTIPLIER_Y_SIZE }; hudXRect[2] = Rect{ HUD_INFO::INITIAL_MULTIPLIER_X, HUD_INFO::INITIAL_ORANGE_MULTIPLIER_Y, HUD_INFO::MULTIPLIER_X_SIZE , HUD_INFO::MULTIPLIER_Y_SIZE }; hudStrawberryID = SCORE_0::ID; hudStrawberryRect = Rect{ HUD_INFO::INITIAL_FRUITS_COUNT_X, HUD_INFO::INITIAL_STRAWBERRY_COUNT_Y, HUD_INFO::SCORE_W , HUD_INFO::SCORE_H }; hudCherryID = SCORE_0::ID; hudCherryRect = Rect{ HUD_INFO::INITIAL_FRUITS_COUNT_X, HUD_INFO::INITIAL_CHERRY_COUNT_Y, HUD_INFO::SCORE_W , HUD_INFO::SCORE_H }; hudOrangeID = SCORE_0::ID; hudOrangeRect = Rect{ HUD_INFO::INITIAL_FRUITS_COUNT_X, HUD_INFO::INITIAL_ORANGE_COUNT_Y, HUD_INFO::SCORE_W , HUD_INFO::SCORE_H }; hudCherry.objectId = PACMAN_SPRITESHEET::ID; hudCherry.objectRect = Rect{ HUD_INFO::INITIAL_CHERRY_X, HUD_INFO::INITIAL_CHERRY_Y, HUD_INFO::CHERRY_SIZE, HUD_INFO::CHERRY_SIZE }; hudCherry.objectSpriteRect = Rect{ (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_CHERRY, (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_CHERRY, PACMAN_SPRITESHEET::SPRITES_SIZE, PACMAN_SPRITESHEET::SPRITES_SIZE }; hudStrawberry.objectId = PACMAN_SPRITESHEET::ID; hudStrawberry.objectRect = Rect{ HUD_INFO::INITIAL_STRAWBERRY_X, HUD_INFO::INITIAL_STRAWBERRY_Y, HUD_INFO::STRAWBERRY_SIZE, HUD_INFO::STRAWBERRY_SIZE }; hudStrawberry.objectSpriteRect = Rect{ (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_STRAWBERRY, (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_STRAWBERRY, PACMAN_SPRITESHEET::SPRITES_SIZE, PACMAN_SPRITESHEET::SPRITES_SIZE }; hudOrange.objectId = PACMAN_SPRITESHEET::ID; hudOrange.objectRect = Rect{ HUD_INFO::INITIAL_ORANGE_X, HUD_INFO::INITIAL_ORANGE_Y, HUD_INFO::ORANGE_SIZE, HUD_INFO::ORANGE_SIZE }; hudOrange.objectSpriteRect = Rect{ (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_ORANGE, (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_ORANGE, PACMAN_SPRITESHEET::SPRITES_SIZE, PACMAN_SPRITESHEET::SPRITES_SIZE }; hudLives = new Object[PLAYER_INITIAL_INFO::LIVES]; for (int i = 0; i < PLAYER_INITIAL_INFO::LIVES; i++) { hudLives[i].objectId = PACMAN_SPRITESHEET::ID; hudLives[i].objectRect = Rect{ HUD_INFO::INITIAL_LIVE_X + i * HUD_INFO::LIVE_SIZE, HUD_INFO::INITIAL_LIVE_Y, HUD_INFO::LIVE_SIZE, HUD_INFO::LIVE_SIZE }; hudLives[i].objectSpriteRect = Rect{ (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_LIVE, (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_LIVE, PACMAN_SPRITESHEET::SPRITES_SIZE, PACMAN_SPRITESHEET::SPRITES_SIZE }; } hudSpaceStartID1 = PRESS_SPACE1::ID; hudSpaceStartRect1 = Rect{ PRESS_SPACE1::X, PRESS_SPACE1::Y, PRESS_SPACE1::W, PRESS_SPACE1::H }; hudSpaceStartID2 = PRESS_SPACE2::ID; hudSpaceStartRect2 = Rect{ PRESS_SPACE2::X, PRESS_SPACE2::Y, PRESS_SPACE2::W, PRESS_SPACE2::H }; hudSpacePauseID1 = NULL_TEXT::ID; hudSpacePauseRect1 = Rect{ STOP_PRESS_SPACE1::X, STOP_PRESS_SPACE1::Y, STOP_PRESS_SPACE1::W, STOP_PRESS_SPACE1::H }; hudSpacePauseID2 = NULL_TEXT::ID; hudSpacePauseRect2 = Rect{ STOP_PRESS_SPACE2::X, STOP_PRESS_SPACE2::Y, STOP_PRESS_SPACE2::W, STOP_PRESS_SPACE2::H }; hudSpacePauseID3 = NULL_TEXT::ID; hudSpacePauseRect3 = Rect{ STOP_PRESS_SPACE3::X, STOP_PRESS_SPACE3::Y, STOP_PRESS_SPACE3::W, STOP_PRESS_SPACE3::H }; hudSound = Button{ SOUND_PAUSE::ID, SOUND_PAUSE::ID, SOUND_PAUSE::X, SOUND_PAUSE::Y, SOUND_PAUSE::W, SOUND_PAUSE::H }; hudSound.buttonId = NULL_TEXT::ID; hudTransparent.objectId = PACMAN_SPRITESHEET::ID; hudTransparent.objectRect = Rect{ INITIAL_X, INITIAL_Y, SCREEN_WIDTH, SCREEN_HEIGHT };; hudTransparent.objectSpriteRect = Rect{ (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_TRANSPARENT, (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_TRANSPARENT, PACMAN_SPRITESHEET::SPRITES_SIZE, PACMAN_SPRITESHEET::SPRITES_SIZE }; } void HUD::Update() { switch (strawberryCount) { case 0: hudStrawberryID = SCORE_0::ID; break; case 1: hudStrawberryID = SCORE_1::ID; break; case 2: hudStrawberryID = SCORE_2::ID; break; case 3: hudStrawberryID = SCORE_3::ID; break; case 4: hudStrawberryID = SCORE_4::ID; break; case 5: hudStrawberryID = SCORE_5::ID; break; case 6: hudStrawberryID = SCORE_6::ID; break; case 7: hudStrawberryID = SCORE_7::ID; break; case 8: hudStrawberryID = SCORE_8::ID; break; case 9: hudStrawberryID = SCORE_9::ID; break; default: break; } switch (cherryCount) { case 0: hudCherryID = SCORE_0::ID; break; case 1: hudCherryID = SCORE_1::ID; break; case 2: hudCherryID = SCORE_2::ID; break; case 3: hudCherryID = SCORE_3::ID; break; case 4: hudCherryID = SCORE_4::ID; break; case 5: hudCherryID = SCORE_5::ID; break; case 6: hudCherryID = SCORE_6::ID; break; case 7: hudCherryID = SCORE_7::ID; break; case 8: hudCherryID = SCORE_8::ID; break; case 9: hudCherryID = SCORE_9::ID; break; default: break; } switch (orangeCount) { case 0: hudOrangeID = SCORE_0::ID; break; case 1: hudOrangeID = SCORE_1::ID; break; case 2: hudOrangeID = SCORE_2::ID; break; case 3: hudOrangeID = SCORE_3::ID; break; case 4: hudOrangeID = SCORE_4::ID; break; case 5: hudOrangeID = SCORE_5::ID; break; case 6: hudOrangeID = SCORE_6::ID; break; case 7: hudOrangeID = SCORE_7::ID; break; case 8: hudOrangeID = SCORE_8::ID; break; case 9: hudOrangeID = SCORE_9::ID; break; default: break; } } void HUD::DisableStart() { hudSpaceStartID1 = NULL_TEXT::ID; hudSpaceStartID2 = NULL_TEXT::ID; hudTransparent.objectSpriteRect.x = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_NULL; hudTransparent.objectSpriteRect.y = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_NULL; } void HUD::EnablePause() { hudSpacePauseID1 = STOP_PRESS_SPACE1::ID; hudSpacePauseID2 = STOP_PRESS_SPACE2::ID; hudSpacePauseID3 = STOP_PRESS_SPACE3::ID; hudSound.buttonId = SOUND_PAUSE::ID; hudTransparent.objectSpriteRect.x = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_TRANSPARENT; hudTransparent.objectSpriteRect.y = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_TRANSPARENT; } void HUD::DisablePause() { hudSpacePauseID1 = NULL_TEXT::ID; hudSpacePauseID2 = NULL_TEXT::ID; hudSpacePauseID3 = NULL_TEXT::ID; hudSound.buttonId = NULL_TEXT::ID; hudTransparent.objectSpriteRect.x = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).x / 8) * HUD_INFO::X_NULL; hudTransparent.objectSpriteRect.y = (Renderer::Instance()->GetTextureSize(PACMAN_SPRITESHEET::ID).y / 8) * HUD_INFO::Y_NULL; } void HUD::UpdateScoreInfo(int _playerScore) { int aux = 0; for (int i = 3; i >= 0; i--) { aux = _playerScore % 10; switch (aux) { case 0: hudScoreID[i] = SCORE_0::ID; break; case 1: hudScoreID[i] = SCORE_1::ID; break; case 2: hudScoreID[i] = SCORE_2::ID; break; case 3: hudScoreID[i] = SCORE_3::ID; break; case 4: hudScoreID[i] = SCORE_4::ID; break; case 5: hudScoreID[i] = SCORE_5::ID; break; case 6: hudScoreID[i] = SCORE_6::ID; break; case 7: hudScoreID[i] = SCORE_7::ID; break; case 8: hudScoreID[i] = SCORE_8::ID; break; case 9: hudScoreID[i] = SCORE_9::ID; break; default: break; } _playerScore /= 10; } } void HUD::Draw(int _lives) { Renderer::Instance()->PushSprite(hudBackground.objectId, hudBackground.objectSpriteRect, hudBackground.objectRect); for (int i = 0; i < 4; i++) { Renderer::Instance()->PushImage(hudScoreID[i], hudScoreRect[i]); } Renderer::Instance()->PushImage(hudXID, hudXRect[0]); Renderer::Instance()->PushImage(hudXID, hudXRect[1]); Renderer::Instance()->PushImage(hudXID, hudXRect[2]); Renderer::Instance()->PushImage(hudStrawberryID, hudStrawberryRect); Renderer::Instance()->PushImage(hudCherryID, hudCherryRect); Renderer::Instance()->PushImage(hudOrangeID, hudOrangeRect); Renderer::Instance()->PushSprite(hudCherry.objectId, hudCherry.objectSpriteRect, hudCherry.objectRect); Renderer::Instance()->PushSprite(hudStrawberry.objectId, hudStrawberry.objectSpriteRect, hudStrawberry.objectRect); Renderer::Instance()->PushSprite(hudOrange.objectId, hudOrange.objectSpriteRect, hudOrange.objectRect); for (int i = 0; i < _lives; i++) { Renderer::Instance()->PushSprite(hudLives[i].objectId, hudLives[i].objectSpriteRect, hudLives[i].objectRect); } Renderer::Instance()->PushSprite(hudTransparent.objectId, hudTransparent.objectSpriteRect, hudTransparent.objectRect); Renderer::Instance()->PushImage(hudSpaceStartID1, hudSpaceStartRect1); Renderer::Instance()->PushImage(hudSpaceStartID2, hudSpaceStartRect2); Renderer::Instance()->PushImage(hudSpacePauseID1, hudSpacePauseRect1); Renderer::Instance()->PushImage(hudSpacePauseID2, hudSpacePauseRect2); Renderer::Instance()->PushImage(hudSpacePauseID3, hudSpacePauseRect3); Renderer::Instance()->PushImage(hudSound.buttonId, hudSound.buttonRect); } HUD::~HUD() { }
/* Автор: Орлов Никита Описание: По latex запросу стоится посфиксная запись, для которой требуется список операторов с их приоритетом. Если оператор правоассоциативный, то его приоритет отрицательный, иначе положительный. */ #pragma once #include <set> #include <string> #include <vector> #include "StringTokenizer.h" #include "TokenTypes.h" #include <map> #include <regex> #include <stack> #include <iostream> /*Пока реализацией является класс, чтобы можно было добавить методы для построения дерева + есть внутренние методы, которые нужно скрыть от пользователя*/ class CNotationBuilder { public: CNotationBuilder(); void BuildReverseNotation( const std::string& src, const std::map< std::string, std::pair< int, std::string > >& funcArgsNum ); std::stack< std::string > GetNotation() const { return outputNotation; } std::set< std::string > GetVariableSet() const { return variableSet; } std::string GetFunctionName() { return functionName; } private: //флаг указывающий может ли следующая операция быть унарной bool mayUnary; //может ли текуйщий токен быть унарным оператором. int curTokenId; //Id токена, который рассматривается в момент построения нотации int bracArraySize; //размер массива скобок int currentArgsNum; //колличество аргументов, которое не нашел preTransform при преобразованиях. std::string functionName; //имя функции, передаваемой нам. //регулярные выражения для проверки std::string token; std::regex numberRegex; std::regex variableRegex; std::regex rightOpRegex; std::regex leftOpRegex; std::regex functionRegex; std::stack< std::pair< std::string, int > > tempStack; std::map< std::pair< std::string, int >, int > argsPreCalculatedCount; std::set< std::string > variableSet; std::vector< std::string > delimFrac, delimSqrtFigBrack, delimSqrtSqBrack; std::vector< int > seqOfBlocksForFrac; std::vector< int > orderSqrtFigBrack; std::vector< int > orderSqrtSqBrack; std::vector< int > criticalPositions; static const std::string bracket[]; std::string preTransform( std::string src, const std::string& codeName, int argsNumber, const std::vector< std::string >& delimetrs, const std::vector< int >& tokenPosition ); std::string findArgs( const std::string& src ); void processClosingBracket( const std::map< std::string, std::pair< int, std::string > >& argsTable ); void processComma(); void processOperator(); void dumpToOutput(); bool prepareAndCheck( CStringTokenizer& tokenizer, const std::string& src ); bool checkBrackets( CStringTokenizer& tokenizer ); void findCriticalPositions( int begIndex, const std::string& src ); std::stack< std::string > outputNotation; bool isUnary( const std::string& src ) { return ( src == "-" ); } bool isOpenBracket(std::string token) { return (token == "(") || (token == "{") || (token == "["); } bool isCloseBracket(std::string token) { return (token == ")") || (token == "}") || (token == "]"); } static std::map< std::string, int > operatorsPriority; }; std::stack< std::string > getNotation( const std::string& src);
#pragma once #include"Conversation.h" #include "afxdialogex.h" #include "Talk2Me.h" #include "afxcmn.h" using namespace std; // CChatRoom 对话框 class CChatRoom : public CDialogEx { DECLARE_DYNAMIC(CChatRoom) public: CChatRoom(int id,int ownerId, CWnd* pParent = NULL); // 标准构造函数 virtual ~CChatRoom(); virtual void OnClose(); int m_id;//roomId int m_owner;//owner id int nCurSel; //当前选中的行号 CString strText; //当前选中行的字符串 // 对话框数据 enum { IDD = IDD_CHATROOMDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedChatsendfilebtn(); afx_msg void OnLbnSelchangeOulist(); afx_msg void OnLbnSelchangeChatmemberlist(); afx_msg void OnBnClickedChatsendmsgbtn(); CString m_content; CString m_history; CString m_filePath; CString m_fileEx; CRichEditCtrl m_Scroll; };
#include "terrain_shader.h" namespace sloth { TerrainShader* TerrainShader::m_Inst = nullptr; TerrainShader::TerrainShader() : Shader(TERRAIN_VERTEX_FILE, TERRAIN_FRAGMENT_FILE) { getAllUniformLocation(); } TerrainShader::~TerrainShader() { delete[] m_LocLightPos; delete[] m_LocLightColor; delete[] m_LocAttenuation; m_Inst = nullptr; } TerrainShader * TerrainShader::inst() { if (!m_Inst) m_Inst = new TerrainShader(); return m_Inst; } void TerrainShader::loadModelMatrix(const glm::mat4 & model) { glProgramUniformMatrix4fv(m_ID, m_LocModel, 1, GL_FALSE, glm::value_ptr(model)); } void TerrainShader::loadViewMatrix(const RawCamera &camera) { glProgramUniformMatrix4fv(m_ID, m_LocView, 1, GL_FALSE, glm::value_ptr(camera.getViewMatrix())); } void TerrainShader::loadProjectionMatrix(const glm::mat4 & projection) { glProgramUniformMatrix4fv(m_ID, m_LocProjection, 1, GL_FALSE, glm::value_ptr(projection)); } void TerrainShader::loadLight(const Light & light) { glProgramUniform3f(m_ID, m_LocLightPos[0], light.position[0], light.position[1], light.position[2]); glProgramUniform3f(m_ID, m_LocLightColor[0], light.color[0], light.color[1], light.color[2]); glProgramUniform3f(m_ID, m_LocAttenuation[0], light.attenuation[0], light.attenuation[1], light.attenuation[2]); for (int i = 1; i < GLSL_MAX_LIGHTS; ++i) { glProgramUniform3f(m_ID, m_LocLightPos[i], 0.0f, 0.0f, 0.0f); glProgramUniform3f(m_ID, m_LocLightColor[i], 0.0f, 0.0f, 0.0f); glProgramUniform3f(m_ID, m_LocAttenuation[i], 1.0f, 0.0f, 0.0f); } } void TerrainShader::loadLights(const std::vector<Light>& lights) { for (size_t i = 0; i < GLSL_MAX_LIGHTS; ++i) { if (i < lights.size()) { glProgramUniform3f(m_ID, m_LocLightPos[i], lights[i].position[0], lights[i].position[1], lights[i].position[2]); glProgramUniform3f(m_ID, m_LocLightColor[i], lights[i].color[0], lights[i].color[1], lights[i].color[2]); glProgramUniform3f(m_ID, m_LocAttenuation[i], lights[i].attenuation[0], lights[i].attenuation[1], lights[i].attenuation[2]); } else { glProgramUniform3f(m_ID, m_LocLightPos[i], 0.0f, 0.0f, 0.0f); glProgramUniform3f(m_ID, m_LocLightColor[i], 0.0f, 0.0f, 0.0f); glProgramUniform3f(m_ID, m_LocAttenuation[i], 1.0f, 0.0f, 0.0f); } } } void TerrainShader::loadShineVariable(const float shininess, const float reflectivity) { glProgramUniform1f(m_ID, m_LocShininess, shininess); glProgramUniform1f(m_ID, m_LocReflectivity, reflectivity); } void TerrainShader::loadSkyColor(const float r, const float g, const float b) { glProgramUniform3f(m_ID, m_LocSkyColor, r, g, b); } void TerrainShader::connectTextureUnits() { glProgramUniform1i(m_ID, m_LocBackgroundTexture, 0); glProgramUniform1i(m_ID, m_LocRTexture, 1); glProgramUniform1i(m_ID, m_LocGTexture, 2); glProgramUniform1i(m_ID, m_LocBTexture, 3); glProgramUniform1i(m_ID, m_LocBlendMapTexture, 4); glProgramUniform1i(m_ID, m_LocShadowMap, 5); } void TerrainShader::loadClipPlane(const glm::vec4 & clipPlane) { glProgramUniform4f(m_ID, m_LocClipPlane, clipPlane.x, clipPlane.y, clipPlane.z, clipPlane.w); } void TerrainShader::loadLightSpace(const glm::mat4 & lightSpace) { glProgramUniformMatrix4fv(m_ID, m_LocLightSpace, 1, GL_FALSE, glm::value_ptr(lightSpace)); } void TerrainShader::getAllUniformLocation() { m_LocModel = glGetUniformLocation(m_ID, "model"); m_LocView = glGetUniformLocation(m_ID, "view"); m_LocProjection = glGetUniformLocation(m_ID, "projection"); m_LocShininess = glGetUniformLocation(m_ID, "shininess"); m_LocReflectivity = glGetUniformLocation(m_ID, "reflectivity"); m_LocLightPos = new int[GLSL_MAX_LIGHTS]; m_LocLightColor = new int[GLSL_MAX_LIGHTS]; m_LocAttenuation = new int[GLSL_MAX_LIGHTS]; for (int i = 0; i < GLSL_MAX_LIGHTS; ++i) { char c = '0' + i; m_LocLightPos[i] = glGetUniformLocation(m_ID, (std::string("lightPosition[") + c + "]").c_str()); m_LocLightColor[i] = glGetUniformLocation(m_ID, (std::string("lightColor[") + c + "]").c_str()); m_LocAttenuation[i] = glGetUniformLocation(m_ID, (std::string("attenuation[") + c + "]").c_str()); } m_LocSkyColor = glGetUniformLocation(m_ID, "skyColor"); m_LocBackgroundTexture = glGetUniformLocation(m_ID, "backgroundTexture"); m_LocRTexture = glGetUniformLocation(m_ID, "rTexture"); m_LocGTexture = glGetUniformLocation(m_ID, "gTexture"); m_LocBTexture = glGetUniformLocation(m_ID, "bTexture"); m_LocBlendMapTexture = glGetUniformLocation(m_ID, "blendMap"); m_LocClipPlane = glGetUniformLocation(m_ID, "clipPlane"); m_LocLightSpace = glGetUniformLocation(m_ID, "lightSpace"); m_LocShadowMap = glGetUniformLocation(m_ID, "shadowMap"); } }