blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
3a4cadf2bc66ddb722cb381883e537a4f3e7c83a
fd4103e6f5116c776249b00171d8639313f05bc1
/Src/PartModelingEngine/PmeExplicitModelObjectReference.cpp
405b5471a693605017a5408a784102cf09bb273c
[]
no_license
Wanghuaichen/TransCAD
481f3b4e54cc066dde8679617a5b32ac2041911b
35ca89af456065925984492eb23a0543e3125bb8
refs/heads/master
2020-03-25T03:54:51.488397
2018-06-25T17:38:39
2018-06-25T17:38:39
143,367,529
2
1
null
2018-08-03T02:30:03
2018-08-03T02:30:03
null
UTF-8
C++
false
false
571
cpp
#include "StdAfx.h" #include ".\pmeexplicitmodelobjectreference.h" #include ".\PmeExceptionTest.h" #include ".\PmeArgumentNullException.h" #include ".\PmeExplicitModelObject.h" PME_IMPLEMENT_RUNTIME_TYPE(PmeExplicitModelObjectReference, PmeReference) PmeExplicitModelObjectReference::PmeExplicitModelObjectReference(PmePart * pPart, PmeExplicitModelObject * pObject) : PmeReference(pPart) { PmeThrowExceptionIf<PmeArgumentNullException>(!pObject); SetReferenceeName(pObject->GetName()); } PmeExplicitModelObjectReference::~PmeExplicitModelObjectReference(void) { }
[ "kyk5415@gmail.com" ]
kyk5415@gmail.com
aaf6b0a35c11bd3757c2a9acfac94932cf7d2fd0
60a15a584b00895e47628c5a485bd1f14cfeebbe
/AWIN/ctrl_groupbox.h
5701cba5c53fc3244d057561d0d35f45359029b4
[]
no_license
fcccode/vt5
ce4c1d8fe819715f2580586c8113cfedf2ab44ac
c88049949ebb999304f0fc7648f3d03f6501c65b
refs/heads/master
2020-09-27T22:56:55.348501
2019-06-17T20:39:46
2019-06-17T20:39:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,653
h
#pragma once #include "win_base.h" #define GBCTRL_DS_ROUND_RECT 0 #define GBCTRL_DS_SIMPLE_RECT 1 class group_box_ctrl : public win_impl { public: group_box_ctrl(); virtual ~group_box_ctrl(); public: virtual void handle_init(); virtual LRESULT on_paint(); virtual LRESULT on_destroy(); virtual bool subclass( HWND hwnd, bool f_nccreate = false ); void set_text( HINSTANCE hrc, UINT nID ); void set_text( char *psz ); void set_offset( int n ) {m_cx_offset = n;} void set_icon( HINSTANCE hrc, uint id ); void set_colors( COLORREF color_back, COLORREF color_text ); void set_draw_style( int nstyle ); void set_text_align( int nalign ); void set_text_valign( int nalign ); protected: HICON m_hicon; HFONT m_font; COLORREF m_color, m_color_text; int m_ndraw_style; int m_nalign; int m_nvalign; char *m_psz_text; int m_cx_offset; }; inline group_box_ctrl::group_box_ctrl() { m_hicon = 0; m_font = 0; m_ndraw_style = GBCTRL_DS_ROUND_RECT; m_nalign = DT_LEFT; m_nvalign = DT_VCENTER; m_color_text = RGB( 255, 255, 255 ); m_color = RGB( 192, 192, 192 ); m_psz_text = 0; m_cx_offset = 24; } inline group_box_ctrl::~group_box_ctrl() { if( m_hicon )::DestroyIcon( m_hicon ); _assert( m_font == 0 ); if( m_psz_text ) ::free( m_psz_text ); } inline void group_box_ctrl::handle_init() { _assert( m_font == 0 ); LOGFONT lf; ::GetObject( ::GetStockObject( DEFAULT_GUI_FONT ), sizeof( lf ), &lf ); lf.lfWeight = FW_BOLD; lf.lfHeight = 14; m_font = ::CreateFontIndirect( &lf ); } inline LRESULT group_box_ctrl::on_destroy() { if( m_font ) ::DeleteObject( m_font ); m_font = 0; return win_impl::on_destroy(); } inline bool group_box_ctrl::subclass( HWND hwnd, bool f_nccreate ) { char buf[1024]; ::GetWindowText( hwnd, buf, sizeof(buf)-1 ); ::SetWindowText( hwnd, "" ); if( m_psz_text )::free( m_psz_text ); m_psz_text = _tcsdup( buf ); return win_impl::subclass( hwnd, f_nccreate ); }; inline LRESULT group_box_ctrl::on_paint() { PAINTSTRUCT ps; HDC hdc = ::BeginPaint( handle(), &ps ); HFONT hold = (HFONT)::SelectObject( hdc, m_font ); char *psz_text = m_psz_text; char sz[1024]; if( !psz_text ) { ::GetWindowText( handle(), sz, sizeof( sz ) ); psz_text = sz; } _rect rect_client; ::GetClientRect( handle(), &rect_client ); { HBRUSH hbrush = ::CreateSolidBrush( m_color ); HBRUSH hold_brush = (HBRUSH)::SelectObject( hdc, hbrush ); HPEN hpen = ::CreatePen( PS_SOLID, 1, m_color ); HPEN hold_pen = (HPEN)::SelectObject( hdc, hpen ); if( m_ndraw_style == GBCTRL_DS_ROUND_RECT ) ::RoundRect( hdc, rect_client.left, rect_client.top, rect_client.right, rect_client.bottom, 5, 5 ); else if( m_ndraw_style == GBCTRL_DS_SIMPLE_RECT ) ::Rectangle( hdc, rect_client.left, rect_client.top, rect_client.right, rect_client.bottom ); ::SelectObject( hdc, hold_brush ); ::SelectObject( hdc, hold_pen ); //??? ::DeleteObject( hbrush ); ::DeleteObject( hpen ); } //draw icon if( m_hicon ) ::DrawIconEx( hdc, rect_client.left+rect_client.height()/2-8, rect_client.vcenter()-8, m_hicon, 16, 16, 0, 0, DI_NORMAL ); //draw text _rect rc_text( rect_client ); if( m_nalign == DT_LEFT ) rc_text.left += m_cx_offset; else if( m_nalign == DT_RIGHT ) rc_text.right -= 12; ::SetBkMode( hdc, TRANSPARENT ); ::SetTextColor( hdc, m_color_text ); if( _tcslen( psz_text ) ) { _rect rc_calc( 0, 0, rc_text.width(), 0 ); ::DrawText( hdc, psz_text, -1, &rc_calc, DT_LEFT|DT_CALCRECT ); rc_text.top = rc_text.top + ( rc_text.height() - rc_calc.height() ) / 2; rc_text.bottom = rc_text.top + rc_calc.height(); ::DrawText( hdc, psz_text, -1, &rc_text, m_nalign | m_nvalign ); } ::SelectObject( hdc, hold ); ::EndPaint( handle(), &ps ); return 0; } inline void group_box_ctrl::set_colors( COLORREF color_back, COLORREF color_text ) { m_color_text = color_text; m_color = color_back; } inline void group_box_ctrl::set_draw_style( int nstyle ) { m_ndraw_style = nstyle; } inline void group_box_ctrl::set_text_align( int nalign ) { m_nalign = nalign; } inline void group_box_ctrl::set_text_valign( int nvalign ) { m_nvalign = nvalign; } inline void group_box_ctrl::set_text( HINSTANCE hrc, UINT nID ) { if( m_psz_text ) ::free( m_psz_text ); m_psz_text = 0; char sz[250] = {0}; LoadString( hrc, nID, sz, sizeof( sz ) ); m_psz_text = _tcsdup( sz ); } inline void group_box_ctrl::set_text( char *psz ) { if( m_psz_text ) ::free( m_psz_text ); m_psz_text = 0; m_psz_text = _tcsdup( psz ); } inline void group_box_ctrl::set_icon( HINSTANCE hrc, uint id ) { m_hicon = ::LoadIcon( hrc, MAKEINTRESOURCE( id ) ); }
[ "videotestc@gmail.com" ]
videotestc@gmail.com
f4bbc9f2990c9f50d5285e619702df80cafcb22c
7bee86f3325e6ddf10626e289c8b77a24d7d9eb7
/Assignment_4.cpp
548750850ef15cd9073337e28ce4dc61bc7146d1
[]
no_license
MarilizePi/Foothill_College_CS_2A
0215e9bc7bdc19340b525c350f1677f0791308b9
dffa56dda03674533d50e1697c65e46ff817598d
refs/heads/master
2020-05-29T11:24:55.662170
2019-06-20T01:15:48
2019-06-20T01:15:48
189,113,233
0
0
null
null
null
null
UTF-8
C++
false
false
5,498
cpp
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { int initial_stamps = 0; int final_stamps = 0; const int FREE_YOGURT = 10; int userInputInt; string userInputStr; char userInputChar; bool quit; quit = false; while (!quit) { cout << "Menu: " << endl; cout << "P (process Purchase)" << endl; cout << "S (Shut down)" << endl << endl; cout << "Your choice: "; getline(cin, userInputStr); userInputChar = userInputStr[0]; if (toupper(userInputChar) == 'P') { cout << "\n" << "How many yogurts would you like to buy? "; getline(cin, userInputStr); istringstream(userInputStr) >> userInputInt; initial_stamps = userInputInt; final_stamps += userInputInt; cout << "\n" << "You just earned " << initial_stamps << " stamps and have a total of " << final_stamps << " stamps to use." << endl << endl; if (final_stamps >= FREE_YOGURT) { cout << "You qualify for a free yogurt. "; cout << "Would you like to use your credits ? (Y or N) "; getline(cin, userInputStr); userInputChar = userInputStr[0]; if (toupper(userInputChar) == 'Y') { final_stamps -= FREE_YOGURT; cout << "\n" << "Enjoy your yogurt!" << endl; cout << "You now have " << final_stamps << " stamps." << endl << endl; } /* Since I didn't know (yet) how to return to the specific loop, I decided to repeate some lines of code.*/ else { if (toupper(userInputChar) == 'N') { cout << "\n" << "How many yogurts would you like to buy? "; getline(cin, userInputStr); istringstream(userInputStr) >> userInputInt; initial_stamps = userInputInt; final_stamps += userInputInt; cout << "\n" << "You just earned " << initial_stamps << " stamps and have a total of " << final_stamps << " stamps to use." << endl << endl; } } } } else if (toupper(userInputChar) == 'S') { cout << "See you next time!" << endl; quit = true; } else { if (toupper(userInputChar) != 'P' || toupper(userInputChar) != 'S') { cout << "*** Use P or S, please. ***" << endl << endl; continue; } } } return 0; } /*------------------- Run 1--------------------- Menu: P (process Purchase) S (Shut down) Your choice: p How many yogurts would you like to buy? 7 You just earned 7 stamps and have a total of 7 stamps to use. Menu: P (process Purchase) S (Shut down) Your choice: purchase How many yogurts would you like to buy? 7 You just earned 7 stamps and have a total of 14 stamps to use. You qualify for a free yogurt. Would you like to use your credits ? (Y or N) y Enjoy your yogurt! You now have 4 stamps. Menu: P (process Purchase) S (Shut down) Your choice: puppy How many yogurts would you like to buy? 8 You just earned 8 stamps and have a total of 12 stamps to use. You qualify for a free yogurt. Would you like to use your credits ? (Y or N) yes Enjoy your yogurt! You now have 2 stamps. Menu: P (process Purchase) S (Shut down) Your choice: shut See you next time! Press any key to continue . . . ------------------- Run 2--------------------- Menu: P (process Purchase) S (Shut down) Your choice: pp How many yogurts would you like to buy? 5 You just earned 5 stamps and have a total of 5 stamps to use. Menu: P (process Purchase) S (Shut down) Your choice: t *** Use P or S, please. *** Menu: P (process Purchase) S (Shut down) Your choice: 9 *** Use P or S, please. *** Menu: P (process Purchase) S (Shut down) Your choice: . *** Use P or S, please. *** Menu: P (process Purchase) S (Shut down) Your choice: p How many yogurts would you like to buy? 9 You just earned 9 stamps and have a total of 14 stamps to use. You qualify for a free yogurt. Would you like to use your credits ? (Y or N) n How many yogurts would you like to buy? 3 You just earned 3 stamps and have a total of 17 stamps to use. Menu: P (process Purchase) S (Shut down) Your choice: p How many yogurts would you like to buy? 0 You just earned 0 stamps and have a total of 17 stamps to use. You qualify for a free yogurt. Would you like to use your credits ? (Y or N) nope How many yogurts would you like to buy? 1 You just earned 1 stamps and have a total of 18 stamps to use. Menu: P (process Purchase) S (Shut down) Your choice: p How many yogurts would you like to buy? 10 You just earned 10 stamps and have a total of 28 stamps to use. You qualify for a free yogurt. Would you like to use your credits ? (Y or N) y Enjoy your yogurt! You now have 18 stamps. Menu: P (process Purchase) S (Shut down) Your choice: p How many yogurts would you like to buy? 0 You just earned 0 stamps and have a total of 18 stamps to use. You qualify for a free yogurt. Would you like to use your credits ? (Y or N) y Enjoy your yogurt! You now have 8 stamps. Menu: P (process Purchase) S (Shut down) Your choice: s See you next time! Press any key to continue . . . ---------------------------------------------*/
[ "marilizepi@gmail.com" ]
marilizepi@gmail.com
bd408c423cc003906786a0520eedc22cb08f582d
41e107a91f6307d3c78b211ff12afddc832d5926
/ugine/src/ugine/layer_stack.cc
3999e24702dab2add8ee6c50675acf885981f365
[ "Apache-2.0" ]
permissive
AdrianOrcik/ugine
8e5bb43f0d9e32ff9be82389649728d5815221e9
4f5a9a5641c834834d9e18fc5b85b55140544568
refs/heads/master
2022-11-05T08:22:29.090685
2020-06-20T19:54:57
2020-06-20T19:54:57
245,837,032
0
0
null
null
null
null
UTF-8
C++
false
false
734
cc
#include "uepch.h" #include "layer_stack.h" namespace Ugine { LayerStack::LayerStack() { } LayerStack::~LayerStack() { for (Layer* layer : layers_) delete layer; } void LayerStack::PushLayer(Layer* layer) { layers_.emplace(layers_.begin() + layerIndex_, layer); layerIndex_++; } void LayerStack::PushOverlay(Layer* overlay) { layers_.push_back(overlay); } void LayerStack::PopLayer(Layer* layer) { auto it = std::find(layers_.begin(), layers_.end(), layer); if (it != layers_.end()) { layers_.erase(it); layerIndex_--; } } void LayerStack::PopOverlay(Layer* overlay) { auto it = std::find(layers_.begin(), layers_.end(), overlay); if (it != layers_.end()) layers_.erase(it); } }
[ "adrian.orcik@gmail.com" ]
adrian.orcik@gmail.com
c1cae12fb9c68557d7e2802793581eaec924fc37
523badc1b9f85de3d37c2cfa092dc24cbb3a0e08
/bus_mgr_lib_prj/bus_mgr.h
876f6ed095c2d753e17100324886b2239dd49ee9
[]
no_license
yiliangwu880/libevent_prj
2b3f222043c91cd623143ab6331aba2d657d5dc4
48badafc0bf2b9f97d64b848877dbe8da37ef67d
refs/heads/master
2021-05-05T03:11:10.936226
2019-07-13T07:35:32
2019-07-13T07:35:32
119,790,929
0
0
null
null
null
null
GB18030
C++
false
false
1,460
h
/* author: yiliang.wu 功能:busmgr 管理进程和进程之间的连接, mgr 和 p必须同一台机器 */ #pragma once #include "include_all.h" #include <map> #include "channel.h" #include "utility/misc.h" #include <memory.h> #include "bus_typedef.h" //mc = mgr connector, p 通过socket连接mgr, 在mgr进程的connector class MgrConnector : public ListenerConnector { public: template<class ResMsg> bool Send(const ResMsg &res) { MsgPack pack; memcpy(pack.data, &res, sizeof(res)); pack.len = sizeof(res); return send_data(pack); } template<class ResMsg> bool SendError(ResMsg &res, const std::string &msg, uint16 error_code = 1) { res.error_code = error_code; memcpy(res.error_msg, msg.c_str(), msg.length() + 1); MsgPack pack; memcpy(pack.data, &res, sizeof(res)); pack.len = sizeof(res); return send_data(pack); } private: virtual void OnRecv(const MsgPack &msg) override; virtual void OnConnected() override; virtual void onDisconnected(); private: }; //检查outer channel 读写定时器 class CheckOuterChannelTimer : public BaseLeTimer { private: virtual void OnTimer(void *user_data) override; }; //bus mgr总管理器,一切从这里出发 class BusMgr { public: static BusMgr &Instance() { static BusMgr d; return d; } bool Init(unsigned short listen_port); void Run(); MgrConnector *FindMc(uint64 mc_id); private: Listener<MgrConnector> m_listener; CheckOuterChannelTimer m_timer; };
[ "30390012@qq.com" ]
30390012@qq.com
58b01478c0e31ebd795d6a5a0d8949f083c0aec8
2367e655305a00dd84f7aa0b1fa18501d2511c52
/KwSing_iphone/.svn/pristine/d3/d3a472400b52025f46f6be7c547a68a220052a9d.svn-base
080df86e0dda17b482aef69912d2a5f3fba3da68
[]
no_license
XClouded/dev_project
a165e7a313d182ed5f90e8dcef0e167dce1f6307
c938277aaf73992923e6d6d1ededd8ef3629a38f
refs/heads/master
2021-01-22T17:03:32.375508
2014-11-26T08:23:37
2014-11-26T08:23:37
null
0
0
null
null
null
null
GB18030
C++
false
false
654
/*********************************************************************************************************** File: preamp.h Desc: 用于放大16 bit wav信号的类PreAmp的定义文件,可以把wav信号按照要求的db数进行放大和缩小 Author: Wang Lei Date: May, 2008 ***********************************************************************************************************/ #ifndef PREAMP_H #define PREAMP_H class PreAmp { public: PreAmp(); ~PreAmp(); bool process(void * pWav, int nLen, int nDB); static const unsigned long table_size = 65536; private: void make_table(float ratio); signed short * m_table; int m_db; }; #endif
[ "wangmingjob@gmail.com" ]
wangmingjob@gmail.com
8e2ed737193dc1c910276ec40b59d15828014542
63c71060f36866bca4ac27304cef6d5755fdc35c
/src/TransServer/Torturer/main.cpp
53e83d14d3c229f77caade5c58056868f61cde4b
[]
no_license
15831944/barry_dev
bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a
d4a83421458aa28ca293caa7a5567433e9358596
refs/heads/master
2022-03-24T07:00:26.810732
2015-12-22T07:19:58
2015-12-22T07:19:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,696
cpp
//////////////////////////////////////////////////////////////////////////// // // 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 // // Description: // This file is automatically generated by the TorturerGen facility. // // Modification History: // 06/08/2011: Created by Ketty //////////////////////////////////////////////////////////////////////////// #include "AppMgr/App.h" #include "Debug/Debug.h" #include "Porting/Sleep.h" #include "XmlUtil/XmlTag.h" #include "TransClient/Tester/main.cpp" #include "TransServer/Tester/main.cpp" #include "TransServer/Torturer/TransCheck.h" #include "Util/OmnNew.h" #include "util2/global_data.h" #include <sys/types.h> #include <signal.h> #include <sys/wait.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> using namespace std; union semun { int val; struct semid_ds *buf; unsigned short *arry; }; int gAosLogLevel = 5; char *firstAddr = 0; char *triesAddr = 0; char *clientSyncAddr = 0; char *serverSyncAddr = 0; int firstAddrSize = 0; int syncAddrSize = 0; int semidTries; int semidClient; int semidServer; int semidKillClient; int semidKillServer; int semaphoreP(int semid); int semaphoreV(int semid); int cltSendConnNum = 5; // change by config int shareMemConnSize = 0; u32 totalTransNum = 2000000; int clientMain(int, char**); int serverMain(int, char**); void testStart(int child_client_pid, int child_server_pid, int argc, char **argv); int redirectOutPut(bool server); void getSmareMemory(int size, const char* fn, char ** addr); void semaphore(const char* fn, int &semid); int status; // totalNransNum ---(need)--- firstAddrSize // 4096000 ---(need)--- 4096 * 2000 // 2048000 ---(need)--- 4096 * 1000 int main(int argc, char **argv) { signal(SIGUSR1, AosTransCheckGetSignal); signal(SIGUSR2, AosTransCheckGetSignal); int child_client_pid; int child_server_pid; const char *cmd = "rm /home/ice/AOS/src/TransClient/Tester/Data/* /home/ice/AOS/src/TransServer/Tester/Data/* server_* client_*"; system(cmd); cout << "-------------------Parent ID:\t" << getpid() << " -------------" << endl; // get share memory. int size = getpagesize(); cout << "------ getpagesize():" << size << endl; firstAddrSize = size * 1000; // can change. if(totalTransNum * 2 > (int)firstAddrSize) { cout << "--------- share memory is too small!" << endl; return 0; } syncAddrSize = firstAddrSize * 2; getSmareMemory(firstAddrSize, "a", &firstAddr); getSmareMemory(size, "b", &triesAddr); getSmareMemory(syncAddrSize, "c", &clientSyncAddr); getSmareMemory(syncAddrSize, "d", &serverSyncAddr); shareMemConnSize = syncAddrSize/cltSendConnNum; cout << "firstAddr:" << (int)firstAddr << "; triesAddr:" << (int)triesAddr << "; clientSyncAddr:" << (int)clientSyncAddr << "; serverSyncAddr:" << (int)serverSyncAddr << endl; semaphore("e", semidTries); semaphore("f", semidClient); semaphore("g", semidServer); semaphore("h", semidKillClient); semaphore("i", semidKillServer); // start client ans server. if ((child_server_pid=fork())== 0) { cout << "----------------init start server:\t" << getpid() << " -----------" << endl; redirectOutPut(true); serverMain(argc, argv); } else { if ((child_client_pid=fork())== 0) { cout << "---------------init start client: \t" << getpid() << " --------" << endl; redirectOutPut(false); clientMain(argc, argv); } else { //testStart(child_client_pid, child_server_pid, argc, argv); } } while(1) { wait(&status); OmnSleep(200); } return 0; } void getSmareMemory(int size, const char* fn, char ** addr) { int shmid; key_t key = ftok(fn, 0); struct shmid_ds dsbuf; if( (shmid=shmget(key, size, 0664|IPC_CREAT)) < 0 ) { perror("share memery allocate error!"); exit(1); } shmctl(shmid, IPC_STAT, &dsbuf); *addr = (char*)shmat(shmid, NULL, 0); if((int)*addr == -1) { perror("share memery load error!"); exit(1); } memset(*addr, 0, size); } void semaphore(const char* fn, int &semid) { //semaphore key_t key = ftok(fn, 0); if( (semid=semget(key, 1, 0664|IPC_CREAT)) < 0) { perror("semaphore init error!"); exit(1); } union semun arg; arg.val= 1; if (semctl(semid, 0, SETVAL, arg) < 0 ) { perror("semaphore reset error!"); exit(1); } } void testStart(int child_client_pid, int child_server_pid, int argc, char **argv) { bool killedClient = false; bool killedServer = false; //int num = 30; //int add = 10; while(1) { int time = rand() % 60 + 20; //int time = rand() % num + 20; //num = num + add; //add = add + 5; cout << "..........................." << "parent sleep:" << time << ",to kill Server or client" << "..........................." << endl; OmnSleep(time); int aa = rand() & 0x0001; //int aa = 0; if ( aa == 1 && !killedClient) { cout << ">>>>>>>>------>>>>>>>>--------killclient:\t" << child_client_pid << "(" << getpid() << ")" << "------<<<<<<<<<<-----------<<<<<<<<" << endl; //cout << "want kill client lock1" << endl; semaphoreP(semidKillClient); kill(child_client_pid, 9); //cout << "kill client lock1" << endl; semaphoreV(semidKillClient); //cout << "kill client unlock1" << endl; wait(&status); killedClient = true; //The possibility of 10 percent to kill server /* if((rand()%100) < 10 && !killedServer) { cout << ">>>>>>>>>------->>>>>>>>--------killserver(after kill client):\t" << child_server_pid << "(" << getpid() << ")" << "-----------<<<<<<<<-------------<<<<<<<" << endl; cout << "want kill server lock1" << endl; semaphoreP(semidKillServer); kill(child_server_pid, 9); cout << "kill server lock1" << endl; semaphoreV(semidKillServer); cout << "kill server unlock1" << endl; wait(&status); killedServer = true; } */ } else if(!killedServer) { cout << ">>>>>>>>--------->>>>>>>>>-------killserver:\t" << child_server_pid << "(" << getpid() << ")" << "----------<<<<<<<<<<----------<<<<<<<<" << endl; //cout << "want kill server lock2" << endl; semaphoreP(semidKillServer); //cout << "kill server lock2" << endl; kill(child_server_pid, 9); semaphoreV(semidKillServer); //cout << "kill server unlock2" << endl; wait(&status); killedServer = true; //The possibility of 10 percent to kill client /* if((rand()%100) < 10 && !killedClient) { cout << ">>>>>>>>>>---------->>>>>>>>>>>>>>---------killclient(after kill server):\t" << child_client_pid << "(" << getpid() << ")" << "----------------<<<<<<<<<<<<<<<<<<--------------------<<<<<<<<<<<<" << endl; cout << "want kill client lock2" << endl; semaphoreP(semidKillClient); cout << "kill client lock2" << endl; kill(child_client_pid, 9); semaphoreV(semidKillClient); cout << "kill client unlock2" << endl; wait(&status); killedClient = true; } */ } if(killedClient) { if ((child_client_pid=fork())== 0) { OmnSleep(rand()% 10); cout << "-----*********------*********--------start client: " << getpid() << " -----********-------********" << endl; redirectOutPut(false); clientMain(argc, argv); } killedClient = false; } if(killedServer) { if ((child_server_pid=fork())== 0) { OmnSleep(rand()% 10); cout << "-----*******-----********----------start server: " << getpid() << " ----------****-----*********" << endl; redirectOutPut(true); serverMain(argc, argv); } killedServer = false; } } } int redirectOutPut(bool server) { //return 0; close(STDOUT_FILENO); OmnString filename; if (server) { filename = "server_"; } else { filename = "client_"; } filename << getpid(); int fd = open(filename.data(), O_RDWR|O_CREAT, S_IREAD | S_IWRITE); int fd2 = dup2(fd, STDOUT_FILENO); if (fd != fd2) { close(fd); } return 0; } int semaphoreV(int semid) { //cout << "v" << (int)pthread_self()<<endl; struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = 1; sem_b.sem_flg = SEM_UNDO; if (semop(semid, &sem_b, 1) == -1) { perror("opr v error!"); return -1; } return 0; } int semaphoreP(int semid) { //cout << "p" << (int)pthread_self()<<endl; struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; sem_b.sem_flg = SEM_UNDO; if (semop(semid, &sem_b, 1) == -1) { perror("opr p error!"); return -1; } return 0; }
[ "barryniu@jimodb.com" ]
barryniu@jimodb.com
1a37cc63b1eea59e35f2bd9f8d80c9380ea5fa3b
8a431e5d895785ef0e81037485e8d53d2dba8083
/1-intro/fibonacci_last_digit/fibonacci_last_digit.cpp
1b0a0650eab4824cc5bbd3f066219600ba2db378
[]
no_license
reazh/algo-toolbox
a94128dfbe5165f5f5c5f76ef3722d15aa511bd6
7e4e73f223d944e0b95f6a13ad459d588abeda6d
refs/heads/master
2021-05-31T07:40:04.424761
2016-05-23T03:34:58
2016-05-23T03:34:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
#include <iostream> int get_fibonacci_last_digit(int n) { //write your code here return 0; } int main() { int n; std::cin >> n; int c = get_fibonacci_last_digit(n); std::cout << c << '\n'; }
[ "rhasan@gmail.com" ]
rhasan@gmail.com
d2b805c5b541da1fe386cbe74ab80c0ddc83bcf6
7d467aac466f3077f0586b18e9f0fc665b5b6868
/example_c/i8086tools/7run/i8086/VM.cpp
4479761c44b1470018dadd4aa21c5ed4300e7129
[ "LicenseRef-scancode-public-domain-disclaimer" ]
permissive
Bo0km4n/rust-disassembler-x86-8086
b443525a59b0024c763954331af1f1dd534dcd4f
64de7149fc036c6d4c21731ba0aa68a4d18ad099
refs/heads/master
2020-04-09T04:44:13.245341
2019-02-27T07:09:10
2019-02-27T07:09:10
160,034,490
0
0
null
null
null
null
UTF-8
C++
false
false
3,988
cpp
#include "VM.h" #include "disasm.h" #include "regs.h" #include <stdio.h> #include <string.h> #include <sys/stat.h> using namespace i8086; const char *i8086::header = " AX BX CX DX SP BP SI DI FLAGS IP\n"; bool VM::ptable[256]; void VM::showHeader() { fprintf(stderr, header); } void VM::debug(uint16_t ip, const OpCode &op) { debugsym(ip); fprintf(stderr, "%04x %04x %04x %04x %04x %04x %04x %04x %c%c%c%c %04x:%-12s %s", r[0], r[3], r[1], r[2], r[4], r[5], r[6], r[7], "-O"[OF], "-S"[SF], "-Z"[ZF], "-C"[CF], ip, hexdump(text + ip, op.len).c_str(), op.str().c_str()); if (trace >= 3) { int ad1 = addr(op.opr1); int ad2 = addr(op.opr2); if (ad1 >= 0) { if (op.opr1.w) fprintf(stderr, " ;[%04x]%04x", ad1, read16(ad1)); else fprintf(stderr, " ;[%04x]%02x", ad1, read8(ad1)); } if (ad2 >= 0) { if (op.opr2.w) fprintf(stderr, " ;[%04x]%04x", ad2, read16(ad2)); else fprintf(stderr, " ;[%04x]%02x", ad2, read8(ad2)); } } fprintf(stderr, "\n"); } static bool initialized; void VM::init() { if (!initialized) { for (int i = 0; i < 256; i++) { int n = 0; for (int j = 1; j < 256; j += j) { if (i & j) n++; } ptable[i] = (n & 1) == 0; } initialized = true; } uint16_t tmp = 0x1234; uint8_t *p = (uint8_t *) r; if (*(uint8_t *) & tmp == 0x34) { for (int i = 0; i < 4; i++) { r8[i] = p + i * 2; r8[i + 4] = r8[i] + 1; } } else { for (int i = 0; i < 4; i++) { r8[i] = p + i * 2 + 1; r8[i + 4] = r8[i] - 1; } } } VM::VM() : IP(0), start_sp(0) { init(); memset(r, 0, sizeof (r)); OF = DF = SF = ZF = AF = PF = CF = false; } VM::VM(const VM &vm) : VMBase(vm) { init(); memcpy(r, vm.r, sizeof (r)); IP = vm.IP; OF = vm.OF; DF = vm.DF; SF = vm.SF; ZF = vm.ZF; AF = vm.AF; PF = vm.PF; CF = vm.CF; start_sp = vm.start_sp; } VM::~VM() { } bool VM::load(const std::string& fn, FILE* f, size_t size) { if (!VMBase::load(fn, f, size)) return false; IP = 0; return true; } int VM::addr(const Operand &opr) { switch (opr.type) { case Ptr: return uint16_t(opr.value); case ModRM + 0: return uint16_t(BX + SI + opr.value); case ModRM + 1: return uint16_t(BX + DI + opr.value); case ModRM + 2: return uint16_t(BP + SI + opr.value); case ModRM + 3: return uint16_t(BP + DI + opr.value); case ModRM + 4: return uint16_t(SI + opr.value); case ModRM + 5: return uint16_t(DI + opr.value); case ModRM + 6: return uint16_t(BP + opr.value); case ModRM + 7: return uint16_t(BX + opr.value); } return -1; } void VM::run2() { while (!hasExited) run1(); } void VM::disasm() { int addr = 0, undef = 0; while (addr < (int) tsize) { showsym(addr); OpCode op = disasm1(text, addr, tsize); disout(text, addr, op.len, disstr(op)); if (op.undef()) undef++; addr += op.len; } if (undef) printf("undefined: %d\n", undef); } std::string VM::disstr(const OpCode &op) { std::string ret = op.str(); if (op.opr1.type == Addr) { std::map<int, Symbol>::iterator it = syms[1].find(op.opr1.value); if (it != syms[1].end()) { ret += " ; " + it->second.name; } } if (op.opr2.type == Addr) { std::map<int, Symbol>::iterator it = syms[1].find(op.opr2.value); if (it != syms[1].end()) { ret += " ; " + it->second.name; } } return ret; }
[ "pokopenkatuya@gmail.com" ]
pokopenkatuya@gmail.com
0bd2be133cb154059838ae94ef136c163f8bd731
cb7ae10692a3692cad7d500cddadfbf7ea4f4a1a
/c/ParticleFilter/sirTest.cpp
be65a3d0f68782bf9e09f96ce4db61b1c7a68fee
[]
no_license
UCSD-SEELab/ContextEngine27
c715b32ab08a94224b289a7e00d8d51d6cfc9e84
754458c919d96a338d010a6eab31bcb93ee73e09
refs/heads/master
2021-06-16T07:16:31.951345
2017-04-27T19:52:07
2017-04-27T19:52:07
62,247,545
1
0
null
null
null
null
UTF-8
C++
false
false
4,330
cpp
// this version runs on rpi or osx #include "smctc.hh" #include "pffuncs.hh" #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <string.h> #include <sys/time.h> using namespace std; typedef unsigned long long timestamp_t; static timestamp_t get_timestamp () { struct timeval now; gettimeofday (&now, NULL); return now.tv_usec + (timestamp_t)now.tv_sec * 1000000; } ///The observations cv_obs * y; long load_data(char const * szName, cv_obs** y); double integrand_mean_y(const cv_state&, void*); double prevY = 0; int sampleIndex =0; // double integrand_mean_y(const cv_state&, void*); // double integrand_var_x(const cv_state&, void*); double integrand_var_y(const cv_state&, void*); int main() { //Assigning number of particles long arg = 100; //Setting up the output file // string fileNameStr = "100data80.csv"; //ofstream outFile; //outFile.open (fileNameStr.c_str()); char fileNameStr[100] = "100data80.csv"; FILE* fp = fopen(fileNameStr, "w"); //Number of iterations. long lIterates = 10; // was argv3 //Assigning number of particles long lNumber = 100; //Load observations load_data("data80.csv", &y); //Initialise and run the sampler smc::sampler<cv_state> Sampler(lNumber, SMC_HISTORY_NONE); smc::moveset<cv_state> Moveset(fInitialise, fMove, NULL); timestamp_t t0 = get_timestamp(); Sampler.SetResampleParams(SMC_RESAMPLE_RESIDUAL, 0.5); timestamp_t t1 = get_timestamp(); // cout << "The Set ResampleParams Ex Time" << (t1 - t0) / 1000000.0L <<endl; t0 = get_timestamp(); Sampler.SetMoveSet(Moveset); t1 = get_timestamp(); // cout << "The Set Move Set Ex Time" << (t1 - t0) / 1000000.0L <<endl; t0 = get_timestamp(); Sampler.Initialise(); t1 = get_timestamp(); //cout << "The Initialise Ex Time" << (t1 - t0) / 1000000.0L <<endl; // Process double aveIter = 0.0; double cur = 0.0; double aveInter = 0.0; for(int n=1 ; n < lIterates ; ++n) { // Iterate moves the particles //Check if ltime is the same as y[lindex].xposition. //So we can update the index after is used on the particles t0 = get_timestamp(); Sampler.Iterate(); t1 = get_timestamp(); cur = ((t1 - t0) / 1000000.0L); // cout << "Iter:" << cur << endl; aveIter += cur; double xm,xv,ym,yv; t0 = get_timestamp(); // xm = Sampler.Integrate(integrand_mean_x,NULL); // xv = Sampler.Integrate(integrand_var_x, (void*)&xm); ym = Sampler.Integrate(integrand_mean_y,NULL); yv = Sampler.Integrate(integrand_var_y, (void*)&ym); // printf("Cur var ym %f, Prev ym: %f\n", ym, prevY); // Checking if we reached a sample //So we can update the index if ((n) == y[sampleIndex].x_pos){ // printf("The sample index in main %d\n", sampleIndex); // printf("n: %d, xpos:%f\n",(n), y[sampleIndex].x_pos); sampleIndex++; } prevY = ym; t1 = get_timestamp(); cur = ((t1 - t0) / 1000000.0L); aveInter += cur; // cout << "Inte:" << (t1 - t0) / 1000000.0L <<"\n " << endl; //cout << "Sample num:"<< n << " "<< ym << ","<< yv << "," << endl; //outFile << n <<","<<ym << "\n"; fprintf(fp, "%d,%.6f\n", n, ym); //cout << ym<< ","; } //outFile.close(); fclose(fp); //cout << "Iter Ave"<< aveIter/lIterates <<endl; //cout << "Itegrate Ave"<< aveInter/lIterates <<endl; } long load_data(char const * szName, cv_obs** yp) { FILE * fObs = fopen(szName,"rt"); char* szBuffer = new char[1024]; fgets(szBuffer, 1024, fObs); long lIterates = strtol(szBuffer, NULL, 10); *yp = new cv_obs[lIterates]; for(long i = 0; i < lIterates; ++i) { fgets(szBuffer, 1024, fObs); (*yp)[i].x_pos = strtod(strtok(szBuffer, ",\r\n "), NULL); (*yp)[i].y_pos = strtod(strtok(NULL, ",\r\n "), NULL); printf("y:%f, x:%f \n", (*yp)[i].y_pos, (*yp)[i].x_pos); } fclose(fObs); printf("%s\n","Done with file" ); delete [] szBuffer; return lIterates; } double integrand_mean_y(const cv_state& s, void *) { return s.y_pos; } double integrand_var_y(const cv_state& s, void* vmy) { double* dmy = (double*)vmy; double d = (s.y_pos - (*dmy)); return d*d; }
[ "csc019@eng.ucsd.edu" ]
csc019@eng.ucsd.edu
fb8c721eb5e2be8f76b0d1292f050eb8e9068281
c397bb468d86f000868fee4fdbe288ceb5994420
/inc/ToGraphvizWriter.h
b9fee989b9e9ded84f71040346fb8463812fc8e3
[ "MIT" ]
permissive
dueringa/WikiWalker
41cc83a43a3d01e4d245ba5d6d2d9a572a8077d2
24a83936efac1e217af949275b0677861c216957
refs/heads/master
2021-01-19T06:27:50.719969
2018-04-19T18:40:03
2018-04-19T18:40:03
87,462,913
0
0
null
null
null
null
UTF-8
C++
false
false
968
h
//! \file ToGraphvizWriter.h #ifndef WIKIWALKER_TOGRAPHVIZWRITER_H #define WIKIWALKER_TOGRAPHVIZWRITER_H #include "DataOutputBase.h" namespace WikiWalker { /*! Writing to a file in dot format */ class ToGraphvizWriter : public DataOutputBase { public: /*! output an article with links in dot format to a stream * \param a reference to article to be output * \param os out stream to putput to * YOU are responsible for opening and closing the stream */ void output(const Article* a, std::ostream& os) override; /*! output an article collection in dot format to a stream * \param ac reference to article collection to be output * \param os out stream to putput to * YOU are responsible for opening and closing the stream */ void output(const CollectionUtils::ArticleCollection& ac, std::ostream& os) override; }; } // namespace WikiWalker #endif // WIKIWALKER_TOGRAPHVIZWRITER_H
[ "github@duering-andreas.de" ]
github@duering-andreas.de
c193f22a931ea47419701613cab4d429c7041f5e
ed649693468835126ae0bc56a9a9745cbbe02750
/alljoyn_core/router/winrt/proximity/ProximityListener.h
cb33346d2da5015cac38ee08c1ca3431591cdd26
[]
no_license
tkellogg/alljoyn-core
982304d78da73f07f888c7cbd56731342585d9a5
931ed98b3f5e5dbd40ffb529a78825f28cc59037
refs/heads/master
2020-12-25T18:22:32.166135
2014-07-17T13:56:18
2014-07-17T13:58:56
21,984,205
2
1
null
null
null
null
UTF-8
C++
false
false
1,275
h
/** * @file * ProximityListener is to notify status changes of the proximity connection. */ /****************************************************************************** * Copyright (c) 2012, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or 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. ******************************************************************************/ #ifndef _PROXIMITY_LISTENER_H #define _PROXIMITY_LISTENER_H namespace ajn { class ProximityListener { public: virtual void OnProximityDisconnected() = 0; }; } // namespace ajn #endif
[ "gerritadmin@allseenalliance.org" ]
gerritadmin@allseenalliance.org
5746890ba09a04eb0e49fe2c4a82a909efa018e9
5775eb2150996990318bec38c79d59dfa2c562bc
/sprout/compost/formats/as_imag.hpp
b2b698005ec5b8f0eab392d84e1fc45ef9b02f22
[ "BSL-1.0" ]
permissive
horance-liu/Sprout
6e1e396db9e27fbc83da41270c96412cced5a767
8274f34db498b02bff12277bac5416ea72e018cd
refs/heads/master
2020-04-05T14:47:12.706952
2018-05-29T14:09:43
2018-05-29T14:09:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,814
hpp
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_COMPOST_FORMATS_AS_IMAG_HPP #define SPROUT_COMPOST_FORMATS_AS_IMAG_HPP #include <utility> #include <sprout/config.hpp> #include <sprout/complex.hpp> #include <sprout/utility/forward.hpp> #include <sprout/range/adaptor/transformed.hpp> namespace sprout { namespace compost { // // to_imag_value // struct to_imag_value { public: template<typename Complex> SPROUT_CONSTEXPR decltype(imag(std::declval<Complex const&>())) operator()(Complex const& x) const { return imag(x); } }; namespace formats { // // as_imag_forwarder // class as_imag_forwarder {}; // // as_imag // namespace { SPROUT_STATIC_CONSTEXPR sprout::compost::formats::as_imag_forwarder as_imag = {}; } // anonymous-namespace // // operator| // template<typename Range> inline SPROUT_CONSTEXPR auto operator|(Range&& lhs, sprout::compost::formats::as_imag_forwarder const&) -> decltype( SPROUT_FORWARD(Range, lhs) | sprout::adaptors::transformed(sprout::compost::to_imag_value()) ) { return SPROUT_FORWARD(Range, lhs) | sprout::adaptors::transformed(sprout::compost::to_imag_value()) ; } } // namespace formats using sprout::compost::formats::as_imag; } // namespace compost } // namespace sprout #endif // #ifndef SPROUT_COMPOST_FORMATS_AS_IMAG_HPP
[ "bolero.murakami@gmail.com" ]
bolero.murakami@gmail.com
50c99ec7e4f4a8c72c92ed7c397ccfa6669635e9
ab1712d65f8510a705a1f28064e4d3fc5a48cf64
/SDK/SoT_BP_Island_Bell_classes.hpp
efbe33ec53adab37c2798027939c2f061fce1ff8
[]
no_license
zk2013/SoT-SDK
577f4e26ba969c3fa21a9191a210afc116a11dba
04eb22c1c31aaa4d5cf822b0a816786c99e3ea2f
refs/heads/master
2020-05-29T20:06:57.165354
2019-05-29T16:46:51
2019-05-29T16:46:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
671
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_Island_Bell_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_Island_Bell.BP_Island_Bell_C // 0x0000 (0x0640 - 0x0640) class ABP_Island_Bell_C : public ABell { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_Island_Bell.BP_Island_Bell_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
d59f1fb42f19dbb4fb8538f4db26c4dd227cb718
34488d45dbf546ff1e804452c250fc885e7e13fb
/practices/cpp/level1/p03_SafeArray/safeArray.cpp
48129f3f90a210a7de6defa61e653497ba2309e9
[]
no_license
mufengjun260/CCpp2016
cc58bb2ff3d25be53ea74e752ef8200d1d7ab10a
c23b80e079f95980bc76923f0f2a6b235bd93f59
refs/heads/master
2020-12-25T16:47:37.350747
2016-05-03T15:19:33
2016-05-03T15:19:33
52,486,087
0
0
null
2016-02-25T01:03:12
2016-02-25T01:03:12
null
UTF-8
C++
false
false
467
cpp
#include "safeArray.h" #include <iostream> using namespace std; SafeArray::SafeArray(int cap) { data = new int[cap]; size = cap; } int SafeArray::get(int location) { if (location > size) { std::cout << "outOfSize!!!" << std::endl; } else { return data[location]; } } void SafeArray::set(int location, int num) { if (location > size) { std::cout << "outOfSize!!!" << std::endl; return; } else { data[location] = num; } }
[ "穆逢君" ]
穆逢君
a0cfdbd885ff700f32a744e07d2bab2b63d368a4
844969bd953d7300f02172c867725e27b518c08e
/SDK/ShantyCategory_functions.cpp
4a4a004535e141155449eeed76ec1b6f53ce3138
[]
no_license
zanzo420/SoT-Python-Offset-Finder
70037c37991a2df53fa671e3c8ce12c45fbf75a5
d881877da08b5c5beaaca140f0ab768223b75d4d
refs/heads/main
2023-07-18T17:25:01.596284
2021-09-09T12:31:51
2021-09-09T12:31:51
380,604,174
0
0
null
2021-06-26T22:07:04
2021-06-26T22:07:03
null
UTF-8
C++
false
false
544
cpp
// Name: SoT, Version: 2.2.1.1 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void UShantyCategory_C::AfterRead() { UShantyCategory::AfterRead(); } void UShantyCategory_C::BeforeDelete() { UShantyCategory::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "51171051+DougTheDruid@users.noreply.github.com" ]
51171051+DougTheDruid@users.noreply.github.com
2fa072836a1ca64e67e0cbf4aeca487c507a8c27
55de3adb94c4dab6bd9cc6f7dabc34c614841d15
/Day1/SocialNetwork(easy).cpp
1554fcfaa6a9af5c524f7a7e740b0eb662c2ce27
[]
no_license
Jyotishman-Ghatak/Daily-Competitive-Coding
ad4f8615b0e8c788ba28a9ef4d60fe8766b2b079
5dcbf11d056d0d9975657764ce9066dc50b38dcf
refs/heads/master
2023-01-19T03:25:02.187543
2020-11-27T20:49:40
2020-11-27T20:49:40
315,717,771
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ vector <int> a; long long n,k,p; cin>>n>>k; for(long long i=0;i<n;i++){ cin>>p; if(find(a.begin(),a.end(),p)==a.end()){ if(int(a.size())>=k){ a.pop_back(); } a.insert(a.begin(),p); } } cout<<a.size()<<endl; for(long long i=0;i<a.size();i++){ cout<<a[i]<<" "; } }
[ "jyotish.tubai@gmail.com" ]
jyotish.tubai@gmail.com
3097dabf4a6ca51d041366d731bebba599129559
c912675c40e232e4a12cd94410e062477ea163b4
/football.cpp
2ad71cfa1ef862c2201e87724a1541a61fac7f8a
[]
no_license
Abhishek183/codeforces-solutions
9cb152f9263e8fa301dde545869c03be5287e018
6657247ae77bd4f1960cec112865aed658af21a8
refs/heads/master
2022-07-08T16:19:51.625271
2020-05-14T20:13:28
2020-05-14T20:13:28
264,010,955
1
0
null
null
null
null
UTF-8
C++
false
false
394
cpp
#include<iostream> using namespace std; #include<string> #include<algorithm> #include<unordered_map> #define ll long long int main() { ll int n; cin>>n; pair<int,string>s[n]; for(ll int i=0;i<n;i++) { s[i].first=0; cin>>s[i].second; for(ll int j=0;j<i;j++) { if(s[j].second==s[i].second) {s[j].first++; break;} } } sort(s,s+n); cout<<s[n-1].second; }
[ "mishra.mr97@gmail.com" ]
mishra.mr97@gmail.com
bc0fb9bbfd516fc6834469853e0a3dffc636198b
9f48878caa37ac5f2ccf938fc476efa47c89c644
/tests/Unit/PointwiseFunctions/AnalyticData/Test_AnalyticData.cpp
e600ed6da48de0ff37875ba9bf6b2c0824e5fdd2
[ "MIT" ]
permissive
sxs-collaboration/spectre
34f7733ab4c75dbca2f432028145fed110c9ef24
96f573cf158201f712da2bfb3378edf497a35a0d
refs/heads/develop
2023-08-19T11:18:18.465609
2023-08-19T04:24:25
2023-08-19T04:24:25
87,570,510
149
190
NOASSERTION
2023-09-14T20:10:35
2017-04-07T17:28:20
C++
UTF-8
C++
false
false
901
cpp
// Distributed under the MIT License. // See LICENSE.txt for details. #include "PointwiseFunctions/AnalyticData/AnalyticData.hpp" #include "PointwiseFunctions/AnalyticSolutions/AnalyticSolution.hpp" namespace { struct AnalyticData : public MarkAsAnalyticData {}; struct Solution : public MarkAsAnalyticSolution {}; struct SolutionDependentAnalyticData : public MarkAsAnalyticData, private Solution {}; static_assert(is_analytic_data_v<AnalyticData>, "Failed testing is_analytic_data_v"); static_assert(is_analytic_data_v<SolutionDependentAnalyticData>, "Failed testing is_analytic_data_v"); static_assert(is_analytic_data<AnalyticData>::value, "Failed testing is_analytic_data"); static_assert(is_analytic_data<SolutionDependentAnalyticData>::value, "Failed testing is_analytic_data"); } // namespace
[ "nils@nilsdeppe.com" ]
nils@nilsdeppe.com
beeb3f5f2cd104cd4be716de52e61b8398aad435
81d1c11616c321a3aeae92b588f0ba59c635080d
/walk_hls/hlsinput.h
6e190e844658dc192b37bce1674a2a9754708fb5
[]
no_license
porjo/libdvbtee
818aef46de6b7569f1f02e125466c449367f57c6
0e6b6cdda4786f075605567f34e757efe8898410
refs/heads/master
2021-01-14T08:55:04.075039
2014-02-06T04:55:38
2014-02-06T04:55:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
h
/***************************************************************************** * Copyright (C) 2013 Michael Krufky * * Author: Michael Krufky <mkrufky@linuxtv.org> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 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 * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef HLSINPUT_H #define HLSINPUT_H #include "feed.h" class hlsinput { public: explicit hlsinput(bool feed_stdout = false); bool get(const char *url); private: bool b_stdout; feed feeder; static void write_feed(void *context, void *buffer, size_t size, size_t nmemb); }; #endif // HLSINPUT_H
[ "mkrufky@linuxtv.org" ]
mkrufky@linuxtv.org
7a76386f74dcfcdaf286cc6ad4e901bcc04b977a
bc756e3b8bd50bc0439f9df71092264eb63cb414
/src/ransac/ransacutility.cpp
a22008f9881461bfc2dde380228abe62161e8935
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
akhtarjunaid/fbench
3af9cf449b591f115b68d9ab383aab93af88f9ae
0e21704f9e4dd3440b03ee913e058ee3916086f2
refs/heads/master
2023-03-15T17:54:57.582839
2020-11-14T16:08:46
2020-11-14T16:08:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,456
cpp
/* * Copyright (c) 2016 University of Cordoba and University of Illinois * All rights reserved. * * Developed by: IMPACT Research Group * University of Cordoba and University of Illinois * http://impact.crhc.illinois.edu/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * with 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: * * > Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimers. * > Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimers in the * documentation and/or other materials provided with the distribution. * > Neither the names of IMPACT Research Group, University of Cordoba, * University of Illinois nor the names of its contributors may be used * to endorse or promote products derived from this Software without * specific prior written permission. * * 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 * CONTRIBUTORS 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 WITH * THE SOFTWARE. * * * Modifiers: Jennifer Faj * Modifications: - Adjustments in file reading and random number generation, * - added additional model (linear function) * Date: 2020/06/21 * */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <iostream> #include "ransacutility.h" using namespace std; int readInputSize(string fileName) { FILE *File = NULL; File = fopen(fileName.c_str(), "r"); if(File == NULL) { puts("Error opening the file"); exit(-1); } int n; fscanf(File, "%d", &n); fclose(File); return n; } void readInputData(flowvector *v, string fileName) { int ic = 0; // Open input file FILE *File = NULL; File = fopen(fileName.c_str(), "r"); if(File == NULL) { puts("Error opening file!"); exit(-1); } int n; fscanf(File, "%d", &n); while(fscanf(File, "%d,%d,%d,%d", &v[ic].x, &v[ic].y, &v[ic].vx, &v[ic].vy) == 4) { ic++; if(ic > n) { puts("Error: inconsistent file data!"); exit(-1); } } if(ic < n) { puts("Error: inconsistent file data!"); exit(-1); } } void readInputData(point *p, string fileName) { int ic = 0; // Open input file FILE *File = NULL; File = fopen(fileName.c_str(), "r"); if(File == NULL) { puts("Error opening file!"); exit(-1); } int n; fscanf(File, "%d", &n); while(fscanf(File, "%f,%f", &p[ic].x, &p[ic].y) == 2) { ic++; if(ic > n) { puts("Error: inconsistent file data!"); exit(-1); } } if(ic < n) { puts("Error: inconsistent file data!"); exit(-1); } } void genRandNumbers(int *r, int maxIter, int n){ srand(time(NULL)); for(int i = 0; i < 2 * maxIter; i++) { r[i] = ((int)rand()) % n; } } inline int compare_output(int count1, int count2, int outliers1, int outliers2) { if(count1 != count2) { printf("Test failed\n"); exit(EXIT_FAILURE); } if(outliers1 != outliers2) { printf("Test failed\n"); exit(EXIT_FAILURE); } return 0; } // Sequential implementation for comparison purposes // Function to compute new set of motion vectors based on the first order flow model inline void gen_firstOrderFlow_vectors( float *model_param, int flow_vector_count, flowvector *flow_vector_array, flowvector *ego_vector_array) { float temp_x, temp_y; // Compute new set of motion vectors for each point specified in the flow_vector_array for(int i = 0; i < flow_vector_count; i++) { temp_x = ((float)(flow_vector_array[i].x)) - model_param[0]; temp_y = ((float)(flow_vector_array[i].y)) - model_param[1]; ego_vector_array[i].x = flow_vector_array[i].x; ego_vector_array[i].y = flow_vector_array[i].y; ego_vector_array[i].vx = flow_vector_array[i].x + ((temp_x * model_param[2]) - (temp_y * model_param[3])); ego_vector_array[i].vy = flow_vector_array[i].y + ((temp_y * model_param[2]) + (temp_x * model_param[3])); } } // Compare to better model inline void choose_better_model(flowvector *flow_vector_array, flowvector *ego_vector_array, int flow_vector_count, float *model_param, int *model_candidate, int *outliers_candidate, int *count_candidates, int error_threshold, float convergence_threshold, int iter) { int outlier_count = 0; int vx1, vy1; float vx_error, vy_error; // This loop calculates the no of outliers for(int i = 0; i < flow_vector_count; i++) { vx1 = flow_vector_array[i].vx - flow_vector_array[i].x; vy1 = flow_vector_array[i].vy - flow_vector_array[i].y; vx_error = flow_vector_array[i].x + ((int)((flow_vector_array[i].x - model_param[0]) * model_param[2]) - (int)((flow_vector_array[i].y - model_param[1]) * model_param[3])) - flow_vector_array[i].vx; vy_error = flow_vector_array[i].y + ((int)((flow_vector_array[i].y - model_param[1]) * model_param[2]) + (int)((flow_vector_array[i].x - model_param[0]) * model_param[3])) - flow_vector_array[i].vy; if((fabs(vx_error) < error_threshold) && (fabs(vy_error) < error_threshold)) { ego_vector_array[i].x = 0; ego_vector_array[i].y = 0; ego_vector_array[i].vx = 0; ego_vector_array[i].vy = 0; } else { outlier_count++; ego_vector_array[i].vx = ego_vector_array[i].x + vx_error; ego_vector_array[i].vy = ego_vector_array[i].y + vy_error; } } // Compare to threshold if(outlier_count < flow_vector_count * convergence_threshold) { int ind = count_candidates[0]++; model_candidate[ind] = iter; outliers_candidate[ind] = outlier_count; } } // Function to generate model parameters for first order flow (xc, yc, D and R) inline int gen_model_param(int x1, int y1, int vx1, int vy1, int x2, int y2, int vx2, int vy2, float *model_param) { float temp; // xc -> model_param[0], yc -> model_param[1], D -> model_param[2], R -> model_param[3] temp = (float)((vx1 * (vx1 - (2 * vx2))) + (vx2 * vx2) + (vy1 * vy1) - (vy2 * ((2 * vy1) - vy2))); if(temp == 0) { // Check to prevent division by zero return (0); } model_param[0] = (((vx1 * ((-vx2 * x1) + (vx1 * x2) - (vx2 * x2) + (vy2 * y1) - (vy2 * y2))) + (vy1 * ((-vy2 * x1) + (vy1 * x2) - (vy2 * x2) - (vx2 * y1) + (vx2 * y2))) + (x1 * ((vy2 * vy2) + (vx2 * vx2)))) / temp); model_param[1] = (((vx2 * ((vy1 * x1) - (vy1 * x2) - (vx1 * y1) + (vx2 * y1) - (vx1 * y2))) + (vy2 * ((-vx1 * x1) + (vx1 * x2) - (vy1 * y1) + (vy2 * y1) - (vy1 * y2))) + (y2 * ((vx1 * vx1) + (vy1 * vy1)))) / temp); temp = (float)((x1 * (x1 - (2 * x2))) + (x2 * x2) + (y1 * (y1 - (2 * y2))) + (y2 * y2)); if(temp == 0) { // Check to prevent division by zero return (0); } model_param[2] = ((((x1 - x2) * (vx1 - vx2)) + ((y1 - y2) * (vy1 - vy2))) / temp); model_param[3] = ((((x1 - x2) * (vy1 - vy2)) + ((y2 - y1) * (vx1 - vx2))) / temp); return (1); } // Generate F-o-F model inline int gen_firstOrderFlow_model( int flow_vector_count, flowvector *flow_vector_array, float *model_param, int *random_numbers, int iter) { int rand_num; int x1, x2, y1, y2, vx1, vx2, vy1, vy2; int ret; float highest_val = 0; // Select two motion vectors at random rand_num = random_numbers[iter * 2]; x1 = flow_vector_array[rand_num].x; y1 = flow_vector_array[rand_num].y; vx1 = flow_vector_array[rand_num].vx - flow_vector_array[rand_num].x; vy1 = flow_vector_array[rand_num].vy - flow_vector_array[rand_num].y; rand_num = random_numbers[iter * 2 + 1]; x2 = flow_vector_array[rand_num].x; y2 = flow_vector_array[rand_num].y; vx2 = flow_vector_array[rand_num].vx - flow_vector_array[rand_num].x; vy2 = flow_vector_array[rand_num].vy - flow_vector_array[rand_num].y; // Function to generate model parameters according to first order flow (xc, yc, D and R) ret = gen_model_param(x1, y1, vx1, vy1, x2, y2, vx2, vy2, model_param); return (ret); } // Estimate egomotion using RANSAC inline int estimate_ego_motion_first_order_flow(flowvector *flow_vector_array, int size_flow_vector_array, int *model_candidate, int *outliers_candidate, int *count_candidates, int *random_numbers, int max_iter, int error_threshold, float convergence_threshold) { int iter = 0; int ret; if(size_flow_vector_array == 0) { return (0); } // Allocate memory to store newly generated vectors flowvector ego_vector_array[size_flow_vector_array]; *count_candidates = 0; for(iter = 0; iter < max_iter; iter++) { float model_param_seq[4]; // Obtain model parameters for First Order Flow ret = gen_firstOrderFlow_model(size_flow_vector_array, flow_vector_array, model_param_seq, random_numbers, iter); if(ret == 0) { continue; } // Compute motion vectors at every point of optical flow using First Order Flow equations gen_firstOrderFlow_vectors(model_param_seq, size_flow_vector_array, flow_vector_array, ego_vector_array); // Decide if the new model is better than the previous model choose_better_model(flow_vector_array, ego_vector_array, size_flow_vector_array, model_param_seq, model_candidate, outliers_candidate, count_candidates, error_threshold, convergence_threshold, iter); } return (1); } void verify(flowvector *flow_vector_array, int size_flow_vector_array, int *random_numbers, int max_iter, int error_threshold, float convergence_threshold, int candidates, int b_outliers) { int *model_candidate = (int *)malloc(max_iter * sizeof(int)); int *outliers_candidate = (int *)malloc(max_iter * sizeof(int)); int count_candidates = 0; estimate_ego_motion_first_order_flow(flow_vector_array, size_flow_vector_array, model_candidate, outliers_candidate, &count_candidates, random_numbers, max_iter, error_threshold, convergence_threshold); // Post-processing (chooses the best model among the candidates) int best_model = -1; int best_outliers = size_flow_vector_array; for(int i = 0; i < count_candidates; i++) { if(outliers_candidate[i] < best_outliers) { best_outliers = outliers_candidate[i]; best_model = model_candidate[i]; } } compare_output(candidates, count_candidates, best_outliers, b_outliers); free(model_candidate); free(outliers_candidate); } inline void linear_function_oultier_count(point *point_array, int point_count, float *model_param, int *model_candidate, int *outliers_candidate, int *count_candidates, int error_threshold, float convergence_threshold, int iter){ int outlier_count = 0; float px, py; float m1, m2, b1, b2, qy, qx, dist_error; m1 = model_param[0]; b1 = model_param[1]; for(int i = 0; i < point_count; i++) { px = point_array[i].x; py = point_array[i].y; m2 = (-1)/m1; b2 = py - (m2*px); qx = (b1-b2)/(m2-m1); qy = (m1*qx) + b1; dist_error = sqrt(((qy-py) * (qy-py)) + ((qx-px) * (qx-px))); if(fabs(dist_error) >= error_threshold){ outlier_count++; } } // Compare to threshold if(outlier_count < point_count * convergence_threshold) { int ind = count_candidates[0]++; model_candidate[ind] = iter; outliers_candidate[ind] = outlier_count; } } inline int gen_linear_function_params(point *point_array, float *model_param, int *random_numbers, int iter){ int rand_num; float x1, x2, y1, y2; int ret; float m, b; rand_num = random_numbers[iter * 2]; x1 = point_array[rand_num].x; y1 = point_array[rand_num].y; rand_num = random_numbers[iter * 2 + 1]; x2 = point_array[rand_num].x; y2 = point_array[rand_num].y; if((x2-x1) == 0){ return (0); } m = (y2-y1)/(x2-x1); b = y1 - (x1*m); model_param[0] = m; model_param[1] = b; return (1); } inline int estimate_linear_function(point *point_array, int size_point_array, int *model_candidate, int *outliers_candidate, int *count_candidates, int *random_numbers, int max_iter, int error_threshold, float convergence_threshold){ int iter = 0; int ret; if(size_point_array == 0) { return (0); } *count_candidates = 0; for(iter = 0; iter < max_iter; iter++) { float model_param[2]; // Obtain model parameters ret = gen_linear_function_params(point_array, model_param, random_numbers, iter); if(ret == 0) { continue; } linear_function_oultier_count(point_array, size_point_array, model_param, model_candidate, outliers_candidate, count_candidates, error_threshold, convergence_threshold, iter); } return (1); } void verify(point *point_array, int size_point_array, int *random_numbers, int max_iter, int error_threshold, float convergence_threshold, int candidates, int b_outliers) { int *model_candidate = (int *)malloc(max_iter * sizeof(int)); int *outliers_candidate = (int *)malloc(max_iter * sizeof(int)); int count_candidates = 0; estimate_linear_function(point_array, size_point_array, model_candidate, outliers_candidate, &count_candidates, random_numbers, max_iter, error_threshold, convergence_threshold); // Post-processing (chooses the best model among the candidates) int best_model = -1; int best_outliers = size_point_array; for(int i = 0; i < count_candidates; i++) { if(outliers_candidate[i] < best_outliers) { best_outliers = outliers_candidate[i]; best_model = model_candidate[i]; } } compare_output(candidates, count_candidates, best_outliers, b_outliers); free(model_candidate); free(outliers_candidate); }
[ "jfaj@mail.uni-paderborn.de" ]
jfaj@mail.uni-paderborn.de
0318c4dc3ed3c79e8e5309b5bd08de17b7560d37
be21a6670509b53504a0422e2b781becc0deee83
/Applications/DaftEngineApp/src/Widgets/SettingWidgets/SettingWidget.cpp
613d88fdc4f9e20d3e02a953c2c24eec57987616
[ "MIT" ]
permissive
DaftMat/Daft-Engine
ff216723c682a68abe0363059072c830ea003a8c
e3d918b4b876d17abd889b9b6b13bd858a079538
refs/heads/master
2021-07-23T22:33:09.934433
2020-12-25T18:00:49
2020-12-25T18:00:49
277,404,325
1
0
MIT
2020-12-25T18:00:50
2020-07-06T00:06:12
C++
UTF-8
C++
false
false
1,924
cpp
// // Created by mathis on 12/07/2020. // #include "SettingWidget.hpp" #include <QApplication> #include <QDesktopWidget> #include <QtWidgets/QLabel> namespace daft::app { SettingWidget::SettingWidget(DrawableSettings *settings, TransformSettings *transforms, std::string name, float exposure, QWidget *parent) : QScrollArea(parent), m_settings{settings}, m_transforms{transforms} { std::string pname; if (m_settings == nullptr && m_transforms == nullptr) { pname = "Scene settings"; core::SettingManager sm; sm.add("Exposure", exposure); m_settings = std::make_unique<DrawableSettings>(sm); m_settings->addDoubleSpinBox("Exposure", 0.01, 999.9, 0.1); } else pname = std::move(name); m_title = new QLabel(pname.c_str()); m_title->setObjectName("sectionTitle"); createWidgets(); if (m_settings != nullptr) connect(m_settings.get(), SIGNAL(updateEvent()), this, SLOT(on_updateEvent())); if (m_transforms != nullptr) connect(m_transforms.get(), SIGNAL(updateEvent()), this, SLOT(on_updateEvent())); } void SettingWidget::setTitle(const std::string &name) { m_title->setText(name.c_str()); } void SettingWidget::on_updateEvent() { createWidgets(); } void SettingWidget::createWidgets() { m_layout = std::make_unique<QVBoxLayout>(); m_layout->setMargin(1); m_layout->addWidget(m_title); if (m_settings != nullptr) m_layout->addWidget(m_settings.get()); if (m_transforms != nullptr) m_layout->addWidget(m_transforms.get()); auto widget = new QWidget; widget->setLayout(m_layout.get()); setWidget(widget); auto screenWidth = float(QApplication::desktop()->screenGeometry().width()); setMinimumWidth(int(screenWidth / 5.5f)); setObjectName("settingWidget"); setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Preferred); } } // namespace daft::app
[ "mathis.margot98@gmail.com" ]
mathis.margot98@gmail.com
fd541ed0cf2077b1022f45222278d91f1dcf31bf
e12f4fb063cb0d26ebc500dd48bea14d2e5e3116
/atcoder/abc166_c.cpp
1d1d06be56e878b653b1224c5044ae5dc1cbd632
[]
no_license
komekome09/comp_prog
869ccf40863c9a6bc92f45e630a230669dfb64bb
8b168f8ced37b8399d890691774eac0d49695874
refs/heads/master
2023-04-20T23:57:42.051560
2021-05-15T13:40:31
2021-05-15T13:40:31
259,368,988
0
0
null
null
null
null
UTF-8
C++
false
false
1,136
cpp
#include <iostream> #include <string> #include <stdio.h> #include <cmath> #include <cfloat> #include <algorithm> #include <numeric> #include <vector> #include <iterator> #include <set> #include <map> using namespace std; const double PI=acos(-1); vector<int> h(1000000, 0); using graph = vector<vector<int>>; vector<bool> seen; int mmax = 0; void dfs(const graph &g, int v){ seen[v] = true; if(h[v] > mmax) mmax = h[v]; for(auto next_v : g[v]){ if(seen[next_v]) continue; dfs(g, next_v); } } int main(){ int n, m; cin >> n >> m; for(int i = 0; i < n; i++){ cin >> h[i]; } graph g(n); for(int i = 0; i < m; i++){ int a, b; cin >> a >> b; g[a-1].push_back(b-1); g[b-1].push_back(a-1); } int cnt = 0; for(int i = 0; i < n; i++){ int k = h[i]; for(int j = 0; j < g[i].size(); j++){ if(h[i] == h[g[i][j]]){ k = -1; break; } k = max(k, h[g[i][j]]); } if(k == h[i]) cnt++; } cout << cnt << endl; return 0; }
[ "fanmaskome@gmail.com" ]
fanmaskome@gmail.com
ea128e0d54bf1350c1f23988496ab126391bb97e
56f431ac8061ddb4c45b32457b0f948d1029d98f
/MonoNative.Tests/mscorlib/System/Runtime/CompilerServices/mscorlib_System_Runtime_CompilerServices_CompilerMarshalOverride_Fixture.cpp
b169bebf2f7fe7403157c9b6a408afc9b832e0e7
[ "BSD-2-Clause" ]
permissive
brunolauze/MonoNative
886d2a346a959d86e7e0ff68661be1b6767c5ce6
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
refs/heads/master
2016-09-15T17:32:26.626998
2016-03-01T17:55:27
2016-03-01T17:55:27
22,582,991
12
1
null
null
null
null
UTF-8
C++
false
false
679
cpp
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Runtime.CompilerServices // Name: CompilerMarshalOverride // C++ Typed Name: mscorlib::System::Runtime::CompilerServices::CompilerMarshalOverride #include <gtest/gtest.h> #include <mscorlib/System/Runtime/CompilerServices/mscorlib_System_Runtime_CompilerServices_CompilerMarshalOverride.h> #include <mscorlib/System/mscorlib_System_Type.h> #include <mscorlib/System/mscorlib_System_String.h> namespace mscorlib { namespace System { namespace Runtime { namespace CompilerServices { //Public Methods Tests } } } }
[ "brunolauze@msn.com" ]
brunolauze@msn.com
1b4652ce09bd2c88b5d27ad38a58c0cb9df76eec
59166d9d1eea9b034ac331d9c5590362ab942a8f
/ParticlePlayer/MainNode/UpdClbkMainNode.cpp
2c608e342c584f67905f27aeec17af4b43872bf5
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
3,004
cpp
#include "UpdClbkMainNode.h" #include "KeyboardState.h" #include "CameraState.h" #include <osg/Math> #include <iostream> UpdClbkMainNode::UpdClbkMainNode() : m_fMoveSpeed( 0.0 ) { } void UpdClbkMainNode::operator()( osg::Node* node, osg::NodeVisitor* nv ) { //обработать вращения ProcessRotate(); //обработать перемещение ProcessMove(); // first update subgraph to make sure objects are all moved into position traverse(node,nv); } void UpdClbkMainNode::ProcessRotate() { //обработать вращения //получить доступ к состоянию клавиатуры binEvents &mEvents = KeyboardState::Instance().GetEvents(); //получить доступ к состоянию камеры binCameraState &mCamState = CameraState::Instance().GetCameraState(); mCamState.m_dR = mCamState.m_dR + mEvents.m_dX * 0.5; mCamState.m_dH = mCamState.m_dH + mEvents.m_dY * 0.5; //ограничение диапазона углов if ( mCamState.m_dH > 360.0 ) mCamState.m_dH -= 360.0; else if ( mCamState.m_dH < -360.0 ) mCamState.m_dH += 360.0; if ( mCamState.m_dR > 360.0 ) mCamState.m_dR -= 360.0; else if ( mCamState.m_dR < -360.0 ) mCamState.m_dR += 360.0; } void UpdClbkMainNode::ProcessMove() { //обработать перемещение //получить доступ к состоянию клавиатуры binEvents &mEvents = KeyboardState::Instance().GetEvents(); if ( mEvents.m_bLeft ) //перемещение камеры вперед MoveForward(); else if ( mEvents.m_bRight ) //перемещение камеры назад MoveBackward(); } void UpdClbkMainNode::MoveForward() { //перемещение камеры вперед //получить доступ к состоянию камеры binCameraState &mCamState = CameraState::Instance().GetCameraState(); double dZ = cos( osg::DegreesToRadians( -mCamState.m_dH + 90.0 ) ); double nD = sqrt( 1.0 - dZ * dZ ); double dX = -nD * sin( osg::DegreesToRadians( mCamState.m_dR ) ); double dY = -nD * cos( osg::DegreesToRadians( mCamState.m_dR ) ); mCamState.m_dX += dX * 0.01; mCamState.m_dY += dY * 0.01; mCamState.m_dZ += dZ * 0.01; std::cout << mCamState.m_dY << " "; } void UpdClbkMainNode::MoveBackward() { //перемещение камеры назад //получить доступ к состоянию камеры binCameraState &mCamState = CameraState::Instance().GetCameraState(); double dZ = -cos( osg::DegreesToRadians( -mCamState.m_dH + 90.0 ) ); double nD = sqrt( 1.0 - dZ * dZ ); double dX = nD * sin( osg::DegreesToRadians( mCamState.m_dR ) ); double dY = nD * cos( osg::DegreesToRadians( mCamState.m_dR ) ); mCamState.m_dX += dX * 0.01; mCamState.m_dY += dY * 0.01; mCamState.m_dZ += dZ * 0.01; std::cout << mCamState.m_dY << " "; }
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b
1945d4d12661dbb81bc6aaf83e2bb3bb4f1cc779
5d1b1533f00f7ce58f7cd459cfdcaacb68069e49
/kattis/downtime/downtime.cpp
5a5705eeb355e8b251c31563b71c5dcb6673f594
[]
no_license
ongspxm/kattis
b19386afbcbb3680611fca7dbe13af19879446c0
a8f0f8c49e28c9bcaf1bf20a669c459c035ce83a
refs/heads/master
2020-03-08T11:10:13.496997
2018-12-26T08:20:53
2018-12-26T08:20:53
128,090,388
0
0
null
null
null
null
UTF-8
C++
false
false
790
cpp
#include <bits/stdc++.h> #define let const auto #define REP(var, i) for (int var = 0; var < i; ++var) using namespace std; using Int = int; //using Int = long long; using vi = vector<Int>; using vvi = vector< vector<Int> >; /** * Solution for problem: downtime * * Written by: ongspxm * * Date: 2018-12-14 07:29:42.303473 UTC * * Lessons learned: TEXTTEXTTEXT */ void solve() { Int N, k; cin >> N >> k; priority_queue< Int, vector<Int>, greater<Int> > times; REP (n, N) { Int x; cin >> x; if (times.size() > 0 && times.top() <= x) { times.pop(); } times.push(x+1000); } Int size = times.size(); cout << size/k + 1*(size%k > 0); } int main() { ios::sync_with_stdio(false); cin.tie(NULL); solve(); }
[ "ongspxm@gmail.com" ]
ongspxm@gmail.com
547a95aabbc7e693b2bd8818df367d8910feac32
9140dd125826503501d9cc111d36d604e93cd433
/Tree/Questions/Sum_at_lvl_K.cpp
149fd425da9cf22aeaa5fe6d34cf94392409c9e0
[]
no_license
vibgyor98/dsalgocp
f7d43854886b97a468754fb6929ebfcce51b45e2
7260033c11b17601034153a082456ff7ddc4578d
refs/heads/master
2021-08-04T05:54:50.610133
2020-12-18T18:14:23
2020-12-18T18:14:23
228,390,576
0
1
null
null
null
null
UTF-8
C++
false
false
894
cpp
#include <bits/stdc++.h> using namespace std; class node { public: int data; node* left; node* right; node(int d) { data = d; left = NULL; right = NULL; } }; //constructing tree node* buildTree() { int d, num; cin >> d; node* root = new node(d); cin >> num; if (num == 2) { root->left = buildTree(); root->right = buildTree(); } else if (num == 1) { root->left = buildTree(); } return root; } //Sum at kth level int sum = 0; void sum_at_Kth_level(node* root, int k) { if (root == NULL) { return; } if (k == 0) { sum += root->data; } if (k < 1) { return; } sum_at_Kth_level(root->left, k - 1); sum_at_Kth_level(root->right, k - 1); } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif node* root = buildTree(); int k; cin >> k; sum_at_Kth_level(root, k); cout << sum; return 0; }
[ "karsourav05@gmail.com" ]
karsourav05@gmail.com
6312bb78eb01a43c881c74f3dae2862deb96d62e
193cacbe89f5b2ef2208ef075dedc1871464f5f4
/src/objects/src/exchangeinfo.cpp
4d447146b49f4a80a04afca15b902e6bbb74624a
[ "MIT" ]
permissive
sssong81/coincenter
6c867fc39d9b096bafb71a9cb41295ed76dd29f5
5f46b89af3a10c4a85a1fe6d3cbda950b7b3c949
refs/heads/master
2023-04-22T21:43:08.753950
2021-05-05T06:53:20
2021-05-06T13:40:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,270
cpp
#include "exchangeinfo.hpp" #include "cct_exception.hpp" #include "cct_log.hpp" #include "cct_mathhelpers.hpp" #include "monetaryamount.hpp" namespace cct { ExchangeInfo::ExchangeInfo(std::string_view exchangeNameStr, const json &exchangeData) { // Load trade fees constexpr char kTradeFeesStr[] = "tradefees"; if (!exchangeData.contains(kTradeFeesStr)) { throw exception("Unable to load trade fees for exchange " + std::string(exchangeNameStr)); } const json &tradeFeesData = exchangeData[kTradeFeesStr]; std::string_view makerStr = tradeFeesData["maker"].get<std::string_view>(); std::string_view takerStr = tradeFeesData["taker"].get<std::string_view>(); _generalMakerRatio = (MonetaryAmount("100") - MonetaryAmount(makerStr)) / 100; _generalTakerRatio = (MonetaryAmount("100") - MonetaryAmount(takerStr)) / 100; // Load asset config constexpr char kAssets[] = "asset"; if (exchangeData.contains(kAssets)) { const json &assetData = exchangeData[kAssets]; constexpr const char *const kSubAssetConfig[] = {"allexclude", "withdrawexclude"}; CurrencySet *const pCurrencySetPerConfig[] = {std::addressof(_excludedCurrenciesAll), std::addressof(_excludedCurrenciesWithdrawal)}; const int kNbSub = std::end(pCurrencySetPerConfig) - std::begin(pCurrencySetPerConfig); for (int subIdx = 0; subIdx < kNbSub; ++subIdx) { if (assetData.contains(kSubAssetConfig[subIdx])) { // Don't make these json fields required, do nothing if not present const json &subData = assetData[kSubAssetConfig[subIdx]]; CurrencySet &currencySet = *pCurrencySetPerConfig[subIdx]; std::string currenciesCSV = subData; std::size_t first = 0; std::size_t last = currenciesCSV.find_first_of(','); while (last != std::string::npos) { currencySet.emplace(std::string_view(currenciesCSV.begin() + first, currenciesCSV.begin() + last)); first = last + 1; last = currenciesCSV.find_first_of(',', first); } if (first != currenciesCSV.size()) { currencySet.emplace(std::string_view(currenciesCSV.begin() + first, currenciesCSV.end())); } for (CurrencyCode code : currencySet) { log::debug("{}: Adding {} as {}", exchangeNameStr, code.str(), kSubAssetConfig[subIdx]); } log::info("Loaded {} currencies in config", currencySet.size()); } } } // Load query config constexpr char kQuery[] = "query"; if (!exchangeData.contains(kQuery)) { throw exception("Unable to load query configuration for exchange " + std::string(exchangeNameStr)); } const json &queryData = exchangeData[kQuery]; _minPublicQueryDelay = std::chrono::milliseconds(queryData["minpublicquerydelayms"].get<int>()); _minPrivateQueryDelay = std::chrono::milliseconds(queryData["minprivatequerydelayms"].get<int>()); log::info("Loaded {} & {} ms as minimum time between two queries in config (public & private exchanges respectively)", std::chrono::duration_cast<std::chrono::milliseconds>(_minPublicQueryDelay).count(), std::chrono::duration_cast<std::chrono::milliseconds>(_minPrivateQueryDelay).count()); } } // namespace cct
[ "stephane.janel@amadeus.com" ]
stephane.janel@amadeus.com
b1cc88c8c016043863bf5a19ecf8828d6b5e7e77
0ebb297fe3a7354d988661be5b1de8ab2019c60a
/code/common/ddl/node_ref.cpp
7bbf3641e51a16e0e0a427b20dfdd20eaa45c1f5
[]
no_license
kamrann/workbase
a56e8ca3874ae5e71e4c77331ed10f59acff5914
ce2cade80365f885839bf96bfc5db5e57059ba39
refs/heads/master
2021-01-19T03:22:32.745349
2015-01-02T23:05:04
2015-01-02T23:05:04
15,985,205
0
0
null
null
null
null
UTF-8
C++
false
false
1,823
cpp
// node_ref.cpp #include "node_ref.h" #include "values/value.h" #include "values/navigator.h" namespace ddl { navigator nav_to_ref(node_ref const& ref, navigator nav) { auto rf = resolve_reference_unique(ref, nav); if(rf) { return navigator{ nav.tree_, rf }; } else { return{}; } } sd_node_ref_list resolve_reference(node_ref const& ref, navigator nav) { if(nav) { auto id = ref.nd.get_id(); auto fr = nav.find_by_id(id); // todo: perhaps this call will need to be passed info from node_ref::res context settings if(!fr.by_location.empty()) { if(ref.res == node_ref::Resolution::Unique) { auto const& first_list = fr.by_location.begin()->second; if(first_list.size() == 1) { auto const& pth = first_list.front(); auto rnav = nav[pth]; return{ rnav.get_ref() }; } else { throw std::runtime_error("ambiguous reference id lookup"); } } else // todo: more fine grained control of resolving context done here... // currently just accept any matching id anywhere in hierarchy { sd_node_ref_list results; for(auto const& entry : fr.by_location) { auto const& res_list = entry.second; for(auto const& pth : res_list) { auto rnav = nav[pth]; results.insert(rnav.get_ref()); } } return results; } } } return{}; } sd_node_ref resolve_reference_unique(node_ref const& ref, navigator nav) { auto res = resolve_reference(ref, nav); if(res.size() != 1) { throw std::runtime_error("ambiguous reference id lookup"); } else { return *res.begin(); } } sd_node_ref unique_reference(sd_node_ref_list const& list) { if(list.size() == 1) { return *list.begin(); } else { return{}; } } }
[ "cjangus@gmail.com" ]
cjangus@gmail.com
bddbfeec18fdf0b921628ec1b476ebf2d512a731
027a76f640874ede2cf27f1dc49611a2bbbb34dd
/gfg/string/anagram.cpp
580457fbc3fe47f011f8ab7894929668150d0441
[]
no_license
ashishugi/MYCODES
b33cda06a18defd8f2de91b4a66cdb8eba55ca47
8e5e4d047ae415ab72ec4fd74171432e6c0cbb6e
refs/heads/master
2022-02-09T00:51:47.406788
2022-01-28T17:34:42
2022-01-28T17:34:42
165,395,936
17
1
null
null
null
null
UTF-8
C++
false
false
865
cpp
#include<bits/stdc++.h> #define loop(i,n) for(int i=0;i<n;i++) using namespace std; bool anagram(string s1,string s2){ int n=s1.length(); int m=s2.length(); if(n!=m){ return false; } map<char,int> m1; map<char,int> m2; loop(i,n){ m1[s1[i]]++; m2[s2[i]]++; } map<char,int>::iterator i1 = m1.begin(); map<char,int>::iterator i2 = m2.begin(); for(;i1!=m1.end();i1++,i2++){ if(i1->first == i2->first){ if(i1->second != i2->second){ return false; } }else{ return false; } } return true; } int main(void){ int t; cin>>t; while(t--){ string s1,s2; cin>>s1>>s2; if(anagram(s1,s2)){ cout<<"YES"<<endl; }else{ cout<<"NO"<<endl; } } return 0; }
[ "ashishkumarguptacse@gmail.com" ]
ashishkumarguptacse@gmail.com
27855431a64af048c27ed15c07aa2d1dec47180a
84ecf1c812b7dfd121d32c923e66dbfa5a967403
/TestFileOperation/Star.h
845795efe497ae6c61e65d7104766fdc4ae2cd7f
[ "MIT" ]
permissive
Takayoshi1125/GPG_LT07
ecd3b406bb9fada7e5daff1f0c97bfe9f7107574
c0c1005a5c3207177ca703bad61fedf8c88f2e69
refs/heads/main
2023-06-18T10:47:09.952565
2021-07-15T03:00:39
2021-07-15T03:00:39
385,107,322
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
411
h
#pragma once #include "Vector2.h" class Star { public: static constexpr int SPEED_SLOW_ROT = 4; // 初期処理 void Init(void); // 更新ステップ void Update(void); // 描画処理 void Draw(void); // 解放処理 void Release(void); Vector2 GetPos(void); void SetPos(Vector2 pos); void SetSizeRate(float rate); private: int mImage; Vector2 mPos; int mRot; float mSizeRate; };
[ "takayoshi176@gmail.com" ]
takayoshi176@gmail.com
1507956ce53d53a3aa4bc14f2f28304e2c973d80
01eb9bea1e6c1b3eab913b3636a6895b1d2b39f5
/API/src/System.cpp
22b77647562fa4b733c1f2793de4a5f4fd95e73b
[ "MIT" ]
permissive
thaolt/OtterUI
a5e4424341047eeac03c27bebceae6442763975b
a2c524378e4933bd772b44f4c56b5139e8b4094a
refs/heads/master
2021-05-30T04:24:15.442292
2015-08-21T18:35:58
2015-08-21T18:35:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,653
cpp
#include <string.h> #include <stdlib.h> #include <assert.h> #include "System.h" #include "Scene.h" #include "Data/OtterData.h" #include "Graphics/Graphics.h" #include "Memory/Memory.h" #include "Common/Log.h" namespace Otter { /* Constructor. Allocates an internal buffer from default allocators of size 'memorySize' */ System::System(int memorySize) { mScreenWidth = 0; mScreenHeight = 0; mMemoryBuffer = NULL; if(memorySize > 0) { mMemoryBuffer = (uint8*)malloc(memorySize); MemoryManager::initializeMemoryManager(mMemoryBuffer, memorySize); } mFileSystem = NULL; mSoundSystem = NULL; mGraphics = OTTER_NEW(Graphics, ()); SetResolution(1024, 768); } /* Constructor. Uses the provided buffer as its heap memory. */ System::System(uint8* pMemoryBuffer, int memorySize) { MemoryManager::initializeMemoryManager(pMemoryBuffer, memorySize); InitLog(this); mFileSystem = NULL; mGraphics = NULL; mScreenWidth = 0; mScreenHeight = 0; mMemoryBuffer = NULL; SetResolution(1024, 768); } /* Destructor */ System::~System(void) { UnloadAllScenes(); DeinitLog(); mScenes.clear(true); mPlugins.clear(true); mOnSceneLoaded.Clear(); mOnSceneUnloaded.Clear(); mOnLog.Clear(); mOnMessage.Clear(); OTTER_DELETE(mGraphics); mGraphics = NULL; MemoryManager::deinitializeMemoryManager(); if(mMemoryBuffer) { free(mMemoryBuffer); mMemoryBuffer = NULL; } } /* Sets the file system. This object will be called * when opening / closing / reading from files. */ Result System::SetFileSystem(IFileSystem* pFileSystem) { mFileSystem = pFileSystem; return kResult_OK; } /* Sets the object responsible for rendering the GUI */ Result System::SetRenderer(IRenderer* pRenderer) { mGraphics->SetUserRenderer(pRenderer); return kResult_OK; } /* Sets the sound system */ Result System::SetSoundSystem(ISoundSystem* pSoundSystem) { mSoundSystem = pSoundSystem; return kResult_OK; } /* Adds a plugin */ Result System::AddPlugin(IPlugin* pPlugin) { if(pPlugin == NULL) return kResult_Error; int cnt = mPlugins.size(); for(int i = 0; i < cnt; i++) { if(mPlugins[i] == pPlugin) return kResult_OK; } mPlugins.push_back(pPlugin); return kResult_OK; } /** * Enables / disables (cpu) pre-transforming of vertices. * Enabling vertex pretransformation may reduce draw calls at the cost * of additional CPU load. */ Result System::EnablePreTransformVerts(bool bEnable) { if(!mGraphics) return kResult_Error; mGraphics->EnablePreTransformVerts(bEnable); return kResult_OK; } /** * Enables / disables logging */ Result System::EnableLogging(bool bEnable) { if(bEnable) { InitLog(this); } else { DeinitLog(); } return kResult_OK; } /* Sets the resolution of the UI. Can be called at any time. */ Result System::SetResolution(uint32 width, uint32 height) { mScreenWidth = width; mScreenHeight = height; int cnt = GetSceneCount(); for(int i = 0; i < cnt; i++) if( Scene * s=GetScene(i) ) s->SetResolution(mScreenWidth, mScreenHeight); return kResult_OK; } bool System::HasScene( char const * name ) const { assert(mFileSystem!=0); void* pHandle = (void*)mFileSystem->Open(name, AccessFlag(kBinary | kRead)); if(pHandle == NULL) return false; mFileSystem->Close(pHandle); return true; } /* Loads a scene from file */ Result System::LoadScene(const char* szPath, Scene** ppScene) { if(!mFileSystem) return kResult_NoFileSystem; void* pHandle = (void*)mFileSystem->Open(szPath, AccessFlag(kBinary | kRead)); if(pHandle == NULL) return kResult_FileNotFound; uint32 size = mFileSystem->Size(pHandle); if(size == 0) return kResult_InvalidFile; uint8* pBuffer = (uint8*)OTTER_ALLOC(size); uint32 readSize = mFileSystem->Read(pHandle, pBuffer, size); mFileSystem->Close(pHandle); // Check if we failed to read all the data, or if we // simply failed to load the scene. Cleanup and bail if so. if(readSize != size) { OTTER_FREE(pBuffer); return kResult_FailedRead; } return LoadScene(pBuffer, size, false, ppScene); } /* Loads a scene from an existing in-memory buffer */ Result System::LoadScene(const uint8* pBuffer, uint32 bufferSize, bool bCopy, Scene** ppScene) { // Copy the data if necessary. const uint8* pSceneBuffer = pBuffer; if(bCopy) { pSceneBuffer = (uint8*)OTTER_ALLOC(bufferSize); memcpy((uint8*)pSceneBuffer, pBuffer, bufferSize); } // Cast the buffer to the scene data object and verify it's a // valid scene data buffer and version. const SceneData* pSceneData = (const SceneData*)pSceneBuffer; if(pSceneData->mFourCC != FOURCC_GGSC) { return kResult_InvalidSceneFile; } if(pSceneData->mVersion != SCENE_DATA_VERSION) { return kResult_InvalidSceneVersion; } Scene* pScene = OTTER_NEW(Scene, (this, mGraphics, mSoundSystem, pSceneData)); pScene->SetResolution(mScreenWidth, mScreenHeight); mScenes.push_back(pScene); mOnSceneLoaded(this, pScene); if(ppScene) *ppScene = pScene; return kResult_OK; } /** * Unloads the specified scene */ Result System::UnloadScene(Scene* pScene) { if(!pScene) return kResult_Error; uint32 numActiveViews = pScene->GetNumActiveViews(); for(uint32 i = 0; i < numActiveViews; i++) { View* view = pScene->GetActiveView(i); view->OnDeactivate(); } // Grab a pointer to the internal scene data in case we need // to free it ourselves later. const uint8* pData = (const uint8*)pScene->GetData(); mOnSceneUnloaded(this, pScene); OTTER_DELETE(pScene); // The data may not have come from us. If it's the memory manager's // memory pool, we allocated it and so we must release it. if(MemoryManager::isValid(pData)) { OTTER_FREE((void*)pData); } for(uint32 i = 0; i < mScenes.size(); i++) { if(mScenes[i] == pScene) { mScenes.erase(i); break; } } return kResult_OK; } /** * Unloads a scene by index */ Result System::UnloadScene(uint32 index) { Scene * s=GetScene(index); assert(s!=0); return UnloadScene(s); } /* Unloads the active scene */ Result System::UnloadAllScenes() { while(mScenes.size() > 0) { UnloadScene(mScenes[0]); } mScenes.clear(); return kResult_OK; } /* Returns a loaded scene by index */ Scene* System::GetScene(uint32 index) { if(index >= mScenes.size()) return 0; return mScenes[index]; } /* Returns the number of scenes currently loaded */ uint32 System::GetSceneCount() { return mScenes.size(); } void System::BringToFront( Scene * s ) { assert(s!=0); for( int i=0,n=GetSceneCount(); i!=n; ++i ) { Scene * ss=mScenes[i]; if( s==ss ) { for( ; i!=n-1; ++i ) mScenes[i]=mScenes[i+1]; mScenes[i]=s; return; } } assert(0); } /* Draws the GUI */ Result System::Draw() { if(!mGraphics) return kResult_NoRenderer; uint32 numScenes = GetSceneCount(); if(numScenes) { mGraphics->Begin(); for(uint32 i = 0; i < numScenes; i++) if( Scene * s=GetScene(i) ) s->Draw(); mGraphics->End(); } return kResult_OK; } /* Updates the GUI * "frameDelta" indicates the number of frames that have passed since last update. */ Result System::Update(float frameDelta) { uint32 numScenes = GetSceneCount(); if(numScenes) { for(uint32 i = 0; i < numScenes; i++) if( Scene * s=GetScene(i) ) s->Update(frameDelta); for(uint32 i = 0; i < numScenes; i++) if( !GetScene(i) ) { mScenes.erase(i); break; } } return kResult_OK; } /* Points (touches/mouse/etc) were pressed down */ void System::OnPointsDown(const Point* points, sint32 numPoints) { uint32 numScenes = GetSceneCount(); if(numScenes) for(int i=numScenes; --i>=0; ) if( Scene * s=GetScene(i) ) if( s->OnPointsDown(points, numPoints) ) return; } /* Points (touches/mouse/etc) were released */ void System::OnPointsUp(const Point* points, sint32 numPoints) { uint32 numScenes = GetSceneCount(); if(numScenes) for(int i=numScenes; --i>=0; ) if( Scene * s=GetScene(i) ) if( s->OnPointsUp(points, numPoints) ) return; } /* Points (touches/mouse/etc) were moved. */ void System::OnPointsMove(const Point* points, sint32 numPoints) { uint32 numScenes = GetSceneCount(); if(numScenes) for(int i=numScenes; --i>=0; ) if( Scene * s=GetScene(i) ) if( s->OnPointsMove(points, numPoints) ) return; } };
[ "grafalgar@gmail.com" ]
grafalgar@gmail.com
3af003b8d000d0f5db2d296783cc3635fc189ae1
e3c27edbd2f0a8e733cee84b90a906c0a6d7c176
/mpi/time.cpp
00f171c540eb8a47e2e062f015225edd99ac1be7
[]
no_license
dmitryhd/dmitryhd_code
c32223da5506156a068bbb0f20ad4cd06fdf2166
5173f6f74d4fa1c9c5fba9ffc4fc9134c56f4b0c
refs/heads/master
2021-01-17T11:56:50.221745
2011-04-26T18:31:58
2011-04-26T18:31:58
1,650,576
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
cpp
/*Copyright 2011 Dmitry Khodakov coded: 2.03.11 */ #include <mpi.h> #include <stdlib.h> #include <stdint.h> // mark of every message #define TAG 0 void master(); void node(); int main(int argc, char *argv[]) { int myid = 0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myid); double tbegin, tend; tbegin = MPI_Wtime(); if (myid == 0) master(); else node(); tend = MPI_Wtime(); if (myid == 0) printf("%f\n", tend - tbegin); MPI_Finalize(); return 0; } // master (id = 0) process, it split task and get first part of it // args: last_number - bottom of natural sequence. void master() { int numproc = 1; // number of nodes in network MPI_Comm_size(MPI_COMM_WORLD, &numproc); MPI_Status stat; // status of receiving. I didn't use it here. Don't delete. uint32_t sended_res; // result of partial computation by node for (int i = 1, add_count = 0; i < numproc; ++i, ++add_count) { MPI_Recv(&sended_res, 1, MPI_UNSIGNED_LONG, i, TAG, MPI_COMM_WORLD, &stat); MPI_Send(&sended_res, 1, MPI_UNSIGNED_LONG, i, TAG, MPI_COMM_WORLD); } } // calculating process, takes tasks from master void node() { MPI_Status stat; uint32_t sended_res; MPI_Send(&sended_res, 1, MPI_UNSIGNED_LONG, 0, TAG, MPI_COMM_WORLD); MPI_Recv(&sended_res, 1, MPI_UNSIGNED_LONG, 0, TAG, MPI_COMM_WORLD, &stat); }
[ "dmitryhd@google.com" ]
dmitryhd@google.com
cde2be3feffb26f18512cf0e5d04133b36252a3e
3189f9fc40192435a2f4edd258a0ea169ba62428
/CSES/Introductory Problems/palindromeReorder.cpp
d5d4c9a4605e3caba2cccd44188997725b67971d
[]
no_license
lifchrs/CP
ee5820be5654784162145633ab58937056494264
7223731ae368f365afaec175c75540e7454165ec
refs/heads/master
2023-03-03T23:22:47.801445
2021-02-19T05:13:49
2021-02-19T05:13:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define se second #define pb push_back #define pf push_front #define ll long long #define F0R(i,a) for(int i=0;i<a;i++) #define FOR(i,a,b) for(int i=a;i<b;i++) ll binpow(ll a,ll b){ ll res=1; while(b>0){ if(b & 1) res*=a; a*=a; b>>=1; } return res; } int freq[27]; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); //ifstream cin("name.in"); //ofstream cout("name.out"); string a; cin>>a; FOR(i,0,27) freq[i]=0; for(char x:a){ freq[x-'A']++; } int numOdd=0; for(int i:freq){ if(i%2==1) numOdd++; } if(numOdd>1){ cout<<"NO SOLUTION\n"; return 0; } string first=""; string alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(int i=0;i<27;i++){ if(freq[i]%2==0){ for(int x=0;x<freq[i]/2;x++) first+=alphabet[i]; } } //cout<<first; string bruh=first; reverse(first.begin(),first.end()); for(int i=0;i<27;i++){ if(freq[i]%2==1){ for(int x=0;x<freq[i];x++) first+=alphabet[i]; } } //cout<<"first: "<<first<<endl; //cout<<"bruh: "<<bruh<<endl; cout<<first+bruh<<endl; }
[ "polavaramadhitya@gmail.com" ]
polavaramadhitya@gmail.com
b760068219e09d000ae682df11fe4f9793b91645
794ec36417d1f5fe9f8a8dfefee17169ba346447
/UVA/156/10094942_AC_0ms_0kB.cpp
60a8a42be89654e8e2a514e95147ca779ca58460
[]
no_license
riba2534/My_ACM_Code
1d2f7dacb50f7e9ed719484419b3a7a41ba407cf
fa914ca98ad0794073bc1ccac8ab7dca4fe13f25
refs/heads/master
2020-03-24T01:19:19.889558
2019-03-11T03:01:09
2019-03-11T03:01:09
142,331,120
3
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include <cstdio> #include <cstring> #include <cctype> #include <string> #include <set> #include <iostream> #include <stack> #include <map> #include <cmath> #include <queue> #include <vector> #include <algorithm> #define mem(a,b) memset(a,b,sizeof(a)) #define inf 0x3f3f3f3f #define N 10000+20 #define ll long long using namespace std; //map<string,int>mp; //vector<string>v; //string str(string s) //{ // for(int i=0;i<s.length();i++) // s[i]=tolower(s[i]); // sort(s.beg) // //} //int main() //{ // string s; // while(cin>>s&&s!="#") // { // // } //} map<string,int>cnt; vector<string>words; string repr(string s) { string ans=s; for(int i=0; i<ans.length(); i++) ans[i]=tolower(ans[i]); sort(ans.begin(),ans.end()); return ans; } int main() { int n=0; string s; while(cin>>s&&s!="#") { words.push_back(s); string r=repr(s); if(!cnt.count(r)) cnt[r]=0; cnt[r]++; } vector<string>ans; for(int i=0; i<words.size(); i++) if(cnt[repr(words[i])]==1) ans.push_back(words[i]); sort(ans.begin(),ans.end()); for(int i=0; i<ans.size(); i++) cout<<ans[i]<<endl; return 0; }
[ "riba2534@qq.com" ]
riba2534@qq.com
c03d0632fdd245e28d301ba82e7d9f9a9acc3894
8a7efe320d8f0389b9d1c8d471fce6888680451d
/src/main.cpp
8d7b4c266895987dde751c34c0c19da6624c9dff
[]
no_license
qwertyuiopasdfghjklqwertyuiop/CS2C.05.nonstd-Multiset.remove
aa077229c83a95b57cb38df39f9a21bf4c26989f
a44b242c09a55da7a7c7adce75c45951d87b044c
refs/heads/master
2021-08-08T08:59:32.296195
2017-11-10T01:24:48
2017-11-10T01:24:48
108,688,410
0
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
#include <iostream> #include <cmath> #include "./multiset.h" using nonstd::MultiSet; int main(const int argc, char ** argv){ if(argc != 3) { std::cerr << "./main BIGGEST_NUMBER NUM_INSERTIONS" << std::endl; exit(1); } srand(time(NULL)); MultiSet<int> test; const int BIGGEST_NUMBER = std::stoi(*(argv+1)); const int NUM_INSERTIONS = std::stoi(*(argv+2)); int myCounter = 0; int toCountFor = rand() % BIGGEST_NUMBER; for(int k = 0; k < NUM_INSERTIONS; k++) { int temp = rand() % BIGGEST_NUMBER; test.insert(temp); if(toCountFor == temp) myCounter++; } std::cout << "Size: " << test.size() << std::endl; std::cout << "Count for: " << toCountFor << std::endl; std::cout << "Counted: " << test.count(toCountFor) << std::endl; std::cout << "Removed: " << test.remove(toCountFor) << std::endl; std::cout << "Removed again: " << test.remove(toCountFor) << std::endl; std::cout << "New Size: " << test.size() << std::endl; return 0; }
[ "bobthefrank24685@gmail.com" ]
bobthefrank24685@gmail.com
2b8253c21380f250d036538f69a902053cac8820
85f1cd01c68731a30bff2b99a9e21e5d3a81fb70
/data-structure/17.Dahua/all.cpp
09f00733266d17cff5cf48a40c92fe3c36fa2fec
[]
no_license
ddayzzz/algorithm-and-basic-apps
f146ee9a31a61d92c963d6a14d17c59f3de67740
7ea0cedd32df0b8d207e85696e30105e87b003c8
refs/heads/master
2020-04-01T06:24:17.842635
2019-10-09T15:11:51
2019-10-09T15:11:51
152,945,967
0
0
null
null
null
null
UTF-8
C++
false
false
3,379
cpp
// 大话数据结构1.cpp : 定义控制台应用程序的入口点。 // #include "../stdafx.h" #include "../00.Dahua_Datastructures_Common/StaticList.h" #include "../00.Dahua_Datastructures_Common/DoubleList.h" #include "../00.Dahua_Datastructures_Common/SharedStack.h" #include "../00.Dahua_Datastructures_Common/LinkStack.h" #include "../00.Dahua_Datastructures_Common/Calc.h" #include "../00.Dahua_Datastructures_Common/LinkQueue.h" #include "../00.Dahua_Datastructures_Common/String.h" int main() { /* 静态链表的使用 CursorList l; l = initialize_cursorlist(10); insert_cursorlist(l, 1, 5); insert_cursorlist(l, 2, 9); insert_cursorlist(l, 3, 19); insert_cursorlist(l, 4, 29); StaticList *s = &l[2]; insert_cursorlist(l, 5, 39); print_allelements(l); free(l); s->cursor; */ /*双端链表的使用 DoubleList dl; dl = initialize_DoubleList(); insert_DoubleList(dl, 1, 3); insert_DoubleList(dl, 2, 5); insert_DoubleList(dl, 3, 6); insert_DoubleList(dl, 4, 69); print_DoubleList_prior(dl); printf("-----------"); delete_DoubleList(dl, 3); print_DoubleList_next(dl); auto df = dl->next->next; free_DoubleList(dl); //print_DoubleList_next(dl); */ /* 共享的栈使用 SharedStack s; s=create_sharedStack(6); push_sharedStack(5, s, 1); push_sharedStack(6, s, 1); push_sharedStack(7, s, 1); push_sharedStack(8, s, 1); push_sharedStack(9, s, 2); push_sharedStack(10, s, 2); push_sharedStack(12, s, 2); print_allelemaentsinSharedStack(s); pop_sharedStack(s, 1); popandtop_sharedStack(s, 2); print_allelemaentsinSharedStack(s); free_sharedStack(s); */ /*链栈的使用 LinkStack li; li = create_empty_LinkStack(); push_LinkStack(5,li); push_LinkStack(6, li); push_LinkStack(66, li); push_LinkStack(666, li); topandpop_linkstack(li); auto i = li->next->next; push_LinkStack(66666, li); print_all_linkstack(li); free_all_linkstack(li); */ //char c[] = { '1','+','2','*','3','+','(','4','*','5','+','6',')','*','7','\0' };// { '9', '+', '(', '3', '-', '1', ')', '*', '3', '+', '1', '/', '2' }; //int s = sizeof(c) / sizeof(c[0]); //char *gff=infixToSuffix(c, s-1); //printf("%s", gff); /* 中缀式 转后缀式 char c; int cnt = 0; char p[256]; do { c = getchar(); if (c != ' ' && c !='\n') { p[cnt++] = c; } } while (cnt <256 && c != '\n'); p[cnt] = '\0'; char *f=infixToSuffix(p, cnt); printf(" postfix is \'%s\'", f); free(f); */ /* LinkQueue lq; lq = create_empty_linkqueue(); EnQueue_linkqueue(lq, 1); EnQueue_linkqueue(lq, 2); EnQueue_linkqueue(lq, 3); //printf("%d\n",DeQueue_linkqueuq(lq)); //printf("%d\n", DeQueue_linkqueuq(lq)); //printf("%d\n", DeQueue_linkqueuq(lq)); destroy_allLinkQueue(lq); */ String h; h = create_string('\0', 5); int g = size_string(h); for(int j=1;j<=5;++j) push_back_string(h, '0'+j); printf("%s", h->first); insert_string(h, '6', 2); String h2; h2 = create_string('\0', 10); for (int j = 1; j <= 9; ++j) push_back_string(h2, '0'+j); String hh = union_string(h, h2); String p = create_string(); push_back_string(p, 's'); String hhh = create_string('2', 6); push_back_string(hhh, 'A'); push_back_string(hhh, 'A'); push_back_string(hhh, 'A'); push_back_string(hhh, 'B'); push_back_string(hhh, 'D'); push_back_string(hhh, 'A'); int a = find_string_KMP(hhh,hh); free_string(h); getchar(); return 0; }
[ "wangshu214@live.cn" ]
wangshu214@live.cn
1fb85ca53367ccb1960657ed9c3c456f92fd6517
6b660cb96baa003de9e18e332b048c0f1fa67ab9
/External/SDK/BP_LargeShip_StandardHull_functions.cpp
546c1dcbe8f8c7e5bbbaaddf4176a2051a7b7562
[]
no_license
zanzo420/zSoT-SDK
1edbff62b3e12695ecf3969537a6d2631a0ff36f
5e581eb0400061f6e5f93b3affd95001f62d4f7c
refs/heads/main
2022-07-30T03:35:51.225374
2021-07-07T01:07:20
2021-07-07T01:07:20
383,634,601
1
0
null
null
null
null
UTF-8
C++
false
false
1,272
cpp
// Name: SoT, Version: 2.2.0.2 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_LargeShip_StandardHull.BP_LargeShip_StandardHull_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_LargeShip_StandardHull_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_LargeShip_StandardHull.BP_LargeShip_StandardHull_C.UserConstructionScript"); ABP_LargeShip_StandardHull_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } void ABP_LargeShip_StandardHull_C::AfterRead() { AHull::AfterRead(); READ_PTR_FULL(Occluder, UStaticMeshComponent); READ_PTR_FULL(Damage, UChildActorComponent); READ_PTR_FULL(Art, UChildActorComponent); } void ABP_LargeShip_StandardHull_C::BeforeDelete() { AHull::BeforeDelete(); DELE_PTR_FULL(Occluder); DELE_PTR_FULL(Damage); DELE_PTR_FULL(Art); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
b368a7db1d4b45fd8b7c3699ad56dd60463db67c
3702e384050f90bb8ad39db7002ec5f6fabe4047
/curses/game_manager.h
824abe36fbc8ee8e41cb3faaa086a3cebcaa4e5a
[]
no_license
pviolette3/jamstacks
264872f292253206defb763af3d5b109cd008d73
94e2faed58d65ee4f5d1e86f8dd43200cd7d7b6c
refs/heads/master
2021-07-21T22:23:24.585472
2017-10-30T08:23:16
2017-10-30T08:23:16
94,112,596
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
h
#pragma once #include <array> #include <memory> #include <vector> #include <string> #include <stdint.h> namespace jam { // Thread-safe game state class GameManager { public: GameManager() {} class Handler { GameManager *gameManager_; protected: Handler(GameManager &gameManager) noexcept : gameManager_(&gameManager) { gameManager_->registerHandler(*this); } GameManager const &gameManager() { return *gameManager_; } public: virtual ~Handler() noexcept {} // Show cards, small blind, big blind, dealer token virtual void onHandStart() noexcept = 0; virtual void onHandComplete() noexcept = 0; /// @returns 0 for check/fold (context dependent) or the bet. virtual uint64_t onPlayersAction() noexcept = 0; virtual void onOthersAction(size_t player) noexcept = 0; virtual void onFlop() noexcept = 0; virtual void onTurn() noexcept = 0; virtual void onRiver() noexcept = 0; }; private: void registerHandler(Handler &handler) { handlers_.push_back(&handler); } std::vector<Handler *> handlers_; }; }
[ "terrelln@fb.com" ]
terrelln@fb.com
0044c75051c182a0ff04ba2b7440fd8ee70c5b9f
d9866786b5d6bf2d14aed66c3cfd511751dd1b57
/Sandbox/src/Snow/PointCloud.h
b45306dcef38058d956a4f811bff005ea8c9a081
[]
no_license
kodai100/HydronEngine
6474b710f249f47619b79ebc5c4c3240d025a198
1670c556e90b05e733fbc29ae5eaeb3ca30b3283
refs/heads/master
2023-04-21T07:45:36.947492
2021-05-07T07:49:26
2021-05-07T07:49:26
361,784,814
4
0
null
null
null
null
UTF-8
C++
false
false
3,168
h
#pragma once #include <vector> #include "SimConstants.h" #include "Particle.h" #include "Shape.h" #define AREA_EPSILON 1e-5 inline float random_number(float lo, float hi){ return lo + rand() / (float) (RAND_MAX/(hi-lo)); } class PointCloud { public: int size; float max_velocity; std::vector<Particle> particles; PointCloud(); PointCloud(int cloud_size); PointCloud(const PointCloud& orig); virtual ~PointCloud(); //Transform points in cloud void scale(Vector2f origin, Vector2f scale); void translate(Vector2f off); //Update particle data void update(); //Merge two point clouds void merge(const PointCloud& other); //Get bounding box [xmin, xmax, ymin, ymax] void bounds(float bounds[4]); void draw(); //Generate particles that fill a set of shapes static PointCloud* createShape(std::vector<Shape*>& snow_shapes){ //Compute area of all the snow shapes float area = 0; int len = snow_shapes.size(), num_shapes = 0; for (int i=0; i<len; i++){ float indi_area = snow_shapes[i]->area(); if (indi_area > AREA_EPSILON && snow_shapes[i]->vertices.size() > 2){ num_shapes++; area += indi_area; } } //If there is no volume, we can't really do a snow sim if (area < AREA_EPSILON) return NULL; //Otherwise, create our object //Calculate particle settings float particle_area = PARTICLE_DIAM*PARTICLE_DIAM, particle_mass = particle_area*DENSITY; int particles = area / particle_area; //Randomly scatter points PointCloud *obj = new PointCloud(particles); float bounds[4]; int shape_num = 0, total_points = 0; float max_vel = 0; for (int i=0; i<len; i++){ float a = snow_shapes[i]->area(); Vector2f vel = snow_shapes[i]->vel; if (vel.length_squared() > max_vel) max_vel = vel.length_squared(); if (a > AREA_EPSILON && snow_shapes[i]->vertices.size() > 2){ int points; //Points given to each shape is proportional to their area if (++shape_num < num_shapes) points = a*particles/area; //Last shape gets remainder, so we don't have round-off errors else points = particles-total_points; total_points += points; //Estimate the centroid of the shape with the bounds snow_shapes[i]->bounds(bounds); float cx = (bounds[0]+bounds[1])/2.0, cy = (bounds[2]+bounds[3])/2.0, cw = bounds[1] - cx, ch = bounds[3] - cy; //Randomly scatter points in the shape until the quota is met int points_found = 0; srand(5); while (points_found != points){ float tx = random_number(bounds[0], bounds[1]), ty = random_number(bounds[2], bounds[3]); //Check if this point is inside the shape if (snow_shapes[i]->contains(tx, ty)){ //Randomly adjust hardness of snow float adjust = (rand()/(float) RAND_MAX)*10; //Make snow hardest on the outer edges adjust *= ((fabs(tx-cx)/cw) + (fabs(ty-cy)/ch))/2.0; //Add the snow particle obj->particles.push_back(Particle(Vector2f(tx, ty), Vector2f(vel), particle_mass, LAMBDA, MU)); points_found++; } } } } //Set initial max velocity obj->max_velocity = max_vel; return obj; } };
[ "kodai100@gmail.com" ]
kodai100@gmail.com
08302da214060ab38e5c8fef0385027d88b860a7
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazetest/src/mathtest/dmatsmatmult/UDbDCa.cpp
f23c37af79ef8d8d1319500c3f51c35f5bc9ba66
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
4,536
cpp
//================================================================================================= /*! // \file src/mathtest/dmatsmatmult/UDbDCa.cpp // \brief Source file for the UDbDCa dense matrix/sparse matrix multiplication math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD 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 names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/UpperMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatsmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'UDbDCa'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using UDb = blaze::UpperMatrix< blaze::DynamicMatrix<TypeB> >; using DCa = blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeA> >; // Creator type definitions using CUDb = blazetest::Creator<UDb>; using CDCa = blazetest::Creator<DCa>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=i; ++j ) { RUN_DMATSMATMULT_OPERATION_TEST( CUDb( i ), CDCa( i, j ) ); } } // Running tests with large matrices RUN_DMATSMATMULT_OPERATION_TEST( CUDb( 31UL ), CDCa( 31UL, 7UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CUDb( 67UL ), CDCa( 67UL, 7UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CUDb( 127UL ), CDCa( 127UL, 13UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CUDb( 32UL ), CDCa( 32UL, 8UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CUDb( 64UL ), CDCa( 64UL, 8UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CUDb( 128UL ), CDCa( 128UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
95295edc81d654e997b8657ee8116f5c73ff7c50
b6de8ad7f01c9d973fe7eabc4dde57ff4d4d6160
/C++ programming/1-1 C++ basics/computer password.cpp
28a3c9b86a3f7cc5ba62606fb04daec36dbea27c
[]
no_license
seungminlll3420/C-PP
d33c6f969854e1affed57d91a260de628db62cb8
e459289d185bbb2350d1326806ede7f53a8037e0
refs/heads/master
2020-07-17T09:43:35.637688
2019-11-26T19:36:03
2019-11-26T19:36:03
205,996,375
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <iostream> #include <cstring> using namespace std; int main() { char password[11]; cout << "Please enter your computer password." << endl; while (true) { cout << "password>>"; cin >> password; if (strcmp(password, "c++") == 0) { cout << "Exit the program."; break; } else cout << "The password is wrong."; } }
[ "seungminlll3420@gmail.com" ]
seungminlll3420@gmail.com
f05bf76ad5175f3dd1c832730e02d8a584a6c153
182d0c8add424d2e273d56e50fe871bcf654f020
/core/src/storage/s3/S3IOWriter.h
0464f1ecd5de6fe7e152b6e53b8af04a8b7c8ab4
[ "BSD-3-Clause", "Zlib", "LicenseRef-scancode-unknown-license-reference", "JSON", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
jielinxu/milvus
233c70573e83dfc82f526a0c9b77ce0a086fb10d
fc8e11666f08cd421ba040c7861eac598273d1b9
refs/heads/master
2020-12-14T21:41:11.957507
2020-01-19T09:58:34
2020-01-19T09:58:34
226,777,480
0
1
Apache-2.0
2019-12-09T03:33:48
2019-12-09T03:33:47
null
UTF-8
C++
false
false
1,195
h
// 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. #pragma once #include <string> #include "storage/IOWriter.h" namespace milvus { namespace storage { class S3IOWriter : public IOWriter { public: explicit S3IOWriter(const std::string& name); ~S3IOWriter(); void write(void* ptr, size_t size) override; size_t length() override; public: std::string buffer_; }; } // namespace storage } // namespace milvus
[ "hai.jin@zilliz.com" ]
hai.jin@zilliz.com
9457246fe4296b4dc3303a25ee40b4865e686767
27162a7b844853ae69a095116e375511e8cfc6e7
/source/circle.hpp
2001701c18f8305e7eb331642d8e3702c6eeceaf
[ "MIT" ]
permissive
Fabi3nn3/programmiersprachen-aufgabenblatt-3
7c7cd4172bffe2778112de0deebb7ce27b6471c2
ac822ed6944c57d94baabbe0b2f4820c2a80fcba
refs/heads/master
2021-01-01T05:16:20.133630
2016-05-19T12:45:26
2016-05-19T12:45:26
58,547,805
0
0
null
null
null
null
UTF-8
C++
false
false
351
hpp
#ifndef CIRCLE_HPP #define CIRCLE_HPP class Circle{ public: Circle(); //const& ! Circle(float rad); void setradius(float r); //Set Radius float getradius(); // Get Radius bool operator< (Circle const& b); bool operator> (Circle const& b); bool operator== (Circle const& b); private: float rad_; }; #endif
[ "fabienne.hubricht@uni-weimar.de" ]
fabienne.hubricht@uni-weimar.de
93a12c94a100d8b0a902e873554e299fc4ed7dcc
9e5d1e9414833472f43f3616e1c140f6ed5b6ee9
/NCKU_CP/Class_contest_6/64.cpp
1bafcacb1d22c27b18976857dc134937ef36d07a
[]
no_license
junewaves/contests
a93dc3b3c1a167005fe12bb0ee6f330ac572f1c4
387860b65bdd3c1559f93c5f2d01c69ee364506e
refs/heads/master
2023-02-27T07:45:11.339127
2021-02-08T18:05:01
2021-02-08T18:05:01
254,631,323
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll a1 = 1919434LL; // * 10000000 const ll a2 = 2495775LL; // 1.1 ^ 31 const int m1 = 1e7; const int m2 = 2e5; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; while (n--) { ll b, c, d; cin >> b; d = a2 * b; c = a1 * b + d / m1; int r = (d % m1 || c % m2) ? 1 : 0; cout << c / m2 + r << '\n'; } return 0; }
[ "a0929551932@gmail.com" ]
a0929551932@gmail.com
94636954d18f8498c97218f737439b9c7f53bbdb
50f2a23b6164e4161d06547d897b979608f9b6d1
/SDK/FG_Widget_BuildMenu_InfoBox_classes.hpp
94a85ac9ef208722d886796295b3890b39a121da
[]
no_license
satisfactorymodding/SatisfactorySDK
35433a3bd19f34c7dfd0a4cf141a310be4b9d382
e9a2332e0f76b92c99d4072638c1560b8137e821
refs/heads/master
2020-05-24T11:21:41.715919
2019-10-10T07:48:30
2019-10-10T07:48:30
187,234,176
8
3
null
null
null
null
UTF-8
C++
false
false
5,549
hpp
#pragma once // Satisfactory SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "FG_Widget_BuildMenu_InfoBox_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass Widget_BuildMenu_InfoBox.Widget_BuildMenu_InfoBox_C // 0x0040 (0x0248 - 0x0208) class UWidget_BuildMenu_InfoBox_C : public UUserWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0208(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UWidgetAnimation* IconAnim; // 0x0210(0x0008) (BlueprintVisible, ExportObject, BlueprintReadOnly, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UWrapBox* mCostContainer; // 0x0218(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UTextBlock* mItemName; // 0x0220(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* mPreviewIcon; // 0x0228(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class URichTextBlock* mRichTextBlock; // 0x0230(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UWrapBox* mStatContainer; // 0x0238(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UVerticalBox* VerticalBox_5; // 0x0240(0x0008) (ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass Widget_BuildMenu_InfoBox.Widget_BuildMenu_InfoBox_C"); return ptr; } ESlateVisibility GetStatsVisibility(); void AnimateCostslots(); void ExecuteUbergraph_Widget_BuildMenu_InfoBox(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "kronosdev45@gmail.com" ]
kronosdev45@gmail.com
f9709384ff71ed3a7cf59ec1a332ff1ad4439156
28d68af73c56375314efd07eaf6a1a9241a51ce3
/aws-cpp-sdk-core/source/utils/windows/FileSystemUtils.cpp
469bac3a2d1313184a389a5d15722baef9a49722
[ "JSON", "MIT", "Apache-2.0" ]
permissive
zeliard/aws-sdk-cpp
93b560791fa359be25b201e9a6513bc3cb415046
14119f1f5bc159ce00a1332f86e117362afd3cb6
refs/heads/master
2021-01-16T22:49:18.731977
2016-01-04T01:54:38
2016-01-04T01:54:38
41,892,393
0
1
null
2015-09-04T01:35:43
2015-09-04T01:35:43
null
UTF-8
C++
false
false
3,669
cpp
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/core/utils/FileSystemUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/core/utils/StringUtils.h> #include <Userenv.h> #pragma warning( disable : 4996) using namespace Aws::Utils; static const char* LOG_TAG = "FileSystemUtils"; Aws::String FileSystemUtils::GetHomeDirectory() { static const char* HOME_DIR_ENV_VAR = "USERPROFILE"; AWS_LOGSTREAM_TRACE(LOG_TAG, "Checking " << HOME_DIR_ENV_VAR << " for the home directory."); char* homeDir = std::getenv(HOME_DIR_ENV_VAR); CHAR path[MAX_PATH]; AWS_LOGSTREAM_DEBUG(LOG_TAG, "Environment value for variable " << HOME_DIR_ENV_VAR << " is " << homeDir); if(!homeDir) { AWS_LOG_WARN(LOG_TAG, "Home dir not stored in environment, trying to fetch manually from the OS."); HANDLE hToken; if (OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &hToken)) { DWORD len = MAX_PATH; if (GetUserProfileDirectoryA(hToken, path, &len)) { homeDir = path; } CloseHandle(hToken); } AWS_LOGSTREAM_INFO(LOG_TAG, "Pulled " << homeDir << " as home directory from the OS."); } Aws::String retVal = homeDir ? StringUtils::Trim(static_cast<const char*>(homeDir)) : ""; if (!retVal.empty()) { if (retVal.at(retVal.length() - 1) != PATH_DELIM) { retVal += PATH_DELIM; } } return std::move(retVal); } bool FileSystemUtils::CreateDirectoryIfNotExists(const char* path) { AWS_LOGSTREAM_INFO(LOG_TAG, "Creating directory " << path); if (CreateDirectoryA(path, nullptr)) { AWS_LOGSTREAM_DEBUG(LOG_TAG, "Creation of directory " << path << " succeeded.") return true; } else { DWORD errorCode = GetLastError(); AWS_LOGSTREAM_DEBUG(LOG_TAG, " Creation of directory " << path << " returned code: " << errorCode); return errorCode == ERROR_ALREADY_EXISTS; } } bool FileSystemUtils::RemoveFileIfExists(const char* path) { AWS_LOGSTREAM_INFO(LOG_TAG, "Deleting file: " << path); if(DeleteFileA(path)) { AWS_LOGSTREAM_DEBUG(LOG_TAG, "Successfully deleted file: " << path); return true; } else { DWORD errorCode = GetLastError(); AWS_LOGSTREAM_DEBUG(LOG_TAG, "Deletion of file: " << path << " Returned error code: " << errorCode); return errorCode == ERROR_FILE_NOT_FOUND; } } bool FileSystemUtils::RelocateFileOrDirectory(const char* from, const char* to) { AWS_LOGSTREAM_INFO(LOG_TAG, "Moving file at " << from << " to " << to); if(MoveFileA(from, to)) { AWS_LOGSTREAM_DEBUG(LOG_TAG, "The moving operation of file at " << from << " to " << to << " Succeeded."); return true; } else { int errorCode = GetLastError(); AWS_LOGSTREAM_DEBUG(LOG_TAG, "The moving operation of file at " << from << " to " << to << " Returned error code of " << errorCode); return false; } }
[ "henso@amazon.com" ]
henso@amazon.com
9e740ee77750e1c3e6f4fe54e9c3f4df196bd8a1
72f6f0bbe19e07e684abfe953bfc36aeb5d2b692
/iterator/iterator/iterator.cpp
f23db4fb49560b312516ceef7acb1ff3367161f5
[]
no_license
AlexID-0987/Testgit
ec7ab62f0a776b63c95c19cfccc22c25aaa57b29
f707acc6e854a66f15bc0ba3068440c1971f298f
refs/heads/master
2023-08-22T15:28:37.841162
2021-09-19T18:06:40
2021-09-19T18:06:40
305,180,932
0
0
null
null
null
null
UTF-8
C++
false
false
746
cpp
// iterator.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include<string> #include<vector> int main() { std::vector<std::string>myVector = { "Resminov Alex ID76859430 Deli", "Revtov Stasha ID5465464 Parish", "Sidorov Fedul ID870689 Berlin","Petrow Rex ID897698 Warshawa" }; for (std::vector<std::string>::iterator i = myVector.begin(); i != myVector.end(); i++) { std::cout << *i << std::endl; } std::vector<std::string>::iterator it; it = myVector.begin(); it++; std::cout << *it << std::endl; it++; std::cout << *it << std::endl; it+=1; std::cout << *it << std::endl; }
[ "a1980dominov@gmail.com" ]
a1980dominov@gmail.com
28ce4190f6a8a2cc9d781c31986e2a026064ea7a
1a7e9320129984b8ee59912fa4c7782e6429e56a
/main.cpp
e31443d460a3b5215078ee450616ee052f5dcc47
[]
no_license
go2sea/DesignPattern
de64843c6086e90fc9b783d874a90feca16fe300
0c3a5e6b965a579613246bb117f0bd746070c21f
refs/heads/master
2021-01-10T10:50:10.388053
2016-01-04T14:38:47
2016-01-04T14:38:47
49,001,993
0
0
null
null
null
null
GB18030
C++
false
false
5,712
cpp
#pragma once #include <iostream> #include "Factory.h" #include "AbstractFactory.h" #include "Prototype.h" #include "Builder.h" #include "Singleton.h" #include "Adapter.h" #include "Bridge.h" #include "Decorator.h" #include "Proxy.h" #include "TemplateMethod.h" #include "Composite.h" #include "ChainOfResponsibility.h" #include "Flyweight.h" #include "Command.h" #include "Observer.h" #include "Strategy.h" #include "State.h" #include "Iterator.h" #include "Memento.h" #include "Visitor.h" using namespace std; void main() { //printf("%s\n\n", "This is an example of Factory-Method pattern:"); //Factory* fa = new FactoryA(); //Product* pa = fa->createProduct(); //Factory* fb = new FactoryB(); //Product* pb = fb->createProduct(); //printf("%s\n\n", "This is an example of Abstract-Factory pattern:"); ////锤子科技生产 //AbstractFactory* smartisan = new Smartisan(); //AbstractSOC* sm_soc = smartisan->createSOC(); //AbstractScreen* sm_screen = smartisan->createScreen(); ////小米科技生产 //AbstractFactory* mi = new Mi(); //AbstractSOC* mi_soc = mi->createSOC(); //AbstractScreen* mi_screen = mi->createScreen(); //printf("%s\n\n", "This is an example of Prototype pattern:"); //Prototype* p1 = new ConcretePrototypeA(); //Prototype* p1_copy = p1->clone(); //Prototype* p2 = new ConcretePrototypeB(); //Prototype* p2_copy = p2->clone(); //printf("%s\n\n", "This is an example of Builder pattern:"); ////锤子手机build //Director* sm_dr = new Director(new SmartisanBuilder()); //sm_dr->build(); ////小米手机build //Director* mi_dr = new Director(new MiBuilder()); //mi_dr->build(); //printf("%s\n\n", "This is an example of Singleton pattern::"); //Singleton::getInstance().test(); //printf("%s\n\n", "This is an example of Adapter pattern:"); //Adaptee* a = new Adaptee(); //Target* t = new Adapter(a); //t->Request(); //printf("%s\n\n", "This is an example of Bridge pattern:"); //Music* midian = new MiDian(); //Music* xiushuijie = new XiuShuiJie(); //Phone* t1 = new T1(midian); //Phone* t2 = new T2(xiushuijie); //t1->ring(); //t2->ring(); //printf("%s\n\n", "This is an example of Decorator pattern:"); //IphoneComponent* ip6 = new Iphone6(); //IphoneComponent* ip6s = new Iphone6s(ip6); //ip6s->multiTouch(); //printf("%s\n\n", "This is an example of Proxy pattern:"); //Subject* pro = new Proxy(); //pro->Request(); //pro->Request(); //printf("%s\n\n", "This is an example of Composite Pattern:"); //Composite* sm = new SmartisanT1(); //Leaf* soc = new SOC(); //Leaf* screen = new Screen(); //sm->add(soc); //sm->add(screen); //sm->sales(); //sm->remove(soc); //sm->sales(); //sm->remove(sm->getChild(0)); //sm->sales(); //printf("%s\n\n", "This is am example of Template-Method pattern:"); //ConcreteAlgorithm* ca = new ConcreteAlgorithm(); //ca->templateMethod(); //printf("%s\n\n", "This is an example of ChainOfResponsibility pattern:"); //Handler* h1 = new ConcreteHandler1(); ////h1作为h2的successor //Handler* h2 = new ConcreteHandler2(h1); //h2->handleRequest(); //printf("%s\n\n", "This is an example of Flyweight pattern:"); //FlyweightFactory* ff = new FlyweightFactory(); //ff->getFlyweight("ConcreteFlyweight1"); //ff->getFlyweight("ConcreteFlyweight1"); //ff->getFlyweight("ConcreteFlyweight2"); //ff->getFlyweight("ConcreteFlyweight2"); //printf("%s\n\n", "This is an example of Command pattern"); //Receiver* receiver = new Receiver(); //Command* command = new ConcreteCommand(receiver); //Invoker* invoker = new Invoker(command); //invoker->invoke(); //delete invoker; //printf("%s\n\n", "This is an example of Observer pattern:"); //Observer* ob1 = new ConcreteObserver(); //Observer* ob2 = new ConcreteObserver(); //SSubject* sub = new ConcreteSSubject(); //sub->attach(ob1); //sub->attach(ob2); //sub->attach(ob1); //sub->attach(ob2); //sub->setState(1); //sub->notify(); //sub->detach(ob1); //sub->setState(2); //sub->notify(); //delete sub; //sub = NULL; //ob1 = NULL; //ob2 = NULL; //printf("%s\n\n", "This is an example of Strategy pattern:"); //Traverse* dfs = new DFS(); //Context* context = new Context(dfs); //context->process(); //delete context; //context = NULL; //dfs = NULL; //printf("%s\n\n", "This is an example of State pattern:"); //State* hungry = new Hungry(); //State* thirsty = new Thirsty(); //Man* man = new Man(hungry); //man->handle(); //man->changeState(thirsty); //man->handle(); //delete man; //man = NULL; //thirsty = NULL; //delete hungry; //hungry = NULL; //printf("%s\n\n", "This is an example of Iterator pattern:"); //Aggregate* aggregate = new ConcreteAggregate(5); //Iterator* it = new ConcreteIterator(aggregate); //it->first(); //for (; !it->isDone(); it->next()) // printf("%d\n", it->currentItem()); //delete it; //it = NULL; //printf("%s\n\n", "This is an example of Memento pattern:"); //Originator* pOriginator = new Originator("Old State!"); //Memento* pMemento = pOriginator->createMemento(); //pOriginator->printState(); //pOriginator->setState("New State!"); //pOriginator->printState(); //pOriginator->restoreState(pMemento); //pOriginator->printState(); //delete pOriginator; //pOriginator = NULL; //delete pMemento;//默认析构函数是public的 //pMemento = NULL; printf("%s\n\n", "This is an example of Visitor pattern:"); Visitor* pVisitor1 = new ConcreteVisitor1(); Visitor* pVisitor2 = new ConcreteVisitor2(); Element* pElementA = new ConcreteElementA(); Element* pElementB = new ConcreteElementB(); pElementA->accept(pVisitor1); pElementA->accept(pVisitor2); pElementB->accept(pVisitor1); pElementB->accept(pVisitor2); system("pause"); }
[ "412183136@qq.com" ]
412183136@qq.com
c06147494d08b12c9f07c9beb3b58267ea91ec99
6e25ca122e98dc53738cc150556cfa4e4833ba4b
/src/cxx.cc
da05ee2f79f2d4f6d55511c8c7bf5818a5f78f52
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BLQ5/cxx
4c8832a0202dd8bc1e2c0e42431b03ca48ab7686
041c9040ba4f678e87622ea59515e16f35eeb1e5
refs/heads/master
2022-12-04T00:22:22.154442
2020-08-26T05:16:15
2020-08-26T05:16:15
290,582,317
1
0
NOASSERTION
2020-08-26T19:07:26
2020-08-26T19:07:25
null
UTF-8
C++
false
false
11,729
cc
#include "../include/cxx.h" #include <cstring> #include <exception> #include <iostream> #include <memory> #include <stdexcept> #include <vector> template <typename Exception> static void panic [[noreturn]] (const char *msg) { #if defined(RUST_CXX_NO_EXCEPTIONS) std::cerr << "Error: " << msg << ". Aborting." << std::endl; std::terminate(); #else throw Exception(msg); #endif } extern "C" { const char *cxxbridge03$cxx_string$data(const std::string &s) noexcept { return s.data(); } size_t cxxbridge03$cxx_string$length(const std::string &s) noexcept { return s.length(); } // rust::String void cxxbridge03$string$new(rust::String *self) noexcept; void cxxbridge03$string$clone(rust::String *self, const rust::String &other) noexcept; bool cxxbridge03$string$from(rust::String *self, const char *ptr, size_t len) noexcept; void cxxbridge03$string$drop(rust::String *self) noexcept; const char *cxxbridge03$string$ptr(const rust::String *self) noexcept; size_t cxxbridge03$string$len(const rust::String *self) noexcept; // rust::Str bool cxxbridge03$str$valid(const char *ptr, size_t len) noexcept; } // extern "C" namespace rust { inline namespace cxxbridge03 { String::String() noexcept { cxxbridge03$string$new(this); } String::String(const String &other) noexcept { cxxbridge03$string$clone(this, other); } String::String(String &&other) noexcept { this->repr = other.repr; cxxbridge03$string$new(&other); } String::~String() noexcept { cxxbridge03$string$drop(this); } String::String(const std::string &s) : String(s.data(), s.length()) {} String::String(const char *s) : String(s, std::strlen(s)) {} String::String(const char *s, size_t len) { if (!cxxbridge03$string$from(this, s, len)) { panic<std::invalid_argument>("data for rust::String is not utf-8"); } } String &String::operator=(const String &other) noexcept { if (this != &other) { cxxbridge03$string$drop(this); cxxbridge03$string$clone(this, other); } return *this; } String &String::operator=(String &&other) noexcept { if (this != &other) { cxxbridge03$string$drop(this); this->repr = other.repr; cxxbridge03$string$new(&other); } return *this; } String::operator std::string() const { return std::string(this->data(), this->size()); } const char *String::data() const noexcept { return cxxbridge03$string$ptr(this); } size_t String::size() const noexcept { return cxxbridge03$string$len(this); } size_t String::length() const noexcept { return cxxbridge03$string$len(this); } String::String(unsafe_bitcopy_t, const String &bits) noexcept : repr(bits.repr) {} std::ostream &operator<<(std::ostream &os, const String &s) { os.write(s.data(), s.size()); return os; } Str::Str() noexcept : repr(Repr{reinterpret_cast<const char *>(this), 0}) {} Str::Str(const Str &) noexcept = default; Str::Str(const std::string &s) : Str(s.data(), s.length()) {} Str::Str(const char *s) : Str(s, std::strlen(s)) {} Str::Str(const char *s, size_t len) : repr(Repr{s, len}) { if (!cxxbridge03$str$valid(this->repr.ptr, this->repr.len)) { panic<std::invalid_argument>("data for rust::Str is not utf-8"); } } Str &Str::operator=(Str other) noexcept { this->repr = other.repr; return *this; } Str::operator std::string() const { return std::string(this->data(), this->size()); } const char *Str::data() const noexcept { return this->repr.ptr; } size_t Str::size() const noexcept { return this->repr.len; } size_t Str::length() const noexcept { return this->repr.len; } Str::Str(Repr repr_) noexcept : repr(repr_) {} Str::operator Repr() noexcept { return this->repr; } std::ostream &operator<<(std::ostream &os, const Str &s) { os.write(s.data(), s.size()); return os; } extern "C" { const char *cxxbridge03$error(const char *ptr, size_t len) { char *copy = new char[len]; strncpy(copy, ptr, len); return copy; } } // extern "C" Error::Error(Str::Repr msg) noexcept : msg(msg) {} Error::Error(const Error &other) { this->msg.ptr = cxxbridge03$error(other.msg.ptr, other.msg.len); this->msg.len = other.msg.len; } Error::Error(Error &&other) noexcept { delete[] this->msg.ptr; this->msg = other.msg; other.msg.ptr = nullptr; other.msg.len = 0; } Error::~Error() noexcept { delete[] this->msg.ptr; } const char *Error::what() const noexcept { return this->msg.ptr; } } // namespace cxxbridge03 } // namespace rust extern "C" { void cxxbridge03$unique_ptr$std$string$null( std::unique_ptr<std::string> *ptr) noexcept { new (ptr) std::unique_ptr<std::string>(); } void cxxbridge03$unique_ptr$std$string$raw(std::unique_ptr<std::string> *ptr, std::string *raw) noexcept { new (ptr) std::unique_ptr<std::string>(raw); } const std::string *cxxbridge03$unique_ptr$std$string$get( const std::unique_ptr<std::string> &ptr) noexcept { return ptr.get(); } std::string *cxxbridge03$unique_ptr$std$string$release( std::unique_ptr<std::string> &ptr) noexcept { return ptr.release(); } void cxxbridge03$unique_ptr$std$string$drop( std::unique_ptr<std::string> *ptr) noexcept { ptr->~unique_ptr(); } } // extern "C" #define STD_VECTOR_OPS(RUST_TYPE, CXX_TYPE) \ size_t cxxbridge03$std$vector$##RUST_TYPE##$size( \ const std::vector<CXX_TYPE> &s) noexcept { \ return s.size(); \ } \ const CXX_TYPE *cxxbridge03$std$vector$##RUST_TYPE##$get_unchecked( \ const std::vector<CXX_TYPE> &s, size_t pos) noexcept { \ return &s[pos]; \ } \ void cxxbridge03$unique_ptr$std$vector$##RUST_TYPE##$null( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(); \ } \ void cxxbridge03$unique_ptr$std$vector$##RUST_TYPE##$raw( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr, \ std::vector<CXX_TYPE> *raw) noexcept { \ new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(raw); \ } \ const std::vector<CXX_TYPE> \ *cxxbridge03$unique_ptr$std$vector$##RUST_TYPE##$get( \ const std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ return ptr.get(); \ } \ std::vector<CXX_TYPE> \ *cxxbridge03$unique_ptr$std$vector$##RUST_TYPE##$release( \ std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ return ptr.release(); \ } \ void cxxbridge03$unique_ptr$std$vector$##RUST_TYPE##$drop( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ ptr->~unique_ptr(); \ } #define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \ void cxxbridge03$rust_vec$##RUST_TYPE##$new( \ rust::Vec<CXX_TYPE> *ptr) noexcept; \ void cxxbridge03$rust_vec$##RUST_TYPE##$drop( \ rust::Vec<CXX_TYPE> *ptr) noexcept; \ size_t cxxbridge03$rust_vec$##RUST_TYPE##$len( \ const rust::Vec<CXX_TYPE> *ptr) noexcept; \ const CXX_TYPE *cxxbridge03$rust_vec$##RUST_TYPE##$data( \ const rust::Vec<CXX_TYPE> *ptr) noexcept; \ size_t cxxbridge03$rust_vec$##RUST_TYPE##$stride() noexcept; #define RUST_VEC_OPS(RUST_TYPE, CXX_TYPE) \ template <> \ Vec<CXX_TYPE>::Vec() noexcept { \ cxxbridge03$rust_vec$##RUST_TYPE##$new(this); \ } \ template <> \ void Vec<CXX_TYPE>::drop() noexcept { \ return cxxbridge03$rust_vec$##RUST_TYPE##$drop(this); \ } \ template <> \ size_t Vec<CXX_TYPE>::size() const noexcept { \ return cxxbridge03$rust_vec$##RUST_TYPE##$len(this); \ } \ template <> \ const CXX_TYPE *Vec<CXX_TYPE>::data() const noexcept { \ return cxxbridge03$rust_vec$##RUST_TYPE##$data(this); \ } \ template <> \ size_t Vec<CXX_TYPE>::stride() noexcept { \ return cxxbridge03$rust_vec$##RUST_TYPE##$stride(); \ } // Usize and isize are the same type as one of the below. #define FOR_EACH_NUMERIC(MACRO) \ MACRO(u8, uint8_t) \ MACRO(u16, uint16_t) \ MACRO(u32, uint32_t) \ MACRO(u64, uint64_t) \ MACRO(i8, int8_t) \ MACRO(i16, int16_t) \ MACRO(i32, int32_t) \ MACRO(i64, int64_t) \ MACRO(f32, float) \ MACRO(f64, double) #define FOR_EACH_STD_VECTOR(MACRO) \ FOR_EACH_NUMERIC(MACRO) \ MACRO(usize, size_t) \ MACRO(isize, rust::isize) #define FOR_EACH_RUST_VEC(MACRO) \ FOR_EACH_NUMERIC(MACRO) \ MACRO(bool, bool) extern "C" { FOR_EACH_STD_VECTOR(STD_VECTOR_OPS) FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS) } // extern "C" namespace rust { inline namespace cxxbridge03 { FOR_EACH_RUST_VEC(RUST_VEC_OPS) } // namespace cxxbridge03 } // namespace rust
[ "dtolnay@gmail.com" ]
dtolnay@gmail.com
8ee5f6dc3b03fa2bdf7cc0b56ee05d0da23b406f
e1efe8a7dbf1544565cc1702ea0230537d1be62f
/programmes codeforces/Bulbs.cpp
ede669718d122c1637688ff477e1f2ae97912dd0
[]
no_license
Sourav9063/Cpp-All-codes
d99061666b2d40961e458c95d7e436388a351eec
06369df7b5f7b9a4b091a49a74722ea41761914d
refs/heads/master
2023-03-08T09:25:18.843800
2023-02-06T15:19:29
2023-02-06T15:19:29
243,684,953
2
0
null
null
null
null
UTF-8
C++
false
false
1,642
cpp
// Name: https://codeforces.com/problemset/problem/615/A #include <bits/stdc++.h> using namespace std; #define ll long long int //lld #define ull unsigned long long int //llu #define pt cout << "*" \ << "\n"; #define nl cout << "\n"; #define deb(x) cout << #x << "=" << x << "\n"; #define pb(a) emplace_back(a) #define all(x) (x).begin(), (x).end() #define rSort(x) sort((x).rbegin(), (x).rend()) #define Sourav \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); //template<typename... T>void read(T&... args) {((cin >> args), ...);} template <class T> inline void sarray(T *st, T *nd) { while (st < nd) cin >> *st++; /*sf("%d", st++);*/ } template <class T> inline void parray(T *st, T *nd) { while (st < nd) cout << *st++ << endl; /*sf("%d", st++);*/ } ll tmp, ans; int main() { Sourav; #ifndef ONLINE_JUDGE freopen("C:\\Users\\my_code\\input.in", "r", stdin); freopen("C:\\Users\\my_code\\output.in", "w", stdout); #endif int n, m; cin >> n >> m; bool ar[m + 1]; for (int i = 1; i <= m; i++) { ar[i] = false; } for (int i = 0; i < n; i++) { int l; cin >> l; for (int i = 0; i < l; i++) { cin >> tmp; ar[tmp] = true; } } bool a = true; for (int i = 1; i <= m; i++) { if (ar[i] == false) { a = false; break; }; } cout << (a ? "YES" : "NO") << endl; return 0; } /* Documentation: */
[ "53114581+Sourav9063@users.noreply.github.com" ]
53114581+Sourav9063@users.noreply.github.com
e9bce2b539abdc73fe43caa6146760776568e437
46f1a4060d00334f3a655b340e4afb211d413686
/Triangle.cc
609165151fb9bb850c3c44932233df1cafe965f0
[]
no_license
BrianPopeck/render
da477c69de925c17c9f48aa1af8542dcb507e83b
c5929f48e7bcd7c48221c01d32158f4fa0d1d194
refs/heads/master
2022-08-15T21:35:20.202750
2020-05-19T01:51:55
2020-05-19T01:51:55
261,857,168
0
0
null
null
null
null
UTF-8
C++
false
false
201
cc
#include "Triangle.h" Triangle::Triangle(const Vector3& p0, const Vector3& p1, const Vector3& p2): vertices{p0, p1, p2} {} const Vector3& Triangle::getVertex(int i) const { return vertices[i]; }
[ "bpopeck4@gmail.com" ]
bpopeck4@gmail.com
f13a38988343ee62c7314886d719fc618586f69c
3c65f0944a3045486fca92a190eb7839d9e2684f
/read_write.cpp
eeb46fae463dcf3eb4b15646f0be3c87941e0636
[]
no_license
AlexeyMakurin/twist-feronematic
1fdd00c7e645716cc903c37a64a003940f085056
febc43bda31ea3220e2a00e1df38ce9a12082801
refs/heads/twist-ferronematic_nmsm
2023-05-21T21:38:23.604790
2021-06-09T07:56:46
2021-06-09T07:56:46
372,394,155
0
0
null
2021-06-09T07:59:01
2021-05-31T05:39:06
C++
UTF-8
C++
false
false
1,480
cpp
#include "read_write.h" void write(const TwistFerronematic& twist_feronematic) { std::filesystem::create_directory("results"); std::filesystem::path dir("results"); std::filesystem::path file_name(twist_feronematic.Name() + ".csv"); std::filesystem::path path_to_file = dir / file_name; std::ofstream file; file.open(path_to_file); file << "zeta" << "," << "phi" << "," << "psi" << "," << "g" << "\n"; for (size_t i = 0; i < twist_feronematic.Zeta().size(); ++i) { file.precision(7); file << twist_feronematic.Zeta()[i] << "," << twist_feronematic.Phi()[i] << "," << twist_feronematic.Psi()[i] << "," << twist_feronematic.G()[i] << "\n"; } file.close(); } std::vector<std::pair<std::set<double>, TwistFerronematic>> parse_json(char* argv[]) { std::ifstream input(argv[1]); nlohmann::json objJson; input >> objJson; objJson = objJson["twist_ferronematics"]; std::vector<std::pair<std::set<double>, TwistFerronematic>> reader; std::set<double> h; for (auto& twist_ferronematic : objJson) { h = twist_ferronematic["h"].get<std::set<double>>(); TwistFerronematic tw( twist_ferronematic["configuration"]["alpha"].get<double>(), twist_ferronematic["configuration"]["b"].get<double>(), twist_ferronematic["configuration"]["sigma"].get<double>(), twist_ferronematic["configuration"]["kappa"].get<double>(), twist_ferronematic["configuration"]["nodes"].get<int>() ); reader.push_back(std::make_pair(h, tw)); } return reader; }
[ "makurin-1997@mail.ru" ]
makurin-1997@mail.ru
e1785beb6d86bf9e86cb5f71b366cbabb25e8984
41b4adb10cc86338d85db6636900168f55e7ff18
/aws-cpp-sdk-support/include/aws/support/model/AttachmentDetails.h
32f12256d88f7cd9b7f10064ef37cf553c8bfb61
[ "JSON", "MIT", "Apache-2.0" ]
permissive
totalkyos/AWS
1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80
7cb444814e938f3df59530ea4ebe8e19b9418793
refs/heads/master
2021-01-20T20:42:09.978428
2016-07-16T00:03:49
2016-07-16T00:03:49
63,465,708
1
1
null
null
null
null
UTF-8
C++
false
false
3,802
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/support/Support_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Support { namespace Model { /** * <p>The file name and ID of an attachment to a case communication. You can use * the ID to retrieve the attachment with the <a>DescribeAttachment</a> * operation.</p> */ class AWS_SUPPORT_API AttachmentDetails { public: AttachmentDetails(); AttachmentDetails(const Aws::Utils::Json::JsonValue& jsonValue); AttachmentDetails& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The ID of the attachment.</p> */ inline const Aws::String& GetAttachmentId() const{ return m_attachmentId; } /** * <p>The ID of the attachment.</p> */ inline void SetAttachmentId(const Aws::String& value) { m_attachmentIdHasBeenSet = true; m_attachmentId = value; } /** * <p>The ID of the attachment.</p> */ inline void SetAttachmentId(Aws::String&& value) { m_attachmentIdHasBeenSet = true; m_attachmentId = value; } /** * <p>The ID of the attachment.</p> */ inline void SetAttachmentId(const char* value) { m_attachmentIdHasBeenSet = true; m_attachmentId.assign(value); } /** * <p>The ID of the attachment.</p> */ inline AttachmentDetails& WithAttachmentId(const Aws::String& value) { SetAttachmentId(value); return *this;} /** * <p>The ID of the attachment.</p> */ inline AttachmentDetails& WithAttachmentId(Aws::String&& value) { SetAttachmentId(value); return *this;} /** * <p>The ID of the attachment.</p> */ inline AttachmentDetails& WithAttachmentId(const char* value) { SetAttachmentId(value); return *this;} /** * <p>The file name of the attachment.</p> */ inline const Aws::String& GetFileName() const{ return m_fileName; } /** * <p>The file name of the attachment.</p> */ inline void SetFileName(const Aws::String& value) { m_fileNameHasBeenSet = true; m_fileName = value; } /** * <p>The file name of the attachment.</p> */ inline void SetFileName(Aws::String&& value) { m_fileNameHasBeenSet = true; m_fileName = value; } /** * <p>The file name of the attachment.</p> */ inline void SetFileName(const char* value) { m_fileNameHasBeenSet = true; m_fileName.assign(value); } /** * <p>The file name of the attachment.</p> */ inline AttachmentDetails& WithFileName(const Aws::String& value) { SetFileName(value); return *this;} /** * <p>The file name of the attachment.</p> */ inline AttachmentDetails& WithFileName(Aws::String&& value) { SetFileName(value); return *this;} /** * <p>The file name of the attachment.</p> */ inline AttachmentDetails& WithFileName(const char* value) { SetFileName(value); return *this;} private: Aws::String m_attachmentId; bool m_attachmentIdHasBeenSet; Aws::String m_fileName; bool m_fileNameHasBeenSet; }; } // namespace Model } // namespace Support } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
1193a4747bf8829379bbbfc4bca770f64af86f8b
c7ad1dd84604e275ebfc5a7e354b23ceb598fca5
/src/app/cn3d/conservation_colorer.hpp
6149c3bd62f5c91df021f0949a6d9dc140cf9481
[]
no_license
svn2github/ncbi_tk
fc8cfcb75dfd79840e420162a8ae867826a3d922
c9580988f9e5f7c770316163adbec8b7a40f89ca
refs/heads/master
2023-09-03T12:30:52.531638
2017-05-15T14:17:27
2017-05-15T14:17:27
60,197,012
1
1
null
null
null
null
UTF-8
C++
false
false
5,408
hpp
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Paul Thiessen * * File Description: * Classes to color alignment blocks by sequence conservation * * =========================================================================== */ #ifndef CN3D_CONSERVATION_COLORER__HPP #define CN3D_CONSERVATION_COLORER__HPP #include <corelib/ncbistl.hpp> #include <map> #include <vector> #include "vector_math.hpp" #include "cn3d_colors.hpp" BEGIN_SCOPE(Cn3D) class UngappedAlignedBlock; class BlockMultipleAlignment; class ConservationColorer { private: const BlockMultipleAlignment *alignment; typedef std::map < const UngappedAlignedBlock *, std::vector < int > > BlockMap; BlockMap blocks; typedef std::map < char, int > ColumnProfile; typedef std::vector < ColumnProfile > AlignmentProfile; AlignmentProfile alignmentProfile; int GetProfileIndex(const UngappedAlignedBlock *block, int blockColumn) const { return blocks.find(block)->second[blockColumn]; } void GetProfileIndexAndResidue(const UngappedAlignedBlock *block, int blockColumn, int row, int *profileIndex, char *residue) const; int nColumns; bool basicColorsCurrent, fitColorsCurrent; void CalculateBasicConservationColors(void); void CalculateFitConservationColors(void); std::vector < bool > identities; typedef std::vector < Vector > ColumnColors; ColumnColors varietyColors, weightedVarietyColors, informationContentColors; typedef std::map < char, Vector > ResidueColors; typedef std::vector < ResidueColors > FitColors; FitColors fitColors; typedef std::map < const UngappedAlignedBlock * , std::vector < Vector > > BlockFitColors; BlockFitColors blockFitColors, blockZFitColors, blockRowFitColors; public: ConservationColorer(const BlockMultipleAlignment *parent); // add an aligned block to the profile void AddBlock(const UngappedAlignedBlock *block); // frees memory used by color storage (but keeps blocks around) void FreeColors(void); // clears everything, including alignment blocks void Clear(void); // color accessors const Vector *GetIdentityColor(const UngappedAlignedBlock *block, int blockColumn) { CalculateBasicConservationColors(); return GlobalColors()->Get(Colors::eConservationMap, (identities[GetProfileIndex(block, blockColumn)] ? Colors::nConservationMap - 1 : 0)); } const Vector *GetVarietyColor(const UngappedAlignedBlock *block, int blockColumn) { CalculateBasicConservationColors(); return &(varietyColors[GetProfileIndex(block, blockColumn)]); } const Vector *GetWeightedVarietyColor(const UngappedAlignedBlock *block, int blockColumn) { CalculateBasicConservationColors(); return &(weightedVarietyColors[GetProfileIndex(block, blockColumn)]); } const Vector *GetInformationContentColor(const UngappedAlignedBlock *block, int blockColumn) { CalculateBasicConservationColors(); return &(informationContentColors[GetProfileIndex(block, blockColumn)]); } const Vector *GetFitColor(const UngappedAlignedBlock *block, int blockColumn, int row) { int profileIndex; char residue; CalculateFitConservationColors(); GetProfileIndexAndResidue(block, blockColumn, row, &profileIndex, &residue); return &(fitColors[profileIndex].find(residue)->second); } const Vector *GetBlockFitColor(const UngappedAlignedBlock *block, int row) { CalculateFitConservationColors(); return &(blockFitColors.find(block)->second[row]); } const Vector *GetBlockZFitColor(const UngappedAlignedBlock *block, int row) { CalculateFitConservationColors(); return &(blockZFitColors.find(block)->second[row]); } const Vector *GetBlockRowFitColor(const UngappedAlignedBlock *block, int row) { CalculateFitConservationColors(); return &(blockRowFitColors.find(block)->second[row]); } }; // screen residue to be in ncbistdaa extern char ScreenResidueCharacter(char original); END_SCOPE(Cn3D) #endif // CN3D_CONSERVATION_COLORER__HPP
[ "thiessen@112efe8e-fc92-43c6-89b6-d25c299ce97b" ]
thiessen@112efe8e-fc92-43c6-89b6-d25c299ce97b
30ddcafdb280533c0f6a08d74f7818e3e06c5adf
07ec50b64e3a2d7570a0fe964ce6fdf7216fb70d
/modular_a_star/modular_a_star.h
173a2e9c808c664cf82b8816cd776ced9b9952f4
[]
no_license
Forrest-Z/modular-A-star
8cef7e09f9a97abefdfbf6a4889cff381509647d
f5a357cc98dab926939d92eac9c743c7470fe29a
refs/heads/master
2020-04-14T23:11:27.119446
2018-11-20T23:18:10
2018-11-20T23:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,286
h
#ifndef MODULAR_A_STAR_H #define MODULAR_A_STAR_H #include <iostream> #include <vector> #include "map.h" /** Path Planner namespace */ namespace pp { /** A Star algorithm - Path planner solver */ template<typename stateT, int nbStates> class A_Star { public: /** A* Contrustor takes as input a reference to a state */ A_Star(const IMap<stateT>& map) : mMap(map) {} /** Search for path from start to goal. * Expands the state provided as class template argument at each step. * * @param[in] grid Grid map with all possible and impossible locations * @param[out] pathToGoal Path taken from beginning to the end * @param[in] start Starting state * @param[in|out] goal Goal to reach as inputs comes out as the reach state if success. * * @return Bool if final state has been reached, False otherwise */ bool search( std::vector<std::vector<int> >& grid , std::vector<std::vector<std::vector<stateT> > >& pathToGoal , stateT start , stateT& goal ) { // Tri dimensional vector for storing all spacial positions on the grid // as well as the states within each positions that have been visited and closed. mClosed = std::vector<std::vector<std::vector<int> > >( nbStates , std::vector<std::vector<int> >(grid.size() , std::vector<int>(grid[0].size()))); // Tri dimensional vector for storing all states to be expanded. pathToGoal = std::vector<std::vector<std::vector<stateT> > >( nbStates , std::vector<std::vector<stateT> >(grid.size() , std::vector<stateT>(grid[0].size()))); // Set the first state as visited mClosed[start.getInternalState()][start.getX()][start.getY()] = visited; pathToGoal[start.getInternalState()][start.getX()][start.getY()] = start; // Count number of expansions int closedCount = 1; // Stack all states to be visited std::vector<stateT> opened = { start }; stateT currentState; while(!opened.empty()) { // Sort possible next steps to always expand towards the closest to the goal std::sort(opened.begin(), opened.end()); currentState = opened[0]; opened.erase(opened.begin()); //std::cout << currentState.getX() << " " << currentState.getY() << "\n"; if (currentState.hasReached(goal)) { std::cout << "Found path to goal in " << closedCount << " expansions.\n"; // Return the final state by replacing the goal input argument goal = currentState; return true; } // Expand state to get all next possible states from current one std::vector<stateT*> nextStates; currentState.expand(nextStates, goal); for(auto& next : nextStates) { // If next state is not accessible, it is not added to the next possible states to visit if (!mMap.isAccessible(*next)) continue; if ( mClosed[next.getInternalState()][next.getX()][next.getY()] == accessibleLocation && (grid[next.getX()][next.getY()] == accessibleLocation || grid[next.getX()][next.getY()] == end) ) { opened.push_back(next); mClosed[next.getInternalState()][next.getX()][next.getY()] = visited; pathToGoal[next.getInternalState()][next.getX()][next.getY()] = currentState; ++closedCount; } } } // If we end up here it's because no path was found. std::cout << "No valid path found.\n"; goal = currentState; return false; } /** Uses the 3D vector of past locations and states to reconstruct the path * * @return Path Sequence of states from the end to the beginning. */ std::vector<stateT> reconstructPath(std::vector<std::vector<std::vector<stateT> > > from, stateT start, stateT end) { std::vector<stateT> path = { end }; int internalState = end.getInternalState(); stateT current = from[internalState][end.getX()][end.getY()]; internalState = current.getInternalState(); while (!current.hasReached(start)) { path.push_back(current); current = from[internalState][current.getX()][current.getY()]; internalState = current.getInternalState(); } path.push_back(current); return path; } /** * Get function to avoid overloading the search method with parameters. */ void getClosedStates(std::vector<std::vector<std::vector<int> > >& closed) { closed = mClosed; } private: const IMap<stateT>& mMap; ///< Map object able to tell wheather the state is valid or not and signal when the goal has been reached. std::vector<std::vector<std::vector<int> > > mClosed; ///< Set of all closed states to prevent revisiting them. }; } // END: pp #endif
[ "granie.guillaume@gmail.com" ]
granie.guillaume@gmail.com
cba720a81a1423e7eb3bc6ec4ddd98f7feb77b48
50c3e66d5a505f0a5ff5c25bb87c83c2d2171283
/test/test_output.cpp
a99d0ba99545a082b6b2dc2a13c4ffd4f656ea2f
[ "MIT" ]
permissive
firefly1250/nano-cereal
6b0813ffcfe026d5adfdb8f6ad3ce8f98351b739
e8421d6759385f7c70fa1d02fffe73e7c13ba6fd
refs/heads/main
2023-06-03T11:40:36.200087
2021-06-19T08:47:19
2021-06-19T08:47:19
378,214,829
0
0
null
null
null
null
UTF-8
C++
false
false
1,067
cpp
#include <nano-cereal/binary.hpp> #include <cereal/archives/binary.hpp> #include <iostream> struct MyRecord { uint8_t x; int y[5]; enum E { a, b, c, d, e, f } z; template <class Archive> void serialize(Archive &ar) { ar(x, y, z); } bool operator==(const MyRecord &m) { if (x != m.x) return false; for (int i = 0; i < 5; i++) if (y[i] != m.y[i]) return false; if (z != m.z) return false; return true; } }; int main() { etl::deque<uint8_t, 100> buf; MyRecord output_data; MyRecord input_data; // output { output_data.x = 24; output_data.y[3] = 5; output_data.z = MyRecord::E::d; nanocereal::ostream os(&buf); nanocereal::BinaryOutputArchive archive(os); archive(output_data); } std::string str; std::copy(buf.begin(), buf.end(), std::back_inserter(str)); std::stringstream ss; ss << str; // input { cereal::BinaryInputArchive archive(ss); archive(input_data); } const auto result = output_data == input_data; std::cout << result << std::endl; return 0; }
[ "ynhrt1250@gmail.com" ]
ynhrt1250@gmail.com
23b97277f3a966c6296ed7154b6a4689fa265f51
14a8e2b7c1c7e89dde8e1b840be5bcf8672599cc
/HandDetector_Native/HDStreamSink.cpp
e4e0075e8ee388b7fa30e631dd36f7bca2ef2da2
[]
no_license
MickaelSERENO/HoloLens_HandDetector
bf2acc6c4490c76722104c94e1637646009e038e
d1d72b89909f3d819f928576023f99233d05a160
refs/heads/master
2020-05-29T16:51:37.129979
2020-02-14T15:39:11
2020-02-14T15:39:11
189,260,453
0
0
null
null
null
null
UTF-8
C++
false
false
21,326
cpp
#include "HDStreamSink.h" #include <string> #include "ICameraIntrinsics.h" #include "utils.h" namespace Sereno { // Class-static matrix of operations vs states. // If an entry is TRUE, the operation is valid from that state. BOOL HDStreamSink::validStateMatrix[State_Count][Op_Count] = { // States: Operations: // SetType Start Restart Pause Stop Sample Marker /* NotSet */ TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, /* Ready */ TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, /* Start */ TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, /* Pause */ TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, /* Stop */ TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, }; HDStreamSink::HDStreamSink() : m_workQueueCB(this, &HDStreamSink::OnDispatchWorkItem) { TRACE(L"In Constructor\n") } HDStreamSink::~HDStreamSink() { TRACE(L"In Destructor\n"); } IFACEMETHODIMP_(ULONG) HDStreamSink::AddRef() { TRACE(L"In AddRef\n") return InterlockedIncrement(&m_cRef); } IFACEMETHODIMP_(ULONG) HDStreamSink::Release() { TRACE(L"In Release\n") long cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } HRESULT HDStreamSink::QueryInterface(REFIID riid, void **ppv) { TRACE(L"In QueryInterface\n") if (ppv == nullptr) return E_POINTER; (*ppv) = nullptr; HRESULT hr = S_OK; if(riid == IID_IUnknown || riid == IID_IMFStreamSink || riid == IID_IMFMediaEventGenerator) { (*ppv) = static_cast<IMFStreamSink*>(this); AddRef(); } else if(riid == IID_IMFMediaTypeHandler) { (*ppv) = static_cast<IMFMediaTypeHandler*>(this); AddRef(); } else hr = E_NOINTERFACE; if(FAILED(hr) && riid == IID_IMarshal) { if(m_spFTM == nullptr) { AutoLock lock(m_critSec); if(m_spFTM == nullptr) hr = CoCreateFreeThreadedMarshaler(static_cast<IMFStreamSink*>(this), &m_spFTM); } if(SUCCEEDED(hr)) { if(m_spFTM == nullptr) hr = E_UNEXPECTED; else hr = m_spFTM.Get()->QueryInterface(riid, ppv); } } return hr; } HRESULT HDStreamSink::Initialize(IMFMediaSink* parent, HandDetector_Native::IHDMediaSinkClbk^ clbk, DWORD identifier) { TRACE(L"In Initialize\n") m_clbk = clbk; m_identifier = identifier; AutoLock lock(m_critSec); Microsoft::WRL::ComPtr<IMFMediaType> mediaType; CHECK(MFCreateEventQueue(&m_spEventQueue)) m_spSink = parent; CHECK(MFAllocateSerialWorkQueue(MFASYNC_CALLBACK_QUEUE_STANDARD, &m_workQueueId)) //Create the current media type CHECK(MFCreateMediaType(&mediaType)) CHECK(mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video)) CHECK(mediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB24)) CHECK(SetCurrentMediaType(mediaType.Get())) return S_OK; } HRESULT HDStreamSink::BeginGetEvent(IMFAsyncCallback *pCallback, IUnknown *punkState) { TRACE(L"In BeginGetEvent\n") AutoLock lock(m_critSec); CHECK(m_spEventQueue->BeginGetEvent(pCallback, punkState)) return S_OK; } HRESULT HDStreamSink::EndGetEvent(IMFAsyncResult *pResult, IMFMediaEvent **ppEvent) { TRACE(L"In EndGetEvent\n") AutoLock lock(m_critSec); CHECK(m_spEventQueue->EndGetEvent(pResult, ppEvent)) return S_OK; } HRESULT HDStreamSink::GetEvent(DWORD dwFlags, IMFMediaEvent **ppEvent) { TRACE(L"In GetEvent\n") // NOTE: // GetEvent can block indefinitely, so we don't hold the lock. // This requires some juggling with the event queue pointer. Microsoft::WRL::ComPtr<IMFMediaEventQueue> spQueue; { AutoLock lock(m_critSec); spQueue = m_spEventQueue; } // Now get the event. CHECK(spQueue->GetEvent(dwFlags, ppEvent)) return S_OK; } HRESULT HDStreamSink::QueueEvent(MediaEventType met, REFGUID guidExtendedType, HRESULT hrStatus, PROPVARIANT const *pvValue) { TRACE(L"In QueueEvent\n") CHECK(m_spEventQueue->QueueEventParamVar(met, guidExtendedType, hrStatus, pvValue)) return S_OK; } HRESULT HDStreamSink::GetIdentifier(DWORD *pdwIdentifier) { TRACE(L"In GetIdentifier\n") *pdwIdentifier = 0; return S_OK; } HRESULT HDStreamSink::GetMediaSink(IMFMediaSink **ppMediaSink) { TRACE(L"In GetMediaSink\n") AutoLock lock(m_critSec); return m_spSink->QueryInterface(IID_IMFMediaSink, (void**)ppMediaSink); } HRESULT HDStreamSink::GetMediaTypeHandler(IMFMediaTypeHandler **ppHandler) { TRACE(L"In GetMediaTypeHandler\n") AutoLock lock(m_critSec); return QueryInterface(IID_IMFMediaTypeHandler, (void**)ppHandler); } HRESULT HDStreamSink::ProcessSample(IMFSample *pSample) { TRACE(L"In ProcessSample\n") if(pSample == nullptr) return E_INVALIDARG; AutoLock lock(m_critSec); //Validate the operation. CHECK(ValidateOperation(OpProcessSample)) SampleData sampleData(ST_SAMPLE); sampleData.asCOM = pSample; pSample->AddRef(); m_queueData.push(sampleData); QueueAsyncOperation(OpProcessSample); //Ask new frame CHECK(QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, nullptr)) return S_OK; } HRESULT HDStreamSink::PlaceMarker(MFSTREAMSINK_MARKER_TYPE eMarkerType, const PROPVARIANT *pvarMarkerValue, const PROPVARIANT *pvarContextValue) { TRACE(L"In PlaceMarker\n") AutoLock lock(m_critSec); CHECK(ValidateOperation(OpPlaceMarker)) Marker* marker = new Marker(eMarkerType, pvarMarkerValue, pvarContextValue); SampleData sampleData(ST_MARKER); sampleData.asMarker = std::shared_ptr<Marker>(marker); m_queueData.push(sampleData); // Unless we are paused, start an async operation to dispatch the next sample/marker. if(m_state != State_Paused) QueueAsyncOperation(OpPlaceMarker); // Increments ref count on pOp. return S_OK; } HRESULT HDStreamSink::Flush() { TRACE(L"In Flush\n"); return S_OK; } HRESULT HDStreamSink::Shutdown() { TRACE(L"In Shutdown\n"); return S_OK; } HRESULT HDStreamSink::IsMediaTypeSupported(IMFMediaType *pMediaType, IMFMediaType **ppMediaType) { TRACE(L"In IsMediaTypeSupported\n"); if(pMediaType == nullptr) return E_INVALIDARG; AutoLock lock(m_critSec); GUID majorType = GUID_NULL; CHECK(pMediaType->GetGUID(MF_MT_MAJOR_TYPE, &majorType)) if (majorType != MFMediaType_Video) { TRACE(L"Not a video media type...\n"); return MF_E_INVALIDTYPE; } GUID guiNewSubtype; CHECK(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)); if (guiNewSubtype != MFVideoFormat_RGB24 && guiNewSubtype != MFVideoFormat_ARGB32 && guiNewSubtype != MFVideoFormat_L8 && guiNewSubtype != MFVideoFormat_L16 && guiNewSubtype != MFVideoFormat_D16) { TRACE(L"Not the correct media SubType...\n"); return MF_E_INVALIDTYPE; } // We don't return any "close match" types. if(ppMediaType) *ppMediaType = nullptr; return S_OK; } HRESULT HDStreamSink::GetMediaTypeCount(DWORD *pdwTypeCount) { TRACE(L"In GetMediaTypeCount\n"); if (pdwTypeCount == nullptr) return E_INVALIDARG; *pdwTypeCount = 1; return S_OK; } HRESULT HDStreamSink::GetMediaTypeByIndex(DWORD dwIndex, IMFMediaType **ppType) { TRACE(L"In GetMediaTypeByIndex\n"); if (ppType == nullptr) { return E_INVALIDARG; } AutoLock lock(m_critSec); if(dwIndex > 0) return MF_E_NO_MORE_TYPES; else { *ppType = m_spCurrentType.Get(); if(*ppType != nullptr) (*ppType)->AddRef(); } return S_OK; } HRESULT HDStreamSink::SetCurrentMediaType(IMFMediaType *pMediaType) { TRACE(L"In SetCurrentMediaType\n"); AutoLock lock(m_critSec); // We don't allow format changes after streaming starts. CHECK(ValidateOperation(OpSetMediaType)); // We set media type already if (m_state >= State_Ready) CHECK(IsMediaTypeSupported(pMediaType, nullptr)); CHECK(MFCreateMediaType(m_spCurrentType.ReleaseAndGetAddressOf())); CHECK(pMediaType->CopyAllItems(m_spCurrentType.Get())); if(m_state < State_Ready) m_state = State_Ready; else if(m_state > State_Ready) { Microsoft::WRL::ComPtr<IMFMediaType> spType; CHECK(MFCreateMediaType(&spType)); CHECK(pMediaType->CopyAllItems(spType.Get())); ProcessFormatChange(spType.Get()); } QueueEvent(MEStreamSinkFormatChanged, GUID_NULL, S_OK, nullptr); UINT32 width, height; if (FAILED(MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &width, &height))) { TRACE(L"Could not get the size attribute...\n"); return S_OK; } m_streamWidth = width; m_streamHeight = height; UINT32 framerateNum = -1, framerateDenum=1; if (FAILED(MFGetAttributeRatio(m_spCurrentType.Get(), MF_MT_FRAME_RATE, &framerateNum, &framerateDenum))) TRACE(L"Could not get the framerate attribute...\n"); GUID guiNewSubtype; CHECK(pMediaType->GetGUID(MF_MT_SUBTYPE, &guiNewSubtype)); //Delete the old hand detector if (m_handDetector != NULL) { delete m_handDetector; m_handDetector = NULL; } //Create the hand detector //We detect between 25 and 80 centimeters, with a blob of minimum size = 900 pixels //Maximum wrist length : 100 pixels if (guiNewSubtype == MFVideoFormat_L8) m_handDetector = new HandDetection<D8Func>(width, height, 230, 630, 15, 700, 110); else if (guiNewSubtype == MFVideoFormat_D16 || guiNewSubtype == MFVideoFormat_L16) m_handDetector = new HandDetection<D16Func>(width, height, 230, 630, 15, 700, 110); else TRACE(L"Could not determine GUID %ld\n", guiNewSubtype); m_mediaSubtype = guiNewSubtype; TRACE(L"Media type setted. Width: %d, Height: %d, framerate: %f, format: %ws\n", width, height, (float)((INT32)framerateNum) / framerateDenum, (guiNewSubtype == MFVideoFormat_D16 ? L"D16" : (guiNewSubtype == MFVideoFormat_RGB24 ? L"RGB24" : (guiNewSubtype == MFVideoFormat_L8 ? L"L8" : (guiNewSubtype == MFVideoFormat_L16 ? L"L16" : L"ARGB32"))))); return S_OK; } HRESULT HDStreamSink::GetCurrentMediaType(IMFMediaType **ppMediaType) { TRACE(L"In GetCurrentMediaType\n") AutoLock lock(m_critSec); *ppMediaType = m_spCurrentType.Get(); if(*ppMediaType) (*ppMediaType)->AddRef(); return S_OK; } HRESULT HDStreamSink::GetMajorType(GUID *pguidMajorType) { TRACE(L"In GetMajorType") AutoLock lock(m_critSec); *pguidMajorType = MFMediaType_Video; return S_OK; } HRESULT HDStreamSink::Start(MFTIME start) { TRACE(L"In Start\n") AutoLock lock(m_critSec); CHECK(ValidateOperation(OpStart)) m_state = State_Started; CHECK(QueueAsyncOperation(OpStart)) return S_OK; } HRESULT HDStreamSink::Restart() { TRACE(L"In Restart\n") AutoLock lock(m_critSec); CHECK(ValidateOperation(OpRestart)) m_state = State_Started; CHECK(QueueAsyncOperation(OpRestart)) return S_OK; } HRESULT HDStreamSink::Stop() { TRACE(L"In Stop\n") AutoLock lock(m_critSec); CHECK(ValidateOperation(OpStop)) m_state = State_Stopped; CHECK(QueueAsyncOperation(OpStop)) return S_OK; } HRESULT HDStreamSink::Pause() { TRACE(L"In Pause\n") AutoLock lock(m_critSec); CHECK(ValidateOperation(OpPause)) m_state = State_Paused; CHECK(QueueAsyncOperation(OpPause)) return S_OK; } void HDStreamSink::ProcessFormatChange(IMFMediaType *pMediaType) { TRACE(L"In process format change\n") // Add the media type to the sample queue. SampleData sampleData(ST_MEDIATYPE); sampleData.asCOM = pMediaType; pMediaType->AddRef(); m_queueData.push(sampleData); // Unless we are paused, start an async operation to dispatch the next sample. // Queue the operation. QueueAsyncOperation(OpSetMediaType); } // Puts an async operation on the work queue. HRESULT HDStreamSink::QueueAsyncOperation(StreamOperation op) { TRACE(L"In Queue Async Operation\n") AutoLock _lock(m_critSec); Microsoft::WRL::ComPtr<AsyncOperation> spOp; spOp.Attach(new AsyncOperation(op)); // Created with ref count = 1 CHECK(MFPutWorkItem2(m_workQueueId, 0, &m_workQueueCB, spOp.Get())) return S_OK; } BOOL HDStreamSink::ValidateOperation(StreamOperation op) const { return validStateMatrix[m_state][op]; } HRESULT HDStreamSink::OnDispatchWorkItem(IMFAsyncResult *pAsyncResult) { TRACE(L"New work Item received\n") Microsoft::WRL::ComPtr<IUnknown> spState; CHECK(pAsyncResult->GetState(&spState)) // The state object is a AsyncOperation object. AsyncOperation *asyncOP = static_cast<AsyncOperation *>(spState.Get()); StreamOperation op = asyncOP->op; switch(op) { case OpStart: case OpRestart: { TRACE(L"Sending Operation Start\n"); AutoLock _lock(m_critSec); CHECK(QueueEvent(MEStreamSinkStarted, GUID_NULL, S_OK, nullptr)) CHECK(QueueEvent(MEStreamSinkRequestSample, GUID_NULL, S_OK, nullptr)) TRACE(L"End Operation Start\n") break; } case OpPause: { AutoLock _lock(m_critSec); TRACE(L"Sending Operation Paused\n"); CHECK(QueueEvent(MEStreamSinkPaused, GUID_NULL, S_OK, nullptr)) break; } case OpStop: { AutoLock _lock(m_critSec); TRACE(L"Sending Operation Stopped\n"); CHECK(QueueEvent(MEStreamSinkStopped, GUID_NULL, S_OK, nullptr)) TRACE(L"End Operation Start\n") break; } case OpProcessSample: { TRACE(L"Processing sample in work item thread\n") //Fetch sample data IMFSample* sample = NULL; { AutoLock _lock(m_critSec); SampleData& sd = m_queueData.front(); sample = static_cast<IMFSample*>(sd.asCOM.Get()); m_queueData.pop(); } MFPinholeCameraIntrinsics cameraIntrinsics; sample->GetBlob(MFSampleExtension_PinholeCameraIntrinsics, (UINT8*)(&cameraIntrinsics), 1, NULL); IMFMediaBuffer* sampleBuffer; unsigned long bufferCount; sample->GetBufferCount(&bufferCount); sample->ConvertToContiguousBuffer(&sampleBuffer); BYTE* rawBuffer; DWORD bufferCurrentLength; sampleBuffer->Lock(&rawBuffer, NULL, &bufferCurrentLength); //Update the hand position CHECK(UpdateHandDetection(sample, rawBuffer, bufferCurrentLength)) //Release the frame sampleBuffer->Unlock(); sampleBuffer->Release(); sample->Release(); break; } case OpPlaceMarker: { AutoLock _lock(m_critSec); QueueEvent(MEStreamSinkMarker, GUID_NULL, S_OK, nullptr); m_queueData.pop(); break; } case OpSetMediaType: { AutoLock _lock(m_critSec); m_queueData.pop(); break; } default: break; } TRACE(L"End onWorkItem received\n") return S_OK; } HRESULT HDStreamSink::UpdateHandDetection(IMFSample* sample, BYTE* rawBuffer, unsigned long bufferCurrentLength) { //WriteSampleToFile(rawBuffer, bufferCurrentLength); if (m_handDetector != NULL) { //Update the status m_handDetector->updateDetection(rawBuffer); //Call the callback interface if (m_clbk != nullptr) { Platform::Collections::Vector<HandDetector_Native::Hand^>^ hands = ref new Platform::Collections::Vector<HandDetector_Native::Hand^>(); //Determine what depth function to use DepthFunc depthFunc = NULL; if (m_mediaSubtype == MFVideoFormat_D16 || m_mediaSubtype == MFVideoFormat_L16) depthFunc = &D16Func::depthAt; else if (m_mediaSubtype == MFVideoFormat_L8) depthFunc = &D8Func::depthAt; //Get the camera parameters HandDetector_Native::CameraParameter camera; //First the spatial coordinate system Microsoft::WRL::ComPtr<IUnknown> spUnknown; Microsoft::WRL::ComPtr<IInspectable> spSpatialCoordinateSystem = NULL; if(SUCCEEDED(sample->GetUnknown(MFSampleExtension_Spatial_CameraCoordinateSystem, IID_PPV_ARGS(&spUnknown)))) spUnknown.As(&spSpatialCoordinateSystem); memset(&camera.CameraViewTransform, 0, sizeof(camera.CameraViewTransform)); memset(&camera.CameraProjectionTransform, 0, sizeof(camera.CameraProjectionTransform)); memset(&camera.CameraIntrinsics, 0, sizeof(camera.CameraIntrinsics)); //Then camera parameters UINT32 blobSize; if(FAILED(sample->GetBlob(MFSampleExtension_Spatial_CameraViewTransform, (UINT8*)(&camera.CameraViewTransform), sizeof(camera.CameraViewTransform), &blobSize))) TRACE("Failed to get camera view transform\n") if(FAILED(sample->GetBlob(MFSampleExtension_Spatial_CameraProjectionTransform, (UINT8*)(&camera.CameraProjectionTransform), sizeof(camera.CameraProjectionTransform), &blobSize))) TRACE("Failed to get camera projection transform\n") if(FAILED(sample->GetBlob(MFSampleExtension_PinholeCameraIntrinsics, (UINT8*)&camera.CameraIntrinsics, sizeof(camera.CameraIntrinsics), &blobSize))) TRACE("Failed to get pinhole camera intrinsics\n") SensorStreaming::ICameraIntrinsics* sensorStreamingCameraIntrinsics = NULL; if(SUCCEEDED(sample->GetUnknown(SensorStreaming::MFSampleExtension_SensorStreaming_CameraIntrinsics, IID_PPV_ARGS(&spUnknown)))) sensorStreamingCameraIntrinsics = (SensorStreaming::ICameraIntrinsics*)spUnknown.Get(); //If found if(depthFunc) { //Create the WinRT proxy object if (sensorStreamingCameraIntrinsics == NULL) { for (const auto& h : m_handDetector->getHands()) { HandDetector_Native::Hand^ hand = ref new HandDetector_Native::Hand(); hand->InPixels = true; //Palm position hand->PalmX = h.palmX; hand->PalmY = h.palmY; hand->PalmZ = depthFunc(h.palmX, h.palmY, m_streamWidth, rawBuffer); //Fingers for (const auto& f : h.fingers) { HandDetector_Native::Finger finger; finger.TipX = f.tipX; finger.TipY = f.tipY; finger.TipZ = depthFunc(f.tipX, f.tipY, m_streamWidth, rawBuffer); hand->Fingers->Append(finger); } //Wrist hand->WristX = h.wristPosX; hand->WristY = h.wristPosY; hand->WristZ = depthFunc(h.wristPosX, h.wristPosY, m_streamWidth, rawBuffer); hands->Append(hand); } } else { for (const auto& h : m_handDetector->getHands()) { HandDetector_Native::Hand^ hand = ref new HandDetector_Native::Hand(); //Palm Position float outXY[2]; float inXY[2] = { (float)h.palmX, (float)h.palmY}; float depth = -depthFunc(h.palmX, h.palmY, m_streamWidth, rawBuffer)/1000.0f; sensorStreamingCameraIntrinsics->MapImagePointToCameraUnitPlane(inXY, outXY); float z = depth / sqrt(outXY[0] * outXY[0] + outXY[1] * outXY[1] + 1); hand->PalmX = z*outXY[0]; hand->PalmY = z*outXY[1]; hand->PalmZ = z; //Fingers for (const auto& f : h.fingers) { HandDetector_Native::Finger finger; inXY[0] = f.tipX; inXY[1] = f.tipY; depth = -depthFunc(f.tipX, f.tipY, m_streamWidth, rawBuffer)/1000.0f; sensorStreamingCameraIntrinsics->MapImagePointToCameraUnitPlane(inXY, outXY); z = depth / sqrt(outXY[0] * outXY[0] + outXY[1] * outXY[1] + 1); finger.TipX = z*outXY[0]; finger.TipY = z*outXY[1]; finger.TipZ = z; hand->Fingers->Append(finger); } //Wrist positions inXY[0] = (float)(h.wristPosX); inXY[1] = (float)(h.wristPosY); depth = -depthFunc(h.wristPosX, h.wristPosY, m_streamWidth, rawBuffer)/1000.0f; sensorStreamingCameraIntrinsics->MapImagePointToCameraUnitPlane(inXY, outXY); z = depth / sqrt(outXY[0] * outXY[0] + outXY[1] * outXY[1] + 1); hand->WristX = z * outXY[0]; hand->WristY = z * outXY[1]; hand->WristZ = z; //Copy the ROIs information hand->BlobROIMinX = h.blobMinROI[0]; hand->BlobROIMinY = h.blobMinROI[1]; hand->BlobROIMaxX = h.blobMaxROI[0]; hand->BlobROIMaxY = h.blobMaxROI[1]; hand->WristROIMinX = h.wristMinROI[0]; hand->WristROIMinY = h.wristMinROI[1]; hand->WristROIMaxX = h.wristMaxROI[0]; hand->WristROIMaxY = h.wristMaxROI[1]; hands->Append(hand); } } } //Call the interface if(spSpatialCoordinateSystem != NULL) m_clbk->OnHandUpdate(camera, safe_cast<Windows::Perception::Spatial::SpatialCoordinateSystem^>(reinterpret_cast<Platform::Object^>(spSpatialCoordinateSystem.Get())), hands); } } return S_OK; } HRESULT HDStreamSink::WriteSampleToFile(BYTE* rawBuffer, unsigned long bufferCurrentLength) { uint32_t width; uint32_t height; Platform::String^ strPath = Windows::Storage::ApplicationData::Current->LocalFolder->Path; const wchar_t* path = strPath->Data(); wchar_t fileName[2048]; swprintf_s(fileName, 2048, L"%s/frame%d.ppm", path, m_frameID++); FILE* f; _wfopen_s(&f, fileName, L"w"); TRACE(L"Writing to %s\n", fileName) char header[256]; { AutoLock _lock(m_critSec); CHECK(MFGetAttributeSize(m_spCurrentType.Get(), MF_MT_FRAME_SIZE, &width, &height)) } sprintf_s(header, 256, "P2\n%d %d\n%d", width, height, (1 << 16) - 1); fwrite(header, sizeof(char), strlen(header), f); std::string txt; for (DWORD i = 0; i < bufferCurrentLength / 2; i++) { if (i % 70 == 0) txt.push_back('\n'); char intStr[16]; sprintf_s(intStr, 16, "%d ", (int)((int)rawBuffer[2 * i] + (int)(rawBuffer[2 * i + 1] << 8))); txt += intStr; } fwrite(txt.c_str(), sizeof(char), txt.length(), f); TRACE(L"End writting") fclose(f); return S_OK; } }
[ "serenomickael@gmail.com" ]
serenomickael@gmail.com
58519b599c35bcc7f370067fc786ed3605873681
d39d88fd160cf213b0f4c833c5c7565fdaa0abd1
/1 yellow belt/week 3/BusStopDecomposition2/original_solution/responses.h
7b8d4cce89cb91af17969786073ea32c60c081ae
[]
no_license
DwarKapex/Cpp-Specialisation-Coursera-Yandex-MIPT
4b78691a4b64d8eb20ef64eaae3226f301283a6a
9a1a694640dbe994c3afda0fbd589ac1039b5d37
refs/heads/master
2022-05-19T18:01:48.352717
2022-03-08T06:15:48
2022-03-08T06:15:48
199,929,864
1
2
null
null
null
null
UTF-8
C++
false
false
544
h
#pragma once #include <iostream> #include <map> #include <string> #include <vector> using namespace std; struct BusesForStopResponse { vector<string> buses; }; ostream& operator << (ostream& os, const BusesForStopResponse& r); struct StopsForBusResponse { string bus; vector<pair<string, vector<string>>> stops_for_buses; }; ostream& operator << (ostream& os, const StopsForBusResponse& r); struct AllBusesResponse { map<string, vector<string>> buses_to_stops; }; ostream& operator << (ostream& os, const AllBusesResponse& r);
[ "vkozlov@magicleap.com" ]
vkozlov@magicleap.com
5a20bc9224a280debbeaa2030896ee73792a4aa6
1bbfeca83bac53d22b1110ca7f6c9a28bc46c22e
/ru-olymp-train-winter-2009/Submits/081227/10_25_51_02_A_0627.cpp
0c3081d5c9cbf246aa92618aa6952c0d30d0ba06
[]
no_license
stden/olymp
a633c1dfb1dd8d184a123d6da89f46163d5fad93
d85a4bb0b88797ec878b64db86ad8ec8854a63cd
refs/heads/master
2016-09-06T06:30:56.466755
2013-07-13T08:48:16
2013-07-13T08:48:16
5,158,472
1
0
null
null
null
null
UTF-8
C++
false
false
2,388
cpp
#include <cstdio> #include <cstdlib> #include <memory.h> #include <algorithm> #include <vector> #include <list> #include <string> using namespace std; #define TASKNAME "help" void answer(bool result) { printf(result ? "YES\n" : "NO\n"); exit(0); } int getcount(string str, string substr) { int res = 0; for (int pos = str.find(substr, 0); pos < str.size(); pos = str.find(substr, pos + 1)) res++; return res; } bool is_rus(char ch) { return ch > 127; } string lcase(string old) { string res = ""; for (int i = 0; i < old.size(); i++) { if ((old[i] >= 'A') && (old[i] <= 'Z')) res += old[i] - 'A' + 'a'; else res += old[i]; } return res; } char file[1000000]; int main() { freopen(TASKNAME ".in", "r", stdin); freopen(TASKNAME ".out", "w", stdout); fread(file, 1, 1000000, stdin); string str = file; str = lcase(str); if (string(str, 0, 7) == "program") answer(false); if (str.find("close(", 0) < str.size()) answer(false); if (str.find(":)", 0) < str.size()) answer(false); if (str.find(":(", 0) < str.size()) answer(false); if (str.find("-)", 0) < str.size()) answer(false); if (str.find("-(", 0) < str.size()) answer(false); if (string(str, 0, 2) == "//") answer(true); if (str.find("zadach", 0) < str.size()) answer(false); if (str.find(";;", 0) < str.size()) answer(false); if (str.find("lib", 0) < str.size()) answer(true); if (str.find("asm", 0) < str.size()) answer(true); if (str.find("randseed", 0) < str.size()) answer(true); if (str.find("__", 0) < str.size()) answer(true); bool instr = 0; int found = 0; for (int i = 0; i < str.size(); i++) { switch (str[i]) { case '"': if (!instr) instr = 1; else if (instr == 1) instr = 0; found = 0; break; case '\'': if (!instr) instr = 2; else if (instr == 2) instr = 0; found = 0; break; case '/':if (!instr) found++; break; default:found = 0; break; } if (found == 2) { string comment = string(str, i + 1, str.find("\n", i + 1) - i - 1); for (int i = 0; i < comment.size(); i++) if (is_rus(comment[i])) answer(false); if (comment.find("created", 0) < comment.size()) answer(true); if (comment.find("powered", 0) < comment.size()) answer(true); if (comment.find("author", 0) < comment.size()) answer(true); } } answer(true); return 0; }
[ "super.denis@gmail.com" ]
super.denis@gmail.com
898acf96ad6963127045b76e5008e8bbc2913077
62e744795a2d8e1e3587cdef33ee176d7e564b7b
/Seagull-Core/src/Renderer/RenderCommand.cpp
7ee28969f44040d0cae6a347bfb2b1dddf6515f0
[ "MIT" ]
permissive
Catddly/Seagull-Engine-Discarded
49bde4b8d3d16d6d519c2372176eb97b7c0a9931
fb51b66812eca6b70ed0e35ecba091e9874b5bea
refs/heads/main
2023-06-16T15:10:49.754971
2020-11-15T11:26:26
2020-11-15T11:26:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
188
cpp
#include "sgpch.h" #include "RenderCommand.h" #include "Platform/DirectX/DirectX12RendererAPI.h" namespace SG { RendererAPI* RenderCommand::s_RendererAPI = new DirectX12RendererAPI(); }
[ "illmewds@gmail.com" ]
illmewds@gmail.com
e5f68fc5739139bd17107764b8865f094d98050a
94907d58c786a835b8ea51eaf5f5f922dd0f2cbc
/Form1.h
641202597e693d76e4eaaecff27a1734ab9a4dbf
[]
no_license
jdsepulveda136/Projeto-Alfa
dd89cd656620837d01d686fe6af0eaefd30fa70e
8bc82bbfc53700b6eeb5135aec1f9708d805bdc3
refs/heads/master
2022-12-04T00:39:16.032258
2019-06-19T14:26:24
2019-06-19T14:26:24
190,013,995
0
0
null
null
null
null
ISO-8859-1
C++
false
false
45,300
h
#pragma once namespace ProjCLR { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; /// <summary> /// Summary for Form1 /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Windows::Forms::DataGridView^ data_infos; private: System::Windows::Forms::Button^ bt_limpa; private: System::Windows::Forms::Button^ bt_localiza; private: System::Windows::Forms::TextBox^ txt_localiza; private: System::Windows::Forms::TextBox^ txt_result; private: System::Windows::Forms::Button^ bt_velhos; private: System::Windows::Forms::Button^ bt_freguesia; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem1; private: System::Windows::Forms::ToolStripMenuItem^ verLinhaParaAdicionarToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ delegadoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ mostrarColunaDelegadoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ sortearDelegadoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ reiniciarDatagridToolStripMenuItem; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Nome; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Freguesia; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Nascimento; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Sexo; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Delegado; private: System::Windows::Forms::ToolStripMenuItem^ estatisticasToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ removerLinhaSelecionadaToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ maisVelhosToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ guardaDelegadoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ clacularMédiasToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ melhorAlunoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ mostraNegativasToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ mostraReprovadosToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ mostraDelegadoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ gerarNotasToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ ficheiroToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ sairToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ sobreToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ autorToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ versãoToolStripMenuItem; private: System::Windows::Forms::DataGridView^ data_copia; private: System::Windows::Forms::DataGridViewTextBoxColumn^ copia_nome; private: System::Windows::Forms::DataGridViewTextBoxColumn^ copia_freguesia; private: System::Windows::Forms::DataGridViewTextBoxColumn^ copia_sexo; private: System::Windows::Forms::DataGridViewTextBoxColumn^ copia_estado; private: System::Windows::Forms::Button^ bt_copia; private: System::Windows::Forms::TextBox^ txt_copia; private: System::Windows::Forms::RadioButton^ rd_masc; private: System::Windows::Forms::RadioButton^ rd_fem; private: System::Windows::Forms::RadioButton^ rd_todos; protected: protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid)); this->data_infos = (gcnew System::Windows::Forms::DataGridView()); this->Nome = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Freguesia = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Nascimento = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Sexo = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Delegado = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->bt_limpa = (gcnew System::Windows::Forms::Button()); this->bt_localiza = (gcnew System::Windows::Forms::Button()); this->txt_localiza = (gcnew System::Windows::Forms::TextBox()); this->txt_result = (gcnew System::Windows::Forms::TextBox()); this->bt_velhos = (gcnew System::Windows::Forms::Button()); this->bt_freguesia = (gcnew System::Windows::Forms::Button()); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->ficheiroToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->sairToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->verLinhaParaAdicionarToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->reiniciarDatagridToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->gerarNotasToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->removerLinhaSelecionadaToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->delegadoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mostrarColunaDelegadoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->sortearDelegadoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->guardaDelegadoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mostraDelegadoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->estatisticasToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->maisVelhosToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->clacularMédiasToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->melhorAlunoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mostraNegativasToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mostraReprovadosToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->sobreToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->autorToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->versãoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->data_copia = (gcnew System::Windows::Forms::DataGridView()); this->copia_nome = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->copia_freguesia = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->copia_sexo = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->copia_estado = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->bt_copia = (gcnew System::Windows::Forms::Button()); this->txt_copia = (gcnew System::Windows::Forms::TextBox()); this->rd_masc = (gcnew System::Windows::Forms::RadioButton()); this->rd_fem = (gcnew System::Windows::Forms::RadioButton()); this->rd_todos = (gcnew System::Windows::Forms::RadioButton()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->data_infos))->BeginInit(); this->menuStrip1->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->data_copia))->BeginInit(); this->SuspendLayout(); // // data_infos // this->data_infos->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Left)); this->data_infos->AutoSizeRowsMode = System::Windows::Forms::DataGridViewAutoSizeRowsMode::DisplayedCells; this->data_infos->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->data_infos->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(5) { this->Nome, this->Freguesia, this->Nascimento, this->Sexo, this->Delegado }); this->data_infos->GridColor = System::Drawing::SystemColors::ActiveBorder; this->data_infos->Location = System::Drawing::Point(12, 137); this->data_infos->Name = L"data_infos"; this->data_infos->SelectionMode = System::Windows::Forms::DataGridViewSelectionMode::FullRowSelect; this->data_infos->Size = System::Drawing::Size(552, 423); this->data_infos->TabIndex = 0; // // Nome // this->Nome->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Nome->FillWeight = 80; this->Nome->HeaderText = L"Nome"; this->Nome->Name = L"Nome"; // // Freguesia // this->Freguesia->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Freguesia->FillWeight = 50; this->Freguesia->HeaderText = L"Freguesia"; this->Freguesia->Name = L"Freguesia"; // // Nascimento // this->Nascimento->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Nascimento->FillWeight = 50; this->Nascimento->HeaderText = L"Nascimento"; this->Nascimento->Name = L"Nascimento"; // // Sexo // this->Sexo->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Sexo->FillWeight = 15; this->Sexo->HeaderText = L"Sexo"; this->Sexo->Name = L"Sexo"; // // Delegado // this->Delegado->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Delegado->FillWeight = 25; this->Delegado->HeaderText = L"Delegado"; this->Delegado->Name = L"Delegado"; // // bt_limpa // this->bt_limpa->Anchor = System::Windows::Forms::AnchorStyles::Top; this->bt_limpa->BackColor = System::Drawing::SystemColors::ControlLightLight; this->bt_limpa->Location = System::Drawing::Point(12, 29); this->bt_limpa->Name = L"bt_limpa"; this->bt_limpa->Size = System::Drawing::Size(218, 23); this->bt_limpa->TabIndex = 1; this->bt_limpa->Text = L"Reinicia Datagrid"; this->bt_limpa->UseVisualStyleBackColor = false; this->bt_limpa->Click += gcnew System::EventHandler(this, &Form1::Bt_limpa_Click); // // bt_localiza // this->bt_localiza->Anchor = System::Windows::Forms::AnchorStyles::Top; this->bt_localiza->BackColor = System::Drawing::SystemColors::ControlLightLight; this->bt_localiza->Location = System::Drawing::Point(12, 58); this->bt_localiza->Name = L"bt_localiza"; this->bt_localiza->Size = System::Drawing::Size(218, 23); this->bt_localiza->TabIndex = 2; this->bt_localiza->Text = L"Localiza Nome"; this->bt_localiza->UseVisualStyleBackColor = false; this->bt_localiza->Click += gcnew System::EventHandler(this, &Form1::Bt_localiza_Click); // // txt_localiza // this->txt_localiza->Anchor = System::Windows::Forms::AnchorStyles::Top; this->txt_localiza->Location = System::Drawing::Point(118, 87); this->txt_localiza->Name = L"txt_localiza"; this->txt_localiza->Size = System::Drawing::Size(217, 20); this->txt_localiza->TabIndex = 3; // // txt_result // this->txt_result->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right)); this->txt_result->Location = System::Drawing::Point(480, 27); this->txt_result->Multiline = true; this->txt_result->Name = L"txt_result"; this->txt_result->Size = System::Drawing::Size(225, 89); this->txt_result->TabIndex = 4; this->txt_result->Visible = false; this->txt_result->TextChanged += gcnew System::EventHandler(this, &Form1::Txt_result_TextChanged); // // bt_velhos // this->bt_velhos->Anchor = System::Windows::Forms::AnchorStyles::Top; this->bt_velhos->BackColor = System::Drawing::SystemColors::ControlLightLight; this->bt_velhos->Location = System::Drawing::Point(236, 29); this->bt_velhos->Name = L"bt_velhos"; this->bt_velhos->Size = System::Drawing::Size(218, 23); this->bt_velhos->TabIndex = 5; this->bt_velhos->Text = L"Quem é o mais velho\?"; this->bt_velhos->UseVisualStyleBackColor = false; this->bt_velhos->Click += gcnew System::EventHandler(this, &Form1::Bt_velhos_Click); // // bt_freguesia // this->bt_freguesia->Anchor = System::Windows::Forms::AnchorStyles::Top; this->bt_freguesia->BackColor = System::Drawing::SystemColors::ControlLightLight; this->bt_freguesia->Location = System::Drawing::Point(236, 58); this->bt_freguesia->Name = L"bt_freguesia"; this->bt_freguesia->Size = System::Drawing::Size(218, 23); this->bt_freguesia->TabIndex = 6; this->bt_freguesia->Text = L"Quantos há desta freguesia"; this->bt_freguesia->UseVisualStyleBackColor = false; this->bt_freguesia->Click += gcnew System::EventHandler(this, &Form1::Bt_freguesia_Click); // // menuStrip1 // this->menuStrip1->BackColor = System::Drawing::SystemColors::ControlLightLight; this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5) { this->ficheiroToolStripMenuItem, this->toolStripMenuItem1, this->delegadoToolStripMenuItem, this->estatisticasToolStripMenuItem, this->sobreToolStripMenuItem }); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(951, 24); this->menuStrip1->TabIndex = 8; this->menuStrip1->Text = L"menuStrip1"; // // ficheiroToolStripMenuItem // this->ficheiroToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->sairToolStripMenuItem }); this->ficheiroToolStripMenuItem->Name = L"ficheiroToolStripMenuItem"; this->ficheiroToolStripMenuItem->Size = System::Drawing::Size(61, 20); this->ficheiroToolStripMenuItem->Text = L"Ficheiro"; // // sairToolStripMenuItem // this->sairToolStripMenuItem->Name = L"sairToolStripMenuItem"; this->sairToolStripMenuItem->Size = System::Drawing::Size(93, 22); this->sairToolStripMenuItem->Text = L"Sair"; this->sairToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::SairToolStripMenuItem_Click); // // toolStripMenuItem1 // this->toolStripMenuItem1->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) { this->verLinhaParaAdicionarToolStripMenuItem, this->reiniciarDatagridToolStripMenuItem, this->gerarNotasToolStripMenuItem, this->removerLinhaSelecionadaToolStripMenuItem }); this->toolStripMenuItem1->Name = L"toolStripMenuItem1"; this->toolStripMenuItem1->Size = System::Drawing::Size(64, 20); this->toolStripMenuItem1->Text = L"Datagrid"; // // verLinhaParaAdicionarToolStripMenuItem // this->verLinhaParaAdicionarToolStripMenuItem->Name = L"verLinhaParaAdicionarToolStripMenuItem"; this->verLinhaParaAdicionarToolStripMenuItem->Size = System::Drawing::Size(300, 22); this->verLinhaParaAdicionarToolStripMenuItem->Text = L"Esconder linha para adicionar e cabeçalhos"; this->verLinhaParaAdicionarToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::VerLinhaParaAdicionarToolStripMenuItem_Click); // // reiniciarDatagridToolStripMenuItem // this->reiniciarDatagridToolStripMenuItem->Name = L"reiniciarDatagridToolStripMenuItem"; this->reiniciarDatagridToolStripMenuItem->Size = System::Drawing::Size(300, 22); this->reiniciarDatagridToolStripMenuItem->Text = L"Reiniciar Datagrid"; this->reiniciarDatagridToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::ReiniciarDatagridToolStripMenuItem_Click); // // gerarNotasToolStripMenuItem // this->gerarNotasToolStripMenuItem->Name = L"gerarNotasToolStripMenuItem"; this->gerarNotasToolStripMenuItem->Size = System::Drawing::Size(300, 22); this->gerarNotasToolStripMenuItem->Text = L"Gerar notas"; this->gerarNotasToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::GerarNotasToolStripMenuItem_Click); // // removerLinhaSelecionadaToolStripMenuItem // this->removerLinhaSelecionadaToolStripMenuItem->Name = L"removerLinhaSelecionadaToolStripMenuItem"; this->removerLinhaSelecionadaToolStripMenuItem->Size = System::Drawing::Size(300, 22); this->removerLinhaSelecionadaToolStripMenuItem->Text = L"Remover linha selecionada"; this->removerLinhaSelecionadaToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::RemoverLinhaSelecionadaToolStripMenuItem_Click); // // delegadoToolStripMenuItem // this->delegadoToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) { this->mostrarColunaDelegadoToolStripMenuItem, this->sortearDelegadoToolStripMenuItem, this->guardaDelegadoToolStripMenuItem, this->mostraDelegadoToolStripMenuItem }); this->delegadoToolStripMenuItem->Name = L"delegadoToolStripMenuItem"; this->delegadoToolStripMenuItem->Size = System::Drawing::Size(69, 20); this->delegadoToolStripMenuItem->Text = L"Delegado"; // // mostrarColunaDelegadoToolStripMenuItem // this->mostrarColunaDelegadoToolStripMenuItem->Name = L"mostrarColunaDelegadoToolStripMenuItem"; this->mostrarColunaDelegadoToolStripMenuItem->Size = System::Drawing::Size(223, 22); this->mostrarColunaDelegadoToolStripMenuItem->Text = L"Mostrar coluna do delegado"; this->mostrarColunaDelegadoToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::MostrarColunaDelegadoToolStripMenuItem_Click); // // sortearDelegadoToolStripMenuItem // this->sortearDelegadoToolStripMenuItem->Name = L"sortearDelegadoToolStripMenuItem"; this->sortearDelegadoToolStripMenuItem->Size = System::Drawing::Size(223, 22); this->sortearDelegadoToolStripMenuItem->Text = L"Sortear delegado"; this->sortearDelegadoToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::SortearDelegadoToolStripMenuItem_Click); // // guardaDelegadoToolStripMenuItem // this->guardaDelegadoToolStripMenuItem->Name = L"guardaDelegadoToolStripMenuItem"; this->guardaDelegadoToolStripMenuItem->Size = System::Drawing::Size(223, 22); this->guardaDelegadoToolStripMenuItem->Text = L"Guarda delegado"; this->guardaDelegadoToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::GuardaDelegadoToolStripMenuItem_Click); // // mostraDelegadoToolStripMenuItem // this->mostraDelegadoToolStripMenuItem->Name = L"mostraDelegadoToolStripMenuItem"; this->mostraDelegadoToolStripMenuItem->Size = System::Drawing::Size(223, 22); this->mostraDelegadoToolStripMenuItem->Text = L"Mostra delegado"; this->mostraDelegadoToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::MostraDelegadoToolStripMenuItem_Click); // // estatisticasToolStripMenuItem // this->estatisticasToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5) { this->maisVelhosToolStripMenuItem, this->clacularMédiasToolStripMenuItem, this->melhorAlunoToolStripMenuItem, this->mostraNegativasToolStripMenuItem, this->mostraReprovadosToolStripMenuItem }); this->estatisticasToolStripMenuItem->Name = L"estatisticasToolStripMenuItem"; this->estatisticasToolStripMenuItem->Size = System::Drawing::Size(76, 20); this->estatisticasToolStripMenuItem->Text = L"Estatisticas"; // // maisVelhosToolStripMenuItem // this->maisVelhosToolStripMenuItem->Name = L"maisVelhosToolStripMenuItem"; this->maisVelhosToolStripMenuItem->Size = System::Drawing::Size(180, 22); this->maisVelhosToolStripMenuItem->Text = L"Mais velho(s)"; this->maisVelhosToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::MaisVelhosToolStripMenuItem_Click); // // clacularMédiasToolStripMenuItem // this->clacularMédiasToolStripMenuItem->Name = L"clacularMédiasToolStripMenuItem"; this->clacularMédiasToolStripMenuItem->Size = System::Drawing::Size(180, 22); this->clacularMédiasToolStripMenuItem->Text = L"Calcular médias"; this->clacularMédiasToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::ClacularMédiasToolStripMenuItem_Click); // // melhorAlunoToolStripMenuItem // this->melhorAlunoToolStripMenuItem->Name = L"melhorAlunoToolStripMenuItem"; this->melhorAlunoToolStripMenuItem->Size = System::Drawing::Size(180, 22); this->melhorAlunoToolStripMenuItem->Text = L"Melhores alunos"; this->melhorAlunoToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::MelhorAlunoToolStripMenuItem_Click); // // mostraNegativasToolStripMenuItem // this->mostraNegativasToolStripMenuItem->BackColor = System::Drawing::SystemColors::Control; this->mostraNegativasToolStripMenuItem->Name = L"mostraNegativasToolStripMenuItem"; this->mostraNegativasToolStripMenuItem->Size = System::Drawing::Size(180, 22); this->mostraNegativasToolStripMenuItem->Text = L"Mostra negativas"; this->mostraNegativasToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::MostraNegativasToolStripMenuItem_Click); // // mostraReprovadosToolStripMenuItem // this->mostraReprovadosToolStripMenuItem->Name = L"mostraReprovadosToolStripMenuItem"; this->mostraReprovadosToolStripMenuItem->Size = System::Drawing::Size(180, 22); this->mostraReprovadosToolStripMenuItem->Text = L"Mostra reprovados"; this->mostraReprovadosToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::MostraReprovadosToolStripMenuItem_Click); // // sobreToolStripMenuItem // this->sobreToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) { this->autorToolStripMenuItem, this->versãoToolStripMenuItem }); this->sobreToolStripMenuItem->Name = L"sobreToolStripMenuItem"; this->sobreToolStripMenuItem->Size = System::Drawing::Size(49, 20); this->sobreToolStripMenuItem->Text = L"Sobre"; // // autorToolStripMenuItem // this->autorToolStripMenuItem->Name = L"autorToolStripMenuItem"; this->autorToolStripMenuItem->Size = System::Drawing::Size(108, 22); this->autorToolStripMenuItem->Text = L"Autor"; this->autorToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::AutorToolStripMenuItem_Click); // // versãoToolStripMenuItem // this->versãoToolStripMenuItem->Name = L"versãoToolStripMenuItem"; this->versãoToolStripMenuItem->Size = System::Drawing::Size(108, 22); this->versãoToolStripMenuItem->Text = L"Versão"; this->versãoToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::VersãoToolStripMenuItem_Click); // // data_copia // this->data_copia->AllowUserToAddRows = false; this->data_copia->AllowUserToDeleteRows = false; this->data_copia->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->data_copia->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(4) { this->copia_nome, this->copia_freguesia, this->copia_sexo, this->copia_estado }); this->data_copia->Location = System::Drawing::Point(570, 137); this->data_copia->Name = L"data_copia"; this->data_copia->ReadOnly = true; this->data_copia->Size = System::Drawing::Size(369, 423); this->data_copia->TabIndex = 9; // // copia_nome // this->copia_nome->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::AllCells; this->copia_nome->HeaderText = L"Nome"; this->copia_nome->Name = L"copia_nome"; this->copia_nome->ReadOnly = true; this->copia_nome->Width = 60; // // copia_freguesia // this->copia_freguesia->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::AllCells; this->copia_freguesia->HeaderText = L"Freguesia"; this->copia_freguesia->Name = L"copia_freguesia"; this->copia_freguesia->ReadOnly = true; this->copia_freguesia->Width = 78; // // copia_sexo // this->copia_sexo->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::AllCells; this->copia_sexo->HeaderText = L"Sexo"; this->copia_sexo->Name = L"copia_sexo"; this->copia_sexo->ReadOnly = true; this->copia_sexo->Width = 56; // // copia_estado // this->copia_estado->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::AllCells; this->copia_estado->HeaderText = L"Estado"; this->copia_estado->Name = L"copia_estado"; this->copia_estado->ReadOnly = true; this->copia_estado->Width = 65; // // bt_copia // this->bt_copia->Location = System::Drawing::Point(776, 87); this->bt_copia->Name = L"bt_copia"; this->bt_copia->Size = System::Drawing::Size(75, 23); this->bt_copia->TabIndex = 10; this->bt_copia->Text = L"Copiar"; this->bt_copia->UseVisualStyleBackColor = true; this->bt_copia->Click += gcnew System::EventHandler(this, &Form1::Bt_copia_Click); // // txt_copia // this->txt_copia->Location = System::Drawing::Point(734, 27); this->txt_copia->Name = L"txt_copia"; this->txt_copia->Size = System::Drawing::Size(147, 20); this->txt_copia->TabIndex = 11; // // rd_masc // this->rd_masc->AutoSize = true; this->rd_masc->Location = System::Drawing::Point(752, 58); this->rd_masc->Name = L"rd_masc"; this->rd_masc->Size = System::Drawing::Size(34, 17); this->rd_masc->TabIndex = 12; this->rd_masc->TabStop = true; this->rd_masc->Text = L"M"; this->rd_masc->UseVisualStyleBackColor = true; // // rd_fem // this->rd_fem->AutoSize = true; this->rd_fem->Location = System::Drawing::Point(794, 58); this->rd_fem->Name = L"rd_fem"; this->rd_fem->Size = System::Drawing::Size(31, 17); this->rd_fem->TabIndex = 13; this->rd_fem->TabStop = true; this->rd_fem->Text = L"F"; this->rd_fem->UseVisualStyleBackColor = true; // // rd_todos // this->rd_todos->AutoSize = true; this->rd_todos->Location = System::Drawing::Point(837, 58); this->rd_todos->Name = L"rd_todos"; this->rd_todos->Size = System::Drawing::Size(32, 17); this->rd_todos->TabIndex = 14; this->rd_todos->TabStop = true; this->rd_todos->Text = L"T"; this->rd_todos->UseVisualStyleBackColor = true; // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->AutoSizeMode = System::Windows::Forms::AutoSizeMode::GrowAndShrink; this->BackColor = System::Drawing::SystemColors::ControlLightLight; this->ClientSize = System::Drawing::Size(951, 572); this->Controls->Add(this->rd_todos); this->Controls->Add(this->rd_fem); this->Controls->Add(this->rd_masc); this->Controls->Add(this->txt_copia); this->Controls->Add(this->bt_copia); this->Controls->Add(this->data_copia); this->Controls->Add(this->bt_freguesia); this->Controls->Add(this->bt_velhos); this->Controls->Add(this->txt_result); this->Controls->Add(this->txt_localiza); this->Controls->Add(this->bt_localiza); this->Controls->Add(this->bt_limpa); this->Controls->Add(this->data_infos); this->Controls->Add(this->menuStrip1); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::Fixed3D; this->Icon = (cli::safe_cast<System::Drawing::Icon^>(resources->GetObject(L"$this.Icon"))); this->MainMenuStrip = this->menuStrip1; this->Name = L"Form1"; this->Text = L"Jorge Sepúlveda"; this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->data_infos))->EndInit(); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->data_copia))->EndInit(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { inicializa(); //Cria o ficheiro de delegado StreamWriter^ fp = gcnew StreamWriter("DELEGADO.TXT"); fp->Close(); data_infos->ColumnCount = 18; data_infos->Columns[5]->Name = "d1"; data_infos->Columns[5]->HeaderText = "POR"; data_infos->Columns[6]->Name = "d2"; data_infos->Columns[6]->HeaderText = "ING"; data_infos->Columns[7]->Name = "d3"; data_infos->Columns[7]->HeaderText = "FIL"; data_infos->Columns[8]->Name = "d4"; data_infos->Columns[8]->HeaderText = "MAT"; data_infos->Columns[9]->Name = "d5"; data_infos->Columns[9]->HeaderText = "FÍS"; data_infos->Columns[10]->Name = "d6"; data_infos->Columns[10]->HeaderText = "QUÍ"; data_infos->Columns[11]->Name = "d7"; data_infos->Columns[11]->HeaderText = "GEO"; data_infos->Columns[12]->Name = "d8"; data_infos->Columns[12]->HeaderText = "HIS"; data_infos->Columns[13]->Name = "d9"; data_infos->Columns[13]->HeaderText = "EF"; data_infos->Columns[14]->Name = "d10"; data_infos->Columns[14]->HeaderText = "MOR"; data_infos->Columns[15]->Name = "med"; data_infos->Columns[15]->HeaderText = "MED"; data_infos->Columns[16]->Name = "neg"; data_infos->Columns[16]->HeaderText = "NEG"; data_infos->Columns[17]->Name = "est"; data_infos->Columns[17]->HeaderText = "EST"; data_infos->Columns[15]->Visible = false; data_infos->Columns[16]->Visible = false; data_infos->Columns[17]->Visible = false; for (int i = 5; i < 17; i++) { data_infos->Columns[i]->Width = 35; data_infos->Columns[i]->DefaultCellStyle->Alignment = DataGridViewContentAlignment::MiddleCenter; } for (size_t i = 5; i < 15; i++) { for (size_t j = 0; j < 20; j++) { data_infos->Rows[j]->Cells[i]->Value = geravalor(); } } } //Função com a inicialização dos dados da datagridview private: void inicializa() { data_infos->Rows->Clear(); data_infos->Rows->Add("Ana Rita Cunha", "Maximinos", 1998, "F"); data_infos->Rows->Add("Bela Costa Silva", "Lomar", 2002, "F"); data_infos->Rows->Add("Carlos Alberto Costa", "Sequeira", 1999, "M"); data_infos->Rows->Add("Carlos Daniel Ferreira", "Sequeira", 2001, "M"); data_infos->Rows->Add("Daniel Bastos Gomes", "Lovios", 1998, "M"); data_infos->Rows->Add("Daniel Silva Ferraz", "S. Vítor", 1999, "M"); data_infos->Rows->Add("Elvira Gomes Pendes", "Maximinos", 2001, "F"); data_infos->Rows->Add("Fernanda Maria Silva", "S. Vítor", 2002, "F"); data_infos->Rows->Add("Fernando Gomes Barros", "Maximinos", 1999, "M"); data_infos->Rows->Add("Gilherme Alexandre Barros", "Lamaçães", 2001, "M"); data_infos->Rows->Add("Hilda Fonseca Silva", "S. Geraldo", 1999, "F"); data_infos->Rows->Add("José Manuel Carvalho", "Gualtar", 1997, "M"); data_infos->Rows->Add("José Alberto Gomes", "Maximinos", 2001, "M"); data_infos->Rows->Add("Maria Silvéria Bastos", "Maximinos", 1997, "F"); data_infos->Rows->Add("Anabela Bastos Torres", "S. Vítor", 1996, "F"); data_infos->Rows->Add("Rui Vasco Santos", "Maximinos", 2002, "M"); data_infos->Rows->Add("Otávio Ferreira", "Maximinos", 1999, "M"); data_infos->Rows->Add("Silvério Silva Teixeira", "Lamaçães", 2001, "M"); data_infos->Rows->Add("Teodoro Armando Matos", "Maximinos", 2002, "M"); data_infos->Rows->Add("Zacarias Alexandre Sampaio", "Ferreiros", 1996, "M"); } //Função mostrar/esconder linha e cabeçalhos private: void mostra_adicionar() { if (data_infos->RowHeadersVisible) { try { data_infos->RowHeadersVisible = false; data_infos->AllowUserToAddRows = false; verLinhaParaAdicionarToolStripMenuItem->Text = "Mostrar linha adicionar e cabeçalho"; } catch (...){} } else { try { data_infos->RowHeadersVisible = true; data_infos->AllowUserToAddRows = true; verLinhaParaAdicionarToolStripMenuItem->Text = "Esconder linha adicionar e cabeçalho"; } catch (...){} } } //Função que encontra o mais velho ou os mais velhos //Escreve os nomes e o ano de nascimento na textbox private: void mais_velhos() { int index = data_infos->Rows->Count - 1; int data_velho = Convert::ToInt16(data_infos->Rows[0]->Cells[2]->Value); String^ resultado = "Mais velho(s):\r\n"; for (size_t i = 1; i < index; i++) { if (Convert::ToInt16(data_infos->Rows[i]->Cells[2]->Value) < data_velho) { data_velho = Convert::ToInt16(data_infos->Rows[i]->Cells[2]->Value); } } for (size_t i = 1; i < index; i++) { if (Convert::ToInt16(data_infos->Rows[i]->Cells[2]->Value) == data_velho) { resultado = resultado + Convert::ToString(data_infos->Rows[i]->Cells[0]->Value) + ", " + Convert::ToString(data_infos->Rows[i]->Cells[2]->Value) + "\r\n"; } } txt_result->Visible = true; txt_result->Text = resultado; } private: void mostra_delegado() { if (data_infos->Columns["Delegado"]->Visible == false) { //data_infos->Width = data_infos->Width + 100; data_infos->Columns["Delegado"]->Visible = true; mostrarColunaDelegadoToolStripMenuItem->Text = "Esconder coluna do delegado"; } else { //data_infos->Width = data_infos->Width - 100; data_infos->Columns["Delegado"]->Visible = false; mostrarColunaDelegadoToolStripMenuItem->Text = "Mostrar coluna do delegado"; } } //Função para gerar as notas private: int geravalor() { //devolve valor entre 6 e 20 //para gerar números aleatórios: Random^ r = gcnew Random(); int avaliacao; int contador = 0; for (int k = 0; k < 9999999; k++) { //diversão ao processador, //para melhorar a geração de aleatórios } //gera um número entre 6 e 20 avaliacao = r->Next(6, 21); if (avaliacao < 10) { avaliacao = r->Next(6, 21); } return avaliacao; } private: System::Void Bt_limpa_Click(System::Object^ sender, System::EventArgs^ e) { inicializa(); } private: System::Void Bt_localiza_Click(System::Object^ sender, System::EventArgs^ e) { String^ busca = txt_localiza->Text->ToUpper(); int index = data_infos->Rows->Count-1; for (size_t i = 0; i < index; i++) { if (data_infos->Rows[i]->Cells[0]->Value->ToString()->ToUpper()==busca) { txt_result->Visible = true; txt_result->Text = data_infos->Rows[i]->Cells[0]->Value->ToString(); } index--; } } //Botão mais velhos private: System::Void Bt_velhos_Click(System::Object^ sender, System::EventArgs^ e) { mais_velhos(); } private: System::Void Bt_freguesia_Click(System::Object^ sender, System::EventArgs^ e) { int index = data_infos->Rows->Count - 1; int cont_freg = 0; String^ nomes = "Sexo masculino: \r\n\r\n"; for (size_t i = 0; i < index; i++) { if (data_infos->Rows[i]->Cells[1]->Value->ToString()->ToUpper() == txt_localiza->Text->ToUpper() && data_infos->Rows[i]->Cells[3]->Value->ToString()->ToUpper()== "M") { nomes = nomes + Convert::ToString(data_infos->Rows[i]->Cells[0]->Value->ToString()) + "\r\n"; cont_freg++; } } txt_result->Visible = true; txt_result->Text = nomes + "\r\nTotal: " + Convert::ToString(cont_freg); } private: System::Void VerLinhaParaAdicionarToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { mostra_adicionar(); } private: System::Void MostrarColunaDelegadoToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { mostra_delegado(); } private: System::Void SortearDelegadoToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { Random^ sorteio = gcnew Random();//para gerar números aleatórios int x = sorteio->Next(1, 20); //gera um número entre 1 e 20 int index = data_infos->Rows->Count - 1; for (size_t i = 0; i < index; i++) { data_infos->Rows[i]->Cells[4]->Value=" "; } data_infos->Rows[x]->Cells[4]->Value = "X"; } private: System::Void ReiniciarDatagridToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { inicializa(); } private: System::Void Txt_result_TextChanged(System::Object^ sender, System::EventArgs^ e) {} //Apagar linha selecionada private: System::Void RemoverLinhaSelecionadaToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { int index = data_infos->Rows->Count - 1; for (size_t i = 0; i < index; i++) { if (data_infos->Rows[i]->Selected) { data_infos->Rows->RemoveAt(i); } } } //Menu mais velhos private: System::Void MaisVelhosToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { mais_velhos(); } //Guardar nome do delegado em ficheiro (incompleto) private: System::Void GuardaDelegadoToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { String^ nome_delegado; StreamWriter^ fp = gcnew StreamWriter("DELEGADO.TXT"); int index = data_infos->Rows->Count - 1; for (size_t i = 0; i < index; i++) { if (data_infos->Rows[i]->Cells[4]->Value == "X") { nome_delegado = Convert::ToString(data_infos->Rows[i]->Cells[0]->Value); } } fp->WriteLine(nome_delegado); fp->Close(); } //Menu da média private: System::Void ClacularMédiasToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { data_infos->Columns[15]->Visible = true; calcula_media(); } //Função que calcula as média private: void calcula_media() { float media = 0; float soma = 0; for (size_t linhas = 0; linhas < 20; linhas++) { soma = 0; for (size_t colunas = 5; colunas < 15; colunas++) { soma = soma + Convert::ToInt16(data_infos->Rows[linhas]->Cells[colunas]->Value); } media = soma / 10; data_infos->Rows[linhas]->Cells[15]->Value = media.ToString("f2"); } data_infos->Columns[15]->DefaultCellStyle->ForeColor = Color::Blue; } //Procura as média mais altas e escreve na textbox private: System::Void MelhorAlunoToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { int media = 0; int media_alta = 0; String^ resultado = ""; for (size_t linhas = 0; linhas < 20; linhas++) { for (size_t colunas = 5; colunas < 15; colunas++) { media = media + Convert::ToInt16(data_infos->Rows[linhas]->Cells[colunas]->Value); } media = media / 10; if (media > media_alta) { resultado = ""; media_alta = media; resultado = resultado + Convert::ToString(data_infos->Rows[linhas]->Cells[0]->Value) + " " + Convert::ToString(media) + "\r\n"; } else if (media==media_alta) { resultado = resultado + Convert::ToString(data_infos->Rows[linhas]->Cells[0]->Value) + " " + Convert::ToString(media) + "\r\n"; } } for (size_t linhas = 0; linhas < 20; linhas++) { for (size_t colunas = 5; colunas < 15; colunas++) { if (Convert::ToInt16(data_infos->Rows[linhas]->Cells[colunas]->Value) >=18) { data_infos->Rows[linhas]->Cells[colunas]->Style->BackColor = Color::Green; } } } txt_result->Visible = true; txt_result->Text = resultado; } //Botão contar as negativas private: System::Void MostraNegativasToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { data_infos->Columns[16]->Visible = true; conta_negativas(); } //Função que conta as negativas private: void conta_negativas() { int contador = 0; for (size_t linhas = 0; linhas < 20; linhas++) { int contador = 0; for (size_t colunas = 5; colunas < 15; colunas++) { if (Convert::ToInt16(data_infos->Rows[linhas]->Cells[colunas]->Value) < 10) { data_infos->Rows[linhas]->Cells[colunas]->Style->BackColor = Color::OrangeRed; contador++; } if (Convert::ToInt16(data_infos->Rows[linhas]->Cells[colunas]->Value) < 8) { data_infos->Rows[linhas]->Cells[colunas]->Style->BackColor = Color::Red; } } data_infos->Rows[linhas]->Cells[16]->Value = contador; } } private: System::Void MostraReprovadosToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { data_infos->Columns[17]->Visible = true; reprovados(); } private: void reprovados() { bool reprovados = false; conta_negativas(); for (size_t linhas = 0; linhas < 20; linhas++) { reprovados = false; for (size_t colunas = 5; colunas < 15; colunas++) { //Verifica se o aluno tem uma nota abaixo de 8 if (Convert::ToDouble(data_infos->Rows[linhas]->Cells[colunas]->Value) < 8) { reprovados = true; } } //Verifica se o numero de negativas é maior que 2 if (Convert::ToDouble(data_infos->Rows[linhas]->Cells[16]->Value)>2) { reprovados = true; } //Coloca o estado na grid if (reprovados) { data_infos->Rows[linhas]->Cells[17]->Value = "Rep."; } else { data_infos->Rows[linhas]->Cells[17]->Value = "Ap."; } } } private: System::Void MostraDelegadoToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { int n_linhas = data_infos->Rows->Count - 1; StreamReader^ fp = gcnew StreamReader("DELEGADO.TXT"); String^ nome = fp->ReadLine(); if (existe(nome)) { for (size_t i = 0; i < n_linhas; i++) { //limpa a coluna: data_infos->Rows[i]->Cells[4]->Value = ""; } for (size_t i = 0; i < n_linhas; i++) { if (nome == data_infos->Rows[i]->Cells[0]->Value->ToString()) { //o nome foi encontrado: data_infos->Rows[i]->Cells[4]->Value = "X"; } } } fp->Close(); } private: bool existe(String^ s) { //afirmação: esse nome não existe: bool encontrado = false; for (size_t i = 0; i < data_infos->Rows->Count - 1; i++) { //se existir na grid, trocar o estado da vairável de boole: if (data_infos->Rows[i]->Cells[0]->Value->ToString() == s) encontrado = true; } return encontrado; } //Gerar notas aleatorias private: System::Void GerarNotasToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { for (size_t i = 5; i < 15; i++) { for (size_t j = 0; j < 20; j++) { data_infos->Rows[j]->Cells[i]->Value = geravalor(); } } } //Fechar o programa private: System::Void SairToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { Application::Exit(); } //Nome do autor private: System::Void AutorToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { MessageBox::Show("Jorge Sepúlveda"); } //Informação sobre a versão private: System::Void VersãoToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { MessageBox::Show("v0.0.2 \nVersão alfa, use por sua conta e risco."); } private: System::Void Bt_copia_Click(System::Object^ sender, System::EventArgs^ e) { //data_infos->Columns[17]->Visible = true; reprovados(); data_copia->Rows->Clear(); String^ copia_nome = " "; String^ copia_freguesia = " "; String^ copia_sexo = " "; String^ copia_estado = " "; for (size_t linhas = 0; linhas < 20; linhas++) { if (Convert::ToString(data_infos->Rows[linhas]->Cells[1]->Value) == txt_copia->Text && rd_masc->Checked) { if (Convert::ToString(data_infos->Rows[linhas]->Cells[3]->Value)=="M") { copia_nome = Convert::ToString(data_infos->Rows[linhas]->Cells[0]->Value); copia_freguesia = Convert::ToString(data_infos->Rows[linhas]->Cells[1]->Value); copia_sexo = Convert::ToString(data_infos->Rows[linhas]->Cells[3]->Value); copia_estado = Convert::ToString(data_infos->Rows[linhas]->Cells[17]->Value); data_copia->Rows->Add(copia_nome, copia_freguesia, copia_sexo, copia_estado); } } if (Convert::ToString(data_infos->Rows[linhas]->Cells[1]->Value) == txt_copia->Text && rd_fem->Checked) { if (Convert::ToString(data_infos->Rows[linhas]->Cells[3]->Value) == "F") { copia_nome = Convert::ToString(data_infos->Rows[linhas]->Cells[0]->Value); copia_freguesia = Convert::ToString(data_infos->Rows[linhas]->Cells[1]->Value); copia_sexo = Convert::ToString(data_infos->Rows[linhas]->Cells[3]->Value); copia_estado = Convert::ToString(data_infos->Rows[linhas]->Cells[17]->Value); data_copia->Rows->Add(copia_nome, copia_freguesia, copia_sexo, copia_estado); } } if (Convert::ToString(data_infos->Rows[linhas]->Cells[1]->Value) == txt_copia->Text && rd_todos->Checked) { copia_nome = Convert::ToString(data_infos->Rows[linhas]->Cells[0]->Value); copia_freguesia = Convert::ToString(data_infos->Rows[linhas]->Cells[1]->Value); copia_sexo = Convert::ToString(data_infos->Rows[linhas]->Cells[3]->Value); copia_estado = Convert::ToString(data_infos->Rows[linhas]->Cells[17]->Value); data_copia->Rows->Add(copia_nome, copia_freguesia, copia_sexo, copia_estado); } } } }; }
[ "jdsepulveda136@gmail.com" ]
jdsepulveda136@gmail.com
82e74661401d038e50284361fba37fd22b44ddc3
142ddd4c42dc7ff65fd9b531cfd0adbfe2a1dd34
/export/servers/physics/joints/cone_twist_joint_sw.h
cb97d921221e0e43346c7dc6b54dccb8a99ff872
[ "LicenseRef-scancode-free-unknown", "MIT", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "CC0-1.0", "OFL-1.1", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "FTL", "BSD-3-Clause", "Bitstream-Vera", "MPL-2.0", "Zlib", "CC-BY-4.0" ]
permissive
GhostWalker562/godot-admob-iOS-precompiled
3fa99080f224d1b4c2dacac31e3786cebc034e2d
18668d2fd7ea4bc5a7e84ddba36481fb20ee4095
refs/heads/master
2023-04-03T23:31:36.023618
2021-07-29T04:46:45
2021-07-29T04:46:45
195,341,087
24
2
MIT
2023-03-06T07:20:25
2019-07-05T04:55:50
C++
UTF-8
C++
false
false
5,287
h
/*************************************************************************/ /* cone_twist_joint_sw.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ /* Adapted to Godot from the Bullet library. */ /* Bullet Continuous Collision Detection and Physics Library ConeTwistJointSW is Copyright (c) 2007 Starbreeze Studios 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. Written by: Marcus Hennix */ #ifndef CONE_TWIST_JOINT_SW_H #define CONE_TWIST_JOINT_SW_H #include "servers/physics/joints/jacobian_entry_sw.h" #include "servers/physics/joints_sw.h" ///ConeTwistJointSW can be used to simulate ragdoll joints (upper arm, leg etc) class ConeTwistJointSW : public JointSW { #ifdef IN_PARALLELL_SOLVER public: #endif union { struct { BodySW *A; BodySW *B; }; BodySW *_arr[2]; }; JacobianEntrySW m_jac[3]; //3 orthogonal linear constraints real_t m_appliedImpulse; Transform m_rbAFrame; Transform m_rbBFrame; real_t m_limitSoftness; real_t m_biasFactor; real_t m_relaxationFactor; real_t m_swingSpan1; real_t m_swingSpan2; real_t m_twistSpan; Vector3 m_swingAxis; Vector3 m_twistAxis; real_t m_kSwing; real_t m_kTwist; real_t m_twistLimitSign; real_t m_swingCorrection; real_t m_twistCorrection; real_t m_accSwingLimitImpulse; real_t m_accTwistLimitImpulse; bool m_angularOnly; bool m_solveTwistLimit; bool m_solveSwingLimit; public: virtual PhysicsServer::JointType get_type() const { return PhysicsServer::JOINT_CONE_TWIST; } virtual bool setup(real_t p_timestep); virtual void solve(real_t p_timestep); ConeTwistJointSW(BodySW *rbA, BodySW *rbB, const Transform &rbAFrame, const Transform &rbBFrame); void setAngularOnly(bool angularOnly) { m_angularOnly = angularOnly; } void setLimit(real_t _swingSpan1, real_t _swingSpan2, real_t _twistSpan, real_t _softness = 0.8f, real_t _biasFactor = 0.3f, real_t _relaxationFactor = 1.0f) { m_swingSpan1 = _swingSpan1; m_swingSpan2 = _swingSpan2; m_twistSpan = _twistSpan; m_limitSoftness = _softness; m_biasFactor = _biasFactor; m_relaxationFactor = _relaxationFactor; } inline int getSolveTwistLimit() { return m_solveTwistLimit; } inline int getSolveSwingLimit() { return m_solveTwistLimit; } inline real_t getTwistLimitSign() { return m_twistLimitSign; } void set_param(PhysicsServer::ConeTwistJointParam p_param, real_t p_value); real_t get_param(PhysicsServer::ConeTwistJointParam p_param) const; }; #endif // CONE_TWIST_JOINT_SW_H
[ "pvu2002@outlook.com" ]
pvu2002@outlook.com
22aef41ae568ac9770b4afc5fdc2de085b87fcf0
75a9a84935c5cf75b17e93827f2f9a5d5f4d5777
/mistakes/Array.cpp
967bb1a18f17a01583ef129ec23b0db58625b36e
[]
no_license
weetee/something
8bfdf64839f86f03aaae1f82811596ede52f2885
2674b7b9f0a77815f4592b3b445a4332ffb0e2e9
refs/heads/master
2020-08-30T10:15:03.411361
2018-07-31T00:01:41
2018-07-31T00:01:41
94,389,644
0
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include <iostream> using namespace std; int main() { cout << "------------" << endl; int arr[3][2] = {{0,1}, {2,3}, {4,5}}; int *p = arr[0]; cout << p[0] << endl; //0 cout << "------------" << endl; int b = 2, c = 7, d = 5; int a; a = ++b, c--, d+3; cout << a << endl; //3 cout << "------------" << endl; char c_arr[3][3] = {{'a','b','c'},{'d','e','f'}, {'g','h','i'}}; cout << c_arr[1][4] << endl; //h cout << "------------" << endl; int (*p_arr)[2] = arr; cout << *(*(p_arr+1)+1) << endl; //3 cout << "------------" << endl; char str[][10] = {"China", "Beijing"}; char *p_str = str[0]; cout << p_str + 10 << endl; //Beijing return 0; }
[ "weitaoee@gmail.com" ]
weitaoee@gmail.com
a9e99e48a679cf063991c8c271a9955381049906
f5c30d45080b330f3eacbb703cec8c196697b207
/src/CCryptingDlg.cpp
f0ce92e9ce14c27bec8b96b3ea015ede42ea8ec0
[]
no_license
qr96/HelloCrypt
75c34b0442cb5e958abae2ef34d70eba676c7e9e
51a13964e28bd9a4ddf2a1c3725c9e6faf5d9aac
refs/heads/master
2022-12-11T11:55:45.446697
2020-09-01T11:32:29
2020-09-01T11:32:29
291,943,477
0
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
// CCryptingDlg.cpp: 구현 파일 // #include "pch.h" #include "HelloCrypt.h" #include "CryptingDlg.h" #include "afxdialogex.h" // CCryptingDlg 대화 상자 IMPLEMENT_DYNAMIC(CCryptingDlg, CDialogEx) CCryptingDlg::CCryptingDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_CRYPTING_DIALOG, pParent) , crypt_password1(_T("")) , crypt_password2(_T("")) { } CCryptingDlg::~CCryptingDlg() { } void CCryptingDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST1, crypt_list); DDX_Text(pDX, IDC_CRYPT_PASSWORD1, crypt_password1); DDV_MaxChars(pDX, crypt_password1, 16); DDX_Text(pDX, IDC_CRYPT_PASSWORD2, crypt_password2); DDV_MaxChars(pDX, crypt_password2, 16); DDX_Control(pDX, IDC_PROGRESS1, m_Progress); } BEGIN_MESSAGE_MAP(CCryptingDlg, CDialogEx) ON_NOTIFY(NM_CUSTOMDRAW, IDC_PROGRESS1, &CCryptingDlg::OnNMCustomdrawProgress1) ON_WM_DROPFILES() ON_BN_CLICKED(IDOK, &CCryptingDlg::OnBnClickedOk) ON_LBN_SELCHANGE(IDC_LIST1, &CCryptingDlg::OnLbnSelchangeList1) ON_BN_CLICKED(IDOK2, &CCryptingDlg::OnBnClickedOk2) END_MESSAGE_MAP() // CCryptingDlg 메시지 처리기
[ "qr96@naver.com" ]
qr96@naver.com
a23019c5e491d371b0cd71202736ba03bc8f8ece
5f0faeb7bbbe6372631b97928b3f6658c17b5de3
/P5_Extended_Kalman_Filters/src/kalman_filter.h
c246bb1bb378e05d8dad6a6d617bd95271723f4d
[ "MIT" ]
permissive
ShaliniShivakumar/Self-Driving-Car-Nanodegree
f800a476534c96a879d7f64d5172ee8bc1a1b0c1
b805e0568d2729578099c40209c2a8a3aa3194c3
refs/heads/main
2023-04-10T00:25:46.295999
2021-03-27T13:04:30
2021-03-27T13:04:30
351,864,932
0
0
null
null
null
null
UTF-8
C++
false
false
1,493
h
#ifndef KALMAN_FILTER_H_ #define KALMAN_FILTER_H_ #include "Eigen/Dense" #include <iostream> class KalmanFilter { public: /** * Constructor */ KalmanFilter(); /** * Destructor */ virtual ~KalmanFilter(); /** * Init Initializes Kalman filter * @param x_in Initial state * @param P_in Initial state covariance * @param F_in Transition matrix * @param H_in Measurement matrix * @param R_in Measurement covariance matrix * @param Q_in Process covariance matrix */ void Init(Eigen::VectorXd &x_in, Eigen::MatrixXd &P_in, Eigen::MatrixXd &F_in, Eigen::MatrixXd &H_in, Eigen::MatrixXd &R_in, Eigen::MatrixXd &Q_in); /** * Prediction Predicts the state and the state covariance * using the process model * @param delta_T Time between k and k+1 in s */ void Predict(); /** * Updates the state by using standard Kalman Filter equations * @param z The measurement at k+1 */ void Update(const Eigen::VectorXd &z); /** * Updates the state by using Extended Kalman Filter equations * @param z The measurement at k+1 */ void UpdateEKF(const Eigen::VectorXd &z); // state vector Eigen::VectorXd x_; // state covariance matrix Eigen::MatrixXd P_; // state transition matrix Eigen::MatrixXd F_; // process covariance matrix Eigen::MatrixXd Q_; // measurement matrix Eigen::MatrixXd H_; // measurement covariance matrix Eigen::MatrixXd R_; }; #endif // KALMAN_FILTER_H_
[ "shalini.shivakumar17@gmail.com" ]
shalini.shivakumar17@gmail.com
f8c11ad2dbd834fbc5b7da9ebb35e06af204bbb0
a46f0d8693fb1979b475e68c782030fd0bcb18e7
/Ch4_18_SpeedOfSound/Ch4_18_SpeedOfSound/SpeedOfSound.cpp
a38de07dda5d6b2aeaf807df54b607953a998ea1
[]
no_license
jgramelb/c-plus-plus
8c56c904ecde231d83c55ed579b88d429bd53d07
71d9efb2d1256ee08130737204b39312d1421b4a
refs/heads/master
2020-04-08T14:08:18.113375
2018-12-21T01:11:07
2018-12-21T01:11:07
159,423,571
2
0
null
null
null
null
UTF-8
C++
false
false
2,961
cpp
/****************************************************** **Name: Jeannie Ramelb **Date: December 20, 2018 **Description: Chapter 4 Problem 18. Speed of Sound ******************************************************/ #include <iostream> using std::cin; using std::cout; using std::endl; void displayMenu(); int getChoice(int, int); int main() { const int MIN_VALUE = 1; const int MAX_VALUE = 4; double feetAir, secAir, feetWater, secWater, feetSteel, secSteel; displayMenu(); int choice = getChoice(MIN_VALUE, MAX_VALUE); do { if (choice == 1) { cout << "Enter the number of feet a sound will travel through air " << endl; cin.clear(); cin.ignore(); cin >> feetAir; while (feetAir < 0.0) { cout << "Please enter a positive number for the distance. "; cin >> feetAir; } secAir = feetAir / 1100; cout << "Time it will take for sound to travel " << feetAir << " feet through air is: " << secAir << "\n\n" << endl; } if (choice == 2) { cout << "Enter the number of feet a sound will travel through water " << endl; cin.clear(); cin.ignore(); cin >> feetWater; while (feetWater < 0.0) { cout << "Please enter a positive number for the distance. "; cin >> feetWater; } secWater = feetWater / 4900; cout << "Time it will take for sound to travel " << feetWater << " feet through air is: " << secWater << "\n\n" << endl; } if (choice == 3) { cout << "Enter the number of feet a sound will travel through steel" << endl; cin.clear(); cin.ignore(); cin >> feetSteel; while (feetSteel < 0.0) { cout << "Please enter a positive number for the distance. "; cin >> feetSteel; } secSteel = feetSteel / 1100; cout << "Time it will take for sound to travel " << feetSteel << " feet through air is: " << secSteel << "\n\n" << endl; } if (choice == 4) { cout << "The program will now end " << endl; } } while (choice != 4); return 0; } /*********************************************** **Description: displayMenu() **This function displays the user's menu on the screen **********************************************/ void displayMenu() { cout << "\n\nGThe Speed of Sound\n\n"; cout << "This program calculates the time it takes for\n" << "for the speed of sound based on the medium chosen. \n\n"; cout << "1. Air\n"; cout << "2. Water\n"; cout << "3. Steel\n"; cout << "4. Quit\n\n"; cout << "Enter your choice (1-4):"; } /************************************************ **Description:: getChoice() **This function get, validates, and returns the user's choice *************************************************/ int getChoice(int min, int max) { int choice; cin.clear(); cin >> choice; while (!cin || choice < min || choice > max) { cout << "Choice must be between " << min << " and " << max << ". \n" << "Please re-enter choice: "; cin.clear(); cin.ignore(); cin >> choice; } return choice; }
[ "jeannie.ramelb@gmail.com" ]
jeannie.ramelb@gmail.com
925572a98bf37e4ff1ab6094b6849069b06bed99
560fc2ce85280b08a018a5f6f6eba93e9161f8fb
/source/helpers/dirty.hpp
93115d9be7703ee7d985ef8d34628fadcc0dd87f
[]
no_license
segrax/firy
c62411611351c3820439abcc093a6b3bd3934b9a
aceb0a6ad7536734d6e48f3edeeefb5e3305ec56
refs/heads/master
2023-02-11T13:53:21.667990
2021-01-17T01:33:59
2021-01-17T01:33:59
312,756,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
hpp
/* * FIRY * --------------- * * Copyright (C) 2019-2021 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ namespace firy { namespace helpers { class cDirty { public: cDirty() : mDirty(false) {} virtual inline bool isDirty() const { return mDirty; } /** * Set dirty state, return state */ virtual inline bool dirty(const bool pVal = true) { mDirty = pVal; return mDirty; } private: volatile bool mDirty; }; } }
[ "robcrossfield@gmail.com" ]
robcrossfield@gmail.com
a44c3e41b2559f020bc788aebdd8bfa31a14cdc9
1470f1d211f52afd48d25dfb1eea177a69461b3c
/LeetCode-HARD/Leetcode057/Main.cpp
5fc55a611a5581bb815b83b99197d1e449616dfe
[]
no_license
Mazziruso/LeetCode-Solution
31c1a923af64f38c851e53688136db2df2264c18
ea22c9f013381eb6c817182495828e459399fcad
refs/heads/master
2020-04-03T01:16:20.089306
2019-04-16T16:24:14
2019-04-16T16:24:14
154,925,727
0
0
null
null
null
null
UTF-8
C++
false
false
2,855
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; class Solution { public: vector<Interval> intervals; int binarySearch(int l, int r, int k) { int mid; while(l<r) { mid = l+(r-l)/2; if(intervals[mid].start<k) { l = mid+1; } else { r = mid; } } if(intervals[l].start<k) { return l+1; } return l; } vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { int n = intervals.size(); vector<Interval> res; if(n==0) { res.push_back(newInterval); return res; } this->intervals = intervals; int index; Interval mergeInt; int s,e; //start index = binarySearch(0, n-1, newInterval.start); //start if(index==n) { s = (newInterval.start<=intervals[index-1].end) ? index-1 : index; mergeInt.start = (newInterval.start<=intervals[index-1].end) ? intervals[index-1].start : newInterval.start; } else if(intervals[index].start != newInterval.start) { if(index>0 && intervals[index-1].end>=newInterval.start){ s = index-1; mergeInt.start = intervals[index-1].start; } else { s = index; mergeInt.start = newInterval.start; } } else { s = index; mergeInt.start = intervals[index].start; } //end index = binarySearch(0, n-1, newInterval.end); if(index==n) { e = index; mergeInt.end = max(newInterval.end, intervals[index-1].end); } else if(intervals[index].start != newInterval.end) { if(index>0 && intervals[index-1].end>=newInterval.end){ e = index; mergeInt.end = intervals[index-1].end; }else { e = index; mergeInt.end = newInterval.end; } } else { e = index+1; mergeInt.end = intervals[index].end; } index = 0; while(index<s) { res.push_back(intervals[index]); index++; } res.push_back(mergeInt); index=e; while(index<n) { res.push_back(intervals[index]); index++; } return res; } }; int main() { vector<Interval> ints({Interval(1,5)}); vector<Interval> res = Solution().insert(ints, Interval(2,3)); for(auto i : res) { cout << i.start << " " << i.end << endl; } return 0; }
[ "33518504+Mazziruso@users.noreply.github.com" ]
33518504+Mazziruso@users.noreply.github.com
8067ef50ebb7a77e10fed2e23e528025153efef8
29e2f465fcd00023849f8a99f25c038eb1b488a1
/source/util/ck_util.cpp
7eb05ea4087c2c941e729c00ced7a8c524bb59f5
[]
no_license
Kiti-Nomad/catcake
e8fdaef9cab9d048e09d214105f71c08830f7644
7e5ed2bfd47d3e500860f9c3dab3d231198e244a
refs/heads/master
2022-02-05T01:17:23.438907
2018-07-03T10:37:43
2018-07-03T10:37:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,492
cpp
/* Copyright (c) 2007-2010 Takashi Kitao 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 "ck_util_all.h" #include "ck_res_all.h" #include "ck_low_level_api.h" u32 ckUtil::strlen(const char* str) { if (!str) { ckThrow(ExceptionInvalidArgument); } u32 len = 0; while (*str) { str++; len++; } return len; } u32 ckUtil::wcslen(const wchar_t* str) { if (!str) { ckThrow(ExceptionInvalidArgument); } u32 len = 0; while (*str) { str++; len++; } return len; } void ckUtil::charToWchar(wchar_t* buf, u32 buf_size, const char* str) { if (!buf || buf_size == 0 || !str) { ckThrow(ExceptionInvalidArgument); } for (u32 i = 0; i < buf_size; i++) { char c = str[i]; if (!c) { buf[i] = L'\0'; break; } buf[i] = c; } buf[buf_size - 1] = L'\0'; } const char* ckUtil::getBasename(const char* filename) { if (!filename) { ckThrow(ExceptionInvalidArgument); } const char* base = filename; for (const char* c = base; *c != '\0'; c++) { if (*c == '\\' || *c == '/' || *c == ':') { base = c + 1; } } return base; } const char* ckUtil::getExtension(const char* filename) { if (!filename) { ckThrow(ExceptionInvalidArgument); } const char* ext = getBasename(filename); for ( ; *ext != '\0'; ext++) { if (*ext == '.') return ext + 1; } return ext; } void ckUtil::calcNormalAsTriangles(ckVec* normal, const ckPrim::PrimData* prim_data, u16 vert_num, bool is_smoothing) { if (!normal || !prim_data || vert_num == 0) { ckThrow(ExceptionInvalidArgument); } if (vert_num < 3) { for (s32 i = 0; i < vert_num; i++) { normal[i] = ckVec::Z_UNIT; } return; } u16 tri_vert_num = (vert_num / 3) * 3; for (s32 i = 0; i < tri_vert_num; i += 3) { ckVec vec1 = prim_data[i + 1].pos - prim_data[i].pos; ckVec vec2 = prim_data[i + 2].pos - prim_data[i].pos; normal[i] = normal[i + 1] = normal[i + 2] = vec1.cross(vec2).normalize(); } for (s32 i = tri_vert_num; i < vert_num; i++) { normal[i] = ckVec::Z_UNIT; } if (!is_smoothing) { return; } u32 mark_buf_size = sizeof(u16) * vert_num; u16* mark_buf = static_cast<u16*>(ckMalloc(mark_buf_size)); ckMemMgr::memset(mark_buf, 0, mark_buf_size); for (s32 i = 0; i < vert_num; i++) { if (mark_buf[i] > 0) { continue; } u16 mark = i + 1; u16 mark_num = 1; const ckVec& pos1 = prim_data[i].pos; const ckVec& n1 = normal[i]; ckVec avgn = n1; mark_buf[i] = mark; for (s32 j = i + 1; j < vert_num; j++) { const ckVec& pos2 = prim_data[j].pos; const ckVec& n2 = normal[j]; if (pos1.x == pos2.x && pos1.y == pos2.y && pos1.z == pos2.z) { r32 inner = n1.dot(n2); if (inner > 0.7071f) // cos 45 { mark_buf[j] = mark; mark_num++; if (inner < 1.0f - ckMath::EPSILON) { avgn += n2; } } } } if (mark_num > 1) { if (avgn.x == 0.0f && avgn.y == 0.0f && avgn.z == 0.0f) { continue; } avgn = avgn.normalize(); for (s32 j = i; j < vert_num; j++) { if (mark_buf[j] == mark) { normal[j] = avgn; } } } } ckFree(mark_buf); } bool ckUtil::readJpegInfo(u16* width, u16* height, ckTex::TexFormat* format, const void* data, u32 data_size) { if (!width || !height || !format || !data || data_size == 0) { ckThrow(ExceptionInvalidArgument); } ckLowLevelAPI::TextureFormat texture_format; bool res = ckLowLevelAPI::readJpegInfo(width, height, &texture_format, data, data_size); *format = static_cast<ckTex::TexFormat>(ckTex::FORMAT_PNG_RGB + texture_format); //*format = ckTex::FORMAT_JPEG_RGB; return res; } bool ckUtil::readJpegImage(void* buf, u32 buf_size, u32 buf_line_size, const void* data, u32 data_size) { if (!buf || buf_size == 0 || buf_line_size == 0 || !data || data_size == 0) { ckThrow(ExceptionInvalidArgument); } return ckLowLevelAPI::readJpegImage(buf, buf_size, buf_line_size, data, data_size); } bool ckUtil::readPNGInfo(u16* width, u16* height, ckTex::TexFormat* format, const void* data, u32 data_size) { if (!width || !height || !format || !data || data_size == 0) { ckThrow(ExceptionInvalidArgument); } ckLowLevelAPI::TextureFormat texture_format; bool res = ckLowLevelAPI::readPNGInfo(width, height, &texture_format, data, data_size); *format = static_cast<ckTex::TexFormat>(ckTex::FORMAT_PNG_RGB + texture_format); return res; } bool ckUtil::readPNGImage(void* buf, u32 buf_size, u32 buf_line_size, const void* data, u32 data_size) { if (!buf || buf_size == 0 || buf_line_size == 0 || !data || data_size == 0) { ckThrow(ExceptionInvalidArgument); } return ckLowLevelAPI::readPNGImage(buf, buf_size, buf_line_size, data, data_size); } void ckUtil::loadWindowsFont(const char* filename) { if (!filename) { ckThrow(ExceptionInvalidArgument); } char buf[256]; ckLowLevelAPI::getWindowsFontDirectory(buf, 256); ckStr<char, 255> str = buf; str += filename; ckResMgr::loadResource(str.getString(), true); } void ckUtil::loadShader(ckID shd_id, const char* vert_file, const char* frag_file, u8 uni_num, u8 att_num, u8 tex_num) { ckID vert_id = ckID::genID(); char* vert_code = NULL; if (vert_file) { ckResMgr::loadResourceAs(vert_id, vert_file, false); ckRes res = ckResMgr::getResource(vert_id); vert_code = static_cast<char*>(ckMalloc(res.getDataSize() + 1)); ckMemMgr::memcpy(vert_code, res.getData<void>(), res.getDataSize()); vert_code[res.getDataSize()] = '\0'; ckResMgr::removeResource(vert_id); } ckID frag_id = ckID::genID(); char* frag_code = NULL; if (frag_file) { ckResMgr::loadResourceAs(frag_id, frag_file, false); ckRes res = ckResMgr::getResource(frag_id); frag_code = static_cast<char*>(ckMalloc(res.getDataSize() + 1)); ckMemMgr::memcpy(frag_code, res.getData<void>(), res.getDataSize()); frag_code[res.getDataSize()] = '\0'; ckResMgr::removeResource(frag_id); } ckDrawMgr::newShader(shd_id, vert_code, frag_code, uni_num, att_num, tex_num); if (vert_code) { ckFree(vert_code); } if (frag_code) { ckFree(frag_code); } }
[ "root@berry-love.tk" ]
root@berry-love.tk
8b99460b41621dab359dbcb60e47ae2c33bd858e
3bc55e096d0a9fd5b70de6838d5c127bf45e3bf2
/double_dispatch1.cpp
4531bcae7b0c39845b17dfce15ed30a4e66cb510
[ "MIT" ]
permissive
mjaimin/design_patterns
90975441c6e2442bd4f5991904cd713b18953e84
0d5ebcbb0e8a71bf31f7ea3bf3f308837cf72b76
refs/heads/master
2022-04-01T16:04:11.735641
2020-01-06T02:10:45
2020-01-06T02:10:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,896
cpp
// Double dispatching via virtual functions #include <iostream> #include <memory> #include <string> class Cat; class Bird; class Dog; struct IAnimal { virtual std::string name() const = 0; virtual void play(const IAnimal&) const = 0; virtual void play(const Cat&) const = 0; virtual void play(const Bird&) const = 0; virtual void play(const Dog&) const = 0; virtual ~IAnimal() = default; }; class Cat: public IAnimal { public: std::string name() const override { return "Cat"; } void play(const IAnimal& animal) const override { animal.play(*this); // double dispatching } void play(const Cat&) const override; void play(const Dog&) const override; void play(const Bird&) const override; }; class Dog: public IAnimal { public: std::string name() const override { return "Dog"; } void play(const IAnimal& animal) const override { animal.play(*this); // double dispatching } void play(const Cat&) const override; void play(const Dog&) const override; void play(const Bird&) const override; }; class Bird: public IAnimal { public: std::string name() const override { return "Bird"; } void play(const IAnimal& animal) const override { animal.play(*this); // double dispatching } void play(const Cat&) const override; void play(const Dog&) const override; void play(const Bird&) const override; }; void Cat::play(const Cat& cat) const { std::cout << name() << " plays with " << cat.name() << '\n'; } void Cat::play(const Bird& bird) const { std::cout << name() << " plays with " << bird.name() << '\n'; } void Cat::play(const Dog& dog) const { std::cout << name() << " plays with " << dog.name() << '\n'; } void Dog::play(const Cat& cat) const { std::cout << name() << " plays with " << cat.name() << '\n'; } void Dog::play(const Bird& bird) const { std::cout << name() << " plays with " << bird.name() << '\n'; } void Dog::play(const Dog& dog) const { std::cout << name() << " plays with " << dog.name() << '\n'; } void Bird::play(const Cat& cat) const { std::cout << name() << " plays with " << cat.name() << '\n'; } void Bird::play(const Bird& bird) const { std::cout << name() << " plays with " << bird.name() << '\n'; } void Bird::play(const Dog& dog) const { std::cout << name() << " plays with " << dog.name() << '\n'; } void play(const IAnimal& first, const IAnimal& second) { second.play(first); } int main() { std::unique_ptr<IAnimal> upCat{std::make_unique<Cat>()}; std::unique_ptr<IAnimal> upDog{std::make_unique<Dog>()}; std::unique_ptr<IAnimal> upBird{std::make_unique<Bird>()}; play(*upCat, *upDog); play(*upCat, *upBird); play(*upDog, *upBird); play(*upDog, *upCat); play(*upBird, *upCat); play(*upBird, *upDog); }
[ "vsoftco@gmail.com" ]
vsoftco@gmail.com
6aa5b0d877d3a912639b4b15f8c1531542d05bc9
45bf55ec0e4fc8a6893ec2ff8f223b52c3c2708f
/Cascade/bl.cpp
018274c98ec684e1fe2fd1500c48a9183a0a129d
[]
no_license
qiaoranliqu/WorkSpace
e4fd72e81e475f771442b678cb0d858b8c108939
a62a357c26a665597170dc6cb13f6901664ebb95
refs/heads/master
2023-01-01T08:17:03.549045
2020-10-30T13:06:30
2020-10-30T13:06:30
294,959,563
0
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
#include<cstdio> #include<algorithm> #include<cstring> #include<map> using namespace std; int ty,key,val; map<int,int>mp; int main() { freopen("data.in","r",stdin); freopen("bl.out","w",stdout); for (int i=0;i<500000;++i) { scanf("%d%d",&ty,&key); if (ty==0) { scanf("%d",&val); mp[key]=val; } else if (ty==1) { if (mp.find(key)==mp.end()) puts("None key matches!"); else printf("%d\n",mp[key]); } else if (ty==2) { if (mp.find(key)==mp.end()) puts("This key is already deleted!"); else mp.erase(key); } else if (ty==3) { scanf("%d",&val); mp[key]=val; } } }
[ "857075272@qq.com" ]
857075272@qq.com
4c9203c8dbc3603cfecd04bfcba404489d925d40
c3869ba42919ce534216a7585931c0e0a8216955
/upp/uppsrc/Docking/Docking.h
9fb90dfc534461fcc96a531fefd0d9524cc621e6
[]
no_license
RanJi0128/Chromium-customization
018c977c26a270387a2d9b3c1855a0668691b477
89b3550d7fc6f1b61f5e6023c293b82c521c509d
refs/heads/master
2020-07-13T01:31:26.499121
2019-08-29T07:07:17
2019-08-29T07:07:17
204,954,330
2
1
null
null
null
null
UTF-8
C++
false
false
21,626
h
#ifndef _Docking_Docking_h_ #define _Docking_Docking_h_ #include <CtrlLib/CtrlLib.h> #include <TabBar/TabBar.h> namespace Upp { class DockWindow; #include "ToolWin.h" #include "DockableCtrl.h" #include "DockMenu.h" #include "DockTabBar.h" #include "DockCont.h" #include "DockPane.h" class DockWindow : public TopWindow { public: typedef DockWindow CLASSNAME; enum { DOCK_NONE = -1, DOCK_LEFT = SplitterFrame::LEFT, DOCK_TOP = SplitterFrame::TOP, DOCK_RIGHT = SplitterFrame::RIGHT, DOCK_BOTTOM = SplitterFrame::BOTTOM, }; virtual void State(int reason); virtual bool Key(dword key, int count); protected: enum { TIMEID_ACTION_CHECK = Ctrl::TIMEID_COUNT, TIMEID_ANIMATE, TIMEID_ANIMATE_DELAY, TIMEID_COUNT }; // DnD interface struct HighlightCtrl : public DockableCtrl { HighlightCtrl() { BackPaint(); } void ClearHighlight() { img.Clear(); buffer.Clear(); } void SetHighlight(const Value& hl, bool _isnested, bool cannest, Image bg = Image()); void SetNested(bool _isnested); void CreateBuffer(); virtual void Paint(Draw& w); int oldframesize; Rect bounds; private: Image img; Image buffer; bool isnested; bool cannest; const Value *highlight; }; struct PosInfo : public Moveable<PosInfo> { PosInfo() : state(DockCont::STATE_NONE) {} DockCont::DockState state; // State info Ptr<DockCont> tabcont;// Only valid when ctrl was tabbed String data; // Serialized context info dependent on state }; protected: // Highlight control virtual HighlightCtrl& GetHighlightCtrl() { return hlc; } void StartHighlight(DockCont *dcptr); void Highlight(int align, DockCont& cont, DockCont *target); void StopHighlight(bool do_animatehl); virtual bool NeedFrameReorder(int align); bool IsReorderingFrames() { return prehighlightframepos >= 0; } // Called by containers to signal drag-drop events virtual void ContainerDragStart(DockCont& dc); virtual void ContainerDragMove(DockCont& dc); virtual void ContainerDragEnd(DockCont& dc); // Container docking/undocking void DockContainer(int align, DockCont& c, int pos = -1); void DockAsTab(DockCont& target, DockableCtrl& dc); void DockContainerAsTab(DockCont& target, DockCont& c, bool do_nested); void FloatContainer(DockCont& c, Point p = Null, bool move = true); void FloatFromTab(DockCont& c, DockableCtrl& tab) { FloatFromTab(c, *CreateContainer(tab)); } void FloatFromTab(DockCont& c, DockCont& tab); void AutoHideContainer(int align, DockCont& c); void CloseContainer(DockCont& c); DockCont *TabifyGroup(String group); void Undock(DockCont& c); void Unfloat(DockCont& c); void Detach(DockCont& c) { Undock(c); Unfloat(c); } // For finding drag-drop targets and computing boundary rect DockCont *GetMouseDockTarget(); DockCont *FindDockTarget(DockCont& dc, int& al); int FindDocker(const Ctrl *dc); Rect GetAlignBounds(int al, Rect r, bool center, bool allow_lr = true, bool allow_tb = true); int GetPointAlign(const Point p, Rect r, bool center, bool allow_lr = true, bool allow_tb = true); int GetQuad(Point p, Rect r); Rect GetFinalAnimRect(int align, Ctrl& c); // Helpers bool IsTL(int align) const { return align < 2; } //ie (align == DOCK_LEFT || align == DOCK_TOP) bool IsTB(int align) const { return align & 1; } //ie (align == DOCK_TOP || align == DOCK_BOTTOM) int GetDockAlign(const Ctrl& c) const; int GetDockAlign(const Point& p) const; int GetAutoHideAlign(const DockCont& c) const; bool IsFrameAnimating(int align) const { return frameanim[align].inc; } bool IsPaneAnimating(int align) const { return dockpane[align].IsAnimating(); } bool CheckNesting() const { return (GetMouseFlags() & nesttoggle) ? !nestedtabs : nestedtabs; } void DoHotKeys(dword key); void SaveDockerPos(DockableCtrl& dc, PosInfo& pi); void SetDockerPosInfo(DockableCtrl& dc, const PosInfo& pi); friend class DockCont; private: bool init; bool tabbing; bool autohide; bool animatehl; bool animatefrm; bool animatewnd; bool nestedtabs; bool grouping; bool menubtn; bool closebtn; bool hidebtn; bool dockable[4]; bool locked; bool tabtext; bool tabalign; bool frameorder; bool showlockedhandles; bool childtoolwindows; dword nesttoggle; String layoutbackup; int dockframepos; int prehighlightframepos; Array<DockCont> conts; Vector<DockableCtrl *> dockers; ArrayMap<String, String> layouts; Array<DockableCtrl> ctrls; HighlightCtrl hlc; DockPane dockpane[4]; SplitterFrame dockframe[4]; AutoHideBar hideframe[4]; DockMenu menu; Vector<PosInfo> dockerpos; struct FrameAnim { FrameAnim() : target(0), inc(0) {} int target; int inc; }; FrameAnim frameanim[4]; int animdelay; public: // If you are attaching DockableCtrls programmatically it must be done in an overloaded DockInit. // It is called after Ctrl::OPEN in order so that docking can be done with the correct window size. virtual void DockInit() { } // Attaches all the required frames to the DockWindow. // It is called internally on Ctrl::Open so should not usually be needed void DockLayout(bool tb_precedence = true); // Functions for registering/deregistering externally owned DockableCtrls // NOTE: Registering is automatically done when using Dock/Float etc functions, but Register // also be called before DockInit (eg in constructor), and are prefered if you are only going // to be serializing the DockWindow layout DockableCtrl& Register(DockableCtrl& dc); void Deregister(const DockableCtrl& dc); // Creates an internal DockableCtrl for you to allow simple wrapping of GUI elements DockableCtrl& Dockable(Ctrl& ctrl, WString title); DockableCtrl& Dockable(Ctrl& ctrl, const char *title = 0) { return Dockable(ctrl, (WString)title); } // More flexible methods for creating internally stored DockableCtrl derived classes template<class T> T& CreateDockable(WString title); template<class T> T& CreateDockable(const char *title = 0) { return CreateDockable<T>((WString)title); } // Get a list of all registered DockableCtrls (including externally owned ones const Vector<DockableCtrl *>& GetDockableCtrls() const { return dockers; } // Simple docking control void DockLeft(DockableCtrl& dc, int pos = -1) { Dock(DOCK_LEFT, dc, pos); } void DockTop(DockableCtrl& dc, int pos = -1) { Dock(DOCK_TOP, dc, pos); } void DockRight(DockableCtrl& dc, int pos = -1) { Dock(DOCK_RIGHT, dc, pos); } void DockBottom(DockableCtrl& dc, int pos = -1) { Dock(DOCK_BOTTOM, dc, pos); } void Dock(int align, DockableCtrl& dc, int pos = -1); // Attaches 'dc' as a tab to 'target', wherever it may be void Tabify(DockableCtrl& target, DockableCtrl& dc); // Detaches the passed ctrl as a floating window void Float(DockableCtrl& dc, Point p = Null); void Float(DockableCtrl& dc, const char *title, Point p = Null); // Attaches the passed ctrl to the autohide frames on the window edges // If no alignment is given the ctrl will be autohidden where it is docked or to the top bar if not docked void AutoHide(DockableCtrl& dc); void AutoHide(int align, DockableCtrl& dc); // Closes the window, detaching it from and docking panes or autohide frames. // This just 'hides' the window, it can be opened again at any time. void Close(DockableCtrl& dc); // Activate the passed ctrl. If open this will make sure it's the active tab, if // closed the ctrls last known position will be restored (see RestoreDockerPos) void ActivateDockable(Ctrl& c); // As above, but you can pass any child ctrl of the DockableCtrl (useful with the Dockable functions) void ActivateDockableChild(Ctrl& c); // When DockableCtrls change state a record of their last position is stored internally. // These functions can restore the previous DockableCtrl's postion of force a save of the current one void SaveDockerPos(DockableCtrl& dc); void RestoreDockerPos(DockableCtrl& dc, bool savefirst = false); // Toggle window visibility. If the window is open it is hidden, if it is hidden it is restored void HideRestoreDocker(DockableCtrl& dc); // Group docking ctrl. These work the same way as for single DockableCtrls but apply to the passed group // TabDockGroup and DockGroup will respect the DockAllowed settings for DockableCtrls void DockGroup(int align, String group, int pos = -1); void FloatGroup(String group); void AutoHideGroup(int align, String group); void AutoHideGroup(String group); void TabFloatGroup(String group); void CloseGroup(String group); void TabDockGroup(int align, String group, int pos = -1); // These variants of DockGroup and DockTabGroup ignore the DockAllowed settings void ForceDockGroup(int align, String group, int pos = -1); void ForceTabDockGroup(int align, String group, int pos = -1); // Check docking frame visibility. If there are no docked ctrls it will be invisibly bool IsDockVisible(int align) const { ASSERT(align >= 0 && align <= 4); return dockpane[align].IsVisible(); } // Manually sets the size of a docking frame void SetFrameSize(int align, int size); // Animation settings. Disabling various forms of animation can improve performance when // you have complex displays/GUIs in either DockableCtrls of the DockWindow client area DockWindow& AnimateDelay(int ms) { animdelay = max(ms, 0); return *this; } DockWindow& Animate(bool highlight = true, bool frames = true, bool windows = true, int ticks = 10, int interval = 20); DockWindow& NoAnimate() { return Animate(false, false); } bool IsAnimated() const { return animatehl || animatewnd; } bool IsAnimatedHighlight() const { return animatehl; } bool IsAnimatedFrames() const { return animatefrm; } bool IsAnimatedWindows() const { return animatewnd; } // Lock control. When the layout is locked the user cannot use the drag-drop functionality, the // title bar buttons or the titlebar context menus. ShowLockedHandles determines whether the // title bar is shown on docked ctrls when the layout is locked. void LockLayout(bool lock = true); void UnlockLayout() { LockLayout(true); } bool IsLocked() const { return locked; } DockWindow& ShowLockedHandles(bool show = true) { showlockedhandles = show; SyncAll(); return *this; } bool IsShowingLockedHandles() const { return showlockedhandles; } // Enableing TabAutoAlign will move docked tab bars depending on where their contained is docked. // For instance, a collection of controls docked one the left edge will have it's tab bar moved // to its ;left hand side DockWindow& TabAutoAlign(bool al = true); // If this is disabled only icons will be shown when windows are tabbed (in containers of autohidden) DockWindow& TabShowText(bool text = true); // Enable/Disable tabbing support DockWindow& Tabbing(bool _tabbing = true) { tabbing = _tabbing; return *this; } DockWindow& NoTabbing() { return Tabbing(false); } bool IsTabbing() const { return tabbing; } // Enable/Disable multi-layer tab support (groups of tabs stored as a tab in another group) // When enabled the user can use this function by holding NestedToggleKey during a drag-drop DockWindow& NestedTabs(bool _nestedtabs = true) { nestedtabs = _nestedtabs; return *this; } DockWindow& NoNestedTabs() { return NestedTabs(false); } bool IsNestedTabs() const { return nestedtabs; } dword NestedToggleKey() { return nesttoggle; } DockWindow& SetNestedToggleKey(dword key) { nesttoggle = key; return *this; } // Enable/Disable grouping support DockWindow& Grouping(bool grouping = true); DockWindow& NoGrouping() { return Grouping(false); } bool IsGrouping() const { return grouping; } // Allows the user to change docking frame precedence/ordering. By default the left and right // frames take precedence over the top/bottom frames (meaning they occupy the entire height of the window) // When this option is enabled the user chan change this by dragging to the appropriate corner of the frame DockWindow& FrameReordering(bool reorder = true){ frameorder = reorder; return *this;} DockWindow& NoFrameReordering() { return FrameReordering(false); } bool IsFrameReordering() const { return frameorder; } DockWindow& SetFrameOrder(int first, int second = DOCK_NONE, int third = DOCK_NONE, int fourth = DOCK_NONE); // Allow/Block docking to particular sides of the DockWindow. This works in conjunction with // the settings in the DockableCtrl class. DockWindow& AllowDockAll(); DockWindow& AllowDockNone(); DockWindow& AllowDockLeft(bool v = true) { dockable[DOCK_LEFT] = v; return *this; } DockWindow& AllowDockTop(bool v = true) { dockable[DOCK_TOP] = v; return *this; } DockWindow& AllowDockRight(bool v = true) { dockable[DOCK_RIGHT] = v; return *this; } DockWindow& AllowDockBottom(bool v = true) { dockable[DOCK_BOTTOM] = v; return *this; } DockWindow& AllowDock(int a, bool v = true) { ASSERT(a >= 0 && a < 4); dockable[a] = v; return *this; } bool IsDockAllowed(int align) const { ASSERT(align >= 0 && align < 4); return dockable[align]; } bool IsDockAllowed(int align, DockableCtrl& dc) const; bool IsDockAllowedLeft() const { return dockable[DOCK_LEFT]; } bool IsDockAllowedTop() const { return dockable[DOCK_TOP]; } bool IsDockAllowedRight() const { return dockable[DOCK_RIGHT]; } bool IsDockAllowedBottom() const { return dockable[DOCK_BOTTOM]; } bool IsDockAllowedAny() const { return dockable[DOCK_LEFT] || dockable[DOCK_TOP] || dockable[DOCK_RIGHT] || dockable[DOCK_BOTTOM]; } bool IsDockAllowedNone() const { return !IsDockAllowedAny(); } // Enable/Disable the AutoHide functions DockWindow& AutoHide(bool v = true); bool IsAutoHide() { return autohide; } // Determines which buttons are visible on docked/autohidden DockableCtrl title bars DockWindow& WindowButtons(bool menu, bool hide, bool close); bool HasMenuButtons() const { return menubtn; } bool HasHideButtons() const { return hidebtn; } bool HasCloseButtons() const { return closebtn; } // When enabled (default) floating DockableCtrl windows are set to be tool windows // (exactly what this means varies between OSs) void ChildToolWindows(bool v = true) { childtoolwindows = v; SyncAll(); } bool HasToolWindows() const { return childtoolwindows; } // Opens the standard Docking Configuration dialog (see DockConfig) void DockManager(); // Returns the standard Docking menu so that an application can add it to it's main menu bar void DockWindowMenu(Bar& bar); // SerializeWindow serialized both the DockWindow layout and the window position/state (using TopWindow::SerializePlacement) void SerializeWindow(Stream& s); // SerializeLayout only serializes the DockQWindow layout void SerializeLayout(Stream& s, bool withsavedlayouts = true); // Saves/Load/Manage dockwindow layouts. Theese are handy for saving different // GUI configurations for different application states (like editing/debugging) int SaveLayout(String name); void LoadLayout(int ix); void LoadLayout(String name); void DeleteLayout(String name) { layouts.RemoveKey(name); } String GetLayoutName(int ix) const { return layouts.GetKey(ix); } int LayoutCount() const { return layouts.GetCount(); } const ArrayMap<String, String>& GetLayouts() const { return layouts; } // Serializes/Loads layout to/from an internal buffer (used for cancelling changes in the DockConfig window) // The difference between this and Save/LoadLayout is that it also backs-up the saved layouts void BackupLayout(); void RestoreLayout(); // This enables/disables all floating windows. This can be used to prevent the user // moving windows when a dialog is visible (like DockConfig) void DisableFloating() { EnableFloating(false); } void EnableFloating(bool enable = true); // Changes the Chameleon style for the highlight ctrl void SetHighlightStyle(DockableCtrl::Style& s) { GetHighlightCtrl().SetStyle(s); } // Constructer DockWindow(); private: // Container management DockCont *GetContainer(Ctrl& dc) { return dynamic_cast<DockCont *>(dc.GetParent()); } DockCont *CreateContainer(); DockCont *CreateContainer(DockableCtrl& dc); void DestroyContainer(DockCont& c); DockCont *GetReleasedContainer(DockableCtrl& dc); void SyncContainer(DockCont& c); void SyncAll(); // Helpers void Dock0(int align, Ctrl& c, int pos, bool do_animatehl = false, bool ishighlight = false); void Dock0(int align, Ctrl& c, int pos, Size sz, bool do_animatehl = false, bool ishighlight = false); void Undock0(Ctrl& c, bool do_animatehl = false, int fsz = -1, bool ishighlight = false); void Activate(DockableCtrl& dc); void DoFrameSize(bool animate, int align, int targetsize); void FrameAnimateTick(); void DoFrameReorder(int align); void UndoFrameReorder(); Size CtrlBestSize(const Ctrl& c, int align, bool restrict = true) const; void ClearLayout(); }; class PopUpDockWindow : public DockWindow { public: struct Style : ChStyle<Style> { Value inner[5]; Value outer[4]; Value hide[4]; Value highlight; int innersize; int outersize; }; static const Style& StyleDefault(); protected: virtual void ContainerDragStart(DockCont& dc); virtual void ContainerDragMove(DockCont& dc); virtual void ContainerDragEnd(DockCont& dc); private: struct PopUpButton : public Ctrl { const Value *icon; const Value *hlight; virtual void Paint(Draw& w) { Rect r = GetSize(); ChPaint(w, r, *icon); if (hlight) ChPaint(w, r, *hlight); } PopUpButton() { hlight = NULL; } }; const Style *style; DockCont *last_target; PopUpButton *last_popup; PopUpButton inner[5]; PopUpButton outer[4]; PopUpButton hide[4]; bool showhide; int PopUpHighlight(PopUpButton *pb, int cnt); void ShowOuterPopUps(DockCont& dc); void ShowInnerPopUps(DockCont& dc, DockCont *target); void ShowPopUp(PopUpButton& pb, const Rect& r); void HidePopUps(bool _inner, bool _outer); public: PopUpDockWindow& SetStyle(const Style& s); PopUpDockWindow(); PopUpDockWindow& AutoHidePopUps(bool v = true) { showhide = v; return *this; } }; #define LAYOUTFILE <Docking/Docking.lay> #include <CtrlCore/lay.h> class DockConfigDlg : public WithDockConfigLayout<TopWindow> { public: typedef DockConfigDlg CLASSNAME; DockConfigDlg(DockWindow& dockwindow); private: DockWindow & dock; const Vector<DockableCtrl *>& dockers; VectorMap<String, int> groups; DockMenu menu; String backup; int all; DockableCtrl *highlight; void RefreshTree(bool dogroups = false); void OnTreeContext(Bar& bar); void OnSaveLayout(); void OnLoadLayout(); void OnDeleteLayout(); void OnTreeCursor(); void OnListCursor(); void OnNewGroup(); void OnDeleteGroup(); void OnOK(); void OnCancel(); void OnLock(); void OnTreeDrag(); void OnTreeDrop(int parent, int ii, PasteClip& d); void Highlight(DockableCtrl *dc); void StopHighlight(); void DeleteGroup(int id); String DockerString(DockableCtrl *dc) const; String PositionString(DockableCtrl *dc) const; int ListIndex() const; void DupePrompt(String type); }; template <class T> T& DockWindow::CreateDockable(WString title) { T &q = ctrls.Create<T>(); Register(q.Title(title)); return q; } } #endif
[ "you@example.com" ]
you@example.com
58d890572d1940a6787e4d7fe1353b06d219759e
bf013ac9608c7f11ec9ee1eb1197529422d02848
/huggle/exceptionwindow.hpp
81921b9e23dff63ab6d9c38183910cf39acb9785
[]
no_license
9shi/huggle3-qt-lx
e2064d04f378a0356df639c26723efdb79daf58b
07974ded3bddb16d982ee8376d4374a88bf704d9
refs/heads/master
2021-01-15T14:18:22.456129
2014-01-09T15:31:34
2014-01-09T15:32:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
hpp
//This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. #ifndef EXCEPTIONWINDOW_H #define EXCEPTIONWINDOW_H #if _MSC_VER #define TRACING 0 #else #define TRACING 1 #endif #include <QDialog> #include "core.hpp" #if TRACING //#include <execinfo.h> #endif #include "exception.hpp" namespace Ui { class ExceptionWindow; } namespace Huggle { //! Recovery window class ExceptionWindow : public QDialog { Q_OBJECT public: explicit ExceptionWindow(Exception *e); ~ExceptionWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_3_clicked(); private: Ui::ExceptionWindow *ui; }; } #endif // EXCEPTIONWINDOW_H
[ "benapetr@gmail.com" ]
benapetr@gmail.com
ce3b48135d568d3503558bebfc0694f523b72d87
b6607ecc11e389cc56ee4966293de9e2e0aca491
/codeforces.com/Contests/160 div 2/A/A.cpp
2a191ea1cc56e5f169afc2da77f930d67143566e
[]
no_license
BekzhanKassenov/olymp
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
e3013095a4f88fb614abb8ac9ba532c5e955a32e
refs/heads/master
2022-09-21T10:07:10.232514
2021-11-01T16:40:24
2021-11-01T16:40:24
39,900,971
5
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
/**************************************** ** Solution by Bekzhan Kassenov ** ****************************************/ #include <iostream> #include <cstdio> #include <fstream> #include <sstream> #include <string> #include <vector> #include <deque> #include <queue> #include <stack> #include <map> #include <set> #include <list> #include <algorithm> #include <cstdlib> #include <cmath> #include <ctime> #include <iomanip> using namespace std; #define PII pair <int, int> #define F first #define S second #define MP make_pair #define PB push_back #define VI vector <int> #define sqr(x) (x) * (x) #define INF (int) (2e9) #define MOD (1000 * 1000 * 1000 + 7) #define ull unsigned long long #define ll long long int cnt(int n) { int ans = 0; while (n) { if (n % 10 == 4 || n % 10 == 7) ans++; n /= 10; } return ans; } int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); #endif int n, k; cin >> n >> k; int ans = 0; int x; for (int i = 0; i < n ;i++) { cin >> x; if (cnt(x) <= k) ans++; } cout << ans; return 0; }
[ "bekzhan.kassenov@nu.edu.kz" ]
bekzhan.kassenov@nu.edu.kz
298c7c18d7706c162db908249255c10e56a1871e
b110c07c077672594db91a2827a97b189cd0f761
/reference/bfs.cpp
3ce6eaaa15e54507616aba32f715cec37a142953
[]
no_license
sandheepp/Shortest-cycle-in-a-graph
acc68ac23fce9298124af48f1a1df55455f5289d
7966b76890029ec460db8ee7a4a8e16d41d5c033
refs/heads/master
2022-12-03T15:06:54.599918
2020-08-26T17:03:45
2020-08-26T17:03:45
203,951,051
1
0
null
null
null
null
UTF-8
C++
false
false
2,853
cpp
/* BFS (G, s) //Where G is the graph and s is the source node let Q be queue. Q.enqueue( s ) //Inserting s in queue until all its neighbour vertices are marked. mark s as visited. while ( Q is not empty) //Removing that vertex from queue,whose neighbour will be visited now v = Q.dequeue( ) //processing all the neighbours of v for all neighbours w of v in Graph G if w is not visited Q.enqueue( w ) //Stores w in Q to further visit its neighbour. mark w as visited. */ // A C++ Program to detect cycle in a graph #include<iostream> #include <list> #include <limits.h> using namespace std; class Graph { int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency lists bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic() public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isCyclic(); // returns true if there is a cycle in this graph }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } // This function is a variation of DFSUtil() in https://www.geeksforgeeks.org/archives/18212 bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack) { if(visited[v] == false) { // Mark the current node as visited and part of recursion stack visited[v] = true; recStack[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) return true; else if (recStack[*i]) continue; } } recStack[v] = false; // remove the vertex from recursion stack return false; } // Returns true if the graph contains a cycle, else false. // This function is a variation of DFS() in https://www.geeksforgeeks.org/archives/18212 bool Graph::isCyclic() { // Mark all the vertices as not visited and not part of recursion // stack bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; recStack[i] = false; } // Call the recursive helper function to detect cycle in different // DFS trees for(int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if(g.isCyclic()) cout << "Graph contains cycle"; else cout << "Graph doesn't contain cycle"; return 0; }
[ "sandheep.p01gmail.com" ]
sandheep.p01gmail.com
f24c11d4a9bd5f7539a40f86af21a9dae5e6654e
934f7ba52f4856129effe9948d4de5573307c776
/Utils/Quantize Wrap.cpp
f3eef809fbcae9675509fed55c6e16c67fed1ace
[]
no_license
FluffyQuack/JA2-113
9663176a66610e7685e953aafe66b9fdfad0e474
a53fb01b69ec12296b6022613e978ba713b90c32
refs/heads/master
2023-05-05T08:05:41.594371
2021-05-18T15:17:25
2021-05-18T15:17:25
368,576,923
0
0
null
null
null
null
UTF-8
C++
false
false
2,022
cpp
#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include "types.h" #include "himage.h" #include "Quantize.h" #include "Quantize Wrap.h" #include "phys math.h" typedef struct { UINT8 r; UINT8 g; UINT8 b; } RGBValues; BOOLEAN QuantizeImage( UINT8 *pDest, UINT8 *pSrc, INT16 sWidth, INT16 sHeight, SGPPaletteEntry *pPalette ) { INT16 sNumColors; // FIRST CREATE PALETTE CQuantizer q( 255, 6 ); q.ProcessImage( pSrc, sWidth, sHeight ); sNumColors = q.GetColorCount(); memset( pPalette, 0, sizeof( SGPPaletteEntry ) * 256 ); q.GetColorTable( (RGBQUAD*)pPalette ); // THEN MAP IMAGE TO PALETTE // OK, MAPIT! MapPalette( pDest, pSrc, sWidth, sHeight, sNumColors, pPalette ); return( TRUE ); } void MapPalette( UINT8 *pDest, UINT8 *pSrc, INT16 sWidth, INT16 sHeight, INT16 sNumColors, SGPPaletteEntry *pTable ) { INT32 cX, cY, cnt, bBest; real dLowestDist; real dCubeDist; vector_3 vTableVal, vSrcVal, vDiffVal; UINT8 *pData; RGBValues *pRGBData; pRGBData = (RGBValues*)pSrc; for ( cX = 0; cX < sWidth; cX++ ) { for ( cY = 0; cY < sHeight; cY++ ) { // OK, FOR EACH PALETTE ENTRY, FIND CLOSEST bBest = 0; dLowestDist = (float)9999999; pData = &(pSrc[ ( cY * sWidth ) + cX ]); for ( cnt = 0; cnt < sNumColors; cnt++ ) { vSrcVal.x = pRGBData[ ( cY * sWidth ) + cX ].r; vSrcVal.y = pRGBData[ ( cY * sWidth ) + cX ].g; vSrcVal.z = pRGBData[ ( cY * sWidth ) + cX ].b; vTableVal.x = pTable[ cnt ].peRed; vTableVal.y = pTable[ cnt ].peGreen; vTableVal.z = pTable[ cnt ].peBlue; // Get Dist vDiffVal = VSubtract( &vSrcVal, &vTableVal ); // Get mag dist dCubeDist = VGetLength( &(vDiffVal) ); if ( dCubeDist < dLowestDist ) { dLowestDist = dCubeDist; bBest = cnt; } } // Now we have the lowest value // Set into dest pData = &(pDest[ ( cY * sWidth ) + cX ]); //Set! *pData = (UINT8)bBest; } } }
[ "git@fluffyquack.com" ]
git@fluffyquack.com
6f3ad2842e57324c3364977274302b57eace6450
0805ca8bb3e2aa9027efc413677e2a74791146c0
/src/rpc/protocol.cpp
e85ab142d6e4540d182e420298255030ebb694c2
[ "MIT" ]
permissive
omn14/scicoin
f2403bb26b76029a4c7466d329e2c505772a32ce
8b48d9e800304781de7a777f4a93432357b0b133
refs/heads/master
2021-01-16T18:09:29.231945
2017-11-24T16:10:45
2017-11-24T16:10:45
100,041,187
0
0
null
null
null
null
UTF-8
C++
false
false
3,739
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/protocol.h" #include "random.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "version.h" #include <stdint.h> #include <fstream> /** * JSON-RPC protocol. Scicoin speaks version 1.0 for maximum compatibility, * but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were * unspecified (HTTP errors and contents of 'error'). * * 1.0 spec: http://json-rpc.org/wiki/specification * 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html */ UniValue JSONRPCRequestObj(const std::string& strMethod, const UniValue& params, const UniValue& id) { UniValue request(UniValue::VOBJ); request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return request; } UniValue JSONRPCReplyObj(const UniValue& result, const UniValue& error, const UniValue& id) { UniValue reply(UniValue::VOBJ); if (!error.isNull()) reply.push_back(Pair("result", NullUniValue)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } std::string JSONRPCReply(const UniValue& result, const UniValue& error, const UniValue& id) { UniValue reply = JSONRPCReplyObj(result, error, id); return reply.write() + "\n"; } UniValue JSONRPCError(int code, const std::string& message) { UniValue error(UniValue::VOBJ); error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } /** Username used when cookie authentication is in use (arbitrary, only for * recognizability in debugging/logging purposes) */ static const std::string COOKIEAUTH_USER = "__cookie__"; /** Default name for auth cookie file */ static const std::string COOKIEAUTH_FILE = ".cookie"; fs::path GetAuthCookieFile() { fs::path path(GetArg("-rpccookiefile", COOKIEAUTH_FILE)); if (!path.is_complete()) path = GetDataDir() / path; return path; } bool GenerateAuthCookie(std::string *cookie_out) { const size_t COOKIE_SIZE = 32; unsigned char rand_pwd[COOKIE_SIZE]; GetRandBytes(rand_pwd, COOKIE_SIZE); std::string cookie = COOKIEAUTH_USER + ":" + HexStr(rand_pwd, rand_pwd+COOKIE_SIZE); /** the umask determines what permissions are used to create this file - * these are set to 077 in init.cpp unless overridden with -sysperms. */ std::ofstream file; fs::path filepath = GetAuthCookieFile(); file.open(filepath.string().c_str()); if (!file.is_open()) { LogPrintf("Unable to open cookie authentication file %s for writing\n", filepath.string()); return false; } file << cookie; file.close(); LogPrintf("Generated RPC authentication cookie %s\n", filepath.string()); if (cookie_out) *cookie_out = cookie; return true; } bool GetAuthCookie(std::string *cookie_out) { std::ifstream file; std::string cookie; fs::path filepath = GetAuthCookieFile(); file.open(filepath.string().c_str()); if (!file.is_open()) return false; std::getline(file, cookie); file.close(); if (cookie_out) *cookie_out = cookie; return true; } void DeleteAuthCookie() { try { fs::remove(GetAuthCookieFile()); } catch (const fs::filesystem_error& e) { LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, e.what()); } }
[ "sirole@gmail.com" ]
sirole@gmail.com
9b63ca09918d20b1c9366b3706b22d7881b90c17
1a749e90a8a70df85d027cba362dc517e901b8a0
/linear.cpp
867acadf1a00b5907b121cbf4765231cdf8432da
[]
no_license
kunalkumar37/c-programming
2cb11bd9b96ea86a1fa4dc5eff031e217d54661a
d3c02753cdea628774484da4fb331b4a4057078d
refs/heads/master
2023-07-13T05:01:46.989537
2021-08-20T10:51:28
2021-08-20T10:51:28
310,206,689
2
1
null
2021-08-20T10:51:29
2020-11-05T06:13:27
C++
UTF-8
C++
false
false
441
cpp
#include<iostream> #include<climits> using namespace std; int main() { int n; cin>>n; int arr[n]; for(int i=1;i<=n;i++) { cin>>arr[i]; } int maxno=INT_MIN; int minno=INT_MAX; for(int i=0;i<n;i++) { if(arr[i]>maxno) { maxno=arr[i]; } if(arr[i]<minno) { minno=arr[i]; } } cout<<maxno<<endl<<minno; return 0; }
[ "61112064+kunalkumar37@users.noreply.github.com" ]
61112064+kunalkumar37@users.noreply.github.com
f4dadd70b3f2e23d9c1798ec721f467493bdab58
f005b1511ca69533ee31649a2a921f0238aea784
/cxx/indexer/cxx/testdata/template/template_var_ps_completes.cc
ca6d858c57e3101f975774435318d37d89f88da0
[ "Apache-2.0" ]
permissive
gameduell/kythe
8bce30ab0dd7ad968754702357bc853ca247181a
be21e512a21d8e37604d6a9d373a963ad9cf4f6d
refs/heads/master
2016-09-05T23:21:04.111891
2015-07-24T14:10:32
2015-07-24T14:10:32
39,763,950
1
0
null
null
null
null
UTF-8
C++
false
false
270
cc
// Checks completion edges for variable template partial specializations. template <typename T, typename S> extern T z; //- @z defines VarZPsAbsDecl template <typename U> extern int z<int, U>; //- @z completes/uniquely VarZPsAbsDecl template <typename U> int z<int, U>;
[ "itar@dl-pir.office.gameduell.de" ]
itar@dl-pir.office.gameduell.de
697e62f43e1cf2d5cd7669e3e70d567f24f2db7a
85e7114ea63a080c1b9b0579e66c7a2d126cffec
/SDK/SoT_BP_Eye_Col_Brown_03_Desc_classes.hpp
30b47f4a0da02dcd6b4b53771aae062b0e26ce51
[]
no_license
EO-Zanzo/SeaOfThieves-Hack
97094307d943c2b8e2af071ba777a000cf1369c2
d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51
refs/heads/master
2020-04-02T14:18:24.844616
2018-10-24T15:02:43
2018-10-24T15:02:43
154,519,316
0
2
null
null
null
null
UTF-8
C++
false
false
734
hpp
#pragma once // Sea of Thieves (1.2.6) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_eye_col_brown_03_Desc_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_eye_col_brown_03_Desc.BP_eye_col_brown_03_Desc_C // 0x0000 (0x00E0 - 0x00E0) class UBP_eye_col_brown_03_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass BP_eye_col_brown_03_Desc.BP_eye_col_brown_03_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
59b809e7464365b10fdbe79497ef8bc335ad16ed
1f013e822124dfe9b4611f1fe08675a23871566e
/home/TomaszGusciora/z1/LAN.cpp
65277a4f2570107579360ad0ff82ef6cdccd2605
[]
no_license
dtraczewski/zpk2014
a1d9a26d25ff174561e3b20c8660901178d827a5
548970bc5a9a02215687cb143d2f3f44307ff252
refs/heads/master
2021-01-21T06:06:32.044028
2015-09-06T12:17:07
2015-09-06T12:17:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include <iostream> using namespace std; int main(){ int nr,rok; cin >> nr >> rok; cout << ((nr % 10) * 2 + 5) * 50 + 1764 - rok << endl; }
[ "tgusciora@student.uw.edu.pl" ]
tgusciora@student.uw.edu.pl
0eb57ac7beca6040ff07bbc832e1cdfbbc0c2ac9
719f6aa6740f92d84091f30263901540b6daa864
/SummerNodeProject/Model/HashTable2016.hpp
d664c8c578a4099ffb1f63b6f80e2235740a6825
[]
no_license
tonidavis/SummerNodeProject
05e0cf49b57293284d39a717877ef7b274278cac
52d912d2b68cd1206f2760782899b73d26febfb9
refs/heads/master
2021-01-20T19:57:04.650936
2016-07-29T20:22:55
2016-07-29T20:22:55
64,252,126
0
0
null
null
null
null
UTF-8
C++
false
false
697
hpp
// // HashTable2016.hpp // SummerNodeProject // // Created by Henrichsen, Cody on 7/29/16. // Copyright © 2016 CTEC. All rights reserved. // #ifndef HashTable2016_hpp #define HashTable2016_hpp #include "HashNode.cpp" template <class Type> class HashTable { private: long capacity; long size; double efficiencyPercentage; HashNode<Type> * front; bool isPrime(int sampleNumber); void resize(); long nextPrime(long current); long findPosition(Type data); long handleCollision(Type data, long currentPosition); public: HashTable(); void add(Type data); bool remove(Type data); void displayContents(); }; #endif /* HashTable2016_hpp */
[ "cody.henrichsen@740s-pl-114.local" ]
cody.henrichsen@740s-pl-114.local
acbe9f00e126d5788b6727a2a79b97e966a057cc
a265e6cb1bb132d551cf1bba068bf3357d81ce1c
/SimpleTrees/trees.h
10aa93882a035b0ab10c17b6cb40d1105ee824c6
[]
no_license
Can-ZHOU/CS2LL3
50eee24530251be98db3348ba1b24c6f19bedc0c
1c0d6d4ef6da3a02ac9c8473d4ac917403535b2d
refs/heads/master
2022-11-22T00:12:32.091726
2020-07-24T16:37:07
2020-07-24T16:37:07
257,650,144
0
0
null
null
null
null
UTF-8
C++
false
false
942
h
#include "rules.h" #include <fstream> using namespace std; #if !defined TREE_H #define TREE_H //! a node in a syntax tree class Tree { public: Category mother; //!< label of node in a tree vector<Tree *> dtrs; //!< the daughters of the node, each being a dynamically allocated Tree pointer Tree(void); ~Tree(void); Tree(Category c); //!< sets mother to c Tree(Category m, vector<Tree *> ds); // pertaining to drawing the output void drawtree(void); //!< shows the tree on standard output with standard ascii characters void draw_just_top(void); //!< shows the top-layer on standard output with standard ascii characters void dot_tree(void); //!< uses the dot program and ghostscript to show tree in graphical way void dot_tree(ostream& f); static int node_count; private: void drawdtrs(vector<Tree *> dtrs, string prefix); void drawtree(Tree *t, int prefix); void printspaces(int prefix); }; #endif
[ "zhoucan1999@outlook.com" ]
zhoucan1999@outlook.com
939aec2ebbb2ee99895dbcc243c6c34be1eef793
fb6ecd662c1b7eb156df99d3b1dbaa3702e17244
/include/gals/input-fields/levelset.h
b3f973fdba5a601b829e316a75b9eb86c869d5c6
[ "BSD-3-Clause" ]
permissive
acrlakshman/gradient-augmented-levelset-cuda
440176d6f2906fc00cc55fae861a443867949995
63f4b7225940fabd5a3145a0faa97bdcfc9b4e6e
refs/heads/master
2020-04-21T05:48:58.879857
2019-07-29T15:22:26
2019-07-29T15:22:26
169,350,742
1
0
BSD-3-Clause
2019-08-18T19:04:29
2019-02-06T03:35:56
C++
UTF-8
C++
false
false
2,220
h
/////////////////////////////////////////////////////////////////////////////// // Copyright 2019 Lakshman Anumolu, Raunak Bardia. // // 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. /////////////////////////////////////////////////////////////////////////////// #pragma once #include "gals/utilities/vec3.h" #include <string> namespace GALS { namespace INPUT_FIELDS { struct Levelset { std::string name; //! Name of levelset field. GALS::CPU::Vec3<double> center; //! Center of levelset field for few levelset types. double radius; //! Radius of levelset field for few object types. std::string gradient_scheme; //! Scheme to compute gradient of levelset field. }; } // namespace INPUT_FIELDS } // namespace GALS
[ "acrlakshman@yahoo.co.in" ]
acrlakshman@yahoo.co.in
78e01f84b733ee0c20708ab3fa9e620181fa3e21
2c738fe6fef5ffcd24af68f35257ec9d6359710f
/src/signALib/SAVariantCaster.h
0132a4f626990992c147cf1227c6b583170558ff
[]
no_license
zxqdlenovo/sa
6fffb1e61ac698f9bce4698993fa7b8abc06fd99
ce22face1da284070dd44681f6b34b8eb867f781
refs/heads/master
2020-03-18T19:11:11.815652
2018-04-24T05:54:40
2018-04-24T05:54:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
h
#ifndef SAVARIANTCASTER_H #define SAVARIANTCASTER_H #include <QVariant> #include <QIODevice> #include "SALibGlobal.h" /// /// \brief 扩展QVariant的转换 /// class SALIB_EXPORT SAVariantCaster { public: SAVariantCaster(); static QString variantToString(const QVariant& var); static QVariant stringToVariant(const QString& var, const QString& typeName); template<typename T> static QString converVariantToBase64String(const QVariant& var) { if(var.canConvert<T>()) { QByteArray byte; QDataStream st(&byte,QIODevice::ReadWrite); T ba = var.value<T>(); st << ba; return QString(byte.toBase64()); } return QString(); } template<typename T> static QVariant converBase64StringToVariant(const QString& base64) { QByteArray byte = QByteArray::fromBase64(base64.toLocal8Bit()); QDataStream st(&byte,QIODevice::ReadWrite); T ba; st >> ba; return QVariant::fromValue(ba); } }; #endif // SAVARIANTCASTER_H
[ "czy.t@163.com" ]
czy.t@163.com
c602a022e747f23f7fbfc8b6e94fa59f9f89ee00
48c27471b8d5aa435ae7ff45f74ba88576a9b68a
/src/qt/guiutil.cpp
2e58d1499f121efba105f815b26e4d23db9fc549
[ "MIT" ]
permissive
eysho/BestKnownGame-Coins---Source
591798ee8c561212756032d5c945838f724c702b
32cfcbdd9ce45671fcab93133628982470c91cff
refs/heads/master
2021-01-10T19:31:47.795365
2014-09-05T18:42:40
2014-09-05T18:42:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,464
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #else #include <QUrl> #endif #include <QTextDocument> // for Qt::mightBeRichText #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin URI if(!uri.isValid() || uri.scheme() != QString("nichts")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("nichts://")) { uri.replace(0, 11, "nichts:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item (global clipboard) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard); // Copy first item (global mouse selection for e.g. X11 - NOP on Windows) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection); } } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip)) { // Envelop with <qt></qt> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "Nichts.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "nichts.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=Nichts\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("Nichts-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " nichts-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("Nichts-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
[ "eysho@bkg.me" ]
eysho@bkg.me
8c152f80717ccf4e8547ce7b32c2ac01b2e2e8cb
7970d87f6871c5562db95ea91439054dbea1e333
/GameObject.h
bd8427332613097f98b3d3844ca080a2f31edcd2
[]
no_license
rkqls00/D2D1
6493303ac0afcc25127786e09462f36638fe1aa3
0dbde18bfcca2b1590ae71b80a11adc014a25691
refs/heads/master
2022-11-26T11:39:23.835884
2020-08-02T12:27:11
2020-08-02T12:27:11
284,225,348
0
0
null
null
null
null
UHC
C++
false
false
901
h
#pragma once class CGameObject : public IGameObject //0504 { protected: D2D1_POINT_2F m_Pos; //위치 CSprite* m_Sprite; //이미지 D2D1_POINT_2F m_BPos; public: D2D1_POINT_2F m_Scale; //크기 D2D1_RECT_F m_rTiled; //사이즈 INT m_tag; CStringW m_Name; //이름 BOOL m_isLive; //죽음? 살음? INT m_PLife; //플레이어의 생명 INT m_BLife; //보스 생명 INT m_Option; CGameObject(LPCWSTR sFileName, D2D1_POINT_2F Pos, int sprWidth, int sprHeight, int tag); virtual ~CGameObject(void); virtual void Render() override; //비어있어도 정의는 해야됨 virtual void FrameMove(DWORD elapsed) override; //비어있어도 정의는 해야됨 virtual void Control( CInput* Input) override; //07 //비어있어도 정의는 해야됨 D2D1_POINT_2F GetPos() { return m_Pos; } };
[ "53118916+gabin00@users.noreply.github.com" ]
53118916+gabin00@users.noreply.github.com
f4e409c6fdb6c39e1d4e157a97e3f27872afac90
3415cce948e5cc506280d9683bacd06a022acb39
/include/container.h
853adc5258c069da0237334d08dc7b6cadf35f95
[ "MIT" ]
permissive
Articula/RPG-Game-Engine
d7da9949c3379f19f8b7cebaa3fc1f4e51acd224
dd0ae407b813593a2f7936d3c53e892673d2cc50
refs/heads/master
2020-06-04T08:40:10.085327
2014-06-26T21:27:07
2014-06-26T21:27:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
594
h
/* * container.h * * Created on: Dec 8, 2013 * Author: faye */ #ifndef CONTAINER_H_ #define CONTAINER_H_ #include <list> #include <string> #include "drawable.h" class Container: public Drawable { public: Container(); virtual ~Container(); virtual std::list<Container*> GetChildren(); static bool LoadAttribute (const std::string* attribute, const std::string* value); protected: private: const std::string* pId_; Container* pParent_; std::list<Container*> children_; }; #endif /* CONTAINER_H_ */
[ "articula@hotmail.com" ]
articula@hotmail.com
004c14afa6a1bf3d004fc75012742eb415995ed0
02095cd4aeaa3a0d724f7362cdb8795fe9a81620
/oplink/algorithms/team/src/skeleton/utils/fuzzylite/src/term/Gaussian.cpp
153095a7aa455fc056c88fc803fdce9f34cdcd28
[]
no_license
PAL-ULL/software-metco
ba5123cb1423fed4a2ac678ab375728ba4bbfbc8
59edc4e49bddbd9fc7237bf2f24271bdfc8afd79
refs/heads/master
2021-04-15T04:12:56.292543
2021-03-08T13:29:14
2021-03-08T13:29:14
126,484,450
10
5
null
2020-07-21T18:43:10
2018-03-23T12:49:10
C++
UTF-8
C++
false
false
1,889
cpp
/* Copyright 2013 Juan Rada-Vilela Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * Gaussian.cpp * * Created on: 29/11/2012 * Author: jcrada */ #include "fl/term/Gaussian.h" #include <cmath> #include <sstream> namespace fl { Gaussian::Gaussian(const std::string& name, scalar mean, scalar sigma) : Term(name), _mean(mean), _standardDeviation(sigma) { } Gaussian::~Gaussian() { } std::string Gaussian::className() const { return "Gaussian"; } Gaussian* Gaussian::copy() const { return new Gaussian(*this); } scalar Gaussian::membership(scalar x) const { if (fl::Op::isNan(x)) return fl::nan; return std::exp((-(x - _mean) * (x - _mean)) / (2 * _standardDeviation * _standardDeviation)); } std::string Gaussian::toString() const { std::ostringstream ss; ss << className() << " (" <<fl::Op::str( _mean) << ", " << fl::Op::str(_standardDeviation) << ")"; return ss.str(); } void Gaussian::setMean(scalar c) { this->_mean = c; } scalar Gaussian::getMean() const { return this->_mean; } void Gaussian::setStandardDeviation(scalar sigma) { this->_standardDeviation = sigma; } scalar Gaussian::getStandardDeviation() const { return this->_standardDeviation; } }
[ "edusegre@gmail.com" ]
edusegre@gmail.com
bce79249197ec720c090c0db8b2bdb932a8a5f4e
a743342cf4057a7c2cc573e79602bf89c00b3579
/GraphViewer/GrClock.cpp
95a38c8ac533ff9e2dec8bbc810f39cd56158392
[]
no_license
prografix/prografix.github.io
deddc17515c93566616e74b292b7e4fb1136064f
4f316beb0fa24b98aec8eb127bd294c012c60538
refs/heads/master
2023-07-25T09:48:34.670827
2023-07-09T13:55:25
2023-07-09T13:55:25
166,195,307
3
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
#include "GrClock.h" #include "time.h" GrClock::GrClock() : bBack(false), bPause(false) { pre_clock = clock(); cur_tick = 0; } long GrClock::get() { if ( bPause == false ) { long cur_clock = clock(); long cl = cur_clock - pre_clock; pre_clock = cur_clock; if ( bBack ) { cur_tick -= cl; if ( cur_tick < 0 ) cur_tick = 0; } else { cur_tick += cl; } } return cur_tick; } void GrClock::back() { if ( bPause ) { bPause = false; pre_clock = clock(); } bBack = true; } void GrClock::begin() { pre_clock = clock(); cur_tick = 0; } void GrClock::pause() { bPause = true; } void GrClock::forward() { if ( bPause ) { bPause = false; pre_clock = clock(); } bBack = false; } GrClock grClock;
[ "shevchenka@narod.ru" ]
shevchenka@narod.ru
213075517d0993938109345d949b7aa3afb7b462
7a92206984e9007948afaa363adbb95c06897a74
/demo/DesignPatternsTest/Facade.hpp
64f8134eae754279f59870d530f3fd8704da431e
[]
no_license
fengbingchun/Messy_Test
6a801414a36581bce16edbde122b66ac86b57ddb
b55fcfc4b8adc538f9ac70bf78aa391a50b20241
refs/heads/master
2023-06-26T18:07:59.679346
2023-06-22T06:23:16
2023-06-22T06:23:16
55,020,860
305
171
null
null
null
null
UTF-8
C++
false
false
1,315
hpp
#ifndef FBC_MESSY_TEST_FACADE_HPP_ #define FBC_MESSY_TEST_FACADE_HPP_ #include <iostream> class SubSysOne { public: void MethodOne() { std::cout << "方法一" << std::endl; } }; class SubSysTwo { public: void MethodTwo() { std::cout << "方法二" << std::endl; } }; class SubSysThree { public: void MethodThree() { std::cout << "方法三" << std::endl; } }; //外观类 class Facade { private: SubSysOne* sub1; SubSysTwo* sub2; SubSysThree* sub3; public: Facade() { sub1 = new SubSysOne(); sub2 = new SubSysTwo(); sub3 = new SubSysThree(); } ~Facade() { delete sub1; delete sub2; delete sub3; } void FacadeMethod() { sub1->MethodOne(); sub2->MethodTwo(); sub3->MethodThree(); } }; // ================================================ class Subsystem1 { public: Subsystem1(); ~Subsystem1(); void Operation(); protected: private: }; class Subsystem2 { public: Subsystem2(); ~Subsystem2(); void Operation(); protected: private: }; class Facade_1 { public: Facade_1(); ~Facade_1(); void OperationWrapper(); protected: private: Subsystem1* _subs1; Subsystem2* _subs2; }; int test_Facade1(); int test_Facade2(); #endif // FBC_MESSY_TEST_FACADE_HPP_
[ "fengbingchun@163.com" ]
fengbingchun@163.com
b433b22fe50dc715620baed3d99a9adc78b52999
60b1b24de7f2315bdec25747b0cdb4b0746ce820
/v3/software/AS64/source/expr.cpp
04c73285229bf893ae5d099985b7c3559cfd6dc2
[]
no_license
robfinch/ANY-1
c436c52a1b7d0adba2d54313596ba030820d8096
0a47c5dc055b85dff92a4ab14a65b7efd16f1196
refs/heads/main
2023-07-24T22:36:06.640147
2021-09-09T04:24:13
2021-09-09T04:24:13
332,168,690
4
1
null
null
null
null
UTF-8
C++
false
false
8,243
cpp
// ============================================================================ // __ // \\__/ o\ (C) 2014-2021 Robert Finch, Waterloo // \ __ / All rights reserved. // \/_// robfinch<remove>@finitron.ca // || // // AS64 - Assembler // - 64 bit CPU // // This source file 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 3 of the License, or // (at your option) any later version. // // This source file is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // ============================================================================ // #include "stdafx.h" int64_t expr(); int nsym; // id // const // (expr) // >expr int64_t primary(int64_t* def) { int64_t val; SYM *sym; static char buf[500]; ZeroMemory(buf,sizeof(buf)); *def = 1; switch(token) { case tk_id: if (lastid[0]=='.') // local label sprintf(buf, "%s%s", current_label, lastid); else strcpy(buf, lastid); sym = find_symbol(buf); if (!sym) sym = new_symbol(buf); if (current_symbol) { sym->parent = current_symbol->ord; } val = sym->value.low; if (sym->segment < 5) nsym++; lastsym = sym; sym->referenceCount++; *def = sym->isDefined; NextToken(); if (token==tk_eol) prevToken(); break; case tk_icon: val = ival.low; NextToken(); if (token==tk_eol) prevToken(); break; case '\'': inptr++; if (*inptr=='\\') { inptr++; switch(*inptr) { case '\r': val = '\r'; NextToken(); expect('\''); return (val); case '\n': val = '\n'; NextToken(); expect('\''); return (val); case '\t': val = '\t'; NextToken(); expect('\''); return (val); case '\f': val = '\f'; NextToken(); expect('\''); return (val); case '\b': val = '\b'; NextToken(); expect('\''); return (val); } } val = *inptr; NextToken(); expect('\''); break; case '(': NextToken(); val = expr(); expect(')'); break; default: if (token=='>' && gCpu==5) { val = expr(); val >>= 12; } else if (token=='<' && gCpu==5) { val = expr(); val &= 0xFFF; } else { //printf("Syntax error.\r\n"); val = 0; if (token != tk_eol) NextToken(); } break; } return val; } // !unary // -unary // +unary // ~unary // primary int64_t unary(int64_t* def) { int64_t val; switch(token) { case '!': NextToken(); return !unary(def); case '-': NextToken(); return -unary(def); case '+': NextToken(); return +unary(def); case '~': NextToken(); return ~unary(def); default: return primary(def); } } // unary // unary [*/%] unary int64_t mult_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = unary(&def1); while(1) { switch(token) { case '*': NextToken(); val = val * unary(&def2); *def = *def && (def1 && def2); break; case '/': NextToken(); val = val / unary(&def2); *def = *def && (def1 && def2); break; case '%': NextToken(); val = val % unary(&def2); *def = *def && (def1 && def2); break; default: goto j1; } } j1: return val; } // mult_expr // mult_expr [+-] add_expr_list // int64_t add_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = mult_expr(&def1); while (1) { switch(token) { case '+': NextToken(); val = val + mult_expr(&def2); *def = *def && (def1 && def2); break; case '-': NextToken(); val = val - mult_expr(&def2); *def = *def && (def1 && def2); break; default: goto j1; } } j1: return val; } int64_t shift_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = add_expr(&def1); while(1) { switch(token) { case tk_lshift: NextToken(); val = val << add_expr(&def2); *def = *def && (def1 && def2); break; case tk_rshift: NextToken(); val = val >> add_expr(&def2); *def = *def && (def1 && def2); break; default: goto j1; } } j1: return val; } int64_t relational_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = shift_expr(&def1); while (1) { switch(token) { case tk_lt: NextToken(); val = val <shift_expr(&def2); *def = *def && (def1 && def2); break; case tk_le: NextToken(); val = val<=shift_expr(&def2); *def = *def && (def1 && def2); break; case tk_gt: NextToken(); val = val >shift_expr(&def2); *def = *def && (def1 && def2); break; case tk_ge: NextToken(); val = val>=shift_expr(&def2); *def = *def && (def1 && def2); break; default: goto j1; } } j1: return val; } // relational_expr // relational_expr & equals_expr_list // int64_t equals_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = relational_expr(&def1); while (1) { switch(token) { case tk_eq: NextToken(); val = val == relational_expr(&def2); *def = *def && (def1 && def2); break; case tk_ne: NextToken(); val = val != relational_expr(&def2); *def = *def && (def1 && def2); break; default: goto j1; } } j1: return val; } // equals_expr // equals_expr & bitwise_expr_list // int64_t bitwise_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = equals_expr(&def1); while (1) { switch(token) { case '&': NextToken(); val = val & equals_expr(&def2); *def = *def && (def1 && def2); break; case '^': NextToken(); val = val ^ equals_expr(&def2); *def = *def && (def1 && def2); break; case '|': NextToken(); val = val | equals_expr(&def2); *def = *def && (def1 && def2); break; default: goto j1; } } j1: return val; } // bitwise_expr // bitwise_expr && and_expr_list // int64_t and_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = bitwise_expr(&def1); while(token==tk_land) { NextToken(); val = val && bitwise_expr(&def2); *def = *def && (def1 && def2); } return val; } // and_expr // and_expr || or_expr_list // int64_t or_expr(int64_t* def) { int64_t val; int64_t def1, def2; val = and_expr(&def1); while(token==tk_lor) { NextToken(); val = val || and_expr(&def2); *def = *def && (def1 && def2); } return val; } int64_t expr() { int64_t val; int64_t def; nsym = 0; lastsym = (SYM*)NULL; if (token=='#') NextToken(); val = or_expr(&def); // We only care about the symbol if relocatable output is being generated. // Setting the symbol to NULL will result in no rel records being output. if (nsym > 1 || !rel_out) lastsym = (SYM *)NULL; return val; } int64_t expr_def(int64_t *def) { int64_t val; nsym = 0; lastsym = (SYM*)NULL; if (token == '#') NextToken(); val = or_expr(def); // We only care about the symbol if relocatable output is being generated. // Setting the symbol to NULL will result in no rel records being output. if (nsym > 1 || !rel_out) lastsym = (SYM*)NULL; return val; }
[ "5563401+robfinch@users.noreply.github.com" ]
5563401+robfinch@users.noreply.github.com
aa5f1c10ff6f057ea70152a7c523db55fb01b197
ed5669151a0ebe6bcc8c4b08fc6cde6481803d15
/magma-1.5.0/src/dgeqrf3_gpu.cpp
9d254383bc427fa11bb269a3d02bc7ce3fc3f292
[]
no_license
JieyangChen7/DVFS-MAGMA
1c36344bff29eeb0ce32736cadc921ff030225d4
e7b83fe3a51ddf2cad0bed1d88a63f683b006f54
refs/heads/master
2021-09-26T09:11:28.772048
2018-05-27T01:45:43
2018-05-27T01:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,803
cpp
/* -- MAGMA (version 1.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date September 2014 @generated from zgeqrf3_gpu.cpp normal z -> d, Wed Sep 17 15:08:32 2014 */ #include "common_magma.h" /* //////////////////////////////////////////////////////////////////////////// -- Auxiliary function: 'a' is pointer to the current panel holding the Householder vectors for the QR factorization of the panel. This routine puts ones on the diagonal and zeros in the upper triangular part of 'a'. The upper triangular values are stored in work. */ void dsplit_diag_block3(int ib, double *a, int lda, double *work) { int i, j; double *cola, *colw; double c_zero = MAGMA_D_ZERO; double c_one = MAGMA_D_ONE; for (i=0; i < ib; i++) { cola = a + i*lda; colw = work + i*ib; for (j=0; j < i; j++) { colw[j] = cola[j]; cola[j] = c_zero; } colw[i] = cola[i]; cola[i] = c_one; } } /** Purpose ------- DGEQRF3 computes a QR factorization of a real M-by-N matrix A: A = Q * R. This version stores the triangular dT matrices used in the block QR factorization so that they can be applied directly (i.e., without being recomputed) later. As a result, the application of Q is much faster. Also, the upper triangular matrices for V have 0s in them and the corresponding parts of the upper triangular R are stored separately in dT. Arguments --------- @param[in] m INTEGER The number of rows of the matrix A. M >= 0. @param[in] n INTEGER The number of columns of the matrix A. N >= 0. @param[in,out] dA DOUBLE_PRECISION array on the GPU, dimension (LDDA,N) On entry, the M-by-N matrix A. On exit, the elements on and above the diagonal of the array contain the min(M,N)-by-N upper trapezoidal matrix R (R is upper triangular if m >= n); the elements below the diagonal, with the array TAU, represent the orthogonal matrix Q as a product of min(m,n) elementary reflectors (see Further Details). @param[in] ldda INTEGER The leading dimension of the array dA. LDDA >= max(1,M). To benefit from coalescent memory accesses LDDA must be divisible by 16. @param[out] tau DOUBLE_PRECISION array, dimension (min(M,N)) The scalar factors of the elementary reflectors (see Further Details). @param[out] dT (workspace) DOUBLE_PRECISION array on the GPU, dimension (2*MIN(M, N) + (N+31)/32*32 )*NB, where NB can be obtained through magma_get_dgeqrf_nb(M). It starts with MIN(M,N)*NB block that store the triangular T matrices, followed by the MIN(M,N)*NB block of the diagonal matrices for the R matrix. The rest of the array is used as workspace. @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value or another error occured, such as memory allocation failed. Further Details --------------- The matrix Q is represented as a product of elementary reflectors Q = H(1) H(2) . . . H(k), where k = min(m,n). Each H(i) has the form H(i) = I - tau * v * v' where tau is a real scalar, and v is a real vector with v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), and tau in TAU(i). @ingroup magma_dgeqrf_comp ********************************************************************/ extern "C" magma_int_t magma_dgeqrf3_gpu( magma_int_t m, magma_int_t n, double *dA, magma_int_t ldda, double *tau, double *dT, magma_int_t *info ) { #define dA(a_1,a_2) (dA + (a_2)*(ldda) + (a_1)) #define dT(a_1) (dT + (a_1)*nb) #define d_ref(a_1) (dT + ( minmn+(a_1))*nb) #define dd_ref(a_1) (dT + (2*minmn+(a_1))*nb) #define work(a_1) (work + (a_1)) #define hwork (work + (nb)*(m)) magma_int_t i, k, minmn, old_i, old_ib, rows, cols; magma_int_t ib, nb; magma_int_t ldwork, lddwork, lwork, lhwork; double *work, *ut; /* check arguments */ *info = 0; if (m < 0) { *info = -1; } else if (n < 0) { *info = -2; } else if (ldda < max(1,m)) { *info = -4; } if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } k = minmn = min(m,n); if (k == 0) return *info; nb = magma_get_dgeqrf_nb(m); lwork = (m + n + nb)*nb; lhwork = lwork - m*nb; if (MAGMA_SUCCESS != magma_dmalloc_pinned( &work, lwork )) { *info = MAGMA_ERR_HOST_ALLOC; return *info; } ut = hwork+nb*(n); memset( ut, 0, nb*nb*sizeof(double)); magma_queue_t stream[2]; magma_queue_create( &stream[0] ); magma_queue_create( &stream[1] ); ldwork = m; lddwork= n; if ( (nb > 1) && (nb < k) ) { /* Use blocked code initially */ old_i = 0; old_ib = nb; for (i = 0; i < k-nb; i += nb) { ib = min(k-i, nb); rows = m -i; magma_dgetmatrix_async( rows, ib, dA(i,i), ldda, work(i), ldwork, stream[1] ); if (i > 0) { /* Apply H' to A(i:m,i+2*ib:n) from the left */ cols = n-old_i-2*old_ib; magma_dlarfb_gpu( MagmaLeft, MagmaConjTrans, MagmaForward, MagmaColumnwise, m-old_i, cols, old_ib, dA(old_i, old_i ), ldda, dT(old_i), nb, dA(old_i, old_i+2*old_ib), ldda, dd_ref(0), lddwork); /* store the diagonal */ magma_dsetmatrix_async( old_ib, old_ib, ut, old_ib, d_ref(old_i), old_ib, stream[0] ); } magma_queue_sync( stream[1] ); lapackf77_dgeqrf(&rows, &ib, work(i), &ldwork, tau+i, hwork, &lhwork, info); /* Form the triangular factor of the block reflector H = H(i) H(i+1) . . . H(i+ib-1) */ lapackf77_dlarft( MagmaForwardStr, MagmaColumnwiseStr, &rows, &ib, work(i), &ldwork, tau+i, hwork, &ib); /* Put 0s in the upper triangular part of a panel (and 1s on the diagonal); copy the upper triangular in ut. */ magma_queue_sync( stream[0] ); dsplit_diag_block3(ib, work(i), ldwork, ut); magma_dsetmatrix( rows, ib, work(i), ldwork, dA(i,i), ldda ); if (i + ib < n) { /* Send the triangular factor T to the GPU */ magma_dsetmatrix( ib, ib, hwork, ib, dT(i), nb ); if (i+nb < k-nb) { /* Apply H' to A(i:m,i+ib:i+2*ib) from the left */ magma_dlarfb_gpu( MagmaLeft, MagmaConjTrans, MagmaForward, MagmaColumnwise, rows, ib, ib, dA(i, i ), ldda, dT(i), nb, dA(i, i+ib), ldda, dd_ref(0), lddwork); } else { cols = n-i-ib; magma_dlarfb_gpu( MagmaLeft, MagmaConjTrans, MagmaForward, MagmaColumnwise, rows, cols, ib, dA(i, i ), ldda, dT(i), nb, dA(i, i+ib), ldda, dd_ref(0), lddwork); /* Fix the diagonal block */ magma_dsetmatrix( ib, ib, ut, ib, d_ref(i), ib ); } old_i = i; old_ib = ib; } } } else { i = 0; } /* Use unblocked code to factor the last or only block. */ if (i < k) { ib = n-i; rows = m-i; magma_dgetmatrix( rows, ib, dA(i, i), ldda, work, rows ); lhwork = lwork - rows*ib; lapackf77_dgeqrf(&rows, &ib, work, &rows, tau+i, work+ib*rows, &lhwork, info); magma_dsetmatrix( rows, ib, work, rows, dA(i, i), ldda ); } magma_queue_destroy( stream[0] ); magma_queue_destroy( stream[1] ); magma_free_pinned( work ); return *info; } /* magma_dgeqrf_gpu */ #undef dA #undef dT #undef d_ref #undef work
[ "cjy7117@gmail.com" ]
cjy7117@gmail.com
b781d7bd0f94a1c1c87ba834c5d6d2e3a739451b
590c5112081e588cbe7c5914c7eb3b2ff9937b40
/include/ZSTL/ZHashMap.hpp
7e4c7b39c23f4058c117091c35f920ddbbdbf30e
[]
no_license
crertel/onizuka-oculus-client
ce9045a1e86a5d1fe5bb992e0c5f8fa0ffa528ee
9ef665d8e14aca193b1fc5faa41954a8a5eaa641
refs/heads/master
2021-01-17T11:51:51.204928
2014-01-26T12:48:12
2014-01-26T12:48:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,931
hpp
/* ZHashMap.hpp Author: James Russell <jcrussell@762studios.com> Created: 12/24/2011 Purpose: Templated hash map implementation. License: This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. */ #pragma once #ifndef _ZHASHMAP_HPP #define _ZHASHMAP_HPP #include <ZSTL/ZPair.hpp> #include <ZSTL/ZArray.hpp> #include <ZSTL/ZList.hpp> //Default number of buckets #ifndef ZHASHMAP_DEFAULT_BUCKETS #define ZHASHMAP_DEFAULT_BUCKETS (31) #endif //Default load factor for the HashMap (expressed as an integer percentage LF / 100) #ifndef ZHASHMAP_DEFAULT_LOADFACTOR #define ZHASHMAP_DEFAULT_LOADFACTOR (75) #endif //Factor by which HashMap grows when loadfactor is exceeded #ifndef ZHASHMAP_DEFAULT_GROWFACTOR #define ZHASHMAP_DEFAULT_GROWFACTOR (2.0) #endif //Number of nodes for the lists stored locally (safe since we never splice) #ifndef ZHASHMAP_DEFAULT_LOCAL_NODES #define ZHASHMAP_DEFAULT_LOCAL_NODES (10) #endif //Forward Declaration of ZHashMap template < typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA > class ZHashMap; //Forward Declaration of ZHashMapIterator template <typename K, typename V, typename HT> class ZHashMapIterator; /* Forward Declaration of ZHashMap Method Implementation Structures Existence of these structures allows for template specialization of individual methods of the ZHashMap class. In order to specialize a single method of ZHashMap, simply specialize the corresponding method implementation structure. */ //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Clear struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_ClearImpl { inline static void Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::ContainsKey struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_ContainsKeyImpl { inline static bool Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::ContainsValue struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_ContainsValueImpl { inline static bool Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const V& _value); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Empty struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_EmptyImpl { inline static bool Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Erase struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_EraseImpl { inline static void Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key); inline static void Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, ZHashMapIterator<K, V, HT>& _itr); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Get struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_GetImpl { inline static V& Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Put struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_PutImpl { inline static void Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key); inline static void Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key, const V& _value); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Resize struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_ResizeImpl { inline static void Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, size_t _buckets); }; //Forward Declaration of ZHashMap<K, V, HT, H, LF, LA, AA>::Size struct template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> struct ZHashMap_SizeImpl { inline static size_t Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self); }; /////////////////////////////////////// /* Hash Comparator, Hasher, HashNode */ /////////////////////////////////////// /* Hash comparator class, which compares elements with the == operator. */ template <typename T> struct ZHashComparator { ZHashComparator() { } //Silence Sun C++ warnings about uninitialized structs //operator overload which returns true if equivalent (as per ==), false otherwise bool operator () (const T& _a, const T& _b) const { if ((T)_a == (T)_b) return true; else return false; } }; /* Hasher class, which produces hash values of objects for use in ZHashMap. The template parameter T is the type we will be hashing. The template parameter HT is the hash type that is computed. */ template <typename T, typename HT> class ZHasher { public: //Comparator for use with equals and less than ZHashComparator<T> Comp; //Default hash function, which attempts to cast the object as a hash value HT Hash(const T& _obj) const { return (HT)_obj; } //Default comparison function, which compares objects (should return 0 if not equal, !0 otherwise) int Equals(const T& _first, const T& _second) const { return Comp(_first, _second); } }; /* Hash node structure, which contains a key, a value, and the pre-computed hash for the key as well as the hash mod (bucket). This node is stored within a ZListNode for hash chaining. The template parameter K is the key type. The template parameter V is the value type. The template parameter HT is the hash type. */ template <typename K, typename V, typename HT> struct ZHashNode { ZHashNode() { } //Silence Sun C++ warnings about uninitialized structs K Key; //The contained key V Value; //The contained value HT Hash; //The hash of the key size_t HashMod; //The hash mod number of buckets (gives bucket) }; /////////////////////// /* ZHashMap Iterator */ /////////////////////// /* Iterator for ZHashMap. The template parameter K is the key type. The template parameter V is the value type. The template parameter HT is the hash type. */ template <typename K, typename V, typename HT> class ZHashMapIterator { private: //The current node we are pointing to ZListNode< ZHashNode<K, V, HT> > *Node; //The end node of the map ZListNode< ZHashNode<K, V, HT> > *EndNode; public: /* Default Constructor. */ ZHashMapIterator() : Node(NULL), EndNode(NULL) { } /* Useful constructor. @param _node - the node we are to begin iterating at */ ZHashMapIterator(ZListNode< ZHashNode<K, V, HT> >* _node, ZListNode< ZHashNode<K, V, HT> >* _endNode) : Node(_node), EndNode(_endNode) { } /* Copy Constructor. @param _other - the other iterator */ ZHashMapIterator(const ZHashMapIterator& _other) : Node(_other.Node), EndNode(_other.EndNode) { } /* public ZHashMapIterator<K, V, HT>::CheckNodeCurrent Node check function that does not allow the current node to point to NULL. @return (void) */ void CheckNodeCurrent() const { #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(Node != NULL, "ZHashMap Iterator Invalid!"); #endif } /* public ZHashMapIterator<K, V, HT>::CheckNodeNext Node check function that does not allow Node to be 'End' @return (void) */ void CheckNodeNext() const { #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(Node != NULL && Node != EndNode, "ZHashMap Iterator Next Invalid!"); #endif } /* public ZHashMapIterator<K, V, HT>::CheckNodePrevious Node check function that does not allow Node to be 'Begin' @return (void) */ void CheckNodePrevious() const { #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(Node != NULL && Node->Previous != EndNode, "ZHashMap Iterator Previous Invalid!"); #endif } /* public ZHashMapIterator<K, V, HT>::GetNode Gets the node that this iterator is currently pointed at. @return (ZListNode<T>*) - the node we are currently pointed at */ ZListNode< ZHashNode<K, V, HT> >* GetNode() const { return Node; } /* public ZHashMapIterator<K, V, HT>::SetNode Sets the current node for this iterator. Useful for when the underlying list changes state. @param _node - the node to point this iterator at @return (void) */ void SetNode(ZListNode< ZHashNode<K, V, HT> >* _node) { Node = _node; } /* public ZHashMapIterator<K, V, HT>::GetKey Gets the key this iterator points to. @return (const K&) - the key pointed to */ const K& GetKey() const { CheckNodeCurrent(); return Node->Element.Key; } /* public ZHashMapIterator<K, V, HT>::GetValue Gets the value this iterator points to. @return (V&) - the value pointed to */ V& GetValue() const { CheckNodeCurrent(); return Node->Element.Value; } /* public ZHashMapIterator<K, V, HT>::HasCurrent Determines if this iterator currently points to a valid element. @return (bool) - true if element at current position */ bool HasCurrent() const { return Node != NULL && Node != EndNode; } /* public ZHashMapIterator<K, V, HT>::HasNext Determines if this iterator has a valid element after the current element. @return (bool) - true if element after current, false otherwise */ bool HasNext() const { return Node != NULL && Node != EndNode && Node->Next != EndNode; } /* public ZHashMapIterator<K, V, HT>::HasPrev Determines if this iterator has a valid element before the current element. @return (bool) - true if element before current, false otherwise */ bool HasPrev() const { return Node != NULL && Node->Previous != EndNode; } /* public ZHashMapIterator<K, V, HT>::Next Advances this iterator to the next element. @return (void) @assert - if this would advance past end */ void Next() { ++(*this); } /* public ZHashMapIterator<K, V, HT>::Prev Returns this iterator to the previous element. @return (void) @assert - if this would advance past begin */ void Prev() { --(*this); } /* public ZHashMapIterator<K, V, HT>::SetValue Sets the value mapped to the given key. @return (void) @assert - if this is the end node */ void SetValue(const V& _value) { CheckNodeCurrent(); Node->Element.Value = _value; } //Operator overrides ZHashMapIterator& operator ++ () { CheckNodeNext(); Node = Node->Next; return *this; } ZHashMapIterator operator ++ (int) { ZListNode< ZHashNode<K, V, HT> > *node = Node; CheckNodeNext(); Node = Node->Next; return ZHashMapIterator(node, EndNode); } ZHashMapIterator operator + (int _value) { ZHashMapIterator itr(*this); for (int i = 0; i < _value; i++) ++itr; return itr; } ZHashMapIterator& operator += (int _value) { for (int i = 0; i < _value; i++) ++(*this); return *this; } ZHashMapIterator& operator -- () { CheckNodePrevious(); Node = Node->Previous; return *this; } ZHashMapIterator operator -- (int) { ZListNode< ZHashNode<K, V, HT> > *node = Node; CheckNodePrevious(); Node = Node->Previous; return ZHashMapIterator(node, EndNode); } ZHashMapIterator operator - (int _value) { ZHashMapIterator itr(*this); for (int i = _value; i > 0; i--) --itr; return itr; } ZHashMapIterator& operator -= (int _value) { for (int i = 0; i < _value; i--) --(*this); return *this; } ZHashMapIterator& operator = (const ZHashMapIterator &_other) { Node = _other.Node; EndNode = _other.EndNode; return *this; } bool operator == (const ZHashMapIterator& _other) const { return (Node == _other.Node) && (EndNode == _other.EndNode); } bool operator != (const ZHashMapIterator& _other) const { return !( (*this)==_other ); } const ZHashNode<K, V, HT>& operator * () const { CheckNodeCurrent(); return Node->Element; } }; ///////////////////////////// /* ZHashMap Implementation */ ///////////////////////////// /* Templated dynamic hash map implementation. Uses chained hashing and (optional) load factor balancing to ensure it behaves gracefully even under heavy load. This implementation does not maintain order between keys. The template parameter K is the key type, which must be hashable. The template parameter V is the value type, which need not be hashable. The template parameter HT is the hash type. This should generally correspond to something like a 32-bit or 64-bit unsigned integer. It must be compatible with the modulo operator. The template parameter H is the hasher type, which defaults to the ZHasher for K using hash type HT. The hasher must expose the same methods as ZHasher (Hash, Equals). The template parameter LF is the load factor of the hash map given as an integral value between 0 (hashmap will not resize) and 100. Load factor is then computed as (double)(LF / 100). Whenever the current load factor exceeds this value, the number of buckets is increased (map is resized). The template parameter LA is the allocator type to use for list nodes. It must allocate ZListNode instances containing type ZHashNode<K, V, HT>. The template parameter AA is the allocator type to pass along to the contained ZArray. It must allocate arrays of type ZListNode< ZHashNode< K, V > >*. */ template <typename K, typename V, typename HT = ZHashValue32, typename H = ZHasher<K, HT>, size_t LF = ZHASHMAP_DEFAULT_LOADFACTOR, typename LA = ZListPooledAllocator< ZHashNode<K, V, HT>, ZHASHMAP_DEFAULT_LOCAL_NODES >, typename AA = ZArrayAllocator< ZListNode< ZHashNode<K, V, HT> >*, ZHASHMAP_DEFAULT_BUCKETS> > class ZHashMap { friend struct ZHashMap_ClearImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_ContainsKeyImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_ContainsValueImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_EmptyImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_EraseImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_GetImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_PutImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_ResizeImpl<K, V, HT, H, LF, LA, AA>; friend struct ZHashMap_SizeImpl<K, V, HT, H, LF, LA, AA>; private: H Hasher; //The hasher for our keys LA NodeAllocator; //Allocator for chained hashing size_t ElementCount; //The element count ZArray< ZListNode< ZHashNode<K, V, HT> >*, AA> Map; //The map ZListNode< ZHashNode<K, V, HT> > EmptyNode; //The end node for the hash map //Resizes and copies the HashMap if we exceed LoadFactor (LF of 0 indicates we should not resize) inline void CheckLoadFactor() { //This will evaluate to false if LF == 0, true if LF > 0 (done to avoid C4127) if ((void)LF,LF) { double currentLoadFactor = LoadFactor(); if (currentLoadFactor > ((double)LF / (double)100.0)) Resize((size_t)((double)Map.Size() * ZHASHMAP_DEFAULT_GROWFACTOR)); } } //Gets a bucket given a hash code inline size_t GetBucket(HT _hash) const { return _hash % Map.Size(); } public: /* Iterator type for ZHashMap. Allows ZHashMap::Iterator notation. */ typedef ZHashMapIterator< K, V, HT > Iterator; /* Default Constructor. */ ZHashMap() : ElementCount(0), Map(ZHASHMAP_DEFAULT_BUCKETS) { EmptyNode.Next = &EmptyNode; EmptyNode.Previous = &EmptyNode; Map.Resize(ZHASHMAP_DEFAULT_BUCKETS, NULL); } /* Parameterized Constructor. @param _buckets - the number of buckets the hashmap should use */ ZHashMap(size_t _buckets) : ElementCount(0), Map(_buckets) { #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(_buckets > 0, "Cannot make ZHashMap with no buckets!"); #endif EmptyNode.Next = &EmptyNode; EmptyNode.Previous = &EmptyNode; Map.Resize(_buckets, NULL); } /* Copy constructor. @param _other - the other hash map */ ZHashMap(const ZHashMap<K, V, HT, H, LF, LA, AA>& _other) : ElementCount(_other.Size()), Map(_other.Size()) { EmptyNode.Next = &EmptyNode; EmptyNode.Previous = &EmptyNode; Map.Resize(_other.Size(), NULL); for (typename ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator itr = _other.Begin(); itr != _other.End(); ++itr) Put((*itr).Key, (*itr).Value); } /* Copy constructor that can copy hash maps with other template types. Key and Value type must be the same. @param _other - the other hash map */ template <typename OHT, typename OH, size_t OLF, typename OLA, typename OAA> ZHashMap(const ZHashMap<K, V, OHT, OH, OLF, OLA, OAA>& _other) : ElementCount(_other.Size()), Map(_other.Size()) { EmptyNode.Next = &EmptyNode; EmptyNode.Previous = &EmptyNode; Map.Resize(_other.Map.Size(), NULL); for (typename ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator itr = _other.Begin(); itr != _other.End(); ++itr) Put((*itr).Key, (*itr).Value); } /* = operator overload. Makes a copy of another hash map. This version is needed to override the default version. @param _other - the other hash map @return (ZHashMap<K, V, HT, H, LF, LA, AA>) - this hash map */ ZHashMap<K, V, HT, H, LF, LA, AA>& operator = (const ZHashMap<K, V, HT, H, LF, LA, AA>& _other) { Clear(); ElementCount = _other.ElementCount; Map.Resize(_other.Map.Size()); EmptyNode.Next = &EmptyNode; EmptyNode.Previous = &EmptyNode; for (typename ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator itr = _other.Begin(); itr != _other.End(); ++itr) { Put((*itr).Key, (*itr).Value); } return *this; } /* = operator overload. @param _other - the other hash map @return (ZHashMap<K, V, HT, H, LF, LA, AA>) - this hash map */ template <typename OHT, typename OH, size_t OLF, typename OLA, typename OAA> ZHashMap<K, V, HT, H, LF, LA, AA>& operator = (const ZHashMap<K, V, OHT, OH, OLF, OLA, OAA>& _other) { Clear(); ElementCount = _other.ElementCount; Map.Resize(_other.Map.Size()()); EmptyNode.Next = &EmptyNode; EmptyNode.Previous = &EmptyNode; for (typename ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator itr = _other.Begin(); itr != _other.End(); ++itr) { Put((*itr).Key, (*itr).Value); } return *this; } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::operator[] Gets a value from the map. Functionally the same as Get. @param _key - the key to lookup @return (V&) - the value mapped to _key @assert - if the key is not mapped */ V& operator [] (const K& _key) { return Get(_key); } /* public ZHashMap<K, V, H, LF, lA, AA>::Begin Gets an iterator to the first element in the hash map. Keep in mind that hash map elements are unordered. @return (ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator) - iterator to the first element */ Iterator Begin() const { return ZHashMapIterator< K, V, HT >(const_cast<ZListNode< ZHashNode<K, V, HT> >* >(&EmptyNode)->Next, const_cast<ZListNode< ZHashNode<K, V, HT> >* >(&EmptyNode)); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Clear Clears the hash map of all keys and values. @return (void) */ void Clear() { ZHashMap_ClearImpl<K, V, HT, H, LF, LA, AA>::Call(*this); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::ContainsKey Determines if the hash map contains the given key. @param _key - the key to check @return (bool) - boolean indicating if the hash map contains the key */ bool ContainsKey(const K& _key) const { return ZHashMap_ContainsKeyImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _key); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::ContainsValue Determines if the hash map contains the given value. @param _value - the value to check for @return (bool) - boolean indicating if the hash map contains the value */ bool ContainsValue(const V& _value) const { return ZHashMap_ContainsValueImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _value); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Empty Indicates whether or not the hash map is empty. @return (bool) - boolean indicating the hash map is empty (free of keys and values) */ bool Empty() const { return ZHashMap_EmptyImpl<K, V, HT, H, LF, LA, AA>::Call(*this); } /* public ZHashMap<K, V, H, LF, lA, AA>::End Gets an iterator to the end node in the hash map. Keep in mind that hash map elements are unordered. @return (ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator) - iterator to the end node */ Iterator End() const { return ZHashMapIterator< K, V, HT >(const_cast<ZListNode< ZHashNode<K, V, HT> >* >(&EmptyNode), const_cast<ZListNode< ZHashNode<K, V, HT> >* >(&EmptyNode)); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Erase Removes the associated key and mapped value. @param _key - the key to lookup @return (void) - this hash map @assert - if the key is not mapped */ void Erase(const K& _key) { ZHashMap_EraseImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _key); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Erase Removes the key and mapped value given by the iterator. This version is more efficient than the key-only version because no hash lookup is performed. @param _itr - iterator to the hash node to remove @return (void) @assert - if it is the end iterator */ void Erase(Iterator& _itr) { ZHashMap_EraseImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _itr); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Find Returns an iterator to the element mapped to the given key. Will return the End() iterator if not mapped. @param _key - the key to look up @return (ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator) - iterator to the element, End() if not found */ Iterator Find(const K& _key) const { HT hash = Hasher.Hash(_key); size_t bucket = GetBucket(hash); ZListNode< ZHashNode<K, V, HT> >* node = Map.Data()[bucket]; while (node != NULL && node != &EmptyNode && node->Element.HashMod == bucket) { if (node->Element.Hash == hash && Hasher.Equals(_key, node->Element.Key) != 0) return Iterator(node, const_cast< ZListNode< ZHashNode<K, V, HT> > *>(&EmptyNode)); node = node->Next; } return End(); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Get Gets the value mapped to the given key. @param _key - the key to look up @return (V&) - the value mapped to _key @assert - if the key is not present in the map */ V& Get(const K& _key) const { return ZHashMap_GetImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _key); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Keys Gets a list of keys in the map. Uses the method 'PushBack' to add the keys. @param C - the container type to push the keys into, which must contain type K and have a 'PushBack' method @param _container - the container to put the keys into @return - ZList containing all the keys in the map */ template <typename C> void Keys(C& _container) const { Iterator itr = Begin(); while (itr.HasCurrent()) { _container.PushBack((*itr).Key); itr.Next(); } } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::LoadFactor Returns the current load factor of the hash map, as determined by number of elements over number of buckets. @return (double) - the load factor */ double LoadFactor() const { return (double)ElementCount / (double)Map.Size(); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Mappings Gets a list of all the key value mappings in the hash map. Adds pairs of mappings using 'PushBack'. @param C - the container type to push the keys into, which must contain type ZPair<K, V> and have a 'PushBack' method @param _container - the container to put the keys into @return (ZList<ZPair<K, V>>)- list of key-value pairs */ template <typename C> void Mappings(C& _container) const { Iterator itr = Begin(); while (itr.HasCurrent()) { _container.PushBack(ZPair<K, V>((*itr).Key, (*itr).Value)); itr.Next(); } } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Put Puts the given key into the map with a default constructed value of type V. @param _key - the key to place in the map */ void Put(const K& _key) { return ZHashMap_PutImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _key); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Put Puts the given key and value combination into the hash map. @param _key - the key to associate with _value @param _value - the value to lookup using _key */ void Put(const K& _key, const V& _value) { return ZHashMap_PutImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _key, _value); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Resize Sets the number of buckets the hashmap will use. Existing elements will be re-hashed into the map. @param _buckets - number of buckets to use @return (ZHashMap<K, V, HT, H, LF, LA, AA>&) - this map */ void Resize(size_t _buckets) { ZHashMap_ResizeImpl<K, V, HT, H, LF, LA, AA>::Call(*this, _buckets); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Size Returns the number of mapped key-value pairs in the map. @return (size_t) - the number of key value pairs */ size_t Size() const { return ZHashMap_SizeImpl<K, V, HT, H, LF, LA, AA>::Call(*this); } /* public ZHashMap<K, V, HT, H, LF, LA, AA>::Values Gets a list of values in the map. @param C - the container type to push the keys into, which must contain type V and have a 'PushBack' method @param _container - the container to put the keys into @return (ZList<V>)- ZList containing all the values in the map */ template <typename C> void Values(C& _container) const { Iterator itr = Begin(); while (itr.HasCurrent()) { _container.PushBack((*itr).Value); itr.Next(); } } }; //////////////////////////////////////////// /* Non-Specialized Method Implementations */ //////////////////////////////////////////// template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> void ZHashMap_ClearImpl<K, V, HT, H, LF, LA, AA>::Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self) { ZListNode< ZHashNode<K, V, HT> >* node = _self.EmptyNode.Next; while (node != &_self.EmptyNode) { node = node->Next; _self.NodeAllocator.Deallocate(node->Previous); } for (size_t i = 0; i < _self.Map.Size(); i++) _self.Map.Data()[i] = NULL; _self.EmptyNode.Next = &_self.EmptyNode; _self.EmptyNode.Previous = &_self.EmptyNode; _self.ElementCount = 0; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> bool ZHashMap_ContainsKeyImpl<K, V, HT, H, LF, LA, AA>::Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key) { HT hash = _self.Hasher.Hash(_key); size_t bucket = _self.GetBucket(hash); ZListNode< ZHashNode<K, V, HT> >* node = _self.Map.Data()[bucket]; while (node != NULL && node != &_self.EmptyNode && node->Element.HashMod == bucket) { if (node->Element.Hash == hash && _self.Hasher.Equals(_key, node->Element.Key) != 0) return true; node = node->Next; } return false; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> bool ZHashMap_ContainsValueImpl<K, V, HT, H, LF, LA, AA>::Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const V& _value) { typename ZHashMap<K, V, HT, H, LF, LA, AA>::Iterator itr = _self.Begin(); while (itr.HasCurrent()) { if ((*itr).Value == _value) return true; itr.Next(); } return false; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> bool ZHashMap_EmptyImpl<K, V, HT, H, LF, LA, AA>::Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self) { return _self.ElementCount == 0; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> void ZHashMap_EraseImpl<K, V, HT, H, LF, LA, AA>::Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key) { HT hash = _self.Hasher.Hash(_key); size_t bucket = _self.GetBucket(hash); ZListNode< ZHashNode<K, V, HT> >* node = _self.Map.Data()[bucket]; while (node != NULL && node != &_self.EmptyNode && node->Element.HashMod == bucket) { if (node->Element.Hash == hash && _self.Hasher.Equals(_key, node->Element.Key) != 0) { ZListNode< ZHashNode<K, V, HT> >* prevNode = node->Previous; ZListNode< ZHashNode<K, V, HT> >* nextNode = node->Next; prevNode->Next = nextNode; nextNode->Previous = prevNode; //If the bucket maps to this node, it must change (either Next or NULL) if (_self.Map.Data()[bucket] == node) { if (nextNode->Element.HashMod == bucket) _self.Map.Data()[bucket] = nextNode; else _self.Map.Data()[bucket] = NULL; } _self.NodeAllocator.Deallocate(node); _self.ElementCount--; return; } node = node->Next; } } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> void ZHashMap_EraseImpl<K, V, HT, H, LF, LA, AA>::Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, ZHashMapIterator<K, V, HT>& _itr) { #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(_itr != _self.End(), "ZHashMap: Cannot Erase End iterator!"); #endif ZListNode< ZHashNode<K, V, HT> >* node = _itr.GetNode(); ZListNode< ZHashNode<K, V, HT> >* prevNode = node->Previous; ZListNode< ZHashNode<K, V, HT> >* nextNode = node->Next; size_t bucket = node->Element.HashMod; prevNode->Next = nextNode; nextNode->Previous = prevNode; //If the bucket maps to this node, it must change (either Next or NULL) if (_self.Map.Data()[node->Element.HashMod] == node) { if (nextNode->Element.HashMod == bucket) _self.Map.Data()[bucket] = nextNode; else _self.Map.Data()[bucket] = NULL; } _self.NodeAllocator.Deallocate(node); _self.ElementCount--; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> V& ZHashMap_GetImpl<K, V, HT, H, LF, LA, AA>::Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key) { HT hash = _self.Hasher.Hash(_key); size_t bucket = _self.GetBucket(hash); ZListNode< ZHashNode<K, V, HT> >* node = _self.Map.Data()[bucket]; while (node != NULL && node != &_self.EmptyNode && node->Element.HashMod == bucket) { if (node->Element.Hash == hash && _self.Hasher.Equals(_key, node->Element.Key) != 0) return node->Element.Value; node = node->Next; } #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ERROR("ZHashMap: Get could not find value!"); #endif //If the runtime assert is ignored and we continue, return ref to a static local variable //This is effectively 'undefined' behavior static V val; return val; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> void ZHashMap_PutImpl<K, V, HT, H, LF, LA, AA>::Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key) { _self.CheckLoadFactor(); HT hash = _self.Hasher.Hash(_key); size_t bucket = _self.GetBucket(hash); ZListNode< ZHashNode<K, V, HT> >* node = _self.Map.Data()[bucket]; if (node == NULL) { //Empty bucket, so search for the next node for (size_t i = bucket + 1; i < _self.Map.Size(); i++) { node = _self.Map.Data()[i]; if (node != NULL) break; } //No node was found, so use the empty node if (node == NULL) node = &_self.EmptyNode; } else { //Non-empty bucket, so see if we are already mapped while (node->Element.HashMod == bucket) { if (node->Element.Hash == hash && _self.Hasher.Equals(_key, node->Element.Key) != 0) return; node = node->Next; } } //Not mapped, so insert (node is currently one past where we should be) ZListNode< ZHashNode<K, V, HT> >* newNode = _self.NodeAllocator.Allocate(); #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(newNode != NULL, "ZHashMap: Unable to allocate hash node!"); #endif //If the bucket has NULL linkage, set it if (_self.Map.Data()[bucket] == NULL) _self.Map.Data()[bucket] = newNode; newNode->Next = node; newNode->Previous = node->Previous; newNode->Element.Key = _key; newNode->Element.Value = V(); //Be sure to default construct the value instance newNode->Element.Hash = hash; newNode->Element.HashMod = bucket; newNode->Previous->Next = newNode; newNode->Next->Previous = newNode; _self.ElementCount++; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> void ZHashMap_PutImpl<K, V, HT, H, LF, LA, AA>::Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, const K& _key, const V& _value) { _self.CheckLoadFactor(); HT hash = _self.Hasher.Hash(_key); size_t bucket = _self.GetBucket(hash); ZListNode< ZHashNode<K, V, HT> >* node = _self.Map.Data()[bucket]; if (node == NULL) { //Empty bucket, so search for the next node for (size_t i = bucket + 1; i < _self.Map.Size(); i++) { node = _self.Map.Data()[i]; if (node != NULL) break; } //No node was found, so use the empty node if (node == NULL) node = &_self.EmptyNode; } else { //Non-empty bucket, so see if we are already mapped while (node->Element.HashMod == bucket) { if (node->Element.Hash == hash && _self.Hasher.Equals(_key, node->Element.Key) != 0) { node->Element.Value = _value; return; } node = node->Next; } } //Not mapped, so insert (node is currently one past where we should be) ZListNode< ZHashNode<K, V, HT> >* newNode = _self.NodeAllocator.Allocate(); #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(newNode != NULL, "ZHashMap: Unable to allocate hash node!"); #endif //If the bucket has NULL linkage, set it if (_self.Map.Data()[bucket] == NULL) _self.Map.Data()[bucket] = newNode; newNode->Next = node; newNode->Previous = node->Previous; newNode->Element.Key = _key; newNode->Element.Value = _value; newNode->Element.Hash = hash; newNode->Element.HashMod = bucket; newNode->Previous->Next = newNode; newNode->Next->Previous = newNode; _self.ElementCount++; } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> void ZHashMap_ResizeImpl<K, V, HT, H, LF, LA, AA>::Call(ZHashMap<K, V, HT, H, LF, LA, AA>& _self, size_t _buckets) { #if !ZSTL_DISABLE_RUNTIME_CHECKS ZSTL_ASSERT(_buckets > 0, "ZHashMap: Unable to resize to zero buckets!"); #endif //Get a pointer to the first non-empty element (which may itself be the empty element) ZListNode< ZHashNode<K, V, HT> >* node = _self.EmptyNode.Next; //Clear out the map completely for (size_t i = 0; i < _self.Map.Size(); i++) _self.Map.Data()[i] = NULL; _self.EmptyNode.Next = &_self.EmptyNode; _self.EmptyNode.Previous = &_self.EmptyNode; _self.Map.Resize(_buckets, NULL); //Loop through our previous nodes and place them back in the map in their new spots while (node != &_self.EmptyNode) { //Compute new bucket node->Element.HashMod = node->Element.Hash % _buckets; //Determine where we should be placing this node ZListNode< ZHashNode<K, V, HT> >* curNode = node; ZListNode< ZHashNode<K, V, HT> >* nextNode = _self.Map.Data()[node->Element.HashMod]; //Get the next node to place now, before we scribble the pointers node = curNode->Next; //If the bucket has NULL linkage, next node if (nextNode == NULL) { //Empty bucket, so search for the next nextNode for (size_t i = curNode->Element.HashMod + 1; i < _self.Map.Size(); i++) { nextNode = _self.Map.Data()[i]; if (nextNode != NULL) break; } //No nextNode was found, so use the empty nextNode if (nextNode == NULL) nextNode = &_self.EmptyNode; } //Reestablish linkage curNode->Next = nextNode; curNode->Previous = nextNode->Previous; curNode->Previous->Next = curNode; curNode->Next->Previous = curNode; //Since we are pushing front, this always means we set the pointer _self.Map.Data()[curNode->Element.HashMod] = curNode; } } /*************************************************************************/ template <typename K, typename V, typename HT, typename H, size_t LF, typename LA, typename AA> size_t ZHashMap_SizeImpl<K, V, HT, H, LF, LA, AA>::Call(const ZHashMap<K, V, HT, H, LF, LA, AA>& _self) { return _self.ElementCount; } #endif
[ "PTB6082@C6499970EB677A4.amer.homedepot.com" ]
PTB6082@C6499970EB677A4.amer.homedepot.com
49e1231a6c62191ece894c1d971d1c7a4d8236b4
4897b9d75d851a81606d19a0e046b32eb16aa1bd
/other/lcp/09/09_bfs.cpp
abde9cb2f9f50a84eab728ca225fb311b1e2e763
[]
no_license
tiankonguse/leetcode-solutions
0b5e3a5b3f7063374e9543b5f516e9cecee0ad1f
a36269c861bd5797fe3835fc179a19559fac8655
refs/heads/master
2023-09-04T11:01:00.787559
2023-09-03T04:26:25
2023-09-03T04:26:25
33,770,209
83
38
null
2020-05-12T15:13:59
2015-04-11T09:31:39
C++
UTF-8
C++
false
false
2,242
cpp
#include "base.h" typedef long long ll; typedef long long LL; typedef unsigned long long ull; typedef unsigned long long ULL; typedef pair<int, int> pii; typedef pair<ll, ll> pll; // const int mod = 1e9 + 7; template <class T> using min_queue = priority_queue<T, vector<T>, greater<T>>; template <class T> using max_queue = priority_queue<T>; // lower_bound 大于等于 // upper_bound 大于 // vector/array: upper_bound(vec.begin(), vec.end(), v) // map: m.upper_bound(v) // reserve vector预先分配内存 // reverse(v.begin(), v.end()) 反转 // sum = accumulate(a.begin(), a.end(), 0); // unordered_map / unordered_set // 排序,小于是升序:[](auto&a, auto&b){ return a < b; }) // 优先队列 priority_queue<Node>:大于是升序 // struct Node{ // int t; // bool operator<(const Node & that)const { return this->t > that.t; } // }; const LL INF = 0x3f3f3f3f3f3f3f3fll; const double PI = acos(-1.0), eps = 1e-7; const int inf = 0x3f3f3f3f, ninf = 0xc0c0c0c0, mod = 1000000007; const int max3 = 2100, max4 = 11100, max5 = 200100, max6 = 2000100; // 基本思路,BFS,每个节点至多入队一次,for 循环内每个节点只扫描一次 // 复杂度:O(n) class Solution { public: int minJump(vector<int>& jump) { int n = jump.size(); vector<int> vis(n, 0); queue<pair<int, int>> que; que.push({0, 0}); vis[0] = 1; int max_left = 1; while(!que.empty()){ auto [v, step] = que.front(); que.pop(); int next_pos = v + jump[v]; if(next_pos >= n){ return step + 1; } if(vis[next_pos] == 0){ // 向后跳 que.push({next_pos, step + 1}); vis[next_pos] = 1; } // 向前跳 for(;max_left <= v; max_left++){ if(vis[max_left]) continue; que.push({max_left, step + 1}); vis[max_left] = 1; } } return 0; } }; int main() { // vector<double> ans = {1.00000,-1.00000,3.00000,-1.00000}; // vector<vector<int>> cars = {{1, 2}, {2, 1}, {4, 3}, {7, 2}}; // TEST_SMP1(Solution, getCollisionTimes, ans, cars); return 0; }
[ "i@tiankonguse.com" ]
i@tiankonguse.com
fc5c4d825bf43d2d7bce12ec036ec5a6826f0a85
1a7574ab447c4a12f9b93e6bf4783914f3ed6706
/WickedEngine/EnvProbeWindow.cpp
ac104d86b30a186ef973ec0958eb13fc9e1f68eb
[ "MIT", "Zlib" ]
permissive
cappah/WickedEngine
dfa9aecd7820129ff10f9cfb9d90e368eac53349
bf92cbda40a6ac514428a3af43764536d333fdf2
refs/heads/master
2021-01-12T15:05:44.637974
2016-10-22T11:38:23
2016-10-22T11:38:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,341
cpp
#include "stdafx.h" #include "EnvProbeWindow.h" int resolution = 256; EnvProbeWindow::EnvProbeWindow(wiGUI* gui) : GUI(gui) { assert(GUI && "Invalid GUI!"); float screenW = (float)wiRenderer::GetDevice()->GetScreenWidth(); float screenH = (float)wiRenderer::GetDevice()->GetScreenHeight(); envProbeWindow = new wiWindow(GUI, "Environment Probe Window"); envProbeWindow->SetSize(XMFLOAT2(600, 400)); envProbeWindow->SetEnabled(true); GUI->AddWidget(envProbeWindow); float x = 250, y = 0, step = 45; resolutionSlider = new wiSlider(1, 4096, 256, 4096, "Resolution"); resolutionSlider->SetPos(XMFLOAT2(x, y += step)); resolutionSlider->OnSlide([](wiEventArgs args) { resolution = (int)args.fValue; }); envProbeWindow->AddWidget(resolutionSlider); generateButton = new wiButton("Put"); generateButton->SetPos(XMFLOAT2(x, y += step)); generateButton->OnClick([](wiEventArgs args) { XMFLOAT3 pos; XMStoreFloat3(&pos, XMVectorAdd(wiRenderer::getCamera()->GetEye(), wiRenderer::getCamera()->GetAt()*4)); wiRenderer::PutEnvProbe(pos, resolution); }); envProbeWindow->AddWidget(generateButton); envProbeWindow->Translate(XMFLOAT3(30, 30, 0)); envProbeWindow->SetVisible(false); } EnvProbeWindow::~EnvProbeWindow() { SAFE_DELETE(envProbeWindow); SAFE_DELETE(resolutionSlider); SAFE_DELETE(generateButton); }
[ "turanszkij@gmail.com" ]
turanszkij@gmail.com
0f18a97c3d5ad0d5ce437338882abf3feff8e25b
748565c05766fd5610f9b22dfb4cf7279f264921
/Knights of Valor/Camera.cpp
d1d351bd90fbf73d6c84488740eaf0403cf24ad6
[]
no_license
ACEenterprise/Knights-of-Valor
f7e90d0bf149e31f0759ab8c10164ed77a80541a
070e3982967de54d7c753adb3af90e83ec481155
refs/heads/master
2021-01-20T17:51:07.599918
2017-05-26T10:48:58
2017-05-26T10:48:58
90,893,579
1
0
null
null
null
null
UTF-8
C++
false
false
425
cpp
#include"Camera.h" Camera::Camera(Map* map) { this->map = map; } void Camera::centrate(Knight* knight) { this->knight = knight; } void Camera::action(Graphics &g) { map->setX((1280 / 2 / 64) * 64-knight->getX()); map->setY((720 / 2 / 64) * 64 -knight->getY()); knight->draw(g, (1280 / 2 / 64) * 64, (720 / 2 / 64) * 64); } int Camera::getX() { return map->getX(); } int Camera::getY() { return map->getY(); }
[ "stoicaastefan@gmail.com" ]
stoicaastefan@gmail.com
8749ce083d33638e3dd669d4c15d27b53376aa7e
f5758d1e30fd4ea1e9e1db6e19345fef77e2a470
/CuartoEntregable/Evidencia/Graph/CSV.cpp
d1387a128e1714569ca1ce4e244c9caca6469feb
[]
no_license
JorgePerC/SItuacionProblemaDataEst
fac83eed331f16276bac0e0a28596141e428d89f
f71804b9f6cbfe8f06a179846b5d2354fbadf104
refs/heads/master
2023-01-28T12:11:58.609021
2020-12-02T06:00:01
2020-12-02T06:00:01
297,765,627
1
0
null
null
null
null
UTF-8
C++
false
false
3,901
cpp
// // CSV.cpp // POO_Class // // Created by Luis Alberto Fernández Castro on 21/09/20. // Copyright © 2020 LF Coding. All rights reserved. // #include <algorithm> #include "CSV.hpp" CSV::CSV() { this->filename = ""; } /** * Class to read file.csv * Arg: * string filename -> name of the file to read */ CSV::CSV(string filename) { this->filename = filename; } /** * Returns a vector containg the information * from the file.csv. Vector type is Details. * Iterates over the file.csv lines. */ vector<Details> CSV::read_csv_details() { vector<Details> lines; ifstream file(this->filename); if(!file.is_open()) { throw runtime_error("File can't be opened."); } else { } string line; while(getline(file, line)) { stringstream ss(line); string date; string time; string sourceIp; int sourcePort; string a; string aTest; string sourceName; string destinationIp; int destinationPort; string b; string bTest; string destinationName; getline(ss, date, ','); getline(ss, time, ','); getline(ss, sourceIp, ','); getline(ss, a, ','); stringstream aconv(a); aconv >> aTest; if (aTest == "-") { stringstream conva("-1"); conva >> sourcePort; } else { stringstream conva(a); conva >> sourcePort; } getline(ss, sourceName, ','); getline(ss, destinationIp, ','); getline(ss, b, ','); stringstream bconv(b); bconv >> bTest; if (bTest == "-") { stringstream convb("-1"); convb >> destinationPort; } else { stringstream convb(b); convb >> destinationPort; } ss >> destinationName; lines.push_back(Details(date, time, sourceIp, sourcePort, sourceName, destinationIp, destinationPort, destinationName)); } file.close(); return lines; } vector<string> CSV::getUniqueRowData(){ vector<string> lines; ifstream file(this->filename); if(!file.is_open()) { throw runtime_error("File can't be opened."); } string line; while(getline(file, line)) { stringstream ss(line); string date; string time; string sourceIp; int sourcePort; string a; string aTest; string sourceName; string destinationIp; int destinationPort; string b; string bTest; string destinationName; getline(ss, date, ','); // getline(ss, time, ','); // getline(ss, sourceIp, ','); // getline(ss, a, ','); // stringstream aconv(a); // aconv >> aTest; // if (aTest == "-") { // stringstream conva("-1"); // conva >> sourcePort; // } else { // stringstream conva(a); // conva >> sourcePort; // } // getline(ss, sourceName, ','); // getline(ss, destinationIp, ','); // getline(ss, b, ','); // stringstream bconv(b); // bconv >> bTest; // if (bTest == "-") { // stringstream convb("-1"); // convb >> destinationPort; // } else { // stringstream convb(b); // convb >> destinationPort; // } // ss >> destinationName; if(lines.empty()){ lines.push_back(date); } if(find(lines.begin(), lines.end(), date) != lines.end()) { /* do nothing */ } else { lines.push_back(date); } } file.close(); return lines; }
[ "jorgeperez_1@live.com" ]
jorgeperez_1@live.com
d4414eb6491194d84a6d9763e494a76d36a91bd9
fe92a722db8bdba378cc8747895f99bd2c209634
/NOPAT-26.cpp
0fd86695410562cc227c45ffce87ab696509c060
[]
no_license
bnblzq/algo-practice
00292fd79c4c56edda01c5c4b2922cc00cbd1d57
8b9126ecabf61b1d1fdd86207798fd5bdf05c5b4
refs/heads/master
2020-04-14T05:05:03.724096
2019-03-22T08:29:11
2019-03-22T08:29:11
163,652,209
0
0
null
null
null
null
UTF-8
C++
false
false
2,240
cpp
/* * 有一群人,打乒乓球比赛,两两捉对撕杀,每两个人之间最多打一场比赛。 球赛的规则如下:如果 A 打败了 B,B 又打败了 C,而 A 与 C 之间没有进 行过比赛,那么就认定,A 一定能打败 C。 如果 A 打败了 B,B 又打败了 C,而且,C 又打败了 A,那么 A、B、C 三 者都不可能成为冠军。 根据这个规则,无需循环较量,或许就能确定冠军。你的任务就是面对一群 比赛选手,在经过了若干场撕杀之后,确定是否已经实际上产生了冠军。 输入含有一些选手群,每群选手都以一个整数 n(n<1000)开头,后跟 n 对选 手的比赛结果,比赛结果以一对选手名字(中间隔一空格)表示,前者战胜后者。 如果 n 为 0,则表示输入结束。 对于每个选手群,若你判断出产生了冠军,则在一行中输出“Yes”,否则在 一行中输出“No”。 sample in: 3 Alice Bob Smith John Alice Smith 5 ac cd de be ad 0 sample out: Yes NO */ #include "stdio.h" #include "string" #include "map" int in [2002]; using namespace std; map<string,int> M; void clear(){ for (int i = 0; i < 2002; ++i) { in[i] = 0; } M.clear(); } int main(){ int num; char s1[10],s2[10]; while (scanf("%d",&num) !=EOF && num !=0){ clear(); int idx =0; for (int i = 0; i < num; ++i){ scanf("%s %s", s1, s2); string str1 = s1; string str2 = s2; if(M.find(str1) == M.end()){ //not exist M[str1] = idx ++; } int idx2 = 0; if(M.find(str2) == M.end()){ idx2 = idx; M[str2] = idx++; }else idx2 = M[str2]; in[idx2] ++; //DAG 's end point means lose. so ++ means lost to someone ,number means times } int count = 0; for (int j = 0; j < idx; ++j) { if( !in[j]) count ++; //if the factor =0,it is always the winner,but we wannan to find the unique } printf("%s", count==1? "YES":"NO"); printf("\n"); } return 0; }
[ "328397315@qq.com" ]
328397315@qq.com