hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
56720c144b05a88018c932b433a8c585033f0131
2,041
cpp
C++
src/Settings.cpp
gottyduke/BunnyHopperOfSkyrim
0b7539298bd0899060cc926bf3fc2b5758835014
[ "MIT" ]
2
2021-03-24T20:39:02.000Z
2021-08-09T02:12:10.000Z
src/Settings.cpp
gottyduke/BunnyHopperOfSkyrim
0b7539298bd0899060cc926bf3fc2b5758835014
[ "MIT" ]
null
null
null
src/Settings.cpp
gottyduke/BunnyHopperOfSkyrim
0b7539298bd0899060cc926bf3fc2b5758835014
[ "MIT" ]
2
2021-03-24T20:39:04.000Z
2021-08-09T02:12:15.000Z
#include "Settings.h" bool Settings::LoadSettings(const bool a_dumpParse) { auto [log, success] = J2S::load_settings(FILE_NAME, a_dumpParse); if (!log.empty()) { _ERROR("%s", log.c_str()); } return success; } decltype(Settings::globalSpeedMult) Settings::globalSpeedMult("globalSpeedMult", 1.0f); decltype(Settings::maxSpeed) Settings::maxSpeed("maxSpeed", 450.0f); decltype(Settings::misttepAllowed) Settings::misttepAllowed("misstepAllowed", 4); decltype(Settings::baseSpeedBoost) Settings::baseSpeedBoost("baseSpeedBoost", 1.0f); decltype(Settings::baseSpeedMult) Settings::baseSpeedMult("baseSpeedMult", 1.0f); decltype(Settings::minStrafeAngle) Settings::minStrafeAngle("minStrafeAngle", 35.0f); decltype(Settings::maxStrafeAngle) Settings::maxStrafeAngle("maxStrafeAngle", 95.0f); decltype(Settings::strafeDeadzone) Settings::strafeDeadzone("strafeDeadzone", 35.0f); decltype(Settings::strafeSpeedMult) Settings::strafeSpeedMult("strafeSpeedMult", 0.5f); decltype(Settings::minHeightLaunch) Settings::minHeightLaunch("minHeightLaunch", 140.0f); decltype(Settings::heightLaunchMult) Settings::heightLaunchMult("heightLaunchMult", 0.5f); decltype(Settings::crouchSpeedBoost) Settings::crouchSpeedBoost("crouchSpeedBoost", 32.0f); decltype(Settings::crouchBoostMult) Settings::crouchBoostMult("crouchBoostMult", 1.0f); decltype(Settings::crouchBoostCooldown) Settings::crouchBoostCooldown("crouchBoostCooldown", 6); decltype(Settings::ramDamage) Settings::ramDamage("ramDamage", 5.0f); decltype(Settings::ramDamageMult) Settings::ramDamageMult("ramDamageMult", 0.3f); decltype(Settings::ramSpeedThreshold) Settings::ramSpeedThreshold("ramSpeedThreshold", 220.0f); decltype(Settings::ramSpeedReduction) Settings::ramSpeedReduction("ramSpeedReduction", 0.5f); decltype(Settings::enableJumpFeedback) Settings::enableJumpFeedback("enableJumpFeedback", true); decltype(Settings::enableFovZoom) Settings::enableFovZoom("enableFovZoom", true); decltype(Settings::enableTremble) Settings::enableTremble("enableTremble", false);
47.465116
96
0.799118
5676f6326df5b8e56d60ed31f3ff4155d6890611
4,507
hpp
C++
searchlib/src/vespa/searchlib/util/posting_priority_queue_merger.hpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/util/posting_priority_queue_merger.hpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/util/posting_priority_queue_merger.hpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "posting_priority_queue.hpp" #include "posting_priority_queue_merger.h" namespace search { template <class Reader, class Writer> void PostingPriorityQueueMerger<Reader, Writer>::mergeHeap(Writer& writer, const IFlushToken& flush_token, uint32_t remaining_merge_chunk) { while (remaining_merge_chunk > 0u && !empty() && !flush_token.stop_requested()) { Reader *low = lowest(); low->write(writer); low->read(); adjust(); --remaining_merge_chunk; } } template <class Reader, class Writer> void PostingPriorityQueueMerger<Reader, Writer>::mergeOne(Writer& writer, Reader& reader, const IFlushToken& flush_token, uint32_t remaining_merge_chunk) { while (remaining_merge_chunk > 0u && reader.isValid() && !flush_token.stop_requested()) { reader.write(writer); reader.read(); --remaining_merge_chunk; } } template <class Reader, class Writer> void PostingPriorityQueueMerger<Reader, Writer>::mergeTwo(Writer& writer, Reader& reader1, Reader& reader2, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk) { while (remaining_merge_chunk > 0u && !flush_token.stop_requested()) { Reader &low = reader2 < reader1 ? reader2 : reader1; low.write(writer); low.read(); --remaining_merge_chunk; if (!low.isValid()) { break; } } } template <class Reader, class Writer> void PostingPriorityQueueMerger<Reader, Writer>::mergeSmall(Writer& writer, typename Vector::iterator ib, typename Vector::iterator ie, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk) { while (remaining_merge_chunk > 0u && !flush_token.stop_requested()) { typename Vector::iterator i = ib; Reader *low = i->get(); for (++i; i != ie; ++i) if (*i->get() < *low) low = i->get(); low->write(writer); low->read(); --remaining_merge_chunk; if (!low->isValid()) { break; } } } template <class Reader, class Writer> void PostingPriorityQueueMerger<Reader, Writer>::merge(Writer& writer, const IFlushToken& flush_token) { if (_vec.empty()) return; assert(_heap_limit > 0u); uint32_t remaining_merge_chunk = _merge_chunk; if (_vec.size() >= _heap_limit) { void (PostingPriorityQueueMerger::*mergeHeapFunc)(Writer& writer, const IFlushToken& flush_token, uint32_t remaining_merge_chunk) = &PostingPriorityQueueMerger::mergeHeap; (this->*mergeHeapFunc)(writer, flush_token, remaining_merge_chunk); return; } while (remaining_merge_chunk > 0u && !flush_token.stop_requested()) { if (_vec.size() == 1) { void (*mergeOneFunc)(Writer& writer, Reader& reader, const IFlushToken& flush_token, uint32_t remaining_merge_chunk) = &PostingPriorityQueueMerger::mergeOne; (*mergeOneFunc)(writer, *_vec.front().get(), flush_token, remaining_merge_chunk); if (!_vec.front().get()->isValid()) { _vec.clear(); } return; } if (_vec.size() == 2) { void (*mergeTwoFunc)(Writer& writer, Reader& reader1, Reader& reader2, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk) = &PostingPriorityQueueMerger::mergeTwo; (*mergeTwoFunc)(writer, *_vec[0].get(), *_vec[1].get(), flush_token, remaining_merge_chunk); } else { void (*mergeSmallFunc)(Writer& writer, typename Vector::iterator ib, typename Vector::iterator ie, const IFlushToken& flush_token, uint32_t& remaining_merge_chunk) = &PostingPriorityQueueMerger::mergeSmall; (*mergeSmallFunc)(writer, _vec.begin(), _vec.end(), flush_token, remaining_merge_chunk); } for (typename Vector::iterator i = _vec.begin(), ie = _vec.end(); i != ie; ++i) { if (!i->get()->isValid()) { _vec.erase(i); break; } } for (typename Vector::iterator i = _vec.begin(), ie = _vec.end(); i != ie; ++i) { assert(i->get()->isValid()); } assert(!_vec.empty()); } } }
37.247934
195
0.609274
56779e040eb36d545987180dc664df785d04e324
967
hpp
C++
rkt/src/MainScene.hpp
gbuzogany/dash
8667f19fdf288172dad6e28f59c55cd54b3ca8f7
[ "BSD-3-Clause" ]
null
null
null
rkt/src/MainScene.hpp
gbuzogany/dash
8667f19fdf288172dad6e28f59c55cd54b3ca8f7
[ "BSD-3-Clause" ]
null
null
null
rkt/src/MainScene.hpp
gbuzogany/dash
8667f19fdf288172dad6e28f59c55cd54b3ca8f7
[ "BSD-3-Clause" ]
null
null
null
#ifndef MainScene_hpp #define MainScene_hpp #include <stdio.h> #include <iostream> #include <ft2build.h> #include <map> #include <thread> #include <queue> #include FT_FREETYPE_H #include "Scene.hpp" #include "Definitions.h" #include "Animation.hpp" #include "Utils.hpp" #include "SpriteMap.hpp" #include "ShaderProgram.hpp" class MainScene : Scene { GLuint screenTexture; GLuint frameBuffer; GLuint baseTex; GLuint maskTex; GLuint FX1Tex; GLuint FX1FlowTex; GLuint background; std::queue<Animation*> animationQueue; SpriteMap *dashIcons; ShaderProgram *vfxProgram; FontWrapper *x4b03; FontWrapper *robotoSmall; FontWrapper *robotoMedium; FontWrapper *robotoSpeed; void createFramebuffer(); public: MainScene(Renderer *r, RocketteServiceImpl *service); ~MainScene(); void render(); void renderFixed(); bool update(float delta); }; #endif /* MainScene_hpp */
19.34
57
0.692865
56796e2def726508cf2edce78e7c18190d9ceeb1
1,905
inl
C++
dependencies/gl++/framebuffer/Framebuffer.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
dependencies/gl++/framebuffer/Framebuffer.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
dependencies/gl++/framebuffer/Framebuffer.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
/*! \file Framebuffer.inl * \author Jared Hoberock * \brief Inline file for Framebuffer.h. */ #include "Framebuffer.h" Framebuffer::Framebuffer(void):Parent() { setTarget(GL_FRAMEBUFFER_EXT); } // end Framebuffer::Framebuffer() void Framebuffer::attachTexture(const GLenum textureTarget, const GLenum attachment, const GLuint texture, const GLint level) { glFramebufferTexture2DEXT(getTarget(), attachment, textureTarget, texture, level); } // end Framebuffer::attachTexture() void Framebuffer::attachTextureLayer(const GLenum attachment, const GLuint texture, const GLint layer, const GLint level) { #ifdef WIN32 glFramebufferTextureLayerEXT(getTarget(), attachment, texture, level, layer); #else std::cerr << "Not implemented on Ubuntu yet." << std::endl; #endif // WIN32 } // end Framebuffer::attachTextureLayer() void Framebuffer::attachRenderbuffer(const GLenum renderbufferTarget, const GLenum attachment, const GLuint renderbuffer) { glFramebufferRenderbufferEXT(getTarget(), attachment, renderbufferTarget, renderbuffer); } // end Framebuffer::attachRenderbuffer() void Framebuffer::detach(const GLenum attachment) { glFramebufferTexture2DEXT(getTarget(), attachment, GL_TEXTURE_RECTANGLE_NV, 0, 0); } // end Framebuffer::detach() bool Framebuffer::isComplete(void) const { return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(getTarget()); } // end Framebuffer::isComplete()
34.636364
82
0.580577
567f9fdd36f0d77e4b5a192dc733ef3c87aa4dfd
5,320
cpp
C++
admin/wmi/wbem/providers/wdmprovider/classfac.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/providers/wdmprovider/classfac.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/providers/wdmprovider/classfac.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//////////////////////////////////////////////////////////////////////////////////////// // // CLASSFAC.CPP // // Purpose: Contains the class factory. This creates objects when // connections are requested. // // Copyright (c) 1997-2002 Microsoft Corporation, All Rights Reserved // //////////////////////////////////////////////////////////////////////////////////////// #include "precomp.h" #include "wdmdefs.h" //////////////////////////////////////////////////////////////////////////////////////// // // Constructor // //////////////////////////////////////////////////////////////////////////////////////// CProvFactory::CProvFactory(const CLSID & ClsId) { m_cRef=0L; InterlockedIncrement((LONG *) &g_cObj); m_ClsId = ClsId; } //////////////////////////////////////////////////////////////////////////////////////// // // Destructor // //////////////////////////////////////////////////////////////////////////////////////// CProvFactory::~CProvFactory(void) { InterlockedDecrement((LONG *) &g_cObj); } //////////////////////////////////////////////////////////////////////////////////////// // // Standard Ole routines needed for all interfaces // //////////////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CProvFactory::QueryInterface(REFIID riid, PPVOID ppv) { HRESULT hr = E_NOINTERFACE; *ppv=NULL; if (IID_IUnknown==riid || IID_IClassFactory==riid) { *ppv=this; } if (NULL!=*ppv) { AddRef(); hr = NOERROR; } return hr; } ///////////////////////////////////////////////////////////////////////// STDMETHODIMP_(ULONG) CProvFactory::AddRef(void) { return InterlockedIncrement((long*)&m_cRef); } ///////////////////////////////////////////////////////////////////////// STDMETHODIMP_(ULONG) CProvFactory::Release(void) { ULONG cRef = InterlockedDecrement( (long*) &m_cRef); if ( !cRef ){ delete this; return 0; } return cRef; } //////////////////////////////////////////////////////////////////////////////////////// // // Instantiates an object returning an interface pointer. // //////////////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CProvFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, PPVOID ppvObj) { HRESULT hr = E_OUTOFMEMORY; IUnknown* pObj = NULL; *ppvObj=NULL; //================================================================== // This object doesnt support aggregation. //================================================================== try { if (NULL!=pUnkOuter) { hr = CLASS_E_NOAGGREGATION; } else { //============================================================== //Create the object passing function to notify on destruction. //============================================================== if (m_ClsId == CLSID_WMIProvider) { CWMI_Prov * ptr = new CWMI_Prov () ; if( ptr ) { if ( FALSE == ptr->Initialized () ) { delete ptr ; ptr = NULL ; hr = E_FAIL ; } else { if ( FAILED ( hr = ptr->QueryInterface ( __uuidof ( IUnknown ), ( void ** ) &pObj ) ) ) { delete ptr ; ptr = NULL ; } } } } else if (m_ClsId == CLSID_WMIEventProvider) { CWMIEventProvider *ptr = new CWMIEventProvider ( WMIEVENT ) ; if( ptr ) { if ( FALSE == ptr->Initialized () ) { delete ptr ; ptr = NULL ; hr = E_FAIL ; } else { if ( FAILED ( hr = ptr->QueryInterface ( __uuidof ( IUnknown ), ( void ** ) &pObj ) ) ) { delete ptr ; ptr = NULL ; } } } } else if (m_ClsId == CLSID_WMIHiPerfProvider) { CWMIHiPerfProvider *ptr = new CWMIHiPerfProvider ( ) ; if( ptr ) { if ( FALSE == ptr->Initialized () ) { delete ptr ; ptr = NULL ; hr = E_FAIL ; } else { if ( FAILED ( hr = ptr->QueryInterface ( __uuidof ( IUnknown ), ( void ** ) &pObj ) ) ) { delete ptr ; ptr = NULL ; } } } } } } catch ( Heap_Exception & e ) { } if ( pObj ) { hr = pObj->QueryInterface(riid, ppvObj); pObj->Release () ; pObj = NULL ; } return hr; } //////////////////////////////////////////////////////////////////////////////////////// // // Increments or decrements the lock count of the DLL. If the // lock count goes to zero and there are no objects, the DLL // is allowed to unload. See DllCanUnloadNow. // //////////////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CProvFactory::LockServer(BOOL fLock) { if (fLock) InterlockedIncrement(&g_cLock); else InterlockedDecrement(&g_cLock); return NOERROR; }
25.825243
97
0.36485
568391550cc1ee675da1debff7b38b5cb9565139
12,373
cpp
C++
src/public/src/yssystemfont/src/windows/yswin32systemfont.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
1
2019-08-10T00:24:09.000Z
2019-08-10T00:24:09.000Z
src/public/src/yssystemfont/src/windows/yswin32systemfont.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
null
null
null
src/public/src/yssystemfont/src/windows/yswin32systemfont.cpp
rothberg-cmu/rothberg-run
a42df5ca9fae97de77753864f60d05295d77b59f
[ "MIT" ]
2
2019-05-01T03:11:10.000Z
2019-05-01T03:30:35.000Z
/* //////////////////////////////////////////////////////////// File Name: yswin32systemfont.cpp Copyright (c) 2017 Soji Yamakawa. All rights reserved. http://www.ysflight.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////// */ #include <stdio.h> #include "../yssystemfont.h" // The following block is needed for SetDCPenColor >> #if defined(_WIN32_WINNT) && _WIN32_WINNT<0x0500 #undef _WIN32_WINNT #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0500 #endif // The following block is needed for SetDCPenColor << #include <windows.h> class YsSystemFontInternalBitmapCache { public: HBITMAP hBmp; unsigned int wid,hei; void *bit; int bitPerPixel; YsSystemFontInternalBitmapCache(); }; YsSystemFontInternalBitmapCache::YsSystemFontInternalBitmapCache() { hBmp=NULL; wid=0; hei=0; bit=NULL; bitPerPixel=0; } class YsSystemFontCache::InternalData { private: HDC hDC; HGDIOBJ hPrevFont,hPrevBmp; YsSystemFontInternalBitmapCache hBmpCache; public: InternalData(); ~InternalData(); void SetHFont(HFONT hFont); void FreeFont(void); unsigned char *RGBABitmap( unsigned int &wid,unsigned int &hei,unsigned int &bytePerLine, const wchar_t str[],unsigned int outputBitPerPixel, const unsigned char fgCol[3],const unsigned char bgCol[3], YSBOOL reverse); YSRESULT GetTightBitmapSize(int &wid,int &hei,const wchar_t str[]) const; private: HBITMAP CreateDIB(void *&bit,int &srcBitPerPixel,unsigned int wid,unsigned int hei); }; YsSystemFontCache::InternalData::InternalData() { hDC=CreateCompatibleDC(NULL); SetTextAlign(hDC,TA_LEFT|TA_TOP|TA_NOUPDATECP); hPrevFont=NULL; const unsigned int cacheWid=640; const unsigned int cacheHei=120; void *bit; int bitPerPixel; hBmpCache.hBmp=CreateDIB(bit,bitPerPixel,cacheWid,cacheHei); if(NULL!=hBmpCache.hBmp) { hBmpCache.wid=cacheWid; hBmpCache.hei=cacheHei; hBmpCache.bit=bit; hBmpCache.bitPerPixel=bitPerPixel; hPrevBmp=SelectObject(hDC,hBmpCache.hBmp); } else { hPrevBmp=NULL; } } YsSystemFontCache::InternalData::~InternalData() { FreeFont(); if(NULL!=hBmpCache.hBmp) { DeleteObject(hBmpCache.hBmp); } if(NULL!=hDC) { DeleteDC(hDC); } } HBITMAP YsSystemFontCache::InternalData::CreateDIB(void *&bit,int &srcBitPerPixel,unsigned int wid,unsigned int hei) { YSBOOL reverse=YSFALSE; srcBitPerPixel=24; BITMAPINFOHEADER hdr= { sizeof(BITMAPINFOHEADER), 0,0,1,8,BI_RGB,0,0,0,0,0 }; hdr.biWidth=wid; if(YSTRUE!=reverse) { hdr.biHeight=-(int)hei; } else { hdr.biHeight=hei; } hdr.biBitCount=(WORD)srcBitPerPixel; hdr.biCompression=BI_RGB; return CreateDIBSection(hDC,(BITMAPINFO *)&hdr,DIB_RGB_COLORS,&bit,NULL,0); } void YsSystemFontCache::InternalData::SetHFont(HFONT hFont) { if(NULL!=hPrevFont) { FreeFont(); } hPrevFont=SelectObject(hDC,hFont); } void YsSystemFontCache::InternalData::FreeFont(void) { if(NULL!=hPrevFont) { HGDIOBJ hFontToDel=SelectObject(hDC,hPrevFont); DeleteObject(hFontToDel); hPrevFont=NULL; } } unsigned char *YsSystemFontCache::InternalData::RGBABitmap( unsigned int &wid,unsigned int &hei,unsigned int &dstBytePerLine, const wchar_t str[],unsigned int dstBitPerPixel, const unsigned char fgCol[3],const unsigned char bgCol[3], YSBOOL reverse) { if(NULL==str || (1!=dstBitPerPixel && 16!=dstBitPerPixel && 32!=dstBitPerPixel)) { // Currently 16bit:GrayScale+Alpha and 32bit:TrueColor+Alpha only. wid=0; hei=0; return NULL; } wid=0; hei=0; int i=0,i0=0; for(;;) { if(0==str[i] || '\n'==str[i]) { RECT rect; rect.left=0; rect.top=0; rect.right=100; rect.bottom=100; if(i0<i) { DrawTextExW(hDC,(wchar_t *)str+i0,i-i0,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL); } else { DrawTextExW(hDC,L" ",1,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL); } if(wid<(unsigned int)rect.right) { wid=rect.right; } hei+=rect.bottom; i0=i+1; } if(0==str[i]) { break; } i++; } wid=((wid+3)/4)*4; int srcBitPerPixel; void *bit; HBITMAP hBmp=NULL; HGDIOBJ hPrevBmp=NULL; int srcWid=0; if(NULL!=hBmpCache.hBmp && wid<=hBmpCache.wid && hei<=hBmpCache.hei) { hBmp=hBmpCache.hBmp; srcWid=hBmpCache.wid; srcBitPerPixel=hBmpCache.bitPerPixel; bit=hBmpCache.bit; hPrevBmp=NULL; } else { hBmp=CreateDIB(bit,srcBitPerPixel,wid,hei); srcWid=wid; hPrevBmp=SelectObject(hDC,hBmp); } int srcBytePerLine=((srcWid+3)/4)*4*srcBitPerPixel/8; // Needs to be signed. ZeroMemory(bit,srcBytePerLine*hei); SetTextColor(hDC,RGB(255,255,255)); SetDCPenColor(hDC,RGB(255,255,255)); SetBkColor(hDC,RGB(0,0,0)); SetBkMode(hDC,OPAQUE); RECT rect; rect.left=0; rect.top=0; rect.right=wid; rect.bottom=hei; i=0; i0=0; for(;;) { if(0==str[i] || '\n'==str[i]) { int hei; if(i0<i) { hei=DrawTextExW(hDC,(wchar_t *)str+i0,i-i0,&rect,DT_TOP|DT_LEFT,NULL); } else { hei=DrawTextExW(hDC,L" ",1,&rect,DT_TOP|DT_LEFT,NULL); } rect.top+=hei; rect.bottom+=hei; i0=i+1; } if(0==str[i]) { break; } i++; } unsigned char *retBuf=NULL; switch(dstBitPerPixel) { case 1: dstBytePerLine=((wid+31)&~31)/8; break; case 16: case 32: dstBytePerLine=wid*dstBitPerPixel/8; break; } retBuf=new unsigned char [dstBytePerLine*hei]; if(1==dstBitPerPixel) { for(int i=0; i<(int)(dstBytePerLine*hei); i++) { retBuf[i]=0; } } unsigned char *srcLineTop=(unsigned char *)bit,*dstLineTop=retBuf; if(YSTRUE==reverse) { srcLineTop+=(hei-1)*srcBytePerLine; srcBytePerLine=-srcBytePerLine; } for(unsigned int y=0; y<hei; y++) { unsigned char *srcPtr=srcLineTop; unsigned char *dstPtr=dstLineTop; unsigned char dstMask=0x80; switch(dstBitPerPixel) { case 1: for(int x=0; (unsigned int)x<wid; x++,srcPtr+=3) { if(128<*srcPtr) { (*dstPtr)|=dstMask; } if(1==dstMask) { dstMask=0x80; dstPtr++; } else { dstMask>>=1; } } break; case 16: for(int x=0; (unsigned int)x<wid; x++,srcPtr+=3) { if(128<*srcPtr) { dstPtr[0]=fgCol[0]; dstPtr[1]=255; } else { dstPtr[0]=bgCol[0]; dstPtr[1]=0; } dstPtr+=2; } break; case 32: for(int x=0; (unsigned int)x<wid; x++,srcPtr+=3) { if(128<*srcPtr) { dstPtr[0]=fgCol[0]; dstPtr[1]=fgCol[1]; dstPtr[2]=fgCol[2]; dstPtr[3]=255; } else { dstPtr[0]=bgCol[0]; dstPtr[1]=bgCol[1]; dstPtr[2]=bgCol[2]; dstPtr[3]=0; } dstPtr+=4; } break; } dstLineTop+=dstBytePerLine; srcLineTop+=srcBytePerLine; } if(NULL!=hPrevBmp) { SelectObject(hDC,hPrevBmp); } if(hBmpCache.hBmp!=hBmp) { DeleteObject(hBmp); } return retBuf; } YSRESULT YsSystemFontCache::InternalData::GetTightBitmapSize(int &wid,int &hei,const wchar_t str[]) const { if(NULL==str || 0==str[0]) { wid=0; hei=0; return YSOK; } wid=0; hei=0; int i=0,i0=0; for(;;) { if(0==str[i] || '\n'==str[i]) { RECT rect; rect.left=0; rect.top=0; rect.right=100; rect.bottom=100; if(i0<i) { DrawTextExW(hDC,(wchar_t *)str+i0,i-i0,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL); } else { DrawTextExW(hDC,L" ",1,&rect,DT_TOP|DT_LEFT|DT_CALCRECT,NULL); } if(wid<(int)rect.right) { wid=rect.right; } hei+=rect.bottom; i0=i+1; } if(0==str[i]) { break; } i++; } return YSOK; } YsSystemFontCache::YsSystemFontCache() { internal=new YsSystemFontCache::InternalData; } YsSystemFontCache::~YsSystemFontCache() { delete internal; } YSRESULT YsSystemFontCache::RequestDefaultFont(void) { HFONT hFont=NULL; NONCLIENTMETRICSW metric; metric.cbSize=sizeof(metric); if(0!=SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,sizeof(metric),&metric,0)) { hFont=CreateFontIndirectW(&metric.lfMenuFont); } else { HFONT hSysFont=(HFONT)GetStockObject(DEFAULT_GUI_FONT); LOGFONTW logFontW; if(NULL!=hSysFont && 0<GetObjectW(hSysFont,sizeof(logFontW),&logFontW)) { // Making a copy of the system font. Stock object is not supposed to be deleted later. hFont=CreateFontIndirectW(&logFontW); } } if(NULL!=hFont) { internal->SetHFont(hFont); return YSOK; } return YSERR; } YSRESULT YsSystemFontCache::RequestDefaultFontWithHeight(int height) { HFONT hFont=NULL; NONCLIENTMETRICSW metric; metric.cbSize=sizeof(metric); hFont=CreateFont( -height, 0, // nWidth auto select 0, // nEscapement 0, // nOrientation FW_DONTCARE, // fnWeight FALSE, // fdwItalic FALSE, // fdwUnderline FALSE, // fdwStrikeOut DEFAULT_CHARSET, // fdwCharSet OUT_DEFAULT_PRECIS, // fdwOutputPrecision CLIP_DEFAULT_PRECIS, // fdwClipPrecision DEFAULT_QUALITY, // WORD fdwQuality DEFAULT_PITCH, // fdwPitchAndFamily NULL); // lpszFace Use whatever found first. if(NULL==hFont) { if(0!=SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,sizeof(metric),&metric,0)) { LOGFONTW logFontW=metric.lfMenuFont; logFontW.lfHeight=-height; hFont=CreateFontIndirectW(&logFontW); } } if(NULL==hFont) { HFONT hSysFont=(HFONT)GetStockObject(DEFAULT_GUI_FONT); LOGFONTW logFontW; if(NULL!=hSysFont && 0<GetObjectW(hSysFont,sizeof(logFontW),&logFontW)) { // Making a copy of the system font. Stock object is not supposed to be deleted later. logFontW.lfHeight=-height; hFont=CreateFontIndirectW(&logFontW); } } if(NULL!=hFont) { internal->SetHFont(hFont); return YSOK; } return YSERR; } YSRESULT YsSystemFontCache::MakeSingleBitBitmap(YsSystemFontTextBitmap &bmp,const wchar_t wStr[],YSBOOL reverse) const { unsigned int wid,hei,bytePerLine; const unsigned int bitPerPixel=1; const unsigned char fgCol[3]={255,255,255},bgCol[3]={0,0,0}; unsigned char *dat=internal->RGBABitmap(wid,hei,bytePerLine,wStr,bitPerPixel,fgCol,bgCol,reverse); if(NULL!=dat) { bmp.SetBitmap(wid,hei,bytePerLine,bitPerPixel,dat); return YSOK; } return YSERR; } YSRESULT YsSystemFontCache::MakeRGBABitmap(YsSystemFontTextBitmap &bmp,const wchar_t wStr[],const unsigned char fgCol[3],const unsigned char bgCol[3],YSBOOL reverse) const { unsigned int wid,hei,bytePerLine; const unsigned int bitPerPixel=32; unsigned char *dat=internal->RGBABitmap(wid,hei,bytePerLine,wStr,bitPerPixel,fgCol,bgCol,reverse); if(NULL!=dat) { bmp.SetBitmap(wid,hei,bytePerLine,bitPerPixel,dat); return YSOK; } return YSERR; } YSRESULT YsSystemFontCache::MakeGrayScaleAndAlphaBitmap(YsSystemFontTextBitmap &bmp,const wchar_t wStr[],unsigned char fgColS,unsigned char bgColS,YSBOOL reverse) const { const unsigned char fgCol[3]={fgColS,fgColS,fgColS},bgCol[3]={bgColS,bgColS,bgColS}; unsigned int wid,hei,bytePerLine; const unsigned int bitPerPixel=16; unsigned char *dat=internal->RGBABitmap(wid,hei,bytePerLine,wStr,bitPerPixel,fgCol,bgCol,reverse); if(NULL!=dat) { bmp.SetBitmap(wid,hei,bytePerLine,bitPerPixel,dat); return YSOK; } return YSERR; } YSRESULT YsSystemFontCache::GetTightBitmapSize(int &wid,int &hei,const wchar_t str[]) const { return internal->GetTightBitmapSize(wid,hei,str); }
20.656093
171
0.693041
5683b9d1393d2d9026b43d7ac0d9abaff4b5a99a
6,028
hpp
C++
source/sema/sema_node_visitor.hpp
stryku/cmakesl
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
[ "BSD-3-Clause" ]
51
2019-05-06T01:33:34.000Z
2021-11-17T11:44:54.000Z
source/sema/sema_node_visitor.hpp
stryku/cmakesl
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
[ "BSD-3-Clause" ]
191
2019-05-06T18:31:24.000Z
2020-06-19T06:48:06.000Z
source/sema/sema_node_visitor.hpp
stryku/cmakesl
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
[ "BSD-3-Clause" ]
3
2019-10-12T21:03:29.000Z
2020-06-19T06:22:25.000Z
#pragma once namespace cmsl::sema { class add_declarative_file_node; class add_subdirectory_node; class add_subdirectory_with_declarative_script_node; class add_subdirectory_with_old_script_node; class binary_operator_node; class block_node; class bool_value_node; class break_node; class cast_to_reference_node; class cast_to_reference_to_base_node; class cast_to_base_value_node; class cast_to_value_node; class class_member_access_node; class class_node; class conditional_node; class constructor_call_node; class designated_initializers_node; class double_value_node; class enum_constant_access_node; class enum_node; class for_node; class function_call_node; class function_node; class id_node; class if_else_node; class implicit_member_function_call_node; class implicit_return_node; class import_node; class initializer_list_node; class int_value_node; class member_function_call_node; class namespace_node; class return_node; class sema_node; class string_value_node; class ternary_operator_node; class translation_unit_node; class unary_operator_node; class variable_declaration_node; class while_node; class sema_node_visitor { public: virtual ~sema_node_visitor() = default; virtual void visit(const initializer_list_node& node) = 0; virtual void visit(const add_declarative_file_node& node) = 0; virtual void visit(const add_subdirectory_node& node) = 0; virtual void visit( const add_subdirectory_with_declarative_script_node& node) = 0; virtual void visit(const add_subdirectory_with_old_script_node& node) = 0; virtual void visit(const binary_operator_node& node) = 0; virtual void visit(const block_node& node) = 0; virtual void visit(const bool_value_node& node) = 0; virtual void visit(const break_node& node) = 0; virtual void visit(const cast_to_reference_node& node) = 0; virtual void visit(const cast_to_value_node& node) = 0; virtual void visit(const cast_to_reference_to_base_node& node) = 0; virtual void visit(const cast_to_base_value_node& node) = 0; virtual void visit(const class_member_access_node& node) = 0; virtual void visit(const class_node& node) = 0; virtual void visit(const conditional_node& node) = 0; virtual void visit(const constructor_call_node& node) = 0; virtual void visit(const designated_initializers_node& node) = 0; virtual void visit(const double_value_node& node) = 0; virtual void visit(const enum_constant_access_node& node) = 0; virtual void visit(const enum_node& node) = 0; virtual void visit(const for_node& node) = 0; virtual void visit(const function_call_node& node) = 0; virtual void visit(const function_node& node) = 0; virtual void visit(const id_node& node) = 0; virtual void visit(const if_else_node& node) = 0; virtual void visit(const implicit_member_function_call_node& node) = 0; virtual void visit(const implicit_return_node& node) = 0; virtual void visit(const import_node& node) = 0; virtual void visit(const int_value_node& node) = 0; virtual void visit(const member_function_call_node& node) = 0; virtual void visit(const namespace_node& node) = 0; virtual void visit(const return_node& node) = 0; virtual void visit(const string_value_node& node) = 0; virtual void visit(const ternary_operator_node& node) = 0; virtual void visit(const translation_unit_node& node) = 0; virtual void visit(const unary_operator_node& node) = 0; virtual void visit(const variable_declaration_node& node) = 0; virtual void visit(const while_node& node) = 0; }; class empty_sema_node_visitor : public sema_node_visitor { public: virtual ~empty_sema_node_visitor() = default; virtual void visit(const add_declarative_file_node&) override {} virtual void visit(const add_subdirectory_node&) override {} virtual void visit(const add_subdirectory_with_old_script_node&) override {} virtual void visit( const add_subdirectory_with_declarative_script_node& node) override { } virtual void visit(const binary_operator_node&) override {} virtual void visit(const block_node&) override {} virtual void visit(const bool_value_node&) override {} virtual void visit(const break_node&) override {} virtual void visit(const cast_to_reference_to_base_node&) override {} virtual void visit(const cast_to_base_value_node&) override {} virtual void visit(const cast_to_reference_node&) override {} virtual void visit(const cast_to_value_node&) override {} virtual void visit(const class_member_access_node&) override {} virtual void visit(const class_node&) override {} virtual void visit(const conditional_node&) override {} virtual void visit(const constructor_call_node&) override {} virtual void visit(const designated_initializers_node&) override {} virtual void visit(const double_value_node&) override {} virtual void visit(const enum_constant_access_node&) override {} virtual void visit(const enum_node&) override {} virtual void visit(const for_node&) override {} virtual void visit(const function_call_node&) override {} virtual void visit(const function_node&) override {} virtual void visit(const id_node&) override {} virtual void visit(const if_else_node&) override {} virtual void visit(const implicit_member_function_call_node&) override {} virtual void visit(const implicit_return_node&) override {} virtual void visit(const import_node&) override {} virtual void visit(const initializer_list_node&) override {} virtual void visit(const int_value_node&) override {} virtual void visit(const member_function_call_node&) override {} virtual void visit(const namespace_node&) override {} virtual void visit(const return_node&) override {} virtual void visit(const string_value_node&) override {} virtual void visit(const ternary_operator_node&) override {} virtual void visit(const translation_unit_node&) override {} virtual void visit(const unary_operator_node&) override {} virtual void visit(const variable_declaration_node&) override {} virtual void visit(const while_node&) override {} }; }
42.751773
78
0.7928
568979b22aa48321f52ee46162c98edbae691c38
41,473
cpp
C++
src/component_route.cpp
skfzyy/WEAVESS
dd529e37ebccaedebbd801a6ef9bf67373594369
[ "MIT" ]
21
2021-03-31T10:44:07.000Z
2022-03-21T03:46:43.000Z
src/component_route.cpp
skfzyy/WEAVESS
dd529e37ebccaedebbd801a6ef9bf67373594369
[ "MIT" ]
null
null
null
src/component_route.cpp
skfzyy/WEAVESS
dd529e37ebccaedebbd801a6ef9bf67373594369
[ "MIT" ]
17
2021-02-01T10:54:53.000Z
2022-03-15T02:49:18.000Z
// // Created by MurphySL on 2020/10/23. // #include "weavess/component.h" namespace weavess { void ComponentSearchRouteGreedy::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &res) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); std::vector<char> flags(index->getBaseLen(), 0); int k = 0; while (k < (int) L) { int nk = L; if (pool[k].flag) { pool[k].flag = false; unsigned n = pool[k].id; index->addHopCount(); for (unsigned m = 0; m < index->getLoadGraph()[n].size(); ++m) { unsigned id = index->getLoadGraph()[n][m]; if (flags[id])continue; flags[id] = 1; float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * id, (unsigned) index->getBaseDim()); index->addDistCount(); if (dist >= pool[L - 1].distance) continue; Index::Neighbor nn(id, dist, true); int r = Index::InsertIntoPool(pool.data(), L, nn); //if(L+1 < retset.size()) ++L; if (r < nk)nk = r; } //lock to here } if (nk <= k)k = nk; else ++k; } res.resize(K); for (size_t i = 0; i < K; i++) { res[i] = pool[i].id; } } void ComponentSearchRouteNSW::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &res) { const auto K = index->getParam().get<unsigned>("K_search"); auto *visited_list = new Index::VisitedList(index->getBaseLen()); Index::HnswNode *enterpoint = index->nodes_[0]; std::priority_queue<Index::FurtherFirst> result; std::priority_queue<Index::CloserFirst> tmp; SearchAtLayer(query, enterpoint, 0, visited_list, result); while(!result.empty()) { tmp.push(Index::CloserFirst(result.top().GetNode(), result.top().GetDistance())); result.pop(); } res.resize(K); int pos = 0; while (!tmp.empty() && pos < K) { auto *top_node = tmp.top().GetNode(); tmp.pop(); res[pos] = top_node->GetId(); pos ++; } delete visited_list; } void ComponentSearchRouteNSW::SearchAtLayer(unsigned qnode, Index::HnswNode *enterpoint, int level, Index::VisitedList *visited_list, std::priority_queue<Index::FurtherFirst> &result) { const auto L = index->getParam().get<unsigned>("L_search"); // TODO: check Node 12bytes => 8bytes std::priority_queue<Index::CloserFirst> candidates; float d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(), index->getBaseData() + enterpoint->GetId() * index->getBaseDim(), index->getBaseDim()); index->addDistCount(); result.emplace(enterpoint, d); candidates.emplace(enterpoint, d); visited_list->Reset(); visited_list->MarkAsVisited(enterpoint->GetId()); while (!candidates.empty()) { const Index::CloserFirst &candidate = candidates.top(); float lower_bound = result.top().GetDistance(); if (candidate.GetDistance() > lower_bound) break; Index::HnswNode *candidate_node = candidate.GetNode(); std::unique_lock<std::mutex> lock(candidate_node->GetAccessGuard()); const std::vector<Index::HnswNode *> &neighbors = candidate_node->GetFriends(level); candidates.pop(); index->addHopCount(); for (const auto &neighbor : neighbors) { int id = neighbor->GetId(); if (visited_list->NotVisited(id)) { visited_list->MarkAsVisited(id); d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(), index->getBaseData() + neighbor->GetId() * index->getBaseDim(), index->getBaseDim()); index->addDistCount(); if (result.size() < L || result.top().GetDistance() > d) { result.emplace(neighbor, d); candidates.emplace(neighbor, d); if (result.size() > L) result.pop(); } } } } } void ComponentSearchRouteHNSW::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &res) { const auto K = index->getParam().get<unsigned>("K_search"); // const auto L = index->getParam().get<unsigned>("L_search"); auto *visited_list = new Index::VisitedList(index->getBaseLen()); Index::HnswNode *enterpoint = index->enterpoint_; std::vector<std::pair<Index::HnswNode *, float>> ensure_k_path_; Index::HnswNode *cur_node = enterpoint; float d = index->getDist()->compare(index->getQueryData() + query * index->getQueryDim(), index->getBaseData() + cur_node->GetId() * index->getBaseDim(), index->getBaseDim()); index->addDistCount(); float cur_dist = d; ensure_k_path_.clear(); ensure_k_path_.emplace_back(cur_node, cur_dist); for (auto i = index->max_level_; i >= 0; --i) { visited_list->Reset(); unsigned visited_mark = visited_list->GetVisitMark(); unsigned int* visited = visited_list->GetVisited(); visited[cur_node->GetId()] = visited_mark; bool changed = true; while (changed) { changed = false; std::unique_lock<std::mutex> local_lock(cur_node->GetAccessGuard()); const std::vector<Index::HnswNode *> &neighbors = cur_node->GetFriends(i); index->addHopCount(); for (auto iter = neighbors.begin(); iter != neighbors.end(); ++iter) { if(visited[(*iter)->GetId()] != visited_mark) { visited[(*iter)->GetId()] = visited_mark; d = index->getDist()->compare(index->getQueryData() + query * index->getQueryDim(), index->getBaseData() + (*iter)->GetId() * index->getBaseDim(), index->getBaseDim()); index->addDistCount(); if (d < cur_dist) { cur_dist = d; cur_node = *iter; changed = true; ensure_k_path_.emplace_back(cur_node, cur_dist); } } } } } //std::cout << "ensure_k : " << ensure_k_path_.size() << " " << ensure_k_path_[0].first->GetId() << std::endl; // std::vector<std::pair<Index::HnswNode*, float>> tmp; std::priority_queue<Index::FurtherFirst> result; std::priority_queue<Index::CloserFirst> tmp; while(result.size() < K && !ensure_k_path_.empty()) { cur_dist = ensure_k_path_.back().second; ensure_k_path_.pop_back(); SearchAtLayer(query, ensure_k_path_.back().first, 0, visited_list, result); } while(!result.empty()) { tmp.push(Index::CloserFirst(result.top().GetNode(), result.top().GetDistance())); result.pop(); } res.resize(K); int pos = 0; while (!tmp.empty() && pos < K) { auto *top_node = tmp.top().GetNode(); tmp.pop(); res[pos] = top_node->GetId(); pos ++; } delete visited_list; } void ComponentSearchRouteHNSW::SearchAtLayer(unsigned qnode, Index::HnswNode *enterpoint, int level, Index::VisitedList *visited_list, std::priority_queue<Index::FurtherFirst> &result) { const auto L = index->getParam().get<unsigned>("L_search"); // TODO: check Node 12bytes => 8bytes std::priority_queue<Index::CloserFirst> candidates; float d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(), index->getBaseData() + enterpoint->GetId() * index->getBaseDim(), index->getBaseDim()); index->addDistCount(); result.emplace(enterpoint, d); candidates.emplace(enterpoint, d); visited_list->Reset(); visited_list->MarkAsVisited(enterpoint->GetId()); while (!candidates.empty()) { const Index::CloserFirst &candidate = candidates.top(); float lower_bound = result.top().GetDistance(); if (candidate.GetDistance() > lower_bound) break; Index::HnswNode *candidate_node = candidate.GetNode(); std::unique_lock<std::mutex> lock(candidate_node->GetAccessGuard()); const std::vector<Index::HnswNode *> &neighbors = candidate_node->GetFriends(level); candidates.pop(); index->addHopCount(); for (const auto &neighbor : neighbors) { int id = neighbor->GetId(); if (visited_list->NotVisited(id)) { visited_list->MarkAsVisited(id); d = index->getDist()->compare(index->getQueryData() + qnode * index->getQueryDim(), index->getBaseData() + neighbor->GetId() * index->getBaseDim(), index->getBaseDim()); index->addDistCount(); if (result.size() < L || result.top().GetDistance() > d) { result.emplace(neighbor, d); candidates.emplace(neighbor, d); if (result.size() > L) result.pop(); } } } } } // void ComponentSearchRouteHNSW::SearchById_(unsigned query, Index::HnswNode* cur_node, float cur_dist, size_t k, // size_t ef_search, std::vector<std::pair<Index::HnswNode*, float>> &result) { // Index::IdDistancePairMinHeap candidates; // Index::IdDistancePairMinHeap visited_nodes; // candidates.emplace(cur_node, cur_dist); // auto *visited_list_ = new Index::VisitedList(index->getBaseLen()); // visited_list_->Reset(); // unsigned int visited_mark = visited_list_->GetVisitMark(); // unsigned int* visited = visited_list_->GetVisited(); // size_t already_visited_for_ensure_k = 0; // if (!result.empty()) { // already_visited_for_ensure_k = result.size(); // for (size_t i = 0; i < result.size(); ++i) { // if (result[i].first->GetId() == cur_node->GetId()) { // return ; // } // visited[result[i].first->GetId()] = visited_mark; // visited_nodes.emplace(std::move(result[i])); // } // result.clear(); // } // visited[cur_node->GetId()] = visited_mark; // //std::cout << "wtf" << std::endl; // float farthest_distance = cur_dist; // size_t total_size = 1; // while (!candidates.empty() && visited_nodes.size() < ef_search+already_visited_for_ensure_k) { // //std::cout << "wtf1" << std::endl; // const Index::IdDistancePair& c = candidates.top(); // cur_node = c.first; // visited_nodes.emplace(std::move(const_cast<Index::IdDistancePair&>(c))); // candidates.pop(); // float minimum_distance = farthest_distance; // int size = cur_node->GetFriends(0).size(); // index->addHopCount(); // //std::cout << "wtf2" << std::endl; // for (auto j = 1; j < size; ++j) { // int node_id = cur_node->GetFriends(0)[j]->GetId(); // //std::cout << "wtf4" << std::endl; // if (visited[node_id] != visited_mark) { // visited[node_id] = visited_mark; // //std::cout << "wtf5" << std::endl; // float d = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, // index->getBaseData() + index->getBaseDim() * node_id, // index->getBaseDim()); // index->addDistCount(); // //std::cout << "wtf6" << std::endl; // if (d < minimum_distance || total_size < ef_search) { // candidates.emplace(cur_node->GetFriends(0)[j], d); // if (d > farthest_distance) { // farthest_distance = d; // } // ++total_size; // } // //std::cout << "wtf7" << std::endl; // } // } // //std::cout << "wtf3" << std::endl; // } // //std::cout << "wtf" <<std::endl; // while (result.size() < k) { // if (!candidates.empty() && !visited_nodes.empty()) { // const Index::IdDistancePair& c = candidates.top(); // const Index::IdDistancePair& v = visited_nodes.top(); // if (c.second < v.second) { // result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(c))); // candidates.pop(); // } else { // result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(v))); // visited_nodes.pop(); // } // } else if (!candidates.empty()) { // const Index::IdDistancePair& c = candidates.top(); // result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(c))); // candidates.pop(); // } else if (!visited_nodes.empty()) { // const Index::IdDistancePair& v = visited_nodes.top(); // result.emplace_back(std::move(const_cast<Index::IdDistancePair&>(v))); // visited_nodes.pop(); // } else { // break; // } // } // } void ComponentSearchRouteIEH::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &result) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); //GNNS Index::CandidateHeap2 cands; for (size_t j = 0; j < pool.size(); j++) { int neighbor = pool[j].id; Index::Candidate2<float> c(neighbor, index->getDist()->compare(&index->test[query][0], &index->train[neighbor][0], index->test[query].size())); index->addDistCount(); cands.insert(c); if (cands.size() > L)cands.erase(cands.begin()); } //iteration // auto expand = index->getParam().get<unsigned>("expand"); auto iterlimit = index->getParam().get<unsigned>("iterlimit"); int niter = 0; while (niter++ < iterlimit) { auto it = cands.rbegin(); std::vector<int> ids; index->addHopCount(); for (int j = 0; it != cands.rend() && j < L; it++, j++) { int neighbor = it->row_id; auto nnit = index->knntable[neighbor].rbegin(); for (int k = 0; nnit != index->knntable[neighbor].rend(); nnit++, k++) { int nn = nnit->row_id; ids.push_back(nn); } } for (size_t j = 0; j < ids.size(); j++) { Index::Candidate2<float> c(ids[j], index->getDist()->compare(&index->test[query][0], &index->train[ids[j]][0], index->test[query].size())); index->addDistCount(); cands.insert(c); if (cands.size() > L)cands.erase(cands.begin()); } }//cout<<i<<endl; auto it = cands.rbegin(); for(int j = 0; it != cands.rend() && j < K; it++, j++){ result.push_back(it->row_id); } } void ComponentSearchRouteBacktrack::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &res) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); std::priority_queue<Index::FANNGCloserFirst> queue; std::priority_queue<Index::FANNGCloserFirst> full; std::vector<char> flags(index->getBaseLen()); for(int i = 0; i < index->getBaseLen(); i ++) flags[i] = false; std::unordered_map<unsigned, int> mp; std::unordered_map<unsigned, unsigned> relation; unsigned enter = pool[0].id; unsigned start = index->getLoadGraph()[enter][0]; relation[start] = enter; mp[enter] = 0; float dist = index->getDist()->compare(index->getBaseData() + index->getBaseDim() * start, index->getQueryData() + index->getQueryDim() * query, index->getBaseDim()); index->addDistCount(); int m = 1; queue.push(Index::FANNGCloserFirst(start, dist)); full.push(Index::FANNGCloserFirst(start, dist)); while(!queue.empty() && m < L) { //std::cout << 1 << std::endl; unsigned top_node = queue.top().GetNode(); queue.pop(); if(!flags[top_node]) { flags[top_node] = true; unsigned nnid = index->getLoadGraph()[top_node][0]; relation[nnid] = top_node; mp[top_node] = 0; m += 1; float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * nnid, index->getBaseDim()); index->addDistCount(); queue.push(Index::FANNGCloserFirst(nnid, dist)); full.push(Index::FANNGCloserFirst(nnid, dist)); } //std::cout << 2 << std::endl; unsigned start_node = relation[top_node]; //std::cout << 3 << " " << start_node << std::endl; unsigned pos = 0; auto iter = mp.find(start_node); //std::cout << 3.11 << " " << (*iter).second << std::endl; //std::cout << index->getFinalGraph()[start_node].size() << std::endl; if((*iter).second < index->getLoadGraph()[start_node].size() - 1) { //std::cout << 3.1 << std::endl; pos = (*iter).second + 1; mp[start_node] = pos; unsigned nnid = index->getLoadGraph()[start_node][pos]; //std::cout << 3.2 << " " << nnid << std::endl; relation[nnid] = start_node; float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * nnid, index->getBaseDim()); index->addDistCount(); //std::cout << 3.3 << std::endl; queue.push(Index::FANNGCloserFirst(nnid, dist)); full.push(Index::FANNGCloserFirst(nnid, dist)); } index->addHopCount(); //std::cout << 4 << std::endl; } int i = 0; while(!full.empty() && i < K) { res.push_back(full.top().GetNode()); full.pop(); i ++; } //std::cout << 5 << std::endl; } void ComponentSearchRouteGuided::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &res) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); std::vector<char> flags(index->getBaseLen(), 0); int k = 0; while (k < (int)L) { int nk = L; if (pool[k].flag) { pool[k].flag = false; unsigned n = pool[k].id; unsigned div_dim_ = index->Tn[n].div_dim; unsigned left_len = index->Tn[n].left.size(); // std::cout << "left_len: " << left_len << std::endl; unsigned right_len = index->Tn[n].right.size(); // std::cout << "right_len: " << right_len << std::endl; std::vector<unsigned> nn; unsigned MaxM; if ((index->getQueryData() + index->getQueryDim() * query)[div_dim_] < (index->getBaseData() + index->getBaseDim() * n)[div_dim_]) { MaxM = left_len; nn = index->Tn[n].left; } else { MaxM = right_len; nn = index->Tn[n].right; } index->addHopCount(); for (unsigned m = 0; m < MaxM; ++m) { unsigned id = nn[m]; if (flags[id]) continue; flags[id] = 1; float dist = index->getDist()->compare(index->getQueryData() + query * index->getQueryDim(), index->getBaseData() + id * index->getBaseDim(), (unsigned)index->getBaseDim()); index->addDistCount(); if (dist >= pool[L - 1].distance) continue; Index::Neighbor nn(id, dist, true); int r = Index::InsertIntoPool(pool.data(), L, nn); // if(L+1 < retset.size()) ++L; if (r < nk) nk = r; } } if (nk <= k) k = nk; else ++k; } // for(int i = 0; i < pool.size(); i ++) { // std::cout << pool[i].id << "|" << pool[i].distance << " "; // } // std::cout << std::endl; // std::cout << std::endl; res.resize(K); for (size_t i = 0; i < K; i++) { res[i] = pool[i].id; } } void ComponentSearchRouteSPTAG_KDT::KDTSearch(unsigned int query, int node, Index::Heap &m_NGQueue, Index::Heap &m_SPTQueue, Index::OptHashPosVector &nodeCheckStatus, unsigned int &m_iNumberOfCheckedLeaves, unsigned int &m_iNumberOfTreeCheckedLeaves) { if (node < 0) { int tmp = -node - 1; if (tmp >= index->getBaseLen()) return; if (nodeCheckStatus.CheckAndSet(tmp)) return; ++m_iNumberOfTreeCheckedLeaves; ++m_iNumberOfCheckedLeaves; m_NGQueue.insert(Index::HeapCell(tmp, index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * tmp, index->getBaseDim()))); index->addDistCount(); return; } auto& tnode = index->m_pKDTreeRoots[node]; float distBound = 0; float diff = (index->getQueryData() + index->getQueryDim() * query)[tnode.split_dim] - tnode.split_value; float distanceBound = distBound + diff * diff; int otherChild, bestChild; if (diff < 0) { bestChild = tnode.left; otherChild = tnode.right; } else { otherChild = tnode.left; bestChild = tnode.right; } m_SPTQueue.insert(Index::HeapCell(otherChild, distanceBound)); KDTSearch(query, bestChild, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves); } void ComponentSearchRouteSPTAG_KDT::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &result) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); unsigned m_iNumberOfCheckedLeaves = 0; unsigned m_iNumberOfTreeCheckedLeaves = 0; unsigned m_iNumOfContinuousNoBetterPropagation = 0; const float MaxDist = (std::numeric_limits<float>::max)(); unsigned m_iThresholdOfNumberOfContinuousNoBetterPropagation = 3; unsigned m_iNumberOfOtherDynamicPivots = 4; unsigned m_iNumberOfInitialDynamicPivots = 50; unsigned maxCheck = index->m_iMaxCheckForRefineGraph > index->m_iMaxCheck ? index->m_iMaxCheckForRefineGraph : index->m_iMaxCheck; // Prioriy queue used for neighborhood graph Index::Heap m_NGQueue; m_NGQueue.Resize(maxCheck * 30); // Priority queue Used for Tree Index::Heap m_SPTQueue; m_SPTQueue.Resize(maxCheck * 10); Index::OptHashPosVector nodeCheckStatus; nodeCheckStatus.Init(maxCheck, index->m_iHashTableExp); nodeCheckStatus.CheckAndSet(query); Index::QueryResultSet p_query(L); for(int i = 0; i < index->m_iTreeNumber; i ++) { int node = index->m_pTreeStart[i]; KDTSearch(query, node, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves); } unsigned p_limits = m_iNumberOfInitialDynamicPivots; while (!m_SPTQueue.empty() && m_iNumberOfCheckedLeaves < p_limits) { auto& tcell = m_SPTQueue.pop(); KDTSearch(query, tcell.node, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves); } while (!m_NGQueue.empty()) { Index::HeapCell gnode = m_NGQueue.pop(); std::vector<unsigned> node = index->getLoadGraph()[gnode.node]; if (!p_query.AddPoint(gnode.node, gnode.distance) && m_iNumberOfCheckedLeaves > index->m_iMaxCheck) { p_query.SortResult(); for(int i = 0; i < p_query.GetResultNum(); i ++) { if(p_query.GetResult(i)->Dist == MaxDist) break; result.emplace_back(p_query.GetResult(i)->VID); } result.resize(result.size() > K ? K : result.size()); return; } float upperBound = std::max(p_query.worstDist(), gnode.distance); bool bLocalOpt = true; index->addHopCount(); for (unsigned i = 0; i < node.size(); i++) { unsigned nn_index = node[i]; if (nn_index < 0) break; if (nodeCheckStatus.CheckAndSet(nn_index)) continue; float distance2leaf = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * nn_index, index->getBaseDim()); index->addDistCount(); if (distance2leaf <= upperBound) bLocalOpt = false; m_iNumberOfCheckedLeaves++; m_NGQueue.insert(Index::HeapCell(nn_index, distance2leaf)); } if (bLocalOpt) m_iNumOfContinuousNoBetterPropagation++; else m_iNumOfContinuousNoBetterPropagation = 0; if (m_iNumOfContinuousNoBetterPropagation > m_iThresholdOfNumberOfContinuousNoBetterPropagation) { if (m_iNumberOfTreeCheckedLeaves <= m_iNumberOfCheckedLeaves / 10) { auto& tcell = m_SPTQueue.pop(); KDTSearch(query, tcell.node, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves); } else if (gnode.distance > p_query.worstDist()) { break; } } } p_query.SortResult(); for(int i = 0; i < p_query.GetResultNum(); i ++) { if(p_query.GetResult(i)->Dist == MaxDist) break; result.emplace_back(p_query.GetResult(i)->VID); // std::cout << p_query.GetResult(i)->VID << "|" << p_query.GetResult(i)->Dist << " "; } // std::cout << std::endl; result.resize(result.size() > K ? K : result.size()); } void ComponentSearchRouteSPTAG_BKT::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &result) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); unsigned maxCheck = index->m_iMaxCheckForRefineGraph > index->m_iMaxCheck ? index->m_iMaxCheckForRefineGraph : index->m_iMaxCheck; unsigned m_iContinuousLimit = maxCheck / 64; const float MaxDist = (std::numeric_limits<float>::max)(); unsigned m_iNumOfContinuousNoBetterPropagation = 0; unsigned m_iNumberOfCheckedLeaves = 0; unsigned m_iNumberOfTreeCheckedLeaves = 0; // Prioriy queue used for neighborhood graph Index::Heap m_NGQueue; m_NGQueue.Resize(maxCheck * 30); // Priority queue Used for Tree Index::Heap m_SPTQueue; m_SPTQueue.Resize(maxCheck * 10); Index::OptHashPosVector nodeCheckStatus; nodeCheckStatus.Init(maxCheck, index->m_iHashTableExp); nodeCheckStatus.CheckAndSet(query); Index::QueryResultSet p_query(L); for (char i = 0; i < index->m_iTreeNumber; i++) { const Index::BKTNode& node = index->m_pBKTreeRoots[index->m_pTreeStart[i]]; if (node.childStart < 0) { float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * node.centerid, index->getBaseDim()); index->addDistCount(); m_SPTQueue.insert(Index::HeapCell(index->m_pTreeStart[i], dist)); } else { for (int begin = node.childStart; begin < node.childEnd; begin++) { int tmp = index->m_pBKTreeRoots[begin].centerid; float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * tmp, index->getBaseDim()); index->addDistCount(); m_SPTQueue.insert(Index::HeapCell(begin, dist)); } } } BKTSearch(query, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves, index->m_iNumberOfInitialDynamicPivots); const unsigned checkPos = index->getLoadGraph()[0].size() - 1; while (!m_NGQueue.empty()) { Index::HeapCell gnode = m_NGQueue.pop(); int tmpNode = gnode.node; std::vector<unsigned> node = index->getLoadGraph()[tmpNode]; if (gnode.distance <= p_query.worstDist()) { int checkNode = node[checkPos]; if (checkNode < -1) { const Index::BKTNode& tnode = index->m_pBKTreeRoots[-2 - checkNode]; m_iNumOfContinuousNoBetterPropagation = 0; p_query.AddPoint(tmpNode, gnode.distance); } else { m_iNumOfContinuousNoBetterPropagation = 0; p_query.AddPoint(tmpNode, gnode.distance); } } else { m_iNumOfContinuousNoBetterPropagation++; if (m_iNumOfContinuousNoBetterPropagation > m_iContinuousLimit || m_iNumberOfCheckedLeaves > maxCheck) { p_query.SortResult(); for(int i = 0; i < p_query.GetResultNum(); i ++) { if(p_query.GetResult(i)->Dist == MaxDist) break; result.emplace_back(p_query.GetResult(i)->VID); } result.resize(result.size() > K ? K : result.size()); return; } } index->addHopCount(); for (unsigned i = 0; i <= checkPos; i++) { int nn_index = node[i]; if (nn_index < 0) break; if (nodeCheckStatus.CheckAndSet(nn_index)) continue; float distance2leaf = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * nn_index, index->getBaseDim()); index->addDistCount(); m_iNumberOfCheckedLeaves++; m_NGQueue.insert(Index::HeapCell(nn_index, distance2leaf)); } if (m_NGQueue.Top().distance > m_SPTQueue.Top().distance) { BKTSearch(query, m_NGQueue, m_SPTQueue, nodeCheckStatus, m_iNumberOfCheckedLeaves, m_iNumberOfTreeCheckedLeaves, index->m_iNumberOfOtherDynamicPivots + m_iNumberOfCheckedLeaves); } } p_query.SortResult(); for(int i = 0; i < p_query.GetResultNum(); i ++) { if(p_query.GetResult(i)->Dist == MaxDist) break; result.emplace_back(p_query.GetResult(i)->VID); } result.resize(result.size() > K ? K : result.size()); } void ComponentSearchRouteSPTAG_BKT::BKTSearch(unsigned int query, Index::Heap &m_NGQueue, Index::Heap &m_SPTQueue, Index::OptHashPosVector &nodeCheckStatus, unsigned int &m_iNumberOfCheckedLeaves, unsigned int &m_iNumberOfTreeCheckedLeaves, int p_limits) { while (!m_SPTQueue.empty()) { Index::HeapCell bcell = m_SPTQueue.pop(); const Index::BKTNode& tnode = index->m_pBKTreeRoots[bcell.node]; if (tnode.childStart < 0) { if (!nodeCheckStatus.CheckAndSet(tnode.centerid)) { m_iNumberOfCheckedLeaves++; m_NGQueue.insert(Index::HeapCell(tnode.centerid, bcell.distance)); } if (m_iNumberOfCheckedLeaves >= p_limits) break; } else { if (!nodeCheckStatus.CheckAndSet(tnode.centerid)) { m_NGQueue.insert(Index::HeapCell(tnode.centerid, bcell.distance)); } for (int begin = tnode.childStart; begin < tnode.childEnd; begin++) { int tmp = index->m_pBKTreeRoots[begin].centerid; float dist = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * tmp, index->getBaseDim()); index->addDistCount(); m_SPTQueue.insert(Index::HeapCell(begin, dist)); } } } } void ComponentSearchRouteNGT::RouteInner(unsigned int query, std::vector<Index::Neighbor> &pool, std::vector<unsigned int> &res) { const auto L = index->getParam().get<unsigned>("L_search"); const auto K = index->getParam().get<unsigned>("K_search"); float radius = static_cast<float>(FLT_MAX); // setup edgeSize size_t edgeSize = pool.size(); std::priority_queue<Index::Neighbor, std::vector<Index::Neighbor>, std::greater<Index::Neighbor>> unchecked; Index::DistanceCheckedSet distanceChecked; std::priority_queue<Index::Neighbor, std::vector<Index::Neighbor>, std::less<Index::Neighbor>> results; //setupDistances(sc, seeds); //setupSeeds(sc, seeds, results, unchecked, distanceChecked); std::sort(pool.begin(), pool.end()); for (auto ri = pool.begin(); ri != pool.end(); ri++){ if ((results.size() < L) && ((*ri).distance <= radius)){ results.push((*ri)); }else{ break; } } if (results.size() >= L){ radius = results.top().distance; } for (auto ri = pool.begin(); ri != pool.end(); ri++){ distanceChecked.insert((*ri).id); unchecked.push(*ri); } float explorationRadius = index->explorationCoefficient * radius; while (!unchecked.empty()){ //std::cout << "radius: " << explorationRadius << std::endl; Index::Neighbor target = unchecked.top(); unchecked.pop(); if (target.distance > explorationRadius){ break; } std::vector<unsigned> neighbors = index->getLoadGraph()[target.id]; if (neighbors.empty()){ continue; } index->addHopCount(); for (unsigned neighborptr = 0; neighborptr < neighbors.size(); ++neighborptr){ //sc.visitCount++; unsigned neighbor = index->getLoadGraph()[target.id][neighborptr]; if (distanceChecked[neighbor]){ continue; } distanceChecked.insert(neighbor); float distance = index->getDist()->compare(index->getQueryData() + index->getQueryDim() * query, index->getBaseData() + index->getBaseDim() * neighbor, index->getBaseDim()); index->addDistCount(); //sc.distanceComputationCount++; if (distance <= explorationRadius){ unchecked.push(Index::Neighbor(neighbor, distance, true)); if (distance <= radius){ results.push(Index::Neighbor(neighbor, distance, true)); if (results.size() >= L){ if (results.top().distance >= distance){ if (results.size() > L){ results.pop(); } radius = results.top().distance; explorationRadius = index->explorationCoefficient * radius; } } } } } } //std::cout << "res : " << results.size() << std::endl; while(!results.empty()) { //std::cout << results.top().id << "|" << results.top().distance << " "; if(results.size() <= K) { res.push_back(results.top().id); } results.pop(); } //std::cout << std::endl; sort(res.begin(), res.end()); //sc.distanceComputationCount = so.distanceComputationCount; //sc.visitCount = so.visitCount; } }
44.787257
194
0.494732
568bd9ad3cb2f62679e434f75af209d2486a40cb
3,909
hpp
C++
openstudiocore/src/model/SolarCollectorFlatPlatePhotovoltaicThermal.hpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
1
2016-12-29T08:45:03.000Z
2016-12-29T08:45:03.000Z
openstudiocore/src/model/SolarCollectorFlatPlatePhotovoltaicThermal.hpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
openstudiocore/src/model/SolarCollectorFlatPlatePhotovoltaicThermal.hpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef MODEL_SOLARCOLLECTORFLATPLATEPHOTOVOLTAICTHERMAL_HPP #define MODEL_SOLARCOLLECTORFLATPLATEPHOTOVOLTAICTHERMAL_HPP #include "ModelAPI.hpp" #include "StraightComponent.hpp" namespace openstudio { namespace model { class PlanarSurface; class GeneratorPhotovoltaic; class SolarCollectorPerformancePhotovoltaicThermalSimple; namespace detail { class SolarCollectorFlatPlatePhotovoltaicThermal_Impl; } // detail /** SolarCollectorFlatPlatePhotovoltaicThermal is a StraightComponent that wraps the OpenStudio IDD object 'OS:SolarCollector:FlatPlate:PhotovoltaicThermal'. */ class MODEL_API SolarCollectorFlatPlatePhotovoltaicThermal : public StraightComponent { public: /** @name Constructors and Destructors */ //@{ explicit SolarCollectorFlatPlatePhotovoltaicThermal(const Model& model); virtual ~SolarCollectorFlatPlatePhotovoltaicThermal() {} //@} static IddObjectType iddObjectType(); /** @name Getters */ //@{ SolarCollectorPerformancePhotovoltaicThermalSimple solarCollectorPerformance() const; boost::optional<PlanarSurface> surface() const; boost::optional<GeneratorPhotovoltaic> generatorPhotovoltaic() const; boost::optional<double> designFlowRate() const; bool isDesignFlowRateAutosized() const; //@} /** @name Setters */ //@{ /// Deletes the current parameters and clones the parameters passed in bool setSolarCollectorPerformance(const SolarCollectorPerformancePhotovoltaicThermalSimple& parameters); /// Deletes the current parameters and constructs a new default set of parameters void resetSolarCollectorPerformance(); bool setSurface(const PlanarSurface& surface); void resetSurface(); bool setGeneratorPhotovoltaic(const GeneratorPhotovoltaic& generatorPhotovoltaic); void resetGeneratorPhotovoltaic(); bool setDesignFlowRate(double designFlowRate); void resetDesignFlowRate(); void autosizeDesignFlowRate(); //@} /** @name Other */ //@{ //@} protected: /// @cond typedef detail::SolarCollectorFlatPlatePhotovoltaicThermal_Impl ImplType; explicit SolarCollectorFlatPlatePhotovoltaicThermal(std::shared_ptr<detail::SolarCollectorFlatPlatePhotovoltaicThermal_Impl> impl); friend class detail::SolarCollectorFlatPlatePhotovoltaicThermal_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; /// @endcond private: REGISTER_LOGGER("openstudio.model.SolarCollectorFlatPlatePhotovoltaicThermal"); }; /** \relates SolarCollectorFlatPlatePhotovoltaicThermal*/ typedef boost::optional<SolarCollectorFlatPlatePhotovoltaicThermal> OptionalSolarCollectorFlatPlatePhotovoltaicThermal; /** \relates SolarCollectorFlatPlatePhotovoltaicThermal*/ typedef std::vector<SolarCollectorFlatPlatePhotovoltaicThermal> SolarCollectorFlatPlatePhotovoltaicThermalVector; } // model } // openstudio #endif // MODEL_SOLARCOLLECTORFLATPLATEPHOTOVOLTAICTHERMAL_HPP
31.780488
160
0.764902
568c41443b53d6196f5f1db2f8ce9c141cff4ddf
4,345
cpp
C++
third_party/WebKit/Source/platform/graphics/BitmapImageMetrics.cpp
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
third_party/WebKit/Source/platform/graphics/BitmapImageMetrics.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
third_party/WebKit/Source/platform/graphics/BitmapImageMetrics.cpp
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "platform/graphics/BitmapImageMetrics.h" #include "platform/Histogram.h" #include "third_party/skia/include/core/SkColorSpaceXform.h" #include "wtf/Threading.h" #include "wtf/text/WTFString.h" namespace blink { void BitmapImageMetrics::countDecodedImageType(const String& type) { DecodedImageType decodedImageType = type == "jpg" ? ImageJPEG : type == "png" ? ImagePNG : type == "gif" ? ImageGIF : type == "webp" ? ImageWebP : type == "ico" ? ImageICO : type == "bmp" ? ImageBMP : DecodedImageType::ImageUnknown; DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, decodedImageTypeHistogram, new EnumerationHistogram("Blink.DecodedImageType", DecodedImageTypeEnumEnd)); decodedImageTypeHistogram.count(decodedImageType); } void BitmapImageMetrics::countImageOrientation( const ImageOrientationEnum orientation) { DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, orientationHistogram, new EnumerationHistogram("Blink.DecodedImage.Orientation", ImageOrientationEnumEnd)); orientationHistogram.count(orientation); } void BitmapImageMetrics::countImageGammaAndGamut(SkColorSpace* colorSpace) { DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, gammaNamedHistogram, new EnumerationHistogram("Blink.ColorSpace.Source", GammaEnd)); gammaNamedHistogram.count(getColorSpaceGamma(colorSpace)); DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, gamutNamedHistogram, new EnumerationHistogram("Blink.ColorGamut.Source", GamutEnd)); gamutNamedHistogram.count(getColorSpaceGamut(colorSpace)); } void BitmapImageMetrics::countOutputGammaAndGamut(SkColorSpace* colorSpace) { DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, gammaNamedHistogram, new EnumerationHistogram("Blink.ColorSpace.Destination", GammaEnd)); gammaNamedHistogram.count(getColorSpaceGamma(colorSpace)); DEFINE_THREAD_SAFE_STATIC_LOCAL( EnumerationHistogram, gamutNamedHistogram, new EnumerationHistogram("Blink.ColorGamut.Destination", GamutEnd)); gamutNamedHistogram.count(getColorSpaceGamut(colorSpace)); } BitmapImageMetrics::Gamma BitmapImageMetrics::getColorSpaceGamma( SkColorSpace* colorSpace) { Gamma gamma = GammaNull; if (colorSpace) { if (colorSpace->gammaCloseToSRGB()) { gamma = GammaSRGB; } else if (colorSpace->gammaIsLinear()) { gamma = GammaLinear; } else { gamma = GammaNonStandard; } } return gamma; } BitmapImageMetrics::Gamut BitmapImageMetrics::getColorSpaceGamut( SkColorSpace* colorSpace) { sk_sp<SkColorSpace> scRGB( SkColorSpace::MakeNamed(SkColorSpace::kSRGBLinear_Named)); std::unique_ptr<SkColorSpaceXform> transform( SkColorSpaceXform::New(colorSpace, scRGB.get())); if (!transform) return GamutUnknown; unsigned char in[3][4]; float out[3][4]; memset(in, 0, sizeof(in)); in[0][0] = 255; in[1][1] = 255; in[2][2] = 255; in[0][3] = 255; in[1][3] = 255; in[2][3] = 255; transform->apply(SkColorSpaceXform::kRGBA_F32_ColorFormat, out, SkColorSpaceXform::kRGBA_8888_ColorFormat, in, 3, kOpaque_SkAlphaType); float score = out[0][0] * out[1][1] * out[2][2]; if (score < 0.9) return GamutLessThanNTSC; if (score < 0.95) return GamutNTSC; // actual score 0.912839 if (score < 1.1) return GamutSRGB; // actual score 1.0 if (score < 1.3) return GamutAlmostP3; if (score < 1.425) return GamutP3; // actual score 1.401899 if (score < 1.5) return GamutAdobeRGB; // actual score 1.458385 if (score < 2.0) return GamutWide; if (score < 2.2) return GamutBT2020; // actual score 2.104520 if (score < 2.7) return GamutProPhoto; // actual score 2.913247 return GamutUltraWide; } } // namespace blink
33.167939
77
0.666974
568f10697831712b4d8f97971a516023086824a9
1,249
cpp
C++
materials/14032019/globalne_ocieplenie.cpp
kamiltokarski/devcpp_thur
4106483644cde347f60eb20c8063e0d78fc89bcb
[ "MIT" ]
null
null
null
materials/14032019/globalne_ocieplenie.cpp
kamiltokarski/devcpp_thur
4106483644cde347f60eb20c8063e0d78fc89bcb
[ "MIT" ]
null
null
null
materials/14032019/globalne_ocieplenie.cpp
kamiltokarski/devcpp_thur
4106483644cde347f60eb20c8063e0d78fc89bcb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int tab[1000009]; pair <int, int> srt[1000009]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; for(int i = 1; i <= n; i++) { cin >> tab[i]; srt[i] = make_pair(tab[i], i); } sort(srt, srt+n+1); int lczwsp = 1; int pzmwd = 0; int i = 1; cout << 1 << " "; while(lczwsp != 0) { pzmwd++; while(srt[i].first <= pzmwd && i <= n) { int ilt = srt[i].second; while(i < n && tab[srt[i + 1].second] == tab[srt[i].second] && (srt[i].second + 1) == srt[i + 1].second) { // cout << srt[i].second + 1 << " = " << srt[i + 1].second << endl; ++i; } // cout << "te same wyspy od " << ilt << " do " << srt[i].second << endl; if(tab[ilt-1] > pzmwd && tab[srt[i].second+1] > pzmwd) { lczwsp++; } else if(tab[ilt-1] <= pzmwd && tab[srt[i].second+1] <= pzmwd) { lczwsp--; } i++; } cout << lczwsp << " "; } return 0; }
22.709091
118
0.38751
5693400ae915eb521f4cda991780ee13e607e42f
13,436
cc
C++
cpp/src/arrow/compute/exec/task_util.cc
karldw/arrow
0d995486e6eb4c94a64f03578731aad05c151596
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2020-09-30T02:48:39.000Z
2020-09-30T02:48:39.000Z
cpp/src/arrow/compute/exec/task_util.cc
karldw/arrow
0d995486e6eb4c94a64f03578731aad05c151596
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
20
2021-05-09T06:53:01.000Z
2022-03-27T22:21:50.000Z
cpp/src/arrow/compute/exec/task_util.cc
karldw/arrow
0d995486e6eb4c94a64f03578731aad05c151596
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2
2021-08-05T14:58:01.000Z
2021-08-10T14:16:01.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 "arrow/compute/exec/task_util.h" #include <algorithm> #include <mutex> #include "arrow/util/logging.h" namespace arrow { namespace compute { class TaskSchedulerImpl : public TaskScheduler { public: TaskSchedulerImpl(); int RegisterTaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) override; void RegisterEnd() override; Status StartTaskGroup(size_t thread_id, int group_id, int64_t total_num_tasks) override; Status ExecuteMore(size_t thread_id, int num_tasks_to_execute, bool execute_all) override; Status StartScheduling(size_t thread_id, ScheduleImpl schedule_impl, int num_concurrent_tasks, bool use_sync_execution) override; void Abort(AbortContinuationImpl impl) override; private: // Task group state transitions progress one way. // Seeing an old version of the state by a thread is a valid situation. // enum class TaskGroupState : int { NOT_READY, READY, ALL_TASKS_STARTED, ALL_TASKS_FINISHED }; struct TaskGroup { TaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) : task_impl_(std::move(task_impl)), cont_impl_(std::move(cont_impl)), state_(TaskGroupState::NOT_READY), num_tasks_present_(0) { num_tasks_started_.value.store(0); num_tasks_finished_.value.store(0); } TaskGroup(const TaskGroup& src) : task_impl_(src.task_impl_), cont_impl_(src.cont_impl_), state_(TaskGroupState::NOT_READY), num_tasks_present_(0) { ARROW_DCHECK(src.state_ == TaskGroupState::NOT_READY); num_tasks_started_.value.store(0); num_tasks_finished_.value.store(0); } TaskImpl task_impl_; TaskGroupContinuationImpl cont_impl_; TaskGroupState state_; int64_t num_tasks_present_; AtomicWithPadding<int64_t> num_tasks_started_; AtomicWithPadding<int64_t> num_tasks_finished_; }; std::vector<std::pair<int, int64_t>> PickTasks(int num_tasks, int start_task_group = 0); Status ExecuteTask(size_t thread_id, int group_id, int64_t task_id, bool* task_group_finished); bool PostExecuteTask(size_t thread_id, int group_id); Status OnTaskGroupFinished(size_t thread_id, int group_id, bool* all_task_groups_finished); Status ScheduleMore(size_t thread_id, int num_tasks_finished = 0); bool use_sync_execution_; int num_concurrent_tasks_; ScheduleImpl schedule_impl_; AbortContinuationImpl abort_cont_impl_; std::vector<TaskGroup> task_groups_; bool aborted_; bool register_finished_; std::mutex mutex_; // Mutex protecting task_groups_ (state_ and num_tasks_present_ // fields), aborted_ flag and register_finished_ flag AtomicWithPadding<int> num_tasks_to_schedule_; }; TaskSchedulerImpl::TaskSchedulerImpl() : use_sync_execution_(false), num_concurrent_tasks_(0), aborted_(false), register_finished_(false) { num_tasks_to_schedule_.value.store(0); } int TaskSchedulerImpl::RegisterTaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) { int result = static_cast<int>(task_groups_.size()); task_groups_.emplace_back(std::move(task_impl), std::move(cont_impl)); return result; } void TaskSchedulerImpl::RegisterEnd() { std::lock_guard<std::mutex> lock(mutex_); register_finished_ = true; } Status TaskSchedulerImpl::StartTaskGroup(size_t thread_id, int group_id, int64_t total_num_tasks) { ARROW_DCHECK(group_id >= 0 && group_id < static_cast<int>(task_groups_.size())); TaskGroup& task_group = task_groups_[group_id]; bool aborted = false; bool all_tasks_finished = false; { std::lock_guard<std::mutex> lock(mutex_); aborted = aborted_; if (task_group.state_ == TaskGroupState::NOT_READY) { task_group.num_tasks_present_ = total_num_tasks; if (total_num_tasks == 0) { task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; all_tasks_finished = true; } task_group.state_ = TaskGroupState::READY; } } if (!aborted && all_tasks_finished) { bool all_task_groups_finished = false; RETURN_NOT_OK(OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished)); if (all_task_groups_finished) { return Status::OK(); } } if (!aborted) { return ScheduleMore(thread_id); } else { return Status::Cancelled("Scheduler cancelled"); } } std::vector<std::pair<int, int64_t>> TaskSchedulerImpl::PickTasks(int num_tasks, int start_task_group) { std::vector<std::pair<int, int64_t>> result; for (size_t i = 0; i < task_groups_.size(); ++i) { int task_group_id = static_cast<int>((start_task_group + i) % (task_groups_.size())); TaskGroup& task_group = task_groups_[task_group_id]; if (task_group.state_ != TaskGroupState::READY) { continue; } int num_tasks_remaining = num_tasks - static_cast<int>(result.size()); int64_t start_task = task_group.num_tasks_started_.value.fetch_add(num_tasks_remaining); if (start_task >= task_group.num_tasks_present_) { continue; } int num_tasks_current_group = num_tasks_remaining; if (start_task + num_tasks_current_group >= task_group.num_tasks_present_) { { std::lock_guard<std::mutex> lock(mutex_); if (task_group.state_ == TaskGroupState::READY) { task_group.state_ = TaskGroupState::ALL_TASKS_STARTED; } } num_tasks_current_group = static_cast<int>(task_group.num_tasks_present_ - start_task); } for (int64_t task_id = start_task; task_id < start_task + num_tasks_current_group; ++task_id) { result.push_back(std::make_pair(task_group_id, task_id)); } if (static_cast<int>(result.size()) == num_tasks) { break; } } return result; } Status TaskSchedulerImpl::ExecuteTask(size_t thread_id, int group_id, int64_t task_id, bool* task_group_finished) { if (!aborted_) { RETURN_NOT_OK(task_groups_[group_id].task_impl_(thread_id, task_id)); } *task_group_finished = PostExecuteTask(thread_id, group_id); return Status::OK(); } bool TaskSchedulerImpl::PostExecuteTask(size_t thread_id, int group_id) { int64_t total = task_groups_[group_id].num_tasks_present_; int64_t prev_finished = task_groups_[group_id].num_tasks_finished_.value.fetch_add(1); bool all_tasks_finished = (prev_finished + 1 == total); return all_tasks_finished; } Status TaskSchedulerImpl::OnTaskGroupFinished(size_t thread_id, int group_id, bool* all_task_groups_finished) { bool aborted = false; { std::lock_guard<std::mutex> lock(mutex_); aborted = aborted_; TaskGroup& task_group = task_groups_[group_id]; task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; *all_task_groups_finished = true; for (size_t i = 0; i < task_groups_.size(); ++i) { if (task_groups_[i].state_ != TaskGroupState::ALL_TASKS_FINISHED) { *all_task_groups_finished = false; break; } } } if (aborted && *all_task_groups_finished) { abort_cont_impl_(); return Status::Cancelled("Scheduler cancelled"); } if (!aborted) { RETURN_NOT_OK(task_groups_[group_id].cont_impl_(thread_id)); } return Status::OK(); } Status TaskSchedulerImpl::ExecuteMore(size_t thread_id, int num_tasks_to_execute, bool execute_all) { num_tasks_to_execute = std::max(1, num_tasks_to_execute); int last_id = 0; for (;;) { if (aborted_) { return Status::Cancelled("Scheduler cancelled"); } // Pick next bundle of tasks const auto& tasks = PickTasks(num_tasks_to_execute, last_id); if (tasks.empty()) { break; } last_id = tasks.back().first; // Execute picked tasks immediately for (size_t i = 0; i < tasks.size(); ++i) { int group_id = tasks[i].first; int64_t task_id = tasks[i].second; bool task_group_finished = false; Status status = ExecuteTask(thread_id, group_id, task_id, &task_group_finished); if (!status.ok()) { // Mark the remaining picked tasks as finished for (size_t j = i + 1; j < tasks.size(); ++j) { if (PostExecuteTask(thread_id, tasks[j].first)) { bool all_task_groups_finished = false; RETURN_NOT_OK( OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished)); if (all_task_groups_finished) { return Status::OK(); } } } return status; } else { if (task_group_finished) { bool all_task_groups_finished = false; RETURN_NOT_OK( OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished)); if (all_task_groups_finished) { return Status::OK(); } } } } if (!execute_all) { num_tasks_to_execute -= static_cast<int>(tasks.size()); if (num_tasks_to_execute == 0) { break; } } } return Status::OK(); } Status TaskSchedulerImpl::StartScheduling(size_t thread_id, ScheduleImpl schedule_impl, int num_concurrent_tasks, bool use_sync_execution) { schedule_impl_ = std::move(schedule_impl); use_sync_execution_ = use_sync_execution; num_concurrent_tasks_ = num_concurrent_tasks; num_tasks_to_schedule_.value += num_concurrent_tasks; return ScheduleMore(thread_id); } Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) { if (aborted_) { return Status::Cancelled("Scheduler cancelled"); } ARROW_DCHECK(register_finished_); if (use_sync_execution_) { return ExecuteMore(thread_id, 1, true); } int num_new_tasks = num_tasks_finished; for (;;) { int expected = num_tasks_to_schedule_.value.load(); if (num_tasks_to_schedule_.value.compare_exchange_strong(expected, 0)) { num_new_tasks += expected; break; } } if (num_new_tasks == 0) { return Status::OK(); } const auto& tasks = PickTasks(num_new_tasks); if (static_cast<int>(tasks.size()) < num_new_tasks) { num_tasks_to_schedule_.value += num_new_tasks - static_cast<int>(tasks.size()); } for (size_t i = 0; i < tasks.size(); ++i) { int group_id = tasks[i].first; int64_t task_id = tasks[i].second; RETURN_NOT_OK(schedule_impl_([this, group_id, task_id](size_t thread_id) -> Status { RETURN_NOT_OK(ScheduleMore(thread_id, 1)); bool task_group_finished = false; RETURN_NOT_OK(ExecuteTask(thread_id, group_id, task_id, &task_group_finished)); if (task_group_finished) { bool all_task_groups_finished = false; return OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished); } return Status::OK(); })); } return Status::OK(); } void TaskSchedulerImpl::Abort(AbortContinuationImpl impl) { bool all_finished = true; { std::lock_guard<std::mutex> lock(mutex_); aborted_ = true; abort_cont_impl_ = std::move(impl); if (register_finished_) { for (size_t i = 0; i < task_groups_.size(); ++i) { TaskGroup& task_group = task_groups_[i]; if (task_group.state_ == TaskGroupState::NOT_READY) { task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; } else if (task_group.state_ == TaskGroupState::READY) { int64_t expected = task_group.num_tasks_started_.value.load(); for (;;) { if (task_group.num_tasks_started_.value.compare_exchange_strong( expected, task_group.num_tasks_present_)) { break; } } int64_t before_add = task_group.num_tasks_finished_.value.fetch_add( task_group.num_tasks_present_ - expected); if (before_add >= expected) { task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; } else { all_finished = false; task_group.state_ = TaskGroupState::ALL_TASKS_STARTED; } } } } } if (all_finished) { abort_cont_impl_(); } } std::unique_ptr<TaskScheduler> TaskScheduler::Make() { std::unique_ptr<TaskSchedulerImpl> impl{new TaskSchedulerImpl()}; return std::move(impl); } } // namespace compute } // namespace arrow
33.012285
90
0.670735
56942edfb2262afe0789d1b4bb07fd1bee627502
17,728
cpp
C++
Development/Plugin/Warcraft3/yd_d3d8hook/Direct3DDevice8.cpp
alanoooaao/YDWE
fa9c6dc24d01f78919b5c8b2c69252291536424a
[ "Apache-2.0" ]
5
2019-01-22T02:35:35.000Z
2022-02-28T02:50:03.000Z
Development/Plugin/Warcraft3/yd_d3d8hook/Direct3DDevice8.cpp
alanoooaao/YDWE
fa9c6dc24d01f78919b5c8b2c69252291536424a
[ "Apache-2.0" ]
8
2016-10-19T00:04:05.000Z
2016-11-14T10:58:14.000Z
Development/Plugin/Warcraft3/yd_d3d8hook/Direct3DDevice8.cpp
alanoooaao/YDWE
fa9c6dc24d01f78919b5c8b2c69252291536424a
[ "Apache-2.0" ]
2
2018-01-24T04:34:16.000Z
2021-01-04T09:49:09.000Z
#include "Direct3DDevice8.h" bool gamerender = false; CDirect3DDevice8::CDirect3DDevice8(IDirect3D8* d3d, HWND hwnd, IDirect3DDevice8* device, D3DPRESENT_PARAMETERS* pPresentationParameters) : m_d3d(d3d) , m_device(device) { } CDirect3DDevice8::~CDirect3DDevice8() { } HRESULT WINAPI CDirect3DDevice8::QueryInterface(THIS_ REFIID riid, void** ppvObj) { return m_device->QueryInterface(riid, ppvObj); } ULONG WINAPI CDirect3DDevice8::AddRef(THIS) { return m_device->AddRef(); } ULONG WINAPI CDirect3DDevice8::Release(THIS) { DWORD refCount = m_device->Release(); if (0 == refCount) { delete this; } return refCount; } /*** IDirect3DDevice8 methods ***/ HRESULT WINAPI CDirect3DDevice8::TestCooperativeLevel(THIS) { return m_device->TestCooperativeLevel(); } UINT WINAPI CDirect3DDevice8::GetAvailableTextureMem(THIS) { return m_device->GetAvailableTextureMem(); } HRESULT WINAPI CDirect3DDevice8::ResourceManagerDiscardBytes(THIS_ DWORD Bytes) { return m_device->ResourceManagerDiscardBytes(Bytes); } HRESULT WINAPI CDirect3DDevice8::GetDirect3D(THIS_ IDirect3D8** ppD3D8) { HRESULT hRet = m_device->GetDirect3D(ppD3D8); if (SUCCEEDED(hRet)) *ppD3D8 = m_d3d; return hRet; } HRESULT WINAPI CDirect3DDevice8::GetDeviceCaps(THIS_ D3DCAPS8* pCaps) { return m_device->GetDeviceCaps(pCaps); } HRESULT WINAPI CDirect3DDevice8::GetDisplayMode(THIS_ D3DDISPLAYMODE* pMode) { return m_device->GetDisplayMode(pMode); } HRESULT WINAPI CDirect3DDevice8::GetCreationParameters(THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters) { return m_device->GetCreationParameters(pParameters); } HRESULT CDirect3DDevice8::SetCursorProperties(THIS_ UINT XHotSpot, UINT YHotSpot, IDirect3DSurface8* pCursorBitmap) { return m_device->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap); } void WINAPI CDirect3DDevice8::SetCursorPosition(THIS_ int X, int Y, DWORD Flags) { m_device->SetCursorPosition(X, Y, Flags); } BOOL WINAPI CDirect3DDevice8::ShowCursor(THIS_ BOOL bShow) { return m_device->ShowCursor(bShow); } HRESULT WINAPI CDirect3DDevice8::CreateAdditionalSwapChain(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain8** pSwapChain) { return m_device->CreateAdditionalSwapChain(pPresentationParameters, pSwapChain); } HRESULT WINAPI CDirect3DDevice8::Reset(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters) { return m_device->Reset(pPresentationParameters); } HRESULT CDirect3DDevice8::Present(THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion) { return m_device->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); } HRESULT CDirect3DDevice8::GetBackBuffer(THIS_ UINT BackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface8** ppBackBuffer) { return m_device->GetBackBuffer(BackBuffer, Type, ppBackBuffer); } HRESULT CDirect3DDevice8::GetRasterStatus(THIS_ D3DRASTER_STATUS* pRasterStatus) { return m_device->GetRasterStatus(pRasterStatus); } void WINAPI CDirect3DDevice8::SetGammaRamp(THIS_ DWORD Flags, CONST D3DGAMMARAMP* pRamp) { m_device->SetGammaRamp(Flags, pRamp); } void WINAPI CDirect3DDevice8::GetGammaRamp(THIS_ D3DGAMMARAMP* pRamp) { m_device->GetGammaRamp(pRamp); } HRESULT WINAPI CDirect3DDevice8::CreateTexture(THIS_ UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture8** ppTexture) { return m_device->CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture); } HRESULT WINAPI CDirect3DDevice8::CreateVolumeTexture(THIS_ UINT Width, UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture8** ppVolumeTexture) { return m_device->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture); } HRESULT WINAPI CDirect3DDevice8::CreateCubeTexture(THIS_ UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture8** ppCubeTexture) { return m_device->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture); } HRESULT WINAPI CDirect3DDevice8::CreateVertexBuffer(THIS_ UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer8** ppVertexBuffer) { return m_device->CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer); } HRESULT WINAPI CDirect3DDevice8::CreateIndexBuffer(THIS_ UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer8** ppIndexBuffer) { return m_device->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer); } HRESULT WINAPI CDirect3DDevice8::CreateRenderTarget(THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, BOOL Lockable, IDirect3DSurface8** ppSurface) { return m_device->CreateRenderTarget(Width, Height, Format, MultiSample, Lockable, ppSurface); } HRESULT WINAPI CDirect3DDevice8::CreateDepthStencilSurface(THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, IDirect3DSurface8** ppSurface) { return m_device->CreateDepthStencilSurface(Width, Height, Format, MultiSample, ppSurface); } HRESULT WINAPI CDirect3DDevice8::CreateImageSurface(THIS_ UINT Width, UINT Height, D3DFORMAT Format, IDirect3DSurface8** ppSurface) { return m_device->CreateImageSurface(Width, Height, Format, ppSurface); } HRESULT WINAPI CDirect3DDevice8::CopyRects(THIS_ IDirect3DSurface8* pSourceSurface, CONST RECT* pSourceRectsArray, UINT cRects, IDirect3DSurface8* pDestinationSurface, CONST POINT* pDestPointsArray) { return m_device->CopyRects(pSourceSurface, pSourceRectsArray, cRects, pDestinationSurface, pDestPointsArray); } HRESULT WINAPI CDirect3DDevice8::UpdateTexture(THIS_ IDirect3DBaseTexture8* pSourceTexture, IDirect3DBaseTexture8* pDestinationTexture) { return m_device->UpdateTexture(pSourceTexture, pDestinationTexture); } HRESULT WINAPI CDirect3DDevice8::GetFrontBuffer(THIS_ IDirect3DSurface8* pDestSurface) { return m_device->GetFrontBuffer(pDestSurface); } HRESULT WINAPI CDirect3DDevice8::SetRenderTarget(THIS_ IDirect3DSurface8* pRenderTarget, IDirect3DSurface8* pNewZStencil) { return m_device->SetRenderTarget(pRenderTarget, pNewZStencil); } HRESULT WINAPI CDirect3DDevice8::GetRenderTarget(THIS_ IDirect3DSurface8** ppRenderTarget) { return m_device->GetRenderTarget(ppRenderTarget); } HRESULT WINAPI CDirect3DDevice8::GetDepthStencilSurface(THIS_ IDirect3DSurface8** ppZStencilSurface) { return m_device->GetDepthStencilSurface(ppZStencilSurface); } HRESULT WINAPI CDirect3DDevice8::BeginScene(THIS) { return m_device->BeginScene(); } HRESULT WINAPI CDirect3DDevice8::EndScene(THIS) { return m_device->EndScene(); } HRESULT WINAPI CDirect3DDevice8::Clear(THIS_ DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil) { return m_device->Clear(Count, pRects, Flags, Color, Z, Stencil); } HRESULT WINAPI CDirect3DDevice8::SetTransform(THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix) { if (State == D3DTS_PROJECTION) { D3DMATRIX* pMatrixNew = new D3DMATRIX(*pMatrix); if (gamerender) { //pMatrixNew->m[1][1] *= 4.0f/3.0f;//vertical FoV pMatrixNew->m[0][0] /= 4.0f / 3.0f;// horizontal Fov } return (m_device->SetTransform(State, pMatrixNew)); } return m_device->SetTransform(State, pMatrix); } HRESULT WINAPI CDirect3DDevice8::GetTransform(THIS_ D3DTRANSFORMSTATETYPE State, D3DMATRIX* pMatrix) { return m_device->GetTransform(State, pMatrix); } HRESULT WINAPI CDirect3DDevice8::MultiplyTransform(THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix) { return m_device->MultiplyTransform(State, pMatrix); } HRESULT WINAPI CDirect3DDevice8::SetViewport(THIS_ CONST D3DVIEWPORT8* pViewport) { //some shitty constants to determine region where actual game draws double rate = (double)pViewport->Y / (double)pViewport->Height; gamerender = rate >= 0.02 && rate <= 0.05; return m_device->SetViewport(pViewport); } HRESULT WINAPI CDirect3DDevice8::GetViewport(THIS_ D3DVIEWPORT8* pViewport) { return m_device->GetViewport(pViewport); } HRESULT WINAPI CDirect3DDevice8::SetMaterial(THIS_ CONST D3DMATERIAL8* pMaterial) { return m_device->SetMaterial(pMaterial); } HRESULT WINAPI CDirect3DDevice8::GetMaterial(THIS_ D3DMATERIAL8* pMaterial) { return m_device->GetMaterial(pMaterial); } HRESULT WINAPI CDirect3DDevice8::SetLight(THIS_ DWORD Index, CONST D3DLIGHT8* pLight) { return m_device->SetLight(Index, pLight); } HRESULT WINAPI CDirect3DDevice8::GetLight(THIS_ DWORD Index, D3DLIGHT8* pLight) { return m_device->GetLight(Index, pLight); } HRESULT WINAPI CDirect3DDevice8::LightEnable(THIS_ DWORD Index, BOOL Enable) { return m_device->LightEnable(Index, Enable); } HRESULT WINAPI CDirect3DDevice8::GetLightEnable(THIS_ DWORD Index, BOOL* pEnable) { return m_device->GetLightEnable(Index, pEnable); } HRESULT WINAPI CDirect3DDevice8::SetClipPlane(THIS_ DWORD Index, CONST float* pPlane) { return m_device->SetClipPlane(Index, pPlane); } HRESULT WINAPI CDirect3DDevice8::GetClipPlane(THIS_ DWORD Index, float* pPlane) { return m_device->GetClipPlane(Index, pPlane); } HRESULT WINAPI CDirect3DDevice8::SetRenderState(THIS_ D3DRENDERSTATETYPE State, DWORD Value) { return m_device->SetRenderState(State, Value); } HRESULT WINAPI CDirect3DDevice8::GetRenderState(THIS_ D3DRENDERSTATETYPE State, DWORD* pValue) { return m_device->GetRenderState(State, pValue); } HRESULT WINAPI CDirect3DDevice8::BeginStateBlock(THIS) { return m_device->BeginStateBlock(); } HRESULT WINAPI CDirect3DDevice8::EndStateBlock(THIS_ DWORD* pToken) { return m_device->EndStateBlock(pToken); } HRESULT WINAPI CDirect3DDevice8::ApplyStateBlock(THIS_ DWORD Token) { return m_device->ApplyStateBlock(Token); } HRESULT WINAPI CDirect3DDevice8::CaptureStateBlock(THIS_ DWORD Token) { return m_device->CaptureStateBlock(Token); } HRESULT WINAPI CDirect3DDevice8::DeleteStateBlock(THIS_ DWORD Token) { return m_device->DeleteStateBlock(Token); } HRESULT WINAPI CDirect3DDevice8::CreateStateBlock(THIS_ D3DSTATEBLOCKTYPE Type, DWORD* pToken) { return m_device->CreateStateBlock(Type, pToken); } HRESULT WINAPI CDirect3DDevice8::SetClipStatus(THIS_ CONST D3DCLIPSTATUS8* pClipStatus) { return m_device->SetClipStatus(pClipStatus); } HRESULT WINAPI CDirect3DDevice8::GetClipStatus(THIS_ D3DCLIPSTATUS8* pClipStatus) { return m_device->GetClipStatus(pClipStatus); } HRESULT WINAPI CDirect3DDevice8::GetTexture(THIS_ DWORD Stage, IDirect3DBaseTexture8** ppTexture) { return m_device->GetTexture(Stage, ppTexture); } HRESULT WINAPI CDirect3DDevice8::SetTexture(THIS_ DWORD Stage, IDirect3DBaseTexture8* pTexture) { return m_device->SetTexture(Stage, pTexture); } HRESULT WINAPI CDirect3DDevice8::GetTextureStageState(THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD* pValue) { return m_device->GetTextureStageState(Stage, Type, pValue); } HRESULT WINAPI CDirect3DDevice8::SetTextureStageState(THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value) { return m_device->SetTextureStageState(Stage, Type, Value); } HRESULT WINAPI CDirect3DDevice8::ValidateDevice(THIS_ DWORD* pNumPasses) { return m_device->ValidateDevice(pNumPasses); } HRESULT WINAPI CDirect3DDevice8::GetInfo(THIS_ DWORD DevInfoID, void* pDevInfoStruct, DWORD DevInfoStructSize) { return m_device->GetInfo(DevInfoID, pDevInfoStruct, DevInfoStructSize); } HRESULT WINAPI CDirect3DDevice8::SetPaletteEntries(THIS_ UINT PaletteNumber, CONST PALETTEENTRY* pEntries) { return m_device->SetPaletteEntries(PaletteNumber, pEntries); } HRESULT WINAPI CDirect3DDevice8::GetPaletteEntries(THIS_ UINT PaletteNumber, PALETTEENTRY* pEntries) { return m_device->GetPaletteEntries(PaletteNumber, pEntries); } HRESULT WINAPI CDirect3DDevice8::SetCurrentTexturePalette(THIS_ UINT PaletteNumber) { return m_device->SetCurrentTexturePalette(PaletteNumber); } HRESULT WINAPI CDirect3DDevice8::GetCurrentTexturePalette(THIS_ UINT *PaletteNumber) { return m_device->GetCurrentTexturePalette(PaletteNumber); } HRESULT WINAPI CDirect3DDevice8::DrawPrimitive(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount) { return m_device->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount); } HRESULT WINAPI CDirect3DDevice8::DrawIndexedPrimitive(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT minIndex, UINT NumVertices, UINT startIndex, UINT primCount) { return m_device->DrawIndexedPrimitive(PrimitiveType, minIndex, NumVertices, startIndex, primCount); } HRESULT WINAPI CDirect3DDevice8::DrawPrimitiveUP(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride) { return m_device->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride); } HRESULT WINAPI CDirect3DDevice8::DrawIndexedPrimitiveUP(THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertexIndices, UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride) { return m_device->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertexIndices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride); } HRESULT WINAPI CDirect3DDevice8::ProcessVertices(THIS_ UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer8* pDestBuffer, DWORD Flags) { return m_device->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer, Flags); } HRESULT WINAPI CDirect3DDevice8::CreateVertexShader(THIS_ CONST DWORD* pDeclaration, CONST DWORD* pFunction, DWORD* pHandle, DWORD Usage) { return m_device->CreateVertexShader(pDeclaration, pFunction, pHandle, Usage); } HRESULT WINAPI CDirect3DDevice8::SetVertexShader(THIS_ DWORD Handle) { return m_device->SetVertexShader(Handle); } HRESULT WINAPI CDirect3DDevice8::GetVertexShader(THIS_ DWORD* pHandle) { return m_device->GetVertexShader(pHandle); } HRESULT WINAPI CDirect3DDevice8::DeleteVertexShader(THIS_ DWORD Handle) { return m_device->DeleteVertexShader(Handle); } HRESULT WINAPI CDirect3DDevice8::SetVertexShaderConstant(THIS_ DWORD Register, CONST void* pConstantData, DWORD ConstantCount) { return m_device->SetVertexShaderConstant(Register, pConstantData, ConstantCount); } HRESULT WINAPI CDirect3DDevice8::GetVertexShaderConstant(THIS_ DWORD Register, void* pConstantData, DWORD ConstantCount) { return m_device->GetVertexShaderConstant(Register, pConstantData, ConstantCount); } HRESULT WINAPI CDirect3DDevice8::GetVertexShaderDeclaration(THIS_ DWORD Handle, void* pData, DWORD* pSizeOfData) { return m_device->GetVertexShaderDeclaration(Handle, pData, pSizeOfData); } HRESULT WINAPI CDirect3DDevice8::GetVertexShaderFunction(THIS_ DWORD Handle, void* pData, DWORD* pSizeOfData) { return m_device->GetVertexShaderFunction(Handle, pData, pSizeOfData); } HRESULT WINAPI CDirect3DDevice8::SetStreamSource(THIS_ UINT StreamNumber, IDirect3DVertexBuffer8* pStreamData, UINT Stride) { return m_device->SetStreamSource(StreamNumber, pStreamData, Stride); } HRESULT WINAPI CDirect3DDevice8::GetStreamSource(THIS_ UINT StreamNumber, IDirect3DVertexBuffer8** ppStreamData, UINT* pStride) { return m_device->GetStreamSource(StreamNumber, ppStreamData, pStride); } HRESULT WINAPI CDirect3DDevice8::SetIndices(THIS_ IDirect3DIndexBuffer8* pIndexData, UINT BaseVertexIndex) { return m_device->SetIndices(pIndexData, BaseVertexIndex); } HRESULT WINAPI CDirect3DDevice8::GetIndices(THIS_ IDirect3DIndexBuffer8** ppIndexData, UINT* pBaseVertexIndex) { return m_device->GetIndices(ppIndexData, pBaseVertexIndex); } HRESULT WINAPI CDirect3DDevice8::CreatePixelShader(THIS_ CONST DWORD* pFunction, DWORD* pHandle) { return m_device->CreatePixelShader(pFunction, pHandle); } HRESULT WINAPI CDirect3DDevice8::SetPixelShader(THIS_ DWORD Handle) { return m_device->SetPixelShader(Handle); } HRESULT WINAPI CDirect3DDevice8::GetPixelShader(THIS_ DWORD* pHandle) { return m_device->GetPixelShader(pHandle); } HRESULT WINAPI CDirect3DDevice8::DeletePixelShader(THIS_ DWORD Handle) { return m_device->DeletePixelShader(Handle); } HRESULT WINAPI CDirect3DDevice8::SetPixelShaderConstant(THIS_ DWORD Register, CONST void* pConstantData, DWORD ConstantCount) { return m_device->SetPixelShaderConstant(Register, pConstantData, ConstantCount); } HRESULT WINAPI CDirect3DDevice8::GetPixelShaderConstant(THIS_ DWORD Register, void* pConstantData, DWORD ConstantCount) { return m_device->GetPixelShaderConstant(Register, pConstantData, ConstantCount); } HRESULT WINAPI CDirect3DDevice8::GetPixelShaderFunction(THIS_ DWORD Handle, void* pData, DWORD* pSizeOfData) { return m_device->GetPixelShaderFunction(Handle, pData, pSizeOfData); } HRESULT WINAPI CDirect3DDevice8::DrawRectPatch(THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo) { return m_device->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo); } HRESULT WINAPI CDirect3DDevice8::DrawTriPatch(THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo) { return m_device->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo); } HRESULT WINAPI CDirect3DDevice8::DeletePatch(THIS_ UINT Handle) { return m_device->DeletePatch(Handle); }
34.026871
274
0.79146
569490308adf4f5dceb4679e68122e2c35bf77b9
1,952
cpp
C++
src/LoadDataWidget.cpp
abdellaui/gender_detection
4a5e80fec4244fe40ef97aad3b1d50f46418db14
[ "MIT" ]
1
2019-12-13T15:27:51.000Z
2019-12-13T15:27:51.000Z
src/LoadDataWidget.cpp
abdellaui/gender_detection
4a5e80fec4244fe40ef97aad3b1d50f46418db14
[ "MIT" ]
null
null
null
src/LoadDataWidget.cpp
abdellaui/gender_detection
4a5e80fec4244fe40ef97aad3b1d50f46418db14
[ "MIT" ]
null
null
null
#include "LoadDataWidget.h" LoadDataWidget::LoadDataWidget(QWidget *parent) : QWidget(parent) { m_gui.setupUi(this); QWidget::setWindowTitle("Select files!"); m_gui.lineEdit_test->setText("/Users/abdullah/Desktop/gender_detection/src/material/test"); m_gui.lineEdit_training->setText("/Users/abdullah/Desktop/gender_detection/src/material/training"); QObject::connect(m_gui.toolButton_test, &QAbstractButton::clicked, this, &LoadDataWidget::onClickTest); QObject::connect(m_gui.toolButton_training, &QAbstractButton::clicked, this, &LoadDataWidget::onClickTraining); QObject::connect(m_gui.pushButton_load, &QAbstractButton::clicked, this, &LoadDataWidget::onClickedLoad); } LoadDataWidget::~LoadDataWidget() {} void LoadDataWidget::onClickTraining() { QString filename = QFileDialog::getExistingDirectory( this, "Open Data", QDir::currentPath(), (QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks | QFileDialog::Option::DontUseNativeDialog)); if (filename.isNull()) { QMessageBox::critical(this, "Error", "Datei konnte nicht gefunden werden!"); return; } m_gui.lineEdit_training->setText(filename); } void LoadDataWidget::onClickTest() { QString filename = QFileDialog::getExistingDirectory( this, "Open Data", QDir::currentPath(), (QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks | QFileDialog::Option::DontUseNativeDialog)); if (filename.isNull()) { QMessageBox::critical(this, "Error", "Datei konnte nicht gefunden werden!"); return; } m_gui.lineEdit_test->setText(filename); } void LoadDataWidget::onClickedLoad() { if (m_gui.lineEdit_test->text().isEmpty() || m_gui.lineEdit_training->text().isEmpty()) { QMessageBox::critical(this, "Error", "Einer der Datein existiert nicht!"); return; } Q_EMIT(gotFiles(m_gui.lineEdit_test->text(), m_gui.lineEdit_training->text())); QWidget::close(); }
32.533333
113
0.729508
5696b9aa3e2c61a83029c42663ffd8eb0d19ff5f
2,305
cpp
C++
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
diogoamvasconcelos/CS106b-eroberts2015-solutions
8964130bb872990b809e74ed489237e0c1c96604
[ "MIT" ]
4
2017-06-26T09:44:28.000Z
2020-01-19T05:42:41.000Z
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
diogoamvasconcelos/CS106b-eroberts2015-solutions
8964130bb872990b809e74ed489237e0c1c96604
[ "MIT" ]
null
null
null
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
diogoamvasconcelos/CS106b-eroberts2015-solutions
8964130bb872990b809e74ed489237e0c1c96604
[ "MIT" ]
1
2020-10-08T08:26:07.000Z
2020-10-08T08:26:07.000Z
#include <iostream> #include "console.h" #include "simpio.h" #include "stack.h" using namespace std; struct HanoiTask { int num_disks; char start_pile; char finish_pile; char temp_pile; }; const char PILE_A = 'A'; const char PILE_B = 'B'; const char PILE_C = 'C'; void MoveHanoiTower(int n); void MoveSingleDisk(char start, char finish); int main() { while(true) { int n = getInteger("Hanoi n:"); if(n < 1) break; MoveHanoiTower(n); } return 0; } void MoveHanoiTower(int n) { Stack<HanoiTask> tasks_stack; HanoiTask starting_task; starting_task.num_disks = n; starting_task.start_pile = PILE_A; starting_task.finish_pile = PILE_B; starting_task.temp_pile = PILE_C; tasks_stack.push(starting_task); while(tasks_stack.size() > 0) { HanoiTask current_task = tasks_stack.pop(); if(current_task.num_disks < 2) { MoveSingleDisk(current_task.start_pile, current_task.finish_pile); } else { HanoiTask move_from_top_task; move_from_top_task.num_disks = current_task.num_disks - 1; move_from_top_task.start_pile = current_task.start_pile; move_from_top_task.finish_pile = current_task.temp_pile; move_from_top_task.temp_pile = current_task.finish_pile; HanoiTask move_single_disk_task; move_single_disk_task.num_disks = 1; move_single_disk_task.start_pile = current_task.start_pile; move_single_disk_task.finish_pile = current_task.finish_pile; move_single_disk_task.temp_pile = current_task.temp_pile; HanoiTask move_back_task; move_back_task.num_disks = current_task.num_disks - 1; move_back_task.start_pile = current_task.temp_pile; move_back_task.finish_pile = current_task.finish_pile; move_back_task.temp_pile = current_task.start_pile; //Stack, first in last out, so tasks need to be correctly stacked tasks_stack.push(move_back_task); tasks_stack.push(move_single_disk_task); tasks_stack.push(move_from_top_task); } } } void MoveSingleDisk(char start, char finish) { cout << start << "->" << finish << endl; }
25.898876
78
0.660738
5698e98f860d2e7e16e6b35725e4ad8d1ad5bc0e
2,682
cpp
C++
lib-src/vgui/ProgressBar.cpp
Velaron/vgui_dll
9ebb9ab4abf49ba3bd4aad8d102923a0d61d139b
[ "BSD-3-Clause" ]
22
2017-02-21T04:30:12.000Z
2022-02-13T22:40:39.000Z
lib-src/vgui/ProgressBar.cpp
FWGS/vgui_dll
4a677fc844f3d92c1b83c6a0f748242a2601286e
[ "BSD-3-Clause" ]
1
2017-05-08T18:31:26.000Z
2017-05-08T18:31:26.000Z
lib-src/vgui/ProgressBar.cpp
nagist/vgui_dll
acf73ec95a4499b229d68854819fb5e951de1759
[ "BSD-3-Clause" ]
12
2017-02-18T16:03:05.000Z
2021-12-30T16:34:27.000Z
/* * BSD 3-Clause License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include<math.h> #include<VGUI_ProgressBar.h> using namespace vgui; ProgressBar::ProgressBar(int segmentCount) { _segmentCount=segmentCount; _progress=0; } void ProgressBar::paintBackground() { int wide,tall; getPaintSize(wide,tall); drawSetColor(Scheme::sc_secondary2); drawFilledRect(0,0,wide,tall); const int segmentGap=2; int segmentWide=wide/_segmentCount-segmentGap; const float rr=0; const float gg=0; const float bb=100; int x=0; int litSeg=(int)floor(_progress); for(int i=litSeg;i>0;i--) { drawSetColor((int)rr,(int)gg,(int)bb,0); drawFilledRect(x,0,x+segmentWide,tall); x+=segmentWide+segmentGap; } if(_segmentCount>_progress) { float frac=_progress-(float)floor(_progress); float r=0; float g=255-(frac*155); float b=0; drawSetColor((int)r,(int)g,(int)b,0); drawFilledRect(x,0,x+segmentWide,tall); } } void ProgressBar::setProgress(float progress) { if(_progress!=progress) { _progress=progress; repaint(); } } int ProgressBar::getSegmentCount() { return _segmentCount; }
29.472527
82
0.722222
569aae33732ac9c6f639809ca8468c3ca1e3d69b
3,150
hh
C++
src/NodeList/FixedSmoothingScale.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/NodeList/FixedSmoothingScale.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/NodeList/FixedSmoothingScale.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // FixedSmoothingScale // // Implements the static fixed smoothing scale option. // // Created by JMO, Wed Sep 14 13:50:49 PDT 2005 //----------------------------------------------------------------------------// #ifndef __Spheral_NodeSpace_FixedSmooothingScale__ #define __Spheral_NodeSpace_FixedSmooothingScale__ #include "SmoothingScaleBase.hh" namespace Spheral { template<typename Dimension> class FixedSmoothingScale: public SmoothingScaleBase<Dimension> { public: //--------------------------- Public Interface ---------------------------// typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; // Constructors, destructor. FixedSmoothingScale(); FixedSmoothingScale(const FixedSmoothingScale& rhs); FixedSmoothingScale& operator=(const FixedSmoothingScale& rhs); virtual ~FixedSmoothingScale(); // Time derivative of the smoothing scale. virtual SymTensor smoothingScaleDerivative(const SymTensor& H, const Vector& pos, const Tensor& DvDx, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh) const; // Return a new H, with limiting based on the old value. virtual SymTensor newSmoothingScale(const SymTensor& H, const Vector& pos, const Scalar zerothMoment, const SymTensor& secondMoment, const TableKernel<Dimension>& W, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh, const ConnectivityMap<Dimension>& connectivityMap, const unsigned nodeListi, const unsigned i) const; // Determine an "ideal" H for the given moments. virtual SymTensor idealSmoothingScale(const SymTensor& H, const Vector& pos, const Scalar zerothMoment, const SymTensor& secondMoment, const TableKernel<Dimension>& W, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh, const ConnectivityMap<Dimension>& connectivityMap, const unsigned nodeListi, const unsigned i) const; // Compute the new H tensors for a tessellation. virtual SymTensor idealSmoothingScale(const SymTensor& H, const Mesh<Dimension>& mesh, const typename Mesh<Dimension>::Zone& zone, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh) const; }; } #endif
35.795455
80
0.546984
569d1bc85900ccbadf1d6542ed46ef40ad524806
2,252
cpp
C++
Verkehrssituation/src/tests/Verkehrssituation.cpp
DavidHeiss/vs2
a00a58acab582e22e426a290eff9dd251edda992
[ "MIT" ]
null
null
null
Verkehrssituation/src/tests/Verkehrssituation.cpp
DavidHeiss/vs2
a00a58acab582e22e426a290eff9dd251edda992
[ "MIT" ]
null
null
null
Verkehrssituation/src/tests/Verkehrssituation.cpp
DavidHeiss/vs2
a00a58acab582e22e426a290eff9dd251edda992
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../Verkehrssituation.h" class VerkehrssituationTest : public testing::Test { protected: void SetUp() override { verkehrssituation = Sensor::Verkehrssitation(); } Sensor::Verkehrssitation verkehrssituation; }; TEST_F(VerkehrssituationTest , has_data) { auto message = verkehrssituation.generateMessage(); ASSERT_TRUE(message.has_data()); } TEST_F(VerkehrssituationTest, has_from_address) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_from_address()); } TEST_F(VerkehrssituationTest, has_from_port) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_from_port()); } TEST_F(VerkehrssituationTest, has_latency) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_latency()); } TEST_F(VerkehrssituationTest, has_received) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_received()); } TEST_F(VerkehrssituationTest, has_round_trip) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_round_trip()); } TEST_F(VerkehrssituationTest, has_send) { auto message = verkehrssituation.generateMessage(); ASSERT_TRUE(message.has_send()); } TEST_F(VerkehrssituationTest, has_to_address) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_to_address()); } TEST_F(VerkehrssituationTest, has_to_port) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_to_port()); } TEST_F(VerkehrssituationTest, has_numeric_value) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_numeric_value()); } TEST_F(VerkehrssituationTest, has_rising) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_rising()); } TEST_F(VerkehrssituationTest, has_type) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_type()); } TEST_F(VerkehrssituationTest, has_value) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_value()); } int main() { testing::InitGoogleTest(); return RUN_ALL_TESTS(); }
21.245283
59
0.746892
569f52cb404ddae81549019ab9880be1adaffbaa
14,400
cc
C++
fawnds/bdb.cc
ByteHamster/silt
9970432b27db7b9ef3f23f56cdd0609183e9fd83
[ "Apache-2.0" ]
134
2015-02-02T21:32:16.000Z
2022-01-27T06:03:22.000Z
fawnds/bdb.cc
theopengroup/silt
9970432b27db7b9ef3f23f56cdd0609183e9fd83
[ "Apache-2.0" ]
null
null
null
fawnds/bdb.cc
theopengroup/silt
9970432b27db7b9ef3f23f56cdd0609183e9fd83
[ "Apache-2.0" ]
43
2015-01-02T03:12:34.000Z
2021-12-17T09:19:28.000Z
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "bdb.h" #include "configuration.h" #include <cassert> #include <sstream> #ifdef HAVE_LIBDB namespace fawn { BDB::BDB() : dbp_(NULL) { } BDB::~BDB() { if (dbp_) Close(); } FawnDS_Return BDB::Create() { if (dbp_) return ERROR; // TODO: use DB_ENV to optimize BDB for SSD? int ret = db_create(&dbp_, NULL, 0); if (ret != 0) { fprintf(stderr, "BDB::Create(): Error while creating DB: %s\n", db_strerror(ret)); return ERROR; } std::string filename = config_->GetStringValue("child::file") + "_"; filename += config_->GetStringValue("child::id"); ret = dbp_->open(dbp_, NULL, filename.c_str(), NULL, DB_BTREE, DB_THREAD | DB_CREATE | DB_TRUNCATE, 0); if (ret != 0) { fprintf(stderr, "BDB::Create(): Error while creating DB: %s\n", db_strerror(ret)); dbp_->close(dbp_, 0); dbp_ = NULL; return ERROR; } size_ = 0; return OK; } FawnDS_Return BDB::Open() { if (dbp_) return ERROR; int ret = db_create(&dbp_, NULL, 0); if (ret != 0) { fprintf(stderr, "BDB::Open(): Error while creating DB: %s\n", db_strerror(ret)); return ERROR; } std::string filename = config_->GetStringValue("child::file") + "_"; filename += config_->GetStringValue("child::id"); ret = dbp_->open(dbp_, NULL, filename.c_str(), NULL, DB_BTREE, DB_THREAD, 0); if (ret != 0) { fprintf(stderr, "BDB::Open(): Error while creating DB: %s\n", db_strerror(ret)); dbp_->close(dbp_, 0); dbp_ = NULL; return ERROR; } // TODO: load size_ from file size_ = 0; return OK; } FawnDS_Return BDB::ConvertTo(FawnDS* new_store) const { BDB* bdb = dynamic_cast<BDB*>(new_store); if (!bdb) return UNSUPPORTED; bdb->Close(); std::string src_filename = config_->GetStringValue("child::file") + "_"; src_filename += config_->GetStringValue("child::id"); std::string dest_filename = bdb->config_->GetStringValue("child::file") + "_"; dest_filename += bdb->config_->GetStringValue("child::id"); if (unlink(dest_filename.c_str())) { fprintf(stderr, "BDB::ConvertTo(): cannot unlink the destination file\n"); } if (link(src_filename.c_str(), dest_filename.c_str())) { fprintf(stderr, "BDB::ConvertTo(): cannot link the destination file\n"); } if (bdb->Open() != OK) return ERROR; return OK; } FawnDS_Return BDB::Flush() { if (!dbp_) return ERROR; // TODO: implement return OK; } FawnDS_Return BDB::Close() { if (!dbp_) return ERROR; dbp_->close(dbp_, 0); dbp_ = NULL; return OK; } FawnDS_Return BDB::Destroy() { if (dbp_) return ERROR; DB* dbp; int ret = db_create(&dbp, NULL, 0); if (ret != 0) { fprintf(stderr, "BDB::Destroy(): Error while creating DB: %s\n", db_strerror(ret)); return ERROR; } std::string filename = config_->GetStringValue("child::file") + "_"; filename += config_->GetStringValue("child::id"); ret = dbp->remove(dbp, filename.c_str(), NULL, 0); if (ret != 0) { fprintf(stderr, "BDB::Destroy(): Error while removing DB: %s\n", db_strerror(ret)); dbp->close(dbp, 0); return ERROR; } dbp->close(dbp, 0); return OK; } FawnDS_Return BDB::Status(const FawnDS_StatusType& type, Value& status) const { if (!dbp_) return ERROR; std::ostringstream oss; switch (type) { case NUM_DATA: case NUM_ACTIVE_DATA: oss << size_; break; case CAPACITY: oss << -1; // unlimited break; case MEMORY_USE: { uint32_t gbytes = 0; uint32_t bytes = 0; int ncache = 0; int ret = dbp_->get_cachesize(dbp_, &gbytes, &bytes, &ncache); if (ret != 0) { fprintf(stderr, "BDB::Status(): Error while querying DB: %s\n", db_strerror(ret)); return ERROR; } oss << gbytes * (1024 * 1024 * 1024) + bytes; // BDB uses powers of two } break; case DISK_USE: { // TODO: check if this work DB_BTREE_STAT stat; int ret = dbp_->stat(dbp_, NULL, &stat, DB_FAST_STAT); if (ret != 0) { fprintf(stderr, "BDB::Status(): Error while querying DB: %s\n", db_strerror(ret)); return ERROR; } oss << stat.bt_pagecnt * stat.bt_pagesize; } break; default: return UNSUPPORTED; } status = NewValue(oss.str()); return OK; } FawnDS_Return BDB::Put(const ConstValue& key, const ConstValue& data) { if (!dbp_) return ERROR; if (key.size() == 0) return INVALID_KEY; DBT key_v; memset(&key_v, 0, sizeof(DBT)); key_v.data = const_cast<char*>(key.data()); key_v.size = key.size(); DBT data_v; memset(&data_v, 0, sizeof(DBT)); data_v.data = const_cast<char*>(data.data()); data_v.size = data.size(); int ret = dbp_->put(dbp_, NULL, &key_v, &data_v, DB_NOOVERWRITE); if (ret == 0) { ++size_; return OK; } else if (ret == DB_KEYEXIST) ret = dbp_->put(dbp_, NULL, &key_v, &data_v, 0); if (ret != 0) { fprintf(stderr, "BDB::Put(): %s\n", db_strerror(ret)); return ERROR; } return OK; } FawnDS_Return BDB::Delete(const ConstValue& key) { if (!dbp_) return ERROR; if (key.size() == 0) return INVALID_KEY; DBT key_v; memset(&key_v, 0, sizeof(DBT)); key_v.data = const_cast<char*>(key.data()); key_v.size = key.size(); int ret = dbp_->del(dbp_, NULL, &key_v, 0); if (ret == 0) { --size_; return OK; } else if (ret == DB_NOTFOUND) return KEY_NOT_FOUND; if (ret != 0) { fprintf(stderr, "BDB::Delete(): %s\n", db_strerror(ret)); return ERROR; } return OK; } FawnDS_Return BDB::Contains(const ConstValue& key) const { if (!dbp_) return ERROR; if (key.size() == 0) return INVALID_KEY; DBT key_v; memset(&key_v, 0, sizeof(DBT)); key_v.data = const_cast<char*>(key.data()); key_v.size = key.size(); int ret = dbp_->exists(dbp_, NULL, &key_v, 0); if (ret == 0) return OK; else if (ret == DB_NOTFOUND) return KEY_NOT_FOUND; else { fprintf(stderr, "BDB::Contains(): %s\n", db_strerror(ret)); return ERROR; } } FawnDS_Return BDB::Length(const ConstValue& key, size_t& len) const { if (!dbp_) return ERROR; if (key.size() == 0) return INVALID_KEY; DBT key_v; memset(&key_v, 0, sizeof(DBT)); key_v.data = const_cast<char*>(key.data()); key_v.size = key.size(); DBT data_v; memset(&data_v, 0, sizeof(DBT)); data_v.flags = DB_DBT_USERMEM; int ret = dbp_->get(dbp_, NULL, &key_v, &data_v, 0); if (ret == 0 || ret == DB_BUFFER_SMALL) { len = data_v.size; return OK; } else if (ret == DB_NOTFOUND) return KEY_NOT_FOUND; else { fprintf(stderr, "BDB::Length(): %s\n", db_strerror(ret)); return ERROR; } } FawnDS_Return BDB::Get(const ConstValue& key, Value& data, size_t offset, size_t len) const { if (!dbp_) return ERROR; if (key.size() == 0) return INVALID_KEY; size_t data_len = 0; FawnDS_Return ret_len = Length(key, data_len); if (ret_len != OK) return ret_len; if (offset > data_len) return END; if (offset + len > data_len) len = data_len - offset; data.resize(len, false); DBT key_v; memset(&key_v, 0, sizeof(DBT)); key_v.data = const_cast<char*>(key.data()); key_v.size = key.size(); DBT data_v; memset(&data_v, 0, sizeof(DBT)); data_v.data = data.data(); data_v.ulen = len; data_v.flags = DB_DBT_USERMEM; int ret = dbp_->get(dbp_, NULL, &key_v, &data_v, 0); if (ret != 0) { fprintf(stderr, "BDB::Get(): %s\n", db_strerror(ret)); return ERROR; } return OK; } FawnDS_ConstIterator BDB::Enumerate() const { if (!dbp_) return FawnDS_ConstIterator(); IteratorElem* elem = new IteratorElem(this); int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0); if (ret != 0) { fprintf(stderr, "BDB::Enumerate(): %s\n", db_strerror(ret)); return FawnDS_ConstIterator(); } elem->Increment(true); return FawnDS_ConstIterator(elem); } FawnDS_Iterator BDB::Enumerate() { if (!dbp_) return FawnDS_Iterator(); IteratorElem* elem = new IteratorElem(this); int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0); if (ret != 0) { fprintf(stderr, "BDB::Enumerate(): %s\n", db_strerror(ret)); return FawnDS_Iterator(); } elem->Increment(true); return FawnDS_Iterator(elem); } FawnDS_ConstIterator BDB::Find(const ConstValue& key) const { if (!dbp_) return FawnDS_ConstIterator(); if (key.size() == 0) return FawnDS_ConstIterator(); IteratorElem* elem = new IteratorElem(this); elem->key = key; int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0); if (ret != 0) { fprintf(stderr, "BDB::Find(): %s\n", db_strerror(ret)); delete elem; return FawnDS_ConstIterator(); } elem->Increment(true); return FawnDS_ConstIterator(elem); } FawnDS_Iterator BDB::Find(const ConstValue& key) { if (!dbp_) return FawnDS_Iterator(); if (key.size() == 0) return FawnDS_Iterator(); IteratorElem* elem = new IteratorElem(this); elem->key = key; int ret = dbp_->cursor(dbp_, NULL, &elem->cursor, 0); if (ret != 0) { fprintf(stderr, "BDB::Find(): %s\n", db_strerror(ret)); delete elem; return FawnDS_Iterator(); } elem->Increment(true); return FawnDS_Iterator(elem); } BDB::IteratorElem::IteratorElem(const BDB* fawnds) { this->fawnds = fawnds; } BDB::IteratorElem::~IteratorElem() { cursor->close(cursor); cursor = NULL; } FawnDS_IteratorElem* BDB::IteratorElem::Clone() const { IteratorElem* elem = new IteratorElem(static_cast<const BDB*>(fawnds)); *elem = *this; int ret = cursor->dup(cursor, &elem->cursor, DB_POSITION); if (ret != 0) { fprintf(stderr, "BDB::Clone(): %s\n", db_strerror(ret)); return NULL; } return elem; } void BDB::IteratorElem::Next() { Increment(false); } void BDB::IteratorElem::Increment(bool initial) { int flags; DBT key_v; memset(&key_v, 0, sizeof(DBT)); DBT data_v; memset(&data_v, 0, sizeof(DBT)); if (initial) { if (key.size() == 0) { flags = DB_FIRST; key_v.flags = DB_DBT_USERMEM; data_v.flags = DB_DBT_USERMEM; } else { flags = DB_SET; key_v.data = key.data(); key_v.size = key.size(); data_v.flags = DB_DBT_USERMEM; } } else { key_v.flags = DB_DBT_USERMEM; data_v.flags = DB_DBT_USERMEM; flags = DB_NEXT; } // obtain the length of key & data int ret = cursor->get(cursor, &key_v, &data_v, flags); if (ret == 0) { // this should not happen because we have key_v.ulen = 0, and there is no zero-length key assert(false); state = END; return; } else if (ret == DB_NOTFOUND) { state = END; return; } else if (ret != DB_BUFFER_SMALL) { fprintf(stderr, "BDB::IteratorElem::Increment(): Error while obtaining length: %s\n", db_strerror(ret)); state = END; return; } //fprintf(stderr, "%d %d\n", key_v.size, data_v.size); // retrieve key & data key.resize(key_v.size, false); key_v.data = key.data(); key_v.size = key.size(); key_v.ulen = key_v.size; key_v.flags = DB_DBT_USERMEM; data.resize(data_v.size, false); data_v.data = data.data(); data_v.size = data.size(); data_v.ulen = data_v.size; key_v.flags = DB_DBT_USERMEM; ret = cursor->get(cursor, &key_v, &data_v, flags); if (ret != 0) { fprintf(stderr, "BDB::IteratorElem::Increment(): Error while reading key and data: %s\n", db_strerror(ret)); state = END; return; } state = OK; key.resize(key_v.size); data.resize(data_v.size); } } // namespace fawn #endif
25.622776
120
0.497917
56a06f3fe2fa251050dd996c7bc7fdc016d33694
4,924
cpp
C++
src/box2ddestructionlistener.cpp
bobweaver/qml-box2d
905841c01d6603678d34f0f8aaaf6843b70dc08a
[ "Zlib" ]
1
2022-02-09T19:14:01.000Z
2022-02-09T19:14:01.000Z
src/box2ddestructionlistener.cpp
bobweaver/qml-box2d
905841c01d6603678d34f0f8aaaf6843b70dc08a
[ "Zlib" ]
null
null
null
src/box2ddestructionlistener.cpp
bobweaver/qml-box2d
905841c01d6603678d34f0f8aaaf6843b70dc08a
[ "Zlib" ]
null
null
null
/* * box2ddestructionlistener.cpp * Copyright (c) 2011 Joonas Erkinheimo <joonas.erkinheimo@nokia.com> * Copyright (c) 2011 Thorbjørn Lindeijer <thorbjorn@lindeijer.nl> * * This file is part of the Box2D QML plugin. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "box2ddestructionlistener.h" #include "box2djoint.h" #include "box2dfixture.h" /*! \class Box2DDestructionListener \title DestructionListener Class \brief Box2D doesn't use reference counting. So if you destroy a body it is really gone. Accessing a pointer to a destroyed body has undefined behavior. In other words, your program will likely crash and burn. To help fix these problems, the debug build memory manager fills destroyed entities with FDFDFDFD. This can help find problems more easily in some cases. If you destroy a Box2D entity, it is up to you to make sure you remove all references to the destroyed object. This is easy if you only have a single reference to the entity. If you have multiple references, you might consider implementing a handle class to wrap the raw pointer. Often when using Box2D you will create and destroy many bodies, shapes, and joints. Managing these entities is somewhat automated by Box2D. If you destroy a body then all associated shapes and joints are automatically destroyed. This is called implicit destruction. When you destroy a body, all its attached shapes, joints, and contacts are destroyed. This is called implicit destruction. Any body connected to one of those joints and/or contacts is woken. This process is usually convenient. However, you must be aware of one crucial issue: Caution When a body is destroyed, all fixtures and joints attached to the body are automatically destroyed. You must nullify any pointers you have to those shapes and joints. Otherwise, your program will die horribly if you try to access or destroy those shapes or joints later. To help you nullify your joint pointers, Box2D provides a listener class named b2DestructionListener that you can implement and provide to your world object. Then the world object will notify you when a joint is going to be implicitly destroyed Note that there no notification when a joint or fixture is explicitly destroyed. In this case ownership is clear and you can perform the necessary cleanup on the spot. If you like, you can call your own implementation of b2DestructionListener to keep cleanup code centralized. Implicit destruction is a great convenience in many cases. It can also make your program fall apart. You may store pointers to shapes and joints somewhere in your code. These pointers become orphaned when an associated body is destroyed. The situation becomes worse when you consider that joints are often created by a part of the code unrelated to management of the associated body. For example, the testbed creates a b2MouseJoint for interactive manipulation of bodies on the screen. Box2D provides a callback mechanism to inform your application when implicit destruction occurs. This gives your application a chance to nullify the orphaned pointers. This callback mechanism is described later in this manual. You can implement a b2DestructionListener that allows b2World to inform you when a shape or joint is implicitly destroyed because an associated body was destroyed. This will help prevent your code from accessing orphaned pointers. class MyDestructionListener : public b2DestructionListener { void SayGoodbye(b2Joint* joint) { // remove all references to joint. } }; You can then register an instance of your destruction listener with your world object. You should do this during world initialization. myWorld->SetListener(myDestructionListener); */ Box2DDestructionListener::Box2DDestructionListener(QObject *parent) : QObject(parent) { } void Box2DDestructionListener::SayGoodbye(b2Joint *joint) { if (joint->GetUserData()) { Box2DJoint *temp = toBox2DJoint(joint); temp->nullifyJoint(); delete temp; } } void Box2DDestructionListener::SayGoodbye(b2Fixture *fixture) { emit fixtureDestroyed(toBox2DFixture(fixture)); }
49.24
108
0.791024
56a0d0b3fad5eb659d96e937d612a531ba3d9e04
1,259
cpp
C++
college/COMP053/LAB01/main.cpp
Ambamore2000/Ambamore2000.github.io
2e84d015f95fd43af55240943477132744fa3a82
[ "MIT" ]
null
null
null
college/COMP053/LAB01/main.cpp
Ambamore2000/Ambamore2000.github.io
2e84d015f95fd43af55240943477132744fa3a82
[ "MIT" ]
4
2020-02-26T13:11:19.000Z
2021-09-28T00:07:05.000Z
college/COMP053/LAB01/main.cpp
Ambamore2000/Ambamore2000.github.io
2e84d015f95fd43af55240943477132744fa3a82
[ "MIT" ]
null
null
null
////////////////////////////////////////////////// /// Group Members: Andrew Kim, Ethan Rodriguez /// ////////////////////////////////////////////////// #include <iostream> using namespace std; class State { public: State(); void printSize() const; void setName(string name) { this->name = name; } void setPopulation(int population) { this->population = population; } string getName() const { return name; } int getPopulation() const { return population; } private: string name; // Name of State. int population; // Population size of State. string size() const; }; State::State() { setName("N/A"); setPopulation(0); } string State::size() const { if (getPopulation() < 1000000) { return "small"; } else if (getPopulation() > 1000000 && getPopulation() < 5000000) { return "medium"; } else if (getPopulation() > 5000000) { return "large"; } } void State::printSize() const { cout << getName() << ": " << size() << endl; } int main() { State state1; state1.printSize(); state1.setName("California"); state1.setPopulation(40000000); state1.printSize(); return 0; }
18.514706
72
0.526608
56a1bd12b942ee6a6bcb244043c7eb2cad8cca1b
7,224
cc
C++
Library/Utilities/fftw++-2.05/mpi/cconv3.cc
stevend12/SolutioCpp
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
[ "Apache-2.0" ]
9
2017-06-27T14:04:46.000Z
2022-02-17T17:38:03.000Z
Library/Utilities/fftw++-2.05/mpi/cconv3.cc
stevend12/SolutioCpp
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
[ "Apache-2.0" ]
null
null
null
Library/Utilities/fftw++-2.05/mpi/cconv3.cc
stevend12/SolutioCpp
6fa8a12207cd1e7e806a8ef5de93dc137c33856e
[ "Apache-2.0" ]
3
2017-06-23T20:10:44.000Z
2021-01-13T10:09:46.000Z
#include "mpiconvolution.h" #include "utils.h" using namespace std; using namespace utils; using namespace fftwpp; void init(Complex **F, unsigned int X, unsigned int Y, unsigned int Z, unsigned int x0, unsigned int y0, unsigned int z0, unsigned int x, unsigned int y, unsigned int z, unsigned int A=2) { unsigned int M=A/2; double factor=1.0/sqrt((double) M); for(unsigned int s=0; s < M; ++s) { Complex *Fs=F[s]; Complex *Gs=F[s+M]; double S=sqrt(1.0+s); double ffactor=S*factor; double gfactor=1.0/S*factor; for(unsigned int i=0; i < X; ++i) { for(unsigned int j=0; j < y; j++) { unsigned int jj=y0+j; for(unsigned int k=0; k < z; k++) { unsigned int kk=z0+k; unsigned int pos=i*y*z+j*z+k; Fs[pos]=ffactor*Complex(i+kk,jj+kk); Gs[pos]=gfactor*Complex(2*i+kk,jj+1+kk); } } } } } void init(Complex **F,split3 &d, unsigned int A=2) { init(F, d.X,d.Y,d.Z, d.x0,d.y0,d.z0, d.x,d.y,d.z,A); } void show(Complex *F, unsigned int X, unsigned int Y, unsigned int Z) { for(unsigned int i=0; i < X; ++i) { for(unsigned int j=0; j < Y; ++j) { for(unsigned int k=0; k < Z; ++k) { unsigned int pos=i*Y*Z+j*Z+k; cout << F[pos] << "\t"; } cout << endl; } cout << endl; } } int main(int argc, char* argv[]) { // Number of iterations. unsigned int N0=1000000; unsigned int N=0; int divisor=0; // Test for best block divisor int alltoall=-1; // Test for best alltoall routine int stats=0; unsigned int mx=4; unsigned int my=0; unsigned int mz=0; unsigned int A=2; // Number of independent inputs unsigned int B=1; // Number of outputs unsigned int outlimit=3000; #ifndef __SSE2__ fftw::effort |= FFTW_NO_SIMD; #endif int retval=0; bool test=false; bool quiet=false; int provided; MPI_Init_thread(&argc,&argv,MPI_THREAD_FUNNELED,&provided); int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); if(rank != 0) opterr=0; #ifdef __GNUC__ optind=0; #endif for (;;) { int c = getopt(argc,argv,"ihtqa:A:B:N:T:S:m:n:s:x:y:z:"); if (c == -1) break; switch (c) { case 0: break; case 'A': A=atoi(optarg); break; case 'B': B=atoi(optarg); break; case 'a': divisor=atoi(optarg); break; case 'N': N=atoi(optarg); break; case 'm': mx=my=mz=atoi(optarg); break; case 's': alltoall=atoi(optarg); break; case 'x': mx=atoi(optarg); break; case 'y': my=atoi(optarg); break; case 'z': mz=atoi(optarg); break; case 'n': N0=atoi(optarg); break; case 't': test=true; break; case 'q': quiet=true; break; case 'T': fftw::maxthreads=atoi(optarg); break; case 'S': stats=atoi(optarg); break; case 'i': // For compatibility reasons with -i option in OpenMP version. break; case 'h': default: if(rank == 0) { usage(3); usageTranspose(); } exit(1); } } if(my == 0) my=mx; if(mz == 0) mz=mx; if(N == 0) { N=N0/mx/my/mz; if(N < 20) N=20; } int size; MPI_Comm_size(MPI_COMM_WORLD,&size); unsigned int x=ceilquotient(mx,size); unsigned int y=ceilquotient(my,size); bool allowpencil=mx*y == x*my; MPIgroup group(MPI_COMM_WORLD,my,mz,allowpencil); if(group.size > 1 && provided < MPI_THREAD_FUNNELED) fftw::maxthreads=1; defaultmpithreads=fftw::maxthreads; if(group.rank < group.size) { bool main=group.rank == 0; if(!quiet && main) { seconds(); cout << "Configuration: " << group.size << " nodes X " << fftw::maxthreads << " threads/node" << endl; cout << "Using MPI VERSION " << MPI_VERSION << endl; } multiplier *mult; switch(A) { case 2: mult=multbinary; break; case 4: mult=multbinary2; break; case 6: mult=multbinary3; break; case 8: mult=multbinary4; break; case 16: mult=multbinary8; break; default: if(main) cout << "A=" << A << " is not yet implemented" << endl; exit(1); } if(!quiet && main) { if(!test) cout << "N=" << N << endl; cout << "A=" << A << endl; cout << "mx=" << mx << ", my=" << my << ", mz=" << mz << endl; } split3 d(mx,my,mz,group,true); bool showresult = mx*my*mz < outlimit; if(B != 1) { cerr << "Only B=1 is implemented" << endl; exit(1); } Complex **F=new Complex*[A]; for(unsigned int a=0; a < A; a++) { F[a]=ComplexAlign(d.n); } ImplicitConvolution3MPI C(mx,my,mz,d,mpiOptions(divisor,alltoall),A,B); if(test) { init(F,d,A); if(!quiet && showresult) { if(main) cout << "Distributed input:" << endl; for(unsigned int a=0; a < A; a++) { if(main) cout << "a: " << a << endl; show(F[a],mx,d.y,d.z,group.active); } } if(!quiet && main) cout << "Gathered input:" << endl; Complex **F0=new Complex*[A]; for(unsigned int a=0; a < A; a++) { if(main) { F0[a]=ComplexAlign(mx*my*mz); } gatheryz(F[a],F0[a],d,group.active); if(!quiet && main && showresult) { cout << "a: " << a << endl; show(F0[a],mx,my,mz); } } C.convolve(F,mult); if(!quiet && showresult) { if(main) cout << "Distributed output:" << endl; show(F[0],mx,d.y,d.z,group.active); } Complex *FC0=ComplexAlign(mx*my*mz); gatheryz(F[0],FC0,d,group.active); if(!quiet && main && showresult) { cout << "Gathered output:" << endl; show(FC0,mx,my,mz); } if(main) { unsigned int B=1; // TODO: generalize ImplicitConvolution3 C(mx,my,mz,A,B); C.convolve(F0,mult); if(!quiet && showresult) { cout << "Local output:" << endl; show(F0[0],mx,my,mz); } } if(main) retval += checkerror(F0[0],FC0,d.X*d.Y*d.Z); if(main) { deleteAlign(FC0); for(unsigned int a=0; a < A; a++) deleteAlign(F0[a]); delete[] F0; } } else { if(!quiet && main) cout << "Initialized after " << seconds() << " seconds." << endl; MPI_Barrier(group.active); double *T=new double[N]; for(unsigned int i=0; i < N; i++) { init(F,d,A); MPI_Barrier(group.active); seconds(); C.convolve(F,mult); // C.convolve(f,g); T[i]=seconds(); MPI_Barrier(group.active); } if(main) timings("Implicit",mx,T,N,stats); delete[] T; if(!quiet && showresult) show(F[0],mx,d.y,d.z,group.active); } for(unsigned int a=0; a < A; a++) deleteAlign(F[a]); delete[] F; } MPI_Finalize(); return retval; }
23.006369
79
0.508029
56a36fc4c7c1ccc621bcf16a5b0375220f0f8cd4
4,132
cc
C++
common/SettingService.cc
zhiqiang-hu/cell-phone-ux-demo
80df27f47bdf3318b60fe327890f868c3fe28969
[ "Apache-2.0" ]
13
2017-12-17T16:18:44.000Z
2022-01-07T15:40:36.000Z
common/SettingService.cc
zhiqiang-hu/cell-phone-ux-demo
80df27f47bdf3318b60fe327890f868c3fe28969
[ "Apache-2.0" ]
null
null
null
common/SettingService.cc
zhiqiang-hu/cell-phone-ux-demo
80df27f47bdf3318b60fe327890f868c3fe28969
[ "Apache-2.0" ]
8
2018-07-07T03:08:33.000Z
2022-01-27T09:25:08.000Z
/////////////////////////////////////////////////////////////////////////////// // // IMPORTANT NOTICE // // The following open source license statement does not apply to any // entity in the Exception List published by FMSoft. // // For more information, please visit: // // https://www.fmsoft.cn/exception-list // ////////////////////////////////////////////////////////////////////////////// #include <cstring> #include <cstdarg> #include <cassert> #include "global.h" #include "SettingService.hh" #include "ContentResolver.hh" #include "SettingsProvider.hh" SettingService* SettingService::s_service = NULL; const char* SettingService::s_optionTable[MAX_OPTION] = { "Photo", "WLAN", "Clock", "Shock", "Network selection", "Language", "Airplane mode", "Bluetooth", "Silent mode" }; SettingService::SettingService() { } SettingService* SettingService::singleton() { if (NULL == s_service) { static SettingService sSettingService; s_service = &sSettingService; return s_service; //return s_service = new SettingService; } return s_service; } ContentValues::Strings SettingService::getAllItemNames() { // StringArray selection; StringArray item_names; // selection.push_back(SettingsProvider::COL_NAME); ContentCursor* cur = GET_CONTENT_RESOLVER()->query(SettingsProvider::CONTENT_URI, NULL, NULL, NULL, NULL); if (NULL != cur) { for (cur->moveToFirst(); !cur->isLast(); cur->moveToNext()) { item_names.push_back(cur->getString(SettingsProvider::COL_NAME)); } delete cur; } return item_names; } ContentValues::Strings SettingService::getCandidacy(const std::string& name) { ContentValues::Strings result; ContentCursor* cur = getContentByName(name); if (NULL != cur) { std::string candidacy(cur->getString(SettingsProvider::COL_CANDIDACY)); size_t pos; if (candidacy.length() > 0) { while (std::string::npos != (pos = candidacy.find_first_of(CANDIDACY_SEPARTOR))) { result.push_back(candidacy.substr(0, pos)); candidacy = candidacy.substr(pos + 1); } if (!candidacy.empty()) { result.push_back(candidacy); } } delete cur; } return result; } std::string SettingService::getCurrent(const std::string& name) { std::string result; ContentCursor* cur = getContentByName(name); if (NULL != cur) { for (cur->moveToFirst(); !cur->isLast(); cur->moveToNext()) { result = (cur->getString(SettingsProvider::COL_CURRENT)); } delete cur; } return result; } ExtraType SettingService::getItemType(const std::string& name) { ContentCursor* cur = getContentByName(name); ExtraType ret; if (NULL != cur) { for (cur->moveToFirst(); !cur->isLast(); cur->moveToNext()) { ret = static_cast<ExtraType>(cur->getInt(SettingsProvider::COL_TYPE)); delete cur; return ret; } delete cur; } return TYPE_NULL; } bool SettingService::getRawData(const ContentValues*& value) { return false; } void SettingService::setCurrent(const std::string& name, const std::string& val) { std::string where(SettingsProvider::COL_NAME); where += "='"; where += name; where += "'"; ContentValues cv; cv.putString(SettingsProvider::COL_CURRENT, val); GET_CONTENT_RESOLVER()->update(SettingsProvider::CONTENT_URI, cv, &where, NULL); } ContentCursor* SettingService::getContentByName(const std::string& name) { std::string where(SettingsProvider::COL_NAME); where += "='"; where += name; where += "'"; ContentCursor* cur = GET_CONTENT_RESOLVER()->query(SettingsProvider::CONTENT_URI, NULL, &where, NULL, NULL); return cur; } std::string SettingService::getCurrent(Option opt) { return getCurrent(s_optionTable[opt]); } ExtraType SettingService::getItemType(Option opt) { return getItemType(s_optionTable[opt]); }
27.006536
115
0.613262
56a37bab1a6013d24cb768f084cecc1faf7e8e02
1,044
cpp
C++
include/nac/ProcessLauncher.cpp
nacitar/old-projects
e5af376f868124b9828196df1f55adb682969f3d
[ "MIT" ]
1
2016-05-04T04:22:42.000Z
2016-05-04T04:22:42.000Z
include/nac/ProcessLauncher.cpp
nacitar/old-projects
e5af376f868124b9828196df1f55adb682969f3d
[ "MIT" ]
null
null
null
include/nac/ProcessLauncher.cpp
nacitar/old-projects
e5af376f868124b9828196df1f55adb682969f3d
[ "MIT" ]
6
2016-05-04T04:23:02.000Z
2020-11-30T22:32:43.000Z
#include "ProcessLauncher.h" namespace nac { ProcessLauncher::ProcessLauncher(std::string strFilePath_,std::string strDirectory_) : strFilePath(strFilePath_), strDirectory(strDirectory_) { if (strDirectory.empty()) { std::string strTemp; split_path(strFilePath,strDirectory,strTemp); } } bool ProcessLauncher::Launch(Process&objProc,const std::string& strParameters,bool bSuspended) const { std::string strPath, strFile, strCommandLine; objProc = Process(); split_path(strFilePath,strPath,strFile); strCommandLine = std::string("\"")+strFilePath+std::string("\""); if (!strParameters.empty()) strCommandLine += std::string(" ")+strParameters; if (!CreateProcess(strFilePath.c_str(), const_cast<char*>(strCommandLine.c_str()), NULL,NULL,FALSE,CREATE_DEFAULT_ERROR_MODE | (bSuspended?CREATE_SUSPENDED:0), NULL,(strDirectory.empty()?NULL:strDirectory.c_str()), &(objProc.si),&(objProc.pi))) { objProc = Process(); return false; } return true; } }
29
102
0.694444
56a44ba46e683f431be3fabd9fd1acc81adb33ae
806
cpp
C++
calc/c_rgb_yuv.cpp
dlarue/donkey_racing
83d243b9379330ed2a4ad462106bc7c294baa92c
[ "MIT" ]
15
2017-08-18T12:26:15.000Z
2020-07-19T23:06:24.000Z
calc/c_rgb_yuv.cpp
dlarue/donkey_racing
83d243b9379330ed2a4ad462106bc7c294baa92c
[ "MIT" ]
2
2018-02-10T23:52:47.000Z
2020-06-09T00:28:47.000Z
calc/c_rgb_yuv.cpp
dlarue/donkey_racing
83d243b9379330ed2a4ad462106bc7c294baa92c
[ "MIT" ]
8
2017-08-30T04:02:47.000Z
2019-01-21T18:09:13.000Z
#include <stdio.h> #include <string.h> #include <stdlib.h> void print_rgb(int q) { float r = ((q >>16) & 0xff); float g = ((q >> 8) & 0xff); float b = (q & 0xff); float y = r * 0.299f + g * 0.587f + b * 0.114f; float u = 0.492f * (b - y); float v = 0.492f * (r - y); fprintf(stdout, "%.1f %.1f %.1f\n", y, u, v); } int main(int argc, char const *argv[]) { if (argc == 2 && strlen(argv[1]) == 6) { char *s; int r = strtol(argv[1], &s, 16); print_rgb(r); return 0; } if (argc == 4) { int r = atoi(argv[1]); int g = atoi(argv[2]); int b = atoi(argv[3]); print_rgb((r << 16) | (g << 8) | b); return 0; } fprintf(stderr, "usage: c_rgb_yuv rrggbb | c_rgb_yuv r g b\n"); return 1; }
22.388889
67
0.46402
56a5da54a9181d31831549916dddaef3e59252fd
616
cpp
C++
factory.cpp
iambillzhao/Movie-Store
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
[ "MIT" ]
1
2020-07-10T06:48:34.000Z
2020-07-10T06:48:34.000Z
factory.cpp
iambillzhao/Movie-Store
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
[ "MIT" ]
null
null
null
factory.cpp
iambillzhao/Movie-Store
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
[ "MIT" ]
null
null
null
/* * factory.cpp is part of the Movie Store Simulator, a C++ program that * offers the function of borrow, return, or stock with up to 10,000 * customers and 26 genres of movies * * @author Bill Zhao, Lucas Bradley * @date March 12th */ #include "factory.h" #include <iostream> // buildMovie takes a string Input and builds the // movie according to specifications Movie *Factory::buildMovie(std::string Input) { char Type = Input[0]; if (Type == 'F') return new Comedy(Input); if (Type == 'C') return new Classic(Input); if (Type == 'D') return new Drama(Input); return nullptr; }
22
71
0.672078
56a7158d66e5a8137e78fd42274f43080a4a3243
554
cpp
C++
test/predict/main.cpp
coffee-lord/angonoka
a8a4a79da4092630c5243c2081f92ba39d0b056c
[ "MIT" ]
2
2019-10-23T18:05:25.000Z
2022-02-21T21:53:24.000Z
test/predict/main.cpp
coffee-lord/angonoka
a8a4a79da4092630c5243c2081f92ba39d0b056c
[ "MIT" ]
3
2022-02-12T19:52:27.000Z
2022-02-12T19:55:52.000Z
test/stun/stochastic_tunneling/main.cpp
coffee-lord/angonoka
a8a4a79da4092630c5243c2081f92ba39d0b056c
[ "MIT" ]
null
null
null
#include <boost/ut.hpp> // boost::ut relies on static destructors so if // we don't defer LLVM coverage report until after // ut's destructor we won't get any coverage. #if defined(__llvm__) && defined(ANGONOKA_COVERAGE) extern "C" { int __llvm_profile_runtime; void __llvm_profile_initialize_file(void); int __llvm_profile_write_file(void); }; namespace { struct on_exit { ~on_exit() noexcept { __llvm_profile_initialize_file(); __llvm_profile_write_file(); }; }; constinit on_exit _; }; // namespace #endif int main() { }
22.16
51
0.718412
56a9d5b4f56c4c293fe2f0c7bb6f54377a4c2296
2,791
cpp
C++
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
akshaykumar23399/DOTS
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
[ "Unlicense" ]
null
null
null
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
akshaykumar23399/DOTS
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
[ "Unlicense" ]
null
null
null
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
akshaykumar23399/DOTS
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
[ "Unlicense" ]
null
null
null
/* * MtpMetadataCache.cpp * * Author: Jason Ferrara * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This software 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 library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02111-1301, USA. * licensing@fsf.org */ #include "MtpMetadataCache.h" #include <time.h> #include <assert.h> MtpMetadataCacheFiller::~MtpMetadataCacheFiller() { } MtpMetadataCache::MtpMetadataCache() { } MtpMetadataCache::~MtpMetadataCache() { for(local_file_cache_type::iterator i = m_localFileCache.begin(); i != m_localFileCache.end(); i++) { delete i->second; } } MtpNodeMetadata MtpMetadataCache::getItem(uint32_t id, MtpMetadataCacheFiller& source) { clearOld(); cache_lookup_type::iterator i = m_cacheLookup.find(id); if (i != m_cacheLookup.end()) return i->second->data; CacheEntry newData; newData.data = source.getMetadata(); assert(newData.data.self.id == id); newData.whenCreated = time(0); m_cacheLookup[id] = m_cache.insert(m_cache.end(), newData); return newData.data; } void MtpMetadataCache::clearItem(uint32_t id) { cache_lookup_type::iterator i = m_cacheLookup.find(id); if (i != m_cacheLookup.end()) { m_cache.erase(i->second); m_cacheLookup.erase(i); } } void MtpMetadataCache::clearOld() { time_t now = time(0); for(cache_type::iterator i = m_cache.begin(); i != m_cache.end();) { if ((now - i->whenCreated) > 5) { m_cacheLookup.erase(m_cacheLookup.find(i->data.self.id)); i = m_cache.erase(i); } else return; } } MtpLocalFileCopy* MtpMetadataCache::openFile(MtpDevice& device, uint32_t id) { local_file_cache_type::iterator i = m_localFileCache.find(id); if (i != m_localFileCache.end()) return i->second; MtpLocalFileCopy* newFile = new MtpLocalFileCopy(device, id); m_localFileCache[id] = newFile; return newFile; } MtpLocalFileCopy* MtpMetadataCache::getOpenedFile(uint32_t id) { local_file_cache_type::iterator i = m_localFileCache.find(id); if (i != m_localFileCache.end()) return i->second; else return 0; } uint32_t MtpMetadataCache::closeFile(uint32_t id) { local_file_cache_type::iterator i = m_localFileCache.find(id); if (i != m_localFileCache.end()) { uint32_t newId = i->second->close(); delete i->second; m_localFileCache.erase(i); return newId; } return id; }
23.652542
100
0.724113
56abeca03db4452942dae28104ef62327d65de85
4,176
hpp
C++
core/src/Simulation/AssetManager.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
core/src/Simulation/AssetManager.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
core/src/Simulation/AssetManager.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_CORE_SIMULATION_ASSET_MANAGER_ #define CRIMILD_CORE_SIMULATION_ASSET_MANAGER_ #include "Foundation/SharedObject.hpp" #include "Foundation/Macros.hpp" #include "Foundation/Singleton.hpp" #include "Visitors/ShallowCopy.hpp" #include <memory> #include <map> #include <string> #include <mutex> namespace crimild { class Texture; class AssetManager : public NonCopyable, public DynamicSingleton< AssetManager > { private: using Mutex = std::mutex; using ScopedLock = std::lock_guard< Mutex >; public: static constexpr const char *FONT_DEFAULT = "fonts/default"; static constexpr const char *FONT_SYSTEM = "fonts/system"; public: AssetManager( void ); virtual ~AssetManager( void ); void set( std::string name, SharedPointer< SharedObject > const &asset, bool isPersistent = false ) { ScopedLock lock( _mutex ); if ( isPersistent ) { _persistentAssets[ name ] = asset; } else { _assets[ name ] = asset; } } template< class T > T *get( std::string name ) { ScopedLock lock( _mutex ); auto &asset = _assets[ name ]; if ( asset == nullptr ) { asset = _persistentAssets[ name ]; } return static_cast< T * >( crimild::get_ptr( asset ) ); } template< class T > SharedPointer< T > clone( std::string filename ) { // No need for lock once we get the prototype auto assetProto = get< T >( filename ); assert( assetProto != nullptr && ( filename + " does not exist in Asset Manager cache" ).c_str() ); ShallowCopy shallowCopy; assetProto->perform( shallowCopy ); return shallowCopy.getResult< T >(); } void clear( bool clearAll = false ) { ScopedLock lock( _mutex ); _assets.clear(); if ( clearAll ) { _persistentAssets.clear(); } } private: std::map< std::string, SharedPointer< SharedObject > > _assets; std::map< std::string, SharedPointer< SharedObject > > _persistentAssets; Mutex _mutex; public: void loadFont( std::string name, std::string fileName ); }; template<> Texture *AssetManager::get< Texture >( std::string name ); } #endif
33.677419
111
0.625479
56afadad706c7d38fce2265cb20214649b49db93
548
hpp
C++
PP/decompose_const.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
3
2019-07-12T23:12:24.000Z
2019-09-05T07:57:45.000Z
PP/decompose_const.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
PP/decompose_const.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
#pragma once #include <PP/compose.hpp> #include <PP/cv_qualifier.hpp> #include <PP/decompose_pair.hpp> #include <PP/overloaded.hpp> #include <PP/to_type_t.hpp> #include <PP/value_t.hpp> namespace PP { PP_CIA decompose_const = compose( overloaded( []<typename T>(type_t<const T>) { return make_decompose_pair(type<T>, PP::value<cv_qualifier::Const>); }, []<typename T>(type_t<T>) { return make_decompose_pair(type<T>, PP::value<cv_qualifier::none>); }), to_type_t); }
23.826087
80
0.625912
56b205ff002447e58f3296486d4f79983530a652
989
cpp
C++
MNO/MATCHORDER/yujungee.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
5
2022-01-13T08:21:54.000Z
2022-01-31T03:37:14.000Z
MNO/MATCHORDER/yujungee.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
115
2022-01-13T07:37:23.000Z
2022-03-13T14:09:15.000Z
MNO/MATCHORDER/yujungee.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
2
2022-01-27T02:10:23.000Z
2022-02-09T14:37:04.000Z
// // matchOrder.cpp // study6 // // Created by yujeong on 2021/03/05. // #include <iostream> #include <algorithm> #include <vector> using namespace std; int tc , n; int rus_r[100], kor_r[100]; vector<int> russian; vector<int> korean; int match() { sort(korean.begin(), korean.end()); int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (korean[j] >= russian[i]) { res++; korean[j] = 0; break; } } } return res; } int main() { cin >> tc; while (tc--) { cin >> n; korean = russian = vector<int>(n); for (int i = 0; i < n; i++) { cin >> russian[i]; } for (int i = 0; i < n; i++) { cin >> korean[i]; } // 정렬 후 함수에 넣기 sort(russian.begin(), russian.end()); sort(korean.begin(), korean.end()); cout << match() << endl; } return 0; }
18.314815
45
0.436805
56b3b547a5fc191f86116d140353a47f0ba15c19
9,427
cpp
C++
tests/server/barriers-validity.cpp
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
1ffa848434ce084cf02dd1abc231ff99dad0d277
[ "MIT" ]
null
null
null
tests/server/barriers-validity.cpp
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
1ffa848434ce084cf02dd1abc231ff99dad0d277
[ "MIT" ]
1
2020-09-07T03:24:26.000Z
2020-09-07T03:24:26.000Z
tests/server/barriers-validity.cpp
freedesktop-unofficial-mirror/xorg__test__xorg-integration-tests
1ffa848434ce084cf02dd1abc231ff99dad0d277
[ "MIT" ]
1
2020-09-07T03:04:34.000Z
2020-09-07T03:04:34.000Z
/* * Copyright © 2012-2013 Red Hat, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ #if HAVE_CONFIG_H #include <config.h> #endif #include <xorg/gtest/xorg-gtest.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/extensions/Xfixes.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> #include "xit-event.h" #include "barriers-common.h" #include "helpers.h" #if HAVE_FIXES5 class BarrierSimpleTest : public BarrierTest {}; TEST_F(BarrierSimpleTest, CreateAndDestroyBarrier) { XORG_TESTCASE("Create a valid pointer barrier.\n" "Ensure PointerBarrier XID is valid.\n" "Delete pointer barrier\n" "Ensure no error is generated\n"); ::Display *dpy = Display(); Window root = DefaultRootWindow(dpy); PointerBarrier barrier; XSync(dpy, False); barrier = XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, BarrierPositiveX, 0, NULL); ASSERT_NE((PointerBarrier)None, barrier) << "Failed to create barrier."; SetErrorTrap(dpy); XFixesDestroyPointerBarrier(dpy, barrier); ASSERT_NO_ERROR(ReleaseErrorTrap(dpy)); } TEST_F(BarrierSimpleTest, DestroyInvalidBarrier) { XORG_TESTCASE("Delete invalid pointer barrier\n" "Ensure error is generated\n"); SetErrorTrap(Display()); XFixesDestroyPointerBarrier(Display(), -1); const XErrorEvent *error = ReleaseErrorTrap(Display()); ASSERT_ERROR(error, xfixes_error_base + BadBarrier); } #if HAVE_XI23 TEST_F(BarrierSimpleTest, MultipleClientSecurity) { XORG_TESTCASE("Ensure that two clients can't delete" " each other's barriers.\n"); ::Display *dpy1 = XOpenDisplay(server.GetDisplayString().c_str()); ::Display *dpy2 = XOpenDisplay(server.GetDisplayString().c_str()); Window root = DefaultRootWindow(dpy1); PointerBarrier barrier = XFixesCreatePointerBarrier(dpy1, root, 20, 20, 20, 40, 0, 0, NULL); XSync(dpy1, False); SetErrorTrap(dpy2); XFixesDestroyPointerBarrier(dpy2, barrier); const XErrorEvent *error = ReleaseErrorTrap(dpy2); ASSERT_ERROR(error, BadAccess); XIEventMask mask; mask.deviceid = XIAllMasterDevices; mask.mask_len = XIMaskLen(XI_LASTEVENT); mask.mask = new unsigned char[mask.mask_len](); XISetMask(mask.mask, XI_BarrierHit); XISelectEvents(dpy1, root, &mask, 1); XISelectEvents(dpy2, root, &mask, 1); delete[] mask.mask; XIWarpPointer(dpy1, VIRTUAL_CORE_POINTER_ID, None, root, 0, 0, 0, 0, 30, 30); XSync(dpy1, False); XSync(dpy2, False); dev->PlayOne(EV_REL, REL_X, -40, True); XITEvent<XIBarrierEvent> event(dpy1, GenericEvent, xi2_opcode, XI_BarrierHit); ASSERT_EQ(XPending(dpy2), 0); SetErrorTrap(dpy2); XIBarrierReleasePointer(dpy2, VIRTUAL_CORE_POINTER_ID, event.ev->barrier, 1); error = ReleaseErrorTrap(dpy2); ASSERT_ERROR(error, BadAccess); } #endif TEST_F(BarrierSimpleTest, PixmapsNotAllowed) { XORG_TESTCASE("Pixmaps are not allowed as drawable.\n" "Ensure error is generated\n"); ::Display *dpy = Display(); Window root = DefaultRootWindow(dpy); Pixmap p = XCreatePixmap(dpy, root, 10, 10, DefaultDepth(dpy, DefaultScreen(dpy))); XSync(dpy, False); SetErrorTrap(Display()); XFixesCreatePointerBarrier(dpy, p, 20, 20, 20, 40, BarrierPositiveX, 0, NULL); const XErrorEvent *error = ReleaseErrorTrap(Display()); ASSERT_ERROR(error, BadWindow); ASSERT_EQ(error->resourceid, p); } TEST_F(BarrierSimpleTest, InvalidDeviceCausesBadDevice) { XORG_TESTCASE("Ensure that passing a garbage device ID\n" "to XFixesCreatePointerBarrier returns with\n" "a BadDevice error\n"); ::Display *dpy = Display(); Window root = DefaultRootWindow(dpy); int garbage_id = 0x00FACADE; const XErrorEvent *error; SetErrorTrap(dpy); XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 40, 0, 1, &garbage_id); error = ReleaseErrorTrap(dpy); ASSERT_ERROR(error, xi_error_base + XI_BadDevice); } #define VALID_DIRECTIONS \ ::testing::Values(0L, \ BarrierPositiveX, \ BarrierPositiveY, \ BarrierNegativeX, \ BarrierNegativeY, \ BarrierPositiveX | BarrierNegativeX, \ BarrierPositiveY | BarrierNegativeX) #define INVALID_DIRECTIONS \ ::testing::Values(BarrierPositiveX | BarrierPositiveY, \ BarrierNegativeX | BarrierNegativeY, \ BarrierPositiveX | BarrierNegativeY, \ BarrierNegativeX | BarrierPositiveY, \ BarrierPositiveX | BarrierNegativeX | BarrierPositiveY, \ BarrierPositiveX | BarrierNegativeX | BarrierNegativeY, \ BarrierPositiveX | BarrierPositiveY | BarrierNegativeY, \ BarrierNegativeX | BarrierPositiveY | BarrierNegativeY, \ BarrierPositiveX | BarrierNegativeX | BarrierPositiveY | BarrierNegativeY) class BarrierZeroLength : public BarrierTest, public ::testing::WithParamInterface<long int> {}; TEST_P(BarrierZeroLength, InvalidZeroLengthBarrier) { XORG_TESTCASE("Create a pointer barrier with zero length.\n" "Ensure server returns BadValue."); ::Display *dpy = Display(); Window root = DefaultRootWindow(dpy); int directions = GetParam(); XSync(dpy, False); SetErrorTrap(dpy); XFixesCreatePointerBarrier(dpy, root, 20, 20, 20, 20, directions, 0, NULL); const XErrorEvent *error = ReleaseErrorTrap(dpy); ASSERT_ERROR(error, BadValue); } INSTANTIATE_TEST_CASE_P(, BarrierZeroLength, VALID_DIRECTIONS); class BarrierNonZeroArea : public BarrierTest, public ::testing::WithParamInterface<long int> {}; TEST_P(BarrierNonZeroArea, InvalidNonZeroAreaBarrier) { XORG_TESTCASE("Create pointer barrier with non-zero area.\n" "Ensure server returns BadValue\n"); ::Display *dpy = Display(); Window root = DefaultRootWindow(dpy); int directions = GetParam(); XSync(dpy, False); SetErrorTrap(dpy); XFixesCreatePointerBarrier(dpy, root, 20, 20, 40, 40, directions, 0, NULL); const XErrorEvent *error = ReleaseErrorTrap(dpy); ASSERT_ERROR(error, BadValue); } INSTANTIATE_TEST_CASE_P(, BarrierNonZeroArea, VALID_DIRECTIONS); static void BarrierPosForDirections(int directions, int *x1, int *y1, int *x2, int *y2) { *x1 = 20; *y1 = 20; if (directions & BarrierPositiveY) { *x2 = 40; *y2 = 20; } else { *x2 = 20; *y2 = 40; } } class BarrierConflictingDirections : public BarrierTest, public ::testing::WithParamInterface<long int> {}; TEST_P(BarrierConflictingDirections, InvalidConflictingDirectionsBarrier) { XORG_TESTCASE("Create a barrier with conflicting directions, such\n" "as (PositiveX | NegativeY), and ensure that these\n" "cases are handled properly."); ::Display *dpy = Display(); Window root = DefaultRootWindow(dpy); int directions = GetParam(); int x1, y1, x2, y2; BarrierPosForDirections(directions, &x1, &y1, &x2, &y2); XSync(dpy, False); SetErrorTrap(dpy); XFixesCreatePointerBarrier(dpy, root, x1, y1, x2, y2, directions, 0, NULL); const XErrorEvent *error = ReleaseErrorTrap(dpy); /* Nonsensical directions are ignored -- they don't * raise a BadValue. Unfortunately, there's no way * to query an existing pointer barrier, so we can't * actually check that the masked directions are proper. * * Just ensure we have no error. */ ASSERT_NO_ERROR(error); } INSTANTIATE_TEST_CASE_P(, BarrierConflictingDirections, INVALID_DIRECTIONS); #endif /* HAVE_FIXES5 */
35.43985
98
0.647926
56ba0137aeee0736e49716c019b8b1a83823a719
256
cpp
C++
1543.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
22
2017-08-12T11:56:19.000Z
2022-03-27T10:04:31.000Z
1543.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
2
2017-12-17T02:52:59.000Z
2018-02-09T02:10:43.000Z
1543.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
4
2017-12-22T15:24:38.000Z
2020-05-18T14:51:16.000Z
#include <iostream> using namespace std; long long n; long long num(long long x) { if (x < 3) return x; long long r = x / 3, m = x - r - (r << 1); return (m + 1) * num(r) + m; } int main() { cin >> n; cout << n - num(n); return 0; }
19.692308
46
0.5
56bfe43665188613028fba330939ebb1d49b833a
9,590
cxx
C++
pdfwiz/parsemake/new_make2proj.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
pdfwiz/parsemake/new_make2proj.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
pdfwiz/parsemake/new_make2proj.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ // // // #pragma warning(disable:4786) /* basic algorithm is as follows: we are passed a set of targets (with accompanying parsed makefiles). Step one: create a complete target graph. This is the structure that the makefile would use to generate actions. Where actions specify invocation of make, perform analysis on this makefile as well. Step two: break in clusters. For each target in the target graph, list all DLLs/executables that this target ends up in (the "executable set"). Create a map from each "executable set" to the targets this set is uses. Each unique set is a cluster. Output each cluster as a project, with its contents being the source files listed as dependencies of the targets in the cluster. */ #include <map> #include <set> #include <string> #include <utility> // for pair<> #include <ostream> #include "generate_pdf.h" // for debugging: #include <iostream> #pragma warning(disable:4503) #include "make_toplevel.h" #include "filetypes.h" #include "filename.h" #include "new_make2proj.h" // questions: currently, we build from the dependency level, using // list_all_depends(). Should we be better off with list_all_targets()? typedef pair<makefile *, string> targetID; // could be pair<makefile, target> typedef string exeID; class graphnode; class cluster { public: void set_name(string const &); //private: string name; set < targetID > whereused; }; // globals: typedef map < targetID, graphnode * > all_targets_type; all_targets_type all_targets; typedef map < set<exeID>, cluster *> cluster_type; cluster_type clusters; void cluster::set_name(string const &n) { name = n; } // build graph: class graphnode { public: graphnode(targetID); void add_child(graphnode *); void add_parent(graphnode *); set<exeID> & exelist(); private: string name; set<graphnode *> parents; set<graphnode *> children; make_target * member; set<exeID> * execlist; }; void graphnode::add_child(graphnode * child) { children.insert(child); } void graphnode::add_parent(graphnode * parent) { parents.insert(parent); } graphnode::graphnode(targetID t) : name(t.second), execlist(0), member(0) { makefile *mf = t.first; string const &target = t.second; set<string> *children = mf->list_target_depends(target); // TODO: // add make actions to the list of pending makefiles to be processed for (set<string>::iterator child = children->begin(); child != children->end(); ++child) { // on loop, this will create duplicate nodes all_targets_type::iterator i = all_targets.find(targetID(mf, *child)); if (i == all_targets.end()) { targetID tid(mf,*child); i = all_targets.insert( all_targets_type::value_type(tid, new graphnode(tid)) ).first; } add_child(i->second); i->second->add_parent(this); } } void add_mftarget2graph(makefile *mf, string const &target) { // foreach target targetID root(mf, target); all_targets.insert(all_targets_type::value_type(root, new graphnode(root))); } void figure_clusters() { string first_target = all_targets.empty() ? string("") : all_targets.begin()->first.second; // for each target, add it to the list of targets in that cluster for (all_targets_type::iterator i = all_targets.begin(); i != all_targets.end(); ++i) { //cout << "considering target: " << i->first.second << endl; #if 0 // do clustering: set<exeID> key = (i->second->exelist()); // make sure empty targets are put in orphaned list: if (key.empty()) key.insert("orphaned"); #else // don't do clustering: set<exeID> key; key.insert(first_target); #endif //cout << "used in " << key.size() << " executables: " << *key.begin() << endl; cluster_type::iterator here = clusters.find(key); if (here == clusters.end()) { here = clusters.insert(cluster_type::value_type(key, new cluster )).first; } //cout << here->second; here->second->whereused.insert(i->first); } } set<exeID> & graphnode::exelist() { if (execlist == 0) { //exelist is storage, and acts as "been here" flag execlist = new set<exeID>; if (global_filetypes.what_type(name).kind == filetype::EXECUTABLE) execlist->insert(name); else { set<graphnode *>::iterator x = parents.begin(); for (;x != parents.end(); ++x) { (*x)->exelist(); set<exeID> parentset = (*x)->exelist(); #if defined(MSVC_NOT_BROKEN) execlist->insert(parentset.begin(), parentset.end()); #else for (set<exeID>::iterator y = parentset.begin(); y != parentset.end(); ++y) { execlist->insert(*y); } #endif } } } // else exelist is cached return *execlist; } #include <iostream> void print_graph() { cluster_type::const_iterator i = clusters.begin(); for (; i != clusters.end(); ++i) { cout << "cluster used in executables:"; set<exeID>::const_iterator j; for (j = i->first.begin(); j != i->first.end(); ++j) { cout << " " << *j; } cout << endl << " made up of:" ; set<targetID> &tmp = i->second->whereused; set<targetID>::const_iterator k; for (k = tmp.begin(); k != tmp.end(); ++k) { cout << " " << k->second; } cout << endl; } } static string name_cluster( set<exeID> const &clusterkey ) { string ret("CLUSTER"); // first, lookup in user-defined map: // well, maybe not! if (clusterkey.size() == 1) { // belongs to only one executable--name after that executable: // find only the last component of the name: filename f(*clusterkey.begin()); ret = f.basename(); } return ret; } set<subproj *> graph2pdf() { set <subproj *> ret; cluster_type::iterator i = clusters.begin(); for (; i != clusters.end(); ++i) { // name the cluster based on where used: string pname(name_cluster(i->first)); projname name(pname, "", pname); i->second->set_name(pname); // create a project for this cluster subproj *theproj = new subproj(name); theproj->set_selector("[[ W ]]"); ret.insert(theproj); // add source files for all targets: set<targetID> &members = i->second->whereused; set<targetID>::iterator member; for (member = members.begin(); member != members.end(); ++member) { // add dependent source files to model: makefile::stringset * dependfiles = member->first->list_target_depends(member->second); makefile::stringset::iterator s = dependfiles->begin(); while (s != dependfiles->end()) { // filter out non-source files filetype const &ftype = global_filetypes.what_type(*s); if (ftype.include_in_pdf()) { string const &fullname = member->first->member_as_absolute(*s); theproj->add_file(fullname.c_str()); } ++s; } delete dependfiles; } } return ret; } void write_scoping_rules(ostream *out) { // build map of exe->cluster usage: typedef map<exeID, set<cluster *> > themap_type; themap_type themap; // OK, now populate it: cluster_type::iterator tc; for (tc = clusters.begin(); tc != clusters.end(); ++tc) { set<exeID> const & exeset = tc->first; set<exeID>::const_iterator exe; for (exe = exeset.begin(); exe != exeset.end(); ++exe) { themap_type::iterator uses = themap.find(*exe); if (uses == themap.end()) { // not sure how to avoid this temp: set<cluster *> tmp; uses = themap.insert(themap_type::value_type(*exe, tmp)).first; } uses->second.insert(tc->second); } } // and print it: themap_type::iterator i; for (i = themap.begin(); i != themap.end(); ++i) { *out << "new_exe " << i->first << endl; set<cluster *>::iterator j; *out << "add_sll " << i->first; for (j = i->second.begin(); j != i->second.end(); ++j) { *out << " " << (*j)->name; } *out << endl; } }
28.040936
92
0.634202
56c3917f8a9590b435d02bab6a627eaa3ed8ab13
169
cpp
C++
_codeforces/486A/486a.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
_codeforces/486A/486a.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
_codeforces/486A/486a.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <iostream> using namespace std; int main() { long long n; cin >> n; if(n & 1) cout << -1LL * (n + 1LL) / 2LL << '\n'; else cout << n / 2LL << '\n'; }
13
41
0.497041
56c5ba9bd8562df759d553e5f6081d2b713ebc66
4,417
hpp
C++
test/logdataprocessor.hpp
Bembelbots/particlefilter
7fc67763da217639de403485abf8a72029c5025a
[ "FSFAP" ]
null
null
null
test/logdataprocessor.hpp
Bembelbots/particlefilter
7fc67763da217639de403485abf8a72029c5025a
[ "FSFAP" ]
null
null
null
test/logdataprocessor.hpp
Bembelbots/particlefilter
7fc67763da217639de403485abf8a72029c5025a
[ "FSFAP" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <definitions.h> #include <coords.h> #include <particlefilter.h> #include <random> struct LogData { int stamp; std::vector<Robot> poseEstimates; Robot wcs; std::vector<Robot> hypos; std::vector<DirectedCoord> odo; std::vector<VisionResult> visionResults; std::vector<std::string> s; std::vector<ParticleFilter::tLocalizationEvent> event; }; class LogDataset { public: std::vector<LogData> data; std::vector<LogData> output; //if multiple visualizations per output are needed LogDataset(const std::string &fn){ std::ifstream input(fn); LogData ld; //one cognition step in dataset for (std::string line; std::getline(input, line);) { if (line.size() < 3) { continue; } if (line.find("(") != 0) { continue; } int stamp = atoi(line.substr(1, line.find(")")).c_str()); ld.stamp = stamp; std::string s = line.substr(line.find(")") + 2); if (s.find("enter new cognition step:") == 0) { int step = atoi(s.substr(s.find(": ") + 2).c_str()); // add as new log data element data.push_back(ld); ld = LogData(); continue; } if (s.find("WCS: ") != std::string::npos) { ld.wcs.setFromString(s.substr(5)); continue; } if (s.find("Odometry: ") != std::string::npos) { size_t pos1 = s.find(";"); size_t pos2 = s.find(";", pos1 + 1); float x = atof(s.substr(10, pos1 - 10).c_str()); float y = atof(s.substr(pos1 + 1, pos2 - pos1 - 1).c_str()); float a = atof(s.substr(pos2 + 1).c_str()); ld.odo.push_back(DirectedCoord(x, y, a)); continue; } if (s.find("Measurement: ") != std::string::npos) { Robot r; r.setFromString(s.substr(13)); ld.poseEstimates.push_back(r); continue; } if (s.find("VisionResult: ") != std::string::npos) { VisionResult vr(s.substr(14)); ld.visionResults.push_back(vr); continue; } if (s.find("Emit event: ") != std::string::npos) { size_t pos = s.find(":"); ld.event.push_back(static_cast<ParticleFilter::tLocalizationEvent>(atoi(s.substr(pos+1).c_str()))); continue; } } std::cout << "read " << data.size() << " cognition steps from logfile " << std::endl; } void logtoFile(const std::string filename){ std::ofstream out(filename); int cognition_step = 0; for (auto d: output) { if (cognition_step %500 == 0){ std::cout<<cognition_step <<std::endl; } //start output with new declaration of cognition step out << "(" << d.stamp << ")" << " enter new cognition step: "<< cognition_step << std::endl; //outpus Robot position out << "(" << d.stamp << ") WCS: "<< d.wcs << std::endl; //output vision results for (auto vr : d.visionResults){ out<< "(" << d.stamp << ") " << "VisionResult: " << vr << std::endl; } //outpus measurement( pose estimations from landmarks) for (auto meas : d.poseEstimates){ out << "(" << d.stamp << ") Measurement: "<< meas << std::endl; } //output particle filter hypos for (auto hypo : d.hypos){ out << "(" << d.stamp << ") Hypo: "<< hypo << std::endl; } //output odometry for (auto odo:d.odo) { out << "(" << d.stamp << ") Odometry: "<< odo.coord.x << ";" << odo.coord.y << ";" << odo.angle.rad << std::endl; } //output localizationevent for (auto event : d.event){ out << "(" << d.stamp << ") Emit event: "<< (int) event << std::endl; } cognition_step ++; } out.close(); } };
35.620968
115
0.465927
08cb00f666f1316b124ce7bd517dd7f05c8e0ca6
473
cpp
C++
src/buffers/Vb0BufferVec2.cpp
MrMCG/MGL
894a336505b510d18dc28e3adae747fd6938816a
[ "MIT" ]
null
null
null
src/buffers/Vb0BufferVec2.cpp
MrMCG/MGL
894a336505b510d18dc28e3adae747fd6938816a
[ "MIT" ]
null
null
null
src/buffers/Vb0BufferVec2.cpp
MrMCG/MGL
894a336505b510d18dc28e3adae747fd6938816a
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include "VboBufferVec2.hpp" namespace MGL { VboBufferVec2::VboBufferVec2(std::vector<Vec2> const& data) : m_data(data) {} void VboBufferVec2::bufferData(int const location) const { bind(); glBufferData(GL_ARRAY_BUFFER, m_data.size() * sizeof(Vec2), &m_data.at(0), GL_STATIC_DRAW); glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0); glEnableVertexAttribArray(location); // unbind(); // needed? } } // MGL
23.65
93
0.710359
08cc021ac5a577a3d899c876fd16ecc61c223bfc
233
hpp
C++
arduino/vroom/topics.hpp
DrakeAxelrod/group-02
9c2ef37f3e4f25cc4572fe03cddb6016ffaa3c22
[ "MIT" ]
24
2021-12-30T16:23:43.000Z
2022-02-03T12:42:42.000Z
arduino/vroom/topics.hpp
DrakeAxelrod/group-02
9c2ef37f3e4f25cc4572fe03cddb6016ffaa3c22
[ "MIT" ]
68
2021-04-02T15:51:35.000Z
2021-05-28T10:39:11.000Z
arduino/vroom/topics.hpp
DrakeAxelrod/group-02
9c2ef37f3e4f25cc4572fe03cddb6016ffaa3c22
[ "MIT" ]
2
2021-05-09T23:08:16.000Z
2021-12-30T16:22:29.000Z
const String forward = "/smartcar/control/throttle/forward"; const String reverse = "/smartcar/control/throttle/reverse"; const String left = "/smartcar/control/steering/left"; const String right = "/smartcar/control/steering/right";
58.25
60
0.781116
08cd1078eabbff7aaf5922dd8add205a48ea0fa8
4,515
cpp
C++
src/test/accounting_tests.cpp
gabriel-eiger/bitcredit
4f8306d98116420e7e80008426006e9fd23ee7db
[ "MIT" ]
1
2015-04-23T04:45:46.000Z
2015-04-23T04:45:46.000Z
src/test/accounting_tests.cpp
gabriel-eiger/bitcredit
4f8306d98116420e7e80008426006e9fd23ee7db
[ "MIT" ]
null
null
null
src/test/accounting_tests.cpp
gabriel-eiger/bitcredit
4f8306d98116420e7e80008426006e9fd23ee7db
[ "MIT" ]
null
null
null
// Copyright (c) 2012-2014 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include <stdint.h> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #ifdef ENABLE_WALLET extern uint64_t bitcredit_nAccountingEntryNumber; extern Credits_CDBEnv bitcredit_bitdb; #endif extern Credits_CWallet* bitcredit_pwalletMain; BOOST_AUTO_TEST_SUITE(accounting_tests) static void GetResults(Credits_CWalletDB& walletdb, std::map<int64_t, CAccountingEntry>& results) { std::list<CAccountingEntry> aes; results.clear(); BOOST_CHECK(walletdb.ReorderTransactions(bitcredit_pwalletMain) == CREDITS_DB_LOAD_OK); walletdb.ListAccountCreditDebit("", aes); BOOST_FOREACH(CAccountingEntry& ae, aes) { results[ae.nOrderPos] = ae; } } BOOST_AUTO_TEST_CASE(acc_orderupgrade) { Credits_CWalletDB walletdb(bitcredit_pwalletMain->strWalletFile, &bitcredit_bitdb); std::vector<Credits_CWalletTx*> vpwtx; Credits_CWalletTx wtx; CAccountingEntry ae; std::map<int64_t, CAccountingEntry> results; LOCK(bitcredit_pwalletMain->cs_wallet); ae.strAccount = ""; ae.nCreditDebit = 1; ae.nTime = 1333333333; ae.strOtherAccount = "b"; ae.strComment = ""; walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); wtx.mapValue["comment"] = "z"; bitcredit_pwalletMain->AddToWallet(wtx); vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[0]->nTimeReceived = (unsigned int)1333333335; vpwtx[0]->nOrderPos = -1; ae.nTime = 1333333336; ae.strOtherAccount = "c"; walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); GetResults(walletdb, results); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 3); BOOST_CHECK(2 == results.size()); BOOST_CHECK(results[0].nTime == 1333333333); BOOST_CHECK(results[0].strComment.empty()); BOOST_CHECK(1 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[2].nTime == 1333333336); BOOST_CHECK(results[2].strOtherAccount == "c"); ae.nTime = 1333333330; ae.strOtherAccount = "d"; ae.nOrderPos = bitcredit_pwalletMain->IncOrderPosNext(); walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); GetResults(walletdb, results); BOOST_CHECK(results.size() == 3); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 4); BOOST_CHECK(results[0].nTime == 1333333333); BOOST_CHECK(1 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[2].nTime == 1333333336); BOOST_CHECK(results[3].nTime == 1333333330); BOOST_CHECK(results[3].strComment.empty()); wtx.mapValue["comment"] = "y"; --wtx.nLockTime; // Just to change the hash :) bitcredit_pwalletMain->AddToWallet(wtx); vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[1]->nTimeReceived = (unsigned int)1333333336; wtx.mapValue["comment"] = "x"; --wtx.nLockTime; // Just to change the hash :) bitcredit_pwalletMain->AddToWallet(wtx); vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[2]->nTimeReceived = (unsigned int)1333333329; vpwtx[2]->nOrderPos = -1; GetResults(walletdb, results); BOOST_CHECK(results.size() == 3); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 6); BOOST_CHECK(0 == vpwtx[2]->nOrderPos); BOOST_CHECK(results[1].nTime == 1333333333); BOOST_CHECK(2 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[3].nTime == 1333333336); BOOST_CHECK(results[4].nTime == 1333333330); BOOST_CHECK(results[4].strComment.empty()); BOOST_CHECK(5 == vpwtx[1]->nOrderPos); ae.nTime = 1333333334; ae.strOtherAccount = "e"; ae.nOrderPos = -1; walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); GetResults(walletdb, results); BOOST_CHECK(results.size() == 4); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 7); BOOST_CHECK(0 == vpwtx[2]->nOrderPos); BOOST_CHECK(results[1].nTime == 1333333333); BOOST_CHECK(2 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[3].nTime == 1333333336); BOOST_CHECK(results[3].strComment.empty()); BOOST_CHECK(results[4].nTime == 1333333330); BOOST_CHECK(results[4].strComment.empty()); BOOST_CHECK(results[5].nTime == 1333333334); BOOST_CHECK(6 == vpwtx[1]->nOrderPos); } BOOST_AUTO_TEST_SUITE_END()
32.956204
91
0.712514
08cea99638e5b48abdbc36e54f88f24ef9a3ddc5
6,202
cpp
C++
src/Alarm/AlarmEntry.cpp
diqiu50/value
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
[ "Apache-2.0" ]
1
2018-04-13T09:41:53.000Z
2018-04-13T09:41:53.000Z
src/Alarm/AlarmEntry.cpp
diqiu50/value
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
[ "Apache-2.0" ]
null
null
null
src/Alarm/AlarmEntry.cpp
diqiu50/value
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2005 // Packet Engineering, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification is not permitted unless authorized in writing by a duly // appointed officer of Packet Engineering, Inc. or its derivatives // // File Name: Alarm.cpp // Description: // // // Modification History: //////////////////////////////////////////////////////////////////////////// #include "Alarm/AlarmEntry.h" #include "Alarm/AlarmMgr.h" #include "AppMgr/App.h" #include "Debug/Debug.h" #include "Porting/ThreadDef.h" #include "Porting/Sleep.h" #include "Util1/Time.h" #include <execinfo.h> OmnAlarmEntry & OmnAlarmEntry::operator << (const OmnEndError) { OmnAlarmMgr::closeEntry(*this); return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const OmnString &errMsg) { mErrMsg += errMsg; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const std::string &errMsg) { mErrMsg += errMsg; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const char *errmsg) { mErrMsg += errmsg; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u8 *msg) { return *this << (const char *)msg; } OmnAlarmEntry & OmnAlarmEntry::operator << (const int value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u8 value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u32 value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u64 value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const int64_t value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const double value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (void *ptr) { char buf[100]; sprintf(buf, "%ld", (unsigned long)ptr); mErrMsg += buf; return *this; } bool OmnAlarmEntry::toString( const int num_alarms, char *data, const int length) const { if (mErrorId == OmnErrId::eSynErr) { return toString_SynErr(num_alarms, data, length); } return toString_Alarm(num_alarms, data, length); } bool OmnAlarmEntry::toString_Alarm( const int num_alarms, char *data, const int length) const { // // Write the alarm in the following form: // // "\n\n<" // << OmnTime::getSecTick() // << "> ******* Alarm Entry **********" // "\nFile: " << mFile << // "\nLine: " << mLine << // "\nAlarm ID: " << mErrorId << // "\nSeqno: " << mAlarmSeqno << // "\nTrigger Thread ID: " << OmnGetCurrentThreadId() << // "\nTrigger Time: " << mTime << // "\nError Message: " << mErrMsg << // "\n*************************\n"; // // Note that we did not use OmnString in order not to generate any alarms // while converting this entry into a string. // OmnString addrs; if (!OmnAlarmMgr::isPrintFullBacktrace()) { void *buff[100]; int sizes = backtrace(buff, 100); char addrStr[100]; for(int i=0; i<sizes; i++) { sprintf(addrStr, "0x%lx", (u64)buff[i]); if (i == sizes - 1) addrs << addrStr << "\n"; else addrs << addrStr << " "; } } else { void *buff[100]; int sizes = backtrace(buff, 100); std::vector<string> tmps; OmnAlarmMgr::getBacktrace(tmps); if (sizes + 1 != tmps.size() || sizes <= 3) return false; char addrStr[100]; for (size_t i=3; i<tmps.size(); i++) { sprintf(addrStr, "0x%lx", (u64)buff[i-1]); addrs << "[" << (i - 3) << "] " << "[" << addrStr << "] " << tmps[i] << "\n"; } } addrs << "--------------------"; int index = 0; if (!addChar(data, length, index, "\n<")) return false; if (!addInt(data, length, index, OmnTime::getSecTick())) return false; OmnString aa = "> ***** Alarm Entry "; aa << mFile << ":" << mLine << ":" << num_alarms << " ******"; if (!addChar(data, length, index, aa.data())) return false; if (!addChar(data, length, index, "\nError Id: ")) return false; if (!addInt(data, length, index, mErrorId)) return false; if (!addChar(data, length, index, "\nSeqno: ")) return false; if (!addInt(data, length, index, mAlarmSeqno)) return false; if (!addChar(data, length, index, "\nTrigger Time: ")) return false; if (!addChar(data, length, index, mTime.data())) return false; if (!addChar(data, length, index, "\nStackAddr:-----------\n")) return false; if (!addChar(data, length, index, addrs.data())) return false; if (!addChar(data, length, index, "\nError Message: ")) return false; if (!addChar(data, length, index, mErrMsg.data())) return false; if (!addChar(data, length, index, "\n*************************\n")) return false; return true; } bool OmnAlarmEntry::toString_SynErr( const int num_alarms, char *data, const int length) const { // // Write the alarm in the following form: // // "\n\n<" // << OmnTime::getSecTick() // << "> [Syntax Error][File:Line]"<< // "\nTrigger Thread ID: " << OmnGetCurrentThreadId() << // "\nTrigger Time: " << mTime << // "\nError Message: " << mErrMsg << // "\n\n"; // // Note that we did not use OmnString in order not to generate any alarms // while converting this entry into a string. // int index = 0; if (!addChar(data, length, index, "\n\n<")) return false; if (!addInt(data, length, index, OmnTime::getSecTick())) return false; OmnString aa = "> [Syntax Error]["; aa << mFile << ":" << mLine << ":" << num_alarms << "]"; if (!addChar(data, length, index, aa.data())) return false; if (!addChar(data, length, index, "\nThread ID: ")) return false; if (!addIntHex(data, length, index, OmnGetCurrentThreadId())) return false; if (!addChar(data, length, index, "\nTrigger Time: ")) return false; if (!addChar(data, length, index, mTime.data())) return false; if (!addChar(data, length, index, "\nError Message: ")) return false; if (!addChar(data, length, index, mErrMsg.data())) return false; if (!addChar(data, length, index, "\n\n")) return false; return true; }
23.055762
82
0.60158
08d1fd930599baa672ee6d5a283414de9a4c8421
13,688
cxx
C++
Utilities/FltkImageViewer/fltkImage2DViewerWindow.cxx
clwyatt/CTC
284d52dc888bcd997214804715fe690149e33f85
[ "BSD-3-Clause" ]
1
2019-07-29T02:04:06.000Z
2019-07-29T02:04:06.000Z
Utilities/FltkImageViewer/fltkImage2DViewerWindow.cxx
clwyatt/CTC
284d52dc888bcd997214804715fe690149e33f85
[ "BSD-3-Clause" ]
null
null
null
Utilities/FltkImageViewer/fltkImage2DViewerWindow.cxx
clwyatt/CTC
284d52dc888bcd997214804715fe690149e33f85
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: fltkImage2DViewerWindow.cxx,v $ Language: C++ Date: $Date: 2002/10/15 15:16:54 $ Version: $Revision: 1.20 $ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "fltkImage2DViewerWindow.h" #include "fltkCommandEvents.h" #ifdef __APPLE__ #include <OpenGL/glu.h> #else #include <GL/glu.h> #endif #include <math.h> #include <FL/Fl.H> #include <FL/Fl_Menu_Button.H> namespace fltk { //------------------------------------------ // // Creator // //------------------------------------------ Image2DViewerWindow:: Image2DViewerWindow(int x,int y,int w,int h, const char * label) :GlWindow(x,y,w,h,label) { m_Background.SetRed( 0.5 ); m_Background.SetGreen( 0.5 ); m_Background.SetBlue( 0.5 ); m_Buffer = 0; m_ShiftX = 0; m_ShiftY = 0; m_Zoom = 1.0; m_NumberOfBytesPerPixel = 1; // change by 4 in case of RGBA m_Width = 0; m_Height = 0; m_SelectionCallBack = 0; m_ClickCallBack = 0; m_InteractionMode = SelectMode; } //------------------------------------------ // // Destructor // //------------------------------------------ Image2DViewerWindow ::~Image2DViewerWindow() { if( m_Buffer ) { delete [] m_Buffer; m_Buffer = 0; } } //------------------------------------------ // // Set Background Color // //------------------------------------------ void Image2DViewerWindow ::SetBackground( GLfloat r, GLfloat g, GLfloat b ) { m_Background.SetRed( r ); m_Background.SetGreen( g ); m_Background.SetBlue( b ); } //------------------------------------------ // // Set Background Color // //------------------------------------------ void Image2DViewerWindow ::SetBackground( const ColorType & newcolor ) { m_Background = newcolor; } //------------------------------------------ // // Get Background Color // //------------------------------------------ const Image2DViewerWindow::ColorType & Image2DViewerWindow ::GetBackground(void) const { return m_Background; } //------------------------------------------ // // Allocate // //------------------------------------------ void Image2DViewerWindow:: Allocate(unsigned int nx,unsigned int ny) { if( m_Buffer ) { delete [] m_Buffer; } this->size(nx,ny); m_Buffer = new unsigned char[ nx * ny * m_NumberOfBytesPerPixel ]; this->SetWidth( nx ); this->SetHeight( ny ); } //------------------------------------------ // // Update the display // //------------------------------------------ void Image2DViewerWindow ::Update(void) { this->redraw(); Fl::check(); } //------------------------------------------ // // Set Height // //------------------------------------------ void Image2DViewerWindow::SetHeight(unsigned int height) { m_Height = height; m_ShiftY = -m_Height; } //------------------------------------------ // // Set Width // //------------------------------------------ void Image2DViewerWindow::SetWidth(unsigned int width) { m_Width = width; m_ShiftX = -m_Width; } //------------------------------------------ // // Get Width // //------------------------------------------ unsigned int Image2DViewerWindow::GetWidth( void ) const { return m_Width; } //------------------------------------------ // // Get Height // //------------------------------------------ unsigned int Image2DViewerWindow::GetHeight( void ) const { return m_Height; } //------------------------------------------ // // Fit Image to Window // //------------------------------------------ void Image2DViewerWindow::FitImageToWindow(void) { m_Zoom = static_cast<GLdouble>( h() ) / static_cast<GLdouble>( m_Height ); m_ShiftY = -m_Height; m_ShiftX = -m_Width; this->redraw(); Fl::check(); } //------------------------------------------ // // Fit Window to Image // //------------------------------------------ void Image2DViewerWindow::FitWindowToImage(void) { m_Zoom = 1.0; m_ShiftX = -m_Width; m_ShiftY = -m_Height; m_ParentWindow->size( m_Width, m_Height ); } //------------------------------------------ // // Draw Scene // //------------------------------------------ void Image2DViewerWindow::draw(void) { if( !m_Buffer) { return; } if( !visible_r() ) { return; } if(!valid()) { glViewport( 0, 0, m_Width, m_Height ); glClearColor( m_Background.GetRed(), m_Background.GetGreen(), m_Background.GetBlue(), 1.0); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); } glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); const GLdouble width = static_cast<GLdouble>( m_Width ); const GLdouble height = static_cast<GLdouble>( m_Height ); // glOrtho( -width, width, -height, height, -20000, 10000 ); gluOrtho2D( -width, width, -height, height ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, m_Width ); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 ); glRasterPos2i( m_ShiftX, m_ShiftY ) ; glPixelZoom( m_Zoom, m_Zoom ); if( m_InteractionMode == SelectMode ) { // drawing selection box begin int X1 = m_Box.X1 * 2 + m_ShiftX ; int X2 = m_Box.X2 * 2 + m_ShiftX ; int Y1 = -(m_Box.Y1 * 2 + m_ShiftY) ; int Y2 = -(m_Box.Y2 * 2 + m_ShiftY) ; if (Y2 >= m_Height - 2 ) { Y2 = m_Height - 2 ; } glBegin(GL_LINE_STRIP); glVertex2i(X1, Y1) ; glVertex2i(X2, Y1) ; glVertex2i(X2, Y2) ; glVertex2i(X1, Y2) ; glVertex2i(X1, Y1) ; glEnd(); // end } glDrawPixels( m_Width, m_Height, GL_LUMINANCE, GL_UNSIGNED_BYTE, static_cast<void *>(m_Buffer) ); // // Prepare for drawing other objects // glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_LIGHT2); GLfloat diffuse1[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat diffuse2[] = { 0.5f, 0.5f, 0.5f, 1.0f }; GLfloat diffuse3[] = { 0.5f, 0.5f, 0.5f, 1.0f }; glLightfv(GL_LIGHT0,GL_DIFFUSE,diffuse1); glLightfv(GL_LIGHT1,GL_DIFFUSE,diffuse2); glLightfv(GL_LIGHT2,GL_DIFFUSE,diffuse3); GLfloat position_0[] = { 200.0, 200.0, 200.0, 0.0}; glLightfv(GL_LIGHT0,GL_POSITION,position_0); GLfloat position_1[] = {-200.0, 0.0, -100.0, 0.0}; glLightfv(GL_LIGHT1,GL_POSITION,position_1); GLfloat position_2[] = { 0.0,-200.0, -100.0, 0.0}; glLightfv(GL_LIGHT2,GL_POSITION,position_2); glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); // Call other drawers GetNotifier()->InvokeEvent( fltk::GlDrawEvent() ); } //------------------------------------------ // // Set Intensity Window // //------------------------------------------ void Image2DViewerWindow ::SetIntensityWindow( Fl_Window * window ) { m_IntensityWindow = window; } //------------------------------------------ // // Set Parent Window // //------------------------------------------ void Image2DViewerWindow ::SetParentWindow( Fl_Window * window ) { m_ParentWindow = window; } //------------------------------------------ // // Intensity Windowing // //------------------------------------------ void Image2DViewerWindow ::IntensityWindowing(void) { m_IntensityWindow->show(); } //------------------------------------------ // // Event Handling // //------------------------------------------ void Image2DViewerWindow ::handlePopUpMenu(void) { static Fl_Menu_Button * popupMenu = 0; // need to keep the shift of the first popup creation for redrawing purpose static unsigned int popupShift=0; if( !popupMenu ) { popupMenu = new Fl_Menu_Button(m_ParentWindow->x()+Fl::event_x(), m_ParentWindow->y()-(m_ParentWindow->h()/2)+Fl::event_y(), 100,200); popupShift = (m_ParentWindow->h()/2); //by using this function this seems to disable position() function (FTLK bug) //popupMenu->type( Fl_Menu_Button::POPUP3); popupMenu->add("Fit Image To Window"); popupMenu->add("Fit Window To Image"); popupMenu->add("Intensity Windowing"); } else { popupMenu->position(m_ParentWindow->x()+Fl::event_x(),m_ParentWindow->y()-popupShift+Fl::event_y()); } typedef enum { FIT_IMAGE_TO_WINDOW, FIT_WINDOW_TO_IMAGE, INTENSITY_WINDOWING } PopupMenuOptions; popupMenu->popup(); switch( popupMenu->value() ) { case FIT_WINDOW_TO_IMAGE: this->FitWindowToImage(); break; case FIT_IMAGE_TO_WINDOW: this->FitImageToWindow(); break; case INTENSITY_WINDOWING: this->IntensityWindowing(); break; } } //------------------------------------------ // // Event Handling // //------------------------------------------ int Image2DViewerWindow ::handle(int event) { static int p1x = 0; static int p1y = 0; switch( event ) { case FL_PUSH: { const int state = Fl::event_state(); if( state & FL_BUTTON1 ) { p1x = Fl::event_x(); p1y = Fl::event_y(); switch( m_InteractionMode ) { case PanningMode: break; case SelectMode: break; case ClickMode: ClickEventHandling( p1x, p1y ); break; case ZoomingMode: break; } } else if( state & FL_BUTTON2 ) { } else if( state & FL_BUTTON3 ) { handlePopUpMenu(); } return 1; } case FL_RELEASE: return 1; case FL_DRAG: { const int state = Fl::event_state(); if( state == FL_BUTTON1 ) { switch( m_InteractionMode ) { case PanningMode: PanningEventHandling( p1x, p1y ); break; case SelectMode: SelectEventHandling( p1x, p1y ); break; case ClickMode: break; case ZoomingMode: break; } } else if (state == FL_BUTTON2 ) { ZoomingEventHandling( p1x, p1y ); } return 1; } } return 0; } //------------------------------------------ // // Panning Event Handling // //------------------------------------------ void Image2DViewerWindow ::PanningEventHandling(int & p1x, int & p1y) { int p2x = Fl::event_x(); int p2y = Fl::event_y(); const int dx = p2x - p1x; const int dy = p2y - p1y; m_ShiftX += dx; m_ShiftY -= dy; // Mouse Y -> - OpenGl Y p1x = p2x; p1y = p2y; redraw(); Fl::check(); } void Image2DViewerWindow ::SetSelectionBox(SelectionBoxType* box) { m_Box.X1 = box->X1 ; m_Box.Y1 = box->Y1 ; m_Box.X2 = box->X2 ; m_Box.Y2 = box->Y2 ; redraw(); Fl::check(); } void Image2DViewerWindow ::SetSelectionCallBack(void* ptrObject, void (*selectionCallBack)(void* ptrObject, SelectionBoxType* box)) { m_SelectionCallBackTargetObject = ptrObject ; m_SelectionCallBack = selectionCallBack ; } void Image2DViewerWindow ::SetClickCallBack(void* ptrObject, void (*clickCallBack)(void* ptrObject, int & px, int & py )) { m_ClickCallBackTargetObject = ptrObject ; m_ClickCallBack = clickCallBack ; } //------------------------------------------ // // Click Event Handling // //------------------------------------------ void Image2DViewerWindow ::ClickEventHandling(int & px, int & py) { if (m_ClickCallBack != 0) { m_ClickCallBack( m_ClickCallBackTargetObject, px, py ) ; } redraw(); Fl::check(); } //------------------------------------------ // // Select Event Handling // //------------------------------------------ void Image2DViewerWindow ::SelectEventHandling(int & p1x, int & p1y) { int p2x = Fl::event_x(); int p2y = Fl::event_y(); if (p2x >= m_Width) { p2x = m_Width - 1 ; } if (p2x <= 0) { p2x = 0 ; } if (p2y >= m_Height) { p2y = m_Height ; } if (p2y <= 0 ) { p2y = 0 ; } m_Box.X1 = p1x ; m_Box.X2 = p2x ; m_Box.Y1 = p1y ; m_Box.Y2 = p2y ; if (m_SelectionCallBack != 0) { m_SelectionCallBack(m_SelectionCallBackTargetObject, &m_Box) ; } redraw(); Fl::check(); } //------------------------------------------ // // Zooming Event Handling // //------------------------------------------ void Image2DViewerWindow ::ZoomingEventHandling(int & p1x, int & p1y) { int p2x = Fl::event_x(); int p2y = Fl::event_y(); const int dx = p2x - p1x; const int dy = p2y - p1y; m_ShiftX += dx; m_ShiftY -= dy; // Mouse Y -> - OpenGl Y p1x = p2x; p1y = p2y; redraw(); Fl::check(); } //------------------------------------------ // // Select Interaction Mode // //------------------------------------------ void Image2DViewerWindow ::SetInteractionMode( InteractionModeType mode ) { m_InteractionMode = mode; } } // end namespace fltk
19.064067
104
0.502192
08d5a67101b5f6c210a2b2213e641905cf404ba9
573
hpp
C++
Chip8lib/font/fontLoader.hpp
tstibro/chip8
fa342b8641737780e20b259f6df9dcb51127786a
[ "MIT" ]
null
null
null
Chip8lib/font/fontLoader.hpp
tstibro/chip8
fa342b8641737780e20b259f6df9dcb51127786a
[ "MIT" ]
null
null
null
Chip8lib/font/fontLoader.hpp
tstibro/chip8
fa342b8641737780e20b259f6df9dcb51127786a
[ "MIT" ]
null
null
null
/* * fontLoader.hpp * * Created on: Jul 23, 2016 * Author: Tomas Stibrany */ #ifndef FONT_FONTLOADER_HPP_ #define FONT_FONTLOADER_HPP_ #include "../chip8Types.hpp" namespace chip8 { namespace core { namespace memory { class RAM; } } } namespace chip8 { namespace font { class Font; } } using namespace chip8::core::memory; using namespace chip8::font; namespace chip8 { namespace font { class FontLoader { private: public: FontLoader(); ~FontLoader(); void LoadTo(RAM *ram, Font *font); }; }} #endif /* FONT_FONTLOADER_HPP_ */
12.191489
36
0.670157
08d8c404b313187f4ba38d65810ce2ceb01a6c07
15,151
cc
C++
chrome/browser/ui/pdf/pdf_unsupported_feature.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
7
2015-05-20T22:41:35.000Z
2021-11-18T19:07:59.000Z
chrome/browser/ui/pdf/pdf_unsupported_feature.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
1
2015-02-02T06:55:08.000Z
2016-01-20T06:11:59.000Z
chrome/browser/ui/pdf/pdf_unsupported_feature.cc
Crystalnix/BitPop
1fae4ecfb965e163f6ce154b3988b3181678742a
[ "BSD-3-Clause" ]
2
2015-12-08T00:37:41.000Z
2017-04-06T05:34:05.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/pdf/pdf_unsupported_feature.h" #include "base/bind.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/version.h" #include "chrome/browser/chrome_plugin_service_filter.h" #include "chrome/browser/infobars/infobar_tab_helper.h" #include "chrome/browser/plugin_prefs.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_preferences_util.h" #include "chrome/browser/tab_contents/confirm_infobar_delegate.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/pref_names.h" #include "content/public/browser/interstitial_page.h" #include "content/public/browser/interstitial_page_delegate.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/user_metrics.h" #include "content/public/browser/web_contents.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "webkit/plugins/npapi/plugin_group.h" #if defined(ENABLE_PLUGIN_INSTALLATION) #include "chrome/browser/plugin_finder.h" #include "chrome/browser/plugin_installer.h" #else // Forward-declare PluginFinder. It's never actually used, but we pass a NULL // pointer instead. class PluginFinder; #endif using content::InterstitialPage; using content::OpenURLParams; using content::PluginService; using content::Referrer; using content::UserMetricsAction; using content::WebContents; using webkit::npapi::PluginGroup; using webkit::WebPluginInfo; namespace { static const char kReaderUpdateUrl[] = "http://www.adobe.com/go/getreader_chrome"; // The info bar delegate used to ask the user if they want to use Adobe Reader // by default. We want the infobar to have [No][Yes], so we swap the text on // the buttons, and the meaning of the delegate callbacks. class PDFEnableAdobeReaderInfoBarDelegate : public ConfirmInfoBarDelegate { public: explicit PDFEnableAdobeReaderInfoBarDelegate( InfoBarTabHelper* infobar_helper, Profile* profile); virtual ~PDFEnableAdobeReaderInfoBarDelegate(); // ConfirmInfoBarDelegate virtual void InfoBarDismissed() OVERRIDE; virtual Type GetInfoBarType() const OVERRIDE; virtual bool Accept() OVERRIDE; virtual bool Cancel() OVERRIDE; virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE; virtual string16 GetMessageText() const OVERRIDE; private: void OnYes(); void OnNo(); Profile* profile_; DISALLOW_IMPLICIT_CONSTRUCTORS(PDFEnableAdobeReaderInfoBarDelegate); }; PDFEnableAdobeReaderInfoBarDelegate::PDFEnableAdobeReaderInfoBarDelegate( InfoBarTabHelper* infobar_helper, Profile* profile) : ConfirmInfoBarDelegate(infobar_helper), profile_(profile) { content::RecordAction(UserMetricsAction("PDF_EnableReaderInfoBarShown")); } PDFEnableAdobeReaderInfoBarDelegate::~PDFEnableAdobeReaderInfoBarDelegate() { } void PDFEnableAdobeReaderInfoBarDelegate::InfoBarDismissed() { OnNo(); } InfoBarDelegate::Type PDFEnableAdobeReaderInfoBarDelegate::GetInfoBarType() const { return PAGE_ACTION_TYPE; } bool PDFEnableAdobeReaderInfoBarDelegate::Accept() { profile_->GetPrefs()->SetBoolean( prefs::kPluginsShowSetReaderDefaultInfobar, false); OnNo(); return true; } bool PDFEnableAdobeReaderInfoBarDelegate::Cancel() { OnYes(); return true; } string16 PDFEnableAdobeReaderInfoBarDelegate::GetButtonLabel( InfoBarButton button) const { return l10n_util::GetStringUTF16((button == BUTTON_OK) ? IDS_PDF_INFOBAR_NEVER_USE_READER_BUTTON : IDS_PDF_INFOBAR_ALWAYS_USE_READER_BUTTON); } string16 PDFEnableAdobeReaderInfoBarDelegate::GetMessageText() const { return l10n_util::GetStringUTF16(IDS_PDF_INFOBAR_QUESTION_ALWAYS_USE_READER); } void PDFEnableAdobeReaderInfoBarDelegate::OnYes() { content::RecordAction(UserMetricsAction("PDF_EnableReaderInfoBarOK")); PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(profile_); plugin_prefs->EnablePluginGroup( true, ASCIIToUTF16(webkit::npapi::PluginGroup::kAdobeReaderGroupName)); plugin_prefs->EnablePluginGroup( false, ASCIIToUTF16(chrome::ChromeContentClient::kPDFPluginName)); } void PDFEnableAdobeReaderInfoBarDelegate::OnNo() { content::RecordAction(UserMetricsAction("PDF_EnableReaderInfoBarCancel")); } // Launch the url to get the latest Adbobe Reader installer. void OpenReaderUpdateURL(WebContents* tab) { OpenURLParams params( GURL(kReaderUpdateUrl), Referrer(), NEW_FOREGROUND_TAB, content::PAGE_TRANSITION_LINK, false); tab->OpenURL(params); } // Opens the PDF using Adobe Reader. void OpenUsingReader(TabContents* tab, const WebPluginInfo& reader_plugin, InfoBarDelegate* old_delegate, InfoBarDelegate* new_delegate) { ChromePluginServiceFilter::GetInstance()->OverridePluginForTab( tab->web_contents()->GetRenderProcessHost()->GetID(), tab->web_contents()->GetRenderViewHost()->GetRoutingID(), tab->web_contents()->GetURL(), ASCIIToUTF16(PluginGroup::kAdobeReaderGroupName)); tab->web_contents()->GetRenderViewHost()->ReloadFrame(); if (new_delegate) { if (old_delegate) { tab->infobar_tab_helper()->ReplaceInfoBar(old_delegate, new_delegate); } else { tab->infobar_tab_helper()->AddInfoBar(new_delegate); } } } // An interstitial to be used when the user chooses to open a PDF using Adobe // Reader, but it is out of date. class PDFUnsupportedFeatureInterstitial : public content::InterstitialPageDelegate { public: PDFUnsupportedFeatureInterstitial( TabContents* tab, const WebPluginInfo& reader_webplugininfo) : tab_contents_(tab), reader_webplugininfo_(reader_webplugininfo) { content::RecordAction(UserMetricsAction("PDF_ReaderInterstitialShown")); interstitial_page_ = InterstitialPage::Create( tab->web_contents(), false, tab->web_contents()->GetURL(), this); interstitial_page_->Show(); } protected: // InterstitialPageDelegate implementation. virtual std::string GetHTMLContents() OVERRIDE { DictionaryValue strings; strings.SetString( "title", l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_TITLE)); strings.SetString( "headLine", l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_BODY)); strings.SetString( "update", l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_UPDATE)); strings.SetString( "open_with_reader", l10n_util::GetStringUTF16( IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_PROCEED)); strings.SetString( "ok", l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_OK)); strings.SetString( "cancel", l10n_util::GetStringUTF16(IDS_READER_OUT_OF_DATE_BLOCKING_PAGE_CANCEL)); base::StringPiece html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_READER_OUT_OF_DATE_HTML, ui::SCALE_FACTOR_NONE)); return jstemplate_builder::GetI18nTemplateHtml(html, &strings); } virtual void CommandReceived(const std::string& command) OVERRIDE { if (command == "0") { content::RecordAction( UserMetricsAction("PDF_ReaderInterstitialCancel")); interstitial_page_->DontProceed(); return; } if (command == "1") { content::RecordAction( UserMetricsAction("PDF_ReaderInterstitialUpdate")); OpenReaderUpdateURL(tab_contents_->web_contents()); } else if (command == "2") { content::RecordAction( UserMetricsAction("PDF_ReaderInterstitialIgnore")); OpenUsingReader(tab_contents_, reader_webplugininfo_, NULL, NULL); } else { NOTREACHED(); } interstitial_page_->Proceed(); } virtual void OverrideRendererPrefs( content::RendererPreferences* prefs) OVERRIDE { renderer_preferences_util::UpdateFromSystemSettings( prefs, tab_contents_->profile()); } private: TabContents* tab_contents_; WebPluginInfo reader_webplugininfo_; InterstitialPage* interstitial_page_; // Owns us. DISALLOW_COPY_AND_ASSIGN(PDFUnsupportedFeatureInterstitial); }; // The info bar delegate used to inform the user that we don't support a feature // in the PDF. See the comment about how we swap buttons for // PDFEnableAdobeReaderInfoBarDelegate. class PDFUnsupportedFeatureInfoBarDelegate : public ConfirmInfoBarDelegate { public: // |reader| is NULL if Adobe Reader isn't installed. PDFUnsupportedFeatureInfoBarDelegate(TabContents* tab_contents, const webkit::WebPluginInfo* reader, PluginFinder* plugin_finder); virtual ~PDFUnsupportedFeatureInfoBarDelegate(); // ConfirmInfoBarDelegate virtual void InfoBarDismissed() OVERRIDE; virtual gfx::Image* GetIcon() const OVERRIDE; virtual Type GetInfoBarType() const OVERRIDE; virtual bool Accept() OVERRIDE; virtual bool Cancel() OVERRIDE; virtual string16 GetButtonLabel(InfoBarButton button) const OVERRIDE; virtual string16 GetMessageText() const OVERRIDE; private: bool OnYes(); void OnNo(); TabContents* tab_contents_; bool reader_installed_; bool reader_vulnerable_; WebPluginInfo reader_webplugininfo_; DISALLOW_IMPLICIT_CONSTRUCTORS(PDFUnsupportedFeatureInfoBarDelegate); }; PDFUnsupportedFeatureInfoBarDelegate::PDFUnsupportedFeatureInfoBarDelegate( TabContents* tab_contents, const webkit::WebPluginInfo* reader, PluginFinder* plugin_finder) : ConfirmInfoBarDelegate(tab_contents->infobar_tab_helper()), tab_contents_(tab_contents), reader_installed_(!!reader), reader_vulnerable_(false) { if (!reader_installed_) { content::RecordAction( UserMetricsAction("PDF_InstallReaderInfoBarShown")); return; } content::RecordAction(UserMetricsAction("PDF_UseReaderInfoBarShown")); reader_webplugininfo_ = *reader; #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller* installer = plugin_finder->FindPluginWithIdentifier("adobe-reader"); reader_vulnerable_ = installer->GetSecurityStatus(*reader) != PluginInstaller::SECURITY_STATUS_UP_TO_DATE; #else NOTREACHED(); #endif } PDFUnsupportedFeatureInfoBarDelegate::~PDFUnsupportedFeatureInfoBarDelegate() { } void PDFUnsupportedFeatureInfoBarDelegate::InfoBarDismissed() { OnNo(); } gfx::Image* PDFUnsupportedFeatureInfoBarDelegate::GetIcon() const { return &ResourceBundle::GetSharedInstance().GetNativeImageNamed( IDR_INFOBAR_INCOMPLETE); } InfoBarDelegate::Type PDFUnsupportedFeatureInfoBarDelegate::GetInfoBarType() const { return PAGE_ACTION_TYPE; } bool PDFUnsupportedFeatureInfoBarDelegate::Accept() { OnNo(); return true; } bool PDFUnsupportedFeatureInfoBarDelegate::Cancel() { return OnYes(); } string16 PDFUnsupportedFeatureInfoBarDelegate::GetButtonLabel( InfoBarButton button) const { return l10n_util::GetStringUTF16((button == BUTTON_OK) ? IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL : IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL); } string16 PDFUnsupportedFeatureInfoBarDelegate::GetMessageText() const { return l10n_util::GetStringUTF16(reader_installed_ ? IDS_PDF_INFOBAR_QUESTION_READER_INSTALLED : IDS_PDF_INFOBAR_QUESTION_READER_NOT_INSTALLED); } bool PDFUnsupportedFeatureInfoBarDelegate::OnYes() { if (!reader_installed_) { content::RecordAction(UserMetricsAction("PDF_InstallReaderInfoBarOK")); OpenReaderUpdateURL(tab_contents_->web_contents()); return true; } content::RecordAction(UserMetricsAction("PDF_UseReaderInfoBarOK")); if (reader_vulnerable_) { new PDFUnsupportedFeatureInterstitial(tab_contents_, reader_webplugininfo_); return true; } if (tab_contents_->profile()->GetPrefs()->GetBoolean( prefs::kPluginsShowSetReaderDefaultInfobar)) { InfoBarDelegate* bar = new PDFEnableAdobeReaderInfoBarDelegate( tab_contents_->infobar_tab_helper(), tab_contents_->profile()); OpenUsingReader(tab_contents_, reader_webplugininfo_, this, bar); return false; } OpenUsingReader(tab_contents_, reader_webplugininfo_, NULL, NULL); return true; } void PDFUnsupportedFeatureInfoBarDelegate::OnNo() { content::RecordAction(reader_installed_ ? UserMetricsAction("PDF_UseReaderInfoBarCancel") : UserMetricsAction("PDF_InstallReaderInfoBarCancel")); } void GotPluginGroupsCallback(int process_id, int routing_id, PluginFinder* plugin_finder, const std::vector<PluginGroup>& groups) { WebContents* web_contents = tab_util::GetWebContentsByID(process_id, routing_id); if (!web_contents) return; TabContents* tab = TabContents::FromWebContents(web_contents); if (!tab) return; string16 reader_group_name(ASCIIToUTF16(PluginGroup::kAdobeReaderGroupName)); // If the Reader plugin is disabled by policy, don't prompt them. PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(tab->profile()); if (plugin_prefs->PolicyStatusForPlugin(reader_group_name) == PluginPrefs::POLICY_DISABLED) { return; } const webkit::WebPluginInfo* reader = NULL; for (size_t i = 0; i < groups.size(); ++i) { if (groups[i].GetGroupName() == reader_group_name) { const std::vector<WebPluginInfo>& plugins = groups[i].web_plugin_infos(); DCHECK_EQ(plugins.size(), 1u); reader = &plugins[0]; break; } } tab->infobar_tab_helper()->AddInfoBar( new PDFUnsupportedFeatureInfoBarDelegate(tab, reader, plugin_finder)); } void GotPluginFinderCallback(int process_id, int routing_id, PluginFinder* plugin_finder) { PluginService::GetInstance()->GetPluginGroups( base::Bind(&GotPluginGroupsCallback, process_id, routing_id, base::Unretained(plugin_finder))); } } // namespace void PDFHasUnsupportedFeature(TabContents* tab) { #if defined(OS_WIN) && defined(ENABLE_PLUGIN_INSTALLATION) // Only works for Windows for now. For Mac, we'll have to launch the file // externally since Adobe Reader doesn't work inside Chrome. PluginFinder::Get(base::Bind(&GotPluginFinderCallback, tab->web_contents()->GetRenderProcessHost()->GetID(), tab->web_contents()->GetRenderViewHost()->GetRoutingID())); #endif }
34.200903
80
0.744901
08d93b6b65eb7e4504db0d0a455eadfdd06ad947
1,897
hpp
C++
unittests/data/temporary_variable_to_be_exported.hpp
electronicvisions/pyplusplus
4d88bb8754d22654a61202ae8adc222807953e38
[ "BSL-1.0" ]
9
2016-06-07T19:14:53.000Z
2020-02-28T09:06:19.000Z
unittests/data/temporary_variable_to_be_exported.hpp
electronicvisions/pyplusplus
4d88bb8754d22654a61202ae8adc222807953e38
[ "BSL-1.0" ]
1
2018-08-15T11:33:40.000Z
2018-08-15T11:33:40.000Z
unittests/data/temporary_variable_to_be_exported.hpp
electronicvisions/pyplusplus
4d88bb8754d22654a61202ae8adc222807953e38
[ "BSL-1.0" ]
5
2016-06-23T09:37:00.000Z
2019-12-18T13:51:29.000Z
// Copyright 2004-2008 Roman Yakovenko. // 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) #ifndef __temporary_variable_to_be_exported_hpp__ #define __temporary_variable_to_be_exported_hpp__ #include <string> namespace temporary_variables{ struct named_item_t{ named_item_t() : m_name( "no name" ) {} virtual const std::string& name() const { return m_name; } private: std::string m_name; }; const std::string& get_name( const named_item_t& ni ){ return ni.name(); } struct pure_virtual_t{ virtual const std::string& name() const = 0; virtual std::string& name_ref() = 0; }; const std::string& get_name( const pure_virtual_t& ni ){ return ni.name(); } std::string& get_name_ref( pure_virtual_t& ni ){ return ni.name_ref(); } struct virtual_t{ virtual_t() : m_name( "no name" ){} virtual const std::string& name() const { return m_name; } virtual std::string& name_ref() { return m_name; } protected: virtual const std::string& name_protected() const { return m_name; } private: virtual const std::string& name_private() const { return m_name; } public: std::string m_name; }; struct virtual2_t{ virtual2_t() : m_name( "no name" ){} protected: virtual const std::string& name_protected_pure() const = 0; virtual const std::string& name_protected() const { return m_name; } private: virtual const std::string& name_private_pure() const = 0; virtual const std::string& name_private() const { return m_name; } public: std::string m_name; }; const std::string& get_name( const virtual_t& ni ){ return ni.name(); } std::string& get_name_ref( virtual_t& ni ){ return ni.name_ref(); } } #endif//__temporary_variable_to_be_exported_hpp__
20.846154
72
0.680548
08df8e684b33864a1b60ea7bd33b533968ba656f
20,057
ipp
C++
include/External/stlib/packages/cpt/Face3.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/cpt/Face3.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/cpt/Face3.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #if !defined(__cpt_Face3_ipp__) #error This file is an implementation detail of the class Face. #endif namespace cpt { //! A 3-D face on a b-rep. template<typename T> class Face<3, T> { public: // // Public types. // //! The number type. typedef T Number; //! A Cartesian point. typedef std::tr1::array<Number, 3> Point; //! An indexed edge polyhedron type. typedef geom::IndexedEdgePolyhedron<Number> Polyhedron; private: //! The representation of a plane in 3 dimensions. typedef geom::Plane<Number> Plane; private: // // Member Data // //! The three vertices of the face. std::tr1::array<Point, 3> _vertices; //! The supporting plane of the face. Plane _supportingPlane; /*! The three planes which are incident on the three edges and orthogonal to the face. These planes have inward pointing normals. */ std::tr1::array<Plane, 3> _sides; //! The index of this face. std::size_t _index; //! An epsilon that is appropriate for the edge lengths. Number _epsilon; public: //------------------------------------------------------------------------- //! \name Constructors, etc. //@{ //! Default constructor. Unititialized memory. Face() : _vertices(), _supportingPlane(), _sides(), _index(), _epsilon() {} //! Construct a face from three vertices, a normal and the face index. Face(const Point& vertex1, const Point& vertex2, const Point& vertex3, const Point& normal, const std::size_t index) { make(vertex1, vertex2, vertex3, normal, index); } //! Copy constructor. Face(const Face& other) : _vertices(other._vertices), _supportingPlane(other._supportingPlane), _sides(other._sides), _index(other._index), _epsilon(other._epsilon) {} //! Assignment operator. Face& operator=(const Face& other); //! Make a face from three vertices, a normal and the face index. void make(const Point& vertex1, const Point& vertex2, const Point& vertex3, const Point& normal, const std::size_t index); //! Trivial destructor. ~Face() {} //@} //------------------------------------------------------------------------- //! \name Accessors. //@{ //! Return the vertices. const std::tr1::array<Point, 3>& getVertices() const { return _vertices; } //! Return the face. const Plane& getSupportingPlane() const { return _supportingPlane; } //! Return the sides. const std::tr1::array<Plane, 3>& getSides() const { return _sides; } //! Return the normal to the face. const Point& getNormal() const { return _supportingPlane.getNormal(); } //! Return the i_th side normal. const Point& getSideNormal(const std::size_t i) const { return _sides[i].getNormal(); } //! Return the index of this face in the b-rep. std::size_t getFaceIndex() const { return _index; } //@} //------------------------------------------------------------------------- //! \name Mathematical operations. //@{ //! Return true if the face is valid. bool isValid() const; //! Return the signed distance to the supporting plane of the face. Number computeDistance(const Point& p) const { return _supportingPlane.computeSignedDistance(p); } //! Compute distance with checking. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeDistanceChecked(const Point& p) const; //! Return the unsigned distance to the supporting plane of the face. Number computeDistanceUnsigned(const Point& p) const { return std::abs(computeDistance(p)); } //! Return the unsigned distance to the face. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeDistanceUnsignedChecked(const Point& p) const { return std::abs(computeDistanceChecked(p)); } //! Return the distance and find the closest point. Number computeClosestPoint(const Point& p, Point* cp) const { return _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp); } //! Return the distance and find the closest point. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointChecked(const Point& p, Point* cp) const; //! Return the unsigned distance and find the closest point. Number computeClosestPointUnsigned(const Point& p, Point* cp) const { return std::abs(computeClosestPoint(p, cp)); } //! Return the unsigned distance and find the closest point. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointUnsignedChecked(const Point& p, Point* cp) const { return std::abs(computeClosestPointChecked(p, cp)); } //! Return the distance and find the gradient of the distance. Number computeGradient(const Point& p, Point* grad) const; //! Return the distance and find the gradient of the distance. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeGradientChecked(const Point& p, Point* grad) const; //! Return the unsigned distance and find the gradient of the unsigned distance. Number computeGradientUnsigned(const Point& p, Point* grad) const; //! Return the unsigned distance and find the gradient of the unsigned distance. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeGradientUnsignedChecked(const Point& p, Point* grad) const; //! Return the distance and find the closest point and gradient of distance Number computeClosestPointAndGradient(const Point& p, Point* cp, Point* grad) const; //! Return the distance and find the closest point and gradient of distance /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointAndGradientChecked(const Point& p, Point* cp, Point* grad) const; //! Return the distance and find the closest point and gradient of distance Number computeClosestPointAndGradientUnsigned(const Point& p, Point* cp, Point* grad) const; //! Return the distance and find the closest point and gradient of distance /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointAndGradientUnsignedChecked(const Point& p, Point* cp, Point* grad) const; //! Make the characteristic polyhedron containing the closest points. /*! The face is a triangle. Consider the larger triangle made by moving the sides outward by delta. Make a triangular prizm of height, 2 * height, with the given triangle at its center. */ void buildCharacteristicPolyhedron(Polyhedron* polyhedron, const Number height) const; //@} private: //! Return true if the point is within delta of being inside the prizm of closest points bool isInside(const Point& p, const Number delta) const { return (_sides[0].computeSignedDistance(p) >= - delta && _sides[1].computeSignedDistance(p) >= - delta && _sides[2].computeSignedDistance(p) >= - delta); } //! Return true if the point is (close to being) inside the prizm of closest points bool isInside(const Point& p) const { return isInside(p, _epsilon); } }; // // Assignment operator. // template<typename T> inline Face<3, T>& Face<3, T>:: operator=(const Face& other) { // Avoid assignment to self if (&other != this) { _vertices = other._vertices; _supportingPlane = other._supportingPlane; _sides = other._sides; _index = other._index; _epsilon = other._epsilon; } // Return *this so assignments can chain return *this; } // // Make. // template<typename T> inline void Face<3, T>:: make(const Point& a, const Point& b, const Point& c, const Point& nm, const std::size_t index) { // The three vertices comprising the face. _vertices[0] = a; _vertices[1] = b; _vertices[2] = c; // Make the face plane from a point and the normal. _supportingPlane = Plane(a, nm); // Make the sides of the prizm from three points each. _sides[0] = Plane(b, a, a + _supportingPlane.getNormal()); _sides[1] = Plane(c, b, b + _supportingPlane.getNormal()); _sides[2] = Plane(a, c, c + _supportingPlane.getNormal()); // The index of this face. _index = index; // An appropriate epsilon for this face. max_length * sqrt(eps) _epsilon = std::sqrt(ads::max(squaredDistance(a, b), squaredDistance(b, c), squaredDistance(c, a)) * std::numeric_limits<Number>::epsilon()); } // // Mathematical Operations // template<typename T> inline bool Face<3, T>:: isValid() const { // Check the plane of the face. if (! _supportingPlane.isValid()) { return false; } // Check the planes of the sides. for (std::size_t i = 0; i < 3; ++i) { if (! _sides[i].isValid()) { return false; } } // Check that the normal points in the correct direction. const Number eps = 10 * std::numeric_limits<Number>::epsilon(); if (std::abs(dot(_supportingPlane.getNormal(), _vertices[0] - _vertices[1])) > eps || std::abs(dot(_supportingPlane.getNormal(), _vertices[1] - _vertices[2])) > eps || std::abs(dot(_supportingPlane.getNormal(), _vertices[2] - _vertices[0])) > eps) { return false; } // Check that the side normals point in the correct direction. if (std::abs(dot(_supportingPlane.getNormal(), _sides[0].getNormal())) > eps || std::abs(dot(_supportingPlane.getNormal(), _sides[1].getNormal())) > eps || std::abs(dot(_supportingPlane.getNormal(), _sides[2].getNormal())) > eps) { return false; } if (std::abs(dot(_sides[0].getNormal(), _vertices[0] - _vertices[1])) > eps || std::abs(dot(_sides[1].getNormal(), _vertices[1] - _vertices[2])) > eps || std::abs(dot(_sides[2].getNormal(), _vertices[2] - _vertices[0])) > eps) { return false; } return true; } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeDistanceChecked(const Point& p) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance. return computeDistance(p); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointChecked(const Point& p, Point* cp) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance and closest point to the supporting plane // of the face. return computeClosestPoint(p, cp); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradient(const Point& p, Point* grad) const { *grad = getNormal(); return _supportingPlane.computeSignedDistance(p); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradientChecked(const Point& p, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance and gradient. return computeGradient(p, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradientUnsigned(const Point& p, Point* grad) const { const Number signedDistance = _supportingPlane.computeSignedDistance(p); *grad = getNormal(); if (signedDistance < 0) { negateElements(grad); } return std::abs(signedDistance); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradientUnsignedChecked(const Point& p, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance and gradient. return computeGradientUnsigned(p, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradient(const Point& p, Point* cp, Point* grad) const { *grad = getNormal(); return _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradientChecked(const Point& p, Point* cp, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance, closest point, and gradient. return computeClosestPointAndGradient(p, cp, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradientUnsigned(const Point& p, Point* cp, Point* grad) const { Number signedDistance = _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp); *grad = getNormal(); if (signedDistance < 0) { negateElements(grad); } return std::abs(signedDistance); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradientUnsignedChecked(const Point& p, Point* cp, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance, closest point, and gradient. return computeClosestPointAndGradientUnsigned(p, cp, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } // Utility Function. // Offset of a point so that the sides with normals n1 and n2 are moved // a distance of delta. template<typename T> std::tr1::array<T, 3> offsetOutward(const std::tr1::array<T, 3>& n1, const std::tr1::array<T, 3>& n2, const T delta) { std::tr1::array<T, 3> outward(n1 + n2); normalize(&outward); T den = dot(outward, n1); if (den != 0) { return (outward *(delta / den)); } return ext::make_array<T>(0, 0, 0); } /* The face is a triangle. Consider the larger triangle made by moving the sides outward by delta. Make a triangular prizm of height, 2 * height, with the given triangle at its center. */ template<typename T> inline void Face<3, T>:: buildCharacteristicPolyhedron(Polyhedron* polyhedron, const Number height) const { polyhedron->clear(); // The initial triangular face. Points on the bottom of the prizm. Point heightOffset = height * getNormal(); Point bot0(getVertices()[0]); bot0 -= heightOffset; Point bot1(getVertices()[1]); bot1 -= heightOffset; Point bot2(getVertices()[2]); bot2 -= heightOffset; // Compute the amount (delta) to enlarge the triangle. Number maximumCoordinate = 1.0; // Loop over the three vertices. for (std::size_t i = 0; i != 3; ++i) { // Loop over the space coordinates. for (std::size_t j = 0; j != 3; ++j) { maximumCoordinate = std::max(maximumCoordinate, std::abs(getVertices()[i][j])); } } // Below, 10 is the fudge factor. const Number delta = maximumCoordinate * 10.0 * std::numeric_limits<Number>::epsilon(); // Enlarge the triangle. Point out0(getSideNormal(0)); negateElements(&out0); Point out1(getSideNormal(1)); negateElements(&out1); Point out2(getSideNormal(2)); negateElements(&out2); bot0 += offsetOutward(out0, out2, delta); bot1 += offsetOutward(out1, out0, delta); bot2 += offsetOutward(out2, out1, delta); // Make the top of the prizm. heightOffset = 2 * height * getNormal(); Point top0(bot0 + heightOffset); Point top1(bot1 + heightOffset); Point top2(bot2 + heightOffset); // Add the vertices of the triangular prizm. polyhedron->insertVertex(bot0); // 0 polyhedron->insertVertex(bot1); // 1 polyhedron->insertVertex(bot2); // 2 polyhedron->insertVertex(top0); // 3 polyhedron->insertVertex(top1); // 4 polyhedron->insertVertex(top2); // 5 // Add the edges of the triangular prizm. polyhedron->insertEdge(0, 1); polyhedron->insertEdge(1, 2); polyhedron->insertEdge(2, 0); polyhedron->insertEdge(3, 4); polyhedron->insertEdge(4, 5); polyhedron->insertEdge(5, 3); polyhedron->insertEdge(0, 3); polyhedron->insertEdge(1, 4); polyhedron->insertEdge(2, 5); } // // Equality / Inequality // template<typename T> inline bool operator==(const Face<3, T>& f1, const Face<3, T>& f2) { if (f1.getVertices()[0] == f2.getVertices()[0] && f1.getVertices()[1] == f2.getVertices()[1] && f1.getVertices()[2] == f2.getVertices()[2] && f1.getSupportingPlane() == f2.getSupportingPlane() && f1.getSides()[0] == f2.getSides()[0] && f1.getSides()[1] == f2.getSides()[1] && f1.getSides()[2] == f2.getSides()[2] && f1.getFaceIndex() == f2.getFaceIndex()) { return true; } return false; } // // File I/O // template<typename T> inline std::ostream& operator<<(std::ostream& out, const Face<3, T>& face) { out << "Vertices:" << '\n' << face.getVertices() << '\n' << "Supporting Plane:" << '\n' << face.getSupportingPlane() << '\n' << "Sides:" << '\n' << face.getSides() << '\n' << "Face index:" << '\n' << face.getFaceIndex() << '\n'; return out; } } // namespace cpt
28.490057
92
0.610311
08e03811b4b6fef2210c8cbc0245664a09e52dcc
1,434
cpp
C++
main/c++-class-templates/c-class-templates.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/c++-class-templates/c-class-templates.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/c++-class-templates/c-class-templates.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cassert> using namespace std; namespace { template <typename T> class AddElements final { public: explicit AddElements(const T elem1) : elem1_{elem1} { } T add(const T elem2) { return elem1_ + elem2; } private: const T elem1_; }; template <> class AddElements<string> final { public: explicit AddElements(const string& elem1) : elem1_{elem1} { } string concatenate(const string& elem2) { return elem1_ + elem2; } private: const string elem1_; }; } // code from HackerRank (not to be modified while completing this exercise) int main () { int n,i; cin >> n; for(i=0;i<n;i++) { string type; cin >> type; if(type=="float") { double element1,element2; cin >> element1 >> element2; AddElements<double> myfloat (element1); cout << myfloat.add(element2) << endl; } else if(type == "int") { int element1, element2; cin >> element1 >> element2; AddElements<int> myint (element1); cout << myint.add(element2) << endl; } else if(type == "string") { string element1, element2; cin >> element1 >> element2; AddElements<string> mystring (element1); cout << mystring.concatenate(element2) << endl; } } return 0; }
24.305085
75
0.593445
08e08cd072855ce935cf1840a2215b955421a32e
953
hpp
C++
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
#ifndef LEDS_HPP #define LEDS_HPP #include "hwlib.hpp" /// @file /// \brief /// leds class /// \details /// This is a class for color for 5 leds. class leds{ private: hwlib::pin_out & l1; hwlib::pin_out & l2; hwlib::pin_out & l3; hwlib::pin_out & l4; hwlib::pin_out & l5; /// \brief /// class public /// \details /// the public part contains the constructor of the leds color and the member functions. public: leds( hwlib::pin_out & l1 , hwlib::pin_out & l2 , hwlib::pin_out & l3 , hwlib::pin_out & l4 , hwlib::pin_out & l5): l1(l1), l2(l2) , l3(l3) , l4(l4) , l5(l5){} /// \brief /// show_color /// \details /// this function has a char parameter. According to this values the function turns the actual color led on. void show_color(char color ); /// \brief /// reset /// \details /// this function turns all the leds off. void reset(); }; #endif
20.276596
112
0.593914
08e1655a6ea40ca41ee8bd4ca653e5c30640d026
1,274
cpp
C++
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
7
2017-02-19T16:22:16.000Z
2021-03-02T05:47:39.000Z
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
61
2017-05-29T06:11:17.000Z
2021-03-28T21:51:44.000Z
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
2
2017-05-28T17:17:40.000Z
2017-07-14T21:45:16.000Z
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen #include <aeon/math/size2d.h> #include <aeon/math/size2d_stream.h> #include <gtest/gtest.h> using namespace aeon; TEST(test_size2d, test_size2d_default_int) { [[maybe_unused]] math::size2d<int> size; } struct external_size2d { int width{}; int height{}; }; TEST(test_size2d, test_size2d_convert_from_unknown) { const external_size2d s{10, 20}; math::size2d<int> size{s}; EXPECT_EQ(size.width, 10); EXPECT_EQ(size.height, 20); const auto s2 = size.convert_to<external_size2d>(); EXPECT_EQ(s2.width, 10); EXPECT_EQ(s2.height, 20); } TEST(test_size2d, test_size2d_clamp) { const math::size2d min{5, 10}; const math::size2d max{50, 100}; EXPECT_EQ(math::clamp(math::size2d{10, 20}, min, max), (math::size2d{10, 20})); EXPECT_EQ(math::clamp(math::size2d{40, 90}, min, max), (math::size2d{40, 90})); EXPECT_EQ(math::clamp(math::size2d{4, 20}, min, max), (math::size2d{5, 20})); EXPECT_EQ(math::clamp(math::size2d{5, 9}, min, max), (math::size2d{5, 10})); EXPECT_EQ(math::clamp(math::size2d{51, 90}, min, max), (math::size2d{50, 90})); EXPECT_EQ(math::clamp(math::size2d{50, 110}, min, max), (math::size2d{50, 100})); }
28.311111
85
0.66562
08e2d306237380b794321d0edbfd42c70a61b2bb
4,852
cpp
C++
src/classical/io/write_verilog.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/io/write_verilog.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/io/write_verilog.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2017 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "write_verilog.hpp" #include <fstream> #include <boost/algorithm/string/join.hpp> #include <boost/assign/std/vector.hpp> #include <boost/format.hpp> #include <boost/range/algorithm.hpp> #include <classical/io/io_utils_p.hpp> using namespace boost::assign; using boost::format; namespace cirkit { /****************************************************************************** * Private functions * ******************************************************************************/ std::string remove_brackets( const std::string& s ) { std::string sc = s; size_t n = 0; while ( ( n = sc.find( '[', n ) ) != std::string::npos ) { auto n2 = sc.find( ']', n ); sc[n] = sc[n2] = '_'; n = n2; } return sc; } void create_possible_inverter( std::ostream& os, const aig_function& f, std::vector<aig_node>& inverter_created, const aig_graph& aig ) { if ( f.complemented && boost::find( inverter_created, f.node ) == inverter_created.end() ) { os << format( "not %1%_inv( %1%_inv, %1% );" ) % get_node_name_processed( f.node, aig, &remove_brackets ) << std::endl; inverter_created += f.node; } } /****************************************************************************** * Public functions * ******************************************************************************/ void write_verilog( const aig_graph& aig, std::ostream& os ) { const auto& aig_info = boost::get_property( aig, boost::graph_name ); std::vector<std::string> inputs, outputs; std::vector<aig_node> inverter_created; /* Inputs */ for ( const auto& v : aig_info.inputs ) { inputs += remove_brackets( aig_info.node_names.find( v )->second ); } /* Outputs */ for ( const auto& v : aig_info.outputs ) { outputs += remove_brackets( v.second ); } os << format( "module top(%s, %s);" ) % boost::join( inputs, ", " ) % boost::join( outputs, ", " ) << std::endl << format( "input %s;" ) % boost::join( inputs, ", " ) << std::endl << format( "output %s;" ) % boost::join( outputs, ", " ) << std::endl; /* AND gates */ for ( const auto& v : boost::make_iterator_range( boost::vertices( aig ) ) ) { /* skip outputs */ if ( boost::out_degree( v, aig ) == 0u ) continue; auto operands = get_operands( v, aig ); create_possible_inverter( os, operands.first, inverter_created, aig ); create_possible_inverter( os, operands.second, inverter_created, aig ); os << format( "and %1%( %1%, %2%%3%, %4%%5% );" ) % get_node_name_processed( v, aig, &remove_brackets ) % get_node_name_processed( operands.first.node, aig, &remove_brackets ) % ( operands.first.complemented ? "_inv" : "" ) % get_node_name_processed( operands.second.node, aig, &remove_brackets ) % ( operands.second.complemented ? "_inv" : "" ) << std::endl; } /* Output functions */ for ( const auto& v : aig_info.outputs ) { os << format( "%1% %2%( %2%, %3% );" ) % ( v.first.complemented ? "not" : "buf" ) % remove_brackets( v.second ) % get_node_name_processed( v.first.node, aig, &remove_brackets ) << std::endl; } os << "endmodule" << std::endl; } void write_verilog( const aig_graph& aig, const std::string& filename ) { std::ofstream os( filename.c_str(), std::ofstream::out ); write_verilog( aig, os ); os.close(); } } // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
34.657143
141
0.591509
08e4d6f55664305d11c4b22861efc87b3e154840
259
cpp
C++
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2021-10-02T19:31:14.000Z
2021-10-02T19:31:14.000Z
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-06-17T01:15:45.000Z
2020-06-17T01:16:08.000Z
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-10-17T23:57:27.000Z
2020-10-17T23:57:27.000Z
// // Created by grant on 1/2/20. // #include "gtest/gtest.h" #include "stms/log_test.cpp" #include "stms/async_test.cpp" #include "stms/general.cpp" #if STMS_SSL_TESTS_ENABLED // Toggle SSL tests, disable for travis # include "stms/ssl_test.cpp" #endif
19.923077
67
0.718147
08e707f8036b8a1d6f86f75bd1152df0f04744d1
1,395
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_bitvectortest.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_bitvectortest.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_bitvectortest.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#include "com_bitvectortest.h" // Library headers. #include <boost/shared_ptr.hpp> #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_suite.hpp> // PCRaster library headers. // Module headers. #include "com_bitvector.h" /*! \file This file contains the implementation of the BitVectorTest class. */ //------------------------------------------------------------------------------ // DEFINITION OF STATIC BITVECTOR MEMBERS //------------------------------------------------------------------------------ //! suite boost::unit_test::test_suite*com::BitVectorTest::suite() { boost::unit_test::test_suite* suite = BOOST_TEST_SUITE(__FILE__); boost::shared_ptr<BitVectorTest> instance(new BitVectorTest()); suite->add(BOOST_CLASS_TEST_CASE(&BitVectorTest::test, instance)); return suite; } //------------------------------------------------------------------------------ // DEFINITION OF BITVECTOR MEMBERS //------------------------------------------------------------------------------ //! ctor com::BitVectorTest::BitVectorTest() { } //! setUp void com::BitVectorTest::setUp() { } //! tearDown void com::BitVectorTest::tearDown() { } void com::BitVectorTest::test() { BitVector bv(5); bv.set(0); bv.set(2); bv.set(4); BOOST_CHECK( bv[0]); BOOST_CHECK(!bv[1]); BOOST_CHECK( bv[2]); BOOST_CHECK(!bv[3]); BOOST_CHECK( bv[4]); }
18.116883
80
0.536201
08e7bc9d26d1bca865b1ba8f1f8b54a2852db55e
336
hpp
C++
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
null
null
null
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
1
2015-03-25T09:42:10.000Z
2015-03-25T09:42:10.000Z
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
null
null
null
#ifndef __SINGLETON_HPP__ #define __SINGLETON_HPP__ #include "noncopyable.hpp" namespace etl { namespace utils { template<class T> class singleton : public noncopyable { public: static T& instance() { static T i; return i; } protected: singleton() {} }; } //utils } //etl #endif // __SINGLETON_HPP__
12.923077
56
0.660714
08e8850381bddd9d41475a7b1eabc6b9dcaeb4b9
1,524
cpp
C++
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
#include <iostream> #include "CUnit.h" #include "CExceptionUnit.h" #include "CArcUnit.h" #include "CVertexUnit.h" #include "CGraphUnit.h" #include "CGraphParserUnit.h" #include "CHashMapUnit.h" #include "../CException.h" #include "CGraphToolboxUnit.h" void CUnit::UNITassertError(const char * pcMessage) { perror(pcMessage); perror("\n"); #ifdef _MSC_VER throw CException(0, (char *) "BREAKPOINT UNIT TESTS"); #else raise(SIGINT); #endif exit(EXIT_FAILURE); } void CUnit::UNITlaunchTests() { std::cout << "Starting CException tests..." << std::endl; CExceptionUnit::EXUnitTests(); std::cout << "CException OK" << std::endl << std::endl; std::cout << "Starting CHashMap tests..." << std::endl; CHashMapUnit::HMPUnitTest(); std::cout << "CHashMap OK" << std::endl << std::endl; std::cout << "Starting CArc tests..." << std::endl; CArcUnit::ARCUnitTests(); std::cout << "CArc OK" << std::endl << std::endl; std::cout << "Starting CVertex tests..." << std::endl; CVertexUnit::VERUnitTest(); std::cout << "CVertex OK" << std::endl << std::endl; std::cout << "Starting CGraphParser tests..." << std::endl; CGraphParserUnit::PGRAUnitTests(); std::cout << "CGraphParser OK" << std::endl << std::endl; std::cout << "Starting CGraph tests..." << std::endl; CGraphUnit::GRAUnitTests(); std::cout << "CGraph OK" << std::endl << std::endl; std::cout << "Starting CGraphToolbox tests..." << std::endl; CGraphToolboxUnit::GRTUnitTests(); std::cout << "CGraphToolbox OK" << std::endl << std::endl; }
28.222222
61
0.660105
08f2dfb507e32aa9e718d9c6509667bf65db2812
14,440
cc
C++
cc_code/src/common/error-model.test.cc
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
null
null
null
cc_code/src/common/error-model.test.cc
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
1
2021-06-12T00:50:08.000Z
2021-06-15T17:59:12.000Z
cc_code/src/common/error-model.test.cc
erisyon/whatprot
176cd7e6ee99ea3f91794dcf1ec14f3578b7ee3c
[ "MIT" ]
1
2021-06-11T19:34:43.000Z
2021-06-11T19:34:43.000Z
/******************************************************************************\ * Author: Matthew Beauregard Smith * * Affiliation: The University of Texas at Austin * * Department: Oden Institute and Institute for Cellular and Molecular Biology * * PI: Edward Marcotte * * Project: Protein Fluorosequencing * \******************************************************************************/ // Boost unit test framework (recommended to be the first include): #include <boost/test/unit_test.hpp> // File under test: #include "error-model.h" // Standard C++ library headers: #include <cmath> #include <functional> namespace whatprot { namespace { using boost::unit_test::tolerance; using std::exp; using std::function; using std::log; const double TOL = 0.000000001; } // namespace BOOST_AUTO_TEST_SUITE(common_suite) BOOST_AUTO_TEST_SUITE(error_model_suite) BOOST_AUTO_TEST_CASE(constructor_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); BOOST_TEST(em.p_edman_failure == p_edman_failure); BOOST_TEST(em.p_detach == p_detach); BOOST_TEST(em.p_bleach == p_bleach); BOOST_TEST(em.p_dud == p_dud); BOOST_TEST(em.distribution_type == dist_type); BOOST_TEST(em.mu == mu); BOOST_TEST(em.sigma == sigma); BOOST_TEST(em.stuck_dye_ratio == stuck_dye_ratio); BOOST_TEST(em.p_stuck_dye_loss == p_stuck_dye_loss); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_zero_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 0; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_zero_obs_one_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 0; BOOST_TEST(pdf(observed, state) == 0.0); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_one_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 1; BOOST_TEST(pdf(observed, state) == 0.0); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_one_obs_one_test, *tolerance(TOL)) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.0); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 1; // The test value was found using an online lognormal distribution pdf // calculator. BOOST_TEST(pdf(observed, state) == 2.4933892525089547); } BOOST_AUTO_TEST_CASE(pdf_lognormal_state_eq_obs_ne_one_test, *tolerance(TOL)) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::LOGNORMAL; double mu = log(1.3); double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.3; int state = 1; // The test value was found using an online lognormal distribution pdf // calculator. BOOST_TEST(pdf(observed, state) == 2.4933892525089547 / 1.3); } BOOST_AUTO_TEST_CASE(pdf_override_state_zero_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 0; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_override_state_zero_obs_one_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 0; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_override_state_one_obs_zero_test) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 0.0; int state = 1; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(pdf_override_state_one_obs_one_test, *tolerance(TOL)) { double p_edman_failure = .07; double p_detach = .04; double p_bleach = .05; double p_dud = .10; DistributionType dist_type = DistributionType::OVERRIDE; double mu = 1.0; double sigma = .16; double stuck_dye_ratio = 0.5; double p_stuck_dye_loss = 0.08; ErrorModel em(p_edman_failure, p_detach, p_bleach, p_dud, dist_type, mu, sigma, stuck_dye_ratio, p_stuck_dye_loss); function<double(double, int)> pdf = em.pdf(); double observed = 1.0; int state = 1; BOOST_TEST(pdf(observed, state) == 1.0); } BOOST_AUTO_TEST_CASE(relative_distance_p_edman_failure_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.66, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_detach_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.66, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_bleach_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.66, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_dud_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.66, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_mu_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.66, 0.5, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (exp(0.66) - exp(0.5)) / exp(0.5)); BOOST_TEST(em2.relative_distance(em1) == (exp(0.66) - exp(0.5)) / exp(0.66)); } BOOST_AUTO_TEST_CASE(relative_distance_sigma_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.66, 0.5, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_stuck_dye_ratio_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.66, 0.5); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_p_stuck_dye_loss_test, *tolerance(TOL)) { ErrorModel em1( 0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.5); ErrorModel em2(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.5, 0.5, 0.5, 0.66); BOOST_TEST(em1.relative_distance(em2) == (0.66 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.66 - 0.5) / 0.66); } BOOST_AUTO_TEST_CASE(relative_distance_max_no_sum_test, *tolerance(TOL)) { ErrorModel em1(0.5, 0.5, 0.5, 0.5, DistributionType::OVERRIDE, 0.66, 0.5, 0.5, 0.5); ErrorModel em2(0.7, 0.7, 0.7, 0.7, DistributionType::OVERRIDE, 0.66, 0.7, 0.7, 0.7); BOOST_TEST(em1.relative_distance(em2) == (0.7 - 0.5) / 0.5); BOOST_TEST(em2.relative_distance(em1) == (0.7 - 0.5) / 0.7); } BOOST_AUTO_TEST_SUITE_END() // error_model_suite BOOST_AUTO_TEST_SUITE_END() // common_suite } // namespace whatprot
32.304251
80
0.523546
08f3d3b0ab3c01c13c305f0aefd1c5a67448b14d
635
cpp
C++
CPP/ones_complement_checksum.cpp
sarthaks-ss/open-source-contribution
ef13e5ed0c8396d62c363fe52708d49c40374d26
[ "MIT" ]
null
null
null
CPP/ones_complement_checksum.cpp
sarthaks-ss/open-source-contribution
ef13e5ed0c8396d62c363fe52708d49c40374d26
[ "MIT" ]
null
null
null
CPP/ones_complement_checksum.cpp
sarthaks-ss/open-source-contribution
ef13e5ed0c8396d62c363fe52708d49c40374d26
[ "MIT" ]
null
null
null
//16bit binary adder with carry #include<iostream> using namespace std; uint16_t b16_adder(uint16_t a,uint16_t b) { uint32_t total32=0; total32=a+b; uint16_t rem=(total32>>16); uint16_t total16=(total32); uint16_t real_total=(total16+rem); return real_total; } //pointer to data array and array size uint16_t checksum_ans16(uint16_t *arr,uint data_size) { uint sz=((data_size%2)>0?data_size+1:data_size); uint16_t current_ans=0; int x=0; while(x<(sz/2)) { uint16_t temp_ans=0; uint16_t no=(arr[x]); temp_ans=b16_adder(current_ans,no); current_ans=(uint16_t)temp_ans; } x++; return (uint16_t)(~current_ans); }
20.483871
53
0.729134
08f4420ae9b237e53d192e28ad209aaae3a6384b
2,524
cpp
C++
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
1
2018-01-09T02:43:57.000Z
2018-01-09T02:43:57.000Z
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
null
null
null
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
null
null
null
/** * * You can modify and use this source freely * only for the development of application related Live2D. * * (c) Live2D Inc. All rights reserved. */ #include "L2DMatrix44.h" namespace live2d { namespace framework { L2DMatrix44::L2DMatrix44() { identity(); } // 単位行列に初期化 void L2DMatrix44::identity(){ for (int i = 0; i < 16; i++) tr[i] = ((i % 5) == 0) ? 1.0f : 0.0f; } void L2DMatrix44::mul(float* a, float* b, float* dst) { float c[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int n = 4; int i, j, k; // 受け取った2つの行列の掛け算を行う。 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { //c[i*4+j]+=a[i*4+k]*b[k*4+j]; c[i + j * 4] += a[i + k * 4] * b[k + j * 4]; } } } for (i = 0; i < 16; i++) { dst[i] = c[i]; } } void L2DMatrix44::multTranslate(float x, float y) { float tr1[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1 }; mul(tr1, tr, tr); } void L2DMatrix44::translate(float x, float y) { tr[12] = x; tr[13] = y; } void L2DMatrix44::multScale(float scaleX, float scaleY) { float tr1[16] = { scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; mul(tr1, tr, tr); } void L2DMatrix44::scale(float scaleX, float scaleY) { tr[0] = scaleX; tr[5] = scaleY; } float L2DMatrix44::transformX(float src) { return tr[0] * src + tr[12]; } float L2DMatrix44::invertTransformX(float src) { return (src - tr[12]) / tr[0]; } float L2DMatrix44::transformY(float src) { return tr[5] * src + tr[13]; } float L2DMatrix44::invertTransformY(float src) { return (src - tr[13]) / tr[5]; } void L2DMatrix44::setMatrix(float* _tr) { for (int i = 0; i < 16; i++) tr[i] = _tr[i]; } void L2DMatrix44::append(L2DMatrix44* m) { mul(m->getArray(), tr, tr); } } }
22.336283
89
0.389857
08f7b1a7196f0b681692d1bb2cbe0f9b9bb590ab
1,926
cpp
C++
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
#include "setting.h" #include "math/fft.h" #include "utils/logger.h" #include "audio/audio_tools.h" using namespace bacchus; const float tol18 = 1e-4f; const int ulpDif = 256*1024; void FftCrossTest(const matxf& x, const matxcx& resy) { matxcx y = DFT(x); int n = y.size(); EXPECT_EQ(resy.size(), n); for (int i = 0; i < n; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y[i].imag(), tol18), i); } matxcx y1 = fft(x); int n1 = y1.size(); EXPECT_EQ(resy.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y1[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y1[i].imag(), tol18), i); } } void FftCrossTest(const matxf& x) { matxcx resy = DFT(x); matxcx y1 = fft(x); //PRINT(resy); //PRINT(y1); // int bd = x.size() > 1000 ? 948 : 0; // EXPECT_FLOAT_EQ(resy[bd].real(),y1[bd].real()); int n1 = y1.size(); EXPECT_EQ(resy.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y1[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y1[i].imag(), tol18), i); } } TEST(FFT2, CrossTest) { matxf x = {1,2,3,4}; matxcx resy = {cplx{10,0}, cplx{-2,2}, cplx{-2,0}, cplx{-2,-2}}; FftCrossTest(x,resy); } TEST(FFT2, DftNoRes) { matxf x = {1,2,3,4}; FftCrossTest(x); } TEST(FFT2, Sine) { int fs = 1024*100; int f1 = 100; matxcx x1 = genSine(1,f1,0,fs,1024); matxcx y = fft(x1); //PRINT(y); matxcx res = fftrev(y); int n1 = x1.size(); EXPECT_EQ(res.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(res[i].real(),x1[i].real(), tol18), i); EXPECT_LE(ulp_difference(res[i].imag(),x1[i].imag(), tol18), i); } //FftCrossTest(x1); //FftCrossTest(x2); }
25.342105
73
0.558152
08fcbe77618e5dfaad7de00fe7b983a15598ca9f
25,842
cc
C++
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
fpersson/MAVSDK
a7161d7634cd04de97f7fbcea10c2da21136892c
[ "BSD-3-Clause" ]
1
2020-03-30T07:53:19.000Z
2020-03-30T07:53:19.000Z
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
fpersson/MAVSDK
a7161d7634cd04de97f7fbcea10c2da21136892c
[ "BSD-3-Clause" ]
1
2021-03-15T18:34:13.000Z
2021-03-15T18:34:13.000Z
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
SEESAI/MAVSDK
5a9289eb09eb6b13f24e9d8d69f5644d2210d6b2
[ "BSD-3-Clause" ]
null
null
null
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: gimbal/gimbal.proto #include "gimbal/gimbal.pb.h" #include "gimbal/gimbal.grpc.pb.h" #include <functional> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/client_callback.h> #include <grpcpp/impl/codegen/message_allocator.h> #include <grpcpp/impl/codegen/method_handler.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/server_callback.h> #include <grpcpp/impl/codegen/server_callback_handlers.h> #include <grpcpp/impl/codegen/server_context.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace mavsdk { namespace rpc { namespace gimbal { static const char* GimbalService_method_names[] = { "/mavsdk.rpc.gimbal.GimbalService/SetPitchAndYaw", "/mavsdk.rpc.gimbal.GimbalService/SetPitchRateAndYawRate", "/mavsdk.rpc.gimbal.GimbalService/SetMode", "/mavsdk.rpc.gimbal.GimbalService/SetRoiLocation", "/mavsdk.rpc.gimbal.GimbalService/TakeControl", "/mavsdk.rpc.gimbal.GimbalService/ReleaseControl", "/mavsdk.rpc.gimbal.GimbalService/SubscribeControl", }; std::unique_ptr< GimbalService::Stub> GimbalService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< GimbalService::Stub> stub(new GimbalService::Stub(channel)); return stub; } GimbalService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_SetPitchAndYaw_(GimbalService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetPitchRateAndYawRate_(GimbalService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetMode_(GimbalService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetRoiLocation_(GimbalService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_TakeControl_(GimbalService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_ReleaseControl_(GimbalService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SubscribeControl_(GimbalService_method_names[6], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) {} ::grpc::Status GimbalService::Stub::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetPitchAndYaw_, context, request, response); } void GimbalService::Stub::experimental_async::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchAndYaw_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchAndYaw_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse>* GimbalService::Stub::PrepareAsyncSetPitchAndYawRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetPitchAndYaw_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse>* GimbalService::Stub::AsyncSetPitchAndYawRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetPitchAndYawRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetPitchRateAndYawRate_, context, request, response); } void GimbalService::Stub::experimental_async::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchRateAndYawRate_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchRateAndYawRate_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse>* GimbalService::Stub::PrepareAsyncSetPitchRateAndYawRateRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetPitchRateAndYawRate_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse>* GimbalService::Stub::AsyncSetPitchRateAndYawRateRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetPitchRateAndYawRateRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::mavsdk::rpc::gimbal::SetModeResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetMode_, context, request, response); } void GimbalService::Stub::experimental_async::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetMode_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetMode_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetModeResponse>* GimbalService::Stub::PrepareAsyncSetModeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetModeResponse, ::mavsdk::rpc::gimbal::SetModeRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetMode_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetModeResponse>* GimbalService::Stub::AsyncSetModeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetModeRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetRoiLocation_, context, request, response); } void GimbalService::Stub::experimental_async::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetRoiLocation_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetRoiLocation_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetRoiLocationResponse>* GimbalService::Stub::PrepareAsyncSetRoiLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetRoiLocation_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetRoiLocationResponse>* GimbalService::Stub::AsyncSetRoiLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetRoiLocationRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::mavsdk::rpc::gimbal::TakeControlResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_TakeControl_, context, request, response); } void GimbalService::Stub::experimental_async::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_TakeControl_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_TakeControl_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::TakeControlResponse>* GimbalService::Stub::PrepareAsyncTakeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::TakeControlResponse, ::mavsdk::rpc::gimbal::TakeControlRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_TakeControl_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::TakeControlResponse>* GimbalService::Stub::AsyncTakeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncTakeControlRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_ReleaseControl_, context, request, response); } void GimbalService::Stub::experimental_async::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_ReleaseControl_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_ReleaseControl_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::ReleaseControlResponse>* GimbalService::Stub::PrepareAsyncReleaseControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_ReleaseControl_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::ReleaseControlResponse>* GimbalService::Stub::AsyncReleaseControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncReleaseControlRaw(context, request, cq); result->StartCall(); return result; } ::grpc::ClientReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::SubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request) { return ::grpc::internal::ClientReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), rpcmethod_SubscribeControl_, context, request); } void GimbalService::Stub::experimental_async::SubscribeControl(::grpc::ClientContext* context, ::mavsdk::rpc::gimbal::SubscribeControlRequest* request, ::grpc::experimental::ClientReadReactor< ::mavsdk::rpc::gimbal::ControlResponse>* reactor) { ::grpc::internal::ClientCallbackReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(stub_->channel_.get(), stub_->rpcmethod_SubscribeControl_, context, request, reactor); } ::grpc::ClientAsyncReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::AsyncSubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request, ::grpc::CompletionQueue* cq, void* tag) { return ::grpc::internal::ClientAsyncReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), cq, rpcmethod_SubscribeControl_, context, request, true, tag); } ::grpc::ClientAsyncReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::PrepareAsyncSubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), cq, rpcmethod_SubscribeControl_, context, request, false, nullptr); } GimbalService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* req, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* resp) { return service->SetPitchAndYaw(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* req, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* resp) { return service->SetPitchRateAndYawRate(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetModeRequest* req, ::mavsdk::rpc::gimbal::SetModeResponse* resp) { return service->SetMode(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* req, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* resp) { return service->SetRoiLocation(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::TakeControlRequest* req, ::mavsdk::rpc::gimbal::TakeControlResponse* resp) { return service->TakeControl(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* req, ::mavsdk::rpc::gimbal::ReleaseControlResponse* resp) { return service->ReleaseControl(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[6], ::grpc::internal::RpcMethod::SERVER_STREAMING, new ::grpc::internal::ServerStreamingHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SubscribeControlRequest, ::mavsdk::rpc::gimbal::ControlResponse>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SubscribeControlRequest* req, ::grpc::ServerWriter<::mavsdk::rpc::gimbal::ControlResponse>* writer) { return service->SubscribeControl(ctx, req, writer); }, this))); } GimbalService::Service::~Service() { } ::grpc::Status GimbalService::Service::SetPitchAndYaw(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetPitchRateAndYawRate(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetMode(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetRoiLocation(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::TakeControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::ReleaseControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SubscribeControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest* request, ::grpc::ServerWriter< ::mavsdk::rpc::gimbal::ControlResponse>* writer) { (void) context; (void) request; (void) writer; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace mavsdk } // namespace rpc } // namespace gimbal
76.910714
317
0.747581
1c00ca7ebcb8c0ce9aeeb4784f8e788502f27923
9,983
cc
C++
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
24
2016-07-10T08:05:11.000Z
2021-11-16T10:53:48.000Z
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
14
2015-04-12T10:45:26.000Z
2016-06-28T22:27:50.000Z
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
4
2016-10-05T17:51:38.000Z
2020-04-20T07:45:23.000Z
// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2018 Christian Parpart <christian@parpart.family> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/http/http1/Parser.h> #include <xzero/http/HttpListener.h> #include <xzero/http/HttpStatus.h> #include <xzero/io/FileUtil.h> #include <xzero/RuntimeError.h> #include <xzero/Buffer.h> #include <vector> #include <xzero/testing.h> using namespace xzero; using namespace xzero::http; using namespace xzero::http::http1; class ParserListener : public HttpListener { // {{{ public: ParserListener(); void onMessageBegin(const BufferRef& method, const BufferRef& entity, HttpVersion version) override; void onMessageBegin(HttpVersion version, HttpStatus code, const BufferRef& text) override; void onMessageBegin() override; void onMessageHeader(const BufferRef& name, const BufferRef& value) override; void onMessageHeaderEnd() override; void onMessageContent(const BufferRef& chunk) override; void onMessageContent(FileView&& chunk) override; void onMessageEnd() override; void onError(std::error_code ec) override; public: std::string method; std::string entity; HttpVersion version; HttpStatus statusCode; std::string statusReason; std::vector<std::pair<std::string, std::string>> headers; Buffer body; HttpStatus errorCode; bool messageBegin; bool headerEnd; bool messageEnd; }; ParserListener::ParserListener() : method(), entity(), version(HttpVersion::UNKNOWN), statusCode(HttpStatus::Undefined), statusReason(), headers(), errorCode(HttpStatus::Undefined), messageBegin(false), headerEnd(false), messageEnd(false) { } void ParserListener::onMessageBegin(const BufferRef& method, const BufferRef& entity, HttpVersion version) { this->method = method.str(); this->entity = entity.str(); this->version = version; } void ParserListener::onMessageBegin(HttpVersion version, HttpStatus code, const BufferRef& text) { this->version = version; this->statusCode = code; this->statusReason = text.str(); } void ParserListener::onMessageBegin() { messageBegin = true; } void ParserListener::onMessageHeader(const BufferRef& name, const BufferRef& value) { headers.push_back(std::make_pair(name.str(), value.str())); } void ParserListener::onMessageHeaderEnd() { headerEnd = true; } void ParserListener::onMessageContent(const BufferRef& chunk) { body += chunk; } void ParserListener::onMessageContent(FileView&& chunk) { body += FileUtil::read(chunk); } void ParserListener::onMessageEnd() { messageEnd = true; } void ParserListener::onError(std::error_code ec) { errorCode = static_cast<HttpStatus>(ec.value()); } // }}} TEST(http_http1_Parser, requestLine0) { /* Seems like in HTTP/0.9 it was possible to create * very simple request messages. */ ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET /\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_TRUE(listener.headerEnd); ASSERT_TRUE(listener.messageEnd); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/0.9\r\n\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine2) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("HEAD /foo?bar HTTP/1.0\r\n\r\n"); ASSERT_EQ("HEAD", listener.method); ASSERT_EQ("/foo?bar", listener.entity); ASSERT_EQ(HttpVersion::VERSION_1_0, listener.version); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine_invalid1_MissingPathAndProtoVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET\r\n\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid3_InvalidVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/0\r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid3_CharsAfterVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/1.1b\r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid5_SpaceAfterVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/1.1 \r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid6_UnsupportedVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); // Actually, we could make it a ParserError, or HttpClientError or so, // But to make googletest lib happy, we should make it even a distinct class. ASSERT_THROW(parser.parseFragment("GET / HTTP/1.2\r\n\r\n"), RuntimeError); } TEST(http_http1_Parser, headers1) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); parser.parseFragment( "Foo: the foo\r\n" "Content-Length: 6\r\n" "\r\n" "123456"); ASSERT_EQ("Foo", listener.headers[0].first); ASSERT_EQ("the foo", listener.headers[0].second); ASSERT_EQ("123456", listener.body); } TEST(http_http1_Parser, invalidHeader1) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); size_t n = parser.parseFragment("Foo : the foo\r\n" "\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); ASSERT_EQ(3, n); ASSERT_EQ(0, listener.headers.size()); } TEST(http_http1_Parser, invalidHeader2) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); size_t n = parser.parseFragment("Foo\r\n" "\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); ASSERT_EQ(5, n); ASSERT_EQ(0, listener.headers.size()); } TEST(http_http1_Parser, requestWithHeaders) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Foo: the foo\r\n" "X-Bar: the bar\r\n" "\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_EQ(2, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); ASSERT_EQ("Foo", listener.headers[0].first); ASSERT_EQ("the foo", listener.headers[0].second); ASSERT_EQ("X-Bar", listener.headers[1].first); ASSERT_EQ("the bar", listener.headers[1].second); } TEST(http_http1_Parser, requestWithHeadersAndBody) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Foo: the foo\r\n" "X-Bar: the bar\r\n" "Content-Length: 6\r\n" "\r\n" "123456"); ASSERT_EQ("123456", listener.body); } // no chunks except the EOS-chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("", listener.body); } // exactly one data chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked2) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("123456", listener.body); } // more than one data chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked3) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" "\r\n" "6\r\n" "123456" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("123456123456", listener.body); } // first chunk is missing CR LR TEST(http_http1_Parser, requestWithHeadersAndBodyChunked_invalid1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); size_t n = parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" //"\r\n" // should bailout here "0\r\n" "\r\n"); ASSERT_EQ(55, n); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); } TEST(http_http1_Parser, pipelined1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); constexpr BufferRef input = "GET /foo HTTP/1.1\r\n\r\n" "HEAD /bar HTTP/0.9\r\n\r\n"; size_t n = parser.parseFragment(input); EXPECT_EQ("GET", listener.method); EXPECT_EQ("/foo", listener.entity); EXPECT_EQ(HttpVersion::VERSION_1_1, listener.version); parser.parseFragment(input.ref(n)); EXPECT_EQ("HEAD", listener.method); EXPECT_EQ("/bar", listener.entity); EXPECT_EQ(HttpVersion::VERSION_0_9, listener.version); }
28.280453
80
0.683863
1c071123e27cd580970c23437b07e9d79b516281
78,938
cpp
C++
ImportantExample/QTDbfDemo/src/dbfeditor.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
3
2018-12-24T19:35:52.000Z
2022-02-04T14:45:59.000Z
ImportantExample/QTDbfDemo/src/dbfeditor.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
null
null
null
ImportantExample/QTDbfDemo/src/dbfeditor.cpp
xiaohaijin/Qt
54d961c6a8123d8e4daf405b7996aba4be9ab7ed
[ "MIT" ]
1
2019-05-09T02:42:40.000Z
2019-05-09T02:42:40.000Z
#/********************************************************************************/ #/* */ #/* Copyright 2011 Alexander Vorobyev (Voral) */ #/* http://va-soft.ru/ */ #/* */ #/* Copyright (C) 2009 Hevele Hegyi Istvan. */ #/* */ #/* This file is part of qtDbf. */ #/* */ #/* Basetest 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. */ #/* */ #/* Basetest 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 protime. If not, see <http://www.gnu.org/licenses/>. */ #/* */ #/********************************************************************************/ #include <QtSql> #include <QDateEdit> #include <QClipboard> #include <QMessageBox> #include <QFileDialog> #include <QApplication> #include <QPlainTextEdit> #include "structures.h" #include "dbfeditor.h" #include "widgets.h" #include "customsqlmodel.h" #include "qtcalculator.h" #include "dbfconfig.h" #include "globals.h" #include "dialogfilter.h" #include "dialogagregat.h" QDbfEditor::QDbfEditor(QString &a_dbfFileName, const QString &title, QWidget *parent) : QWidget(parent) { QHBoxLayout *mainLayout = new QHBoxLayout(this); view = new QDbfTableView(this); openAction = new QAction(QIcon(":/open.png"),tr("Open").append(" Ctrl + O"), this); openAction->setShortcut(Qt::CTRL + Qt::Key_O); connect(openAction, SIGNAL(triggered()), this, SLOT(openNewFile())); addAction(openAction); fillAction = new QAction(QIcon(":/fill.png"),tr("Fill"), this); connect(fillAction, SIGNAL(triggered()), this, SLOT(fillCells())); addAction(fillAction); editAction = new QAction(QIcon(":/edit.png"),tr("Edit").append(" Enter"), this); editAction->setShortcut(Qt::Key_Return); connect(editAction, SIGNAL(triggered()), this, SLOT(editRecord())); addAction(editAction); insertAction = new QAction(QIcon(":/add.png"),tr("Add").append(" Ins"), this); insertAction->setShortcut(Qt::Key_Insert); connect(insertAction, SIGNAL(triggered()), this, SLOT(insertRecord())); addAction(insertAction); deleteAction = new QAction(QIcon(":/remove.png"),tr("Delete").append(" Del"), this); deleteAction->setShortcut(Qt::Key_Delete); connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteRecord())); addAction(deleteAction); saveAction = new QAction(QIcon(":/save.png"),tr("Save").append(" Ctrl + S"), this); connect(saveAction, SIGNAL(triggered()), this, SLOT(saveDbfFile())); saveAction->setShortcut(Qt::CTRL + Qt::Key_S); addAction(saveAction); configAction = new QAction(QIcon(":/config.png"),tr("Configure"), this); connect(configAction, SIGNAL(triggered()), this, SLOT(configApp())); addAction(configAction); helpAction = new QAction(QIcon(":/help.png"),tr("Help").append(" F1"), this); helpAction->setShortcut(Qt::Key_F1); connect(helpAction, SIGNAL(triggered()), this, SLOT(helpDbf())); addAction(helpAction); calcAction = new QAction(QIcon(":/calc.png"),tr("Calculator").append(" Ctrl + E"), this); saveAction->setShortcut(Qt::CTRL + Qt::Key_E); connect(calcAction, SIGNAL(triggered()), this, SLOT(calculator())); addAction(calcAction); quitAction = new QAction(QIcon(":/quit.png"),tr("Close").append(" Esc"), this); saveAction->setShortcut(Qt::Key_Escape); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(closeAllWindows())); addAction(quitAction); filterAction = new QAction(QIcon(":/filter.png"),tr("Set filter").append(" Ctrl + F"), this); filterAction->setShortcut(Qt::CTRL + Qt::Key_F); filterAction->setCheckable(true); connect(filterAction, SIGNAL(triggered(bool)), this, SLOT(filter(bool))); addAction(filterAction); agregatAction = new QAction(QIcon(":/functions.png"),tr("Average functions").append(" Ctrl + A"), this); agregatAction->setShortcut(Qt::CTRL + Qt::Key_A); connect(agregatAction, SIGNAL(triggered()), this, SLOT(agregat())); addAction(agregatAction); openButton = new QDbfToolButton(this); openButton->setDefaultAction(openAction); editButton = new QDbfToolButton(this); editButton->setDefaultAction(editAction); insertButton = new QDbfToolButton(this); insertButton->setDefaultAction(insertAction); deleteButton = new QDbfToolButton(this); deleteButton->setDefaultAction(deleteAction); saveButton = new QDbfToolButton(this); saveButton->setDefaultAction(saveAction); fillButton = new QDbfToolButton(this); fillButton->setDefaultAction(fillAction); configButton = new QDbfToolButton(this); configButton->setDefaultAction(configAction); helpButton = new QDbfToolButton(this); helpButton->setDefaultAction(helpAction); calcButton = new QDbfToolButton(this); calcButton->setDefaultAction(calcAction); quitButton = new QDbfToolButton(this); quitButton->setDefaultAction(quitAction); filterButton = new QDbfToolButton(this); filterButton->setDefaultAction(filterAction); agregatButton = new QDbfToolButton(this); agregatButton->setDefaultAction(agregatAction); openButton->setFocusPolicy(Qt::NoFocus); editButton->setFocusPolicy(Qt::NoFocus); insertButton->setFocusPolicy(Qt::NoFocus); deleteButton->setFocusPolicy(Qt::NoFocus); fillButton->setFocusPolicy(Qt::NoFocus); saveButton->setFocusPolicy(Qt::NoFocus); configButton->setFocusPolicy(Qt::NoFocus); helpButton->setFocusPolicy(Qt::NoFocus); calcButton->setFocusPolicy(Qt::NoFocus); quitButton->setFocusPolicy(Qt::NoFocus); filterButton->setFocusPolicy(Qt::NoFocus); agregatButton->setFocusPolicy(Qt::NoFocus); QVBoxLayout *buttonLayout = new QVBoxLayout; buttonLayout->addWidget(openButton); buttonLayout->addWidget(fillButton); buttonLayout->addWidget(editButton); buttonLayout->addWidget(insertButton); buttonLayout->addWidget(deleteButton); buttonLayout->addWidget(saveButton); buttonLayout->addWidget(filterButton); buttonLayout->addWidget(agregatButton); buttonLayout->addWidget(configButton); buttonLayout->addWidget(calcButton); buttonLayout->addWidget(helpButton); buttonLayout->addStretch(1); buttonLayout->addWidget(quitButton); mainLayout->addWidget(view); mainLayout->addLayout(buttonLayout); connect(this, SIGNAL(modelIsEmpty(bool)), editAction, SLOT(setDisabled(bool))); connect(this, SIGNAL(modelIsEmpty(bool)), deleteAction, SLOT(setDisabled(bool))); connect(this, SIGNAL(modelIsEmpty(bool)), fillAction, SLOT(setDisabled(bool))); connect(view, SIGNAL(editSignal()), this, SLOT(editRecord())); connect(view, SIGNAL(insertSignal()), this, SLOT(insertRecord())); connect(view, SIGNAL(deleteSignal()), this, SLOT(deleteRecord())); connect(view, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(editRecord())); connect(view, SIGNAL(quitSignal()), qApp, SLOT(closeAllWindows())); connect(parent, SIGNAL(setToolButtonIconSize(int)), this, SLOT(setToolButtonIconSize(int))); openFile(a_dbfFileName,false); if (model->rowCount() == 0) emit modelIsEmpty(true); else emit modelIsEmpty(false); view->setFocus(); } void QDbfEditor::setModified(bool value) { modified = value; emit modifiedChanged(value); saveAction->setEnabled(value); } void QDbfEditor::openFile(QString &a_dbfFileName,bool fresh = false) { where = ""; order = ""; filterAction->setChecked(false); if (fresh) { delete this->model; delete fieldsItem; while (fieldsCollection.count()>0) { fieldsCollection.removeLast(); } } setModified(false); dbfFileName = a_dbfFileName; int current; readSettings(); openDbfFile(); QString query; QSqlQuery getData(QSqlDatabase::database("dbfEditor")); int i; query = "SELECT id_"; query += tableName; query += ","; for (i=0;i<fieldsCollection.count();i++) { query += ("`"+fieldsCollection.at(i)->fieldName+"`"); if (i<fieldsCollection.count()-1) query += ","; } query +=" FROM "; query += tableName; model = new QDbfSqlModel(this); for (i=0;i<fieldsCollection.count();i++) { if (fieldsCollection.at(i)->fieldType == "C") model->addCharField(i+1); if (fieldsCollection.at(i)->fieldType == "Y") model->addCurrencyField(i+1); if (fieldsCollection.at(i)->fieldType == "N") model->addNumericField(i+1); if (fieldsCollection.at(i)->fieldType == "F") model->addNumericField(i+1); if (fieldsCollection.at(i)->fieldType == "D") model->addDateField(i+1); if (fieldsCollection.at(i)->fieldType == "T") model->addTimeField(i+1); if (fieldsCollection.at(i)->fieldType == "B") model->addDoubleField(i+1); if (fieldsCollection.at(i)->fieldType == "I") model->addIntField(i+1); if (fieldsCollection.at(i)->fieldType == "L") model->addLogicalField(i+1); if ((fieldsCollection.at(i)->fieldType == "M") && (fieldsCollection.at(i)->fieldSize == 10)) model->addMemoField(i+1); if ((fieldsCollection.at(i)->fieldType == "M") && (fieldsCollection.at(i)->fieldSize == 4)) model->addMemo4Field(i+1); if (fieldsCollection.at(i)->fieldType == "G") model->addGeneralField(i+1); } model->setQuery(query, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); } QString tempChar; QString tempValue; model->setHeaderData(0, Qt::Horizontal, tr("ID")); for (int i=0; i<fieldsCollection.count(); ++i) { tempValue = fieldsCollection.at(i)->fieldName; tempValue += " ("; tempValue += fieldsCollection.at(i)->fieldType; tempChar.setNum(fieldsCollection.at(i)->fieldSize); tempValue += tempChar; if (fieldsCollection.at(i)->fieldDecimals != 0) { tempValue += ","; tempChar.setNum(fieldsCollection.at(i)->fieldDecimals); tempValue += tempChar; } tempValue += ")"; model->setHeaderData(i+1, Qt::Horizontal, tempValue); } view->setModel(model); refresh(0); current = view->currentIndex().row(); QSqlRecord record = model->record(current); recordId = record.value(0).toString(); setModified(false); } void QDbfEditor::writeSettings() { QSettings settings; settings.setValue("dbfeditor/Size", size()); settings.setValue("dbfeditor/edSize", editDialogSize); } void QDbfEditor::readSettings() { QSettings settings; QSize size = settings.value("dbfeditor/Size", QSize(900, 600)).toSize(); resize(size); editDialogSize = settings.value("dbfeditor/edSize", QSize(400,217)).toSize(); } void QDbfEditor::filter(bool on) { if (on) { int c = view->currentIndex().column(); DialogFilter *dlg = new DialogFilter(fieldsCollection,tr("Filter"),fieldsCollection.at(c-1)->fieldName,this); if (dlg->exec() == QDialog::Accepted) where = dlg->getWhere(); else filterAction->setChecked(false); dlg->deleteLater(); } else { filterAction->setChecked(false); where = ""; } QString query; query = "SELECT * FROM "; query += tableName; if (where != "") query += " WHERE " + where; if (order != "") query += " ORDER BY " + order; model->setQuery(query, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(0); } void QDbfEditor::editRecord() { QModelIndexList currentSelection = view->selectionModel()->selectedIndexes(); QModelIndex currentIndex = view->currentIndex(); //int i; QDate tempDate; if (currentSelection.count() == 0) { QMessageBox::critical(this, tr("Error"), tr("Select at least a cell")); return; } int r = view->currentIndex().row(); int c = view->currentIndex().column(); QSqlRecord record = model->record(r); recordId = record.value(0).toString(); QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; QString editValue; QByteArray editByteArray; query = "SELECT "; query += ("`"+fieldsCollection.at(c-1)->fieldName+"`"); query += " FROM "; query += tableName; query += " WHERE id_"; query += tableName; query += "="; query += recordId; query += ""; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } while (getData.next()) { editByteArray = getData.value(0).toByteArray(); editValue = getData.value(0).toString().simplified(); tempDate = getData.value(0).toDate(); } bool ok; if (fieldsCollection.at(c-1)->fieldType == "M") { /* 0x02 FoxBASE 0x03 FoxBASE+/Dbase III plus, no memo 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x32 Visual FoxPro with field type Varchar or Varbinary 0x43 dBASE IV SQL table files, no memo 0x63 dBASE IV SQL system files, no memo 0x83 FoxBASE+/dBASE III PLUS, with memo 0x8B dBASE IV with memo 0xCB dBASE IV SQL table files, with memo 0xF5 FoxPro 2.x (or earlier) with memo 0xE5 HiPer-Six format with SMT memo file 0xFB FoxBASE */ //0x83 FoxBASE+/dBASE III PLUS, with memo if ((dbfFileHeader[0] == '\x83')) readDbtFile(editValue.toInt(&ok,10)); //0xF5 FoxPro 2.x (or earlier) with memo if (dbfFileHeader[0] == '\xF5') (editValue.toInt(&ok,10)); /* 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x32 Visual FoxPro with field type Varchar or Varbinary */ if ((dbfFileHeader[0] == '\x30') ||(dbfFileHeader[0] == '\x31') || (dbfFileHeader[0] == '\x32')) { editByteArray = QByteArray::fromHex(editByteArray); quint32 l = *(quint32 *)editByteArray.data(); readFptFile(l); } //0x8B dBASE IV with memo if (dbfFileHeader[0] == '\x8B') readDbt4File(editValue.toInt(&ok,10)); return; } QDbfDialog *d = new QDbfDialog(tr("Edit"), this); QSettings settings; d->resize(settings.value("dbfeditor/edsize", QSize(140,40)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QString labelText; QString tempValue; tempValue = ""; labelText = "<b>"; labelText += fieldsCollection.at(c-1)->fieldName; labelText += " "; labelText += fieldsCollection.at(c-1)->fieldType; labelText += "("; tempValue.setNum(fieldsCollection.at(c-1)->fieldSize); labelText += tempValue; if (fieldsCollection.at(c-1)->fieldDecimals != 0) { labelText += ","; tempValue.clear(); tempValue.setNum(fieldsCollection.at(c-1)->fieldDecimals); labelText += tempValue; } labelText += ")</b>"; QLabel *label = new QLabel(labelText, d); QDbfLineEdit *l; QDateTimeEdit *dte; QDateEdit *de; QString inputMaskFormat; QTime tempTime; quint32 l1; qint32 l2; qint64 l3; double db; quint8 tempByte; if (fieldsCollection.at(c-1)->fieldType == "C") { l = new QDbfLineEdit(editValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); l->selectAll(); } else if (fieldsCollection.at(c-1)->fieldType == "L") { l = new QDbfLineEdit(editValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); } else if (fieldsCollection.at(c-1)->fieldType == "D") { de = new QDateEdit(tempDate, d); QFont font = de->font(); font.setPointSize(font.pointSize() + 5); de->setFont(font); de->setCalendarPopup(true); de->setDisplayFormat("dd.MM.yyyy"); } else if (fieldsCollection.at(c-1)->fieldType == "Y") { editByteArray = QByteArray::fromHex(editByteArray); l3 = *(qint64 *)editByteArray.data(); db = l3; tempValue.setNum(db/10000,'f',4); l = new QDoubleLineEdit(tempValue,d); l->selectAll(); } else if (fieldsCollection.at(c-1)->fieldType == "T") { editByteArray = QByteArray::fromHex(editByteArray); l1 = *(quint32 *)editByteArray.data(); tempDate = QDate::fromJulianDay(l1); l1 = *(quint32 *)(editByteArray.data()+4); tempTime.setHMS(0,0,0); tempTime = tempTime.addMSecs(l1); QDateTime dt(tempDate,tempTime); dte = new QDateTimeEdit(dt,d); dte->setDisplayFormat("dd.MM.yyyy hh:mm:ss.zzz"); QFont font = dte->font(); font.setPointSize(font.pointSize() + 5); dte->setFont(font); dte->setCalendarPopup(true); } else if (fieldsCollection.at(c-1)->fieldType == "I") { editByteArray = QByteArray::fromHex(editByteArray); l2 = *(qint32 *)editByteArray.data(); tempValue.setNum(l2, 10); l = new QDoubleLineEdit(tempValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); l->selectAll(); } else if (fieldsCollection.at(c-1)->fieldType == "B") { editByteArray = QByteArray::fromHex(editByteArray); db = *(double *)editByteArray.data(); tempValue.setNum(db); l = new QDoubleLineEdit(tempValue,d); l->selectAll(); } else if ((fieldsCollection.at(c-1)->fieldType == "N") || (fieldsCollection.at(c-1)->fieldType == "F")) { l = new QDoubleLineEdit(editValue,d); l->setMaxLength(fieldsCollection.at(c-1)->fieldSize); l->selectAll(); } else { QMessageBox::information(this, tr("Edit"), tr("Unsupported field (yet)")); return; } if (fieldsCollection.at(c-1)->fieldType == "T") { label->setBuddy(dte); } else if (fieldsCollection.at(c-1)->fieldType == "D") { label->setBuddy(de); } else { d->insertLineEditToVerify(l); label->setBuddy(l); } QPushButton *okButton = new QPushButton(tr("OK"), d); QPushButton *cancelButton = new QPushButton(tr("Cancel"), d); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(okButton); buttonLayout->addWidget(cancelButton); mainLayout->addWidget(label); if (fieldsCollection.at(c-1)->fieldType == "T") { mainLayout->addWidget(dte); } else if (fieldsCollection.at(c-1)->fieldType == "D") { mainLayout->addWidget(de); } else { mainLayout->addWidget(l); } mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(okButton, SIGNAL(clicked()), d, SLOT(verifyDbfInputLines())); connect(cancelButton, SIGNAL(clicked()), d, SLOT(reject())); d->setLayout(mainLayout); if (d->exec()) { if (d->result() == QDialog::Accepted) { if (fieldsCollection.at(c-1)->fieldType == "T") { setModified(true); } else if (fieldsCollection.at(c-1)->fieldType == "D") { setModified(true); } else { if (l->text() != editValue) { setModified(true); } } query = "UPDATE "; query += tableName; query += " SET "; query += ("`"+fieldsCollection.at(c-1)->fieldName+"`"); query += "='"; if ((fieldsCollection.at(c-1)->fieldType == "N") || ((fieldsCollection.at(c-1)->fieldType == "F"))) { db = l->text().toDouble(&ok); tempValue.setNum(db,'f',fieldsCollection.at(c-1)->fieldDecimals); query += tempValue; } else if (fieldsCollection.at(c-1)->fieldType == "T") { editByteArray.clear(); l1 = dte->dateTime().date().toJulianDay(); tempByte = l1; editByteArray.append(tempByte); tempByte = l1 >> 8; editByteArray.append(tempByte); tempByte = l1 >> 16; editByteArray.append(tempByte); tempByte = l1 >> 24; editByteArray.append(tempByte); l1 = dte->dateTime().time().msecsTo(QTime(0,0,0)); l1 = l1*(-1); tempByte = l1; editByteArray.append(tempByte); tempByte = l1 >> 8; editByteArray.append(tempByte); tempByte = l1 >> 16; editByteArray.append(tempByte); tempByte = l1 >> 24; editByteArray.append(tempByte); query += editByteArray.toHex().toUpper(); } else if (fieldsCollection.at(c-1)->fieldType == "D") { query+= de->date().toString("yyyy-MM-dd"); } else if (fieldsCollection.at(c-1)->fieldType == "I") { l2 = l->text().toLong(&ok, 10); editByteArray.clear(); editByteArray = editByteArray.fromRawData((const char*)&l2,4); query += editByteArray.toHex().toUpper(); } else if (fieldsCollection.at(c-1)->fieldType == "Y") { db = l->text().toDouble(&ok); db = db*10000; tempValue.setNum(db,'f',0); l3 = tempValue.toLongLong(&ok, 10); editByteArray.clear(); editByteArray = editByteArray.fromRawData((const char*)&l3,8); query += editByteArray.toHex().toUpper(); } else if (fieldsCollection.at(c-1)->fieldType == "B") { db = l->text().toDouble(&ok); editByteArray.clear(); editByteArray = editByteArray.fromRawData((const char*)&db,8); query += editByteArray.toHex().toUpper(); } else { query += l->text(); } query += "' WHERE id_"; query += tableName; query += "='"; query += recordId; query += "'"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(c); view->setCurrentIndex(currentIndex); } } settings.setValue("dbfeditor/edsize", d->size()); delete d; } void QDbfEditor::insertRecord() { QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; int j; QStringList fieldTypes; bool ok = true; for (j = 0;j<fieldsCollection.count();j++) { fieldsItem = fieldsCollection.at(j); //if ((fieldsItem->fieldType == "M") && (fieldsItem->fieldSize == 4)) // ok = false; if (!fieldTypes.contains(fieldsItem->fieldType)) fieldTypes.append(fieldsItem->fieldType); } if (fieldTypes.contains("0")) { ok = false; } if (!ok) { QMessageBox::information(this, tr("Insert"), tr("The file contains unsupported fields.")); return; } query = "INSERT INTO "; query += tableName; query += " ("; for (j=0; j<fieldsCollection.count(); ++j) { query += ("`"+fieldsCollection.at(j)->fieldName+"`"); if (j<fieldsCollection.count()-1) query += ","; } query += ") VALUES ("; QString tempValue; for (j=0; j<fieldsCollection.count(); j++) { fieldsItem = fieldsCollection.at(j); if (fieldsItem->fieldType == "D") { query += "' '"; } else if (fieldsItem->fieldType == "L") { query += "'F'"; } else if (fieldsItem->fieldType == "C") { query += "' '"; } else if (fieldsItem->fieldType == "N") { query += "0"; } else if ((fieldsItem->fieldType == "Y") || (fieldsItem->fieldType == "T") || (fieldsItem->fieldType == "B") || (fieldsItem->fieldType == "I") || (fieldsItem->fieldType == "G") || ((fieldsItem->fieldType == "M") && (fieldsItem->fieldSize == 4))) { query += "'"; for (int i=0;i<fieldsItem->fieldSize;i++) query += "00"; query += "'"; } else { query += "''"; } if (j<fieldsCollection.count()-1) query += ","; } query += ")"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } if (model->rowCount() == 0) emit modelIsEmpty(true); else emit modelIsEmpty(false); setModified(true); } void QDbfEditor::deleteRecord() { int current; QModelIndexList currentSelection = view->selectionModel()->selectedIndexes(); if (currentSelection.count() == 0) { QMessageBox::critical(this, tr("Error"), tr("Select at least a row")); return; } QString ids; int i; int k; QList <int> rowCollection; ids = "("; for (i = 0; i < currentSelection.count(); i++) { current = currentSelection.at(i).row(); if (!rowCollection.contains(current)) rowCollection.append(current); } for (i=0;i<rowCollection.count();i++) { QSqlRecord record = model->record(rowCollection.at(i)); ids += record.value(0).toString(); ids += ","; } k = ids.length(); ids.truncate(k-1); ids += ")"; QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlRecord record = model->record(current); recordId = record.value(0).toString(); QString query; QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Delete current row"),tr("<center><h1><font color='red'>Warning !</font></h1>" "<h3>You are about to delete the current record</h3>" "<h2>Are you sure?</h2></center>"), QMessageBox::Yes | QMessageBox::No ); if (reply == QMessageBox::Yes) { query = "DELETE FROM "; query += tableName; query += " WHERE id_"; query += tableName; query += " IN "; query += ids; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Eroare"), getData.lastError().text()); return; } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Eroare"), model->lastError().text()); return; } if (model->rowCount() != 0) { current--; } refresh(current); QSqlRecord record = model->record(current); recordId = record.value(0).toString(); setModified(true); } if (model->rowCount() == 0) emit modelIsEmpty(true); else emit modelIsEmpty(false); } void QDbfEditor::openNewFile() { // Временная мера. Пока не сделан рефактоинг кода. if (modified) { QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Save"),tr("<center><h2>Do you want to save the changes?</h2></center>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if (reply == QMessageBox::Yes) { saveDbfFile(); } } QString currentDirectory; QSettings settings; currentDirectory= settings.value("dbfeditor/currentdir", "./").toString(); dbfFileName = QFileDialog::getOpenFileName(0, QObject::tr("Open File"),currentDirectory,"DBF Files(*.dbf);;All Files (*)"); if (dbfFileName.isEmpty()) { return; } emit fileOpened(dbfFileName); QFileInfo fileInfo(dbfFileName); currentDirectory = fileInfo.absolutePath(); settings.setValue("dbfeditor/currentdir", currentDirectory); openFile(dbfFileName,true); } void QDbfEditor::openDbfFile() { /* DBF File Header Byte offset Description 0 File type: 0x02 FoxBASE 0x03 FoxBASE+/Dbase III plus, no memo 0x30 Visual FoxPro 0x31 Visual FoxPro, autoincrement enabled 0x32 Visual FoxPro with field type Varchar or Varbinary 0x43 dBASE IV SQL table files, no memo 0x63 dBASE IV SQL system files, no memo 0x83 FoxBASE+/dBASE III PLUS, with memo 0x8B dBASE IV with memo 0xCB dBASE IV SQL table files, with memo 0xF5 FoxPro 2.x (or earlier) with memo 0xE5 HiPer-Six format with SMT memo file 0xFB FoxBASE 1 - 3 Last update (YYMMDD) 4 – 7 Number of records in file 8 – 9 Position of first data record 10 – 11 Length of one data record, including delete flag 12 – 27 Reserved 28 Table flags: 0x01 file has a structural .cdx 0x02 file has a Memo field 0x04 file is a database (.dbc) This byte can contain the sum of any of the above values. For example, the value 0x03 indicates the table has a structural .cdx and a Memo field. 29 Code page mark 30 – 31 Reserved, contains 0x00 32 – n Field subrecords The number of fields determines the number of field subrecords. One field subrecord exists for each field in the table. n+1 Header record terminator (0x0D) n+2 to n+264 A 263-byte range that contains the backlink, which is the relative path of an associated database (.dbc) file, information. If the first byte is 0x00, the file is not associated with a database. Therefore, database files always contain 0x00. Field Subrecords Structure Byte offset Description 0 – 10 Field name with a maximum of 10 characters. If less than 10, it is padded with null characters (0x00). 11 Field type: C – Character 255 bytes ASCII Y – Currency 8 bytes 64 bit integer, allways 4 decimal points N – Numeric F – Float Same as numeric 1 to 20 bytes in table D – Date yyyymmdd T – DateTime It's stored as an 8 byte field. The first 4 bytes stores the date as julian day number. The second 4 bytes stores the number of milliseconds after midnight. B – Double 8 bytes I – Integer 4 bytes L – Logical M – Memo 10 bytes ASCII integer in dBase FoxPro 4 bytes binary integer in Visual FoxPro G – General 4 byte reference to an OLE object C – Character (binary) M – Memo (binary) P – Picture 12 – 15 Displacement of field in record 16 Length of field (in bytes) 17 Number of decimal places 18 Field flags: 0x01 System Column (not visible to user) 0x02 Column can store null values 0x04 Binary column (for CHAR and MEMO only) 0x06 (0x02+0x04) When a field is NULL and binary (Integer, Currency, and Character/Memo fields) 0x0C Column is autoincrementing 19 - 22 Value of autoincrement Next value 23 Value of autoincrement Step value 24 – 31 Reserved */ QString query; QFile file; QByteArray fieldDescription; int i; int j; unsigned char a,b,c,d,e,f,g,h; double db; tableName = "d_table"; strTableName = "s_table"; file.setFileName(dbfFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("DBF open error")); return; } // QTextCodec::setCodecForCStrings(QTextCodec::codecForName(generalTextCodec.toAscii().data())); sizesHeader.clear(); sizesHeader = file.read(16); a = sizesHeader.at(4); b = sizesHeader.at(5); c = sizesHeader.at(6); d = sizesHeader.at(7); e = sizesHeader.at(8); f = sizesHeader.at(9); g = sizesHeader.at(10); h = sizesHeader.at(11); numberOfRecords = a + (b << 8) + (c << 16) + (d << 24); headerLength = e + (f << 8); recordLength = g + (h << 8); file.seek(0); dbfFileHeader = file.read(headerLength); file.seek(32); fieldDescriptions.clear(); fieldDescriptions = file.read(headerLength - 32); fieldDescriptions.truncate(fieldDescriptions.lastIndexOf('\x0D')); numberOfFields = fieldDescriptions.count() >> 5; qint16 tempOffset = 1; for (i=0;i<numberOfFields;i++) { fieldDescription = fieldDescriptions.mid(i*32,32); fieldsItem = new QFieldsItem; fieldsItem->fieldName = ""; j = 0; while (fieldDescription[j] != '\x00') { fieldsItem->fieldName += fieldDescription[j]; j++; } a = fieldDescription.at(12); b = fieldDescription.at(13); c = fieldDescription.at(14); d = fieldDescription.at(15); e = fieldDescription.at(16); f = fieldDescription.at(17); fieldsItem->fieldType = fieldDescription[11]; fieldsItem->fieldOffset = a + (b << 8) + (c << 16) + (d << 24); fieldsItem->fieldOffset = tempOffset; tempOffset += e; fieldsItem->fieldSize = e; fieldsItem->fieldDecimals = f; fieldsCollection.append(fieldsItem); } QSqlQuery getData(QSqlDatabase::database("dbfEditor")); query = "DROP TABLE IF EXISTS '"; query += tableName; query += "'"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } QString tempValue; query = "CREATE TABLE '"; query += tableName; query += "' ( 'id_"; query += tableName; query += "' integer primary key autoincrement,"; for (i=0; i<fieldsCollection.count(); ++i) { query += ("`"+fieldsCollection.at(i)->fieldName+"`"); if (fieldsCollection.at(i)->fieldType == "C") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "L") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "M") { if (fieldsCollection.at(i)->fieldSize == 10) { query += " numeric"; } if (fieldsCollection.at(i)->fieldSize == 4) { query += " blob"; } } else if (fieldsCollection.at(i)->fieldType == "N") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "F") { query += " text"; } else if (fieldsCollection.at(i)->fieldType == "D") { query += " text"; } else { query += " blob"; } if (i<(fieldsCollection.count()-1)) query += ",\n"; } query += ")"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } quint32 q; bool ok; for (q=0;q<numberOfRecords;q++) { query = "INSERT INTO "; query += tableName; query += " ("; for (j=0; j<fieldsCollection.count(); ++j) { query += ("`"+fieldsCollection.at(j)->fieldName+"`"); if (j<fieldsCollection.count()-1) query += ","; } query += ") VALUES ("; recordData.clear(); file.seek(headerLength + q*recordLength); recordData=file.read(recordLength); if (recordData.at(0) == '*') continue; QString tempDate; QString tempString; for (j=0; j<fieldsCollection.count(); j++) { fieldsItem = fieldsCollection.at(j); fieldsItem->fields = "'"; if (fieldsItem->fieldType == "D") { tempDate = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); if (tempDate == " ") fieldsItem->fields+=""; else { fieldsItem->fields += tempDate.mid(0,4); fieldsItem->fields += "-"; fieldsItem->fields += tempDate.mid(4,2); fieldsItem->fields += "-"; fieldsItem->fields += tempDate.mid(6,2); } } else if (fieldsItem->fieldType == "C") { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); fieldsItem->fields += tempString.replace("'","''"); } else if ((fieldsItem->fieldType == "N") || (fieldsItem->fieldType == "F")) { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); db = tempString.toDouble(&ok); tempString.setNum(db,'f',fieldsItem->fieldDecimals); fieldsItem->fields += tempString; } else if (fieldsItem->fieldType == "L") { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); fieldsItem->fields += tempString; } else if ((fieldsItem->fieldType == "M") && (fieldsItem->fieldSize == 10)) { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize); fieldsItem->fields += tempString; } else { tempString = recordData.mid(fieldsItem->fieldOffset,fieldsItem->fieldSize).toHex().toUpper(); fieldsItem->fields += tempString; } fieldsItem->fields += "'"; query += fieldsItem->fields; if (j<fieldsCollection.count()-1) query += ","; } query += ")"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } } query = "DROP TABLE IF EXISTS "; query += strTableName; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } query = "CREATE TABLE "; query += strTableName; query += " ( id_"; query += strTableName; query += " integer primary key autoincrement, \n"; query += "fieldName text, \n"; query += "fieldType text, \n"; query += "fieldLength numeric, \n"; query += "fieldDecimals numeric)"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } for (i=0; i<fieldsCollection.count(); i++) { query = "INSERT INTO "; query += strTableName; query += " (fieldName, fieldType, fieldLength, fieldDecimals) VALUES ('"; query += ("`"+fieldsCollection.at(i)->fieldName+"`"); query += "','"; query += fieldsCollection.at(i)->fieldType; query += "','"; tempValue.setNum(fieldsCollection.at(i)->fieldSize,10); query += tempValue; query += "','"; tempValue.setNum(fieldsCollection.at(i)->fieldDecimals,10); query += tempValue; query += "')"; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } } file.close(); } void QDbfEditor::saveDbfFile() { qint32 nr; QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; bool ok; int i; nr = 0; query = "SELECT count(*) FROM "; query += tableName; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } while (getData.next()) nr = getData.value(0).toString().toULong(&ok, 10); qint16 lnrt = nr; qint16 hnrt = nr >> 16; qint8 llnrt = lnrt ; qint8 hlnrt = lnrt >> 8; qint8 lhnrt = hnrt; qint8 hhnrt = hnrt >> 8; dbfFileHeader[4]= llnrt; dbfFileHeader[5]= hlnrt; dbfFileHeader[6]= lhnrt; dbfFileHeader[7]= hhnrt; QFile dbfFile; dbfFile.setFileName(dbfFileName+".temp"); if (!dbfFile.open(QIODevice::WriteOnly)) { QMessageBox::critical(0, tr("Error"), tr("DBF write error")); return; } dbfFile.write(dbfFileHeader); QString tempValue; QTextStream textStream(&tempValue); query = "SELECT "; for (i=0;i<fieldsCollection.size();i++) { fieldsItem = fieldsCollection.at(i); query += ("`"+fieldsItem->fieldName+"`"); if ( i != fieldsCollection.size()-1 ) query += ","; else query += " "; } query += " FROM "; query += tableName; getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(0, tr("Error"), getData.lastError().text()); return; } int l,l1,j; QString tempNumericValue; QDate tempDateValue; QString tempCharValue; QByteArray tempBinaryValue; while (getData.next()) { recordData.clear(); recordData.append(QChar(' ')); for (i=0;i<fieldsCollection.size();i++) { if ((fieldsCollection.at(i)->fieldType == "C") || (fieldsCollection.at(i)->fieldType == "L")) { tempCharValue = getData.value(i).toString(); tempValue = ""; l = fieldsCollection.at(i)->fieldSize; l1 = tempCharValue.length(); tempCharValue.truncate(l); tempValue = tempCharValue; for (j=0;j<l-l1;j++) tempValue+=" "; recordData.append(tempValue); } else if ((fieldsCollection.at(i)->fieldType == "N") || (fieldsCollection.at(i)->fieldType == "F") || ((fieldsCollection.at(i)->fieldType == "M") && (fieldsCollection.at(i)->fieldSize == 10))) { tempNumericValue = getData.value(i).toString().simplified(); tempValue = ""; l = fieldsCollection.at(i)->fieldSize; l1 = tempNumericValue.length(); tempNumericValue.truncate(l); for (j=0;j<l-l1;j++) tempValue+=" "; tempValue += tempNumericValue; recordData.append(tempValue); } else if (fieldsCollection.at(i)->fieldType == "D") { tempDateValue = getData.value(i).toDate(); if (tempDateValue.isNull()) tempValue = " "; else tempValue = tempDateValue.toString("yyyyMMdd"); recordData.append(tempValue); } else { tempBinaryValue = getData.value(i).toByteArray(); tempBinaryValue = tempBinaryValue.fromHex(tempBinaryValue); recordData.append(tempBinaryValue); } } dbfFile.write(recordData); } recordData.clear(); recordData.append('\x1A'); dbfFile.write(recordData); dbfFile.close(); QFile oldFile; oldFile.setFileName(dbfFileName); oldFile.remove(); dbfFile.rename(dbfFileName); setModified(false); } void QDbfEditor::fillCells() { QSqlQuery modelQuery = model->query(); QString oldQuery = modelQuery.lastQuery(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); QString query; QModelIndexList currentSelection = view->selectionModel()->selectedIndexes(); QModelIndexList currentRowSelection = view->selectionModel()->selectedRows(); QModelIndexList currentColumnSelection = view->selectionModel()->selectedColumns(); if (currentSelection.count() == 0) { QMessageBox::critical(this, tr("Error"), tr("Select at least a cell")); return; } QDbfDialog *d = new QDbfDialog(tr("Fill"), this); QSettings settings; d->resize(settings.value("dbfeditor/filledsize", QSize(140,40)).toSize()); QString sql = settings.value("dbfeditor/fillcommand", "").toString(); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("Fill value or expression"), d); QDbfLineEdit *t = new QDbfLineEdit(sql,d); label->setBuddy(t); QPushButton *okButton = new QPushButton(tr("OK"), d); QPushButton *cancelButton = new QPushButton(tr("Cancel"), d); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(okButton); buttonLayout->addWidget(cancelButton); mainLayout->addWidget(label); mainLayout->addWidget(t); mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(okButton, SIGNAL(clicked()), d, SLOT(accept())); connect(cancelButton, SIGNAL(clicked()), d, SLOT(reject())); d->setLayout(mainLayout); int i; if (d->exec()) { if (d->result() == QDialog::Accepted) { for (i=0;i<currentSelection.count();i++) { if (currentSelection.at(i).column() == 0) continue; fieldsItem = fieldsCollection.at(currentSelection.at(i).column()-1); if ((fieldsItem->fieldType == "M") || (fieldsItem->fieldType == "Y") || (fieldsItem->fieldType == "T") || (fieldsItem->fieldType == "B") || (fieldsItem->fieldType == "I") || (fieldsItem->fieldType == "G")) continue; query = "UPDATE "; query += tableName; query += " SET "; query += ("`"+fieldsItem->fieldName+"`"); query += "="; query += t->text().simplified(); QSqlRecord record = model->record(currentSelection.at(i).row()); query += " WHERE id_"; query += tableName; query += "="; query += record.value(0).toString(); getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } } model->setQuery(oldQuery, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(1); view->selectRow(0); setModified(true); } } settings.setValue("dbfeditor/fillcommand", t->text().simplified()); settings.setValue("dbfeditor/filledsize", d->size()); delete d; } void QDbfEditor::refresh(int current) { view->hideColumn(0); view->setAlternatingRowColors(true); view->resizeColumnsToContents(); view->selectColumn(0); view->selectRow(current); } void QDbfEditor::closeEvent(QCloseEvent *event) { if (modified) { QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Save"),tr("<center><h2>Do you want to save the changes?</h2></center>"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes ); if (reply == QMessageBox::Yes) { saveDbfFile(); } } writeSettings(); event->accept(); } void QDbfEditor::readDbtFile(int i) { /* dBASE III+ _______________________ _______ 0 | Number of next | ^ ^ 1 | available block | | | 2 | for appending data | | Header 3 | (binary) | | | |-----------------------| _|__v__ 4 | ( Reserved ) | | | | | | | | 7 | | | |-----------------------| | 8 | ( Reserved ) | | : : | 15 | | | |-----------------------| | 16 | Version no. (03h) | | |-----------------------| | 17 | (i.e. garbage) | | : : First block : : | 511| | | |=======================| _v_____ 512| | ^ | | | | | 512 Bytes | | text blocks : : | : : | | | | |-----------------------| _|_____ | Field terminator (1Ah)| | ^ |-----------------------| | |Terminating field | Field terminator (1Ah)| | |within the block *1 |-----------------------| _|__v__ : ( Unused ) : | 1023 : | |=======================| _v_____ | | ^ | | | | | 512 Bytes | | text blocks : : | : : | | | | | | _v_____ |=======================| *1 - field terminator Is reported to use only one field terminator (1Ah) - (FoxPro, Fox??) */ QByteArray memoData; QString dbtFileName = dbfFileName; int k = dbtFileName.length(); dbtFileName.truncate(k-1); dbtFileName += "t"; QFile file; file.setFileName(dbtFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("DBT open error")); return; } file.seek(i << 9); memoData = file.read(512); int p = memoData.indexOf('\x1A'); int q=1; while (p == -1) { file.seek((i+q) << 9); memoData.append(file.read(512)); p = memoData.indexOf('\x1A'); q++; } if (p==-1) p=0; memoData.truncate(p); //QString memoText = QString(memoData).toAscii(); //QByteArray encodedString = "..."; QTextCodec *codec = QTextCodec::codecForName("IBM850"); QString memoText = codec->toUnicode(memoData); QDbfDialog *dialog = new QDbfDialog(tr("Memo data"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/memoedsize", QSize(880,560)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("The text from the memo file"), dialog); //QPlainTextEdit *t = new QPlainTextEdit(memoText,dialog); QTextEdit *t = new QTextEdit(dialog); t->setPlainText(memoText); t->setReadOnly(true); t->setWordWrapMode(QTextOption::NoWrap); label->setBuddy(t); QFont font=t->font(); #ifdef UNIX font.setFamily("Monospace"); #else font.setFamily("Lucida Console"); #endif font.setItalic(false); t->setFont(font); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(label); mainLayout->addWidget(t); //mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/memoedsize", dialog->size()); delete dialog; } void QDbfEditor::readFptFile(int i) { /* Xbase: FoxPro Object and Memo Field Files (*.fpt) The file format is used by Fox Pro 2.x and later The size of the header is 512 bytes _______________________ _______ 00h / 0 | Number of next | ^ 00h / 1 | available block | | 00h / 2 | for appending data | Header 00h / 3 | (binary) *1| | |-----------------------| | 00h / 4 | ( Reserved ) | | 00h / 5 | | | |-----------------------| | 00h / 6 | Size of blocks N *1| | 00h / 7 | *2| | |-----------------------| | 00h / 8 | ( Reserved ) | | | | | | | | | (i.e. garbage) | | : : | : : | 00h / 511| | | |=======================| _v_____ 00h / 0| | ^ Used block | | | __ |=======================| | | | / 0| Record type *3| : : | / 1| *1| : : | / 2| | | | | / 3| | 00h / N| | | / |-----------------------| |=======================| _|_____/ 4| Length of memo field | 00h / 0| | | 5| *1| : : | 6| | : : | 7| | | | | |-----------------------| 00h / N| | _|_____ 8| Memo data | |=======================| | \ : : 0| | | \ N| | | | | \_____ |=======================| | | | : : | 00h / N| | _v_____ |=======================| *1. Big-endian. Binary value with high byte first. *2. Size of blocks in memo file (SET BLOCKSIZE). Default is 512 bytes. *3. Record type Value Description 00h Picture. This normally indicates that file is produced on a MacIntosh, since pictures on the DOS/Windows platform are "objects". 01h Memo 02h Object */ QByteArray memoData; QString dbtFileName = dbfFileName; unsigned char a,b,c,d; quint32 tipMemo; quint32 lengthMemo; quint32 memoBlockLength; int k = dbtFileName.length(); dbtFileName.truncate(k-3); if (dbfFileName.endsWith(".dbf")) dbtFileName += "fpt"; if (dbfFileName.endsWith(".DBF")) dbtFileName += "FPT"; QFile file; file.setFileName(dbtFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("FPT open error")); return; } file.seek(0); memoData = file.read(8); a = memoData.at(7); b = memoData.at(6); c = memoData.at(5); d = memoData.at(4); memoBlockLength = a + (b << 8) + (c << 16) + (d << 24); file.seek(i*memoBlockLength); memoData = file.read(8); a = memoData.at(3); b = memoData.at(2); c = memoData.at(1); d = memoData.at(0); tipMemo = a + (b << 8) + (c << 16) + (d << 24); a = memoData.at(7); b = memoData.at(6); c = memoData.at(5); d = memoData.at(4); lengthMemo = a + (b << 8) + (c << 16) + (d << 24); file.seek(i*memoBlockLength+8); memoData = file.read(lengthMemo); QString memoText = QString(memoData); QDbfDialog *dialog = new QDbfDialog(tr("Memo data"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/memoedsize", QSize(880,560)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("The text from the memo file"), dialog); QPlainTextEdit *t = new QPlainTextEdit(memoText,dialog); t->setReadOnly(true); label->setBuddy(t); QFont font=t->font(); #ifdef UNIX font.setFamily("Monospace"); #else font.setFamily("Lucida Console"); #endif font.setItalic(false); t->setFont(font); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(label); mainLayout->addWidget(t); //mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/memoedsize", dialog->size()); delete dialog; } void QDbfEditor::readDbt4File(int i) { /* dBASE IV _______________________ 0 | Number of next | ^ 1 | available block | | 2 | for appending data | Header 3 | (binary) | | |-----------------------| | 4 | ( Reserved ) | | | Size of blocks *1| | | | | 7 | | | |-----------------------| | 8 | DBF file name | | | without extention | | : : | 15 | | | |-----------------------| | 16 | Reserved (00h) | | |-----------------------| | 17 | ( Reserved ) | | 18 | | | 19 | | | |-----------------------| | 20 | Block length in bytes | | 21 | *4| | |-----------------------| | 22 | ( Reserved ) | | | | | | (i.e. garbage) | | : : | : : | 511| | | |=======================| _v_____ 1| | ^ Used block | | ^ __ |=======================| | | | / 0| ( Reserved ) | : : | / 1| | : : | / 2| FFh FFh 08h 00h | | | | / 3| | 511| | | / |-----------------------| |=======================| _|_____/ 4| Length of memo field | 1| | | 5| | : : | 6| | : : | 7| | | | | |-----------------------| 511| | _|_____ 8| Memo data *2| |=======================| | \ : : | | | \ N| | | | | \_____ |=======================| | | | | | 512 Bytes | | text blocks : : | : : | Unused block : : | __ |=======================| : : | / 0| Pointer to next free | : : | / 1| block | : : | / 2| | | | | / 3| | 511| | | / |-----------------------| |=======================| _|_____/ 4| Pointer to next used | 1| | | 5| block | : : | 6| | : : | 7| | | | | |-----------------------| 511| | _|_____ 8| ( Reserved ) | |=======================| | \ : : 1| | | \ N| | | | | \_____ |=======================| | | | : : | | | | |-----------------------| _|_____ | Field terminator (1Ah)| | ^ |-----------------------| | |Terminating field | Field terminator (1Ah)| | |within the block *3 |-----------------------| _|__v__ : ( Unused ) : | 511| : | |=======================| _v_____ | | ^ | | | | | 512 Bytes | | text blocks : : | : : | | | | | | _v_____ |=======================| *1. Size of blocks in memo file (SET BLOCKSIZE). Default is 512 bytes (FoxBase, dBASE IV ??) . *2. End of text mark is 0Dh 0Ah and line breaks are 8Dh 0Ah *3. Field terminator Is reported to use only one field terminator (1Ah) - (FoxPro, Fox??). *4. dBASE III files are marked as lenght = 1. */ QByteArray memoData; QString dbtFileName = dbfFileName; unsigned char a,b; //quint32 tipMemo; quint32 lengthMemo; //quint32 memoBlockLength; quint16 lengthInBlocks; int k = dbtFileName.length(); dbtFileName.truncate(k-3); dbtFileName += "dbt"; QFile file; file.setFileName(dbtFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("DBT open error")); return; } file.seek(0); memoData = file.read(512); a = memoData.at(21); b = memoData.at(20); lengthInBlocks = a + (b << 8); //file.seek(i*512*lengthInBlocks); file.seek(i*512); memoData = file.read(8); a = memoData.at(4); lengthMemo = a; //file.seek(i*512*lengthInBlocks+8); file.seek(i*512+8); memoData = file.read(lengthMemo-8); QString memoText = QString(memoData); QDbfDialog *dialog = new QDbfDialog(tr("Memo data"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/memoedsize", QSize(880,560)).toSize()); QVBoxLayout *mainLayout = new QVBoxLayout; QLabel *label = new QLabel(tr("The text from the memo file"), dialog); QPlainTextEdit *t = new QPlainTextEdit(memoText,dialog); t->setReadOnly(true); label->setBuddy(t); QFont font=t->font(); #ifdef UNIX font.setFamily("Monospace"); #else font.setFamily("Lucida Console"); #endif font.setItalic(false); t->setFont(font); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(label); mainLayout->addWidget(t); //mainLayout->addStretch(1); mainLayout->addLayout(buttonLayout); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/memoedsize", dialog->size()); delete dialog; } void QDbfEditor::helpDbf() { QDbfDialog *dialog = new QDbfDialog(tr("qtDbf documentation"), this); QSettings settings; dialog->resize(settings.value("dbfeditor/helpsize", QSize(860,540)).toSize()); QString dbfLocal = settings.value("dbflocal", "en").toString(); QVBoxLayout *mainLayout = new QVBoxLayout; QString dbfDirPath; #if (defined Q_OS_UNIX) || (defined Q_OS_OS2) if (QFile::exists("/usr/local/share/qtdbf")) { dbfDirPath = "/usr/local/share/qtdbf"; } else { if (QFile::exists("/usr/share/qtdbf")) { dbfDirPath = "/usr/share/qtdbf"; } else { dbfDirPath = qApp->applicationDirPath(); } } #else dbfDirPath = qApp->applicationDirPath(); #endif dbfDirPath += "/help/qtdbf_"; dbfDirPath += dbfLocal; dbfDirPath += ".html"; QFile f(dbfDirPath); QTextEdit *t = new QTextEdit(this); t->setReadOnly(true); if (f.open(QIODevice::ReadOnly)) { QByteArray data = f.readAll(); QTextCodec *codec = Qt::codecForHtml(data); QString str = codec->toUnicode(data); t->setHtml(str); } else { t->setText(tr("Help file missing").append("\n").append(f.errorString())); } QPushButton *aboutButton = new QPushButton(tr("About"), dialog); QPushButton *aboutQtButton = new QPushButton(tr("About Qt"), dialog); QPushButton *closeButton = new QPushButton(tr("Close"), dialog); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addWidget(aboutButton); buttonLayout->addWidget(aboutQtButton); buttonLayout->addStretch(1); buttonLayout->addWidget(closeButton); mainLayout->addWidget(t); mainLayout->addLayout(buttonLayout); connect(aboutButton, SIGNAL(clicked()), this, SLOT(about())); connect(aboutQtButton, SIGNAL(clicked()), qApp, SLOT(aboutQt())); connect(closeButton, SIGNAL(clicked()), dialog, SLOT(accept())); dialog->setLayout(mainLayout); dialog->exec(); settings.setValue("dbfeditor/helpsize", dialog->size()); delete dialog; } void QDbfEditor::configApp() { QDetaliiTabDialog *tabDialog = new QDetaliiTabDialog(strTableName); tabDialog->exec(); delete tabDialog; } void QDbfEditor::about() { QString explic; explic = tr("<b align='center'>qtDbf</b> <p>- an open source, multiplatform DBF viewer and editor written in Qt and using SQLite.</p>"); QMessageBox::about(this,"qtDbf 1.0", explic); } void QDbfEditor::sortDbf(const QModelIndex& index) { int current = view->currentIndex().row(); int c = index.column(); QString query; order = fieldsCollection.at(c-1)->fieldName; query = "SELECT * FROM "; query += tableName; if (where != "") query += " WHERE " + where; if (order != "") query += " ORDER BY " + order; model->setQuery(query, QSqlDatabase::database("dbfEditor")); if (model->lastError().isValid()) { QMessageBox::critical(this, tr("Error"), model->lastError().text()); return; } refresh(current); } void QDbfEditor::calculator() { QCalculatorDialog *d = new QCalculatorDialog(tr("Calculator"), this); d->exec(); delete d; } void QDbfEditor::setToolButtonIconSize(int i) { QSize size = QSize(i,i); editButton->setIconSize(size); openButton->setIconSize(size); insertButton->setIconSize(size); deleteButton->setIconSize(size); saveButton->setIconSize(size); configButton->setIconSize(size); fillButton->setIconSize(size); calcButton->setIconSize(size); helpButton->setIconSize(size); quitButton->setIconSize(size); filterButton->setIconSize(size); agregatButton->setIconSize(size); } QDbfEditor::~QDbfEditor() { } void QDbfEditor::agregat() { int c = view->currentIndex().column(); DialogAgregat *dlg = new DialogAgregat(fieldsCollection,c-1,this); if (dlg->exec() == QDialog::Accepted) { QString query = "SELECT "+dlg->getFieldPart()+" FROM "; query += tableName; if (where != "") query += " WHERE " + where; dlg->deleteLater(); QSqlQuery getData(QSqlDatabase::database("dbfEditor")); getData.prepare(query); getData.exec(); if (getData.lastError().isValid()) { QMessageBox::critical(this, tr("Error"), getData.lastError().text()); return; } if (getData.next()) { QString val = getData.value(0).toString(); QMessageBox msgBox(QMessageBox::Information, tr("Result"), val, QMessageBox::Save | QMessageBox::Close, this); msgBox.setButtonText(QMessageBox::Save, tr("Copy to Clipboard")); if (msgBox.exec()==QMessageBox::Save) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(val); } } } }
33.908076
139
0.475373
1c09fa25e31e9f9eb1cf698f769c434748b626f3
24,246
hpp
C++
src/pbdcex.core.hpp
jj4jj/pbdcex
5b0d2bbdaebf94cceee47350819dae93a88a4cc8
[ "MIT" ]
5
2015-12-24T19:03:41.000Z
2016-09-01T02:32:58.000Z
src/pbdcex.core.hpp
jj4jj/pbdcex
5b0d2bbdaebf94cceee47350819dae93a88a4cc8
[ "MIT" ]
null
null
null
src/pbdcex.core.hpp
jj4jj/pbdcex
5b0d2bbdaebf94cceee47350819dae93a88a4cc8
[ "MIT" ]
2
2019-08-21T19:58:00.000Z
2021-12-22T23:05:16.000Z
#ifndef __PBDCEX_CORE_EX_HPP_XX__ #define __PBDCEX_CORE_EX_HPP_XX__ #pragma once #include <cstdio> #include <cstdarg> #include <cstdint> #include <cstring> #include <cassert> #include <string> #include <algorithm> namespace pbdcex { namespace util { static inline uint64_t FNV_1A_Hash64(const unsigned char * data, size_t zdata){ uint64_t hashv = 14695981039346656037ULL; if (zdata > 0){ for (size_t i = 0; i < zdata; ++i) { // fold in another byte hashv ^= (uint64_t)data[i]; hashv *= 1099511628211ULL; } } else { for (size_t i = 0; data[i] != 0 ; ++i) { // fold in another byte hashv ^= (uint64_t)data[i]; hashv *= 1099511628211ULL; } } hashv ^= hashv >> 32; return (hashv); } static inline size_t FNV_1A_Hash32(const unsigned char * data, size_t zdata){ uint32_t hashv = 2166136261U; if (zdata > 0){ for (size_t i = 0; i < zdata; ++i) { // fold in another byte hashv ^= (uint32_t)data[i]; hashv *= 16777619U; } } else { for (size_t i = 0; data[i] != 0; ++i) { // fold in another byte hashv ^= (uint32_t)data[i]; hashv *= 16777619U; } } return (hashv); } static inline bool _is_prime(size_t n){ for (size_t i = 2; i < n / 2; ++i){ if (n % i == 0){ return false; } } return true; } static inline size_t _next_prime_bigger(size_t n){ ++n; while (true){ if (util::_is_prime(n)){ return n; } ++n; } } static inline size_t _next_prime_smaller(size_t n){ --n; while (true){ if (util::_is_prime(n)){ return n; } --n; } } template<class T> struct Hash { size_t operator ()(const T & td) const { return td.hash(); } }; template<> struct Hash<int8_t> { size_t operator ()(const int8_t & td) const { return td; } }; template<> struct Hash<uint8_t> { size_t operator ()(const uint8_t & td) const { return td; } }; template<> struct Hash<int16_t> { size_t operator ()(const int16_t & td) const { return td; } }; template<> struct Hash<uint16_t> { size_t operator ()(const uint16_t & td) const { return td; } }; template<> struct Hash<int32_t> { size_t operator ()(const int32_t & td) const { return td; } }; template<> struct Hash<uint32_t> { size_t operator ()(const uint32_t & td) const { return td; } }; template<> struct Hash<int64_t> { size_t operator ()(const int64_t & td) const { return td; } }; template<> struct Hash<uint64_t> { size_t operator ()(const uint64_t & td) const { return td; } }; template<> struct Hash<float> { size_t operator ()(const float & td) const { return (size_t)td; } }; template<> struct Hash<double> { size_t operator ()(const double & td) const { return (size_t)td; } }; } inline size_t hash_code_merge_multi_value(size_t vs[], size_t n){ //64bytes optimal todo return util::FNV_1A_Hash64((unsigned char*)&vs[0], n*sizeof(size_t)); } template<class T, class P> struct serializable_t { int dumps(::std::string & str) const { P pm; reinterpret_cast<const T*>(this)->convto(pm); if (!pm.SerializeToString(&str)) { return -1; } return 0; } int loads(const ::std::string & str){ P pm; if (!pm.ParseFromString(str)){ return -1; } int ret = reinterpret_cast<T*>(this)->check_convfrom(pm); if (ret){ return ret; } reinterpret_cast<T*>(this)->convfrom(pm); return 0; } int loads(const char * buff, int ibuff){ P pm; if (!pm.ParseFromArray(buff, ibuff)){ return -1; } int ret = reinterpret_cast<T*>(this)->check_convfrom(pm); if (ret){ return ret; } reinterpret_cast<T*>(this)->convfrom(pm); return 0; } const char * debugs(::std::string & str) const { P pm; reinterpret_cast<const T*>(this)->convto(pm); str = pm.ShortDebugString(); return str.c_str(); }; }; template<size_t lmax> struct string_t { char data[lmax]; ///////////////////////////////////////////////////////////// size_t hash() const { //fnv return util::FNV_1A_Hash64((unsigned char *)data, 0); } static string_t & assign(string_t & str, const char * cs){ str.assign(cs); return str; } void construct(){ this->data[0] = 0; } size_t format(const char * fmt, ...){ va_list ap; va_start(ap, fmt); size_t n=vsnprintf(data, lmax-1, fmt, ap); data[lmax-1]=0; va_end(ap); return n; } int assign(const char * s){ if (!s){ return 0;} size_t l = strlen(s); if (l > lmax){ l = lmax - 1; } memcpy(data, s, l); data[l]=0; return l; } int assign(const ::std::string & s){ return this->assign(s.data()); } string_t & operator = (const char * s) { this->assign(s); return *this; } string_t & operator = (const ::std::string & str) { this->assign(str); return *this; } int clone(char * s, int len) const { if (!s){ return 0; } int xlen = this->length(); if (xlen > len){ xlen = len - 1; } memcpy(s, data, xlen); data[xlen] = 0; return xlen; } operator char * (){ return data; } size_t length() const { return strlen(data); } bool operator == (const string_t & rhs) const { return compare(rhs) == 0; } bool operator < (const string_t & rhs) const { return compare(rhs) < 0; } bool operator > (const string_t & rhs) const { return compare(rhs) > 0; } int compare(const string_t & rhs) const { return strcmp(data, rhs.data); } }; template<size_t lmax, class LengthT = unsigned int> struct bytes_t { unsigned char data[lmax]; LengthT length; ////////////////////////////////////////////////////// size_t hash() const { //fnv return util::FNV_1A_Hash64(data, length); } void construct(){ this->data[0] = 0; this->length = 0; } LengthT assign(const char * s, int len){ LengthT l = len < (int)length ? len : length; memcpy(data, s, l); return l; } LengthT assign(const ::std::string & s){ return this->assign(s.data(), s.length()); } LengthT clone(char * s, int len) const { LengthT l = len < (int)length ? len : length; memcpy(s, data, l); return l; } bool operator == (const bytes_t & rhs) const { return compare(rhs) == 0; } bool operator < (const bytes_t & rhs) const { return compare(rhs) < 0; } bool operator > (const bytes_t & rhs) const { return compare(rhs) > 0; } int compare(const bytes_t & rhs) const { if (length < rhs.length){ return memcmp(data, rhs.data, length); } else { return memcmp(data, rhs.data, rhs.length); } } }; template<class T, size_t cmax, class LengthT=uint32_t> struct array_t { T list[cmax]; LengthT count; ///////////////////////////////// size_t hash() const { //five element if (this->count == 0U){ return 13131313U; } size_t hvs[5] = { 0 }; size_t hvl = this->count; size_t gap = 1; auto hf = util::Hash<T>(); if (this->count > 5U){ hvl = 5; gap = this->count / 5U; } for (LengthT i = 0; i < this->count; i += gap) { hvs[i] = hf(this->list[i]); } return util::FNV_1A_Hash64((unsigned char *)hvs, hvl*sizeof(size_t)); } void construct(){ count = 0; } size_t capacity() const { return cmax; } bool full() const { return this->count >= cmax; } bool empty() const { return this->count == 0; } void clear() { this->count = 0; } bool operator == (const array_t & rhs) const { return compare(rhs) == 0; } bool operator < (const array_t & rhs) const { return compare(rhs) < 0; } bool operator > (const array_t & rhs) const { return compare(rhs) > 0; } int compare(const array_t & rhs) const { if (count < rhs.count){ for (LengthT i = 0; i < count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } else { for (LengthT i = 0; i < rhs.count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } return (int)(count - rhs.count); } //linear list/////////////////////////////////////// int lfind(const T & tk) const { for (LengthT i = 0; i < count && i < cmax; ++i){ if (list[i] == tk){ return i; } } return -1; } int lappend(const T & td, bool shift_overflow = false){ if (count >= cmax && !shift_overflow){ return -1; } if (count < cmax){ list[count] = td; ++count; return 0; } else { if (cmax > 0){ memmove(list, list + 1, (cmax - 1)*sizeof(T)); list[cmax - 1] = td; } } return 0; } int lremove(int idx, bool swap_remove = false){ if (idx < 0 || (LengthT)idx >= count){ return -1; } if (swap_remove){ list[idx] = list[cmax - 1]; //list[cmax - 1].construct(); } else { memmove(list + idx, list + idx + 1, (count - idx - 1)*sizeof(T)); } --count; return 0; } int linsert(int idx, const T & td, bool overflow_shift = false){ if (count >= cmax && !overflow_shift){ return -1; } if ((LengthT)idx >= count){ idx = count; } else if (idx < 0){ idx = 0; } if ((LengthT)idx == count){ return lappend(td, overflow_shift); } //--overlay------idx------>-----idx+1------------------------------ assert(count <= cmax); if (count == cmax){ memmove(list + idx + 1, list + idx, (cmax - 1 - idx)*sizeof(T)); list[idx] = td; } else { memmove(list + idx + 1, list + idx, (count - idx)*sizeof(T)); list[idx] = td; ++count; } return 0; } void lsort(array_t & out) const { memcpy(&out, this, sizeof(*this)); ::std::sort(out.list, out.list + out.count); } ////////////////////////////////////////////////////////// /////////////////////binary-seaching////////////////////// int bfind(const T & tk) const { LengthT idx1st = lower_bound(tk); if (idx1st < count && list[idx1st] == tk){ return idx1st; } return -1; } int binsert(const T & td, bool overflow_shift = false, bool uniq = false) { LengthT idx = lower_bound(td); if (uniq && idx < count && list[idx] == td) { return -1; } return linsert(idx, td, overflow_shift); } int bremove(const T & tk){ int idx = bfind(tk); if (idx < 0){ return -1;} return lremove(idx, false); } LengthT lower_bound(const T & tk) const { const T * p = ::std::lower_bound(list, list + count, tk); return (p - list); } LengthT upper_bound(const T & tk) const { const T * p = ::std::upper_bound(list, list + count, tk); return (p - list); } T & operator [](size_t idx){ assert(idx < count); return list[idx]; } const T & operator [](size_t idx) const { assert(idx < count); return list[idx]; } }; template<class T, size_t cmax> struct mmpool_t { typedef uint64_t mmpool_bit_block_t; //typedef unsigned long long mmpool_bit_block_t; #define mmpool_bit_block_byte_sz (sizeof(mmpool_bit_block_t)) #define mmpool_bit_block_bit_sz (8*mmpool_bit_block_byte_sz) #define mmpool_bit_block_count ((cmax+mmpool_bit_block_bit_sz-1)/mmpool_bit_block_bit_sz) typedef array_t<T, mmpool_bit_block_count*mmpool_bit_block_bit_sz> allocator_t; allocator_t allocator_; mmpool_bit_block_t bmp_[mmpool_bit_block_count]; size_t used_; ///////////////////////////////////////////////////////////////////////////////////////// void construct(){ memset(this, 0, sizeof(*this)); allocator_.count = cmax; used_ = 0; } const allocator_t & allocator() { return allocator_; } size_t alloc(){ if (used() >= capacity()){ return 0; //full } //1.find first 0 set 1 size_t x,i; for (i = 0, x = 0; i < mmpool_bit_block_count; ++i){ if((x = __builtin_ffsll(~(bmp_[i])))){ break; } } if(x != 0){ bmp_[i] |= (1ULL<<(x-1));//set 1 size_t id=i*mmpool_bit_block_bit_sz+x; ++used_; new (&(allocator_.list[id - 1]))T(); return id; } else { return 0; } } size_t id(const T * p) const { assert(p >= allocator_.list && p < allocator_.list + cmax); return 1 + (p - allocator_.list); } T * ptr(size_t id) { if(id > 0 && id <= capacity() && isbusy(id)){ return &(allocator_.list[id-1]); } else { return NULL; } } bool isbusy(size_t id){ assert(id > 0); size_t idx=id-1; return bmp_[idx/mmpool_bit_block_bit_sz]&(1ULL<<(idx%mmpool_bit_block_bit_sz)); } size_t capacity() const { return cmax; } bool empty() const { return used() == 0; } size_t used() const { return used_; } size_t next(size_t it) const { if (used_ == 0){ return 0; } bool head = true; //(it+1)-1 = idx uint32_t pos_bit_ffs = 0; for (size_t idx = it / mmpool_bit_block_bit_sz, pos_bit_offset = it % mmpool_bit_block_bit_sz; idx < sizeof(bmp_) / sizeof(bmp_[0]); ++idx) { if (!head) { pos_bit_offset = 0; } else { head = false; } if (bmp_[idx] != 0ULL) { pos_bit_ffs = __builtin_ffsll(bmp_[idx] >> pos_bit_offset); if (pos_bit_ffs > 0) { return idx*mmpool_bit_block_bit_sz + pos_bit_offset + pos_bit_ffs; } } } return 0; } void free(size_t id){ assert(id > 0); size_t idx = id - 1; if(isbusy(id)){ //set 0 bmp_[idx / mmpool_bit_block_bit_sz] &= (~(1ULL << (idx%mmpool_bit_block_bit_sz))); --used_; allocator_.list[idx].~T(); } } }; //multi layer hash table implementation //---------- //------------------ //---------------------------- //collision strategy : //1.create a link list in multiple layer //2.in last max layer linear probe solving template<class T, size_t cmax, size_t layer = 3, class hcfT = util::Hash<T>> struct hashtable_t { struct hashmap_entry_t { size_t id; size_t next; size_t hco; }; struct { size_t offset; size_t count; } hash_layer_segment[layer]; #define hash_entry_index_size (layer*cmax*150/100) typedef mmpool_t<T, cmax> pool_t; typedef array_t<hashmap_entry_t, hash_entry_index_size+8> index_t; index_t index_; pool_t mmpool_; size_t stat_probe_insert; size_t stat_insert; size_t stat_probe_read; size_t stat_hit_read; //////////////////////////////////////////////////////////// void construct(){ memset(&index_, 0, sizeof(index_)); index_.count = hash_entry_index_size; mmpool_.construct(); stat_probe_insert = stat_insert = stat_hit_read = stat_probe_read = 1;//for div 0 error //bigger and bigger but max is limit hash_layer_segment[0].offset = 1; size_t hash_layer_max_size = util::_next_prime_bigger(cmax); hash_layer_segment[layer - 1].count = hash_layer_max_size; for (int i = layer - 2 ; i >= 0; --i){ hash_layer_segment[i].count = util::_next_prime_smaller(hash_layer_segment[i + 1].count); } for (size_t i = 1; i < layer; ++i){ hash_layer_segment[i].offset = hash_layer_segment[i - 1].offset + hash_layer_segment[i - 1].count; } assert(hash_entry_index_size >= hash_layer_segment[layer - 1].count + hash_layer_segment[layer - 1].offset); } const pool_t & mmpool() const {return mmpool_;} int load(int rate = 100) const { return mmpool_.used() * rate / index_.capacity(); } int factor(){ return cmax * 100 / index_.capacity(); } int hit(int rate = 100) const { return stat_hit_read * rate / stat_probe_read; } int collision() const { return stat_probe_insert / stat_insert; } const char * layers(::std::string & str) const { for (int i = 0; i < layer; ++i){ str.append("[" + ::std::to_string(this->hash_layer_segment[i].offset) + "," + ::std::to_string(this->hash_layer_segment[i].count) + ")"); } return str.c_str(); } const char * stat(::std::string & str){ str += "mbytes size:" + ::std::to_string(sizeof(*this)) + " mused:" + ::std::to_string(this->mmpool().used()) +"/"+::std::to_string(cmax) + " musage:" + ::std::to_string(this->mmpool().used() / cmax) + " iload:" + ::std::to_string(this->load()) + " ihit:" + ::std::to_string(this->hit()) + " ifactor:" + ::std::to_string(this->factor()) + " icollision:" + ::std::to_string(this->collision()) + " ilayers:" + ::std::to_string(layer); return this->layers(str); } bool empty() const { return mmpool_.empty(); } bool full() const { return mmpool_.used() >= cmax; } size_t next_slot(size_t hc, size_t ref){ assert(ref > 0); assert(index_.list[ref].next == 0); size_t find_slot = 0; if (ref < hash_layer_segment[layer - 1].offset){ for (size_t i = 0; i < layer - 1; ++i){ ++stat_probe_insert; find_slot = hash_layer_segment[i].offset + hc % hash_layer_segment[i].count; if (0 == index_.list[find_slot].id){ return find_slot; } } } //next one idle find_slot = ref; while (true){ ++stat_probe_insert; find_slot = hash_layer_segment[layer - 1].offset + (find_slot + 1) % hash_layer_segment[layer - 1].count; if (0 == index_.list[find_slot].id){ return find_slot; } } assert(false); return 0; } T * insert(const T & k){ if (full()){ return NULL; //full } //need to optimalization size_t hco = hcfT()(k); size_t idx = 1 + hco % hash_layer_segment[0].count; T * pv = NULL; while(idx && index_.list[idx].id){//find collision queue available ++stat_probe_insert; pv = mmpool_.ptr(index_.list[idx].id); if (index_.list[idx].hco == hco && *pv == k){ return NULL; } if(index_.list[idx].next == 0){ break; } idx = index_.list[idx].next; } if(idx > 0){ //valid idx if(index_.list[idx].id > 0){ //link list tail assert(index_.list[idx].next == 0); size_t npos = next_slot(hco, idx); assert(npos > 0 && index_.list[npos].id == 0); size_t hid = mmpool_.alloc(); if(hid == 0){ return NULL; } //#list append collision queue index_.list[idx].next = npos; index_.list[npos].id = hid; index_.list[npos].hco = hco; index_.list[npos].next = 0; ++stat_insert; pv = mmpool_.ptr(hid); *pv = k; return pv; } else { //head pos or in layer link list node size_t hid = mmpool_.alloc(); if(hid == 0){ return NULL; } hashmap_entry_t & he = index_.list[idx]; he.id = hid; he.hco = hco; ++stat_insert; pv = mmpool_.ptr(hid); *pv = k; return pv; } } return NULL; } int remove(const T & k){ //need to optimalization size_t hco = hcfT()(k); size_t idx = 1 + hco % hash_layer_segment[0].count; size_t pidx = 0; size_t ltidx = hash_layer_segment[layer - 1].offset + hco % hash_layer_segment[layer - 1].count; while(idx){ if(index_.list[idx].id){ T * p = mmpool_.ptr(index_.list[idx].id); if (index_.list[idx].hco == hco && *p == k){ mmpool_.free(index_.list[idx].id); if (idx < hash_layer_segment[layer - 1].offset || idx == ltidx){ //middle layer index_.list[idx].id = 0; //just erase it (no change list) index_.list[idx].hco = 0; //just erase it (no change list) return 0; } assert(pidx > 0); index_.list[idx].id = 0; index_.list[idx].hco = 0; index_.list[pidx].next = index_.list[idx].next; index_.list[idx].next = 0; return 0; } } pidx = idx; idx = index_.list[idx].next; } return -1; } T * find(const T & k){ //need to optimalization size_t hco = hcfT()(k); size_t idx = 1 + hco % hash_layer_segment[0].count; while(idx){ ++stat_probe_read; if (index_.list[idx].id){ T * pv = mmpool_.ptr(index_.list[idx].id); if (index_.list[idx].hco == hco && *pv == k){ ++stat_hit_read; return pv; } } idx = index_.list[idx].next; } return NULL; } }; }; #endif
30.23192
117
0.471542
1c0f8cdf4689a866f0b5c92700272cdaa0d66e4e
5,951
cpp
C++
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
10
2017-07-22T13:04:45.000Z
2021-12-22T10:02:32.000Z
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
null
null
null
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
3
2017-05-06T20:31:43.000Z
2020-07-01T01:45:37.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved // Plugin written by Philipp Buerki. Copyright 2017. All Rights reserved.. #include "../OnlineSubsystemB3atZUtils/Public/B3atZOnlineBeacon.h" #include "Engine/NetConnection.h" #include "EngineGlobals.h" #include "Engine/Engine.h" DEFINE_LOG_CATEGORY(LogBeacon); AB3atZOnlineBeacon::AB3atZOnlineBeacon(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), NetDriver(nullptr), BeaconState(EBeaconState::DenyRequests) { NetDriverName = FName(TEXT("BeaconDriver")); } bool AB3atZOnlineBeacon::InitBase() { UE_LOG(LogTemp, Warning, TEXT("B3atZOnlineBeacon InitBase")); NetDriver = GEngine->CreateNetDriver(GetWorld(), NAME_BeaconNetDriver); if (NetDriver != nullptr) { UE_LOG(LogTemp, Warning, TEXT("B3atZOnlineBeacon InitBase CreatedNetDriver is valid")); HandleNetworkFailureDelegateHandle = GEngine->OnNetworkFailure().AddUObject(this, &AB3atZOnlineBeacon::HandleNetworkFailure); SetNetDriverName(NetDriver->NetDriverName); return true; } return false; } void AB3atZOnlineBeacon::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } Super::EndPlay(EndPlayReason); } bool AB3atZOnlineBeacon::HasNetOwner() const { // Beacons are their own net owners return true; } void AB3atZOnlineBeacon::DestroyBeacon() { UE_LOG(LogBeacon, Verbose, TEXT("Destroying beacon %s, netdriver %s"), *GetName(), NetDriver ? *NetDriver->GetDescription() : TEXT("NULL")); GEngine->OnNetworkFailure().Remove(HandleNetworkFailureDelegateHandle); if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } Destroy(); } void AB3atZOnlineBeacon::HandleNetworkFailure(UWorld *World, UNetDriver *InNetDriver, ENetworkFailure::Type FailureType, const FString& ErrorString) { if (InNetDriver && InNetDriver->NetDriverName == NetDriverName) { UE_LOG(LogBeacon, Verbose, TEXT("NetworkFailure %s: %s"), *GetName(), ENetworkFailure::ToString(FailureType)); OnFailure(); } } void AB3atZOnlineBeacon::OnFailure() { GEngine->OnNetworkFailure().Remove(HandleNetworkFailureDelegateHandle); if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } } void AB3atZOnlineBeacon::OnActorChannelOpen(FInBunch& Bunch, UNetConnection* Connection) { Connection->OwningActor = this; Super::OnActorChannelOpen(Bunch, Connection); } bool AB3atZOnlineBeacon::IsRelevancyOwnerFor(const AActor* ReplicatedActor, const AActor* ActorOwner, const AActor* ConnectionActor) const { bool bRelevantOwner = (ConnectionActor == ReplicatedActor); return bRelevantOwner; } bool AB3atZOnlineBeacon::IsNetRelevantFor(const AActor* RealViewer, const AActor* ViewTarget, const FVector& SrcLocation) const { // Only replicate to the owner or to connections of the same beacon type (possible that multiple UNetConnections come from the same client) bool bIsOwner = GetNetConnection() == ViewTarget->GetNetConnection(); bool bSameBeaconType = GetClass() == RealViewer->GetClass(); return bOnlyRelevantToOwner ? bIsOwner : bSameBeaconType; } EAcceptConnection::Type AB3atZOnlineBeacon::NotifyAcceptingConnection() { check(NetDriver); if(NetDriver->ServerConnection) { // We are a client and we don't welcome incoming connections. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingConnection: Client refused")); return EAcceptConnection::Reject; } else if(BeaconState == EBeaconState::DenyRequests) { // Server is down UE_LOG(LogNet, Log, TEXT("NotifyAcceptingConnection: Server %s refused"), *GetName()); return EAcceptConnection::Reject; } else //if(BeaconState == EBeaconState::AllowRequests) { // Server is up and running. UE_LOG(LogNet, Log, TEXT("B3atZOnlineBeacon NotifyAcceptingConnection: Server %s accept"), *GetName()); return EAcceptConnection::Accept; } } void AB3atZOnlineBeacon::NotifyAcceptedConnection(UNetConnection* Connection) { check(NetDriver != nullptr); check(NetDriver->ServerConnection == nullptr); UE_LOG(LogNet, Log, TEXT("NotifyAcceptedConnection: Name: %s, TimeStamp: %s, %s"), *GetName(), FPlatformTime::StrTimestamp(), *Connection->Describe()); } bool AB3atZOnlineBeacon::NotifyAcceptingChannel(UChannel* Channel) { check(Channel); check(Channel->Connection); check(Channel->Connection->Driver); UNetDriver* Driver = Channel->Connection->Driver; check(NetDriver == Driver); if (Driver->ServerConnection) { // We are a client and the server has just opened up a new channel. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel %i/%i client %s"), Channel->ChIndex, (int32)Channel->ChType, *GetName()); if (Channel->ChType == CHTYPE_Actor) { // Actor channel. UE_LOG(LogNet, Log, TEXT("Client accepting actor channel")); return 1; } else if (Channel->ChType == CHTYPE_Voice) { // Accept server requests to open a voice channel, allowing for custom voip implementations // which utilize multiple server controlled voice channels. UE_LOG(LogNet, Log, TEXT("Client accepting voice channel")); return 1; } else { // Unwanted channel type. UE_LOG(LogNet, Log, TEXT("Client refusing unwanted channel of type %i"), (uint8)Channel->ChType); return 0; } } else { // We are the server. if (Channel->ChIndex == 0 && Channel->ChType == CHTYPE_Control) { // The client has opened initial channel. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel Control %i server %s: Accepted"), Channel->ChIndex, *GetFullName()); return 1; } else { // Client can't open any other kinds of channels. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel %i %i server %s: Refused"), (uint8)Channel->ChType, Channel->ChIndex, *GetFullName()); return 0; } } } void AB3atZOnlineBeacon::NotifyControlMessage(UNetConnection* Connection, uint8 MessageType, FInBunch& Bunch) { }
31.321053
152
0.750294
1c11aa81d8d5c87a5eba9e1c34588fa89aa6edaa
7,208
cpp
C++
src/tests/unit/cpu/shape_inference_test/interpolate_shape_inference.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
1
2019-09-22T01:05:07.000Z
2019-09-22T01:05:07.000Z
src/tests/unit/cpu/shape_inference_test/interpolate_shape_inference.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
58
2020-11-06T12:13:45.000Z
2022-03-28T13:20:11.000Z
src/tests/unit/cpu/shape_inference_test/interpolate_shape_inference.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2
2019-09-20T01:33:37.000Z
2019-09-20T08:42:11.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <interpolate_shape_inference.hpp> #include <openvino/op/constant.hpp> #include <openvino/op/interpolate.hpp> #include <openvino/op/parameter.hpp> #include <utils/shape_inference/shape_inference.hpp> #include <utils/shape_inference/static_shape.hpp> using namespace ov; using InterpolateMode = op::v4::Interpolate::InterpolateMode; using CoordinateTransformMode = op::v4::Interpolate::CoordinateTransformMode; using Nearest_mode = op::v4::Interpolate::NearestMode; using ShapeCalcMode = op::v4::Interpolate::ShapeCalcMode; static std::shared_ptr<op::v4::Interpolate> build_InterpolateV4() { op::v4::Interpolate::InterpolateAttrs attrs; attrs.mode = InterpolateMode::NEAREST; attrs.shape_calculation_mode = ShapeCalcMode::SCALES; attrs.coordinate_transformation_mode = CoordinateTransformMode::HALF_PIXEL; attrs.nearest_mode = Nearest_mode::ROUND_PREFER_FLOOR; attrs.antialias = false; attrs.pads_begin = {0, 0, 0, 0}; attrs.pads_end = {0, 0, 0, 0}; attrs.cube_coeff = -0.75; auto input_data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto sizes = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic()); auto scales = std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic()); auto axes = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic()); auto interpolate = std::make_shared<op::v4::Interpolate>(input_data, sizes, scales, axes, attrs); return interpolate; } static std::shared_ptr<op::v4::Interpolate> build_InterpolateV4ConstantInput() { op::v4::Interpolate::InterpolateAttrs attrs; attrs.mode = InterpolateMode::NEAREST; attrs.shape_calculation_mode = ShapeCalcMode::SCALES; attrs.coordinate_transformation_mode = CoordinateTransformMode::HALF_PIXEL; attrs.nearest_mode = Nearest_mode::ROUND_PREFER_FLOOR; attrs.antialias = false; attrs.pads_begin = {0, 0, 0, 0}; attrs.pads_end = {0, 0, 0, 0}; attrs.cube_coeff = -0.75; auto input_data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto sizes = std::make_shared<ov::op::v0::Constant>(element::i32, Shape{2}, std::vector<int32_t>{24, 160}); auto scales = std::make_shared<ov::op::v0::Constant>(element::f32, Shape{2}, std::vector<float>{2.0, 0.5}); auto axes = std::make_shared<ov::op::v0::Constant>(element::i32, Shape{2}, std::vector<int32_t>{2, 3}); auto interpolate = std::make_shared<op::v4::Interpolate>(input_data, sizes, scales, axes, attrs); return interpolate; } static std::shared_ptr<op::v0::Interpolate> build_InterpolateV0() { ov::op::v0::Interpolate::Attributes attrs; attrs.axes = {2, 3}; attrs.mode = "nearest"; attrs.align_corners = true; attrs.antialias = false; attrs.pads_begin = {0, 0, 0, 0}; attrs.pads_end = {0, 0, 0, 0}; auto input_data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1}); auto sizes = std::make_shared<op::v0::Parameter>(element::i32, PartialShape::dynamic()); auto interpolate_v0 = std::make_shared<op::v0::Interpolate>(input_data, sizes, attrs); return interpolate_v0; } TEST(StaticShapeInferenceTest, InterpolateV4Test) { auto interpolate = build_InterpolateV4(); int32_t sizes_val[] = {24, 160}; float scales_val[] = {2.0, 0.5}; int32_t axes_val[] = {2, 3}; std::map<size_t, std::shared_ptr<ngraph::runtime::HostTensor>> constant_data; constant_data[1] = std::make_shared<ngraph::runtime::HostTensor>(ngraph::element::Type_t::i32, Shape{2}, sizes_val); constant_data[2] = std::make_shared<ngraph::runtime::HostTensor>(element::f32, Shape{2}, scales_val); constant_data[3] = std::make_shared<ngraph::runtime::HostTensor>(element::i32, Shape{2}, axes_val); std::vector<StaticShape> static_input_shapes = {StaticShape{1, 2, 48, 80}, StaticShape{2}, StaticShape{2}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; shape_inference(interpolate.get(), static_input_shapes, static_output_shapes, constant_data); ASSERT_EQ(static_output_shapes[0], StaticShape({1, 2, 96, 40})); } TEST(StaticShapeInferenceTest, InterpolateV4ConstantInputTest) { auto interpolate = build_InterpolateV4ConstantInput(); std::vector<StaticShape> static_input_shapes = {StaticShape{1, 2, 50, 80}, StaticShape{2}, StaticShape{2}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; shape_inference(interpolate.get(), static_input_shapes, static_output_shapes); ASSERT_EQ(static_output_shapes[0], StaticShape({1, 2, 100, 40})); } TEST(StaticShapeInferenceTest, InterpolateV4MissingConstantTest) { auto interpolate = build_InterpolateV4(); int32_t sizes_val[] = {24, 160}; float scales_val[] = {2.0, 0.5}; std::map<size_t, std::shared_ptr<ngraph::runtime::HostTensor>> constant_data; constant_data[1] = std::make_shared<ngraph::runtime::HostTensor>(ngraph::element::Type_t::i32, Shape{2}, sizes_val); constant_data[2] = std::make_shared<ngraph::runtime::HostTensor>(element::f32, Shape{2}, scales_val); std::vector<StaticShape> static_input_shapes = {StaticShape{1, 2, 48, 80}, StaticShape{2}, StaticShape{2}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; EXPECT_THROW(shape_inference(interpolate.get(), static_input_shapes, static_output_shapes, constant_data), NodeValidationFailure); } TEST(StaticShapeInferenceTest, InterpolateV0Test) { auto interpolate = build_InterpolateV0(); int32_t sizes_val[] = {15, 30}; std::map<size_t, std::shared_ptr<ngraph::runtime::HostTensor>> constant_data; constant_data[1] = std::make_shared<ngraph::runtime::HostTensor>(ngraph::element::Type_t::i32, Shape{2}, sizes_val); std::vector<StaticShape> static_input_shapes = {StaticShape{2, 2, 33, 65}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; shape_inference(interpolate.get(), static_input_shapes, static_output_shapes, constant_data); ASSERT_EQ(static_output_shapes[0], StaticShape({2, 2, 15, 30})); } TEST(StaticShapeInferenceTest, InterpolateV0MissingConstantTest) { auto interpolate = build_InterpolateV0(); std::vector<StaticShape> static_input_shapes = {StaticShape{2, 2, 33, 65}, StaticShape{2}}, static_output_shapes = {StaticShape{}}; EXPECT_THROW(shape_inference(interpolate.get(), static_input_shapes, static_output_shapes), NodeValidationFailure); }
48.375839
120
0.66232
1c1246b06c41ea08f0c0a3bb12e4b5c2f55d9dea
1,107
cpp
C++
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; //Macros #define read(a) scanf("%d",&a) #define CLEAR(a,b) memset(a,b,sizeof(a)) #define VI(a) vector<a> #define lld long long int #define ulld unsigned long long int #define PI acos(-1.0) #define Gamma 0.5772156649015328606065120900824024310421 int arr[22][3]; int dp[22][3]; int n; int cal(int i,int j) { if(i==n) return 0; if(i>=n|| j<0 || j>2) return INT_MAX; if(dp[i][j]!=-1) return dp[i][j]; for(int k=0;k<3;k++) { dp[i][k]= arr[i][k]+min(min( cal(i+1,k+1) , cal(i+1,k-1) ), min( cal(i+1,k+2) , cal(i+1,k-2) )); } return dp[i][j]; } int main() { int test; read(test); for(int Case = 1;Case<=test;Case++) { CLEAR(dp,-1); read(n); for(int i=0;i<n;i++) { for(int j=0;j<3;j++) { scanf("%d",&arr[i][j]); } } int ret = cal(0,0); for(int i=0;i<3;i++) ret = min(ret,dp[0][i]); printf("Case %d: %d\n",Case,ret); } return 0; }
17.030769
104
0.483288
1c135917bc74b3aae19c1068d8fe38e7acb51550
4,730
cpp
C++
dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
1
2022-03-21T03:13:45.000Z
2022-03-21T03:13:45.000Z
dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
null
null
null
dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp
TaoweiZhang/MegEngine
bd3c4a05274f69dacca6097d8cbadbb34c7cc2e4
[ "Apache-2.0" ]
null
null
null
/** * \file dnn/src/naive/elemwise_multi_type/opr_impl_1.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include "./opr_impl.h" #include "megdnn/tensor_iter.h" #include "src/common/elemwise/kern_defs.cuh" #include "src/common/elemwise_multi_type/kern_defs.cuh" #include "src/naive/handle.h" using namespace megdnn; using namespace naive; void ElemwiseMultiTypeImpl::on_fuse_mul_add3_int16x32x32x32( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { auto i0 = tensor_iter_valonly<dt_int16>(src0).begin(); auto i1 = tensor_iter_valonly<dt_int32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_int32>(src2).begin(); auto dst_ptr = dst.ptr<dt_int32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1) + (*i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_fuse_mul_add3_int16xf32xf32xf32( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { auto i0 = tensor_iter_valonly<dt_int16>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_float32>(src2).begin(); auto dst_ptr = dst.ptr<dt_float32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1) + (*i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_fuse_mul_add3_uint8xf32xf32xf32( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { auto i0 = tensor_iter_valonly<dt_uint8>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_float32>(src2).begin(); auto dst_ptr = dst.ptr<dt_float32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1) + (*i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_mul_int16xf32xf32( const ElemwiseOpParamN<2>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto work = [src0, src1, size, dst]() { auto i0 = tensor_iter_valonly<dt_int16>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto dst_ptr = dst.ptr<dt_float32>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = (*i0) * (*i1); ++i0; ++i1; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } void ElemwiseMultiTypeImpl::on_fuse_mul_add3_iXxf32xf32xi8( const ElemwiseOpParamN<3>& param, const TensorND& dst) { switch (param[0].layout.dtype.enumv()) { #define cb(t) \ case DTypeTrait<t>::enumv: \ return dispatch_fma3_iXxf32xf32xi8<DTypeTrait<t>::ctype>(param, dst); MEGDNN_FOREACH_COMPUTING_DTYPE_INT(cb) #undef cb default: megdnn_throw("unsupported src dtype"); } } template <typename ctype> void ElemwiseMultiTypeImpl::dispatch_fma3_iXxf32xf32xi8( const ElemwiseOpParamN<3>& param, const TensorND& dst) { auto size = param.size; auto src0 = param[0]; auto src1 = param[1]; auto src2 = param[2]; auto work = [src0, src1, src2, size, dst]() { elemwise_multi_type::Fma3iXxf32xf32xiYOp<ctype, dt_int8> op; auto i0 = tensor_iter_valonly<ctype>(src0).begin(); auto i1 = tensor_iter_valonly<dt_float32>(src1).begin(); auto i2 = tensor_iter_valonly<dt_float32>(src2).begin(); auto dst_ptr = dst.ptr<dt_int8>(); for (size_t i = 0; i < size; ++i) { dst_ptr[i] = op(*i0, *i1, *i2); ++i0; ++i1; ++i2; } }; MEGDNN_DISPATCH_CPU_KERN_OPR(work()); } // vim: syntax=cpp.doxygen
34.028777
89
0.604017
1c16dc3bb20e37ed22e6079c11a2e75d1e557c8f
1,361
cpp
C++
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
7
2022-02-07T08:26:55.000Z
2022-03-23T02:55:44.000Z
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
null
null
null
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
null
null
null
#include <fcntl.h> #include <string.h> #include "LocalConn.h" #include "Tunnel.h" #include "lib/Util.h" void LocalConn::handleRead() { try{ int bs = splice(fd_, NULL, pipe_fds_[1], NULL, 2048, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bs < 0) { SPDLOG_CRITICAL("proxy_id: {} local_fd: {} -> pipe_fd: {} splice err: {} ", proxy_id_, fd_, pipe_fds_[1], strerror(errno)); return; } // 当proxyConn调用shutdownFromRemote后,shutdown(local_fd, 1)后会往local_fd中添加EPOLLIN事件,所以可能会重复满足bs=0,需要添加closing_判断。避免多次进入循环 // https://mp.weixin.qq.com/s?__biz=MzUxNDUwOTc0Nw==&mid=2247484253&idx=1&sn=e42ed5e1af8382eb6dffa7550470cdf3 if (bs == 0 && !closing_) { tun_->shutdownFromLocal(proxy_id_, getTranCount()); closing_ = true; return; } bs = splice(pipe_fds_[0], NULL, peer_conn_fd_, NULL, bs, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bs < 0) { SPDLOG_CRITICAL("proxy_id {} local_fd: {} pipe_fd: {} -> proxy_conn_fd: {} splice err: {}", proxy_id_, fd_, pipe_fds_[0], peer_conn_fd_, strerror(errno)); return; } incrTranCount(bs); } catch (const std::exception& e) { SPDLOG_CRITICAL("read local_conn except: {}", e.what()); } } void LocalConn::postHandle() { if (closing_) { return; } channel_->setEvents(EPOLLET | EPOLLIN | EPOLLRDHUP); loop_->updatePoller(channel_); }
35.815789
162
0.659809
1c1daf85142e4d3caa7fc315f2ddee90e9f4dda5
490
cpp
C++
dawn/test/unit-test/dawn/Optimizer/samples/KCacheTest02b.cpp
BenWeber42/dawn
727835e027b8270d667452b857fa4e0af57b2c2e
[ "MIT" ]
20
2017-09-28T14:23:54.000Z
2021-08-23T09:58:26.000Z
dawn/test/unit-test/dawn/Optimizer/samples/KCacheTest02b.cpp
BenWeber42/dawn
727835e027b8270d667452b857fa4e0af57b2c2e
[ "MIT" ]
1,018
2017-10-09T13:55:47.000Z
2022-03-14T13:16:38.000Z
dawn/test/unit-test/dawn/Optimizer/samples/KCacheTest02b.cpp
eddie-c-davis/dawn
4dabcfc72e422f125e6a18fe08d0212d588adf98
[ "MIT" ]
20
2017-09-21T10:35:24.000Z
2021-01-18T09:24:58.000Z
#include "gtclang_dsl_defs/gtclang_dsl.hpp" using namespace gtclang::dsl; stencil Test { storage a, b, c; var tmp; Do { // MS0 vertical_region(k_start, k_start) { tmp = a; } vertical_region(k_start + 1, k_end) { b = tmp(k - 1); } // MS1 vertical_region(k_end, k_end) { tmp = (b(k - 1) + b) * tmp; } vertical_region(k_end - 1, k_start) { tmp = 2 * b; c = tmp(k + 1); } } };
19.6
43
0.483673
1c2019fcd1b8894f0a0a76c6cff42181449ee6bc
129,465
cpp
C++
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
// DlgStats.cpp : implementation file // #include "stdafx.h" #include "bwchart.h" #include "DlgStats.h" #include "regparam.h" #include "bwrepapi.h" #include "DlgHelp.h" #include "DlgMap.h" #include "Dlgbwchart.h" #include "gradient.h" #include "hsvrgb.h" #include "overlaywnd.h" #include "ExportCoachDlg.h" #include "bezier.h" #include <math.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define MAXPLAYERONVIEW 6 #define HSCROLL_DIVIDER 2 #define TIMERSPEED 8 //----------------------------------------------------------------------------------------------------------------- // constants for chart painting int hleft=30; const int haxisleft = 2; const int vplayer=30; const int hplayer=52; const int hright=8; const int vtop=24; const int vbottom=12; const int evtWidth=4; const int evtHeight=8; const int layerHeight=14; const COLORREF clrCursor = RGB(200,50,50); const COLORREF clrMineral = RGB(50,50,150); const COLORREF clrGrid = RGB(64,64,64); const COLORREF clrLayer1 = RGB(32,32,32); const COLORREF clrLayer2 = RGB(16,16,16); const COLORREF clrLayerTxt1 = RGB(0,0,0); const COLORREF clrLayerTxt2 = RGB(64,64,64); const COLORREF clrAction = RGB(255,206,70); const COLORREF clrBOLine[3] = {RGB(30,30,120),RGB(80,30,30),RGB(30,80,30)}; const COLORREF clrBOName[3] = {RGB(100,150,190), RGB(200,50,90), RGB(50,200,90) }; #define clrPlayer OPTIONSCHART->GetColor(DlgOptionsChart::CLR_PLAYERS) #define clrUnitName OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) #define clrRatio OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) #define clrTime OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) static bool firstPoint=true; static int lastMaxX=0; static int lastHotPointX=0; static const char *lastHotPoint=0; static CString strDrop; static CString strExpand; static CString strLeave; static CString strMinGas; static CString strSupplyUnit; static CString strMinimapPing; // dividers for splines static int gSplineCount[DlgStats::__MAXCHART]= { //APM 200, //RESOURCES, 200, //UNITS 200, //ACTIONS 0, //BUILDINGS 0, //UPGRADES 0, //APMDIST 0, //BUILDORDER 0, //HOTKEYS 0, //MAPCOVERAGE 100, //MIX_APMHOTKEYS 0 }; //----------------------------------------------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(DlgStats, CDialog) //{{AFX_MSG_MAP(DlgStats) ON_WM_PAINT() ON_BN_CLICKED(IDC_GETEVENTS, OnGetevents) ON_WM_SIZE() ON_NOTIFY(LVN_ITEMCHANGED, IDC_LISTEVENTS, OnItemchangedListevents) ON_WM_LBUTTONDOWN() ON_CBN_SELCHANGE(IDC_ZOOM, OnSelchangeZoom) ON_WM_HSCROLL() ON_NOTIFY(NM_DBLCLK, IDC_PLSTATS, OnDblclkPlstats) ON_BN_CLICKED(IDC_GAZ, OnUpdateChart) ON_WM_DESTROY() ON_CBN_SELCHANGE(IDC_CHARTTYPE, OnSelchangeCharttype) ON_BN_CLICKED(IDC_DHELP, OnHelp) ON_BN_CLICKED(IDC_TESTREPLAYS, OnTestreplays) ON_BN_CLICKED(IDC_ADDEVENT, OnAddevent) ON_NOTIFY(NM_RCLICK, IDC_PLSTATS, OnRclickPlstats) ON_BN_CLICKED(IDC_SEEMAP, OnSeemap) ON_BN_CLICKED(IDC_ANIMATE, OnAnimate) ON_WM_TIMER() ON_BN_CLICKED(IDC_PAUSE, OnPause) ON_BN_CLICKED(IDC_SPEEDMINUS, OnSpeedminus) ON_BN_CLICKED(IDC_SPEEDPLUS, OnSpeedplus) ON_NOTIFY(LVN_GETDISPINFO, IDC_LISTEVENTS, OnGetdispinfoListevents) ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_SETCURSOR() ON_WM_RBUTTONDOWN() ON_NOTIFY(NM_RCLICK, IDC_LISTEVENTS, OnRclickListevents) ON_BN_CLICKED(IDC_FLT_SELECT, OnFilterChange) ON_BN_CLICKED(IDC_NEXT_SUSPECT, OnNextSuspect) ON_BN_CLICKED(IDC_MINERALS, OnUpdateChart) ON_BN_CLICKED(IDC_SUPPLY, OnUpdateChart) ON_BN_CLICKED(IDC_ACTIONS, OnUpdateChart) ON_BN_CLICKED(IDC_UNITS, OnUpdateChart) ON_BN_CLICKED(IDC_USESECONDS, OnUpdateChart) ON_BN_CLICKED(IDC_SPEED, OnUpdateChart) ON_BN_CLICKED(IDC_SINGLECHART, OnUpdateChart) ON_BN_CLICKED(IDC_UNITSONBO, OnUpdateChart) ON_BN_CLICKED(IDC_HOTPOINTS, OnUpdateChart) ON_BN_CLICKED(IDC_UPM, OnUpdateChart) ON_BN_CLICKED(IDC_BPM, OnUpdateChart) ON_BN_CLICKED(IDC_PERCENTAGE, OnUpdateChart) ON_BN_CLICKED(IDC_HKSELECT, OnUpdateChart) ON_BN_CLICKED(IDC_FLT_BUILD, OnFilterChange) ON_BN_CLICKED(IDC_FLT_TRAIN, OnFilterChange) ON_BN_CLICKED(IDC_FLT_SUSPECT, OnFilterChange) ON_BN_CLICKED(IDC_FLT_HACK, OnFilterChange) ON_BN_CLICKED(IDC_FLT_OTHERS, OnFilterChange) ON_BN_CLICKED(IDC_FLT_CHAT, OnFilterChange) ON_BN_CLICKED(IDC_SORTDIST, OnUpdateChart) ON_CBN_SELCHANGE(IDC_APMSTYLE, OnSelchangeApmstyle) //}}AFX_MSG_MAP ON_COMMAND(ID__REMOVEPLAYER,OnRemovePlayer) ON_COMMAND(ID__ENABLEDISABLE,OnEnableDisable) ON_COMMAND(ID__WATCHREPLAY_BW116,OnWatchReplay116) ON_COMMAND(ID__WATCHREPLAY_BW115,OnWatchReplay115) ON_COMMAND(ID__WATCHREPLAY_BW114,OnWatchReplay114) ON_COMMAND(ID__WATCHREPLAY_BW113,OnWatchReplay113) ON_COMMAND(ID__WATCHREPLAY_BW112,OnWatchReplay112) ON_COMMAND(ID__WATCHREPLAY_BW111,OnWatchReplay111) ON_COMMAND(ID__WATCHREPLAY_BW110,OnWatchReplay110) ON_COMMAND(ID__WATCHREPLAY_BW109,OnWatchReplay109) ON_COMMAND(ID__WATCHREPLAYINBW_SC,OnWatchReplaySC) ON_COMMAND(ID__WATCHREPLAYINBW_AUTO,OnWatchReplay) ON_COMMAND(ID_FF_EXPORT_TOTEXTFILE,OnExportToText) ON_COMMAND(ID__EXPORTTO_BWCOACH,OnExportToBWCoach) // ON_COMMAND(ID_FF_EXPORTTO_HTMLFILE,OnExportToHtml) END_MESSAGE_MAP() //----------------------------------------------------------------------------------------------------------------- void DlgStats::_Parameters(bool bLoad) { int defval[__MAXCHART]; int defvalUnits[__MAXCHART]; int defvalApm[__MAXCHART]; memset(defval,0,sizeof(defval)); memset(defvalUnits,0,sizeof(defvalUnits)); memset(defvalApm,0,sizeof(defval)); defvalUnits[MAPCOVERAGE]=1; defvalApm[MAPCOVERAGE]=2; defvalApm[APM]=2; PINT("main",seeMinerals,TRUE); PINT("main",seeGaz,TRUE); PINT("main",seeSupply,FALSE); PINT("main",seeActions,FALSE); PINTARRAY("main",singleChart,__MAXCHART,defval); PINTARRAY("main",seeUnits,__MAXCHART,defvalUnits); PINTARRAY("main",apmStyle,__MAXCHART,defvalApm); PINT("main",useSeconds,FALSE); PINT("main",seeSpeed,FALSE); PINT("main",seeUPM,FALSE); PINT("main",seeBPM,FALSE); PINT("main",chartType,0); PINT("main",seeUnitsOnBO,TRUE); PINT("main",seeHotPoints,TRUE); PINT("main",seePercent,TRUE); PINT("main",animationSpeed,2); PINT("main",hlist,120); PINT("main",wlist,0); PINT("main",viewHKselect,FALSE); PINT("filter",fltSelect,TRUE); PINT("filter",fltTrain,TRUE); PINT("filter",fltBuild,TRUE); PINT("filter",fltSuspect,TRUE); PINT("filter",fltHack,TRUE); PINT("filter",fltOthers,TRUE); PINT("filter",fltChat,TRUE); PINT("main",sortDist,FALSE); } //----------------------------------------------------------------------------------------------------------------- /* static void _GetRemoteItemText(HANDLE hProcess, HWND hlv, LV_ITEM* plvi, int item, int subitem, char *itemText) { // Initialize a local LV_ITEM structure LV_ITEM lvi; lvi.mask = LVIF_TEXT; lvi.iItem = item; lvi.iSubItem = subitem; // NOTE: The text data immediately follows the LV_ITEM structure // in the memory block allocated in the remote process. lvi.pszText = (LPTSTR) (plvi + 1); lvi.cchTextMax = 100; // Write the local LV_ITEM structure to the remote memory block if(!WriteProcessMemory(hProcess, plvi, &lvi, sizeof(lvi), NULL)) { ::MessageBox(0,__TEXT("Cant write into SuperView's memory"), "bwchart", MB_OK | MB_ICONWARNING); return; } // Tell the ListView control to fill the remote LV_ITEM structure ListView_GetItem(hlv, plvi); // Read the remote text string into our buffer if(!ReadProcessMemory(hProcess, plvi + 1, itemText, 256, NULL)) { ::MessageBox(0,__TEXT("Cant read into SuperView's memory"), "bwchart", MB_OK | MB_ICONWARNING); return; } } //----------------------------------------------------------------------------------------------------------------- typedef LPVOID (__stdcall * PFNVIRTALLEX)(HANDLE, LPVOID, SIZE_T, DWORD,DWORD); static HANDLE ghFileMapping=0; static PVOID _AllocSharedMemory(HANDLE hProcess, int size) { OSVERSIONINFO osvi = { sizeof(osvi) }; GetVersionEx( &osvi ); if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { // We're on NT, so use VirtualAllocEx to allocate memory in the other // process address space. Alas, we can't just call VirtualAllocEx // since it's not defined in the Windows 95 KERNEL32.DLL. return VirtualAllocEx(hProcess, NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); } else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { // In Windows 9X, create a small memory mapped file. On this // platform, memory mapped files are above 2GB, and thus are // accessible by all processes. ghFileMapping = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE | SEC_COMMIT, 0, size, 0 ); if ( ghFileMapping ) { LPVOID pStubMemory = MapViewOfFile( ghFileMapping, FILE_MAP_WRITE, 0, 0, size ); return pStubMemory; } else { CloseHandle( ghFileMapping ); ghFileMapping=0; } } return 0; } //----------------------------------------------------------------------------------------------------------------- static void _FreeSharedMemory(HANDLE hProcess, PVOID padr) { OSVERSIONINFO osvi = { sizeof(osvi) }; GetVersionEx( &osvi ); if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { // We're on NT, so use VirtualFreeEx VirtualFreeEx(hProcess, padr, 0, MEM_RELEASE); } else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { // In Windows 9X, create a small memory mapped file. On this // platform, memory mapped files are above 2GB, and thus are // accessible by all processes. UnmapViewOfFile(padr); CloseHandle( ghFileMapping ); } } //----------------------------------------------------------------------------------------------------------------- #define CMPUNIT(val,rval) if(_stricmp(itemParam,val)==0) {strcpy(itemParam,rval); return;} #define CMPBUILD(val,rval) if(_stricmp(lastp,val)==0) {strcpy(lastp,rval); return;} // adjust values static void _AdjustAction(char *itemType, char *itemParam) { if(_stricmp(itemType,"Train")==0) { CMPUNIT("46","Scout"); CMPUNIT("47","Arbiter"); CMPUNIT("3C","Corsair"); CMPUNIT("45","Shuttle"); CMPUNIT("53","Reaver"); CMPUNIT("01","Ghost"); CMPUNIT("0C","Battlecruiser"); CMPUNIT("Vulture","Goliath"); CMPUNIT("Goliath","Vulture"); CMPUNIT("0E","Nuke"); return; } else if(_stricmp(itemType,"2A")==0) {strcpy(itemType,"Train"); strcpy(itemParam,"Archon"); return;} else if(_stricmp(itemType,"5A")==0) {strcpy(itemType,"Train"); strcpy(itemParam,"Dark Archon"); return;} else if(_stricmp(itemType,"Build")==0) { // extract building name char *lastp=strrchr(itemParam,','); if(lastp!=0) lastp++; else lastp=itemParam; while(*lastp==' ') lastp++; CMPBUILD("AA","Arbiter Tribunal"); CMPBUILD("AB","Robotics Support Bay"); CMPBUILD("AC","Shield Battery"); CMPBUILD("75","Covert Ops"); CMPBUILD("76","Physics Lab"); CMPBUILD("6C","Nuclear Silo"); CMPBUILD("Acadamy","Academy"); return; } else if(_stricmp(itemType,"Research")==0 || _stricmp(itemType,"Upgrade")==0) { CMPUNIT("27","Gravitic Booster"); CMPUNIT("22","Zealot Speed"); CMPUNIT("15","Recall"); CMPUNIT("0E","Protoss Air Attack"); CMPUNIT("23","Scarab Damage"); CMPUNIT("26","Sensor Array"); CMPUNIT("16","Statis Field"); CMPUNIT("14","Hallucination"); CMPUNIT("0F","Plasma Shield"); CMPUNIT("24","Reaver Capacity"); CMPUNIT("2C","Khaydarin Core"); CMPUNIT("28","Khaydarin Amulet"); CMPUNIT("29","Apial Sensors"); CMPUNIT("25","Gravitic Drive"); CMPUNIT("1B","Mind Control"); CMPUNIT("2A","Gravitic Thrusters"); CMPUNIT("1F","Maelstrom"); CMPUNIT("31","Argus Talisman"); CMPUNIT("19","Disruption Web"); CMPUNIT("2F","Argus Jewel"); CMPUNIT("01","Lockdown"); CMPUNIT("02","EMP Shockwave"); CMPUNIT("09","Cloaking Field"); CMPUNIT("11","Vulture Speed"); CMPUNIT("0A","Personal Cloaking"); CMPUNIT("08","Yamato Gun"); CMPUNIT("17","Colossus Reactor"); CMPUNIT("18","Restoration"); CMPUNIT("1E","Optical Flare"); CMPUNIT("33","Medic Energy"); return; } } //----------------------------------------------------------------------------------------------------------------- bool DlgStats::_GetListViewContent(HWND hlv) { // Get the count of items in the ListView control int nCount = ListView_GetItemCount(hlv); // Open a handle to the remote process's kernel object DWORD dwProcessId; GetWindowThreadProcessId(hlv, &dwProcessId); HANDLE hProcess = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, dwProcessId); if (hProcess == NULL) { MessageBox(__TEXT("Could not communicate with SuperView"), "bwchart", MB_OK | MB_ICONWARNING); return false; } // Allocate memory in the remote process's address space LV_ITEM* plvi = (LV_ITEM*) //VirtualAllocEx(hProcess, NULL, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); _AllocSharedMemory(hProcess, 4096); if (plvi == NULL) { DWORD dw=GetLastError(); CString msg; msg.Format("Could not allocate virtual memory %lu",dw); MessageBox("Sorry, but BWchart cannot work under Windows 95/98", "bwchart", MB_OK | MB_ICONWARNING); return false; } // Get each ListView item's text data for (int nIndex = 0; nIndex < nCount; nIndex++) { // read elapsed time char itemTime[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 0, itemTime); int nPos = m_listEvents.InsertItem(nIndex,itemTime, 0); m_listEvents.SetItemData(nPos,(DWORD)_atoi64(itemTime)); // read player name char itemPlayer[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 1, itemPlayer); m_listEvents.SetItemText(nPos,1,itemPlayer); // read event type char itemType[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 2, itemType); // read event parameters char itemParam[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 3, itemParam); // adjust values _AdjustAction(itemType,itemParam); // update list view m_listEvents.SetItemText(nPos,2,itemType); m_listEvents.SetItemText(nPos,3,itemParam); // record event //m_replay.AddEvent(atoi(itemTime),itemPlayer,itemType,itemParam); } // Free the memory in the remote process's address space _FreeSharedMemory(hProcess, plvi); //VirtualFreeEx(hProcess, plvi, 0, MEM_RELEASE); // Cleanup and put our results on the clipboard CloseHandle(hProcess); return true; } //----------------------------------------------------------------------------------------------------------------- BOOL CALLBACK EnumChildProc( HWND hwnd, // handle to child window LPARAM lParam // application-defined value ) { char classname[128]; GetClassName(hwnd,classname,sizeof(classname)); if(_stricmp(classname,"SysListView32")==0) { HWND hlv = ::GetNextWindow(hwnd, GW_HWNDNEXT); if(hlv==0) return FALSE; hlv = ::GetNextWindow(hlv, GW_HWNDNEXT); if(hlv==0) return FALSE; *((HWND*)lParam) = hlv; return FALSE; } return TRUE; } */ //----------------------------------------------------------------------------------------------------------------- bool DlgStats::_GetReplayFileName(CString& path) { static char BASED_CODE szFilter[] = "Replay (*.rep)|*.rep|All Files (*.*)|*.*||"; // find initial path CString initialPath; initialPath = AfxGetApp()->GetProfileString("MAIN","LASTADDREPLAY"); if(initialPath.IsEmpty()) DlgOptions::_GetStarcraftPath(initialPath); // stop animation if any StopAnimation(); // open dialog CFileDialog dlg(TRUE,"rep","",0,szFilter,this); dlg.m_ofn.lpstrInitialDir = initialPath; if(dlg.DoModal()==IDOK) { CWaitCursor wait; path = dlg.GetPathName(); AfxGetApp()->WriteProfileString("MAIN","LASTADDREPLAY",path); return true; } return false; } ///////////////////////////////////////////////////////////////////////////// // DlgStats dialog DlgStats::DlgStats(CWnd* pParent /*=NULL*/) : CDialog(DlgStats::IDD, pParent) { //{{AFX_DATA_INIT(DlgStats) m_zoom = 0; m_seeMinerals = TRUE; m_seeGaz = TRUE; m_seeSupply = FALSE; m_seeActions = FALSE; m_useSeconds = FALSE; m_seeSpeed = FALSE; m_chartType = -1; m_seeUnitsOnBO = FALSE; m_exactTime = _T(""); m_seeBPM = FALSE; m_seeUPM = FALSE; m_seeHotPoints = FALSE; m_seePercent = FALSE; m_viewHKselect = FALSE; m_fltSelect = FALSE; m_fltSuspect = FALSE; m_fltHack = FALSE; m_fltTrain = FALSE; m_fltBuild = FALSE; m_fltOthers = FALSE; m_fltChat = FALSE; m_suspectInfo = _T(""); m_sortDist = FALSE; //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_timeBegin = 0; m_timeEnd = 0; m_lockListView=false; m_selectedPlayer=0; m_selectedAction=-1; m_maxPlayerOnBoard=0; m_selectedPlayerList=0; m_bIsAnimating=false; m_animationSpeed=2; m_prevAnimationSpeed=0; m_timer=0; m_mixedCount=0; m_MixedPlayerIdx=0; // map title m_rectMapName.SetRectEmpty(); // resize m_resizing=NONE; m_hlist=120; m_wlist=0; // load parameters _Parameters(true); if(m_hlist<60) m_hlist=60; // scroller increments m_lineDev.cx = 5; m_lineDev.cy = 0; m_pageDev.cx = 50; m_pageDev.cy = 0; // create all fonts _CreateFonts(); // create map m_dlgmap = new DlgMap(0,m_pLabelBoldFont,m_pLayerFont,this); // create overlay m_over = new OverlayWnd(this); // init time m_exactTime = _MkTime(0,0,true); } DlgStats::~DlgStats() { // delete overlay m_over->DestroyWindow(); delete m_over; //delete map delete m_dlgmap; // delete fonts _DestroyFonts(); } void DlgStats::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(DlgStats) DDX_Check(pDX, IDC_SINGLECHART, m_singleChart[m_chartType]); DDX_Check(pDX, IDC_UNITS, m_seeUnits[m_chartType]); DDX_CBIndex(pDX, IDC_APMSTYLE, m_apmStyle[m_chartType]); DDX_CBIndex(pDX, IDC_CHARTTYPE, m_chartType); DDX_Control(pDX, IDC_PROGRESS1, m_progress); DDX_Control(pDX, IDC_GAMEDURATION, m_gamed); DDX_Control(pDX, IDC_DBLCLICK, m_dlbclick); DDX_Control(pDX, IDC_PLSTATS, m_plStats); DDX_Control(pDX, IDC_SCROLLBAR2, m_scrollerV); DDX_Control(pDX, IDC_SCROLLBAR1, m_scroller); DDX_Control(pDX, IDC_LISTEVENTS, m_listEvents); DDX_CBIndex(pDX, IDC_ZOOM, m_zoom); DDX_Check(pDX, IDC_MINERALS, m_seeMinerals); DDX_Check(pDX, IDC_GAZ, m_seeGaz); DDX_Check(pDX, IDC_SUPPLY, m_seeSupply); DDX_Check(pDX, IDC_ACTIONS, m_seeActions); DDX_Check(pDX, IDC_USESECONDS, m_useSeconds); DDX_Check(pDX, IDC_SPEED, m_seeSpeed); DDX_Check(pDX, IDC_UNITSONBO, m_seeUnitsOnBO); DDX_Text(pDX, IDC_EXACTTIME, m_exactTime); DDX_Check(pDX, IDC_BPM, m_seeBPM); DDX_Check(pDX, IDC_UPM, m_seeUPM); DDX_Check(pDX, IDC_HOTPOINTS, m_seeHotPoints); DDX_Check(pDX, IDC_PERCENTAGE, m_seePercent); DDX_Check(pDX, IDC_HKSELECT, m_viewHKselect); DDX_Check(pDX, IDC_FLT_SELECT, m_fltSelect); DDX_Check(pDX, IDC_FLT_CHAT, m_fltChat); DDX_Check(pDX, IDC_FLT_SUSPECT, m_fltSuspect); DDX_Check(pDX, IDC_FLT_HACK, m_fltHack); DDX_Check(pDX, IDC_FLT_TRAIN, m_fltTrain); DDX_Check(pDX, IDC_FLT_BUILD, m_fltBuild); DDX_Check(pDX, IDC_FLT_OTHERS, m_fltOthers); DDX_Text(pDX, IDC_SUSPECT_INFO, m_suspectInfo); DDX_Check(pDX, IDC_SORTDIST, m_sortDist); //}}AFX_DATA_MAP } //------------------------------------------------------------------------------------------------------------ void DlgStats::_CreateFonts() { // get system language LANGID lng = GetSystemDefaultLangID(); //if(lng==0x412) // korea //if(lng==0x0804) //chinese // retrieve a standard VARIABLE FONT from system HFONT hFont = (HFONT)GetStockObject( ANSI_VAR_FONT); CFont *pRefFont = CFont::FromHandle(hFont); LOGFONT LFont; // get font description memset(&LFont,0,sizeof(LOGFONT)); pRefFont->GetLogFont(&LFont); // create our label Font LFont.lfHeight = 18; LFont.lfWidth = 0; LFont.lfQuality|=ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Arial"); m_pLabelFont = new CFont(); m_pLabelFont->CreateFontIndirect(&LFont); // create our bold label Font LFont.lfWeight=700; m_pLabelBoldFont = new CFont(); m_pLabelBoldFont->CreateFontIndirect(&LFont); // create our layer Font pRefFont->GetLogFont(&LFont); LFont.lfHeight = 14; LFont.lfWidth = 0; LFont.lfQuality|=ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Arial"); m_pLayerFont = new CFont(); m_pLayerFont->CreateFontIndirect(&LFont); // create our small label Font LFont.lfHeight = 10; LFont.lfWidth = 0; LFont.lfQuality&=~ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Small Fonts"); m_pSmallFont = new CFont(); m_pSmallFont->CreateFontIndirect(&LFont); // create image list m_pImageList = new CImageList(); } //------------------------------------------------------------------------------------------------------------ void DlgStats::_DestroyFonts() { delete m_pLabelBoldFont; delete m_pLabelFont; delete m_pSmallFont; delete m_pLayerFont; delete m_pImageList; } //------------------------------------------------------------------------------------------------------------ // prepare list view void DlgStats::_PrepareListView() { UINT evCol[]={IDS_COL_TIME,IDS_COL_PLAYER,IDS_COL_ACTION,IDS_COL_PARAMETERS,0,IDS_COL_UNITSID}; int evWidth[]={50,115,80,180,20,180}; UINT stCol[]={IDS_COL_PLAYER,IDS_COL_ACTIONS,IDS_COL_APM,IDS_COL_NULL,IDS_COL_VAPM,IDS_COL_MINERAL,IDS_COL_GAS, IDS_COL_SUPPLY,IDS_COL_UNITS,IDS_COL_APMPM,IDS_COL_APMMAX,IDS_COL_APMMIN,IDS_COL_BASE,IDS_COL_MICRO,IDS_COL_MACRO}; int stWidth[]={115,50,40,35,45,50,50,50,50,50,60,60,40,40,45}; // Allow the header controls item to be movable by the user. // and set full row selection m_listEvents.SetExtendedStyle(m_listEvents.GetExtendedStyle()|LVS_EX_HEADERDRAGDROP+LVS_EX_FULLROWSELECT); CString colTitle; for(int i=0;i<sizeof(evCol)/sizeof(evCol[0]);i++) { if(evCol[i]!=0) colTitle.LoadString(evCol[i]); else colTitle=""; m_listEvents.InsertColumn(i, colTitle,LVCFMT_LEFT,evWidth[i],i); } // Set the background color COLORREF clrBack = RGB(255,255,255); m_listEvents.SetBkColor(clrBack); m_listEvents.SetTextBkColor(clrBack); m_listEvents.SetTextColor(RGB(10,10,10)); m_listEvents.SubclassHeaderControl(); // player stats m_plStats.SetExtendedStyle(m_plStats.GetExtendedStyle()|LVS_EX_HEADERDRAGDROP+LVS_EX_FULLROWSELECT); for(int i=0;i<sizeof(stCol)/sizeof(stCol[0]);i++) { if(stCol[i]!=0) colTitle.LoadString(stCol[i]); else colTitle=""; m_plStats.InsertColumn(i, colTitle,LVCFMT_LEFT,stWidth[i],i); } DlgBrowser::LoadColumns(&m_plStats,"plstats"); // Set the background color m_plStats.SetBkColor(clrBack); m_plStats.SetTextBkColor(clrBack); m_plStats.SetTextColor(RGB(10,10,10)); // create, initialize, and hook up image list m_pImageList->Create(16, 16, ILC_COLOR4, 2, 2); m_pImageList->SetBkColor(clrBack); // add icons CWinApp *pApp = AfxGetApp(); m_pImageList->Add(pApp->LoadIcon(IDI_ICON_DISABLE)); m_pImageList->Add(pApp->LoadIcon(IDI_ICON_OK)); m_plStats.SetImageList(m_pImageList, LVSIL_SMALL); } //------------------------------------------------------------------------------------------------------------ void DlgStats::UpdateBkgBitmap() { // re-init all pens for drawing all the charts _InitAllDrawingTools(); // load background bitmap if any Invalidate(); } //------------------------------------------------------------------------------------------------------------ BOOL DlgStats::OnInitDialog() { CDialog::OnInitDialog(); // init chart type CComboBox *charttype = (CComboBox *)GetDlgItem(IDC_CHARTTYPE); CString msg; msg.LoadString(IDS_CT_APM); charttype->AddString(msg); msg.LoadString(IDS_CT_RESOURCES); charttype->AddString(msg); msg.LoadString(IDS_CT_UNITDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_ACTIONDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_BUILDDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_UPGRADES); charttype->AddString(msg); msg.LoadString(IDS_CT_APMDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_BO); charttype->AddString(msg); msg.LoadString(IDS_CT_HOTKEYS); charttype->AddString(msg); msg.LoadString(IDS_CT_MAPCOVERGAGE); charttype->AddString(msg); msg.LoadString(IDS_CT_MIX_APMHOTKEYS); charttype->AddString(msg); charttype->SetCurSel(m_chartType); // prepare list view _PrepareListView(); // resize CRect rect; GetClientRect(&rect); _Resize(rect.Width(),rect.Height()); // update screen OnSelchangeCharttype(); // create map window m_dlgmap->Create(DlgMap::IDD,(CWnd*)this); // load some strings strDrop.LoadString(IDS_DROP); strExpand.LoadString(IDS_EXPAND); strLeave.LoadString(IDS_LEAVE); strMinGas.LoadString(IDS_MINGAS); strSupplyUnit.LoadString(IDS_SUPPLYUNIT); strMinimapPing.LoadString(IDS_MINIMAPPING); #ifndef NDEBUG GetDlgItem(IDC_TESTREPLAYS)->ShowWindow(SW_SHOW); #endif return TRUE; // return TRUE unless you set the focus to a control } //----------------------------------------------------------------------------------------------------------------- // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void DlgStats::OnPaint() { CPaintDC dc(this); // device context for painting if (!IsIconic()) { // fill chart background OPTIONSCHART->PaintBackground(&dc,m_boardRect); // draw tracking rect for vertical resizing CRect resizeRect; _GetResizeRect(resizeRect); resizeRect.DeflateRect(resizeRect.Width()/3,1); CRect resizeRect2(resizeRect); resizeRect2.right = resizeRect2.left+10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); resizeRect2=resizeRect; resizeRect2.left = resizeRect2.right-10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); // draw tracking rect for horizontal resizing _GetHorizResizeRect(resizeRect); resizeRect.DeflateRect(2,resizeRect.Height()/3); resizeRect2=resizeRect; resizeRect2.bottom = resizeRect2.top+10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); resizeRect2=resizeRect; resizeRect2.top = resizeRect2.bottom-10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); // paint charts if(m_replay.IsDone()) _PaintCharts(&dc); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetCursorRect(CRect& rect, unsigned long time, int width) { // only repaint around the time cursor rect = m_boardRect; rect.left += m_dataAreaX; float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fx=(float)(rect.left+hleft) + finc * (time-m_timeBegin); rect.right = width+(int)fx; rect.left = -width+(int)fx;; } //----------------------------------------------------------------------------------------------------------------- // bUserControl = true when the cursor is changed by the user // void DlgStats::_SetTimeCursor(unsigned long value, bool bUpdateListView, bool bUserControl) { // repaint current cursor zone CRect rect; _GetCursorRect(rect, m_timeCursor, 2); InvalidateRect(rect,FALSE); // update cursor m_timeCursor = value; _GetCursorRect(rect, m_timeCursor, 2); if(m_zoom>0 && (m_timeCursor<m_timeBegin || m_timeCursor>m_timeEnd)) { // the time window has changed, we must repaint everything _AdjustWindow(); rect = m_boardRect; } // update scroller m_scroller.SetScrollPos(value/HSCROLL_DIVIDER); // if we are animating if(m_bIsAnimating) { // if the animation timer is the one who changed the cursor if(!bUserControl) { // only repaint around the time cursor int width = 16 + m_animationSpeed; _GetCursorRect(rect, m_timeCursor, width); } else { // the user has changed the cursor during the animation // we must repaint everything rect = m_boardRect; } } // update map if(bUserControl) m_dlgmap->ResetTime(m_timeCursor); // repaint view InvalidateRect(rect,FALSE); // update list of events if(bUpdateListView) { // select corresponding line in list view unsigned long idx = _GetEventFromTime(m_timeCursor); m_lockListView=true; m_listEvents.SetItemState(idx,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED); m_listEvents.EnsureVisible(idx,FALSE); m_lockListView=false; } // update exact time m_exactTime = _MkTime(m_replay.QueryFile()->QueryHeader(),value,true); UpdateData(FALSE); } //----------------------------------------------------------------------------------------------------------------- // display player stats void DlgStats::_DisplayPlayerStats() { m_plStats.DeleteAllItems(); // for each player for(int i=0; i<m_replay.GetPlayerCount(); i++) { // get event list ReplayEvtList *list = m_replay.GetEvtList(i); // insert player stats CString str; int nPos = m_plStats.InsertItem(i,list->PlayerName(), list->IsEnabled()?1:0); str.Format("%d",list->GetEventCount()); m_plStats.SetItemText(nPos,1,str); str.Format("%d",list->GetActionPerMinute()); m_plStats.SetItemText(nPos,2,str); str.Format("%d",list->GetDiscardedActions()); m_plStats.SetItemText(nPos,3,str); str.Format("%d",list->GetValidActionPerMinute()); m_plStats.SetItemText(nPos,4,str); str.Format("%d",list->ResourceMax().Minerals()); m_plStats.SetItemText(nPos,5,str); str.Format("%d",list->ResourceMax().Gaz()); m_plStats.SetItemText(nPos,6,str); str.Format("%d",(int)list->ResourceMax().Supply()); m_plStats.SetItemText(nPos,7,str); str.Format("%d",list->ResourceMax().Units()); m_plStats.SetItemText(nPos,8,str); str.Format("%d",list->GetStandardAPMDev(-1,-1)); m_plStats.SetItemText(nPos,9,str); str.Format("%d",list->ResourceMax().LegalAPM()); m_plStats.SetItemText(nPos,10,str); str.Format("%d",list->GetMiniAPM()); m_plStats.SetItemText(nPos,11,str); str.Format("%d",list->GetStartingLocation()); m_plStats.SetItemText(nPos,12,str); str.Format("%d",list->GetMicroAPM()); m_plStats.SetItemText(nPos,13,str); str.Format("%d",list->GetMacroAPM()); m_plStats.SetItemText(nPos,14,str); m_plStats.SetItemData(nPos,(DWORD)list); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::LoadReplay(const char *reppath, bool bClear) { CWaitCursor wait; // stop animation if any StopAnimation(); // clear list views if(bClear) m_listEvents.DeleteAllItems(); // update map m_dlgmap->UpdateReplay(0); // load replay if(m_replay.Load(reppath,true,&m_listEvents,bClear)!=0) { CString msg; msg.Format(IDS_CORRUPTEDBIS,reppath); MessageBox(msg,0,MB_OK|MB_ICONEXCLAMATION); return; } AfxGetApp()->WriteProfileString("MAIN","LASTREPLAY",reppath); SetDlgItemText(IDC_REPLAYFILE,reppath); // udpate suspect events counts CString chktitle; int suspectCount = m_replay.GetSuspectCount(); chktitle.Format(IDS_SUSPICIOUS,suspectCount); GetDlgItem(IDC_FLT_SUSPECT)->SetWindowText(chktitle); GetDlgItem(IDC_FLT_SUSPECT)->EnableWindow(suspectCount==0?FALSE:TRUE); // udpate hack events counts int hackCount = m_replay.GetHackCount(); chktitle.Format(IDS_HACK,hackCount); GetDlgItem(IDC_FLT_HACK)->SetWindowText(chktitle); GetDlgItem(IDC_FLT_HACK)->EnableWindow(hackCount==0?FALSE:TRUE); // update "next" button GetDlgItem(IDC_NEXT_SUSPECT)->EnableWindow((suspectCount+hackCount)==0?FALSE:TRUE); // display player stats _DisplayPlayerStats(); // init view m_maxPlayerOnBoard = m_replay.GetPlayerCount(); m_timeBegin = 0; m_timeCursor = 0; m_timeEnd = (m_chartType==BUILDORDER) ? m_replay.GetLastBuildOrderTime() : m_replay.GetEndTime(); m_scroller.SetScrollRange(0,m_timeEnd/HSCROLL_DIVIDER); // init all pens for drawing all the charts _InitAllDrawingTools(); // display game duration and game date CTime cdate; CString str; time_t date = m_replay.QueryFile()->QueryHeader()->getCreationDate(); if(localtime(&date)!=0) cdate = CTime(date); else cdate = CTime(1971,1,1,0,0,0); str.Format(IDS_MKDURATION,_MkTime(m_replay.QueryFile()->QueryHeader(),m_replay.GetEndTime(),true), (const char*)cdate.Format("%d %b %y")); SetDlgItemText(IDC_GAMEDURATION,str); // update map m_dlgmap->UpdateReplay(&m_replay); GetDlgItem(IDC_SEEMAP)->EnableWindow(m_replay.GetMapAnim()==0 ? FALSE :TRUE); if(m_replay.GetMapAnim()==0) m_dlgmap->ShowWindow(SW_HIDE); // init action filter _UpdateActionFilter(true); // update apm with current style m_replay.UpdateAPM(m_apmStyle[APM], m_apmStyle[MAPCOVERAGE]); //repaint Invalidate(FALSE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnGetevents() { // get path CString path; if(!_GetReplayFileName(path)) return; // load replay LoadReplay(path,true); } //----------------------------------------------------------------------------------------------------------------- #define CHANGEPOS(id,x,y)\ {CWnd *wnd = GetDlgItem(id);\ if(wnd && ::IsWindow(wnd->GetSafeHwnd()))\ wnd->SetWindowPos(0,x,y,0,0,SWP_NOZORDER|SWP_NOSIZE);} #define CHANGEPOSSIZE(id,x,y,w,h)\ {CWnd *wnd = GetDlgItem(id);\ if(wnd && ::IsWindow(wnd->GetSafeHwnd()))\ wnd->SetWindowPos(0,x,y,w,h,SWP_NOZORDER);} void DlgStats::_Resize(int cx, int cy) { if(!::IsWindow(m_scroller)) return; // if window was reduced a lot, make sure event list width & height is not too big if(m_wlist==0) m_wlist=min(460,(80*cx/100)); if(m_wlist>(90*cx/100)) m_wlist = 90*cx/100; if(m_hlist>(70*cy/100)) m_hlist = 70*cy/100; int hlist=m_hlist; int wlist=m_wlist; // find position of lowest control on the top CRect rectCtrl; GetDlgItem(IDC_SPEED)->GetWindowRect(&rectCtrl); ScreenToClient(&rectCtrl); int top=rectCtrl.top+rectCtrl.Height()+8; int left=10; int right=16; int wlist2=cx - wlist - right-left-2; m_boardRect.SetRect(left,top,max(16,cx-left-right),max(top+16,cy-32-hlist)); // scrollers if(::IsWindow(m_scroller)) m_scroller.SetWindowPos(0,left,m_boardRect.bottom,m_boardRect.Width()-218,17,SWP_NOZORDER); if(::IsWindow(m_scrollerV)) m_scrollerV.SetWindowPos(0,m_boardRect.right,top,17,m_boardRect.Height(),SWP_NOZORDER); // event list if(::IsWindow(m_listEvents)) m_listEvents.SetWindowPos(0,m_boardRect.left,cy-hlist-8+20,wlist,hlist-40,SWP_NOZORDER); // cursor time CHANGEPOS(IDC_EXACTTIME,m_boardRect.Width()-200,m_boardRect.bottom+2); // filter check boxes CHANGEPOS(IDC_FLT_SELECT,8+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_BUILD,70+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_TRAIN,146+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_OTHERS,222+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_SUSPECT,280+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_HACK,380+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_CHAT,480+m_boardRect.left,cy-hlist-8); CHANGEPOSSIZE(IDC_SUSPECT_INFO,8+m_boardRect.left,cy-22,wlist-70,12); CHANGEPOS(IDC_NEXT_SUSPECT,m_boardRect.left+wlist-58,cy-24); // player list if(::IsWindow(m_plStats)) m_plStats.SetWindowPos(0,m_boardRect.left+wlist+8,cy-hlist-8,wlist2,hlist-20,SWP_NOZORDER); // little help text if(::IsWindow(m_dlbclick)) m_dlbclick.SetWindowPos(0,m_boardRect.left+wlist+8,cy-20,0,0,SWP_NOZORDER|SWP_NOSIZE); // buttons CHANGEPOS(IDC_DHELP,m_boardRect.right-36,cy-22); CHANGEPOSSIZE(IDC_ANIMATE,m_boardRect.Width()-79,m_boardRect.bottom,49,17); CHANGEPOSSIZE(IDC_SEEMAP,m_boardRect.Width()-148,m_boardRect.bottom,69,17); CHANGEPOSSIZE(IDC_SPEEDPLUS,m_boardRect.Width()-30,m_boardRect.bottom,19,17); CHANGEPOSSIZE(IDC_SPEEDMINUS,m_boardRect.Width()-11,m_boardRect.bottom,19,17); CHANGEPOSSIZE(IDC_PAUSE,m_boardRect.Width()+8,m_boardRect.bottom,19,17); Invalidate(TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); if(cx!=0 && cy!=0) _Resize(cx, cy); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintOneEvent(CDC *pDC, const CRect* pRect, const ReplayEvt *evt) { COLORREF m_color = evt->GetColor(); COLORREF oldColor = pDC->GetBkColor(); switch(m_shape) { case SQUARE: pDC->FillSolidRect(pRect,m_color); break; case RECTANGLE: pDC->Draw3dRect(pRect,m_color,m_color); break; case FLAG: case FLAGEMPTY: { CRect rect = *pRect; rect.bottom = rect.top+rect.Height()/2; rect.right = rect.left + (3*rect.Width())/4; if(m_shape==FLAG) pDC->FillSolidRect(&rect,m_color); else pDC->Draw3dRect(&rect,m_color,m_color); rect = *pRect; rect.right = rect.left+1; pDC->FillSolidRect(&rect,m_color); } break; case TEALEFT: case TEARIGHT: { CRect rect = *pRect; if(m_shape==TEALEFT) rect.right = rect.left+1; rect.left = rect.right-1; pDC->FillSolidRect(&rect,m_color); rect.right = pRect->right; rect.left = pRect->left; rect.top=pRect->top+pRect->Height()/2; rect.bottom = rect.top+1; pDC->FillSolidRect(&rect,m_color); } break; case TEATOP: case TEABOTTOM: { CRect rect = *pRect; if(m_shape==TEATOP) rect.bottom = rect.top+1; rect.top = rect.bottom-1; pDC->FillSolidRect(&rect,m_color); rect.top = pRect->top; rect.bottom = pRect->bottom; rect.left=pRect->left+pRect->Width()/2; rect.right = rect.left+1; pDC->FillSolidRect(&rect,m_color); } break; case ROUNDRECT: CPen pen(PS_SOLID,1,m_color); CBrush brush(m_color); CPen *oldPen = pDC->SelectObject(&pen); CBrush *oldBrush = pDC->SelectObject(&brush); pDC->RoundRect(pRect,CPoint(4,4)); pDC->SelectObject(oldBrush); pDC->SelectObject(oldPen); break; } pDC->SetBkColor(oldColor); } //----------------------------------------------------------------------------------------------------------------- DrawingTools* DlgStats::_GetDrawingTools(int player) { if(player>=0) return &m_dtools[player+1]; return &m_dtools[0]; } //----------------------------------------------------------------------------------------------------------------- // init all pens for drawing all the charts void DlgStats::_InitAllDrawingTools() { // init drawing tools for multiple frame mode _InitDrawingTools(-1,m_maxPlayerOnBoard,1); // init drawing tools for all players on one frame mode for(int i=0;i<m_maxPlayerOnBoard;i++) _InitDrawingTools(i,m_maxPlayerOnBoard,2); } //----------------------------------------------------------------------------------------------------------------- // init all pens for drawing the charts of one player void DlgStats::_InitDrawingTools(int player, int maxplayer, int /*lineWidth*/) { // clear tools DrawingTools *tools = _GetDrawingTools(player); tools->Clear(); // create pen for minerals for(int i=0; i<DrawingTools::maxcurve;i++) { int lineSize = ReplayResource::GetLineSize(i); tools->m_clr[i] = ReplayResource::GetColor(i,player,maxplayer); tools->m_penMineral[i] = new CPen(PS_SOLID,lineSize,tools->m_clr[i]); tools->m_penMineralS[i] = new CPen(PS_SOLID,1,tools->m_clr[i]); tools->m_penMineralDark[i] = new CPen(PS_SOLID,1,CHsvRgb::Darker(tools->m_clr[i],0.70)); } } //----------------------------------------------------------------------------------------------------------------- // draw a little text to show a hot point void DlgStats::_PaintHotPoint(CDC *pDC, int x, int y, const ReplayEvt *evt, COLORREF clr) { const char *hotpoint=0; const IStarcraftAction *action = evt->GetAction(); int off=8; //if event is a hack if(evt->IsHack()) { // make color lighter COLORREF clrt = RGB(255,0,0); // draw a little triangle there int off=3; CPen clr(PS_SOLID,1,clrt); CPen clr2(PS_SOLID,1,RGB(160,0,0)); CPen *old=(CPen*)pDC->SelectObject(&clr); for(int k=0;k<3;k++) { pDC->MoveTo(x-k,y-off-k); pDC->LineTo(x+k+1,y-off-k); } pDC->SelectObject(&clr2); for(int k=3;k<5;k++) { pDC->MoveTo(x-k,y-off-k); pDC->LineTo(x+k+1,y-off-k); } pDC->SelectObject(old); } // Expand? if(action->GetID()==BWrepGameData::CMD_BUILD) { int buildID = evt->UnitIdx(); if(buildID == BWrepGameData::OBJ_COMMANDCENTER || buildID == BWrepGameData::OBJ_HATCHERY || buildID == BWrepGameData::OBJ_NEXUS) hotpoint = strExpand; if(buildID == BWrepGameData::OBJ_COMMANDCENTER) { // make sure it's not just a "land" const BWrepActionBuild::Params *p = (const BWrepActionBuild::Params *)action->GetParamStruct(); if(p->m_buildingtype!=BWrepGameData::BTYP_BUILD) hotpoint=0; } } // Leave game? else if(action->GetID()==BWrepGameData::CMD_LEAVEGAME) { hotpoint = strLeave; } // Drop? else if(action->GetID()==BWrepGameData::CMD_UNLOAD || action->GetID()==BWrepGameData::CMD_UNLOADALL || (action->GetID()==BWrepGameData::CMD_ATTACK && evt->Type().m_subcmd==BWrepGameData::ATT_UNLOAD)) { hotpoint = strDrop; } // Minimap ping? else if(action->GetID()==BWrepGameData::CMD_MINIMAPPING) { hotpoint = strMinimapPing; } // no hot point? if(hotpoint==0) return; // previous hotpoint too close? if((x-lastHotPointX)<32 && lastHotPoint==hotpoint) return; // make color lighter clr = CHsvRgb::Darker(clr,1.5); // get text size int w = pDC->GetTextExtent(hotpoint).cx; CRect rectTxt(x-w/2-off,y-off,x+w/2-off,y-10-off); // draw text pDC->SetTextColor(clr); int omode = pDC->SetBkMode(TRANSPARENT); pDC->DrawText(hotpoint,&rectTxt,DT_SINGLELINE|DT_CENTER|DT_VCENTER); pDC->SetBkMode(omode); // draw joining line pDC->MoveTo(x-off,y-off); pDC->LineTo(x,y); lastHotPointX = x; lastHotPoint = hotpoint; } //----------------------------------------------------------------------------------------------------------------- // draw a local maximum void DlgStats::_DrawLocalMax(CDC *pDC, int rx, int ry, const COLORREF clr, int& lastMaxX, int maxval) { // if it's not too close to previous Max if(rx>lastMaxX+32) { // draw a little triangle there lastMaxX = rx; for(int k=0;k<5;k++) { pDC->MoveTo(rx-k,ry-3-k); pDC->LineTo(rx+k+1,ry-3-k); } // draw max value CRect rectTxt(rx-16,ry-20,rx+16,ry-10); CString strMax; strMax.Format("%d",maxval); CFont *oldFont=pDC->SelectObject(m_pSmallFont); COLORREF oldClr=pDC->SetTextColor(clr); int omode = pDC->SetBkMode(TRANSPARENT); pDC->DrawText(strMax,rectTxt,DT_CENTER|DT_SINGLELINE); pDC->SetBkMode(omode); pDC->SetTextColor(oldClr); pDC->SelectObject(oldFont); } } //----------------------------------------------------------------------------------------------------------------- static const double BWPI = 3.1415926535897932384626433832795; static double _CosineInterpolate(double y1,double y2,double mu) { double mu2 = (1-cos(mu*BWPI))/2; return(y1*(1-mu2)+y2*mu2); } //----------------------------------------------------------------------------------------------------------------- class CKnotArray { public: //ctor CKnotArray(int knotcount) : m_knotcount(knotcount) { m_knots = new CPoint*[ReplayResource::__CLR_MAX]; for(int i=0;i<ReplayResource::__CLR_MAX;i++) m_knots[i] = new CPoint[knotcount]; memset(m_isUsed,0,sizeof(m_isUsed)); } //dtor ~CKnotArray() { for(int i=0;i<ReplayResource::__CLR_MAX;i++) delete[]m_knots[i]; delete[]m_knots; } // access CPoint *GetKnots(int curveidx) const {return m_knots[curveidx];} int GetKnotCount() const {return m_knotcount;} bool IsUsed(int i) const {return m_isUsed[i];} void SetIsUsed(int i) {m_isUsed[i]=true;} private: CPoint **m_knots; int m_knotcount; bool m_isUsed[ReplayResource::__CLR_MAX]; }; //----------------------------------------------------------------------------------------------------------------- // draw resource lines for one resource slot void DlgStats::_PaintResources2(CDC *pDC, int ybottom, int cx, DrawingTools *tools, ReplayResource *res, unsigned long time, CKnotArray& knot, int knotidx) { static int rx[DrawingTools::maxcurve],ry[DrawingTools::maxcurve]; static int orx[DrawingTools::maxcurve],ory[DrawingTools::maxcurve]; // save all current points for(int j=0; j<ReplayResource::MaxValue(); j++) { orx[j] = rx[j]; ory[j] = ry[j]; } // for each resource type for(int j=0; j<ReplayResource::MaxValue(); j++) { if(j==0 && (!m_seeMinerals || m_chartType!=RESOURCES)) continue; if(j==1 && (!m_seeGaz || m_chartType!=RESOURCES)) continue; if(j==2 && (!m_seeSupply || m_chartType!=RESOURCES)) continue; if(j==3 && (!m_seeUnits[m_chartType] || m_chartType!=RESOURCES)) continue; if(j==4 && (m_chartType!=APM)) continue; if(j==5 && (!m_seeBPM || m_chartType!=APM)) continue; if(j==6 && (!m_seeUPM || m_chartType!=APM)) continue; if(j==7 && (m_chartType!=APM)) continue; // micro if(j==8) continue; if(j==9 && m_chartType!=MAPCOVERAGE) continue; if(j==10 && (!m_seeUnits[m_chartType] || m_chartType!=MAPCOVERAGE)) continue; // we had a previous point, move beginning of line on it CPoint firstpt(rx[j],ry[j]); if(!firstPoint) pDC->MoveTo(rx[j],ry[j]); // compute position rx[j] = cx; ry[j] = ybottom - (int)((float)(res->Value(j))*m_fvinc[j]); // use splines? bool nodraw=false; if(j<4 || j==9 || j==10 || (j==4 && !m_seeSpeed)) {knot.GetKnots(j)[knotidx]=CPoint(cx,ry[j]); knot.SetIsUsed(j); nodraw=true;} // if upm or bpm if(j==5 || j==6) { // paint upm / bpm bar int w = max(4,(int)m_finc); pDC->FillSolidRect(cx-w/2,ry[j],w,ybottom-ry[j],tools->m_clr[j]); } else { // paint segment for resource line if(!firstPoint) pDC->SelectObject(tools->m_penMineral[j]); if(!nodraw) { if(!firstPoint && j!=7) { // if segment is long enough, and not a straight line if(cx-firstpt.x>8 && firstpt.y!=ry[j]) { // interpolate it for(int x=firstpt.x;x<=cx;x++) { double mu = (double)(x-firstpt.x)/(double)(cx-firstpt.x); double y = _CosineInterpolate(firstpt.y,ry[j],mu); pDC->LineTo(x,(int)y); } } else pDC->LineTo(rx[j],ry[j]); } } // is it a max for APM? if(j==4 && OPTIONSCHART->m_maxapm && res->Value(j) == m_list->ResourceMax().LegalAPM() && time>=MINAPMVALIDTIMEFORMAX) _DrawLocalMax(pDC, rx[j], ry[j], tools->m_clr[j], lastMaxX, m_list->ResourceMax().LegalAPM()); // is it a max for MAP coverage? if(j==10 && OPTIONSCHART->m_maxapm && res->Value(j) == m_list->ResourceMax().MovingMapCoverage()) _DrawLocalMax(pDC, rx[j], ry[j], tools->m_clr[j], lastMaxX, m_list->ResourceMax().MovingMapCoverage()); } } // compute position rx[4] = cx; ry[4] = ybottom - (int)((float)(res->Value(4))*m_fvinc[4]); // if macro is on if(m_chartType==APM && m_seeSpeed && !firstPoint) { // paint surface POINT pt[4]; pt[0].x = orx[4]; pt[1].x = rx[4]; pt[2].x = rx[7]; pt[3].x = orx[7]; pt[0].y = ory[4]; pt[1].y = ry[4]; pt[2].y = ry[7]; pt[3].y = ory[7]; CBrush bkgpoly(tools->m_clr[4]); CBrush *oldb = pDC->SelectObject(&bkgpoly); pDC->SelectObject(tools->m_penMineral[4]); pDC->Polygon(pt, 4); pDC->SelectObject(oldb); // draw up and bottom lines in darker color for antialiasing //CPen penred(PS_SOLID,2,RGB(235,0,0)); //CPen pengreen(PS_SOLID,2,RGB(0,0,235)); pDC->SelectObject(tools->m_penMineralDark[4]); //pDC->SelectObject(&penred); pDC->MoveTo(pt[0].x,pt[0].y); pDC->LineTo(pt[1].x,pt[1].y); //pDC->SelectObject(&pengreen); pDC->MoveTo(pt[2].x,pt[2].y); pDC->LineTo(pt[3].x,pt[3].y); } firstPoint=false; } //----------------------------------------------------------------------------------------------------------------- // paint a spline curve void DlgStats::_PaintSpline(CDC *pDC, const CKnotArray& knots, int curveidx) { // compute control points CPoint* firstControlPoints=0; CPoint* secondControlPoints=0; BezierSpline::GetCurveControlPoints(knots.GetKnots(curveidx), knots.GetKnotCount(), firstControlPoints, secondControlPoints); // allocate point array for call to PolyBezier int ptcount = 3*(knots.GetKnotCount()-1)+1; POINT* pts = new POINT[ptcount]; for(int i=0;i<knots.GetKnotCount()-1;i++) { int step = i*3; pts[step]=knots.GetKnots(curveidx)[i]; pts[step+1]=firstControlPoints[i]; pts[step+2]=secondControlPoints[i]; } pts[ptcount-1]=knots.GetKnots(curveidx)[knots.GetKnotCount()-1]; // draw curve pDC->PolyBezier(pts,ptcount); // delete arrays delete[]pts; delete[]firstControlPoints; delete[]secondControlPoints; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintEvents(CDC *pDC, int chartType, const CRect& rect, const ReplayResource& resmax, int player) { // any event to draw? if(m_list->GetEventCount()==0) return; // compute all ratios depending on the max of every resource float rheight = (float)(rect.Height()-vtop-vbottom); m_fvinc[0] = m_fvinc[1] = rheight/(float)(max(resmax.Minerals(),resmax.Gaz())); m_fvinc[2] = m_fvinc[3] = rheight/(float)(max(resmax.Supply(),resmax.Units())); m_fvinc[4] = rheight/(float)resmax.APM(); m_fvinc[5] = rheight/((float)resmax.BPM()*4.0f); m_fvinc[6] = rheight/((float)resmax.UPM()*2.0f); m_fvinc[7] = rheight/(float)resmax.APM(); m_fvinc[8] = rheight/(float)(resmax.MacroAPM()*4); m_fvinc[9] = m_fvinc[10] = rheight/(float)(max(resmax.MapCoverage(),resmax.MovingMapCoverage())); m_finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); // get drawing tools DrawingTools *tools = _GetDrawingTools(player); CPen *oldPen = (CPen*)pDC->SelectObject(tools->m_penMineral[0]); int oldMode = pDC->GetBkMode(); COLORREF oldclr = pDC->GetBkColor(); CFont *oldfont = pDC->SelectObject(m_pSmallFont); // where do we start painting? unsigned long timeBegin = m_timeBegin; //unsigned long timeBegin = m_bIsAnimating ? m_timeCursor : m_timeBegin; //if(m_timeCursor<500) timeBegin = 0; else timeBegin-=500; // reset last max data lastMaxX = 0; lastHotPointX = 0; lastHotPoint = 0; // for all resource slots firstPoint=true; int slotBegin = m_list->Time2Slot(m_timeBegin); int slotEnd = m_list->Time2Slot(m_timeEnd); // m_list->GetSlotCount() int slotCount = slotEnd-slotBegin; int divider = max(1,slotCount/gSplineCount[chartType]); int knotcount = slotCount==0 ? 0 : (slotCount/divider); CKnotArray *knots = knotcount==0 ? 0 : new CKnotArray(knotcount); for(int slot = slotBegin; slot<slotEnd; slot++) { // get resource object ReplayResource *res = m_list->GetResourceFromIdx(slot); unsigned long tick = m_list->Slot2Time(slot); // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (tick-m_timeBegin); int cx = (int)fx; // draw resource lines int knotslot = min(knotcount-1,(slot-slotBegin)/divider); _PaintResources2(pDC, rect.bottom - vbottom, cx, tools, res, tick, *knots, knotslot); } if(knots!=0) { // paint splines for(int i=0;i<ReplayResource::MaxValue();i++) if(knots->IsUsed(i)) { pDC->SelectObject(tools->m_penMineral[i]); _PaintSpline(pDC,*knots,i); } delete knots; } if(m_chartType==RESOURCES && (m_seeActions || (m_seeMinerals && m_seeHotPoints))) { // for each event in the current window, paint hot points int layer=0; unsigned long eventMax = (unsigned long)m_list->GetEventCount(); CRect rectEvt; firstPoint=true; lastMaxX = 0; lastHotPointX = 0; lastHotPoint = 0; for(unsigned long idx = m_list->GetEventFromTime(timeBegin);;idx++) { // get event description if(idx>=eventMax) break; const ReplayEvt *evt = m_list->GetEvent(idx); if(evt->Time()>m_timeEnd) break; // during animation, we only paint until cursor if(m_bIsAnimating && evt->Time()>m_timeCursor) break; // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (evt->Time()-m_timeBegin); int cx = (int)fx; // if we paint actions if(m_seeActions) { // compute event rect rectEvt.left=cx-evtWidth/2; rectEvt.right=cx+evtWidth/2; layer = m_replay.GetTypeIdx(evt); rectEvt.bottom=rect.bottom-vbottom-layer*layerHeight-(layerHeight-evtHeight)/2; rectEvt.top=rectEvt.bottom-evtHeight-(layerHeight-evtHeight)/2+1; if(rectEvt.top>rect.top) _PaintOneEvent(pDC,&rectEvt,evt); } // draw hot point (if any) firstPoint=false; if(m_seeMinerals && m_seeHotPoints && !evt->IsDiscarded()) { int y = rect.bottom-vbottom - (int)((float)(evt->Resources().Value(0))*m_fvinc[0]); pDC->SelectObject(tools->m_penMineralS[0]); _PaintHotPoint(pDC, cx, y, evt, tools->m_clr[0]); } } } else if(m_chartType==APM) { // for each event in the current window, paint hot points unsigned long eventMax = (unsigned long)m_list->GetEventCount(); CRect rectEvt; for(unsigned long idx = m_list->GetEventFromTime(timeBegin);;idx++) { // get event description if(idx>=eventMax) break; const ReplayEvt *evt = m_list->GetEvent(idx); if(evt->Time()>m_timeEnd) break; if(evt->ActionID()!=BWrepGameData::CMD_MESSAGE) continue; // during animation, we only paint until cursor if(m_bIsAnimating && evt->Time()>m_timeCursor) break; // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (evt->Time()-m_timeBegin); int cx = (int)fx; // if we paint actions if(m_seeHotPoints) { // compute event rect rectEvt.left=cx-evtWidth/2; rectEvt.right=cx+evtWidth/2; int layer = 0; rectEvt.bottom=rect.bottom-vbottom-layer*layerHeight-(layerHeight-evtHeight)/2; rectEvt.top=rectEvt.bottom-evtHeight-(layerHeight-evtHeight)/2+1; if(rectEvt.top>rect.top) _PaintOneEvent(pDC,&rectEvt,evt); } } } else if(m_chartType==MAPCOVERAGE) { } // restore every gdi stuff pDC->SelectObject(oldPen); pDC->SetBkMode(oldMode); pDC->SetBkColor(oldclr); pDC->SelectObject(oldfont); } //----------------------------------------------------------------------------------------------------------------- // compute vertical increment for grid and axis float DlgStats::_ComputeGridInc(unsigned long& tminc, unsigned long& maxres, const CRect& rect, const ReplayResource& resmax, int chartType, bool useGivenMax) const { if(!useGivenMax) { // compute max value switch(chartType) { case APM : maxres = resmax.APM(); break; case MAPCOVERAGE : maxres = max(resmax.MapCoverage(),resmax.MovingMapCoverage()); break; default: maxres = max(resmax.Minerals(),resmax.Gaz()); } } // compute vertical pixel per value float fvinc = (float)(rect.Height()-vbottom-vtop)/(float)(maxres); // compute grid increment tminc=((maxres/10)/1000)*1000; if(tminc==0) tminc=tminc=((maxres/10)/100)*100; if(tminc==0) tminc=((maxres/10)/10)*10; if(tminc==0) tminc=5; if(maxres<15) tminc=1; return fvinc; } void DlgStats::_PaintGrid(CDC *pDC, const CRect& rect, const ReplayResource& resmax) { if(!OPTIONSCHART->m_bggrid) return; // create pen for axis CPen *penGrid = new CPen(PS_DOT,1,clrGrid); CPen *oldPen = pDC->SelectObject(penGrid); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw horizontal lines of grid unsigned long maxres = 0; unsigned long tminc; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax,m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { // draw grid float fy=(float)(rect.bottom-vbottom) - fvinc * tr; pDC->MoveTo(rect.left+hleft+1,(int)fy); pDC->LineTo(rect.right-hright,(int)fy); } // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); delete penGrid; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintActionsName(CDC *pDC, const CRect& rect) { if(!m_seeActions || m_chartType!=RESOURCES) return; // draw layers CString strNum; CRect rectTxt; CFont *oldFont = pDC->SelectObject(m_pLayerFont); // compute first layer rect CRect rectLayer=rect; rectLayer.top = rectLayer.bottom-layerHeight; rectLayer.OffsetRect(hleft,-vbottom); rectLayer.right-=hleft+hright; COLORREF bkc = pDC->GetBkColor(); // for each layer for(int k=0; k<m_replay.GetTypeCount();k++) { // fill layer rect COLORREF clrLayer = (k%2)==0 ? clrLayer1 : clrLayer2; pDC->FillSolidRect(&rectLayer,clrLayer); // draw layer action name clrLayer = (k%2)==0 ? clrLayerTxt1 : clrLayerTxt2; rectTxt = rectLayer; rectTxt.left+=28; rectTxt.right = rectTxt.left+128; pDC->SetTextColor(clrLayer); pDC->DrawText(m_replay.GetTypeStr(k),rectTxt,DT_LEFT|DT_SINGLELINE); //next layer rectLayer.OffsetRect(0,-layerHeight); if(rectLayer.bottom-layerHeight < rect.top) break; } // restore bkcolor pDC->SetBkColor(bkc); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintAxis(CDC *pDC, const CRect& rect, const ReplayResource& resmax, int mask, unsigned long timeBegin, unsigned long timeEnd) { // create pen for axis CPen *penTime = new CPen(PS_SOLID,1,clrTime); CPen *penAction = new CPen(PS_SOLID,1,clrAction); CPen *oldPen = (CPen*)pDC->SelectObject(penTime); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw X axis values CString strNum; CRect rectTxt; float finc = timeEnd>timeBegin ? (float)(rect.Width()-hleft-hright)/(float)(timeEnd - timeBegin) : 0.0f; unsigned long tminc = 10; unsigned long maxres; while(timeEnd>timeBegin && (int)(tminc*finc)<50) tminc*=2; COLORREF oldClr = pDC->SetTextColor(clrTime); CFont *oldFont=pDC->SelectObject(m_pSmallFont); if(mask&MSK_XLINE && timeEnd>timeBegin) { for(unsigned long tm=timeBegin; tm<timeEnd; tm+=tminc) { float fx=(float)(rect.left+hleft) + finc * (tm-timeBegin); strNum = _MkTime(m_replay.QueryFile()->QueryHeader(),tm, m_useSeconds?true:false); int cx = (int)fx; // draw time rectTxt.SetRect(cx,rect.bottom-vbottom+2,cx+128,rect.bottom); pDC->DrawText(strNum,rectTxt,DT_LEFT|DT_SINGLELINE); // draw line pDC->MoveTo(cx,rect.bottom-vbottom-1); pDC->LineTo(cx,rect.bottom-vbottom+2); } } if((m_seeMinerals || m_seeGaz) && m_chartType==RESOURCES) { // draw left Y axis values (minerals and gas) int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); if(mask&MSK_YLEFTLINE) { for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw left Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft+16,rect.top+16); pDC->DrawText(strMinGas,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); } } if((m_seeSupply || m_seeUnits[m_chartType]) && m_chartType==RESOURCES) { // draw right Y axis values (supply & units) if(mask&MSK_YRIGHTLINE) { maxres = resmax.Supply(); float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType,true); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText(strSupplyUnit,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } if(m_chartType==APM) { pDC->SelectObject(penAction); pDC->SetTextColor(clrAction); // draw actions/minute Y axis values int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw actions/minute Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft-3,rect.top+16); pDC->DrawText("APM",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); // draw right Y axis values (supply & units) if(mask&MSK_YRIGHTLINE) { fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText("APM",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } else if(m_chartType==MAPCOVERAGE) { pDC->SelectObject(penAction); pDC->SetTextColor(clrAction); // draw coverage Y axis values int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw building map coverage Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft-3,rect.top+16); pDC->DrawText("%Map",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); if(m_seeUnits[m_chartType]) { // draw right Y axis values (unit map coverage) if(mask&MSK_YRIGHTLINE) { maxres = resmax.MovingMapCoverage(); float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType,true); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText("%Map",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } } // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); pDC->SetTextColor(oldClr); pDC->SelectObject(oldFont); delete penTime; delete penAction; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintAxisLines(CDC *pDC, const CRect& rect, int mask) { // create pen for axis CPen *penTime = new CPen(PS_SOLID,1,clrTime); CPen *oldPen = (CPen*)pDC->SelectObject(penTime); // draw X axis time line if(mask&MSK_XLINE) { pDC->MoveTo(rect.left+hleft,rect.bottom-vbottom); pDC->LineTo(rect.right-hright,rect.bottom-vbottom); } // draw left Y axis time line if(mask&MSK_YLEFTLINE) { pDC->MoveTo(rect.left+hleft,rect.bottom-vbottom); pDC->LineTo(rect.left+hleft,rect.top+vtop); } // draw right Y axis time line if(mask&MSK_YRIGHTLINE) { pDC->MoveTo(rect.right-hright,rect.bottom-vbottom); pDC->LineTo(rect.right-hright,rect.top+vtop); } // restore every gdi stuff pDC->SelectObject(oldPen); delete penTime; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBackgroundLayer(CDC *pDC, const CRect& rect, const ReplayResource& resmax) { // draw horizontal lines of grid _PaintGrid(pDC, rect, resmax); // draw layers _PaintActionsName(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintForegroundLayer(CDC *pDC, const CRect& rect, const ReplayResource& resmax, int mask) { // draw X & Yaxis time line _PaintAxisLines(pDC, rect, mask); // draw X & Y axis values _PaintAxis(pDC, rect, resmax,MSK_ALL,m_timeBegin,m_timeEnd); // draw cursor _PaintCursor(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMapName(CDC *pDC, CRect& rect) { if(m_chartType!=RESOURCES && m_chartType!=APM) return; // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelBoldFont); int oldMode = pDC->SetBkMode(TRANSPARENT); // build title CString title(m_replay.MapName()); if(m_replay.RWAHeader()!=0) { CString audioby; audioby.Format(IDS_AUDIOCOMMENT,m_replay.RWAHeader()->author); title+=audioby; } //get title size with current font CSize sz = pDC->GetTextExtent(title); // draw text CRect rectTxt; rectTxt.SetRect(rect.left+hplayer,rect.top,rect.left+hplayer+sz.cx,rect.top+28); pDC->SetTextColor(OPTIONSCHART->GetColor(DlgOptionsChart::CLR_MAP)); pDC->DrawText(title,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); m_rectMapName = rectTxt; // restore pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintSentinel(CDC *pDC, CRect& rectTxt) { if(m_chartType!=RESOURCES && m_chartType!=APM) return; CString gamename = m_replay.QueryFile()->QueryHeader()->getGameName(); if(gamename.Left(11)=="BWSentinel ") { // select font & color CFont *oldFont = pDC->SelectObject(m_pSmallFont); int oldMode = pDC->SetBkMode(TRANSPARENT); // draw text pDC->SetTextColor(clrPlayer); pDC->DrawText("(sentinel on)",rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // restore pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintPlayerName(CDC *pDC, const CRect& rectpl, ReplayEvtList *list, int playerIdx, int playerPos, COLORREF clr, int offv) { CRect rect(rectpl); rect.OffsetRect(4,0); // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelBoldFont); COLORREF oldClr = pDC->SetTextColor(clr); COLORREF bkClr = pDC->GetBkColor(); int oldMode = pDC->GetBkMode(); // draw player name CString pname; CRect rectTxt; pname.Format("%s (%s)",list->PlayerName(),list->GetRaceStr()); rectTxt.SetRect(rect.left+hplayer,rect.top+offv,rect.left+hplayer+200,rect.top+offv+28); if(playerPos>=0) rectTxt.OffsetRect(0,playerPos*28); if(m_chartType!=RESOURCES && m_chartType!=APM && m_mixedCount==0) rectTxt.OffsetRect(-hplayer+hleft,0); pDC->SetTextColor(clr); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(pname,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); CRect rectRatio=rectTxt; // text size int afterText = pDC->GetTextExtent(pname).cx; // draw colors of resource lines if(playerIdx>=0) { rectTxt.top+=22; rectTxt.right=rectTxt.left+12; rectTxt.bottom=rectTxt.top+3; for(int j=0; j<ReplayResource::MaxValue(); j++) { if(j==0 && (!m_seeMinerals || m_chartType!=RESOURCES)) continue; if(j==1 && (!m_seeGaz || m_chartType!=RESOURCES)) continue; if(j==2 && (!m_seeSupply || m_chartType!=RESOURCES)) continue; if(j==3 && (!m_seeUnits[m_chartType] || m_chartType!=RESOURCES)) continue; if(j==4 && (!m_seeSpeed || m_chartType!=APM)) continue; if(j==5 && (!m_seeBPM || m_chartType!=APM)) continue; if(j==6 && (!m_seeUPM || m_chartType!=APM)) continue; if(j==7 || j==8) continue; pDC->FillSolidRect(&rectTxt,_GetDrawingTools(playerIdx)->m_clr[j]); rectTxt.OffsetRect(rectTxt.Width()+3,0); } } // add player info if(m_chartType>=UNITS && m_chartType<=UPGRADES) { // display distribution total pname.Format(IDS_TOTAL,list->GetDistTotal(m_chartType-UNITS)); } else { // display APM stuff //if(m_maxPlayerOnBoard==2) //{ // compute action ratio //ReplayEvtList *list1 = m_replay.GetEvtList(0); //ReplayEvtList *list2 = m_replay.GetEvtList(1); //float ratio = list==list1 ? (float)list1->GetEventCount()/(float)list2->GetEventCount() : (float)list2->GetEventCount()/(float)list1->GetEventCount(); //pname.Format("[%.2f, %d, %d APM]",ratio,list->GetEventCount(),list->GetActionPerMinute()); //} pname.Format("[%d actions APM=%d]",list->GetEventCount(),list->GetActionPerMinute()); } rectRatio.OffsetRect(afterText+8,0); pDC->SelectObject(m_pLayerFont); pDC->SetTextColor(clrRatio); pDC->SetBkColor(RGB(0,0,0)); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(pname,rectRatio,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // restore every gdi stuff pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkColor(bkClr); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCursor(CDC *pDC, const CRect& rect) { // compute position float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(rect.left+hleft) + finc * (m_timeCursor-m_timeBegin); // prepare pen CPen *penCursor = new CPen(PS_DOT,1,clrCursor); CPen *oldPen = pDC->SelectObject(penCursor); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw cursor pDC->MoveTo((int)fxc,rect.top); pDC->LineTo((int)fxc,rect.bottom); // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); delete penCursor; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBO(CDC *pDC, const CRect& rect, const ReplayObjectSequence& bo, int offset) { // draw building names int levelh = (rect.Height()-32-vplayer)/4; for(int i=0;i<bo.GetCount();i++) { float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(rect.left+hleft) + finc * bo.GetTime(i); int y = rect.top+vplayer+16 + ((i+1)%4)*levelh + offset; pDC->MoveTo((int)fxc,y); pDC->LineTo((int)fxc,rect.bottom-vbottom); // text size CString pname = bo.GetName(i); int wText = pDC->GetTextExtent(pname).cx; CRect rectText; y-=16; rectText.SetRect((int)fxc-wText/2, y, (int)fxc+wText/2, y+16); rectText.InflateRect(1,1); pDC->DrawText(pname,rectText,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBuildOrder(CDC *pDC, const CRect& rect) { // select font & color CFont *oldFont = pDC->SelectObject(m_pLayerFont); COLORREF oldClr = pDC->SetTextColor(clrBOName[0]); int oldMode = pDC->GetBkMode(); CPen *penCursor = new CPen(PS_SOLID,1,clrBOLine[0]); CPen *penCursor2 = new CPen(PS_SOLID,1,clrBOLine[1]); CPen *penCursor3 = new CPen(PS_SOLID,1,clrBOLine[2]); // draw X & Y axis values ReplayResource resmax; _PaintAxis(pDC, rect, resmax, MSK_XLINE,m_timeBegin,m_timeEnd); // draw building names CPen *oldPen = pDC->SelectObject(penCursor); pDC->SetBkMode(TRANSPARENT); _PaintBO(pDC, rect, m_list->GetBuildOrder(),0); // draw upgrades pDC->SetTextColor(clrBOName[2]); pDC->SelectObject(penCursor3); _PaintBO(pDC, rect, m_list->GetBuildOrderUpgrade(),10); // draw research pDC->SetTextColor(clrBOName[2]); pDC->SelectObject(penCursor3); _PaintBO(pDC, rect, m_list->GetBuildOrderResearch(),20); // draw units names if(m_seeUnitsOnBO) { pDC->SetTextColor(clrBOName[1]); pDC->SelectObject(penCursor2); _PaintBO(pDC, rect, m_list->GetBuildOrderUnits(),30); } // paint foreground layer (axis lines + cursor) _PaintForegroundLayer(pDC, rect, resmax, MSK_XLINE); // restore every gdi stuff pDC->SelectObject(oldPen); pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkMode(oldMode); delete penCursor3; delete penCursor2; delete penCursor; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_ComputeHotkeySymbolRect(const ReplayEvtList *list, const HotKeyEvent *hkevt, CRect& datarect, CRect& symRect) { // compute symbol position int levelhk = (datarect.Height()-8-vplayer)/10; float finc = (float)(datarect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(datarect.left+hleft) + finc * (hkevt->m_time - m_timeBegin); int y = datarect.top+vplayer + hkevt->m_slot*levelhk; int wText = 10; symRect.SetRect((int)fxc-wText/2, y, (int)fxc+wText/2, y+levelhk); symRect.InflateRect(2,2); symRect.DeflateRect(0,(levelhk-wText)/2); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintHotKeyEvent(CDC *pDC, CRect& datarect, int offset) { char text[3]; CRect symRect; // draw hotkey events for(int i=0;i<(int)m_list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = m_list->GetHKEvent(i); if(hkevt->m_time < m_timeBegin || hkevt->m_time > m_timeEnd) continue; // view hotkey selection? if(!m_viewHKselect && hkevt->m_type==HotKeyEvent::SELECT) continue; // compute symbol position _ComputeHotkeySymbolRect(m_list, hkevt, datarect, symRect); // text size sprintf(text,"%d", hkevt->m_slot==9?0:hkevt->m_slot+1); // draw text CRect rectText; pDC->SetTextColor(hkevt->m_type!=HotKeyEvent::ASSIGN ? RGB(100,0,100):RGB(0,0,0)); if(hkevt->m_type==HotKeyEvent::ASSIGN) pDC->FillSolidRect(symRect,RGB(100,0,200)); else if(hkevt->m_type==HotKeyEvent::ADD) pDC->Draw3dRect(symRect,RGB(100,0,200),RGB(100,0,200)); pDC->DrawText(text,symRect,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintHotKeys(CDC *pDC, const CRect& rectc) { // select font & color CFont *oldFont = pDC->SelectObject(m_pLayerFont); int oldMode = pDC->GetBkMode(); int oldbkClr = pDC->GetBkColor(); // height of a key strip int levelhk = (rectc.Height()-8-vplayer)/10; // offset rect CRect rect(rectc); rect.left += m_dataAreaX; // draw X & Y axis values ReplayResource resmax; _PaintAxis(pDC, rect, resmax, MSK_XLINE,m_timeBegin,m_timeEnd); // draw hotkey numbers pDC->SetBkMode(TRANSPARENT); int oldclr = pDC->SetTextColor(RGB(0,0,0)); COLORREF clrkey=RGB(255,255,0); COLORREF clrkeydark=CHsvRgb::Darker(clrkey,0.50); for(int i=0;i<10;i++) { // compute symbol position int y = rect.top+vplayer + i*levelhk; // text size CString hkslot; hkslot.Format("%d",i==9?0:i+1); // compute key rect CRect rectText; int wkey = min (24,levelhk-4); int hkey = (85*levelhk)/100; int delta = (levelhk-hkey)/2; rectText.SetRect(rect.left+6-m_dataAreaX,y+delta,0,y+hkey+delta); rectText.right = rectText.left + wkey; while(rectText.Width()<4) rectText.InflateRect(1,1); // fill key rect COLORREF clr = m_list->IsHotKeyUsed(i) ? clrkey : clrkeydark; //pDC->FillSolidRect(rectText,clr); Gradient::Fill(pDC,rectText,clr,CHsvRgb::Darker(clr,0.70)); pDC->Draw3dRect(rectText,clr,CHsvRgb::Darker(clr,0.80)); // draw text pDC->DrawText(hkslot,rectText,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } // draw hotkey events _PaintHotKeyEvent(pDC, rect,0); // paint foreground layer (axis lines + cursor) _PaintForegroundLayer(pDC, rect, resmax, MSK_XLINE); // restore rect rect.left -= m_dataAreaX; // restore every gdi stuff pDC->SetBkMode(oldMode); pDC->SetTextColor(oldclr); pDC->SetBkColor(oldbkClr); } //----------------------------------------------------------------------------------------------------------------- static int _gType; static ReplayEvtList* _gList; static int _gCompareElements( const void *arg1, const void *arg2 ) { int i1 = *((int*)arg1); int i2 = *((int*)arg2); return _gList->GetDistCount(_gType,i2)-_gList->GetDistCount(_gType,i1); } void DlgStats::_PaintDistribution(CDC *pDC, const CRect& rect, int type) { //empty distribution? if(m_list->GetDistTotal(type)==0) return; // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelFont); COLORREF oldClr = pDC->SetTextColor(clrUnitName); COLORREF bkClr = pDC->GetBkColor(); // compute number of non null elements in the distribution int elemcount=m_list->GetDistNonNullCount(type); int dvalmax = m_seePercent ? 50 : m_replay.GetDistPeak(type); // skip elements with 0.0% count if(m_seePercent) { for(int i=0; i<m_list->GetDistMax(type); i++) { int dval = (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type); if(dval>dvalmax) dvalmax=dval; if(m_list->GetDistCount(type,i)>0 && dval==0) elemcount--; } } // compute bar height CRect barRect = rect; barRect.top+=32; barRect.DeflateRect(hleft,0); int barHeight = elemcount==0 ? 0 : min(40,barRect.Height()/elemcount); // select adequate font pDC->SelectObject((barHeight<18) ? ((barHeight<10) ? m_pSmallFont : m_pLayerFont) : m_pLabelFont); int barStart = 150; //(barHeight<18) ? ((barHeight<10) ? 80 : 110) : 150; // create array of pointer to distribution elements int *elemIdx = new int[m_list->GetDistMax(type)]; int j=0; for(int i=0; i<m_list->GetDistMax(type); i++) { // skip elements with 0 count if(m_list->GetDistCount(type,i)==0) continue; // skip elements with 0.0% count if(m_seePercent && (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type)==0) continue; elemIdx[j]=i; j++; } // sort array if(m_sortDist) { _gType=type; _gList=m_list; qsort(elemIdx,j,sizeof(int),_gCompareElements); } // for each element CString val; barRect.bottom = barRect.top + barHeight; int barSpacing = (15*barHeight)/100; //for(int i=0; i<m_list->GetDistMax(type); i++) for(int k=0; k<j; k++) { int i=elemIdx[k]; /* // skip elements with 0 count if(m_list->GetDistCount(type,i)==0) continue; // skip elements with 0.0% count if(m_seePercent && (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type)==0) continue; */ // display element name //pDC->SetBkColor(RGB(0,0,0)); pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(clrUnitName); pDC->DrawText(m_list->GetDistName(type,i),barRect,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // what value int dval = m_seePercent ? (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type) : m_list->GetDistCount(type,i); // draw bar int barWidth = dval*(barRect.Width() - (barStart+42))/dvalmax; CRect zbar=barRect; zbar.DeflateRect(barStart,barSpacing,0,barSpacing); zbar.right =zbar.left+barWidth; COLORREF clr = m_list->GetDistColor(type,i); Gradient::Fill(pDC,&zbar,clr,CHsvRgb::Darker(clr,0.6),GRADIENT_FILL_RECT_V); //pDC->FillSolidRect(&zbar,clr); // draw value if(m_seePercent) { /* if(dval==0) { double fval = (100.0*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type); val.Format("%.1f%%",fval); } else */ val.Format("%d%%",dval); } else val.Format("%d",dval); pDC->SetTextColor(clrUnitName); int oldMode=pDC->SetBkMode(TRANSPARENT); zbar.left=zbar.right+4; zbar.right+=42; pDC->DrawText(val,zbar,DT_LEFT|DT_SINGLELINE|DT_VCENTER); pDC->SetBkMode(oldMode); // next element barRect.OffsetRect(0,barHeight); } delete[]elemIdx; // restore every gdi stuff pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkColor(bkClr); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetDataRectForPlayer(int plidx, CRect& rect, int pcount) { assert(pcount>0); rect = m_boardRect; rect.bottom = rect.top+rect.Height()/pcount; rect.OffsetRect(0,rect.Height()*plidx); } //----------------------------------------------------------------------------------------------------------------- // paint one chart for one player void DlgStats::_PaintChart(CDC *pDC, int chartType, const CRect& rect, int minMargin) { //what kind of chart do we paint? hleft = max(minMargin,6); if(chartType==BUILDORDER) { // build order _PaintBuildOrder(pDC,rect); } else if(chartType==HOTKEYS) { // build hotkeys _PaintHotKeys(pDC,rect); } else if(chartType!=RESOURCES && chartType!=MAPCOVERAGE && chartType!=APM) { // any distribution _PaintDistribution(pDC,rect,chartType-2); } else { hleft = max(minMargin,30); // paint background layer _PaintBackgroundLayer(pDC, rect, m_list->ResourceMax()); // draw selected events & resources _PaintEvents(pDC, chartType, rect, m_list->ResourceMax()); // paint foreground layer _PaintForegroundLayer(pDC, rect, m_list->ResourceMax()); } // draw player name _PaintPlayerName(pDC, rect, m_list, -1, -1, clrPlayer); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMultipleCharts(CDC *pDC) { m_rectMapName.SetRectEmpty(); // for each player on board CRect rect; m_shape = SQUARE; for(int i=0,j=0; i<m_replay.GetPlayerCount() && j<m_maxPlayerOnBoard; i++) { // get event list for that player m_list = m_replay.GetEvtList(i); if(!m_list->IsEnabled()) continue; // get rect for the player's charts _GetDataRectForPlayer(j, rect, m_maxPlayerOnBoard); // paint one chart for one player _PaintChart(pDC, m_chartType, rect); // offset shape for next player m_shape=(eSHAPE)((int)m_shape+1); j++; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMixedCharts(CDC *pDC, int playerIdx, int *chartType, int count) { m_rectMapName.SetRectEmpty(); // for required chart CRect rect; m_shape = SQUARE; m_mixedCount=count; m_MixedPlayerIdx=playerIdx; for(int i=0; i<count; i++) { // get event list for that player m_list = m_replay.GetEvtList(playerIdx); // get rect for the chart _GetDataRectForPlayer(i, rect, count); // paint one chart int ctype = m_chartType; m_chartType = chartType[i]; _PaintChart(pDC, chartType[i], rect, 35); m_mixedRect[i]=rect; m_mixedChartType[i]=m_chartType; m_chartType=ctype; } } //----------------------------------------------------------------------------------------------------------------- // get index of first enabled player int DlgStats::_GetFirstEnabledPlayer() const { // for each player on board for(int i=0; i<m_replay.GetPlayerCount(); i++) if(m_replay.GetEvtList(i)->IsEnabled()) return i; return 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintSingleChart(CDC *pDC) { CRect rect = m_boardRect; hleft = 30; // paint background layer _PaintBackgroundLayer(pDC, rect, m_replay.ResourceMax()); // for each player on board m_shape = SQUARE; for(int i=0,j=0; j<m_maxPlayerOnBoard; i++) { // get event list for that player m_list = m_replay.GetEvtList(i); if(!m_list->IsEnabled()) continue; // draw selected events & resources _PaintEvents(pDC, m_chartType, rect, m_replay.ResourceMax(),i); m_shape=(eSHAPE)((int)m_shape+1); j++; } // paint foreground layer _PaintForegroundLayer(pDC, rect, m_replay.ResourceMax()); // paint map name _PaintMapName(pDC,rect); int offv = vplayer-8; // draw players name for(int i=0,j=0; j<m_maxPlayerOnBoard; i++) { // get event list for that player ReplayEvtList* list = m_replay.GetEvtList(i); if(!list->IsEnabled()) continue; _PaintPlayerName(pDC, rect, list, i,j, clrPlayer,offv); j++; } // paint sentinel logo if needed rect.SetRect(rect.left+hplayer+220,rect.top,rect.left+hplayer+280,rect.top+28); _PaintSentinel(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCheckBoxColor(CDC *pDC) { UINT cid[]={IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITS}; for(int i=0;i<sizeof(cid)/sizeof(cid[0]);i++) { CRect rect; GetDlgItem(cid[i])->GetWindowRect(&rect); ScreenToClient(&rect); rect.OffsetRect(-8,0); rect.DeflateRect(0,2); rect.right = rect.left+6; rect.top--; pDC->FillSolidRect(&rect,_GetDrawingTools(0)->m_clr[i]); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCharts(CDC *pDC) { m_maxPlayerOnBoard = min(MAXPLAYERONVIEW,m_replay.GetEnabledPlayerCount()); if(m_maxPlayerOnBoard>0) { if(m_chartType==MIX_APMHOTKEYS) { int ctype[]={APM,HOTKEYS}; _PaintMixedCharts(pDC,_GetFirstEnabledPlayer(),ctype,sizeof(ctype)/sizeof(ctype[0])); } else if(!m_singleChart[m_chartType] || (m_chartType!=RESOURCES && m_chartType!=APM && m_chartType!=MAPCOVERAGE)) _PaintMultipleCharts(pDC); else _PaintSingleChart(pDC); _PaintCheckBoxColor(pDC); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_SelectAction(int idx) { // update selected player char szPlayerName[128]; m_listEvents.GetItemText(idx,1,szPlayerName,sizeof(szPlayerName)); for(int i=0; i<m_replay.GetPlayerCount(); i++) if(_stricmp(m_replay.GetEvtList(i)->PlayerName(),szPlayerName)==0) {m_selectedPlayer = i; break;} // update current cursor pos ReplayEvt *evt = _GetEventFromIdx(idx); _SetTimeCursor(evt->Time(),false); // suspect event? GetDlgItem(IDC_SUSPECT_INFO)->SetWindowText(""); if(evt->IsSuspect()) { CString origin; ReplayEvtList *list = (ReplayEvtList *)evt->GetAction()->GetUserData(0); list->GetSuspectEventOrigin(evt->GetAction(),origin,m_useSeconds?true:false); GetDlgItem(IDC_SUSPECT_INFO)->SetWindowText(origin); } // remember selected action index m_selectedAction = idx; } //--------------------------------------------------------------------------------------- void DlgStats::OnItemchangedListevents(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; if(pNMListView->uNewState&(LVIS_SELECTED+LVIS_FOCUSED) && !m_lockListView && (pNMListView->iItem!=-1)) { // update selected player & cursor pos _SelectAction(pNMListView->iItem); } *pResult = 0; } //--------------------------------------------------------------------------------------- inline unsigned long DlgStats::_GetActionCount() { return m_replay.GetEnActionCount();//(unsigned long)m_replay.QueryFile()->QueryActions()->GetActionCount(); } //--------------------------------------------------------------------------------------- ReplayEvt * DlgStats::_GetEventFromIdx(unsigned long idx) { assert(idx<_GetActionCount()); const IStarcraftAction *action = m_replay.GetEnAction(idx); //m_replay.QueryFile()->QueryActions()->GetAction(idx); ReplayEvtList *list = (ReplayEvtList *)action->GetUserData(0); ReplayEvt *evt = list->GetEvent(action->GetUserData(1)); return evt; } //--------------------------------------------------------------------------------------- // cursor = value between 0 and full span time // will find the nearest event unsigned long DlgStats::_GetEventFromTime(unsigned long cursor) { unsigned long eventCount = _GetActionCount(); if(eventCount==0) return 0; unsigned long nSlot = 0; unsigned long low = 0; unsigned long high = eventCount - 1; unsigned long beginTimeTS = 0; unsigned long i; unsigned long eventTime; // for all events in the list while(true) { i= (high+low)/2; ASSERT(high>=low); // are we beyond the arrays boundaries? if(i>=eventCount) {nSlot=0;break;} // get event time ReplayEvt *evt = _GetEventFromIdx(i); eventTime = evt->Time(); // compare times LONGLONG delta = eventTime-beginTimeTS; LONGLONG nCmp = (LONGLONG )cursor - delta; // if event time is the same, return index if(nCmp==0) { nSlot = i; goto Exit; } else if(nCmp<0) { if(high==low) {nSlot = low; break;} high = i-1; if(high<low) {nSlot=low; break;} if(high<0) {nSlot=0; break;} } else { if(high==low) {nSlot = low+1; break;} low = i+1; if(low>high) {nSlot=high; break;} if(low>=eventCount-1) {nSlot=eventCount-1; break;} } } ASSERT(nSlot<eventCount); Exit: // make sure event belong to the right player char szPlayerName[128]; int nSlotBegin=nSlot; for(;nSlot<eventCount;) { // get event time ReplayEvt *evt = _GetEventFromIdx(nSlot); assert(evt!=0); if(evt->Time()>cursor) break; m_listEvents.GetItemText(nSlot,1,szPlayerName,sizeof(szPlayerName)); if(strcmp(m_replay.GetEvtList(m_selectedPlayer)->PlayerName(),szPlayerName)!=0) nSlot++; else break; } if(nSlot>=eventCount) nSlot=nSlotBegin; else { ReplayEvt *evt = _GetEventFromIdx(nSlot); if(evt->Time()>cursor) nSlot=nSlotBegin; } return nSlot; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_AdjustWindow() { unsigned long windowWidth = (unsigned long)((double)m_replay.GetEndTime()/pow(2.0f,m_zoom)); if(m_timeCursor<windowWidth/2) { m_timeBegin = 0; m_timeEnd = windowWidth; } else if(m_timeCursor+windowWidth/2>m_replay.GetEndTime()) { m_timeBegin = m_replay.GetEndTime()-windowWidth; m_timeEnd = m_replay.GetEndTime(); } else { m_timeBegin = m_timeCursor-windowWidth/2; m_timeEnd = m_timeCursor+windowWidth/2; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeZoom() { UpdateData(TRUE); if(m_zoom==0) { m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); } else { _AdjustWindow(); } Invalidate(FALSE); } //-------------------------------------------------------------------------------- BOOL DlgStats::_OnScroll(UINT nScrollCode, UINT nPos, BOOL bDoScroll) { // calc new x position int x = m_scroller.GetScrollPos(); int xOrig = x; switch (LOBYTE(nScrollCode)) { case SB_TOP: x = 0; break; case SB_BOTTOM: x = INT_MAX; break; case SB_LINEUP: x -= m_lineDev.cx; break; case SB_LINEDOWN: x += m_lineDev.cx; break; case SB_PAGEUP: x -= m_pageDev.cx; break; case SB_PAGEDOWN: x += m_pageDev.cx; break; case SB_THUMBTRACK: x = nPos; break; } // calc new y position int y = m_scrollerV.GetScrollPos(); int yOrig = y; switch (HIBYTE(nScrollCode)) { case SB_TOP: y = 0; break; case SB_BOTTOM: y = INT_MAX; break; case SB_LINEUP: y -= m_lineDev.cy; break; case SB_LINEDOWN: y += m_lineDev.cy; break; case SB_PAGEUP: y -= m_pageDev.cy; break; case SB_PAGEDOWN: y += m_pageDev.cy; break; case SB_THUMBTRACK: y = nPos; break; } BOOL bResult = _OnScrollBy(CSize(x - xOrig, y - yOrig), bDoScroll); /* if (bResult && bDoScroll) { Invalidate(); UpdateWindow(); } */ return bResult; } //------------------------------------------------------------------------------------------ BOOL DlgStats::_OnScrollBy(CSize sizeScroll, BOOL bDoScroll) { int xOrig, x; int yOrig, y; // don't scroll if there is no valid scroll range (ie. no scroll bar) CScrollBar* pBar; DWORD dwStyle = GetStyle(); pBar = &m_scrollerV; if ((pBar != NULL && !pBar->IsWindowEnabled()) || (pBar == NULL && !(dwStyle & WS_VSCROLL))) { // vertical scroll bar not enabled sizeScroll.cy = 0; } pBar = &m_scroller; if ((pBar != NULL && !pBar->IsWindowEnabled()) || (pBar == NULL && !(dwStyle & WS_HSCROLL))) { // horizontal scroll bar not enabled sizeScroll.cx = 0; } // adjust current x position xOrig = x = m_scroller.GetScrollPos(); //int xMax = GetScrollLimit(SB_HORZ); int xMax, xMin ; m_scroller.GetScrollRange(&xMin,&xMax) ; x += sizeScroll.cx; if (x < xMin) x = xMin; else if (x > xMax) x = xMax; // adjust current y position yOrig = y = m_scrollerV.GetScrollPos(); //int yMax = GetScrollLimit(SB_VERT); int yMax, yMin ; m_scrollerV.GetScrollRange(&yMin,&yMax) ; y += sizeScroll.cy; if (y < 0) y = 0; else if (y > yMax) y = yMax; // did anything change? if (x == xOrig && y == yOrig) return FALSE; if (bDoScroll) { // do scroll and update scroll positions if (x != xOrig) { _SetTimeCursor(x*HSCROLL_DIVIDER); } if (y != yOrig) { m_scrollerV.SetScrollPos(y); //??????????? } } return TRUE; } //--------------------------------------------------------------------------------------- void DlgStats::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { _OnScroll(MAKEWORD(nSBCode, -1), nPos, TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnUpdateChart() { BOOL oldUseSeconds = m_useSeconds; UpdateData(TRUE); InvalidateRect(&m_boardRect,FALSE); if(oldUseSeconds != m_useSeconds) m_listEvents.Invalidate(); } //------------------------------------------------------------------------------------- void DlgStats::_UpdateActionFilter(bool refresh) { // compute filter int filter=0; if(m_fltSelect) filter+=Replay::FLT_SELECT; if(m_fltBuild) filter+=Replay::FLT_BUILD; if(m_fltTrain) filter+=Replay::FLT_TRAIN; if(m_fltSuspect) filter+=Replay::FLT_SUSPECT; if(m_fltHack) filter+=Replay::FLT_HACK; if(m_fltOthers) filter+=Replay::FLT_OTHERS; if(m_fltChat) filter+=Replay::FLT_CHAT; m_replay.UpdateFilter(filter); // update list view if(refresh) { m_listEvents.SetItemCountEx(m_replay.GetEnActionCount(), LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL); m_listEvents.Invalidate(); } } //------------------------------------------------------------------------------------- void DlgStats::_ToggleIgnorePlayer() { POSITION pos = m_plStats.GetFirstSelectedItemPosition(); if(pos!=0) { // get selected item int nItem = m_plStats.GetNextSelectedItem(pos); ReplayEvtList *list = (ReplayEvtList *)m_plStats.GetItemData(nItem); if(list!=0) { // enable/disable player m_replay.EnablePlayer(list,list->IsEnabled()?false:true); LVITEM item = {LVIF_IMAGE ,nItem,0,0,0,0,0,list->IsEnabled()?1:0,0,0}; m_plStats.SetItem(&item); // update list view int nItem=-1; m_listEvents.SetItemCountEx(m_replay.GetEnActionCount(), LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL); m_listEvents.Invalidate(); /* POSITION pos = m_listEvents.GetFirstSelectedItemPosition(); if (pos != NULL) nItem = pList->GetNextSelectedItem(pos); //if(nItem>=m_replay.GetEnActionCount()) m_listEvents.SnItem=m_replay.GetEnActionCount()-1; */ //repaint InvalidateRect(m_boardRect,TRUE); // update map m_dlgmap->UpdateReplay(&m_replay); } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnEnableDisable() { _ToggleIgnorePlayer(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnDblclkPlstats(NMHDR* pNMHDR, LRESULT* pResult) { _ToggleIgnorePlayer(); *pResult = 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnDestroy() { // if we are on pause, unpause if(m_prevAnimationSpeed!=0) OnPause(); // save parameters _Parameters(false); DlgBrowser::SaveColumns(&m_plStats,"plstats"); CDialog::OnDestroy(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeCharttype() { static bool gbTimeWndHasChanged = false; OnUpdateChart(); // update shared "single chart" checkbox CButton *btn = (CButton *)GetDlgItem(IDC_SINGLECHART); btn->SetCheck(m_singleChart[m_chartType]); btn->EnableWindow((m_chartType==RESOURCES || m_chartType==APM || m_chartType==MAPCOVERAGE)?TRUE:FALSE); // update shared "see units" checkbox btn = (CButton *)GetDlgItem(IDC_UNITS); btn->SetCheck(m_seeUnits[m_chartType]); btn->EnableWindow((m_chartType==RESOURCES || m_chartType==MAPCOVERAGE)?TRUE:FALSE); // update shared "apm style" combo box CComboBox *cbx = (CComboBox *)GetDlgItem(IDC_APMSTYLE); cbx->SetCurSel(m_apmStyle[m_chartType]); cbx->EnableWindow((m_chartType==APM || m_chartType==MAPCOVERAGE)?TRUE:FALSE); m_dataAreaX = 0; m_mixedCount=0; m_MixedPlayerIdx=0; // shall we restore the full timeline? if(gbTimeWndHasChanged) { m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); gbTimeWndHasChanged = false; m_zoom=0; UpdateData(FALSE); } switch(m_chartType) { case MAPCOVERAGE: { // disable useless options UINT disable[]={IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_HKSELECT}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_UNITS,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case MIX_APMHOTKEYS: { m_dataAreaX = 0; // disable useless options UINT disable[]={IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST,IDC_UNITS, IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_HKSELECT,IDC_ANIMATE,IDC_SPEED,IDC_BPM,IDC_UPM,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case HOTKEYS: { m_dataAreaX = 32; // disable useless options UINT disable[]={IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_HKSELECT}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case BUILDORDER: { // build order m_timeBegin = 0; m_timeEnd = m_replay.GetLastBuildOrderTime(); gbTimeWndHasChanged = true; // enable useful options GetDlgItem(IDC_UNITSONBO)->EnableWindow(TRUE); GetDlgItem(IDC_USESECONDS)->EnableWindow(TRUE); // disable useless options UINT disable[]={IDC_ZOOM,IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_HKSELECT,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); } break; case RESOURCES: { // disable useless options UINT disable[]={IDC_SPEED,IDC_BPM,IDC_UPM, IDC_HKSELECT,IDC_APMSTYLE,IDC_SORTDIST,IDC_PERCENTAGE,IDC_UNITSONBO}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_ZOOM,IDC_ANIMATE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_UNITS,IDC_USESECONDS,IDC_ACTIONS,IDC_HOTPOINTS}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case APM: { // disable useless options UINT disable[]={IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITS,IDC_ACTIONS, IDC_HKSELECT,IDC_SORTDIST,IDC_PERCENTAGE,IDC_UNITSONBO}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_ZOOM,IDC_ANIMATE,IDC_SPEED,IDC_BPM,IDC_UPM,IDC_USESECONDS,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; default: { // any distribution GetDlgItem(IDC_PERCENTAGE)->EnableWindow(TRUE); GetDlgItem(IDC_SORTDIST)->EnableWindow(TRUE); // disable useless options UINT disable[]={IDC_ZOOM,IDC_ANIMATE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITSONBO, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_HKSELECT,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); } break; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnHelp() { DlgHelp dlg; dlg.DoModal(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_BrowseReplays(const char *dir, int& count, int &idx, bool bCount) { CFileFind finder; char mask[255]; strcpy(mask,dir); if(mask[strlen(mask)-1]!='\\') strcat(mask,"\\"); strcat(mask,"*.*"); // load all replays BOOL bWorking = finder.FindFile(mask); while (bWorking) { // find next package bWorking = finder.FindNextFile(); //dir? if(finder.IsDirectory()) { // . & .. if(finder.IsDots()) continue; // recurse char subdir[255]; strcpy(subdir,dir); if(subdir[strlen(subdir)-1]!='\\') strcat(subdir,"\\"); strcat(subdir,finder.GetFileName()); _BrowseReplays(subdir, count, idx, bCount); continue; } // rep file? CString ext; ext=finder.GetFileName().Right(4); if(ext.CompareNoCase(".rep")!=0) continue; if(bCount) { count++; } else { // load it if(m_replay.Load(finder.GetFilePath(),false,0,true)!=0) { CString msg; msg.Format(IDS_CANTLOAD,(const char*)finder.GetFilePath()); MessageBox(msg); } idx++; // update progress bar m_progress.SetPos((100*idx)/count); } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnTestreplays() { m_progress.ShowWindow(SW_SHOW); // count available replays int count=0; int idx=0; _BrowseReplays("e:\\program files\\starcraft\\maps\\", count, idx, true); // laod them _BrowseReplays("e:\\program files\\starcraft\\maps\\", count, idx, false); m_replay.Clear(); m_progress.ShowWindow(SW_HIDE); } //----------------------------------------------------------------------------------------------------------------- static bool gbAscendingAction=true; int CALLBACK CompareAction(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { int diff=0; const ReplayEvt *evt1 = (const ReplayEvt *)lParam1; const ReplayEvt *evt2 = (const ReplayEvt *)lParam2; unsigned long rep1 = evt1->Time(); unsigned long rep2 = evt2->Time(); switch(lParamSort) { case 0: diff = rep1 - rep2; break; default: assert(0); break; } return gbAscendingAction ? diff : -diff; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnAddevent() { // get path CString path; if(!_GetReplayFileName(path)) return; // add events from that replay LoadReplay(path,false); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRclickPlstats(NMHDR* pNMHDR, LRESULT* pResult) { CPoint pt; GetCursorPos(&pt); // select only one player for(int i=0;i<m_plStats.GetItemCount();i++) m_plStats.SetItemState(i,0, LVIS_SELECTED+LVIS_FOCUSED); // find corresponding item m_plStats.ScreenToClient(&pt); UINT uFlags; int nItem = m_plStats.HitTest(pt,&uFlags); if(nItem!=-1 && (uFlags & LVHT_ONITEMLABEL)!=0) { // select item m_selectedPlayerList = (ReplayEvtList *)m_plStats.GetItemData(nItem); m_plStats.SetItemState(nItem,LVIS_SELECTED+LVIS_FOCUSED, LVIS_SELECTED+LVIS_FOCUSED); // load menu CMenu menu; menu.LoadMenu(IDR_POPUPPLAYER); CMenu *pSub = menu.GetSubMenu(0); // display popup menu m_plStats.ClientToScreen(&pt); pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; } //---------------------------------------------------------------------------------------- void DlgStats::OnRemovePlayer() { if(m_selectedPlayerList!=0) { // remove player events m_replay.RemovePlayer(m_selectedPlayerList,&m_listEvents); m_selectedPlayer=0; // update player stats list _DisplayPlayerStats(); //repaint Invalidate(TRUE); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSeemap() { m_dlgmap->ShowWindow(SW_SHOW); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::StopAnimation() { if(m_bIsAnimating) OnAnimate(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_UpdateAnimSpeed() { CString str; if(m_bIsAnimating) str.Format("(x%d)",m_animationSpeed); SetDlgItemText(IDC_ANIMSPEED,str); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_ToggleAnimateButtons(bool enable) { CString str; str.LoadString(enable ? IDS_ANIMATE:IDS_STOP); SetDlgItemText(IDC_ANIMATE,str); GetDlgItem(IDC_SPEEDPLUS)->EnableWindow(enable ? FALSE : TRUE); GetDlgItem(IDC_SPEEDMINUS)->EnableWindow(enable ? FALSE : TRUE); GetDlgItem(IDC_PAUSE)->EnableWindow(enable ? FALSE : TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnAnimate() { if(m_bIsAnimating) { // if we are on pause, unpause if(m_prevAnimationSpeed!=0) OnPause(); //stopping KillTimer(m_timer); m_bIsAnimating=false; _ToggleAnimateButtons(true); GetDlgItem(IDC_ZOOM)->EnableWindow(TRUE); GetDlgItem(IDC_CHARTTYPE)->EnableWindow(TRUE); // tell map m_dlgmap->Animate(false); // repaint Invalidate(); } else if(m_replay.IsDone()) { // starting m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); //m_timeCursor = 0; m_zoom=0; UpdateData(FALSE); _ToggleAnimateButtons(false); GetDlgItem(IDC_ZOOM)->EnableWindow(FALSE); GetDlgItem(IDC_CHARTTYPE)->EnableWindow(FALSE); m_bIsAnimating=true; _UpdateAnimSpeed(); InvalidateRect(m_boardRect,TRUE); UpdateWindow(); // show animated map m_dlgmap->Animate(true); m_dlgmap->ShowWindow(SW_SHOW); // start timer m_timer = SetTimer(1,1000/TIMERSPEED,0); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnTimer(UINT nIDEvent) { // compute next position unsigned long newpos = m_timeCursor+m_replay.QueryFile()->QueryHeader()->Sec2Tick(m_animationSpeed)/TIMERSPEED; // if we reach the end, stop animation if(newpos>m_timeEnd) OnAnimate(); // udpate cursor if(m_animationSpeed>0) _SetTimeCursor(newpos, true,false); // update map if(m_dlgmap->IsWindowVisible()) m_dlgmap->UpdateTime(newpos); CDialog::OnTimer(nIDEvent); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnPause() { if(m_prevAnimationSpeed==0) { m_prevAnimationSpeed = m_animationSpeed; m_animationSpeed = 0; } else { m_animationSpeed = m_prevAnimationSpeed; m_prevAnimationSpeed = 0; } } void DlgStats::OnSpeedminus() { if(m_animationSpeed>1) m_animationSpeed/=2; _UpdateAnimSpeed(); } void DlgStats::OnSpeedplus() { if(m_animationSpeed<32) m_animationSpeed*=2; _UpdateAnimSpeed(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnGetdispinfoListevents(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; LV_ITEM* pItem= &(pDispInfo)->item; int iItemIndx= pItem->iItem; if (pItem->mask & LVIF_TEXT) //valid text buffer? { // get action const IStarcraftAction *action = m_replay.GetEnAction(iItemIndx);//m_replay.QueryFile()->QueryActions()->GetAction(iItemIndx); assert(action!=0); // get corresponding actionlist ReplayEvtList *list = (ReplayEvtList *)action->GetUserData(0); assert(list!=0); // get event description ReplayEvt *evt = list->GetEvent(action->GetUserData(1)); assert(evt!=0); // display value switch(pItem->iSubItem) { case 0: //time strcpy(pItem->pszText,_MkTime(m_replay.QueryFile()->QueryHeader(),evt->Time(),m_useSeconds?true:false)); break; case 1: //player if(evt->IsSuspect() || evt->IsHack()) sprintf(pItem->pszText,"#FF0000%s",list->PlayerName()); else strcpy(pItem->pszText,list->PlayerName()); break; case 2: //action //assert(evt->Time()!=37925); if(OPTIONSCHART->m_coloredevents) sprintf(pItem->pszText,"%s%s",evt->strTypeColor(),evt->strType()); else sprintf(pItem->pszText,"%s",evt->strType()); break; case 3: //parameters strcpy(pItem->pszText,action->GetParameters(list->GetElemList())); break; case 4: //discard & suspect flag strcpy(pItem->pszText,evt->IsDiscarded()?"*":evt->IsSuspect()?"#FF0000?":evt->IsHack()?"#FF0000!":""); break; case 5: // units ID strcpy(pItem->pszText,action->GetUnitsID(list->GetElemList())); break; default: assert(0); break; } assert(pItem->cchTextMax>(int)strlen(pItem->pszText)); } if(pItem->mask & LVIF_IMAGE) //valid image? pItem->iImage=0; *pResult = 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetResizeRect(CRect& resizeRect) { GetClientRect(&resizeRect); resizeRect.top = resizeRect.bottom - m_hlist - 8 - 6; resizeRect.bottom =resizeRect.top+6; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetHorizResizeRect(CRect& resizeRect) { GetClientRect(&resizeRect); resizeRect.top = resizeRect.bottom - m_hlist - 8 - 6; resizeRect.left = m_boardRect.left+ m_wlist; resizeRect.right = m_boardRect.left+m_wlist+8; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnLButtonDown(UINT nFlags, CPoint point) { // get tracking rect for resizing CRect resizeRect; _GetResizeRect(resizeRect); CRect horizResizeRect; _GetHorizResizeRect(horizResizeRect); // clicking on the resize part? if(resizeRect.PtInRect(point)) { m_resizing=VERTICAL_RESIZE; SetCapture(); m_ystart = point.y; } // clicking on the horizontal resize part? else if(horizResizeRect.PtInRect(point)) { m_resizing=HORIZONTAL_RESIZE; SetCapture(); m_xstart = point.x; } // clicking on map name? else if(m_rectMapName.PtInRect(point)) { OnSeemap(); } else { CRect rect = m_boardRect; rect.left+=hleft+m_dataAreaX; rect.right-=hright; // clicking on the graphics? if(rect.PtInRect(point) && m_maxPlayerOnBoard>0 && (m_chartType==APM || m_chartType==RESOURCES || m_chartType==BUILDORDER || m_chartType==MAPCOVERAGE || m_chartType==HOTKEYS || m_chartType>=MIX_APMHOTKEYS)) { // what player? if(!m_singleChart[m_chartType]) m_selectedPlayer = (point.y-m_boardRect.top) / (m_boardRect.Height() / m_maxPlayerOnBoard); // change time cursor float fx = (float)(point.x-rect.left); float finc = (float)(rect.Width())/(float)(m_timeEnd - m_timeBegin); _SetTimeCursor(m_timeBegin + (unsigned long)(fx/finc)); } } CDialog::OnLButtonDown(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnLButtonUp(UINT nFlags, CPoint point) { if(m_resizing!=NONE) { // release capture ReleaseCapture(); // compute new layout if(m_resizing==VERTICAL_RESIZE) { int newhlist = m_hlist + (m_ystart-point.y); m_hlist = newhlist; } else { int newwlist = m_wlist + (point.x-m_xstart); m_wlist = newwlist; } // resize CRect rect; GetClientRect(&rect); _Resize(rect.Width(),rect.Height()); // end resizing m_resizing=NONE; } CDialog::OnLButtonUp(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetHotKeyDesc(ReplayEvtList *list, int slot, CString& info) { info=""; // browse hotkey events for(int i=0;i<(int)list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = list->GetHKEvent(i); // skip events for other slots if(hkevt->m_slot!=slot) continue; // skip hotkey selection if(hkevt->m_type==HotKeyEvent::SELECT) continue; // new line if(!info.IsEmpty()) info+="\r\n"; // build unit list as string char buffer[64]; strcpy(buffer,_MkTime(m_replay.QueryFile()->QueryHeader(),hkevt->m_time,m_useSeconds?true:false)); info+=buffer+CString(" => "); const HotKey * hk = hkevt->GetHotKey(); for(int uidx=0;uidx<hk->m_unitcount;uidx++) { if(uidx>0) info+=", "; m_replay.QueryFile()->QueryHeader()->MkUnitID2String(buffer, hk->m_hotkeyUnits[uidx], list->GetElemList(), hkevt->m_time); info += buffer; } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_CheckForHotKey(ReplayEvtList *list, CPoint& point, CRect& datarect, int delta) { CRect symRect; // check hotkey numbers if(point.x < datarect.left+m_dataAreaX+delta) { // height of a key strip int levelhk = (datarect.Height()-8-vplayer)/10; // check all keys for(int i=0;i<10;i++) { // compute symbol position int y = datarect.top+vplayer + i*levelhk; CRect rectkey(datarect.left+6,y,datarect.left+6+m_dataAreaX+delta,y+levelhk); if(rectkey.PtInRect(point)) { // build description CString info; _GetHotKeyDesc(list, i, info); // update overlay window m_over->SetText(info,this,point); return; } } } // check hotkey events datarect.left+=m_dataAreaX; for(int i=0;i<(int)list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = list->GetHKEvent(i); if(hkevt->m_time < m_timeBegin || hkevt->m_time > m_timeEnd) continue; // view hotkey selection? if(!m_viewHKselect && hkevt->m_type==HotKeyEvent::SELECT) continue; // compute symbol position _ComputeHotkeySymbolRect(list, hkevt, datarect, symRect); // is mouse over this event? const HotKey * hk = hkevt->GetHotKey(); if(symRect.PtInRect(point) && hk!=0) { // build unit list as string CString info; char buffer[64]; for(int uidx=0;uidx<hk->m_unitcount;uidx++) { if(!info.IsEmpty()) info+="\r\n"; m_replay.QueryFile()->QueryHeader()->MkUnitID2String(buffer, hk->m_hotkeyUnits[uidx], list->GetElemList(), hkevt->m_time); info += buffer; } // update overlay window m_over->SetText(info,this,point); return; } } m_over->Show(false); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnMouseMove(UINT nFlags, CPoint point) { if(m_resizing!=NONE) { m_over->Show(false); //int newhlist = m_hlist + (m_ystart-point.y); //CRect resizeRect = m_boardRect; //resizeRect.top =newhlist; //resizeRect.bottom =newhlist+2; //DrawTrackRect( } else if(m_chartType==HOTKEYS) { // for each player on board CRect rect; for(int i=0,j=0; i<m_replay.GetPlayerCount() && j<m_maxPlayerOnBoard; i++) { // get event list for that player ReplayEvtList *list = m_replay.GetEvtList(i); if(!list->IsEnabled()) continue; // get rect for the player's charts _GetDataRectForPlayer(j++, rect, m_maxPlayerOnBoard); // is mouse in that rect? if(rect.PtInRect(point)) { // check if mouse is over a hotkey symbol _CheckForHotKey(list,point, rect); return; } } m_over->Show(false); } else if(m_chartType==MIX_APMHOTKEYS) { if(m_MixedPlayerIdx<m_replay.GetPlayerCount() && m_mixedCount>0) { // get event list for current player ReplayEvtList *list = m_replay.GetEvtList(m_MixedPlayerIdx); // get rect for the player's charts CRect rect; _GetDataRectForPlayer(1, rect, m_mixedCount); // is mouse in that rect? if(rect.PtInRect(point)) { // check if mouse is over a hotkey symbol _CheckForHotKey(list,point, rect, 32); return; } } m_over->Show(false); } CDialog::OnMouseMove(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- BOOL DlgStats::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // get tracking rect for vertical resizing CRect resizeRect; _GetResizeRect(resizeRect); // get tracking rect for horizontal resizing CRect horizResizeRect; _GetHorizResizeRect(horizResizeRect); // mouse over the resize part? CPoint point; GetCursorPos(&point); ScreenToClient(&point); if(resizeRect.PtInRect(point)) { // top/bottom resize ::SetCursor(::LoadCursor(0,IDC_SIZENS)); return TRUE; } else if(horizResizeRect.PtInRect(point)) { // left/right resize ::SetCursor(::LoadCursor(0,IDC_SIZEWE)); return TRUE; } else if(m_rectMapName.PtInRect(point)) { // map name ::SetCursor(AfxGetApp()->LoadStandardCursor(MAKEINTRESOURCE(32649))); return TRUE; } return CDialog::OnSetCursor(pWnd, nHitTest, message); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRButtonDown(UINT nFlags, CPoint point) { if(!m_replay.IsDone()) return; CPoint pt; GetCursorPos(&pt); // load menu CMenu menu; menu.LoadMenu(IDR_WATCHREP); CMenu *pSub = menu.GetSubMenu(0); // display popup menu pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); CDialog::OnRButtonDown(nFlags, point); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::_StartCurrentReplay(int mode) { CFileFind finder; BOOL bWorking = finder.FindFile(m_replay.GetFileName()); if(bWorking) { // get replay file info finder.FindNextFile(); // get replay info object from replay ReplayInfo *rep = MAINWND->pGetBrowser()->_ProcessReplay(finder.GetRoot(),finder); if(rep) MAINWND->pGetBrowser()->StartReplay(rep, mode); } } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay111() { _StartCurrentReplay(BW_111); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay112() { _StartCurrentReplay(BW_112); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay114() { _StartCurrentReplay(BW_114); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay115() { _StartCurrentReplay(BW_115); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay116() { _StartCurrentReplay(BW_116); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay113() { _StartCurrentReplay(BW_113); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay110() { _StartCurrentReplay(BW_110); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay109() { _StartCurrentReplay(BW_109); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplaySC() { _StartCurrentReplay(BW_SC); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay() { _StartCurrentReplay(BW_AUTO); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRclickListevents(NMHDR* pNMHDR, LRESULT* pResult) { if(m_replay.IsDone()) { // load menu CMenu menu; menu.LoadMenu(IDR_MENU_EVENTS); CMenu *pSub = menu.GetSubMenu(0); // display popup menu CPoint pt; GetCursorPos(&pt); pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; } //------------------------------------------------------------------------------------- static char szFilterTxt[] = "Text File (*.txt)|*.txt|All Files (*.*)|*.*||"; static char szFilterHtml[] = "HTML File (*.html)|*.html|All Files (*.*)|*.*||"; bool DlgStats::_GetFileName(const char *filter, const char *ext, const char *def, CString& file) { CFileDialog dlg(FALSE,ext,def,0,filter,this); CString str = AfxGetApp()->GetProfileString("BWCHART_MAIN","EXPDIR",""); if(!str.IsEmpty()) dlg.m_ofn.lpstrInitialDir = str; if(dlg.DoModal()==IDOK) { file = dlg.GetPathName(); AfxGetApp()->WriteProfileString("BWCHART_MAIN","EXPDIR",file); return true; } return false; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToText() { assert(m_replay.IsDone()); // get export file CString file; if(!_GetFileName(szFilterTxt, "txt", "bwchart.txt", file)) return; // create file CWaitCursor wait; int err = m_replay.ExportToText(file,m_useSeconds?true:false,'\t'); if(err==-1) {AfxMessageBox(IDS_CANTCREATFILE); return;} } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToBWCoach() { assert(m_replay.IsDone()); ExportCoachDlg dlg(this,&m_replay); dlg.DoModal(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToHtml() { assert(m_replay.IsDone()); // get export file CString file; if(!_GetFileName(szFilterHtml, "html", "bwchart.html", file)) return; // create file FILE *fp=fopen(file,"wb"); if(fp==0) {AfxMessageBox(IDS_CANTCREATFILE); return;} // list events in list view CWaitCursor wait; for(unsigned long i=0;i<m_replay.GetEnActionCount(); i++) { // get action const IStarcraftAction *action = m_replay.GetEnAction((int)i); } //close file fclose(fp); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnFilterChange() { UpdateData(TRUE); _UpdateActionFilter(true); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnNextSuspect() { if(!m_replay.IsDone()) return; // find next suspect event int newidx = m_replay.GetNextSuspectEvent(m_selectedAction); if(newidx!=-1) { // select corresponding line in list view m_lockListView=true; m_listEvents.SetItemState(newidx,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED); m_listEvents.EnsureVisible(newidx,FALSE); m_lockListView=false; // update selected player & cursor pos _SelectAction(newidx); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeApmstyle() { UpdateData(TRUE); if(m_replay.IsDone()) { // if apm style was changed if(m_replay.UpdateAPM(m_apmStyle[APM],m_apmStyle[MAPCOVERAGE])) { // repaint chart InvalidateRect(m_boardRect,FALSE); // update player stats _DisplayPlayerStats(); } } } //-----------------------------------------------------------------------------------------------------------------
29.947953
165
0.609408
1c209867ff2b92d973c8bb6b15a5196ba9203476
29,311
cpp
C++
OpenGLEngine/OpenGLEngine/Main.cpp
BEEMO197/Reality-Game-Engine
08ff9d9b02790e31bef5ec1c3a50f1b36d43a572
[ "MIT" ]
1
2021-04-02T17:21:38.000Z
2021-04-02T17:21:38.000Z
OpenGLEngine/OpenGLEngine/Main.cpp
BEEMO197/Reality-Game-Engine
08ff9d9b02790e31bef5ec1c3a50f1b36d43a572
[ "MIT" ]
null
null
null
OpenGLEngine/OpenGLEngine/Main.cpp
BEEMO197/Reality-Game-Engine
08ff9d9b02790e31bef5ec1c3a50f1b36d43a572
[ "MIT" ]
null
null
null
//#define STB_IMAGE_IMPLEMENTATION #include "RenderingSystem.h" #include "RenderingSystemV2.h" #include "InputEventSystem.h" #include "FPSControlSystem.h" #include "RotateSystem.h" #include "RotateSystemV2.h" #include "FireworksSystem.h" #include "GravityForceSystem.h" #include "DragForceSystem.h" #include "FixedSpringSystem.h" #include "PairedSpringSystem.h" #include "ParticleSphereSystem.h" #include "CableSystem.h" #include "RodSystem.h" #include "PlaneSystem.h" #include "ParticleContactResolutionSystem.h" #include "ResetPenetrationDeltaMoveSystem.h" #include "ForceAccumulatorSystem.h" #include "ParticleSystem.h" #include "DynamicDirectionalLightSystem.h" #include "DynamicPointLightSystem.h" #include "DynamicSpotLightSystem.h" #include <string> #include <stdlib.h> #include <time.h> using namespace Reality; void LoadShaders(ECSWorld& world); void LoadModels(ECSWorld& world); void SetupLights(ECSWorld& world); void MakeABunchaObjects(ECSWorld& world); void MakeFireworks(ECSWorld& world); void Make3Particles(ECSWorld& world); void MakeABunchaSprings(ECSWorld& world); void MakeABunchaSpheres(ECSWorld& world); void MakeABunchaCablesAndRods(ECSWorld& world); void MakeARopeBridge(ECSWorld& world); void MakeABunchaObjectsV2(ECSWorld& world); int main() { ECSWorld world; // Init and Load world.data.InitRendering(); //LoadAssets(world); world.data.renderUtil->camera.Position = Vector3(0, 0.0f, 50.0f); world.data.renderUtil->SetFOV(60); // Create entities // Make a player controller auto e = world.createEntity(); e.addComponent<FPSControlComponent>(); SetupLights(world); //MakeABunchaObjects(world); //MakeFireworks(world); //Make3Particles(world); //MakeABunchaSprings(world); //MakeABunchaSpheres(world); //MakeABunchaCablesAndRods(world); MakeARopeBridge(world); //MakeABunchaObjectsV2(world); // Create Systems world.getSystemManager().addSystem<RenderingSystem>(); world.getSystemManager().addSystem<RenderingSystemV2>(); world.getSystemManager().addSystem<InputEventSystem>(); world.getSystemManager().addSystem<FPSControlSystem>(); world.getSystemManager().addSystem<RotateSystem>(); world.getSystemManager().addSystem<RotateSystemV2>(); world.getSystemManager().addSystem<FireworksSystem>(); world.getSystemManager().addSystem<GravityForceSystem>(); world.getSystemManager().addSystem<DragForceSystem>(); world.getSystemManager().addSystem<FixedSpringSystem>(); world.getSystemManager().addSystem<PairedSpringSystem>(); world.getSystemManager().addSystem<ParticleSphereSystem>(); world.getSystemManager().addSystem<CableSystem>(); world.getSystemManager().addSystem<RodSystem>(); world.getSystemManager().addSystem<PlaneSystem>(); world.getSystemManager().addSystem<ParticleContactResolutionSystem>(); world.getSystemManager().addSystem<ResetPenetrationDeltaMoveSystem>(); world.getSystemManager().addSystem<ForceAccumulatorSystem>(); world.getSystemManager().addSystem<ParticleSystem>(); world.getSystemManager().addSystem<DynamicDirectionalLightSystem>(); world.getSystemManager().addSystem<DynamicPointLightSystem>(); world.getSystemManager().addSystem<DynamicSpotLightSystem>(); float time = glfwGetTime(); float stepTime = glfwGetTime(); float deltaTime = 0; float elapsedDeltaTime = 0; float logicDelta = 0; float debugDelta = 0; LoadShaders(world); bool shadersLoaded = false; bool modelsLoadStarted = false; // game loop // ----------- while (!glfwWindowShouldClose(world.data.renderUtil->window->glfwWindow)) { float current = glfwGetTime(); deltaTime = current - time; deltaTime = 1 / 60.0f; time = glfwGetTime(); world.update(); // Poll OpenGl events glfwPollEvents(); world.data.renderUtil->ClearDisplay(world.data.renderUtil->window->glfwWindow); // Load if (!shadersLoaded) { shadersLoaded = world.data.assetLoader->ShadersLoaded(); } if(shadersLoaded && !modelsLoadStarted) { LoadModels(world); modelsLoadStarted = true; } // Update View world.data.renderUtil->UpdateViewMatrix(); // Process Input world.getSystemManager().getSystem<InputEventSystem>().Update(deltaTime); // Game Logic Update world.getSystemManager().getSystem<FPSControlSystem>().Update(deltaTime); world.getSystemManager().getSystem<RotateSystem>().Update(deltaTime); world.getSystemManager().getSystem<RotateSystemV2>().Update(deltaTime); world.getSystemManager().getSystem<FireworksSystem>().Update(deltaTime); world.getSystemManager().getSystem<ParticleSphereSystem>().Update(deltaTime); world.getSystemManager().getSystem<CableSystem>().Update(deltaTime); world.getSystemManager().getSystem<RodSystem>().Update(deltaTime); world.getSystemManager().getSystem<PlaneSystem>().Update(deltaTime); // Update Transform // Physics //float fixedDeltaTime = glfwGetKey(world.data.renderUtil->window->glfwWindow, GLFW_KEY_SPACE) == GLFW_PRESS ? 1 / 60.0f : 0; float fixedDeltaTime = 1 / 60.0f; // Force Generator world.getSystemManager().getSystem<GravityForceSystem>().Update(fixedDeltaTime); world.getSystemManager().getSystem<DragForceSystem>().Update(fixedDeltaTime); world.getSystemManager().getSystem<FixedSpringSystem>().Update(fixedDeltaTime); world.getSystemManager().getSystem<PairedSpringSystem>().Update(fixedDeltaTime); // Force Accumulator world.getSystemManager().getSystem<ForceAccumulatorSystem>().Update(fixedDeltaTime); // Contact Resolution world.getSystemManager().getSystem<ParticleContactResolutionSystem>().Update(fixedDeltaTime); world.getSystemManager().getSystem<ResetPenetrationDeltaMoveSystem>().Update(fixedDeltaTime); // Integrator world.getSystemManager().getSystem<ParticleSystem>().Update(fixedDeltaTime); // Rendering Update ///*** HACK: For the last DrawCall not working on some systems world.data.renderUtil->DrawCube(Vector3(0, 0, 0), Vector3(0, 0, 0)); ///*** HACK: For the last DrawCall not working on some systems world.getSystemManager().getSystem<DynamicDirectionalLightSystem>().Update(deltaTime); world.getSystemManager().getSystem<DynamicPointLightSystem>().Update(deltaTime); world.getSystemManager().getSystem<DynamicSpotLightSystem>().Update(deltaTime); world.getSystemManager().getSystem<RenderingSystem>().Update(deltaTime); world.getSystemManager().getSystem<RenderingSystemV2>().Update(deltaTime); elapsedDeltaTime = glfwGetTime() - time; logicDelta = elapsedDeltaTime - world.data.renderUtil->GetRenderDelta(); stepTime = glfwGetTime(); // Debug if (DEBUG_LOG_LEVEL > 0) { world.data.renderUtil->RenderText("FPS : " + std::to_string((int)round(1.0f / deltaTime)), 1810.0f, 1060.0f, 0.5f, Color(0, 1, 1, 1)); } if (DEBUG_LOG_LEVEL > 1) { int logic = (int)round(logicDelta * 100.0f / deltaTime); std::string logicString = logic < 10 ? " " + std::to_string(logic) : std::to_string(logic); int render = (int)round(world.data.renderUtil->GetRenderDelta() * 100.0f / deltaTime); std::string renderString = logic < 10 ? " " + std::to_string(render) : std::to_string(render); int debug = (int)round(debugDelta * 100.0f / deltaTime); std::string debugString = logic < 10 ? " " + std::to_string(debug) : std::to_string(debug); world.data.renderUtil->RenderText("Logic : " + logicString + "%" + //+ " | Physics : " + std::to_string((int)round(physicsDelta * 100.0f / deltaTime)) + "%" + + " | Rendering : " + renderString + "%" + + " | Debug : " + debugString + "%" , 1680.0f, 1040.0f, 0.25f, Color(0, 1, 1, 1)); } if (DEBUG_LOG_LEVEL > 2) { world.data.renderUtil->RenderText("Draw Calls : " + std::to_string(world.data.renderUtil->GetDrawCalls()) + " | Verts : " + std::to_string(world.data.renderUtil->GetVerts()) + " | Tris : " + std::to_string(world.data.renderUtil->GetTris()) + " | Lines : " + std::to_string(world.data.renderUtil->GetLines()) , 1610.0f, 1020.0f, 0.25f, Color(0, 1, 1, 1)); } // Update debug delta debugDelta = glfwGetTime() - stepTime; stepTime = glfwGetTime(); world.data.renderUtil->SwapBuffers(world.data.renderUtil->window->glfwWindow); // Show FPS in console //std::cout << "FPS : " << 1.0f / deltaTime << std::endl; } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } void LoadShaders(ECSWorld& world) { world.data.assetLoader->StartShaderLoading({ {"Shaders/Lighting_Maps.vs", "Shaders/Lighting_Maps.fs"} }); } void LoadModels(ECSWorld& world) { world.data.assetLoader->StartModelLoading({ //ModelData("Resources/Models/snowy-mountain-terrain/SnowyMountainMesh.obj"), ModelData("Resources/Models/Sponza-master/sponza.obj"), ModelData("Resources/Models/nanosuit/nanosuit.obj"), ModelData("Resources/Models/supermarine-spitfire/spitfire.fbx", {{"spitfire_d.png"}}) }); } void MakeABunchaObjects(ECSWorld& world) { auto castle = world.createEntity(); castle.addComponent<TransformComponent>(Vector3(0, -3.0f, 0.0f), Vector3(0.1f, 0.1f, 0.1f), Vector3(0, 270, 0)); // Add mesh castle.addComponent<ModelComponent>("Resources/Models/Sponza-master/sponza.obj"); //auto flight = world.createEntity(); //flight.addComponent<TransformComponent>(Vector3(0, 30, -50), Vector3(0.1f, 0.1f, 0.1f), Vector3(270, 0, 0)); //// Add mesh //flight.addComponent<ModelComponent>("Resources/Models/supermarine-spitfire/spitfire.fbx"); //flight.addComponent<RotateComponent>(Vector3(0, 90, 0)); //flight.addComponent<ParticleComponent>(Vector3(0, 30, 0)); //flight.addComponent<ForceAccumulatorComponent>(); //flight.addComponent<GravityForceComponent>(); } void MakeFireworks(ECSWorld & world) { for (int i = 0; i < 3; i++) { auto fireworks = world.createEntity(); fireworks.addComponent<TransformComponent>(Vector3(-100 + 100 * i, 30 + RANDOM_FLOAT(-10, 10), -50)); fireworks.addComponent<ParticleComponent>(Vector3(0, 100, 0)); fireworks.addComponent<ForceAccumulatorComponent>(); fireworks.addComponent<GravityForceComponent>(); fireworks.addComponent<FireworksComponent>(6, 3, 3 + RANDOM_FLOAT(-1, 1)); } } void Make3Particles(ECSWorld & world) { auto particle1 = world.createEntity(); particle1.addComponent<TransformComponent>(Vector3(-10, 60, -50)); particle1.addComponent<ParticleComponent>(Vector3(0, 0, 0)); particle1.addComponent<ForceAccumulatorComponent>(); particle1.addComponent<GravityForceComponent>(); particle1.addComponent<DragForceComponent>(0, 0); auto particle2 = world.createEntity(); particle2.addComponent<TransformComponent>(Vector3(0, 60, -50)); particle2.addComponent<ParticleComponent>(Vector3(0, 0, 0)); particle2.addComponent<ForceAccumulatorComponent>(); particle2.addComponent<GravityForceComponent>(); particle2.addComponent<DragForceComponent>(1, 0); auto particle3 = world.createEntity(); particle3.addComponent<TransformComponent>(Vector3(10, 60, -50)); particle3.addComponent<ParticleComponent>(Vector3(0, 0, 0)); particle3.addComponent<ForceAccumulatorComponent>(); particle3.addComponent<GravityForceComponent>(); particle3.addComponent<DragForceComponent>(1, 1); } void MakeABunchaSprings(ECSWorld & world) { auto particle1 = world.createEntity(); particle1.addComponent<TransformComponent>(Vector3(0, 20, -50)); particle1.addComponent<ParticleComponent>(Vector3(0, 0, 0)); particle1.addComponent<ForceAccumulatorComponent>(); particle1.addComponent<GravityForceComponent>(); auto particle2= world.createEntity(); particle2.addComponent<TransformComponent>(Vector3(-10, 0, -50)); particle2.addComponent<ParticleComponent>(Vector3(0, 0, 0)); particle2.addComponent<ForceAccumulatorComponent>(); particle2.addComponent<GravityForceComponent>(); auto spring1 = world.createEntity(); spring1.addComponent<TransformComponent>(Vector3(10, 60, -50)); spring1.addComponent<FixedSpringComponent>(20.0f, 20.0f, particle1); auto spring2 = world.createEntity(); spring2.addComponent<TransformComponent>(Vector3(-10, 60, -50)); spring2.addComponent<FixedSpringComponent>(20.0f, 15.0f, particle1); auto pairedSpring = world.createEntity(); pairedSpring.addComponent<PairedSpringComponent>(20.0f, 20.0f, particle1, particle2); } void MakeABunchaSpheres(ECSWorld & world) { for (int i = 0; i < 40; i++) { auto sphere = world.createEntity(); sphere.addComponent<TransformComponent>(Vector3(RANDOM_FLOAT(-10, 10), RANDOM_FLOAT(-10, 10), RANDOM_FLOAT(-10, 10))); sphere.addComponent<ParticleComponent>(Vector3(RANDOM_FLOAT(-40, 40), RANDOM_FLOAT(-40, 40), RANDOM_FLOAT(-40, 40))); sphere.addComponent<ForceAccumulatorComponent>(1.0f); sphere.addComponent<GravityForceComponent>(); sphere.addComponent<ParticleSphereComponent>(RANDOM_FLOAT(1, 3)); } } void CreateParticleArchetype(ECSEntity e) { e.addComponent<ParticleComponent>(); e.addComponent<ForceAccumulatorComponent>(); e.addComponent<GravityForceComponent>(); //e.addComponent<ParticleSphereComponent>(); e.addComponent<PenetrationDeltaMoveComponent>(); } void MakeARopeBridge(ECSWorld & world) { auto ePivot1 = world.createEntity(); ePivot1.addComponent<TransformComponent>(Vector3(3, 10, 5)); auto e1 = world.createEntity(); e1.addComponent<TransformComponent>(Vector3(0, 3, 5)); CreateParticleArchetype(e1); auto ePivot2 = world.createEntity(); ePivot2.addComponent<TransformComponent>(Vector3(3, 10, -5)); auto e2 = world.createEntity(); e2.addComponent<TransformComponent>(Vector3(0, 3, -5)); CreateParticleArchetype(e2); auto rod1 = world.createEntity(); rod1.addComponent<RodComponent>(e1, e2, 10); auto cable1 = world.createEntity(); cable1.addComponent<CableComponent>(ePivot1, e1, 18, 0.5); auto cable2 = world.createEntity(); cable2.addComponent<CableComponent>(ePivot2, e2, 18, 0.5); // 2 auto ePivot3 = world.createEntity(); ePivot3.addComponent<TransformComponent>(Vector3(3 + 10, 10, 5)); auto e3 = world.createEntity(); e3.addComponent<TransformComponent>(Vector3(0 + 10, 0, 5)); CreateParticleArchetype(e3); auto ePivot4 = world.createEntity(); ePivot4.addComponent<TransformComponent>(Vector3(3 + 10, 10, -5)); auto e4 = world.createEntity(); e4.addComponent<TransformComponent>(Vector3(0 + 10, 0, -5)); CreateParticleArchetype(e4); auto rod2 = world.createEntity(); rod2.addComponent<RodComponent>(e3, e4, 10); auto cable3 = world.createEntity(); cable3.addComponent<CableComponent>(ePivot3, e3, 15, 0.5); auto cable4 = world.createEntity(); cable4.addComponent<CableComponent>(ePivot4, e4, 15, 0.5); auto sphere1 = world.createEntity(); sphere1.addComponent<TransformComponent>(Vector3(5, 10, -4)); sphere1.addComponent<ParticleComponent>(Vector3(0, 0, 0)); sphere1.addComponent<ForceAccumulatorComponent>(1.0f); sphere1.addComponent<GravityForceComponent>(); sphere1.addComponent<ParticleSphereComponent>(1.0f); auto plane1 = world.createEntity(); plane1.addComponent<PlaneComponent>(e1, e2, e3, e4); // 3 auto ePivot5 = world.createEntity(); ePivot5.addComponent<TransformComponent>(Vector3(3 - 10, 10, 5)); auto e5 = world.createEntity(); e5.addComponent<TransformComponent>(Vector3(0 - 10, -3, 5)); CreateParticleArchetype(e5); auto ePivot6 = world.createEntity(); ePivot6.addComponent<TransformComponent>(Vector3(3 - 10, 10, -5)); auto e6 = world.createEntity(); e6.addComponent<TransformComponent>(Vector3(0 - 10, -3, -5)); CreateParticleArchetype(e6); auto rod3 = world.createEntity(); rod3.addComponent<RodComponent>(e5, e6, 10); auto cable5 = world.createEntity(); cable5.addComponent<CableComponent>(ePivot5, e5, 21, 0.5); auto cable6 = world.createEntity(); cable6.addComponent<CableComponent>(ePivot6, e6, 21, 0.5); auto plane2 = world.createEntity(); plane2.addComponent<PlaneComponent>(e5, e6, e1, e2); // auto ePivot7 = world.createEntity(); ePivot7.addComponent<TransformComponent>(Vector3(3 - 20, 10, 5)); auto e7 = world.createEntity(); e7.addComponent<TransformComponent>(Vector3(0 - 20, -5, 5)); CreateParticleArchetype(e7); auto ePivot8 = world.createEntity(); ePivot8.addComponent<TransformComponent>(Vector3(3 - 20, 10, -5)); auto e8 = world.createEntity(); e8.addComponent<TransformComponent>(Vector3(0 - 20, -5, -5)); CreateParticleArchetype(e8); auto rod4 = world.createEntity(); rod4.addComponent<RodComponent>(e7, e8, 10); auto cable7 = world.createEntity(); cable7.addComponent<CableComponent>(ePivot7, e7, 23, 0.5); auto cable8 = world.createEntity(); cable8.addComponent<CableComponent>(ePivot8, e8, 23, 0.5); auto plane3 = world.createEntity(); plane3.addComponent<PlaneComponent>(e7, e8, e5, e6); // // auto ePivot9 = world.createEntity(); ePivot9.addComponent<TransformComponent>(Vector3(3 - 30, 10, 5)); auto e9 = world.createEntity(); e9.addComponent<TransformComponent>(Vector3(0 - 30, -3, 5)); CreateParticleArchetype(e9); auto ePivot10 = world.createEntity(); ePivot10.addComponent<TransformComponent>(Vector3(3 - 30, 10, -5)); auto e10 = world.createEntity(); e10.addComponent<TransformComponent>(Vector3(0 - 30, -3, -5)); CreateParticleArchetype(e10); auto rod5 = world.createEntity(); rod5.addComponent<RodComponent>(e9, e10, 10); auto cable9 = world.createEntity(); cable9.addComponent<CableComponent>(ePivot9, e9, 21, 0.5); auto cable10 = world.createEntity(); cable10.addComponent<CableComponent>(ePivot10, e10, 21, 0.5); auto plane4 = world.createEntity(); plane4.addComponent<PlaneComponent>(e9, e10, e7, e8); // // auto ePivot11 = world.createEntity(); ePivot11.addComponent<TransformComponent>(Vector3(3 - 40, 10, 5)); auto e11 = world.createEntity(); e11.addComponent<TransformComponent>(Vector3(0 - 40, 0, 5)); CreateParticleArchetype(e11); auto ePivot12 = world.createEntity(); ePivot12.addComponent<TransformComponent>(Vector3(3 - 40, 10, -5)); auto e12 = world.createEntity(); e12.addComponent<TransformComponent>(Vector3(0 - 40, 0, -5)); CreateParticleArchetype(e12); auto rod6 = world.createEntity(); rod5.addComponent<RodComponent>(e11, e12, 10); auto cable11 = world.createEntity(); cable11.addComponent<CableComponent>(ePivot11, e11, 18, 0.5); auto cable12 = world.createEntity(); cable12.addComponent<CableComponent>(ePivot12, e12, 18, 0.5); auto plane5 = world.createEntity(); plane5.addComponent<PlaneComponent>(e11, e12, e9, e10); // // auto ePivot13 = world.createEntity(); ePivot13.addComponent<TransformComponent>(Vector3(3 - 50, 10, 5)); auto e13 = world.createEntity(); e13.addComponent<TransformComponent>(Vector3(0 - 50, 3, 5)); CreateParticleArchetype(e13); auto ePivot14 = world.createEntity(); ePivot14.addComponent<TransformComponent>(Vector3(3 - 50, 10, -5)); auto e14 = world.createEntity(); e14.addComponent<TransformComponent>(Vector3(0 - 50, 3, -5)); CreateParticleArchetype(e14); auto rod7 = world.createEntity(); rod5.addComponent<RodComponent>(e13, e14, 10); auto cable13 = world.createEntity(); cable13.addComponent<CableComponent>(ePivot13, e13, 15, 0.5); auto cable14 = world.createEntity(); cable14.addComponent<CableComponent>(ePivot14, e14, 15, 0.5); auto plane6 = world.createEntity(); plane6.addComponent<PlaneComponent>(e13, e14, e11, e12); // // rods auto rod8 = world.createEntity(); rod8.addComponent<RodComponent>(e1, e3, 10); auto rod9 = world.createEntity(); rod9.addComponent<RodComponent>(e2, e4, 10); auto rod10 = world.createEntity(); rod10.addComponent<RodComponent>(e5, e1, 10); auto rod11 = world.createEntity(); rod11.addComponent<RodComponent>(e6, e2, 10); auto rod12 = world.createEntity(); rod12.addComponent<RodComponent>(e7, e5, 10); auto rod13 = world.createEntity(); rod13.addComponent<RodComponent>(e8, e6, 10); auto rod14 = world.createEntity(); rod14.addComponent<RodComponent>(e9, e7, 10); auto rod15 = world.createEntity(); rod15.addComponent<RodComponent>(e10, e8, 10); auto rod16 = world.createEntity(); rod16.addComponent<RodComponent>(e11, e9, 10); auto rod17 = world.createEntity(); rod17.addComponent<RodComponent>(e12, e10, 10); auto rod18 = world.createEntity(); rod18.addComponent<RodComponent>(e13, e11, 10); auto rod19 = world.createEntity(); rod19.addComponent<RodComponent>(e14, e12, 10); // diagonal rods auto rod20 = world.createEntity(); rod20.addComponent<RodComponent>(e1, e4, 10 * pow(2.0f, 0.5f)); auto rod21 = world.createEntity(); rod21.addComponent<RodComponent>(e2, e3, 10 * pow(2.0f, 0.5f)); auto rod22 = world.createEntity(); rod22.addComponent<RodComponent>(e6, e1, 10 * pow(2.0f, 0.5f)); auto rod23 = world.createEntity(); rod23.addComponent<RodComponent>(e5, e2, 10 * pow(2.0f, 0.5f)); auto rod24 = world.createEntity(); rod24.addComponent<RodComponent>(e5, e8, 10 * pow(2.0f, 0.5f)); auto rod25 = world.createEntity(); rod25.addComponent<RodComponent>(e6, e7, 10 * pow(2.0f, 0.5f)); auto rod26 = world.createEntity(); rod26.addComponent<RodComponent>(e7, e10, 10 * pow(2.0f, 0.5f)); auto rod27 = world.createEntity(); rod27.addComponent<RodComponent>(e8, e9, 10 * pow(2.0f, 0.5f)); auto rod28 = world.createEntity(); rod28.addComponent<RodComponent>(e9, e12, 10 * pow(2.0f, 0.5f)); auto rod29 = world.createEntity(); rod29.addComponent<RodComponent>(e10, e11, 10 * pow(2.0f, 0.5f)); auto rod30 = world.createEntity(); rod30.addComponent<RodComponent>(e11, e14, 10 * pow(2.0f, 0.5f)); auto rod31 = world.createEntity(); rod31.addComponent<RodComponent>(e12, e13, 10 * pow(2.0f, 0.5f)); } void MakeABunchaObjectsV2(ECSWorld & world) { //auto flightV1 = world.createEntity(); //flightV1.addComponent<TransformComponent>(Vector3(0, 30, -50), Vector3(0.1f, 0.1f, 0.1f), Vector3(270, 0, 0)); //// Add mesh //flightV1.addComponent<ModelComponent>("Resources/Models/supermarine-spitfire/spitfire.fbx"); //flightV1.addComponent<RotateComponent>(Vector3(0, 90, 0)); auto flightV2 = world.createEntity(); flightV2.addComponent<TransformComponentV2>(Vector3(0, 30, -50), Vector3(0.1f, 0.1f, 0.1f), Vector3(270, 0, 0)); // Add mesh flightV2.addComponent<ModelComponent>("Resources/Models/supermarine-spitfire/spitfire.fbx"); flightV2.addComponent<RotateComponentV2>(Vector3(0, 45, 0)); } void MakeABunchaCablesAndRods(ECSWorld & world) { auto ePivot = world.createEntity(); ePivot.addComponent<TransformComponent>(Vector3(3, 10, 0)); auto e1 = world.createEntity(); e1.addComponent<TransformComponent>(Vector3(0, 10, 0)); e1.addComponent<ParticleComponent>(); e1.addComponent<ForceAccumulatorComponent>(); e1.addComponent<GravityForceComponent>(); e1.addComponent<ParticleSphereComponent>(); e1.addComponent<PenetrationDeltaMoveComponent>(); auto e2 = world.createEntity(); e2.addComponent<TransformComponent>(Vector3(5, 5, 0)); e2.addComponent<ParticleComponent>(); e2.addComponent<ForceAccumulatorComponent>(); e2.addComponent<GravityForceComponent>(); e2.addComponent<ParticleSphereComponent>(); e2.addComponent<PenetrationDeltaMoveComponent>(); auto e3 = world.createEntity(); e3.addComponent<TransformComponent>(Vector3(0, 0, 0)); e3.addComponent<ParticleComponent>(); e3.addComponent<ForceAccumulatorComponent>(); e3.addComponent<GravityForceComponent>(); e3.addComponent<ParticleSphereComponent>(); e3.addComponent<PenetrationDeltaMoveComponent>(); auto e4 = world.createEntity(); e4.addComponent<TransformComponent>(Vector3(-5, 5, 0)); e4.addComponent<ParticleComponent>(); e4.addComponent<ForceAccumulatorComponent>(); e4.addComponent<GravityForceComponent>(); e4.addComponent<ParticleSphereComponent>(); e4.addComponent<PenetrationDeltaMoveComponent>(); auto cable1 = world.createEntity(); //cable.addComponent<CableComponent>(ePivot, e1, 5, 1); cable1.addComponent<PairedSpringComponent>(50, 2, ePivot, e1); auto cable2 = world.createEntity(); //cable.addComponent<CableComponent>(ePivot, e1, 5, 1); cable2.addComponent<PairedSpringComponent>(50, 25, ePivot, e2); auto cable3 = world.createEntity(); cable3.addComponent<CableComponent>(ePivot, e3, 15, 1); //cable3.addComponent<PairedSpringComponent>(50, 20, ePivot, e3); auto rod1 = world.createEntity(); rod1.addComponent<RodComponent>(e1, e2, 5 * pow(2, 0.5f)); auto rod2 = world.createEntity(); rod2.addComponent<RodComponent>(e2, e3, 5 * pow(2, 0.5f)); auto rod3 = world.createEntity(); rod3.addComponent<RodComponent>(e3, e4, 5 * pow(2, 0.5f)); auto rod4 = world.createEntity(); rod4.addComponent<RodComponent>(e4, e1, 5 * pow(2, 0.5f)); auto rod5 = world.createEntity(); rod5.addComponent<RodComponent>(e1, e3, 10); auto rod6 = world.createEntity(); rod6.addComponent<RodComponent>(e2, e4, 10); //for (int i = 0; i < 20; i++) //{ // auto e1 = world.createEntity(); // e1.addComponent<TransformComponent>(Vector3(RANDOM_FLOAT(-5, 5), RANDOM_FLOAT(-5, 5), RANDOM_FLOAT(-5, 5))); // e1.addComponent<ParticleComponent>(); // e1.addComponent<ForceAccumulatorComponent>(); // e1.addComponent<GravityForceComponent>(); // e1.addComponent<ParticleSphereComponent>(RANDOM_FLOAT(0.5, 1.5)); // e1.addComponent<PenetrationDeltaMoveComponent>(); // auto e2 = world.createEntity(); // e2.addComponent<TransformComponent>(Vector3(RANDOM_FLOAT(-5, 5), RANDOM_FLOAT(-5, 5), RANDOM_FLOAT(-5, 5))); // e2.addComponent<ParticleComponent>(); // e2.addComponent<ForceAccumulatorComponent>(); // e2.addComponent<GravityForceComponent>(); // e2.addComponent<ParticleSphereComponent>(RANDOM_FLOAT(0.5, 1.5)); // e2.addComponent<PenetrationDeltaMoveComponent>(); // auto rod = world.createEntity(); // rod.addComponent<RodComponent>(e1, e2, RANDOM_FLOAT(6, 10)); //} } void SetupLights(ECSWorld& world) { auto l = world.createEntity(); l.addComponent<TransformComponent>(Vector3(0, 0, 0), Vector3(0, 0, 0), Vector3(90, 0, 0)); l.addComponent<DynamicDirectionalLightComponent>(Color(0.0, 0.1, 0.1), Color(0.0, 0.1, 0.1), Color(0.0, 0.1, 0.1)); // Lanterns auto pl1 = world.createEntity(); pl1.addComponent<TransformComponent>(Vector3(22, 14, 48.5f)); pl1.addComponent<DynamicPointLightComponent>(100.0f, Color(0.1, 0, 0), Color(1.0f, 0.0f, 0.0f), Color(1.0f, 0.0f, 0.0f)); auto hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(23, 15, 48.0f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(22, 13.5f, 50.5f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(21, 12.5f, 47.5f)); auto pl2 = world.createEntity(); pl2.addComponent<TransformComponent>(Vector3(-14.5f, 14, 49.0f)); pl2.addComponent<DynamicPointLightComponent>(100.0f, Color(0, 0, 0.1f), Color(0.0f, 0.0f, 1.0f), Color(0.0f, 0.0f, 1.0f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(-14.5f + 1, 14 - 1, 49.0f - 1)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(-14.5f - 0.5f, 14 + 1, 49.0f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(-14.5f, 14 - 1, 49.0f + 1)); auto pl3 = world.createEntity(); pl3.addComponent<TransformComponent>(Vector3(22, 14, -62.0f)); pl3.addComponent<DynamicPointLightComponent>(100.0f, Color(0, 0.1f, 0), Color(0.0f, 1.0f, 0.0f), Color(0.0f, 1.0f, 0.0f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(22 - 1, 14 - 1, -62.0f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(22, 14 + 0.5f, -62.0f - 1)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(22 + 1, 14, -62.0f + 0.5f)); auto pl4 = world.createEntity(); pl4.addComponent<TransformComponent>(Vector3(-14.5f, 14, -61.5f)); pl4.addComponent<DynamicPointLightComponent>(100.0f, Color(0.1, 0.05, 0), Color(1.0f, 0.55f, 0.0f), Color(1.0f, 0.55f, 0.0f)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(-14.5f - 1, 14, -61.5f -1)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(-14.5f - 0.25f, 14 - 0.5f, -61.5f + 1)); hook = world.createEntity(); hook.addComponent<TransformComponent>(Vector3(-14.5f + 0.5f, 14+ 1, -61.5f + 1)); // Spears std::vector<Color> cols = { Color(1,0,0), Color(0,1,0), Color(0,0,1), Color(0.7f,0.55f,0) }; for (int i = 1; i < 3; i++) { for (int j = 0; j < 4; j++) { pl1 = world.createEntity(); pl1.addComponent<TransformComponent>(Vector3((i % 2 == 0 ? 8 : -1), 85, 49.5f - 37 * j), Vector3(1, 1, 1), Vector3(180, 0, 0)); pl1.addComponent<DynamicSpotLightComponent>(10.0f, 100, Color(0, 0, 0), cols[3 - j], cols[3 - j], 5); } } }
38.265013
138
0.712804
1c2682699ff4fe1a11841ac9317106789dfb46ed
369
hpp
C++
phase_1/eval/york/challenge/src/http/request_state.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
phase_1/eval/york/challenge/src/http/request_state.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
phase_1/eval/york/challenge/src/http/request_state.hpp
cromulencellc/chess-aces
7780e29de1991758078816ca501ff79a2586b8c2
[ "MIT" ]
null
null
null
#pragma once #include <optional> #include <vector> namespace http { struct RequestState { public: bool abort = false; bool want_line = false; std::optional<size_t> want_bytes; bool ready_to_respond = false; bool in_valid_state() const; }; } std::ostream& operator<<(std::ostream& o, const http::RequestState& rs);
18.45
55
0.634146
1c27fe1b64d1ff82139e5e8dac02a3cbfa0bd650
872
cpp
C++
engine/visibility/BackSurfaceCull/BackSurfaceCull.cpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
engine/visibility/BackSurfaceCull/BackSurfaceCull.cpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
engine/visibility/BackSurfaceCull/BackSurfaceCull.cpp
PiroDev/graphics-engine
bf1e5f57878c02421e2e8a787d94ce6074637402
[ "Apache-2.0" ]
null
null
null
#include "BackSurfaceCull.hpp" void BackSurfaceCull::operator()(std::shared_ptr<Model> &model, const Point3f &eye) const { std::vector<Polygon> remaining; const auto &polygons = model->Polygons(); const auto &points = model->Points(); const auto &normals = model->Normals(); for (const auto &polygon: model->Polygons()) { bool isCulled = true; const auto &pPos = polygon.Points(); const auto &nPos = polygon.Normals(); for (auto i = 0; i < pPos.size() && isCulled; i++) { auto p = points[pPos[i]]; auto n = normals[nPos[i]]; auto eyePointVec = Normal(p, eye); if (n * eyePointVec >= 0) { isCulled = false; } } if (!isCulled) { remaining.push_back(polygon); } } model->Polygons() = remaining; }
28.129032
91
0.544725
1c28a6c2d84c8db78475da19c2ed7f4c02177055
2,687
cc
C++
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////// //// //// cagey-engine - Toy 3D Engine //// Copyright (c) 2014 Kyle Girard <theycallmecoach@gmail.com> //// //// The MIT License (MIT) //// //// Permission is hereby granted, free of charge, to any person obtaining a copy //// of this software and associated documentation files (the "Software"), to deal //// in the Software without restriction, including without limitation the rights //// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //// copies of the Software, and to permit persons to whom the Software is //// furnished to do so, subject to the following conditions: //// //// The above copyright notice and this permission notice shall be included in //// all copies or substantial portions of the Software. //// //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //// SOFTWARE. //// ////////////////////////////////////////////////////////////////////////////////// // //#include <cagey/window/Window.hh> //#include <cagey/window/VideoMode.hh> //#include "cagey/window/WindowFactory.hh" //#include "cagey/window/IWindowImpl.hh" //#include <iostream> // //namespace { // cagey::window::Window const * fullScreenWindow = nullptr; //} // //namespace cagey { //namespace window { // //Window::Window(VideoMode const & vidMode, std::string const & winName, StyleSet const & winStyle) // : mImpl{}, // mVideoMode{vidMode}, // mName{winName}, // mStyle{winStyle}, // mVisible{false} { // // if (winStyle.test(Style::Fullscreen)) { // if (fullScreenWindow) { // std::cerr << "Unable to create two fullscreen windows" << std::endl; // mStyle.flip(Style::Fullscreen); // } else { // if (!mVideoMode.isValid()) { // //@TODO invalid video mode...should have better exception // throw 0; // } // fullScreenWindow = this; // } // } // // mImpl = detail::WindowFactory::create(mVideoMode, mName, mStyle); // mVisible = true; //} // //auto Window::getTitle() const -> std::string { // return mName; //} // //auto Window::setTitle(std::string const & newTitle) -> void { // mName = newTitle; // mImpl->setTitle(newTitle); //} // //} // namespace window //} // namespace cagey // // //
34.012658
99
0.629326
1c2a37052907e1c29dfc55784516f8f3d7af259a
8,085
cc
C++
src/system/kernel/core/process/Process.cc
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
37
2015-01-11T20:08:48.000Z
2022-01-06T17:25:22.000Z
src/system/kernel/core/process/Process.cc
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
4
2016-05-20T01:01:59.000Z
2016-06-22T00:03:27.000Z
src/system/kernel/core/process/Process.cc
jmolloy/pedigree
4f02647d8237cc19cff3c20584c0fdd27b14a7d4
[ "0BSD" ]
6
2015-09-14T14:44:20.000Z
2019-01-11T09:52:21.000Z
/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #if defined(THREADS) #include <processor/types.h> #include <process/Process.h> #include <processor/Processor.h> #include <process/Scheduler.h> #include <processor/VirtualAddressSpace.h> #include <linker/Elf.h> #include <processor/PhysicalMemoryManager.h> #include <Log.h> #include <utilities/ZombieQueue.h> #include <process/SignalEvent.h> #include <Subsystem.h> #include <vfs/File.h> Process::Process() : m_Threads(), m_NextTid(0), m_Id(0), str(), m_pParent(0), m_pAddressSpace(&VirtualAddressSpace::getKernelAddressSpace()), m_ExitStatus(0), m_Cwd(0), m_Ctty(0), m_SpaceAllocator(true), m_pUser(0), m_pGroup(0), m_pEffectiveUser(0), m_pEffectiveGroup(0), m_pDynamicLinker(0), m_pSubsystem(0), m_DeadThreads(0) { m_Id = Scheduler::instance().addProcess(this); m_SpaceAllocator.free(m_pAddressSpace->getUserStart(), m_pAddressSpace->getUserReservedStart()); } Process::Process(Process *pParent) : m_Threads(), m_NextTid(0), m_Id(0), str(), m_pParent(pParent), m_pAddressSpace(0), m_ExitStatus(0), m_Cwd(pParent->m_Cwd), m_Ctty(pParent->m_Ctty), m_SpaceAllocator(pParent->m_SpaceAllocator), m_pUser(pParent->m_pUser), m_pGroup(pParent->m_pGroup), m_pEffectiveUser(pParent->m_pEffectiveUser), m_pEffectiveGroup(pParent->m_pEffectiveGroup), m_pDynamicLinker(pParent->m_pDynamicLinker), m_pSubsystem(0), m_DeadThreads(0) { m_pAddressSpace = pParent->m_pAddressSpace->clone(); // Copy the heap, but only if it's not the kernel heap (which is static) uintptr_t parentHeap = reinterpret_cast<uintptr_t>(pParent->m_pAddressSpace->m_Heap); // 0xc0000000 if(parentHeap < m_pAddressSpace->getKernelStart()) /// \todo A better way would be nice. m_pAddressSpace->setHeap(pParent->m_pAddressSpace->m_Heap, pParent->m_pAddressSpace->m_HeapEnd); m_Id = Scheduler::instance().addProcess(this); // Set a temporary description. str = m_pParent->str; str += "<F>"; // F for forked. } Process::~Process() { Scheduler::instance().removeProcess(this); Thread *pThread = m_Threads[0]; if(m_Threads.count()) m_Threads.erase(m_Threads.begin()); else WARNING("Process with an empty thread list, potentially unstable situation"); if(!pThread && m_Threads.count()) WARNING("Process with a null entry for the first thread, potentially unstable situation"); if (pThread != Processor::information().getCurrentThread()) delete pThread; // Calls Scheduler::remove and this::remove. else if(pThread) pThread->setParent(0); if(m_pSubsystem) delete m_pSubsystem; Spinlock lock; lock.acquire(); // Disables interrupts. VirtualAddressSpace &VAddressSpace = Processor::information().getVirtualAddressSpace(); Processor::switchAddressSpace(*m_pAddressSpace); m_pAddressSpace->revertToKernelAddressSpace(); Processor::switchAddressSpace(VAddressSpace); delete m_pAddressSpace; lock.release(); } size_t Process::addThread(Thread *pThread) { m_Threads.pushBack(pThread); return (m_NextTid += 1); } void Process::removeThread(Thread *pThread) { for(Vector<Thread*>::Iterator it = m_Threads.begin(); it != m_Threads.end(); it++) { if (*it == pThread) { m_Threads.erase(it); break; } } } size_t Process::getNumThreads() { return m_Threads.count(); } Thread *Process::getThread(size_t n) { if (n >= m_Threads.count()) { FATAL("Process::getThread(" << Dec << n << Hex << ") - Parameter out of bounds."); return 0; } return m_Threads[n]; } void Process::kill() { /// \todo Grab the scheduler lock! Processor::setInterrupts(false); if(m_pParent) NOTICE("Kill: " << m_Id << " (parent: " << m_pParent->getId() << ")"); else NOTICE("Kill: " << m_Id << " (parent: <orphan>)"); // Redraw on kill. /// \todo Caveat with redirection, maybe? Hmm... if(m_Ctty) m_Ctty->truncate(); // Bye bye process - have we got any zombie children? for (size_t i = 0; i < Scheduler::instance().getNumProcesses(); i++) { Process *pProcess = Scheduler::instance().getProcess(i); if (pProcess && (pProcess->m_pParent == this)) { if (pProcess->getThread(0)->getStatus() == Thread::Zombie) { // Kill 'em all! delete pProcess; } else { pProcess->m_pParent = 0; } } } // Kill all our threads except one, which exists in Zombie state. while (m_Threads.count() > 1) { Thread *pThread = m_Threads[0]; if (pThread != Processor::information().getCurrentThread()) { m_Threads.erase(m_Threads.begin()); delete pThread; // Calls Scheduler::remove and this::remove. } } // Tell any threads that may be waiting for us to die. if (m_pParent) m_pParent->m_DeadThreads.release(); else { NOTICE("Adding process to zombie queue for cleanup"); ZombieQueue::instance().addObject(new ZombieProcess(this)); Processor::information().getScheduler().killCurrentThread(); // Should never get here. FATAL("Process: should never get here"); } // We'll get reaped elsewhere NOTICE("Not adding process to zombie queue for cleanup"); Processor::information().getScheduler().schedule(Thread::Zombie); FATAL("Should never get here"); } uintptr_t Process::create(uint8_t *elf, size_t elfSize, const char *name) { FATAL("This function isn't implemented correctly - registration with the dynamic linker is required!"); // At this point we're uninterruptible, as we're forking. Spinlock lock; lock.acquire(); // Create a new process for the init process. Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent()); pProcess->description().clear(); pProcess->description().append(name); VirtualAddressSpace &oldAS = Processor::information().getVirtualAddressSpace(); // Switch to the init process' address space. Processor::switchAddressSpace(*pProcess->getAddressSpace()); // That will have forked - we don't want to fork, so clear out all the chaff in the new address space that's not // in the kernel address space so we have a clean slate. pProcess->getAddressSpace()->revertToKernelAddressSpace(); Elf initElf; // initElf.load(elf, elfSize); // uintptr_t iter = 0; // const char *lib = initElf.neededLibrary(iter); // initElf.allocateSegments(); // initElf.writeSegments(); for (int j = 0; j < 0x20000; j += 0x1000) { physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage(); bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x40000000), VirtualAddressSpace::Write| VirtualAddressSpace::Execute); if (!b) WARNING("map() failed in init"); } // Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available... new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(initElf.getEntryPoint()), 0x0 /* parameter */, reinterpret_cast<void*>(0x40020000-8) /* Stack */); // Switch back to the old address space. Processor::switchAddressSpace(oldAS); lock.release(); return pProcess->getId(); } #endif
33
164
0.687322
1c2ab67c1db41c545f994247455c2e688cd42224
321
cpp
C++
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "Omega_h_timer.hpp" namespace Omega_h { Now now() { Now t; t.impl = std::chrono::high_resolution_clock::now(); return t; } Real operator-(Now b, Now a) { return std::chrono::duration_cast<std::chrono::nanoseconds>(b.impl - a.impl) .count() * 1e-9; } } // end namespace Omega_h
17.833333
78
0.619938
1c2cf5f3e0ce5d29833ec36397e7c4fea8733201
1,321
cpp
C++
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
232
2017-10-09T11:45:28.000Z
2022-03-28T11:14:46.000Z
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
26
2019-01-20T21:38:25.000Z
2021-10-16T03:57:17.000Z
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
33
2017-10-26T19:20:38.000Z
2022-03-16T11:21:43.000Z
#include <CGAL/convex_hull_3.h> #include <possumwood_sdk/node_implementation.h> #include "datatypes/meshes.h" #include "errors.h" namespace { using possumwood::CGALPolyhedron; using possumwood::Meshes; typedef possumwood::CGALPolyhedron Mesh; dependency_graph::InAttr<Meshes> a_inMesh; dependency_graph::OutAttr<Meshes> a_outMesh; dependency_graph::State compute(dependency_graph::Values& data) { possumwood::ScopedOutputRedirect redirect; // inefficient - an adaptor to replace this would be much better std::vector<possumwood::CGALKernel::Point_3> points; for(auto& mesh : data.get(a_inMesh)) points.insert(points.end(), mesh.polyhedron().points_begin(), mesh.polyhedron().points_end()); possumwood::Mesh mesh("convex_hull"); CGAL::convex_hull_3(points.begin(), points.end(), mesh.edit().polyhedron()); Meshes result; result.addMesh(mesh); data.set(a_outMesh, result); return redirect.state(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inMesh, "in_mesh", possumwood::Meshes(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_outMesh, "out_mesh", possumwood::Meshes(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_inMesh, a_outMesh); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("cgal/topology/convex_hull", init); } // namespace
28.106383
98
0.766086
1c2e89d744f4124d22abdfe05d593e26c4d67f5a
6,353
cpp
C++
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
9
2015-02-23T15:47:20.000Z
2020-05-19T23:42:05.000Z
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
3
2020-04-21T06:12:53.000Z
2020-08-20T16:56:17.000Z
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
12
2015-02-18T18:34:57.000Z
2020-07-12T04:04:36.000Z
/**************************************************************************/ /** ** @file tListInputData.cpp ** @brief Functions for class tListInputData. ** ** Modifications: ** - changed .tri file format from points-edges-triangles to ** points-triangles-edges, compatible with earlier format (gt 1/98) ** - GT merged tListIFStreams and tListInputData into a single class ** to avoid multiple definition errors resulting from mixing ** template & non-template classes (1/99) ** - Bug fix in constructor: nnodes was being read from edge and ** triangle files -- thus arrays dimensioned incorrectly! (GT 04/02) ** - Remove dead code. Add findRightTime (AD 07/03) ** - Add Random number generator handling. (AD 08/03) ** - Refactoring with multiple classes (AD 11/03) ** - Add tVegetation handling (AD 11/03) ** ** $Id: tListInputData.cpp,v 1.25 2004/06/16 13:37:35 childcvs Exp $ */ /**************************************************************************/ #include "tListInputData.h" #include <iostream> #include "../Mathutil/mathutil.h" void tListInputDataBase:: ReportIOError(IOErrorType t, const char *filename, const char *suffix, int n) { std::cerr << "\nFile: '" << filename << suffix << "' " << "- Can't read "; switch (t){ case IOTime: std::cerr << "time"; break; case IOSize: std::cerr << "size"; break; case IORecord: std::cerr << "record " << n; break; } std::cerr << "." << std::endl; ReportFatalError( "Input/Output Error." ); } /**************************************************************************\ ** ** tListInputDataBase::openFile ** ** Find the right time in file and position it for reading ** \**************************************************************************/ void tListInputDataBase:: openFile( std::ifstream &infile, const char *basename, const char *ext) { char inname[80]; // full name of an input file // Open each of the four files assert( strlen(basename)+strlen(ext)<sizeof(inname) ); strcpy( inname, basename ); strcat( inname, ext ); infile.open(inname); if( !infile.good() ) { std::cerr << "Error: I can't find the following files:\n" << "\t" << basename << ext << "\n"; ReportFatalError( "Unable to open triangulation input file(s)." ); } } /**************************************************************************\ ** ** tListInputData::findRightTime ** ** Find the right time in file and position it for reading ** \**************************************************************************/ void tListInputDataBase:: findRightTime( std::ifstream &infile, int &nn, double intime, const char *basename, const char *ext, const char *typefile) { char headerLine[kMaxNameLength]; // header line read from input file bool righttime = false; double time; while( !( infile.eof() ) && !righttime ) { /*infile.getline( headerLine, kMaxNameLength ); if( headerLine[0] == kTimeLineMark ) { infile.seekg( -infile.gcount(), ios::cur ); infile >> time; std::cout << "from file, time = " << time << std::endl; std::cout << "Read: " << headerLine << std::endl; if( time == intime ) righttime = 1; }*/ infile >> time; if (infile.fail()) ReportIOError(IOTime, basename, ext); if (0) //DEBUG std::cout << "Read time: " << time << std::endl; if( time < intime ) { infile >> nn; if (infile.fail()) ReportIOError(IOSize, basename, ext); if (0) //DEBUG std::cout << "nn (" << typefile << ")= " << nn << std::endl; int i; for( i=1; i<=nn+1; i++ ) { infile.getline( headerLine, kMaxNameLength ); } } else righttime = true; if (0) //DEBUG std::cout << " NOW are we at eof? " << infile.eof() << std::endl; } if( !( infile.eof() ) ) { infile >> nn; if (infile.fail()) ReportIOError(IOSize, basename, ext); } else { std::cerr << "Couldn't find the specified input time in the " << typefile << " file\n"; ReportFatalError( "Input error" ); } } /**************************************************************************\ ** ** tListInputDataRand::tListInputDataRand() ** ** Read state from file ** \**************************************************************************/ tListInputDataRand:: tListInputDataRand( const tInputFile &inputfile, tRand &rand ) { double intime; // desired time char basename[80]; inputfile.ReadItem( basename, sizeof(basename), "INPUTDATAFILE" ); std::ifstream dataInfile; openFile( dataInfile, basename, SRANDOM); // Find out which time slice we want to extract intime = inputfile.ReadItem( intime, "INPUTTIME" ); if (1) //DEBUG std::cout << "intime = " << intime << std::endl; // Find specified input times in input data files and read # items. int nn; findRightTime( dataInfile, nn, intime, basename, SRANDOM, "random number generator"); if ( rand.numberRecords() != nn ) { std::cerr << "Invalid number of records for the random number generator\n"; ReportFatalError( "Input error" ); } // Read in data from file rand.readFromFile( dataInfile ); } /**************************************************************************\ ** ** tListInputDataVegetation::tListInputDataVegetation() ** ** Read state from file ** \**************************************************************************/ tListInputDataVegetation:: tListInputDataVegetation( const tInputFile &inputfile ) { double intime; // desired time char basename[80]; // Read base name for triangulation files from inputfile inputfile.ReadItem( basename, sizeof(basename), "INPUTDATAFILE" ); std::ifstream dataInfile; openFile( dataInfile, basename, SVEG); // Find out which time slice we want to extract intime = inputfile.ReadItem( intime, "INPUTTIME" ); if (1) //DEBUG std::cout << "intime = " << intime << std::endl; // Find specified input times in input data files and read # items. int nn; findRightTime( dataInfile, nn, intime, basename, SVEG, "vegetation mask"); // Read in data from file vegCov.setSize(nn); for( int i=0; i<nn; ++i ){ dataInfile >> vegCov[i]; if (dataInfile.fail()) ReportIOError(IORecord, basename, SVEG, i); } }
30.990244
79
0.555171
1c330f7ac0367e8acfd10060b8804c48af9818e7
353
cpp
C++
source/code/programs/examples/saturating/main.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/programs/examples/saturating/main.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/programs/examples/saturating/main.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include <cstddef> #include <cstdint> #include <iostream> #include "types.hpp" uint8_t x[] { 101, 27, 3, 95 }; int main () { uint_sat8_t s = 25; for (const auto& v : x) { s -= v; } // s == 0 s++; // s == 1 for (const auto& v : x) { s *= v; } unsigned j = s; // s == 255 std::cout << j << std::endl; }
16.045455
32
0.456091
1c3585e9f7e941a11ef84bd043a79cf2de61c87f
2,522
cpp
C++
LeetCode/C++/General/Hard/LongestValidParentheses/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Hard/LongestValidParentheses/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
LeetCode/C++/General/Hard/LongestValidParentheses/main.cpp
busebd12/InterviewPreparation
e68c41f16f7790e44b10a229548186e13edb5998
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include <string> #include <vector> /* * Solutions: * * 1. Brute-force. We generate every possible substring and if the substring is valid, update the result * to be the length of the longest one of these substrings. * * Time complexity: O(n^3) [where n is the length of the input string] * Space complexity: O(n^3) * * * 2. We "colour"/label each pair of valid parentheses with 1's and all invalid parentheses with 0's. * Then, the problem is reduced to finding the maximum substring sum of all 1's. * * Time complexity: O(n) [where n is the length of the input string] * Space complexity: O(n) */ bool isValid(std::string & str) { int count=0; for(const auto & character : str) { if(character=='(') { count++; } else { if(count <= 0) { return false; } count--; } } return count==0; } int longestValidParentheses(std::string s) { int result=0; if(s.empty()) { return result; } int n=int(s.size()); for(int start=0;start<=n;++start) { for(int length=1;length<=n-start;++length) { std::string substring=s.substr(start, length); if(isValid(substring)) { if(result==0 || substring.length() > result) { result=substring.length(); } } } } return result; } int longestValidParentheses(std::string s) { int result=0; if(s.empty()) { return result; } std::stack<int> stk; auto n=s.size(); std::vector<int> digits(n, 0); for(auto i=0;i<n;++i) { char character=s[i]; if(character=='(') { stk.push(i); } else { if(!stk.empty()) { if(s[stk.top()]=='(') { digits[stk.top()]=1; digits[i]=1; stk.pop(); } } else { stk.push(i); } } } int length=0; for(const auto & digit : digits) { if(digit==1) { length++; } else { result=std::max(result, length); length=0; } } result=std::max(result, length); return result; }
18.143885
104
0.458763
1c3910f2a6205a1a12e5f64cf3fca1df90a4da2b
8,952
cpp
C++
Web/src/ApacheAgent/ApacheAgent.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Web/src/ApacheAgent/ApacheAgent.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Web/src/ApacheAgent/ApacheAgent.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (C) 2004-2011 by Autodesk, Inc. // // This library is free software; you can redistribute it and/or // modify it under the terms of version 2.1 of the GNU Lesser // General Public License as published by the Free Software Foundation. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include "MapGuideCommon.h" #include "httpd.h" #include "http_config.h" #include "ap_config.h" #include "http_log.h" #include "http_protocol.h" #include "http_main.h" #include "util_script.h" #include "http_core.h" #include "apr_strings.h" #include "apr_tables.h" #ifdef strtoul #undef strtoul #endif #define strtoul strtoul #ifndef _WIN32 #ifdef REG_NOMATCH #undef REG_NOMATCH #endif #endif #include "WebSupport.h" #include "HttpHandler.h" #include "MapAgentGetParser.h" #include "MapAgentStrings.h" #include "MapAgentCommon.h" #include "ApacheResponseHandler.h" #include "ApachePostParser.h" #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> extern "C" module AP_MODULE_DECLARE_DATA mgmapagent_module; void Initialize(request_rec *r); STRING gConfigPath; // Iterate through the values in an apr_table. // Used only during debugging/development to identify the available environment variables. int iterate_func(void *req, const char *key, const char *value) { int stat; char *line; request_rec *r = (request_rec *)req; if (key == NULL || value == NULL || value[0] == '\0') return 1; line = apr_psprintf(r->pool, "%s => %s\n", key, value); stat = ap_rputs(line, r); return 1; } // Extract the values in the apr_tables. // Used only during debugging/development to identify the available environment variables. static int dump_request(request_rec *r) { // if (strcmp(r->handler, "mgmapagent-handler")) // return DECLINED; ap_set_content_type(r, "text/plain"); if (r->header_only) return OK; apr_table_do(iterate_func, r, r->headers_in, NULL); apr_table_do(iterate_func, r, r->subprocess_env, NULL); apr_table_do(iterate_func, r, r->headers_out, NULL); return OK; } string GetServerVariable(request_rec *r, const char *variableName) { string sValue; const char *value = apr_table_get(r->subprocess_env, variableName); if (value) { sValue.append(value); } return sValue; } static int mgmapagent_handler (request_rec *r) { if (strcmp(r->handler, "mgmapagent_handler") != 0) // NOXLATE { return DECLINED; } Initialize(r); ApacheResponseHandler responseHandler(r); MG_TRY() // Construct self Url. It is embedded into the output stream // of some requests (like GetMap). Use a fully qualified URL. string serverName = GetServerVariable(r, MapAgentStrings::ServerName); string serverPort = GetServerVariable(r, MapAgentStrings::ServerPort); string scriptName = GetServerVariable(r, MapAgentStrings::ScriptName); string remoteAddr = GetServerVariable(r, MapAgentStrings::RemoteAddr); string httpClientIp = GetServerVariable(r, MapAgentStrings::HttpClientIp); string httpXFF = GetServerVariable(r, MapAgentStrings::HttpXForwardedFor); string sSecure = GetServerVariable(r, MapAgentStrings::Secure); const char * secure = sSecure.c_str(); bool isSecure = (secure != NULL && !_stricmp(secure, "on")); // NOXLATE string url = isSecure ? MapAgentStrings::Https : MapAgentStrings::Http; if (!serverName.empty() && !serverPort.empty() && !scriptName.empty()) { url.append(serverName); url += ':'; url.append(serverPort); url.append(scriptName); } STRING wUrl = MgUtil::MultiByteToWideChar(url); Ptr<MgHttpRequest> request = new MgHttpRequest(wUrl); Ptr<MgHttpRequestParam> params = request->GetRequestParam(); string query = GetServerVariable(r, MapAgentStrings::QueryString); string requestMethod = GetServerVariable(r, MapAgentStrings::RequestMethod); ApachePostParser postParser(r); if (!requestMethod.empty() && requestMethod.find("POST") != string::npos) // NOXLATE { // Must be a POST request postParser.Parse(params); } else if (!query.empty()) { MapAgentGetParser::Parse(query.c_str(), params); } // check for CLIENTIP, if it's not there (and it shouldn't be), // add it in using httpClientIp. httpXFF or remoteAddr STRING clientIp = L""; if (!params->ContainsParameter(L"CLIENTIP")) // NOXLATE { if (!httpClientIp.empty() && _stricmp(httpClientIp.c_str(), MapAgentStrings::Unknown) != 0) { clientIp = MgUtil::MultiByteToWideChar(httpClientIp); params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE } else if (!httpXFF.empty() && _stricmp(httpXFF.c_str(), MapAgentStrings::Unknown) != 0) { clientIp = MgUtil::MultiByteToWideChar(httpXFF); params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE } else if (!remoteAddr.empty()) { clientIp = MgUtil::MultiByteToWideChar(remoteAddr); params->AddParameter(L"CLIENTIP", clientIp); // NOXLATE } } // Check for HTTP Basic Auth header string auth = GetServerVariable(r, MapAgentStrings::HttpAuth); bool gotAuth = MapAgentCommon::ParseAuth((char *)auth.c_str(), params); if (!gotAuth) { // And check for a REMOTE_USER remapped header auth = GetServerVariable(r, MapAgentStrings::HttpRemoteUser); gotAuth = MapAgentCommon::ParseAuth((char *)auth.c_str(), params); } // Log request information string postData = ""; if (!requestMethod.empty() && requestMethod.find("POST") != string::npos) // NOXLATE { // Get the post xml data postData = params->GetXmlPostData(); } STRING client = params->GetParameterValue(MgHttpResourceStrings::reqClientAgent); MapAgentCommon::LogRequest(client, clientIp, url, requestMethod, postData, query); Ptr<MgPropertyCollection> paramList = params->GetParameters()->GetPropertyCollection(); if (paramList != NULL) { // Check to be sure that we have some kind of credentials before continuing. Either // username/password or sessionid. bool bValid = paramList->Contains(MgHttpResourceStrings::reqSession); // Strike two: no session? how about a username? if (!bValid) bValid = paramList->Contains(MgHttpResourceStrings::reqUsername); // Strike three: no username either? How about if it's an XML POST if (!bValid) bValid = params->GetXmlPostData().length() != 0; // Certain operations do not require authentication STRING operation = params->GetParameterValue(L"OPERATION"); if((_wcsicmp(operation.c_str(), L"GETSITESTATUS") == 0)) { bValid = true; } if (!bValid) { // Invalid authentication information is not fatal, we should continue. responseHandler.RequestAuth(); return OK; } Ptr<MgHttpResponse> response = request->Execute(); responseHandler.SendResponse(response); } MG_CATCH(L"ApacheAgent.mgmapagent_handler"); if (mgException != NULL) { responseHandler.SendError(mgException); } return OK; } static void register_hooks (apr_pool_t *p) { ap_hook_handler(mgmapagent_handler, NULL, NULL, APR_HOOK_FIRST); } extern "C" { module AP_MODULE_DECLARE_DATA mgmapagent_module = { STANDARD20_MODULE_STUFF, NULL, NULL, NULL, NULL, NULL, register_hooks, }; }; void Initialize(request_rec *r) { ap_add_cgi_vars(r); ap_add_common_vars(r); // Uncomment for Debugging only //dump_request(r); if (!IsWebTierInitialized()) { STRING scriptPath = MgUtil::MultiByteToWideChar(GetServerVariable(r, MapAgentStrings::ScriptFileName)); STRING::size_type lastSlash = scriptPath.find_last_of(L"/"); // NOXLATE if (lastSlash < scriptPath.length()) { gConfigPath = scriptPath.substr(0, lastSlash + 1); } else { gConfigPath = scriptPath; } STRING configFile = gConfigPath; configFile.append(MapAgentStrings::WebConfig); MG_TRY() MgInitializeWebTier(configFile); MG_CATCH_AND_THROW(L"ApacheAgent.Initialize"); } }
30.040268
111
0.661416
1c39384ce95547642533d79874ef7f0dda03a3c5
4,864
cpp
C++
source/Foundation/DataStream.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
19
2015-12-19T11:15:57.000Z
2022-03-09T11:22:11.000Z
source/Foundation/DataStream.cpp
DevilWithin/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
1
2017-05-17T09:31:10.000Z
2017-05-19T17:01:31.000Z
source/Foundation/DataStream.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
3
2015-12-14T17:40:26.000Z
2021-02-25T00:42:42.000Z
#include <Nephilim/Foundation/DataStream.h> #include <Nephilim/Foundation/IODevice.h> #include <Nephilim/Foundation/String.h> #include <assert.h> #include <stdio.h> NEPHILIM_NS_BEGIN /// Constructs a invalid data stream DataStream::DataStream() : m_device(NULL) { } /// Constructs a data stream from a device DataStream::DataStream(IODevice& device) : m_device(&device) { } /// Set the device of this data stream void DataStream::setDevice(IODevice& device) { m_device = &device; } /// Read <size> bytes from the stream void DataStream::read(void* destination, uint32_t size) { assert(m_device); m_device->read(reinterpret_cast<char*>(destination), size); } /// Write a memory segment to the stream as-is void DataStream::write(void* source, uint32_t size) { assert(m_device); m_device->write(reinterpret_cast<char*>(source), size); } /// Write a uint32_t to the stream void DataStream::write_uint32(uint32_t v) { assert(m_device); m_device->write(reinterpret_cast<const char*>(&v), sizeof(v)); } /// Reads the next byte as a char char DataStream::readChar() { char c = EOF; if(m_device) { m_device->read(&c, sizeof(char)); } return c; } /// Reads count chars and stores them in the pre allocated buffer destination void DataStream::readChars(int count, char* destination) { if(m_device) { for(int i = 0; i < count; ++i) { m_device->read(&destination[i], sizeof(char)); } } } /// Write a 64-bit integer DataStream& DataStream::operator<<(Int64 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 64-bit signed integer DataStream& DataStream::operator<<(Int32 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 16-bit signed integer DataStream& DataStream::operator<<(Int16 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 8-bit signed integer DataStream& DataStream::operator<<(Int8 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 32-bit unsigned integer DataStream& DataStream::operator<<(Uint32 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a boolean as a unsigned byte DataStream& DataStream::operator<<(bool value) { if(m_device) { Uint8 tempValue = static_cast<Uint8>(value); m_device->write(reinterpret_cast<const char*>(&tempValue), sizeof(tempValue)); } return *this; } /// Write a String DataStream& DataStream::operator<<(const String& value) { if(m_device) { *this << static_cast<Int64>(value.length()); m_device->write(value.c_str(), sizeof(char)*value.length()); } return *this; } /// Write a float DataStream& DataStream::operator<<(float value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Read a 64-bit integer DataStream& DataStream::operator>>(Int64& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int64)); } return *this; } /// Read a 32-bit signed integer DataStream& DataStream::operator>>(Int32& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int32)); } return *this; } /// Read a 16-bit signed integer DataStream& DataStream::operator>>(Int16& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int16)); } return *this; } /// Read a 32-bit unsigned integer DataStream& DataStream::operator>>(Uint32& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint32)); } return *this; } /// Read a 16-bit unsigned integer DataStream& DataStream::operator>>(Uint16& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint16)); } return *this; } /// Read a 8-bit unsigned integer DataStream& DataStream::operator>>(Uint8& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint8)); } return *this; } /// Read a 8-bit boolean DataStream& DataStream::operator>>(bool& value) { if(m_device) { Uint8 tempValue; m_device->read(reinterpret_cast<char*>(&tempValue), sizeof(Uint8)); value = static_cast<bool>(tempValue); } return *this; } /// Read a String DataStream& DataStream::operator>>(String& value) { if(m_device) { Int64 length = 0; *this >> length; char* buffer = new char[length+1]; m_device->read(buffer, length); buffer[length] = '\0'; value = buffer; } return *this; } /// Read a float DataStream& DataStream::operator>>(float& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(float)); } return *this; } NEPHILIM_NS_END
19.07451
80
0.694901
1c3b4e522196f9a659bf825df253016e8ed0edf2
1,881
cpp
C++
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
22
2016-08-11T06:16:25.000Z
2022-02-22T00:06:59.000Z
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
9
2016-12-08T12:42:38.000Z
2021-12-28T20:12:15.000Z
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
8
2017-06-26T13:15:06.000Z
2021-11-12T18:39:54.000Z
// // bpfrequencytracker.cpp // barcode_project // // Created by luzhao on 4/21/16. // Copyright © 2016 luzhao. All rights reserved. // #include "bpfrequencytracker.hpp" #include <array> #include <cassert> #include <vector> using std::array; using std::vector; namespace barcodeSpace { BPFrequencyTracker::BPFrequencyTracker(size_t num_positions) { _total_position = num_positions; assert(_total_position > 0); _totalFrequency = 0; _condition_frequency_tracker.assign(num_positions, vector<ConditionFrequencyTable>(num_positions,ConditionFrequencyTable())); _self_marginal_frequency.assign(_total_position,array<uint64_t,4>()); for (size_t pos = 0; pos < _total_position; ++pos) { for (auto& t : _condition_frequency_tracker[pos]) { for (auto& c : t) { c.fill(0); } } } for (auto& marg : _self_marginal_frequency) { marg.fill(0); } _dict = kmersDictionary::getAutoInstance(); _bps_buffer.assign(_total_position, 0); } void BPFrequencyTracker::addFrequency(const std::string& seq, size_t freq) { assert(seq.length() == _total_position); for (size_t pos = 0; pos < _total_position; ++pos) { _bps_buffer[pos] = _dict->asc2dna(seq[pos]); _self_marginal_frequency[pos][_bps_buffer[pos]] += 1; } _totalFrequency += freq; // update the conditional frequency table for (size_t pos = 0; pos < _total_position - 1; ++pos) { for (size_t n_pos = pos + 1; n_pos < _total_position; ++n_pos) { _condition_frequency_tracker[pos][n_pos][_bps_buffer[pos]][_bps_buffer[n_pos]] += freq; } } } } // namespace barcodeSpace
34.2
133
0.596491
1c3f0bc21d3ed41f6fe8b58cb8a63f66eb007ca4
2,627
inl
C++
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * transport.inl * * Created on: Feb 8, 2016 * Author: zmij */ #ifndef WIRE_CORE_TRANSPORT_INL_ #define WIRE_CORE_TRANSPORT_INL_ #include <wire/core/transport.hpp> #include <wire/util/debug_log.hpp> namespace wire { namespace core { template < typename Session, transport_type Type > transport_listener< Session, Type >::transport_listener( asio_config::io_service_ptr svc, session_factory factory) : io_service_{svc}, acceptor_{*svc}, factory_{factory}, ready_{false}, closed_{true} { } template < typename Session, transport_type Type > transport_listener< Session, Type >::~transport_listener() { try { close(); } catch (...) {} } template < typename Session, transport_type Type > void transport_listener< Session, Type >::open(endpoint const& ep, bool rp) { endpoint_type proto_ep = traits::create_endpoint(io_service_, ep); acceptor_.open(proto_ep.protocol()); acceptor_.set_option( typename acceptor_type::reuse_address{true} ); acceptor_.set_option( typename acceptor_type::keep_alive{ true } ); if (rp) { acceptor_.set_option( reuse_port{true} ); } acceptor_.bind(proto_ep); acceptor_.listen(); closed_ = false; start_accept(); ready_ = true; } template < typename Session, transport_type Type > void transport_listener< Session, Type >::close() { if (!closed_) { closed_ = true; traits::close_acceptor(acceptor_); ready_ = false; } } template < typename Session, transport_type Type > typename transport_listener<Session, Type>::session_ptr transport_listener<Session, Type>::create_session() { return factory_( io_service_ ); } template < typename Session, transport_type Type > endpoint transport_listener<Session, Type>::local_endpoint() const { return traits::get_endpoint_data(acceptor_.local_endpoint()); } template < typename Session, transport_type Type > void transport_listener<Session, Type>::start_accept() { session_ptr session = create_session(); acceptor_.async_accept(session->socket(), ::std::bind(&transport_listener::handle_accept, this, session, ::std::placeholders::_1)); } template < typename Session, transport_type Type > void transport_listener<Session, Type>::handle_accept(session_ptr session, asio_config::error_code const& ec) { if (!ec) { session->start_session(); if (!closed_) start_accept(); } else { DEBUG_LOG(3, "Listener accept error code " << ec.message()); } } } // namespace core } // namespace wire #endif /* WIRE_CORE_TRANSPORT_INL_ */
25.019048
104
0.694328
1c4131f4e99beaf367375d11ca8b722024d71696
3,249
hpp
C++
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
2
2020-05-05T13:31:55.000Z
2022-01-16T15:38:00.000Z
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
null
null
null
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
1
2021-11-27T02:32:24.000Z
2021-11-27T02:32:24.000Z
#ifndef MATH_HPP #define MATH_HPP #include <cfloat> #include <cmath> #include <iostream> #include <vector> #include "glm/glm.hpp" using namespace std; #define FLT_CMP(a, b) (abs(a-b)<=FLT_EPSILON) #define DEG2RAD(x) (x*M_PI/180.0) #define RAD2DEG(x) (x*180.0/M_PI) template <typename T> ostream& operator<<(ostream& o, const vector<T>& v){ cout<<"["; for(int i=0;i<v.size();i++) cout<<v[i]<<" "; cout<<"]"; return o; } struct Size{ float w; float h; Size(); }; class Vec2D{ public: Vec2D(); Vec2D(float x, float y); void Set(float x, float y); void Normalize(); float Len() const; float Cross(const Vec2D v) const; float Dot(const Vec2D v) const; void Rotate(float degree); Vec2D operator=(const Vec2D v); Vec2D operator+(const Vec2D v); Vec2D operator-(const Vec2D v); Vec2D operator*(const Vec2D v); Vec2D operator/(const Vec2D v); Vec2D operator+=(const Vec2D v); Vec2D operator-=(const Vec2D v); Vec2D operator*=(const Vec2D v); Vec2D operator/=(const Vec2D v); bool operator==(const Vec2D v); bool operator!=(const Vec2D v); Vec2D operator+(float v); Vec2D operator-(float v); Vec2D operator*(float v); Vec2D operator/(float v); Vec2D operator+=(float v); Vec2D operator-=(float v); Vec2D operator*=(float v); Vec2D operator/=(float v); float x; float y; void Print() const; }; float Distance(Vec2D v1, Vec2D v2); Vec2D Normalize(Vec2D v); Vec2D Rotate(Vec2D v, float degree); Vec2D operator+(float n, Vec2D v); Vec2D operator-(float n, Vec2D v); Vec2D operator*(float n, Vec2D v); Vec2D operator/(float n, Vec2D v); ostream& operator<<(ostream& o, const Vec2D v); using Vec = Vec2D; struct Range{ Range(); Range(float a, float b); void Set(float a, float b); float GetMax() const; float GetMin() const; float Len() const; float min; float max; void Print() const; }; ostream& operator<<(ostream& o, Range range); Range GetCoveredRange(const Range r1, const Range r2); Range CombineRange(const Range r1, const Range r2); bool PointInRange(const Range r, float p); bool IsRangeCovered(const Range r1, const Range r2); class Rot2D{ public: Rot2D(); Rot2D(float degree); void Set(float degree); Vec2D GetAxisX() const; Vec2D GetAxisY() const; float GetDegree() const; private: float s; float c; }; struct Mat22{ Mat22(); Mat22(Vec2D c1, Vec2D c2); Mat22(float m00, float m01, float m10, float m11); void Identify(); void Zero(); Mat22 Times(const Mat22 m); Mat22 operator+(const Mat22 m); Mat22 operator-(const Mat22 m); Mat22 operator*(const Mat22 m); Vec2D operator*(const Vec2D v); Mat22 operator*(float n); Mat22 operator/(const Mat22 m); Mat22 operator/(float n); Mat22 operator+=(const Mat22 m); Mat22 operator-=(const Mat22 m); Mat22 operator*=(const Mat22 m); Mat22 operator/=(const Mat22 m); float m00; float m01; float m10; float m11; void Print() const; }; ostream& operator<<(ostream& o, Mat22 m); Mat22 operator*(float n, Mat22 m); Mat22 operator/(float n, Mat22 m); Mat22 GenRotMat22(float degree); #endif
23.374101
54
0.644814
1c4340895d9ff32d7ffa191d42ebd2c4e08e39ec
732
cpp
C++
anagram/anagram.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
1
2022-02-04T19:22:58.000Z
2022-02-04T19:22:58.000Z
anagram/anagram.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
null
null
null
anagram/anagram.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
null
null
null
#include "anagram.h" namespace anagram { anagram::anagram(string s) { word = s; } vector <string> anagram::matches(vector <string> v) { size_t w; for (int i = 0; i < v.size(); i++) { if (word.length() == v[i].length()) { temp1 = v[i]; for (int j = 0; j < v[i].length(); j++) { v[i][j] = tolower(v[i][j]); word[j] = tolower(word[j]); } temp2= v[i]; for (int j = 0; j < v[i].length(); j++) { w = temp2.find(word[j]); if (w == string::npos || word == v[i]) { break; } else { temp2.erase(w, 1); } } if (temp2.length() == 0) { vec.push_back(temp1); } } } return vec; } } // namespace anagram
17.023256
53
0.449454
1c49c154874b273a42fea95b7447dfd1476a38c6
2,902
cpp
C++
src/input.cpp
Bryankaveen/tanks-ce
27670778dbf6329b7fa4e69d12f8a4e5fa1f3ad9
[ "MIT" ]
14
2020-08-11T14:39:52.000Z
2022-02-08T21:17:56.000Z
src/input.cpp
commandblockguy/Tanks-CE
9eb79438a0ecd12cbde23be207257c650b703acb
[ "MIT" ]
1
2020-11-04T08:17:52.000Z
2020-11-05T22:41:46.000Z
src/input.cpp
commandblockguy/Tanks-CE
9eb79438a0ecd12cbde23be207257c650b703acb
[ "MIT" ]
1
2021-12-16T19:24:04.000Z
2021-12-16T19:24:04.000Z
#include "game.h" #include "gui/pause.h" #include "objects/tank.h" #include "util/profiler.h" #include <keypadc.h> #define PLAYER_BARREL_ROTATION DEGREES_TO_ANGLE(5) //1/3 of a second for 90 degree rotation #define PLAYER_TREAD_ROTATION (DEGREES_TO_ANGLE(90) / (TARGET_TICK_RATE / 3)) void handle_movement() { Tank *player = game.player; angle_t target_rot; uint8_t keys = 0; if(kb_IsDown(kb_KeyDown)) keys |= DOWN; if(kb_IsDown(kb_KeyLeft)) keys |= LEFT; if(kb_IsDown(kb_KeyRight)) keys |= RIGHT; if(kb_IsDown(kb_KeyUp)) keys |= UP; switch(keys) { default: player->set_velocity(0); return; case UP: target_rot = DEGREES_TO_ANGLE(270); break; case DOWN: target_rot = DEGREES_TO_ANGLE(90); break; case LEFT: target_rot = DEGREES_TO_ANGLE(180); break; case RIGHT: target_rot = DEGREES_TO_ANGLE(0); break; case UP | RIGHT: target_rot = DEGREES_TO_ANGLE(315); break; case DOWN | RIGHT: target_rot = DEGREES_TO_ANGLE(45); break; case UP | LEFT: target_rot = DEGREES_TO_ANGLE(225); break; case DOWN | LEFT: target_rot = DEGREES_TO_ANGLE(135); } int diff = player->tread_rot - target_rot; if((uint)abs(diff) > DEGREES_TO_ANGLE(90)) { player->tread_rot += DEGREES_TO_ANGLE(180); diff = (int) (player->tread_rot - target_rot); } if(diff < -(int) PLAYER_TREAD_ROTATION) { player->tread_rot += PLAYER_TREAD_ROTATION; } else if(diff > (int) PLAYER_TREAD_ROTATION) { player->tread_rot -= PLAYER_TREAD_ROTATION; } else { player->tread_rot = target_rot; } if((uint)abs(diff) <= DEGREES_TO_ANGLE(45)) { player->set_velocity(TANK_SPEED_NORMAL); } else { player->set_velocity(0); } } uint8_t handle_input() { profiler_start(input); Tank *player = game.player; handle_movement(); if(kb_IsDown(kb_Key2nd)) { player->fire_shell(); } if(kb_IsDown(kb_KeyAlpha)) { player->lay_mine(); } if(kb_IsDown(kb_KeyMode)) { player->barrel_rot -= PLAYER_BARREL_ROTATION; } if(kb_IsDown(kb_KeyGraphVar)) { player->barrel_rot += PLAYER_BARREL_ROTATION; } if(kb_IsDown(kb_KeyAdd)) { switch(pause_menu()) { default: case 0: break; case 1: // todo: restart case 2: return QUIT; } } if(kb_IsDown(kb_KeyDel)) { // TODO: remove return NEXT_LEVEL; } if(kb_IsDown(kb_KeyClear)) { return QUIT; } if(kb_IsDown(kb_KeyYequ)) { profiler_print(); } profiler_end(input); return 0; }
25.910714
77
0.569952
1c50b7b697cd116c9bd383da141940098b7b88dd
1,001
hpp
C++
branch_predictor/btb_set.hpp
thild/orcs
3cf377e5573e05843a15d338c29d595d95ed1495
[ "MIT" ]
null
null
null
branch_predictor/btb_set.hpp
thild/orcs
3cf377e5573e05843a15d338c29d595d95ed1495
[ "MIT" ]
null
null
null
branch_predictor/btb_set.hpp
thild/orcs
3cf377e5573e05843a15d338c29d595d95ed1495
[ "MIT" ]
null
null
null
#include <tuple> #include <cmath> using namespace std; class btb_set_t { public: btb_line_t *lines = NULL; uint8_t depth = 0; // ==================================================================== /// Methods // ==================================================================== // hit, target_address, opcode_address uint64_t search (uint32_t index, uint64_t opcode_address) { return lines[index].search(opcode_address); } void update (uint32_t index, uint64_t opcode_address, uint64_t target_address) { lines[index].update(opcode_address, target_address); } void allocate() { auto numlines = (uint16_t)pow (2, this->depth); this->lines = new btb_line_t[numlines]; } btb_set_t(uint8_t depth) { this->depth = depth; } ~btb_set_t() { if (this->lines) delete [] lines; } };
28.6
88
0.467532
1c5164bdec19659eaffe195a7202c4bdcdd32ff4
1,463
cpp
C++
platforms/gfg/0455_k_maximum_sum_overlapping_contiguous_sub_arrays.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/gfg/0455_k_maximum_sum_overlapping_contiguous_sub_arrays.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/gfg/0455_k_maximum_sum_overlapping_contiguous_sub_arrays.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" void GetKMaxSums(vi arr, int k) { int n = arr.size(); vi presum(n + 1); for (int i = 1; i <= n; ++i) { presum[i] = arr[i - 1] + presum[i - 1]; } vi sums; for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { sums.push_back(presum[j] - presum[i - 1]); } } sort(sums.rbegin(), sums.rend()); for (int i = 0; i < k; ++i) { cout << sums[i] << ' '; } cout << endl; } void GetKMaxSums2(vi arr, int k) { int n = arr.size(); vi presum(n + 1); for (int i = 1; i <= n; ++i) { presum[i] += arr[i - 1] + presum[i - 1]; } priority_queue<int, vector<int>, greater<int>> pq; for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int sum = presum[j] - presum[i - 1]; if (pq.size() < k) { pq.push(sum); } else { if (pq.top() < sum) { pq.pop(); pq.push(sum); } } } } while (not pq.empty()) { cout << pq.top() << ' '; pq.pop(); } cout << endl; } int main() { TimeMeasure _; vi arr1 = {4, -8, 9, -4, 1, -8, -1, 6}; int k1 = 4; vi arr2 = {-2, -3, 4, -1, -2, 1, 5, -3}; int k2 = 3; GetKMaxSums(arr1, k1); GetKMaxSums(arr2, k2); cout << endl; GetKMaxSums2(arr1, k1); GetKMaxSums2(arr2, k2); }
24.383333
56
0.395079
1c5287128a8e952846a5208fa07831366f7e1a2e
2,141
cpp
C++
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
#include <cxlog/logger/logger.h> NAMESPACE_CXLOG_BEGIN void Logger::Log(Level level, const char *file, std::size_t line, const char *func, std::string &&msg) const { const Additional &additional = this->additional; std::vector<Context> contexts; contexts.reserve(additional.statics->size() + additional.dynamics->size()); for (StaticContext &context : *additional.statics) { contexts.emplace_back(Context{context.GetKey(), context.GetValue()}); } for (DynamicContext &context : *additional.dynamics) { contexts.emplace_back(Context{context.GetKey(), context.GetValue()}); } LockGuard lock(this->intrinsic->lock); Record record; record.time = Clock::now(); record.level = level; record.file = file; record.line = line; record.func = func; record.msg = std::move(msg); record.prefix = *additional.prefix; record.contexts = std::move(contexts); record.mark = additional.mark; if (additional.filter(record) && this->intrinsic->config.DoFilter(record)) { this->FormatAndWrite(level, record); } } void Logger::FormatAndWrite(Level level, const Record &record) const { const Intrinsic &intrinsic = *this->intrinsic; std::array<std::string, SlotCount> logs; for (std::size_t i = 0; i < SlotCount; i++) { const Slot &slot = intrinsic.slots[i]; if (slot.NeedToLog(level, record)) { std::string &log = logs[i]; if (log.empty()) { log = slot.Format(record); for (size_t n : intrinsic.equivalents[i]) { logs[n] = log; } } slot.Write(log, record); } } } void Logger::UpdateEquivalents() { Intrinsic &intrinsic = *this->intrinsic; for (std::size_t i = 0; i < SlotCount; i++) { intrinsic.equivalents[i].clear(); for (std::size_t j = i + 1; j < SlotCount; j++) { if (intrinsic.slots[i].GetFormatter() == intrinsic.slots[j].GetFormatter()) { intrinsic.equivalents[i].push_back(j); } } } } NAMESPACE_CXLOG_END
31.485294
89
0.601121
1c545e6a82c9f3620c90a0f0cb67fffe2415267f
781
cpp
C++
Olympiad Solutions/DMOJ/bts17p4.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
Olympiad Solutions/DMOJ/bts17p4.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
Olympiad Solutions/DMOJ/bts17p4.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
// Ivan Carvalho // Solution to https://dmoj.ca/problem/bts17p4 #include <bits/stdc++.h> using namespace std; typedef pair<int,int> ii; vector<ii> todos; vector<int> menores; int N,M,J; int checa(int t){ menores.clear(); for(ii d : todos){ if(d.second <= t) menores.push_back(d.first); } sort(menores.begin(),menores.end()); int pos = 0; for(int i : menores){ if(i - pos <= J) pos = i; } if((N + 1) - pos <= J) return 1; return 0; } int main(){ scanf("%d %d %d",&N,&M,&J); while(M--){ int a,b; scanf("%d %d",&a,&b); todos.push_back(ii(a,b)); } int ini = 0, fim = 1000010 , meio, resp = -1; while(ini <= fim){ meio = (ini+fim)/2; if(checa(meio)){ resp = meio; fim = meio - 1; } else{ ini = meio + 1; } } printf("%d\n",resp); return 0; }
18.595238
47
0.567222
1c551e9d9dd8a9379c999a289f2501eaa2dff666
22,647
cpp
C++
src/plugins/grass/qgsgrasstools.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/grass/qgsgrasstools.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/grass/qgsgrasstools.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsgrasstools.cpp ------------------- begin : March, 2005 copyright : (C) 2005 by Radim Blazek email : blazek@itc.it ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsgrasstools.h" #include "qgsgrassmodule.h" #include "qgsgrassregion.h" #include "qgsgrassshell.h" #include "qgsgrass.h" #include "qgsconfig.h" #include "qgisinterface.h" #include "qgsapplication.h" #include "qgslogger.h" #include "qgssettings.h" #include <QCloseEvent> #include <QDomDocument> #include <QFile> #include <QHeaderView> #include <QMessageBox> #include <QPainter> // // For experimental model view alternative ui by Tim // // #include "qgsdetaileditemdata.h" #include "qgsdetaileditemdelegate.h" #ifdef Q_OS_WIN #include "qgsgrassutils.h" #endif QgsGrassTools::QgsGrassTools( QgisInterface *iface, QWidget *parent, const char *name, Qt::WindowFlags f ) : QgsDockWidget( parent, f ) { Q_UNUSED( name ); QgsDebugMsg( "QgsGrassTools()" ); setupUi( this ); connect( mFilterInput, &QLineEdit::textChanged, this, &QgsGrassTools::mFilterInput_textChanged ); connect( mDebugButton, &QPushButton::clicked, this, &QgsGrassTools::mDebugButton_clicked ); connect( mCloseDebugButton, &QPushButton::clicked, this, &QgsGrassTools::mCloseDebugButton_clicked ); connect( mViewModeButton, &QToolButton::clicked, this, &QgsGrassTools::mViewModeButton_clicked ); QPushButton *closeMapsetButton = new QPushButton( QgsApplication::getThemeIcon( QStringLiteral( "mActionFileExit.svg" ) ), tr( "Close mapset" ), this ); mTabWidget->setCornerWidget( closeMapsetButton ); connect( closeMapsetButton, &QAbstractButton::clicked, this, &QgsGrassTools::closeMapset ); qRegisterMetaType<QgsDetailedItemData>(); mIface = iface; mCanvas = mIface->mapCanvas(); //statusBar()->hide(); // set the dialog title resetTitle(); // Tree view code. if ( !QgsGrass::modulesDebug() ) { mDebugWidget->hide(); } // List view mTreeModel = new QStandardItemModel( 0, 1 ); mTreeModelProxy = new QgsGrassToolsTreeFilterProxyModel( this ); mTreeModelProxy->setSourceModel( mTreeModel ); mTreeModelProxy->setFilterRole( Qt::UserRole + Search ); mTreeView->setModel( mTreeModelProxy ); connect( mTreeView, &QAbstractItemView::clicked, this, &QgsGrassTools::itemClicked ); // List view with filter mModulesListModel = new QStandardItemModel( 0, 1 ); mModelProxy = new QSortFilterProxyModel( this ); mModelProxy->setSourceModel( mModulesListModel ); mModelProxy->setFilterRole( Qt::UserRole + 2 ); mListView->setModel( mModelProxy ); connect( mListView, &QAbstractItemView::clicked, this, &QgsGrassTools::itemClicked ); mListView->hide(); connect( QgsGrass::instance(), &QgsGrass::modulesConfigChanged, this, static_cast<bool ( QgsGrassTools::* )()>( &QgsGrassTools::loadConfig ) ); connect( QgsGrass::instance(), &QgsGrass::modulesDebugChanged, this, &QgsGrassTools::debugChanged ); connect( mDebugReloadButton, &QAbstractButton::clicked, this, static_cast<bool ( QgsGrassTools::* )()>( &QgsGrassTools::loadConfig ) ); // Region widget tab mRegion = new QgsGrassRegion( mIface, this ); mTabWidget->addTab( mRegion, tr( "Region" ) ); // Show before loadConfig() so that user can see loading restorePosition(); showTabs(); } void QgsGrassTools::resetTitle() { QString title; if ( QgsGrass::activeMode() ) { title = tr( "GRASS Tools: %1/%2" ).arg( QgsGrass::getDefaultLocation(), QgsGrass::getDefaultMapset() ); } else { title = tr( "GRASS Tools" ); } setWindowTitle( title ); } void QgsGrassTools::showTabs() { resetTitle(); // Build modules tree if empty QgsDebugMsg( QString( "mTreeModel->rowCount() = %1" ).arg( mTreeModel->rowCount() ) ); if ( mTreeModel->rowCount() == 0 ) { // Load the modules lists QApplication::setOverrideCursor( Qt::WaitCursor ); loadConfig(); QApplication::restoreOverrideCursor(); QgsDebugMsg( QString( "mTreeModel->rowCount() = %1" ).arg( mTreeModel->rowCount() ) ); } // we always show tabs but disabled if not active if ( QgsGrass::activeMode() ) { mMessageLabel->hide(); mTabWidget->setEnabled( true ); } else { mMessageLabel->show(); mTabWidget->setEnabled( false ); } } void QgsGrassTools::runModule( QString name, bool direct ) { if ( name.length() == 0 ) { return; // Section } #ifdef HAVE_POSIX_OPENPT QgsGrassShell *sh = nullptr; #endif QWidget *m = nullptr; if ( name == QLatin1String( "shell" ) ) { #ifdef Q_OS_WIN QgsGrass::putEnv( "GRASS_HTML_BROWSER", QgsGrassUtils::htmlBrowserPath() ); QStringList env; QByteArray origPath = qgetenv( "PATH" ); QByteArray origPythonPath = qgetenv( "PYTHONPATH" ); QString path = QString( origPath ) + QgsGrass::pathSeparator() + QgsGrass::grassModulesPaths().join( QgsGrass::pathSeparator() ); QString pythonPath = QString( origPythonPath ) + QgsGrass::pathSeparator() + QgsGrass::getPythonPath(); QgsDebugMsg( "path = " + path ); QgsDebugMsg( "pythonPath = " + pythonPath ); qputenv( "PATH", path.toLocal8Bit() ); qputenv( "PYTHONPATH", pythonPath.toLocal8Bit() ); // QProcess does not support environment for startDetached() -> set/reset to orig if ( !QProcess::startDetached( getenv( "COMSPEC" ) ) ) { QMessageBox::warning( 0, "Warning", tr( "Cannot start command shell (%1)" ).arg( getenv( "COMSPEC" ) ) ); } qputenv( "PATH", origPath ); qputenv( "PYTHONPATH", origPythonPath ); return; #else #ifdef HAVE_POSIX_OPENPT sh = new QgsGrassShell( this, mTabWidget ); m = qobject_cast<QWidget *>( sh ); #else QMessageBox::warning( 0, tr( "Warning" ), tr( "GRASS Shell is not compiled." ) ); #endif #endif // Q_OS_WIN } else { // set wait cursor because starting module may be slow because of getting temporal datasets (t.list) QApplication::setOverrideCursor( Qt::WaitCursor ); QgsGrassModule *gmod = new QgsGrassModule( this, name, mIface, direct, mTabWidget ); QApplication::restoreOverrideCursor(); if ( !gmod->errors().isEmpty() ) { QgsGrass::warning( gmod->errors().join( QStringLiteral( "\n" ) ) ); } m = qobject_cast<QWidget *>( gmod ); } int height = mTabWidget->iconSize().height(); QString path = QgsGrass::modulesConfigDirPath() + "/" + name; QPixmap pixmap = QgsGrassModule::pixmap( path, height ); if ( !pixmap.isNull() ) { // Icon size in QT does not seem to be variable // -> reset the width to max icon width if ( mTabWidget->iconSize().width() < pixmap.width() ) { mTabWidget->setIconSize( QSize( pixmap.width(), mTabWidget->iconSize().height() ) ); } QIcon is; is.addPixmap( pixmap ); mTabWidget->addTab( m, is, QString() ); } else { mTabWidget->addTab( m, name ); } mTabWidget->setCurrentIndex( mTabWidget->count() - 1 ); // We must call resize to reset COLUMNS environment variable // used by bash !!! #if 0 /* TODO: Implement something that resizes the terminal without * crashes. */ #ifdef HAVE_POSIX_OPENPT if ( sh ) { sh->resizeTerminal(); } #endif #endif } bool QgsGrassTools::loadConfig() { QString conf = QgsGrass::modulesConfigDirPath() + "/default.qgc"; return loadConfig( conf, mTreeModel, mModulesListModel, false ); } bool QgsGrassTools::loadConfig( QString filePath, QStandardItemModel *treeModel, QStandardItemModel *modulesListModel, bool direct ) { QgsDebugMsg( filePath ); treeModel->clear(); modulesListModel->clear(); QFile file( filePath ); if ( !file.exists() ) { QMessageBox::warning( nullptr, tr( "Warning" ), tr( "The config file (%1) not found." ).arg( filePath ) ); return false; } if ( ! file.open( QIODevice::ReadOnly ) ) { QMessageBox::warning( nullptr, tr( "Warning" ), tr( "Cannot open config file (%1)." ).arg( filePath ) ); return false; } QDomDocument doc( QStringLiteral( "qgisgrass" ) ); QString err; int line, column; if ( !doc.setContent( &file, &err, &line, &column ) ) { QString errmsg = tr( "Cannot read config file (%1):" ).arg( filePath ) + tr( "\n%1\nat line %2 column %3" ).arg( err ).arg( line ).arg( column ); QgsDebugMsg( errmsg ); QMessageBox::warning( nullptr, tr( "Warning" ), errmsg ); file.close(); return false; } QDomElement docElem = doc.documentElement(); QDomNodeList modulesNodes = docElem.elementsByTagName( QStringLiteral( "modules" ) ); if ( modulesNodes.count() == 0 ) { file.close(); return false; } QDomNode modulesNode = modulesNodes.item( 0 ); QDomElement modulesElem = modulesNode.toElement(); // Go through the sections and modules and add them to the list view addModules( nullptr, modulesElem, treeModel, modulesListModel, false ); if ( direct ) { removeEmptyItems( treeModel ); } mTreeView->expandToDepth( 0 ); file.close(); return true; } void QgsGrassTools::debugChanged() { if ( QgsGrass::modulesDebug() ) { mDebugWidget->show(); } else { mDebugWidget->hide(); } } void QgsGrassTools::appendItem( QStandardItemModel *treeModel, QStandardItem *parent, QStandardItem *item ) { if ( parent ) { parent->appendRow( item ); } else if ( treeModel ) { treeModel->appendRow( item ); } } void QgsGrassTools::addModules( QStandardItem *parent, QDomElement &element, QStandardItemModel *treeModel, QStandardItemModel *modulesListModel, bool direct ) { QDomNode n = element.firstChild(); while ( !n.isNull() ) { QDomElement e = n.toElement(); if ( !e.isNull() ) { // QgsDebugMsg(QString("tag = %1").arg(e.tagName())); if ( e.tagName() != QLatin1String( "section" ) && e.tagName() != QLatin1String( "grass" ) ) { QgsDebugMsg( QString( "Unknown tag: %1" ).arg( e.tagName() ) ); continue; } // Check GRASS version QStringList errors; if ( !QgsGrassModuleOption::checkVersion( e.attribute( QStringLiteral( "version_min" ) ), e.attribute( QStringLiteral( "version_max" ) ), errors ) ) { // TODO: show somehow errors only in debug mode, but without reloading tree if ( !errors.isEmpty() ) { QString label = e.attribute( QStringLiteral( "label" ) ) + e.attribute( QStringLiteral( "name" ) ); // one should be non empty label += "\n ERROR:\t" + errors.join( QStringLiteral( "\n\t" ) ); QStandardItem *item = new QStandardItem( label ); item->setData( label, Qt::UserRole + Label ); item->setData( label, Qt::UserRole + Search ); item->setData( QgsApplication::getThemeIcon( QStringLiteral( "mIconWarning.svg" ) ), Qt::DecorationRole ); appendItem( treeModel, parent, item ); } n = n.nextSibling(); continue; } if ( e.tagName() == QLatin1String( "section" ) ) { QString label = QApplication::translate( "grasslabel", e.attribute( QStringLiteral( "label" ) ).toUtf8() ); QgsDebugMsg( QString( "label = %1" ).arg( label ) ); QStandardItem *item = new QStandardItem( label ); item->setData( label, Qt::UserRole + Label ); // original label, for debug item->setData( label, Qt::UserRole + Search ); // for filtering later addModules( item, e, treeModel, modulesListModel, direct ); appendItem( treeModel, parent, item ); } else if ( e.tagName() == QLatin1String( "grass" ) ) { // GRASS module QString name = e.attribute( QStringLiteral( "name" ) ); QgsDebugMsgLevel( QString( "name = %1" ).arg( name ), 1 ); //QString path = QgsApplication::pkgDataPath() + "/grass/modules/" + name; QString path = QgsGrass::modulesConfigDirPath() + "/" + name; QgsGrassModule::Description description = QgsGrassModule::description( path ); if ( !direct || description.direct ) { QString label = name + " - " + description.label; QPixmap pixmap = QgsGrassModule::pixmap( path, 32 ); QStandardItem *item = new QStandardItem( name + "\n" + description.label ); item->setData( name, Qt::UserRole + Name ); // for calling runModule later item->setData( label, Qt::UserRole + Label ); // original label, for debug item->setData( label, Qt::UserRole + Search ); // for filtering later item->setData( pixmap, Qt::DecorationRole ); item->setCheckable( false ); item->setEditable( false ); appendItem( treeModel, parent, item ); bool exists = false; for ( int i = 0; i < modulesListModel->rowCount(); i++ ) { if ( modulesListModel->item( i )->data( Qt::UserRole + Name ).toString() == name ) { exists = true; break; } } if ( !exists ) { QStandardItem *listItem = item->clone(); listItem->setText( name + "\n" + description.label ); // setData in the delegate with a variantised QgsDetailedItemData QgsDetailedItemData myData; myData.setTitle( name ); myData.setDetail( label ); myData.setIcon( pixmap ); myData.setCheckable( false ); myData.setRenderAsWidget( false ); QVariant myVariant = qVariantFromValue( myData ); listItem->setData( myVariant, Qt::UserRole ); modulesListModel->appendRow( listItem ); } } } } n = n.nextSibling(); } } // used for direct void QgsGrassTools::removeEmptyItems( QStandardItemModel *treeModel ) { // TODO: never tested if ( !treeModel ) { return; } // Clean tree nodes without children for ( int i = treeModel->rowCount() - 1; i >= 0; i-- ) { QStandardItem *item = treeModel->item( i ); removeEmptyItems( item ); if ( item->rowCount() == 0 ) { treeModel->removeRow( i ); } } } // used for direct void QgsGrassTools::removeEmptyItems( QStandardItem *item ) { // TODO: never tested for ( int i = item->rowCount() - 1; i >= 0; i-- ) { QStandardItem *sub = item->child( i ); removeEmptyItems( sub ); if ( sub->rowCount() == 0 ) { item->removeRow( i ); } } } void QgsGrassTools::closeMapset() { QgsGrass::instance()->closeMapsetWarn(); QgsGrass::saveMapset(); } void QgsGrassTools::mapsetChanged() { mTabWidget->setCurrentIndex( 0 ); closeTools(); mRegion->mapsetChanged(); showTabs(); } QgsGrassTools::~QgsGrassTools() { saveWindowLocation(); } QString QgsGrassTools::appDir( void ) { #if defined(Q_OS_WIN) return QgsGrass::shortPath( QgsApplication::applicationDirPath() ); #else return QgsApplication::applicationDirPath(); #endif } void QgsGrassTools::close( void ) { saveWindowLocation(); hide(); } void QgsGrassTools::closeEvent( QCloseEvent *e ) { saveWindowLocation(); e->accept(); } void QgsGrassTools::restorePosition() { QgsSettings settings; restoreGeometry( settings.value( QStringLiteral( "GRASS/windows/tools/geometry" ) ).toByteArray() ); show(); } void QgsGrassTools::saveWindowLocation() { QgsSettings settings; settings.setValue( QStringLiteral( "GRASS/windows/tools/geometry" ), saveGeometry() ); } void QgsGrassTools::emitRegionChanged() { emit regionChanged(); } void QgsGrassTools::closeTools() { for ( int i = mTabWidget->count() - 1; i > 1; i-- ) // first is module tree, second is region { delete mTabWidget->widget( i ); } } // // Helper function for Tim's experimental model list // void QgsGrassTools::mFilterInput_textChanged( QString text ) { QgsDebugMsg( "GRASS modules filter changed to :" + text ); mTreeModelProxy->setFilter( text ); if ( text.isEmpty() ) { mTreeView->collapseAll(); mTreeView->expandToDepth( 0 ); } else { mTreeView->expandAll(); } // using simple wildcard filter which is probably what users is expecting, at least until // there is a filter type switch in UI QRegExp::PatternSyntax mySyntax = QRegExp::PatternSyntax( QRegExp::Wildcard ); Qt::CaseSensitivity myCaseSensitivity = Qt::CaseInsensitive; QRegExp myRegExp( text, myCaseSensitivity, mySyntax ); mModelProxy->setFilterRegExp( myRegExp ); } void QgsGrassTools::itemClicked( const QModelIndex &index ) { QgsDebugMsg( "Entered" ); if ( index.column() == 0 ) { // // If the model has been filtered, the index row in the proxy won't match // the index row in the underlying model so we need to jump through this // little hoop to get the correct item // const QSortFilterProxyModel *proxyModel = qobject_cast<const QSortFilterProxyModel *>( index.model() ); if ( !proxyModel ) { return; } QModelIndex modelIndex = proxyModel->mapToSource( index ); QStandardItemModel *model = nullptr; if ( proxyModel == mTreeModelProxy ) { model = mTreeModel; } else { model = mModulesListModel; } QStandardItem *mypItem = model->itemFromIndex( modelIndex ); if ( mypItem ) { QString myModuleName = mypItem->data( Qt::UserRole + Name ).toString(); runModule( myModuleName, false ); } } } void QgsGrassTools::mDebugButton_clicked() { QApplication::setOverrideCursor( Qt::BusyCursor ); int errors = 0; for ( int i = 0; i < mTreeModel->rowCount(); i++ ) { errors += debug( mTreeModel->item( i ) ); } mDebugLabel->setText( tr( "%1 errors found" ).arg( errors ) ); QApplication::restoreOverrideCursor(); } int QgsGrassTools::debug( QStandardItem *item ) { if ( !item ) { return 0; } QString name = item->data( Qt::UserRole + Name ).toString(); QString label = item->data( Qt::UserRole + Label ).toString(); if ( name.isEmpty() ) // section { int errors = 0; for ( int i = 0; i < item->rowCount(); i++ ) { QStandardItem *sub = item->child( i ); errors += debug( sub ); } if ( errors > 0 ) { label += " ( " + tr( "%1 errors" ).arg( errors ) + " )"; item->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconWarning.svg" ) ) ); } else { item->setIcon( QIcon() ); } item->setText( label ); return errors; } else // module { if ( name == QLatin1String( "shell" ) ) { return 0; } QgsGrassModule *module = new QgsGrassModule( this, name, mIface, false ); QgsDebugMsg( QString( "module: %1 errors: %2" ).arg( name ).arg( module->errors().size() ) ); Q_FOREACH ( QString error, module->errors() ) { // each error may have multiple rows and may be html formatted (<br>) label += "\n ERROR:\t" + error.replace( QLatin1String( "<br>" ), QLatin1String( "\n" ) ).replace( QLatin1String( "\n" ), QLatin1String( "\n\t" ) ); } item->setText( label ); int nErrors = module->errors().size(); delete module; return nErrors; } } void QgsGrassTools::mCloseDebugButton_clicked() { QgsGrass::instance()->setModulesDebug( false ); } void QgsGrassTools::mViewModeButton_clicked() { if ( mTreeView->isHidden() ) { mListView->hide(); mTreeView->show(); mViewModeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconListView.svg" ) ) ); } else { mTreeView->hide(); mListView->show(); mViewModeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "mIconTreeView.svg" ) ) ); } } QgsGrassToolsTreeFilterProxyModel::QgsGrassToolsTreeFilterProxyModel( QObject *parent ) : QSortFilterProxyModel( parent ) { setDynamicSortFilter( true ); mRegExp.setPatternSyntax( QRegExp::Wildcard ); mRegExp.setCaseSensitivity( Qt::CaseInsensitive ); } void QgsGrassToolsTreeFilterProxyModel::setSourceModel( QAbstractItemModel *sourceModel ) { mModel = sourceModel; QSortFilterProxyModel::setSourceModel( sourceModel ); } void QgsGrassToolsTreeFilterProxyModel::setFilter( const QString &filter ) { QgsDebugMsg( QString( "filter = %1" ).arg( filter ) ); if ( mFilter == filter ) { return; } mFilter = filter; mRegExp.setPattern( mFilter ); invalidateFilter(); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsString( const QString &value ) const { return value.contains( mRegExp ); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsRow( int sourceRow, const QModelIndex &sourceParent ) const { if ( mFilter.isEmpty() || !mModel ) { return true; } QModelIndex sourceIndex = mModel->index( sourceRow, 0, sourceParent ); return filterAcceptsItem( sourceIndex ) || filterAcceptsAncestor( sourceIndex ) || filterAcceptsDescendant( sourceIndex ); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsAncestor( const QModelIndex &sourceIndex ) const { if ( !mModel ) { return true; } QModelIndex sourceParentIndex = mModel->parent( sourceIndex ); if ( !sourceParentIndex.isValid() ) return false; if ( filterAcceptsItem( sourceParentIndex ) ) return true; return filterAcceptsAncestor( sourceParentIndex ); } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsDescendant( const QModelIndex &sourceIndex ) const { if ( !mModel ) { return true; } for ( int i = 0; i < mModel->rowCount( sourceIndex ); i++ ) { QModelIndex sourceChildIndex = mModel->index( i, 0, sourceIndex ); if ( filterAcceptsItem( sourceChildIndex ) ) return true; if ( filterAcceptsDescendant( sourceChildIndex ) ) return true; } return false; } bool QgsGrassToolsTreeFilterProxyModel::filterAcceptsItem( const QModelIndex &sourceIndex ) const { if ( !mModel ) { return true; } return filterAcceptsString( mModel->data( sourceIndex, filterRole() ).toString() ); }
29.034615
159
0.634654
1c5856d4b398bc8f8bf0bc558731f2f7feff1882
1,311
cpp
C++
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
 //------------------------------------------------------------------- // include //------------------------------------------------------------------- #include "weoExceptionMessageCreator.h" #include <sstream> namespace pm_mode { /******************************************************************** * @brief 一定のフォーマットに法った文字列を作成する * @note ExceptionMessage に使用されることを前提としている * @param[in] message 何か残したい特別なメッセージ * @param[in] fileName 文字列を作成したファイルの名前 * @param[in] line 文字列を作成した行 * @param[in] function 文字列を作成した関数 * @return 情報をまとめた文字列 *******************************************************************/ std::string messageCreator(const std::string& message, bool isException, weString fileName, int line, weString function) throw() { std::stringstream ss; std::string returnValue; if (isException) { returnValue += "Exception is thrown!!!\nmessage: " + message; } else { returnValue += "Have Message!!!\nmessage: " + message; } returnValue.append("\nfile: "); returnValue.append(fileName); ss << line; returnValue += "\nline: "; returnValue += ss.str(); returnValue.append("\nfunction: "); returnValue.append(function); returnValue.append("\n"); return returnValue; } } // namespace pm_mode
26.755102
129
0.515637
1c5b3de7fce16286f16fb22e379723f676ef5d50
546
hpp
C++
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
#ifndef SHADER_HPP_ #define SHADER_HPP_ #include "../jmax.hpp" #include <string> #include <vector> namespace jmax { class Shader { public: Shader(std::string const& filePath, GLenum shaderType = 0); virtual ~Shader(); public: static GLuint compileShaderFile(std::string const& shaderFilePath, GLenum shaderType); static GLenum Shader::getShaderType(std::string const& filePath); public: std::string const& filePath; const GLenum type; const GLuint shaderId; bool deleted; }; } // namespace jmax #endif /* !SHADER_HPP_ */
19.5
88
0.725275
1c5b779943d9abe8389382f1717d224f7c402fef
816
cpp
C++
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Node { public: Node *next; int data; }; void printList(Node *n) { while (n != NULL) { cout << n->data << "\t"; n = n->next; } } void insertAtFront(Node **start_node, int data) { Node *new_node = new Node(); new_node->data = data; new_node->next = *start_node; *start_node = new_node; } int main() { Node *first = new Node(); Node *second = new Node(); Node *third = new Node(); first->data = 1; first->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; cout << "Default List: \t"; printList(first); insertAtFront(&first, 0); cout << "\nList after inserting at front: \t"; printList(first); return 0; }
14.571429
50
0.551471
1c5c19ab2d119c2ccec4e995d72e9230b11a2b97
1,807
cpp
C++
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
1
2021-08-13T14:27:39.000Z
2021-08-13T14:27:39.000Z
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #define int long long const int MAX_N = 2000050; const int MOD = 19930726; std::string d, s; int re[MAX_N], cnt[MAX_N]; int n, nn, k; void init(); void manacher(); int quick_pow(int a, int b); signed main() { std::ios::sync_with_stdio(false); std::cin >> nn >> k >> s; int sum = 0, ans = 1; n = nn; init(); manacher(); for (int i = nn; i > 0; i--) { if (i % 2) { sum += cnt[i]; if (k >= sum) { ans *= quick_pow(i, sum); ans %= MOD; k -= sum; } else { ans *= quick_pow(i, k); ans %= MOD; k -= sum; break; } } else { continue; } } if (k > 0) { std::cout << -1 << '\n'; } else { std::cout << ans << '\n'; } return 0; } void init() { d.resize(2 * n + 10); d[0] = d[1] = 'A'; for (int i = 0; i < n; i++) { d[i * 2 + 2] = s[i]; d[i * 2 + 3] = 'A'; } n = 2 * n + 2; d[n] = 0; } void manacher() { int r = 0, mid = 0; for (int l = 1; l < n; l++) { if (l < r) { re[l] = std::min(re[mid * 2 - l], re[mid] + mid - l); } else { re[l] = 1; } while (d[l + re[l]] == d[l - re[l]]) { re[l]++; } if (re[l] + l > r) { r = re[l] + l; mid = l; } if ((re[l] - 1) % 2) { cnt[re[l] - 1]++; } } } int quick_pow(int a, int b) { a %= MOD; int res = 1; while (b) { if (b & 1) { res = res * a % MOD; } a = a * a % MOD; b >>= 1; } return res; }
17.891089
65
0.342557
1c5d2d09af639b8b275c0a1e970826844b4512c4
129
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:338e6e57d5446ad622a48ab505a62e4ddf72367f1dd3bd9dee9773f0f43ab857 size 1576
32.25
75
0.883721
1c60fa930f611edaa3a07a5d07828882b70c0b10
974
cpp
C++
demo/src/main.cpp
fundies/Crash2D
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
1
2017-05-25T13:49:18.000Z
2017-05-25T13:49:18.000Z
demo/src/main.cpp
fundies/SAT
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
6
2016-09-27T22:57:13.000Z
2017-05-11T17:01:26.000Z
demo/src/main.cpp
fundies/SAT
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
4
2016-09-29T01:19:44.000Z
2021-04-02T07:45:59.000Z
#include "MTVDemo.hpp" #include "BroadphaseDemo.hpp" int main(int argc, char **argv) { sf::RenderWindow window(sf::VideoMode(800, 600), "Crash2D Demo"); window.setFramerateLimit(60); Demo *demo = new MTVDemo(window); size_t demoId = 0; while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { switch (event.type) { // "close requested" event: we close the window case sf::Event::Closed: window.close(); break; case sf::Event::KeyReleased: if (event.key.code == sf::Keyboard::Space) { delete demo; ++demoId; if (demoId > 1) demoId = 0; switch (demoId) { case 0: demo = new MTVDemo(window); break; case 1: demo = new BroadphaseDemo(window); break; } } break; default: break; } } demo->draw(); window.display(); } }
21.173913
91
0.596509
1c61f3b6817b5d6e4326b7725944537b55eeac20
1,007
cpp
C++
Exam Practice/dice.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
Exam Practice/dice.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
Exam Practice/dice.cpp
egmnklc/Egemen-Files
34d409fa593ec41fc0d2cb48e23658663a1a06db
[ "MIT" ]
null
null
null
#include "dice.h" #include "randgen.h" // implementation of dice class // written Jan 31, 1994, modified 5/10/94 to use RandGen class // modified 3/31/99 to move RandGen class here from .h file Dice::Dice(int sides) // postcondition: all private fields initialized { myRollCount = 0; mySides = sides; } int Dice::Roll() // postcondition: number of rolls updated // random 'die' roll returned { RandGen gen; // random number generator myRollCount= myRollCount + 1; // update # of times die rolled return gen.RandInt(1,mySides); // in range [1..mySides] } int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; } int Dice::NumRolls() const // postcondition: return # of times die has been rolled { return myRollCount; } int Dice::MultipleRoll(int n) { int i = 0; unsigned int sum = 0; while (i < n) { sum += Roll(); i+=1; } return sum; }
20.55102
73
0.608739
1c6a083592b615ed772efc3dab21d3feb3c4330e
14,096
cpp
C++
Common/win32/ProxyResolver.cpp
JzHuai0108/bluefox-mlc-continuous-capture-avi
b04a2c80223c6f3afa15ca05ba3068f20702549a
[ "BSD-3-Clause" ]
null
null
null
Common/win32/ProxyResolver.cpp
JzHuai0108/bluefox-mlc-continuous-capture-avi
b04a2c80223c6f3afa15ca05ba3068f20702549a
[ "BSD-3-Clause" ]
null
null
null
Common/win32/ProxyResolver.cpp
JzHuai0108/bluefox-mlc-continuous-capture-avi
b04a2c80223c6f3afa15ca05ba3068f20702549a
[ "BSD-3-Clause" ]
null
null
null
#include "ProxyResolver.h" #if _WIN32_WINNT < 0x0602 // This stuff became available with Windows 8 # define WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE 0x01000000 # define WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE # define API_GET_PROXY_FOR_URL (6) #endif // #if _WIN32_WINNT < _WIN32_WINNT_WIN8 PFNWINHTTPGETPROXYFORURLEX ProxyResolver::s_pfnWinhttpGetProxyForUrlEx = NULL; PFNWINHTTPFREEPROXYLIST ProxyResolver::s_pfnWinhttpFreeProxyList = NULL; PFNWINHTTPCREATEPROXYRESOLVER ProxyResolver::s_pfnWinhttpCreateProxyResolver = NULL; PFNWINHTTPGETPROXYRESULT ProxyResolver::s_pfnWinhttpGetProxyResult = NULL; //----------------------------------------------------------------------------- ProxyResolver::ProxyResolver() : m_fInit( FALSE ), m_fExtendedAPI( FALSE ), m_dwError( ERROR_SUCCESS ), m_hEvent( 0 ) //----------------------------------------------------------------------------- { ZeroMemory( &m_wprProxyResult, sizeof( WINHTTP_PROXY_RESULT ) ); ZeroMemory( &m_wpiProxyInfo, sizeof( WINHTTP_PROXY_INFO ) ); HMODULE hWinhttp = GetModuleHandle( L"winhttp.dll" ); if( hWinhttp != NULL ) { s_pfnWinhttpGetProxyForUrlEx = ( PFNWINHTTPGETPROXYFORURLEX )GetProcAddress( hWinhttp, "WinHttpGetProxyForUrlEx" ); s_pfnWinhttpFreeProxyList = ( PFNWINHTTPFREEPROXYLIST )GetProcAddress( hWinhttp, "WinHttpFreeProxyResult" ); s_pfnWinhttpCreateProxyResolver = ( PFNWINHTTPCREATEPROXYRESOLVER )GetProcAddress( hWinhttp, "WinHttpCreateProxyResolver" ); s_pfnWinhttpGetProxyResult = ( PFNWINHTTPGETPROXYRESULT )GetProcAddress( hWinhttp, "WinHttpGetProxyResult" ); } m_fExtendedAPI = s_pfnWinhttpGetProxyForUrlEx && s_pfnWinhttpFreeProxyList && s_pfnWinhttpCreateProxyResolver && s_pfnWinhttpGetProxyResult; } //----------------------------------------------------------------------------- ProxyResolver::~ProxyResolver() //----------------------------------------------------------------------------- { if( m_wpiProxyInfo.lpszProxy != NULL ) { GlobalFree( m_wpiProxyInfo.lpszProxy ); } if( m_wpiProxyInfo.lpszProxyBypass != NULL ) { GlobalFree( m_wpiProxyInfo.lpszProxyBypass ); } if( m_fExtendedAPI ) { s_pfnWinhttpFreeProxyList( &m_wprProxyResult ); } if( m_hEvent != NULL ) { CloseHandle( m_hEvent ); } } //----------------------------------------------------------------------------- BOOL ProxyResolver::IsRecoverableAutoProxyError( _In_ DWORD dwError ) //----------------------------------------------------------------------------- { switch( dwError ) { case ERROR_SUCCESS: case ERROR_INVALID_PARAMETER: case ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR: case ERROR_WINHTTP_AUTODETECTION_FAILED: case ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT: case ERROR_WINHTTP_LOGIN_FAILURE: case ERROR_WINHTTP_OPERATION_CANCELLED: case ERROR_WINHTTP_TIMEOUT: case ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: case ERROR_WINHTTP_UNRECOGNIZED_SCHEME: return TRUE; default: break; } return FALSE; } //----------------------------------------------------------------------------- VOID CALLBACK ProxyResolver::GetProxyCallBack( _In_ HINTERNET hResolver, _In_ DWORD_PTR dwContext, _In_ DWORD dwInternetStatus, _In_ PVOID pvStatusInformation, _In_ DWORD /*dwStatusInformationLength*/ ) //----------------------------------------------------------------------------- { ProxyResolver* pProxyResolver = ( ProxyResolver* )dwContext; if( ( dwInternetStatus != WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE && dwInternetStatus != WINHTTP_CALLBACK_STATUS_REQUEST_ERROR ) || pProxyResolver == NULL ) { return; } if( dwInternetStatus == WINHTTP_CALLBACK_STATUS_REQUEST_ERROR ) { WINHTTP_ASYNC_RESULT* pAsyncResult = ( WINHTTP_ASYNC_RESULT* )pvStatusInformation; if( pAsyncResult->dwResult != API_GET_PROXY_FOR_URL ) { return; } pProxyResolver->m_dwError = pAsyncResult->dwError; } else if( dwInternetStatus == WINHTTP_CALLBACK_STATUS_GETPROXYFORURL_COMPLETE ) { pProxyResolver->m_dwError = s_pfnWinhttpGetProxyResult( hResolver, &pProxyResolver->m_wprProxyResult ); } if( hResolver != NULL ) { WinHttpCloseHandle( hResolver ); hResolver = NULL; } SetEvent( pProxyResolver->m_hEvent ); } #define CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE(HRESOLVER, ERROR_CODE) \ if( HRESOLVER != NULL ) \ { \ WinHttpCloseHandle( HRESOLVER ); \ } \ return ERROR_CODE //----------------------------------------------------------------------------- DWORD ProxyResolver::GetProxyForUrlEx( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl, _In_ WINHTTP_AUTOPROXY_OPTIONS* pAutoProxyOptions ) //----------------------------------------------------------------------------- { // Create proxy resolver handle. It's best to close the handle during call back. HINTERNET hResolver = NULL; DWORD dwError = s_pfnWinhttpCreateProxyResolver( hSession, &hResolver ); if( dwError != ERROR_SUCCESS ) { CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE( hResolver, dwError ); } // Sets up a callback function that WinHTTP can call as proxy results are resolved. WINHTTP_STATUS_CALLBACK wscCallback = WinHttpSetStatusCallback( hResolver, GetProxyCallBack, WINHTTP_CALLBACK_FLAG_REQUEST_ERROR | WINHTTP_CALLBACK_FLAG_GETPROXYFORURL_COMPLETE, 0 ); if( wscCallback == WINHTTP_INVALID_STATUS_CALLBACK ) { dwError = GetLastError(); CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE( hResolver, dwError ); } // The extended API works in asynchronous mode, therefore wait until the // results are set in the call back function. dwError = s_pfnWinhttpGetProxyForUrlEx( hResolver, pwszUrl, pAutoProxyOptions, ( DWORD_PTR )this ); if( dwError != ERROR_IO_PENDING ) { CLOSE_RESOLVER_HANDLE_AND_RETURN_ERROR_CODE( hResolver, dwError ); } // The resolver handle will get closed in the callback and cannot be used any longer. hResolver = NULL; dwError = WaitForSingleObjectEx( m_hEvent, INFINITE, FALSE ); if( dwError != WAIT_OBJECT_0 ) { return GetLastError(); } return m_dwError; } //----------------------------------------------------------------------------- _Success_( return == ERROR_SUCCESS ) DWORD ProxyResolver::GetProxyForAutoSettings( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl, _In_opt_z_ PCWSTR pwszAutoConfigUrl, _Outptr_result_maybenull_ PWSTR* ppwszProxy, _Outptr_result_maybenull_ PWSTR* ppwszProxyBypass ) //----------------------------------------------------------------------------- { DWORD dwError = ERROR_SUCCESS; WINHTTP_AUTOPROXY_OPTIONS waoOptions = {}; WINHTTP_PROXY_INFO wpiProxyInfo = {}; *ppwszProxy = NULL; *ppwszProxyBypass = NULL; if( pwszAutoConfigUrl ) { waoOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; waoOptions.lpszAutoConfigUrl = pwszAutoConfigUrl; } else { waoOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; waoOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; } // First call with no autologon. Autologon prevents the // session (in proc) or autoproxy service (out of proc) from caching // the proxy script. This causes repetitive network traffic, so it is // best not to do autologon unless it is required according to the // result of WinHttpGetProxyForUrl. // This applies to both WinHttpGetProxyForUrl and WinhttpGetProxyForUrlEx. if( m_fExtendedAPI ) { m_hEvent = CreateEventEx( NULL, NULL, 0, EVENT_ALL_ACCESS ); if( m_hEvent == NULL ) { dwError = GetLastError(); goto quit; } dwError = GetProxyForUrlEx( hSession, pwszUrl, &waoOptions ); if( dwError != ERROR_WINHTTP_LOGIN_FAILURE ) { // Unless we need to retry with auto-logon exit the function with the // result, on success the proxy list will be stored in m_wprProxyResult // by GetProxyCallBack. goto quit; } // Enable autologon if challenged. waoOptions.fAutoLogonIfChallenged = TRUE; dwError = GetProxyForUrlEx( hSession, pwszUrl, &waoOptions ); goto quit; } if( !WinHttpGetProxyForUrl( hSession, pwszUrl, &waoOptions, &wpiProxyInfo ) ) { dwError = GetLastError(); if( dwError != ERROR_WINHTTP_LOGIN_FAILURE ) { goto quit; } // Enable autologon if challenged. dwError = ERROR_SUCCESS; waoOptions.fAutoLogonIfChallenged = TRUE; if( !WinHttpGetProxyForUrl( hSession, pwszUrl, &waoOptions, &wpiProxyInfo ) ) { dwError = GetLastError(); goto quit; } } *ppwszProxy = wpiProxyInfo.lpszProxy; wpiProxyInfo.lpszProxy = NULL; *ppwszProxyBypass = wpiProxyInfo.lpszProxyBypass; wpiProxyInfo.lpszProxyBypass = NULL; quit: if( wpiProxyInfo.lpszProxy ) { GlobalFree( wpiProxyInfo.lpszProxy ); wpiProxyInfo.lpszProxy = NULL; } if( wpiProxyInfo.lpszProxyBypass ) { GlobalFree( wpiProxyInfo.lpszProxyBypass ); wpiProxyInfo.lpszProxyBypass = NULL; } return dwError; } //----------------------------------------------------------------------------- DWORD ProxyResolver::ResolveProxy( _In_ HINTERNET hSession, _In_z_ PCWSTR pwszUrl ) //----------------------------------------------------------------------------- { DWORD dwError = ERROR_SUCCESS; WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ProxyConfig = {}; PWSTR pwszProxy = NULL; PWSTR pwszProxyBypass = NULL; BOOL fFailOverValid = FALSE; if( m_fInit ) { dwError = ERROR_INVALID_OPERATION; goto quit; } if( !WinHttpGetIEProxyConfigForCurrentUser( &ProxyConfig ) ) { dwError = GetLastError(); if( dwError != ERROR_FILE_NOT_FOUND ) { goto quit; } // No IE proxy settings found, just do autodetect. ProxyConfig.fAutoDetect = TRUE; dwError = ERROR_SUCCESS; } // Begin processing the proxy settings in the following order: // 1) Auto-Detect if configured. // 2) Auto-Config URL if configured. // 3) Static Proxy Settings if configured. // // Once any of these methods succeed in finding a proxy we are finished. // In the event one mechanism fails with an expected error code it is // required to fall back to the next mechanism. If the request fails // after exhausting all detected proxies, there should be no attempt // to discover additional proxies. if( ProxyConfig.fAutoDetect ) { fFailOverValid = TRUE; // Detect Proxy Settings. dwError = GetProxyForAutoSettings( hSession, pwszUrl, NULL, &pwszProxy, &pwszProxyBypass ); if( dwError == ERROR_SUCCESS ) { goto commit; } if( !IsRecoverableAutoProxyError( dwError ) ) { goto quit; } // Fall back to Autoconfig URL or Static settings. An application can // optionally take some action such as logging, or creating a mechanism // to expose multiple error codes in the class. dwError = ERROR_SUCCESS; } if( ProxyConfig.lpszAutoConfigUrl ) { fFailOverValid = TRUE; // Run autoproxy with AutoConfig URL. dwError = GetProxyForAutoSettings( hSession, pwszUrl, ProxyConfig.lpszAutoConfigUrl, &pwszProxy, &pwszProxyBypass ); if( dwError == ERROR_SUCCESS ) { goto commit; } if( !IsRecoverableAutoProxyError( dwError ) ) { goto quit; } // Fall back to Static Settings. An application can optionally take some // action such as logging, or creating a mechanism to to expose multiple // error codes in the class. dwError = ERROR_SUCCESS; } fFailOverValid = FALSE; // Static Proxy Config. Failover is not valid for static proxy since // it is always either a single proxy or a list containing protocol // specific proxies such as "proxy" or http=httpproxy;https=sslproxy pwszProxy = ProxyConfig.lpszProxy; ProxyConfig.lpszProxy = NULL; pwszProxyBypass = ProxyConfig.lpszProxyBypass; ProxyConfig.lpszProxyBypass = NULL; commit: if( pwszProxy == NULL ) { m_wpiProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY; } else { m_wpiProxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY; } m_wpiProxyInfo.lpszProxy = pwszProxy; pwszProxy = NULL; m_wpiProxyInfo.lpszProxyBypass = pwszProxyBypass; pwszProxyBypass = NULL; m_fInit = TRUE; quit: if( pwszProxy != NULL ) { GlobalFree( pwszProxy ); pwszProxy = NULL; } if( pwszProxyBypass != NULL ) { GlobalFree( pwszProxyBypass ); pwszProxyBypass = NULL; } if( ProxyConfig.lpszAutoConfigUrl != NULL ) { GlobalFree( ProxyConfig.lpszAutoConfigUrl ); ProxyConfig.lpszAutoConfigUrl = NULL; } if( ProxyConfig.lpszProxy != NULL ) { GlobalFree( ProxyConfig.lpszProxy ); ProxyConfig.lpszProxy = NULL; } if( ProxyConfig.lpszProxyBypass != NULL ) { GlobalFree( ProxyConfig.lpszProxyBypass ); ProxyConfig.lpszProxyBypass = NULL; } return dwError; } //----------------------------------------------------------------------------- const WINHTTP_PROXY_RESULT_ENTRY* ProxyResolver::GetProxySetting( const DWORD index ) const //----------------------------------------------------------------------------- { if( index < m_wprProxyResult.cEntries ) { return &m_wprProxyResult.pEntries[index]; } return 0; }
34.380488
264
0.623936
1c6a8639fcb04a9a56098c34f080c26b14a84208
896
cpp
C++
UTSO/utso21p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
UTSO/utso21p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
UTSO/utso21p2.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() using namespace std; #ifndef ONLINE_JUDGE template<typename T> void pr(T a){std::cerr<<a<<std::endl;} template<typename T,typename... Args> void pr(T a, Args... args) {std::cerr<<a<<' ',pr(args...);} #else template<typename... Args> void pr(Args... args){} #endif int n, k; int main(){ cin>>k; for(int n = 1; n <= 101; n++){ assert(n != 101); int cur = n*(n-1)/2+n; vector<int> ans; for(int i = n; i > 0; i--){ int v = i*(i-1)/2+i; while(cur-v >= k){ cur -= v; if(size(ans)) ans.emplace_back(1); for(int j = 0; j < i; j++) ans.emplace_back(2); } } while(size(ans) < n) ans.emplace_back(1); if(size(ans) > n or cur != k) continue; // cout<<cur<<' '<<k<<endl; cout<<n<<'\n'; for(int i: ans) cout<<i<<' '; break; } }
18.666667
60
0.504464
1c6d2c7de9a44b122987529f4e6d173c3d381f35
1,127
cpp
C++
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
#include "townmgr.h" #include "companymgr.h" #include "interop/interop.hpp" #include "openloco.h" using namespace openloco::interop; namespace openloco::townmgr { static loco_global_array<town, 80, 0x005B825C> _towns; std::array<town, max_towns>& towns() { auto arr = (std::array<town, max_towns>*)_towns.get(); return *arr; } town* get(town_id_t id) { if (id >= _towns.size()) { return nullptr; } return &_towns[id]; } // 0x00496B6D void update() { if ((addr<0x00525E28, uint32_t>() & 1) && !is_editor_mode()) { auto ticks = scenario_ticks(); if (ticks % 8 == 0) { town_id_t id = (ticks / 8) % 0x7F; auto town = get(id); if (town != nullptr && !town->empty()) { companymgr::updating_company_id(company_id::neutral); town->update(); } } } } // 0x0049748C void update_monthly() { call(0x0049748C); } }
21.673077
73
0.485359