blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
6b2a921d169355a8f3bacc3a13e4c5388117f99e
f4203d8e67946851abf8af2f80c77d180df34b62
/src/gbxsmartbatteryacfr/oceanserver.h
62baa76e034fb4b5bb0d654136a8edffe36d2e46
[]
no_license
naderman/gearbox
997547c6e6cb0f7830d2c8d9c30dfa999f8f86ff
a92ff328944502ed8ad0cc879a86bc177c5aa335
refs/heads/master
2016-09-05T10:06:36.371732
2010-02-23T23:20:33
2010-02-23T23:20:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,530
h
oceanserver.h
/* * GearBox Project: Peer-Reviewed Open-Source Libraries for Robotics * http://gearbox.sf.net/ * Copyright (c) 2004-2008 Tobias Kaupp * * This distribution is licensed to you under the terms described in * the LICENSE file included in this distribution. * */ #ifndef GBX_OCEANSERVER_H #define GBX_OCEANSERVER_H #include <memory> #include <gbxutilacfr/tracer.h> #include <gbxsmartbatteryacfr/oceanserverreader.h> using namespace std; namespace gbxsmartbatteryacfr { //! Class for reading data from an OceanServer battery system. //! Wraps up all the logic required to read from the system and //! maintain some incremental internal data storage. //! Also handles all ParsingExceptions. //! //! @author Tobias Kaupp //! class OceanServer { public: //! Initialises an OceanServerReader //! May throw a HardwareReadingException OceanServer( const std::string &port, gbxutilacfr::Tracer &tracer); //! Reads data from OceanServer, incrementally updates internal storage //! Returns a reference to the internal storage //! May throw gbxutilacfr::Exception //! May return an empty record ( check with isEmpty() ) const gbxsmartbatteryacfr::OceanServerSystem& getData(); private: gbxsmartbatteryacfr::OceanServerSystem data_; gbxutilacfr::Tracer& tracer_; auto_ptr<gbxsmartbatteryacfr::OceanServerReader> reader_; int exceptionCounter_; std::string exceptionString_; }; } //namespace #endif
4c32020d6aad7dd4e31f7ef6ce27e8006548d47c
cda554194a958513e37411c4dc2ad4fd01496266
/Bazaar/ini.cpp
d6a18802729d37607169233a06c3a860092d4675
[]
no_license
Hesaraih/Mappu
a5613d8238174c7dd413ee14eb1f9fe1bfbd7010
b2efaa195c01148fab1eeca37ed74ae2a46bb04e
refs/heads/master
2022-06-04T04:10:53.019914
2022-05-16T05:42:24
2022-05-16T05:42:24
121,482,419
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
14,551
cpp
ini.cpp
#if(_MSC_VER >= 1400) #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT 1 #define _CRT_NON_CONFORMING_SWPRINTFS 1 #define _CRT_SECURE_NO_WARNINGS 1 #endif //ユニコードでコンパイル #ifndef UNICODE #define UNICODE #endif #ifndef _UNICODE #define _UNICODE #endif #include <windows.h> #include <tchar.h> #include "main.h" //bazaar.ini読込み int ReadIni(HWND hWnd) { _TCHAR szBuf[MAX_PATH]; _TCHAR szFullPathName[MAX_PATH]; POINT pos,size; if(0 == GetFullPathName(_T("bazaar.ini"),sizeof(szFullPathName)/sizeof(_TCHAR),szFullPathName,NULL)){ return 0; } //[OFFSET] g_AutoOffset = GetPrivateProfileInt(_T("OFFSET"),_T("AUTO"),0,szFullPathName);//0.08で追加 GetPrivateProfileString(_T("OFFSET"),_T("NPCMAP"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_OffsetNpcMap = wcstoul(szBuf,NULL,16);//16進数で読み込みを行う GetPrivateProfileString(_T("OFFSET"),_T("NOWSTA"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_OffsetNowSta = wcstoul(szBuf,NULL,16);//16進数で読み込みを行う GetPrivateProfileString(_T("OFFSET"),_T("BAZAAR"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_OffsetBazaar = wcstoul(szBuf,NULL,16);//16進数で読み込みを行う //[NPC_MEM] GetPrivateProfileString(_T("NPC_MEM"),_T("POS_X"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); NPC_MEM.POS_X = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う //GetPrivateProfileString(_T("NPC_MEM"),_T("POS_Y"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName);//0.09で削除 //NPC_MEM.POS_Y = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う GetPrivateProfileString(_T("NPC_MEM"),_T("POS_Z"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); NPC_MEM.POS_Z = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う //GetPrivateProfileString(_T("NPC_MEM"),_T("CHANGEDID"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName);//0.09で削除 //NPC_MEM.CHANGEDID = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う GetPrivateProfileString(_T("NPC_MEM"),_T("NAME"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); NPC_MEM.Name = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う //GetPrivateProfileString(_T("NPC_MEM"),_T("DISTANCE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName);//0.09で削除 //NPC_MEM.DISTANCE = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う GetPrivateProfileString(_T("NPC_MEM"),_T("INRANGE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); NPC_MEM.Inrange = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う GetPrivateProfileString(_T("NPC_MEM"),_T("BAZAAR"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); NPC_MEM.Bazaar = (WORD)wcstoul(szBuf,NULL,16);//16進数で読み込みを行う //[SETTING] GetPrivateProfileString(_T("SETTING"),_T("USE_FILTER_PRICE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_UseFilterPrice = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("FILTER_PRICE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_FilterPrice = (int)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("AUTO_SCROLL"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_AutoScroll = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("LIST_COLOR"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ListColor = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("BLACK_LIST"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_BlackList = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("USE_FFXIAH"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_UseFFXIAH = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("FFXIAH"),NULL,g_FFXIAH,sizeof(g_FFXIAH)/sizeof(_TCHAR),szFullPathName); GetPrivateProfileString(_T("SETTING"),_T("TARGET"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName);//0.08で追加 g_TargetName = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("EXTRACT_SAVE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ExtractSave = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("DIR_SAVE"),NULL,g_DirSave,sizeof(g_FFXIAH)/sizeof(_TCHAR),szFullPathName); GetPrivateProfileString(_T("SETTING"),_T("SAVE_WINDOW"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_SaveWindow = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("SAVE_COLUMN"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_SaveColumn = (BYTE)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("KEY_DELAY"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_KeyDelay = wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("WAIT_UPDATE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_WaitUpdate = wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("SETTING"),_T("RETRY"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_Retry = wcstoul(szBuf,NULL,10); g_BazaarOrder = (BYTE)GetPrivateProfileInt(_T("SETTING"),_T("ORDER"),0,szFullPathName);//0.09で追加 g_BazaarNumWait05 = (BYTE)GetPrivateProfileInt(_T("SETTING"),_T("WAIT_NUM05"),0,szFullPathName);//0.09で追加 g_BazaarNumWait10 = (BYTE)GetPrivateProfileInt(_T("SETTING"),_T("WAIT_NUM10"),0,szFullPathName);//0.09で追加 g_BazaarNumWait20 = (BYTE)GetPrivateProfileInt(_T("SETTING"),_T("WAIT_NUM20"),0,szFullPathName);//0.09で追加 g_BazaarNumWait21 = (BYTE)GetPrivateProfileInt(_T("SETTING"),_T("WAIT_NUM21"),0,szFullPathName);//0.09で追加 //[WINDOW] GetPrivateProfileString(_T("WINDOW"),_T("POS_X"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); pos.x = (LONG)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("POS_Y"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); pos.y = (LONG)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("SIZE_X"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); size.x = (LONG)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("SIZE_Y"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); size.y = (LONG)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("COLUMN_PC"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ColumnWidth[COLUMN_PC] = (int)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("COLUMN_NAME"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ColumnWidth[COLUMN_NAME] = (int)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("COLUMN_PRICE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ColumnWidth[COLUMN_PRICE] = (int)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("COLUMN_NUMBER"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ColumnWidth[COLUMN_NUMBER] = (int)wcstoul(szBuf,NULL,10); GetPrivateProfileString(_T("WINDOW"),_T("COLUMN_NOTE"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_ColumnWidth[COLUMN_NOTE] = (int)wcstoul(szBuf,NULL,10); MoveWindow(hWnd,pos.x,pos.y,size.x,size.y,TRUE); if(g_KeyDelay < 100){ g_KeyDelay = 100; } if(g_WaitUpdate < 1000){ g_WaitUpdate = 1000; } if(g_Retry < 3){ g_Retry = 3; } return 1; } //bazaar.iniに設定を書込み int WriteIni() { _TCHAR szBuf[0x10]; _TCHAR szFullPathName[MAX_PATH]; int ret = 1; if(0 == GetFullPathName(_T("bazaar.ini"),sizeof(szFullPathName)/sizeof(_TCHAR)-1,szFullPathName,NULL)){ return 0; } _swprintf(szBuf,_T("%d"),g_AutoOffset);//0.08で追加 ret &= WritePrivateProfileString(_T("OFFSET"),_T("AUTO"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_UseFilterPrice); ret &= WritePrivateProfileString(_T("SETTING"),_T("USE_FILTER_PRICE"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_FilterPrice); ret &= WritePrivateProfileString(_T("SETTING"),_T("FILTER_PRICE"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_ListColor); ret &= WritePrivateProfileString(_T("SETTING"),_T("LIST_COLOR"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_AutoScroll); ret &= WritePrivateProfileString(_T("SETTING"),_T("AUTO_SCROLL"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_BlackList); ret &= WritePrivateProfileString(_T("SETTING"),_T("BLACK_LIST"),szBuf,szFullPathName); //_swprintf(szBuf,_T("%d"),g_BlackList); _swprintf(szBuf,_T("%d"),g_UseFFXIAH);//0.08で変更 ret &= WritePrivateProfileString(_T("SETTING"),_T("USE_FFXIAH"),szBuf,szFullPathName); ret &= WritePrivateProfileString(_T("SETTING"),_T("FFXIAH"),g_FFXIAH,szFullPathName); _swprintf(szBuf,_T("%d"),g_TargetName);//0.08で追加 ret &= WritePrivateProfileString(_T("SETTING"),_T("TARGET"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_ExtractSave); ret &= WritePrivateProfileString(_T("SETTING"),_T("EXTRACT_SAVE"),szBuf,szFullPathName); ret &= WritePrivateProfileString(_T("SETTING"),_T("DIR_SAVE"),g_DirSave,szFullPathName); _swprintf(szBuf,_T("%d"),g_SaveWindow); ret &= WritePrivateProfileString(_T("SETTING"),_T("SAVE_WINDOW"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_SaveColumn); ret &= WritePrivateProfileString(_T("SETTING"),_T("SAVE_COLUMN"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_KeyDelay); ret &= WritePrivateProfileString(_T("SETTING"),_T("KEY_DELAY"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_WaitUpdate); ret &= WritePrivateProfileString(_T("SETTING"),_T("WAIT_UPDATE"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_Retry); ret &= WritePrivateProfileString(_T("SETTING"),_T("RETRY"),szBuf,szFullPathName); //0.09で追加 _swprintf(szBuf,_T("%d"),g_BazaarOrder); ret &= WritePrivateProfileString(_T("SETTING"),_T("ORDER"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_BazaarNumWait05); ret &= WritePrivateProfileString(_T("SETTING"),_T("WAIT_NUM05"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_BazaarNumWait10); ret &= WritePrivateProfileString(_T("SETTING"),_T("WAIT_NUM10"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_BazaarNumWait20); ret &= WritePrivateProfileString(_T("SETTING"),_T("WAIT_NUM20"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_BazaarNumWait21); ret &= WritePrivateProfileString(_T("SETTING"),_T("WAIT_NUM21"),szBuf,szFullPathName); return ret; } //bazaar.iniの[WINDOW]セクション書込み int WriteIniWindow(HWND hWnd) { _TCHAR szBuf[0x10]; _TCHAR szFullPathName[MAX_PATH]; //RECT rect; WINDOWPLACEMENT wndPlace;//0.07で変更 int ret = 1; if(0 == GetFullPathName(_T("bazaar.ini"),sizeof(szFullPathName)/sizeof(_TCHAR)-1,szFullPathName,NULL)){ return 0; } //GetWindowRect(hWnd,&rect); wndPlace.length = sizeof(WINDOWPLACEMENT);//0.07で変更 GetWindowPlacement(hWnd,&wndPlace); //_swprintf(szBuf,_T("%d"),rect.left); _swprintf(szBuf,_T("%d"),wndPlace.rcNormalPosition.left);//0.07で変更 ret &= WritePrivateProfileString(_T("WINDOW"),_T("POS_X"),szBuf,szFullPathName); //_swprintf(szBuf,_T("%d"),rect.top); _swprintf(szBuf,_T("%d"),wndPlace.rcNormalPosition.top);//0.07で変更 ret &= WritePrivateProfileString(_T("WINDOW"),_T("POS_Y"),szBuf,szFullPathName); //_swprintf(szBuf,_T("%d"),rect.right - rect.left); _swprintf(szBuf,_T("%d"),wndPlace.rcNormalPosition.right - wndPlace.rcNormalPosition.left);//0.07で変更 ret &= WritePrivateProfileString(_T("WINDOW"),_T("SIZE_X"),szBuf,szFullPathName); //_swprintf(szBuf,_T("%d"),rect.bottom - rect.top); _swprintf(szBuf,_T("%d"),wndPlace.rcNormalPosition.bottom - wndPlace.rcNormalPosition.top);//0.07で変更 ret &= WritePrivateProfileString(_T("WINDOW"),_T("SIZE_Y"),szBuf,szFullPathName); return ret; } int WriteIniColumn() { _TCHAR szBuf[0x10]; _TCHAR szFullPathName[MAX_PATH]; int ret = 1; if(0 == GetFullPathName(_T("bazaar.ini"),sizeof(szFullPathName)/sizeof(_TCHAR)-1,szFullPathName,NULL)){ return 0; } _swprintf(szBuf,_T("%d"),g_ColumnWidth[COLUMN_PC]); ret &= WritePrivateProfileString(_T("WINDOW"),_T("COLUMN_PC"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_ColumnWidth[COLUMN_NAME]); ret &= WritePrivateProfileString(_T("WINDOW"),_T("COLUMN_NAME"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_ColumnWidth[COLUMN_PRICE]); ret &= WritePrivateProfileString(_T("WINDOW"),_T("COLUMN_PRICE"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_ColumnWidth[COLUMN_NUMBER]); ret &= WritePrivateProfileString(_T("WINDOW"),_T("COLUMN_NUMBER"),szBuf,szFullPathName); _swprintf(szBuf,_T("%d"),g_ColumnWidth[COLUMN_NOTE]); ret &= WritePrivateProfileString(_T("WINDOW"),_T("COLUMN_NOTE"),szBuf,szFullPathName); return ret; } //wantedを文字列から取得 int ReadWantedFromString(_TCHAR *szIniFile) { _TCHAR szBuf[MAX_PATH]; _TCHAR szFullPathName[MAX_PATH]; _TCHAR szSection[0x20]; int r,g,b; if(0 == GetFullPathName(szIniFile,sizeof(szFullPathName)/sizeof(_TCHAR),szFullPathName,NULL)){ return 0; } GetPrivateProfileString(_T("CALL"),_T("SOUND"),NULL,g_szSound,sizeof(g_szSound)/sizeof(_TCHAR),szFullPathName); GetPrivateProfileString(_T("COLOR"),_T("PRICE_LOW"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); swscanf(szBuf,_T("RGB(%i,%i,%i)"),&r,&g,&b); g_ColorLow = RGB(r,g,b); GetPrivateProfileString(_T("COLOR"),_T("PRICE_HIGH"),NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); swscanf(szBuf,_T("RGB(%i,%i,%i)"),&r,&g,&b); g_ColorHigh = RGB(r,g,b); for(int i=0;i<100;i++){ _swprintf(szSection,_T("%02d_USE"),i); GetPrivateProfileString(_T("WANTED"),szSection,_T("0"),szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_Wanted[i].use = (BYTE)wcstoul(szBuf,NULL,10); _swprintf(szSection,_T("%02d_NAME"),i); GetPrivateProfileString(_T("WANTED"),szSection,NULL,g_Wanted[i].szName,sizeof(g_Wanted[1].szName)/sizeof(_TCHAR),szFullPathName); _swprintf(szSection,_T("%02d_PRICE"),i); GetPrivateProfileString(_T("WANTED"),szSection,NULL,szBuf,sizeof(szBuf)/sizeof(_TCHAR),szFullPathName); g_Wanted[i].price = wcstoul(szBuf,NULL,10); } return 1; } //blist.ini int ReadBlackList() { _TCHAR szFullPathName[MAX_PATH]; _TCHAR szSection[0x20]; if(0 == GetFullPathName(_T("blist.ini"),sizeof(szFullPathName)/sizeof(_TCHAR),szFullPathName,NULL)){ return 0; } for(int i=0;i<100;i++){ _swprintf(szSection,_T("%02d_NAME"),i); GetPrivateProfileString(_T("BLIST"),szSection,NULL,g_szBlackListName[i],sizeof(g_szBlackListName[0])/sizeof(_TCHAR),szFullPathName); } return 1; }
6ee872c70a9cc484cd70aa11797183b2174c766c
fe8ab46707583c25a3fec68d786375f3034ce2cd
/Record.h
32391030303f437e24edb4fd1e17a99ac77cd1ca
[]
no_license
dilnuryuldashev/oop_records
9f35204cd2da5233e48dba26f6e0186086c0e740
28e37f9b63ad38951cd7b451ae8a38fc44e4073a
refs/heads/master
2022-05-15T09:26:39.352075
2016-10-05T05:12:54
2016-10-05T05:12:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,719
h
Record.h
// // Record.h // LinkedListRecordProjectFreelancer // // Created by Dilnur Yuldashev on 10/1/16. // Copyright © 2016 Dilnur Yuldashev. All rights reserved. /* I looked at the attached starter code, and it does not comply with Object-Oriented Programming rules at all. Class Record cannot be a list. Record is an object, and there might be a list of Records. Making class Record a list is not the way to go. Hence, I created a separate class Record. Also, We should not mix the implementations of class Record and Linked List at all because that defeats the logic of later usability and expandibility. For instance, we might want to have a list of football players. Then, if we have a Linked List class independent of Record or FootballPlayer, we can just create a List of football players using the same List class. */ #ifndef Record_h #define Record_h #include <stdio.h> #include <string> #include <iostream> using namespace std; class Record{ private: string _title; //Record name string _address; //Record Address string _date; //Record date float _price; //Record GPA public: // Default Constructor Record(); // Constructor Record(string title, string address, string date, float price); // Setters void setRecordTitle(string); void setRecordDate(string); void setRecordAddress(string); void setRecordPrice(float); // Getters string getRecordTitle(); string getRecordDate(); string getRecordAddress(); float getRecordPrice(); //Records are sorted by their titles //overloading the < operator //without this function, we cannot sort a list of Records //when we are in insert() function bool operator < (const Record &other_Record) const{ if (_title < other_Record._title) return true; //if two Records have the same titles //we look at their prices else if (_title == other_Record._title){ if(_price < other_Record._price) return true; else{ return false; } } return false; } //overloading the == operator bool operator == (const Record &other_Record) const{ if (_title == other_Record._title){ return true; } else return false; } //overloading the != operator bool operator != (const Record &other_Record) const{ return !(*this == other_Record); } //copying values in other to this Record //overloading the = operator Record& operator = (const Record& other) { if (this != &other) { // check if we are not assigning record to itself _title = other._title; _date = other._date; _address = other._address; _price = other._price; } return *this; } }; /* * This class is a child of class Record */ class Book: Record{ private: string _authorFirstName; string _authorSurname; bool _isPaperback; int _numberOfPages; bool isFromFile; public: // Default Constructor Book(); Book(bool t); // Constructor Book(string title, string address, string date, float price, string authorFirstName, string authorLastName, bool paperback, int numberOfPages); // Setters void setBookTitle(string); void setBookDate(string); void setBookAddress(string); void setBookPrice(float); //Book-only functions Setters void setBookAuthorFirstName(string); void setBookAuthorSurname(string); void setBookPaperback(bool); void setBookNumberOfPages(int); void setIsFromFileBool(bool); // Getters string getBookTitle(); string getBookDate(); string getBookAddress(); float getBookPrice(); //Book-only functions Getters string getBookAuthorFirstName(); string getBookAuthorSurname(); bool getBookPaperback(); int getBookNumberOfPages(); bool getIsFromFile(); Book& operator = (const Book& other){ Record::operator=(other); _authorFirstName = other._authorFirstName; _authorSurname = other._authorSurname; _isPaperback = other._isPaperback; _numberOfPages = other._numberOfPages; return *this; } bool operator == (const Book &other_Record) const{ return Record::operator==(other_Record); } bool operator != (const Book &other_Record) const{ return Record::operator!=(other_Record); } bool operator < (const Book &other_Record) const{ return Record::operator<(other_Record); } }; #endif /* Record_h */
77f4ff584b7eb2e0fc99d4fbf500536dc894ec43
157fd7fe5e541c8ef7559b212078eb7a6dbf51c6
/TRiAS/TRiAS/TRiAS/Obsolete (Win16 etc.)/IRISEVTS.CXX
42688e8f3a0da95d46b3c3ebd430e6c0eded29d7
[]
no_license
15831944/TRiAS
d2bab6fd129a86fc2f06f2103d8bcd08237c49af
840946b85dcefb34efc219446240e21f51d2c60d
refs/heads/master
2020-09-05T05:56:39.624150
2012-11-11T02:24:49
2012-11-11T02:24:49
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
36,416
cxx
IRISEVTS.CXX
// IRIS - Version fuer Windows 3.1 -- EventVerarbeitung ----------------------- // File: IRISEVTS.CXX #include "triaspre.hxx" #include "triasres.h" #include <xtensnxx.h> #include <rect.hxx> #if defined(OLD_TOOLBOX) #include "tools.hxx" // ToolBoxKonstanten #endif // OLD_TOOLBOX #include "coords.hxx" #include "legdinfo.hxx" #include "prlayout.hxx" #include "legende.hxx" #include "legwind.hxx" #include "shift.hxx" #if defined(OLD_MASSTAB) #include "masstab.hxx" #endif // OLD_MASSTAB #define NOSIGNONCODE #include "bildobj.hxx" #include "signon.hxx" #include "overview.hxx" #include "selectn.hxx" #if !defined(WIN32) #include "nomenkl.hxx" #else #include <funcs03.h> #include <undoguid.h> // GUID #include <iunredo.hxx> // Interface #endif // !WIN32 #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define BOUND(x,min,max) ((x)<(min)?(min):((x)>(max)?(max):(x))) extern Window *CurrActW; // HauptFenster extern App *CurrApp; extern ToolWind *pToolBox; extern TextRechercheDlg *pTextSearch; extern CoordsDlg *pCoords; extern COverView *pOverView; // Übersichtsanzeige #if !defined(WIN32) extern NomenklaturDlg *pNomenkl; #endif // !WIN32 extern bool Profiling; extern short GCancelFlag; extern bool TextSearchCFlag; extern bool PrintEFlag; extern bool LegendToRepaint; extern bool LegendeCFlag; extern bool OverViewCFlag; extern bool GenerateLegendOnly; // PseudoZeichnen, um genaue Legende zu haben extern CLegendeWindow *pLegende; extern MasstabDlg *pMasstab; extern HPALETTE hPalette; // derzeit aktive Palette des IrisWind extern short g_iMinutes; extern short g_iTicks; extern short g_iSignOnTicks; extern bool g_fPendingSave; // Speichern muß gemacht werden extern CSignOnDlg *g_pSODlg; // SignOnDlg // externe Funktionsdeklarationen --------------------------------------------- Dimension GetDotsPerMM (HANDLE hDC); Rectangle InflateRect (Rectangle &R, short iDelta); // Teile des Fensters neu zeichnen -------------------------------------------- void IrisWind :: Expose (ExposeEvt e) { if (NULL == m_pDBOs || 0 == m_pDBOs -> Count()) return; if (DBO().DB().isOpened() && DBO().toPaint() != PF_INVALID) { if (m_iDrawSem > 0) { // es läuft eine Zeichenaktion GCancelFlag |= GCFRepaint; // aktuelle abbrechen Rectangle rcEA = e.GetExposedArea(); Rectangle rcT = DBO().EA(); rcEA = rcEA + rcT; DBO().SetEA (rcEA); return; } // verhindert doppeltes Zeichnen if (DBO().isDrawing()) return; CEierUhr Wait (this); // EierUhr anzeigen ++m_iDrawSem; // MenuPunkt IDM_DRAW verändern HMENU hMenu = IrisMenu.Handle(API_MENU_HMENU); ModifyMenu (hMenu, IDM_DRAW, MF_BYCOMMAND, IDM_CANCEL, ResString (IDS_CANCELDRAW, 25)); // Accelerator für Abbruch installieren Accel newAccel (CANCELACCELS); pAccel oldAccel = ChangeAccel (&newAccel); DrawMenuBar (Handle (API_WINDOW_HWND)); GCancelFlag = GCFNormal; // eigentliche Zeichenroutinen #if !defined(NOGITTER) // evtl. Gitternetz zeichnen RePaintFlag = false; if (Gitter.GitterFlag()) // Gitternetz zeichnen Draw ((DrawObject *)&Gitter); #endif // DB neu zeichnen (Ausschnitt) Rectangle rcEA = e.GetExposedArea(); InflateRect ((RECT *)&rcEA, 0, -2); if (rcEA.Bottom() < 0) rcEA.Bottom() = 0; // if (rcEA.Top() > 0) rcEA.Top()--; // CommonVu - BugFixing // if (rcEA.Bottom() > 0) rcEA.Bottom()--; DBO().SetEA(rcEA); // neu zu zeichnendes Rechteck // Fenster neu skalieren DBO().Scale (this, DBO().GetExtend(), AspectRatio); // Maßstab neu angeben if (PrintEFlag && pMasstab != NULL) pMasstab -> SetMasstab (CanvasRect()); GenerateLegendOnly = false; DrawEx ((DrawObject *)&DBO(), 0); if (m_pDBOs -> Count() == 0 || !DBO().DB().isOpened()) { // DB wurde inzwischen zu gemacht if (GCancelFlag & GCFAppClosed) App :: Quit(); GCancelFlag = GCFNormal; return; } if (PrintEFlag) // evtl. aktivierte Obj's neu zeichnen ObjInfoListe.ActivateAllObj(); // nur wenn nicht gedruckt wird und nicht abgebrochen wurde // evtl. Legende neu zeichnen if (LegendToRepaint) { LegendToRepaint = false; if (LegendeCFlag) { pLegende -> RefreshLegend(); pLegende -> RePaint(); } } // Select-Rahmen evtl. neu zeichnen if (DRO != NULL) { SelectClipRgn ((HDC)Handle (API_WINDOW_HDC), NULL); // nicht mehr clippen Draw (*DRO); } // MenuPunkt IDM_REDRAW wieder initialisieren ModifyMenu (hMenu, IDM_CANCEL, MF_BYCOMMAND, IDM_DRAW, ResString (IDS_DRAW, 25)); // Wieder alte Acceleratoren ChangeAccel (oldAccel); DrawMenuBar (Handle (API_WINDOW_HWND)); // neu zeichnen auslösen if (GCancelFlag & GCFRepaint) { static Rectangle s_rcT; s_rcT = DBO().EA(); DEX_RePaintRect (s_rcT); } GCancelFlag = GCFNormal; --m_iDrawSem; } } // Behandlung der MausEvents -------------------------------------------------- // MausTaste gedrückt static short NEAR LeftButtonSem = false; // Semaphor für linke MausTaste static short NEAR RightButtonSem = false; // Semaphor für rechte Maustaste static short NEAR TrackObjectMenuFlag = false; // Semaphore für Floating Mneu void IrisWind :: MouseButtonDn (MouseEvt e) { // evtl. SignOn ausblenden DELETE (g_pSODlg); if (NULL == m_pDBOs || 0 == m_pDBOs -> Count()) return; // evtl. Markierungsrechteck löschen if (DRO != NULL && !RightButtonSem && !LeftButtonSem && !TrackObjectMenuFlag) { Draw (*DRO); // Rechteck löschen DELETE (DRO); } short actTool = pToolBox ? pToolBox -> iActTool() : NUMARROW; // MouseEventVerarbeitung if (e.isLeftButton() && !RightButtonSem) { switch (actTool) { case NUMARROW: case NUMZOOM: case NUMLUPE: case NUMSCHERE: LeftButtonSem++; // linke Maustaste auswerten MouseTrap (On); // alle MausEvents an dieses Fenster if (pCoords != NULL) // Koordinatenanzeige aktualisieren pCoords -> SetMode (CoordsDlg :: CM_Rectangle); DELETE (DRO); // DragRechteck initialisieren DRO = new DragRectangleObject (e.Where(), Dimension(), &emptyBrush()); if (DRO == NULL) return; (*DRO) -> ChangeRop (ROP_Invert); Draw (*DRO); // DragRechteck zeichnen break; case NUMLINEAL: // Mode: Entfernungen messen LeftButtonSem++; MouseTrap (On); // alle MausEvt's an dieses Fenster if (pCoords != NULL) // Mode von Koordinatenanzeige pCoords -> SetMode (CoordsDlg :: CM_Measure); DELETE (DRO); DRO = new DragLineObject (e.Where()); if (DRO == NULL) return; (*DRO) -> ChangeRop (ROP_Invert); break; case NUMSCHRIFT: { // Mode: Schrift verschieben Rectangle R; long lONr; Point pt = e.Where(); if (!DBO().Shapes().FindSchriftObjekt (pt, lONr, R)) return; DRO = new ShiftRectangleObject (pt, lONr, R, this); if (DRO == NULL) return; (*DRO) -> ChangeRop (ROP_Invert); LeftButtonSem++; MouseTrap (On); // alle MouseEvt's an dieses Fenster Draw (*DRO); // neues Rechteck zeichnen } break; } } else if (e.isRightButton() && !LeftButtonSem) { // rechte Maustaste auswerten switch (actTool) { #if defined(WIN32) case NUMARROW: case NUMLUPE: case NUMSCHERE: RightButtonSem++; // rechte Maustaste auswerten MouseTrap (On); // alle MausEvents an dieses Fenster if (pCoords != NULL) // Koordinatenanzeige aktualisieren pCoords -> SetMode (CoordsDlg :: CM_Rectangle); DELETE (DRO); // DragRechteck initialisieren DRO = new DragRectangleObject (e.Where(), Dimension(), NULL, &emptyBrush()); if (DRO == NULL) return; (*DRO) -> ChangeRop (ROP_Invert); Draw (*DRO); // DragRechteck zeichnen break; #endif // WIN32 case NUMZOOM: // Vergrößerung zurückschalten RightButtonSem++; PostMessage (Handle(API_WINDOW_HWND), WM_COMMAND, IDM_PREVSELAUSSCHNITT, 0L); break; case NUMSCHRIFT: // TextObjectFloatingMenu anzeigen und auswerten if (!TrackObjectMenuFlag) { long ONr; // ObjektNummer des Textes Rectangle R; // UmrißRechteck des TextObjektes Point Pt; // Punkt, an dem Menu erscheint if (!DBO().Shapes().FindSchriftObjekt (e.Where(), ONr, R)) { ONr = -1; Pt = e.Where(); } else Pt = Point (R.Right(), R.Bottom()); Point pt = e.Where(); DRO = new ShiftRectangleObject (pt, ONr, R); if (DRO == NULL) return; (*DRO) -> ChangeRop (ROP_Invert); RightButtonSem++; TrackObjectMenuFlag = true; Draw (*DRO); // neues Rechteck zeichnen TrackTextObjectMenu (Pt, ONr, R); // TextObjektMenu anzeigen Draw (*DRO); // Rechteck wieder wegblenden DELETE (DRO); TrackObjectMenuFlag = false; } break; } } } // Maus wird bewegt void IrisWind :: MouseMove (MouseEvt e) { if (NULL == m_pDBOs || 0 == m_pDBOs -> Count()) return; MousePos = e.Where(); // aktuelle MouseKoordinaten merken // wenn Koordinatenanzeige aktiv ist, dann neue Koordinaten anzeigen if (pCoords != NULL) pCoords -> SetCoords (MousePos); #if !defined(WIN32) // wenn Nomenklaturanzeige aktiv ist, dann Nomenklatur neu anzeigen if (pNomenkl != NULL) pNomenkl -> SetCoords (MousePos); #endif // !WIN32 } // Maus bei gedrückter Maustaste bewegt void IrisWind :: MouseDrag (MouseEvt e) { if (NULL == m_pDBOs || 0 == m_pDBOs -> Count()) return; // Koordinaten immer anzeigen MousePos = e.Where(); if (pCoords != NULL) pCoords -> SetCoords (MousePos); // nur linke MausTaste auswerten // if (!LeftButtonSem || !e.isLeftButton () || DRO == NULL) if (NULL == DRO) return; // Masstab neu anzeigen short actTool = pToolBox ? pToolBox -> iActTool() : NUMARROW; if (pMasstab != NULL && actTool == NUMZOOM) pMasstab -> SetMasstab (((DragRectangleObject *)(DrawObject *)(*DRO)) -> GetRect()); // DragRechteck neu Dimensionieren und neu Zeichen Draw (*DRO); (*DRO) -> Process (MousePos); Draw (*DRO); } // Maustaste wieder freigegeben void IrisWind :: MouseButtonUp (MouseEvt e) { if (NULL == m_pDBOs || 0 == m_pDBOs -> Count()) return; // Semaphore wieder löschen bool fIsLeft = e.isLeftButton(); bool fIsRight = e.isRightButton(); if (fIsRight && RightButtonSem > 0) RightButtonSem--; if (fIsLeft && LeftButtonSem > 0) LeftButtonSem--; // if (!LeftButtonSem || !e.isLeftButton () || DRO == NULL) if (NULL == DRO) return; // fertig // MausEvents wieder freigeben MouseTrap (Off); // Koordinatenanzeige wieder in alten Zustand bringen if (pCoords != NULL) pCoords -> SetMode (CoordsDlg :: CM_Normal); // Dragrechteck löschen, wenn nicht selektieren short actTool = pToolBox ? pToolBox -> iActTool() : NUMARROW; Draw (*DRO); // ausblenden (*DRO) -> Process (e.Where()); if (actTool == NUMARROW || actTool == NUMZOOM || actTool == NUMLUPE || actTool == NUMSCHERE) ((DragRectangleObject *)(DrawObject *)(*DRO)) -> CorrectCoOrds(); // Rect ggf. kippen // je nach aktivem Werkzeug Aktion auswählen switch (actTool) { case NUMARROW: if (fIsLeft) { if (!((DragRectangleObject *)(DrawObject *)(*DRO)) -> isValid()) { // Rechteck ist entartet --> löschen DELETE (DRO); break; } else Draw (*DRO); // DragRechteck neuzeichnen } #if defined(WIN32) else if (fIsRight) { // SelectRectDlg anzeigen TX_ASSERT(NULL != DRO); // Der Dialog übernimmt den Rest Draw (*DRO); // DragRechteck neuzeichnen CSelectRectDlg SRDlg (this, DBO().pCT(), *(DragRectangleObject *)(DrawObject *)(*DRO)); SRDlg.RemoveOnEnd (false); // blendet DRO bei OK am Schluß nicht aus SRDlg.Show(); if (!SRDlg.Result()) { DELETE(DRO); } } #endif // WIN32 break; // sonst nichts machen, Rechteck ist angezeigt case NUMLUPE: // Recherche case NUMSCHERE: // Recherche und Objekte löschen #if defined(WIN32) if (fIsRight) { // SelectRectDlg anzeigen (nur Rechts) TX_ASSERT(NULL != DRO); Draw (*DRO); // DragRechteck neuzeichnen CSelectRectDlg SRDlg (this, DBO().pCT(), *(DragRectangleObject *)(DrawObject *)(*DRO)); SRDlg.RemoveOnEnd (true); // blendet DRO bei OK am Schluß aus SRDlg.Show(); if (!SRDlg.Result()) break; // abbrechen } #endif // WIN32 { // sowohl Rechts, als auch Links if (!(((DragRectangleObject *)(DrawObject *)(*DRO)) -> isValid())) // kein Rechteck aufgezogen ((DragRectangleObject *)(DrawObject *)(*DRO)) -> InflateRect (3); // Rechteck generieren (4x4Pix) // Koordinaten transformieren Point pt1 = ((DragRectangleObject *)(DrawObject *)(*DRO))->LowerLeft(); Point pt2 = ((DragRectangleObject *)(DrawObject *)(*DRO))->UpperRight(); Punkt Pt1 = DCtoOC (pt1); Punkt Pt2 = DCtoOC (pt2); ObjContainer OC (Pt1, Pt2); ObjektRecherche (*(DragRectangleObject *)(DrawObject *)(*DRO), OC, actTool == NUMSCHERE); } break; case NUMZOOM: // Bildausschnitt wählen, Selektieren if (!fIsLeft) return; // Testen ob Rechteck entartet ist if (((DragRectangleObject *)(DrawObject *)(*DRO)) -> isValid ()) { // Koordinaten transformieren Point pt1 = ((DragRectangleObject *)(DrawObject *)(*DRO))->LowerLeft(); Point pt2 = ((DragRectangleObject *)(DrawObject *)(*DRO))->UpperRight(); Punkt Pt1 = DCtoOC (pt1); Punkt Pt2 = DCtoOC (pt2); ObjContainer OC (Pt1, Pt2); // wenn Auflösungsgrenze erreicht wurde if (!OC.isValid()) break; // raus --> Fehlermeldung ??? actClip.Push (DBO().GetExtend()); // alten Ausschnitt merken // neuen Ausschnitt einstellen ObjContainer oc = OC.InflateCont (10); DBO().SetExtend (this, oc, AspectRatio); // bei Bedarf ScrollBars einblenden und initialisieren InitWndScrollBars (); // wenn Übersicht angezeigt wird, dann Rechteck aktualisieren if (OverViewCFlag && pOverView) { Rectangle rcC = CanvasRect(); ObjContainer OC (rcC); pOverView -> SetActVP (OC); } LegendToRepaint = true; // neuen Ausschnitt darstellen RePaintFlag = true; RePaint (); } break; case NUMSCHRIFT: // Schrift verschieben if (!fIsLeft) return; if (m_pDBOs -> Count() && DBO().DB().isOpened()) { // neue TextKoordinaten wegschreiben ShiftRectangleObject *pSRO = (ShiftRectangleObject *)(DrawObject *)(*DRO); Rectangle BRc = pSRO -> BoundingBox(); // je nach BezugsPunkt den Punkt korrigieren Point Pt = Point (BRc.Left(), BRc.Bottom()); long lONr = pSRO -> ONr(); bool fRO = DEX_GetROMode(); bool fTemp = DEX_GetObjectStatus (lONr) & OSTemp; // auf Bezugspunkt des Textes normalisieren DBO().Shapes().CorrectPosition (lONr, Pt); Punkt Pkt = DCtoOC (Pt); // Geometrie ändern #if defined(WIN32) pSRO -> ResetPointer(); // Cursor rücksetzen if (GetKeyState (VK_CONTROL) >= 0) { if (!pSRO -> isDirty()) break; // keine Änderung // normales Text verschieben ResString resUndo (IDS_UNDOMODIFYTEXTPOINT, 64); char cbBuffer[64]; wsprintf (cbBuffer, resUndo.Addr(), lONr); DEX_BeginUndoLevel (cbBuffer); LPUNDOREDOMODIFYOBJECT pIUndo = NULL; HRESULT hr = UndoCreateInstance (IID_IUndoRedoModifyObject, (LPVOID *)&pIUndo); if (SUCCEEDED(hr)) { TEXTGEOMETRIE TG; INITSTRUCT(TG, TEXTGEOMETRIE); TG.lONr = lONr; TG.lCnt = 1; TG.iFlags = OGModObject; TG.pdblX = &Pkt.X(); TG.pdblY = &Pkt.Y(); TG.iKCnt = _MAX_PATH; hr = pIUndo -> Init (lONr, (OBJGEOMETRIE *)&TG, NULL); } if (!fRO && !fTemp) { if (EC_OKAY == DBO().DB().ModGIPunkt (lONr, Pkt)) { if (SUCCEEDED(hr)) DEX_AddUndoRedo (pIUndo); DEX_EndUndoLevel(); } else { DEX_CancelUndoLevel(true); break; } } else // nur in DB schieben, wenn nicht temp oder RO DEX_CancelUndoLevel(false); if (DBO().Shapes().ModGIText (lONr, Pkt)) { Rectangle rc = pSRO -> oldR(); RePaintRect (InflateRect (rc, 5)); } } else CopyText (lONr, Pkt, fRO); // Text doppeln #else // WIN32 // normales Text verschieben if (!fRO && !fTemp && (DBO().DB().ModGIPunkt (lONr, Pkt) != EC_OKAY)) break; // nur in DB schieben, wenn nicht temp oder RO if (DBO().Shapes().ModGIText (lONr, Pkt)) { Rectangle rc = pSRO -> oldR(); RePaintRect (InflateRect (rc, 5)); } #endif // WIN32 Rectangle rc = pSRO -> BoundingBox(); RePaintRect (InflateRect (rc, 5)); } break; } // DrawObject freigeben, wenn nicht Pfeil if (actTool != NUMARROW) DELETE (DRO); } // EventHandler für MouseDoppelClick ------------------------------------------ void IrisWind :: MouseButtonDblClk (MouseEvt) { return; // für DebuggingZwecke } // EventHandler für den Fall, daß Fenstergröße vom Nutzer verändert wird ------ void IrisWind :: ReSize (ReSizeEvt e) { // neue FensterGröße merken MSize = e.GetNewSize(); // bei Bedarf ScrollBars einblenden und initialisieren InitWndScrollBars(); // wenn Übersicht angezeigt wird, dann Rechteck aktualisieren if (OverViewCFlag && pOverView) { ObjContainer ocT = DBO().GetExtend(); ObjContainer ocT1 = DBO().DB().DBCont(); if (ocT < ocT1) { Rectangle rcC = CanvasRect(); ObjContainer OC (rcC); pOverView -> SetActVP (OC); } } if (pToolBox) // Werkzeugkasten neu positionieren pToolBox -> PositionTools(); } // EventHandler für den Fall, daß das Fenster vom Nutzer verschoben wird void IrisWind :: Move (MoveEvt e) { // neuen FensterUrsprung merken MOrig = e.NewOrigin(); } // Initialisierungsfunktion, die ObjInfoDlg-Fenster anzeigt ------------------- extern "C" { typedef struct tagDELINFODATA { DragRectangleObject *pDRO; bool iDelFlag; } DELINFODATA; POINT EXPORTTRIAS WINAPI OICorrectPosition (pWindow pW, void *pData) { DELINFODATA *pDID = (DELINFODATA *)pData; if (pDID -> iDelFlag) ((ObjektInfo *)pW) -> EnableDeleteMenu(); return ((ObjektInfo *)pW) -> CorrectPosition (*pDID -> pDRO); } } // extern "C" void IrisWind :: ObjektRecherche (DragRectangleObject &DRO, ObjContainer &OC, bool fDelFlag) { ObjFeld Objekte; // ArrayContainer CEierUhr Wait (this); // EierUhr anzeigen HWND hWnd = NULL; if (GetKeyState (VK_CONTROL) < 0) hWnd = ObjInfoListe.GetActiveORWindow(); // alle Objekte in diesem Rechteck suchen { ErrInstall EI (WC_NOON, ReportNotFoundError); ErrCode EC = DBO().DB().GIWindow (OC, Objekte, true); // Objektnummern aufsammeln if (EC != EC_OKAY) return; // nach Identifikatoren filtern DBO().DB().IdFilter (Objekte, DBO().Idents()); if (0 == Objekte.Count()) { db_error (WC_NOON, RC_RechResults, ""); return; } } // Dialogfenster generieren DEXXCREATEOBJEKTINFOEX crOI; DELINFODATA DID; DID.pDRO = &DRO; DID.iDelFlag = fDelFlag; memset (&crOI, '\0', sizeof(DEXXCREATEOBJEKTINFOEX)); crOI.dwSize = sizeof(DEXXCREATEOBJEKTINFOEX); if (!fDelFlag) crOI.lpCaption = StrDup (ResString (IDS_OBJINFOCAPTION, 30), RC_ObjRecherche); else crOI.lpCaption = StrDup (ResString (IDS_OBJDELCAPTION, 30), RC_ObjRecherche); crOI.lcObjs = &Objekte; crOI.pcMColor = new Color (RED); crOI.ppntPos = new Point (0, 0); crOI.fcnPos = (OIPOSPROC)OICorrectPosition; crOI.pData = &DID; crOI.m_hWnd = hWnd; // zu existierendem hinzufügen DEXX_CreateObjektInfo (crOI); // RechercheFenster generieren if (crOI.ppntPos) delete crOI.ppntPos; if (crOI.pcMColor) delete crOI.pcMColor; if (crOI.lpCaption) delete crOI.lpCaption; // Speicher wieder freigeben } // Initialisierungsfunktion, die ObjInfoDlg-Fenster anzeigt ------------------- ErrCode IrisWind :: ShowOIRechResults (ObjFeld &OF) { #if 0 // ====================================================================== // Dialogfenster generieren DEXXCREATEOBJEKTINFOEX crOI; ErrCode RC; memset (&crOI, '\0', sizeof(DEXXCREATEOBJEKTINFOEX)); crOI.dwSize = sizeof(DEXXCREATEOBJEKTINFO); crOI.lpCaption = StrDup (ResString (IDS_DBASEINFOCAPTION, 30), RC_RechResults); crOI.lcObjs = &OF; crOI.pcMColor = new Color (RED); crOI.ppntPos = new Point (0, 0); crOI.fcnPos = NULL; crOI.pData = NULL; RC = DEXX_CreateObjektInfo (crOI) != NULL ? EC_OKAY ? WC_RETURN; // RechercheFenster generieren if (crOI.ppntPos) delete crOI.ppntPos; if (crOI.pcMColor) delete crOI.pcMColor; if (crOI.lpCaption) delete crOI.lpCaption; // Speicher wieder freigeben // ValidateWindow (); // Hauptfenster nicht neu zeichnen return RC; #endif // ===================================================================== return EC_OKAY; } // TimerEvts ------------------------------------------------------------------ void EXPORTTRIAS IrisWind :: Strobe (StrobeEvt e) { switch (e.GetStrobeID()) { case 1: { CTable t(ObjInfoListe); // Alle bestehenden Objektfenster durchsehen, ob noch alle // angezeigt werden, wenn nicht, dann löschen for (t.First(); t.Valid(); ) { register bool toDelete = false; { ObjektInfoLock l(t); if (l && l -> m_fToDelete) toDelete = true; } if (toDelete) { if (!t.Delete()) break; } else { if (!t.Next()) break; } } if (PrintEFlag && ObjInfoListe.Count()) ObjInfoListe.BlinkAllObj (); // blinken wenn nicht gedruckt wird // evtl. Übersichtsfenster löschen if (pOverView && pOverView -> fToDelete()) { DELETE (pOverView); } // SignOn nach spätestens 5 Sekunden ausblenden if (g_iSignOnTicks == 10) { DELETE (g_pSODlg); } else if (g_iSignOnTicks < 10) g_iSignOnTicks++; } break; case 2: // TimerEvent kommt jede Minute, FlushDB auslösen { if ((g_iTicks++/10) < g_iMinutes) break; g_iTicks = 0; g_fPendingSave = true; } break; } } // Parameter der ScrollBalken einstellen -------------------------------------- void IrisWind :: InitWndScrollBars (void) { // wenn keine DB offen ist, dann wieder raus if (m_pDBOs -> Count() == 0 || !DBO().DB().isOpened() || DBO().isClosing()) return; static short NEAR iScrollSem = 0; if (!iScrollSem) { iScrollSem++; // doppeltes rufen verhindern // Wertebereiche der ScrollBar's Rectangle Rc = RealCanvasRect(); ObjContainer DBCont = DBO().DB().DBCont(); // DatenbasisContainer for (short i = 0; i < 2; i++) { Punkt Pkt1 = DCtoOC (Rc.Left(), Rc.Bottom()); Punkt Pkt2 = DCtoOC (Rc.Right(), Rc.Top()); ObjContainer OC (Pkt1, Pkt2); ObjContainer ocDBContEx (DBCont); ocDBContEx += OC; ocDBContEx.InflateCont(5); // 10% größer machen // TransformationsKoeffizienten KoOrd dSX = KoOrdMax (0, ocDBContEx.Breite() - OC.Breite()); KoOrd dSY = KoOrdMax (0, ocDBContEx.Hoehe() - OC.Hoehe()); m_kSX = dSX/SHRT_MAX +1; m_kSY = dSY/SHRT_MAX +1; // Berechnen der ScrollBalken long iRangeH = dSX / m_kSX; long iRangeV = dSY / m_kSY; if (iRangeH < 0) iRangeH = 0; if (iRangeV < 0) iRangeV = 0; // etwas neuzeichnen ? long xThumbPos = m_pWHS ? m_pWHS -> GetThumbPos() : 0; long yThumbPos = m_pWVS ? m_pWVS -> GetThumbPos() : 0; if (yThumbPos > iRangeV || xThumbPos > iRangeH) RePaint(); // ScrollBalken anzeigen bzw. löschen if (iRangeV > 0) { m_pWVS = EnableVScroll (true); m_pWVS -> Show(); m_pWVS -> SetRange (Range (0, short(iRangeV))); yThumbPos = (OC.YMin()- ocDBContEx.YMin()) / m_kSY; yThumbPos = BOUND (yThumbPos, 0, iRangeV); // nur positive Zahlen m_pWVS -> SetThumbPos (short(iRangeV-yThumbPos)); } else { if (m_pWVS) m_pWVS -> Hide(); if (m_pWVS) m_pWVS -> SetRange (Range (0, 0)); EnableVScroll (false); m_pWVS = NULL; m_kSY = 1; } if (iRangeH > 0) { m_pWHS = EnableHScroll (true); m_pWHS -> Show(); m_pWHS -> SetRange (Range (0, short (iRangeH))); xThumbPos = (OC.XMin()- ocDBContEx.XMin()) / m_kSX; xThumbPos = BOUND (xThumbPos, 0, iRangeH); // nur positive Zahlen m_pWHS -> SetThumbPos (short(xThumbPos)); } else { if (m_pWHS) m_pWHS -> Hide(); if (m_pWHS) m_pWHS -> SetRange (Range (0, 0)); EnableHScroll (false); m_pWHS = NULL; m_kSX = 1; } // nur für die zweite Runde if (i == 0) Rc = CanvasRect(); } iScrollSem--; } } // Verarbeitung der ScrollEvt's ----------------------------------------------- static IDLEPAINT NEAR g_ipIdlePaint; // Struktur für Rollen/Neuzeichnen void App :: Idle (InvokeStatus s) // wenn sonst nichts zu tun ist { if (s == IdleInit) { // komt nur einmal am Anfang g_ipIdlePaint.m_hWnd = NULL; g_ipIdlePaint.m_hRgn = NULL; DEXN_ServerInitialized(); // fertig initialisiert, MessageLoop läuft return; } if (g_ipIdlePaint.m_hWnd) { // Request is pending: Redraw if (g_ipIdlePaint.m_hRgn) { // Request is pending: RegionRedraw InvalidateRgn (g_ipIdlePaint.m_hWnd, g_ipIdlePaint.m_hRgn, true); // ReInit IdlePaintStruct DeleteObject (g_ipIdlePaint.m_hRgn); g_ipIdlePaint.m_hRgn = NULL; g_ipIdlePaint.m_hWnd = NULL; // doppeltes WM_PAINT verhindern } else { // FullRedraw InvalidateRect (g_ipIdlePaint.m_hWnd, NULL, true); g_ipIdlePaint.m_hWnd = NULL; // doppeltes WM_PAINT verhindern } } if (g_fPendingSave) { g_fPendingSave = false; if (NULL != __hWndM) PostMessage (__hWndM, WM_COMMAND, IDM_SAVEDB, 0L); } } void IrisWind :: VertScroll (ScrollEvt e) { if (m_iDrawSem || m_pWVS == NULL) return; // nicht während des zeichnens // aktuelle RollBalkenParameter lesen KoOrd iOldPos = e.GetOldPos(); KoOrd iNewPos = e.GetPos(); if (iOldPos == iNewPos) return; // nothing to do Rectangle Rc = CanvasRect(); Punkt Pkt1 = DCtoOC (Rc.Left(), Rc.Bottom()); Punkt Pkt2 = DCtoOC (Rc.Right(), Rc.Top()); ObjContainer OC (Pkt1, Pkt2); // Container des aktuellen Fensters Range r = m_pWVS -> GetRange(); // Scrollbereich lesen KoOrd dSY = (r.Max()-r.Min())*m_kSY; KoOrd Delta = 0; // Fensterverschiebung besorgen // neue horizontale Rollposition berechnen iOldPos *= m_kSY; iNewPos *= m_kSY; switch (e.GetScrollType()) { case UnitDecrement: Delta = -OC.Hoehe() / 32; break; case UnitIncrement: Delta = OC.Hoehe() / 32; break; case BlockDecrement: Delta = -OC.Hoehe() / 3; break; case BlockIncrement: Delta = OC.Hoehe() / 3; break; case ThumbDrag: Delta = iNewPos - iOldPos; break; default: Delta = 0; return; } // Rollen auf aktuellen Rollbereich begrenzen Delta = BOUND (iOldPos + Delta, 0, dSY) - iOldPos; if (Delta != 0) { HWND hWnd = Handle (API_WINDOW_HWND); CoOrd dY = -OCtoDCYDelta (Delta); if (pToolBox) pToolBox -> Hide(); if (DRO != NULL) { Draw(*DRO); // DRO ausblenden DELETE (DRO); // und freigeben } DEXN_ScrollingVert (dY); ScrollWindow (hWnd, 0, dY, NULL, NULL); if (pToolBox) { pToolBox -> PositionTools(); pToolBox -> Show(); } g_ipIdlePaint.m_hWnd = hWnd; if (!m_fFullRedrawOnScroll) { HRGN hRgn = CreateRectRgn (0, 0, 0, 0); GetUpdateRgn (hWnd, hRgn, false); if (g_ipIdlePaint.m_hRgn) { HRGN hCRgn = CreateRectRgn (0, 0, 0, 0); OffsetRgn (g_ipIdlePaint.m_hRgn, 0, dY); CombineRgn (hCRgn, hRgn, g_ipIdlePaint.m_hRgn, RGN_OR); DeleteObject (hRgn); DeleteObject (g_ipIdlePaint.m_hRgn); g_ipIdlePaint.m_hRgn = hCRgn; } else g_ipIdlePaint.m_hRgn = hRgn; } else g_ipIdlePaint.m_hRgn = NULL; ValidateRect (hWnd, NULL); // nicht jetzt zeichnen m_pWVS -> SetThumbPos (short((iOldPos + Delta)/m_kSY)); // neuen Bildausschnitt in GeoDB einstellen Ausdehnung locA (0, -Delta); DBO().Scale (this, DBO().GetExtend().ShiftCont (locA), AspectRatio); if (OverViewCFlag && pOverView) { Rectangle rcC = CanvasRect(); ObjContainer OC (rcC); pOverView -> SetActVP (OC); } } } void IrisWind :: HorizScroll (ScrollEvt e) { if (m_iDrawSem || m_pWHS == NULL) return; // nicht während des Zeichnens // aktuelle RollBalkenParameter lesen KoOrd iOldPos = e.GetOldPos(); KoOrd iNewPos = e.GetPos(); if (iOldPos == iNewPos) return; // nothing to do Rectangle Rc = CanvasRect(); Punkt Pkt1 = DCtoOC (Rc.Left(), Rc.Bottom()); Punkt Pkt2 = DCtoOC (Rc.Right(), Rc.Top()); ObjContainer OC (Pkt1, Pkt2); // Container des aktuellen Fensters Range r = m_pWHS -> GetRange(); // Scrollbereich lesen KoOrd dSX = (r.Max()-r.Min())*m_kSX; KoOrd Delta = 0; // Fensterverschiebung besorgen // neue horizontale Rollposition berechnen iOldPos *= m_kSX; iNewPos *= m_kSX; switch (e.GetScrollType()) { case UnitDecrement: Delta = -OC.Breite() / 32; break; case UnitIncrement: Delta = OC.Breite() / 32; break; case BlockDecrement: Delta = -OC.Breite() / 3; break; case BlockIncrement: Delta = OC.Breite() / 3; break; case ThumbDrag: Delta = iNewPos - iOldPos; break; default: Delta = 0; return; } // Rollen auf aktuellen Rollbereich begrenzen Delta = BOUND (iOldPos + Delta, 0, dSX) - iOldPos; if (Delta != 0) { HWND hWnd = Handle (API_WINDOW_HWND); CoOrd dX = -OCtoDCXDelta (Delta); if (pToolBox) pToolBox -> Hide(); // Werkzeugkasten richten if (DRO != NULL) { Draw(*DRO); // DRO ausblenden DELETE (DRO); } DEXN_ScrollingHorz (dX); // es soll gescrollt werden ScrollWindow (hWnd, dX, 0, NULL, NULL); if (pToolBox) { pToolBox -> PositionTools(); pToolBox -> Show(); } g_ipIdlePaint.m_hWnd = hWnd; if (!m_fFullRedrawOnScroll) { HRGN hRgn = CreateRectRgn (0, 0, 0, 0); GetUpdateRgn (hWnd, hRgn, false); if (g_ipIdlePaint.m_hRgn) { HRGN hCRgn = CreateRectRgn (0, 0, 0, 0); OffsetRgn (g_ipIdlePaint.m_hRgn, dX, 0); CombineRgn (hCRgn, hRgn, g_ipIdlePaint.m_hRgn, RGN_OR); DeleteObject (hRgn); DeleteObject (g_ipIdlePaint.m_hRgn); g_ipIdlePaint.m_hRgn = hCRgn; } else g_ipIdlePaint.m_hRgn = hRgn; } else g_ipIdlePaint.m_hRgn = NULL; ValidateRect (hWnd, NULL); // nicht jetzt zeichnen m_pWHS -> SetThumbPos (short((iOldPos + Delta)/m_kSX)); // neuen Bildausschnitt in GeoDB einstellen Ausdehnung locA (Delta, 0); DBO().Scale (this, DBO().GetExtend().ShiftCont (locA), AspectRatio); if (OverViewCFlag && pOverView) { Rectangle rcC = CanvasRect(); ObjContainer OC (rcC); pOverView -> SetActVP (OC); } } } // FocusChangeEvt ------------------------------------------------------------- void EXPORTTRIAS IrisWind :: FocusChange (FocusChangeEvt e) { StrobeWindow :: FocusChange (e); } // KeyEvents ------------------------------------------------------------------ void IrisWind :: KeyDown (KeyEvt e) { // evtl. SignOn ausblenden DELETE (g_pSODlg); #if defined(WIN32) // evtl. Cursor umschalten if (NULL != DRO) { if (DRO -> ToProcessKey()) { Draw (*DRO); DRO -> ProcessKey(e); Draw (*DRO); } } #endif // WIN32 // RollBalken bedienen if (e.ASCIIChar() == '\0') { HWND hWnd = Handle (API_WINDOW_HWND); switch (e.Keycode()) { case VK_UP: if (m_pWVS) PostMessage (hWnd, WM_VSCROLL, SB_LINEUP, 0L); return; case VK_DOWN: if (m_pWVS) PostMessage (hWnd, WM_VSCROLL, SB_LINEDOWN, 0L); return; case VK_PRIOR: if (m_pWVS) PostMessage (hWnd, WM_VSCROLL, SB_PAGEUP, 0L); return; case VK_NEXT: if (m_pWVS) PostMessage (hWnd, WM_VSCROLL, SB_PAGEDOWN, 0L); return; case VK_HOME: if (m_pWHS) PostMessage (hWnd, WM_HSCROLL, SB_PAGEUP, 0L); return; case VK_END: if (m_pWHS) PostMessage (hWnd, WM_HSCROLL, SB_PAGEDOWN, 0L); return; case VK_LEFT: if (m_pWHS) PostMessage (hWnd, WM_HSCROLL, SB_LINEUP, 0L); return; case VK_RIGHT: if (m_pWHS) PostMessage (hWnd, WM_HSCROLL, SB_LINEDOWN, 0L); return; default: // weiterreichen break; } } StrobeWindow :: KeyDown (e); } void IrisWind :: KeyUp (KeyEvt e) { #if defined(WIN32) if (NULL != DRO) { if (DRO -> ToProcessKey()) { Draw (*DRO); DRO -> ProcessKey(e); Draw (*DRO); } } #endif // WIN32 // ScrollBalken behandeln if (e.ASCIIChar() == '\0') { HWND hWnd = Handle (API_WINDOW_HWND); switch (e.Keycode()) { case VK_UP: case VK_DOWN: case VK_PRIOR: case VK_NEXT: if (m_pWVS) PostMessage (hWnd, WM_VSCROLL, SB_ENDSCROLL, 0L); return; case VK_HOME: case VK_END: case VK_LEFT: case VK_RIGHT: if (m_pWHS) PostMessage (hWnd, WM_HSCROLL, SB_ENDSCROLL, 0L); return; default: // weiterreichen break; } } StrobeWindow :: KeyUp (e); } // PaletteHandling ------------------------------------------------------------ void EXPORTTRIAS IrisWind :: PaletteChange (PaletteChangeEvt e) { HWND hWnd = Handle (API_CLIENT_HWND); int i = 0; switch (e.GetPalAction()) { case PaletteChangeEvt :: PaletteChanged: // Palette wurde von einem Fenster neu realisiert if (hPalette != NULL && hWnd != e.hPalChgWnd()) { HDC hDC = GetDC (hWnd); HPALETTE hOldPal = SelectPalette (hDC, hPalette, false); i = RealizePalette (hDC); if (i) UpdateColors (hDC); SelectPalette (hDC, hOldPal, false); ReleaseDC (hWnd, hDC); } break; case PaletteChangeEvt :: PaletteIsChanging: break; case PaletteChangeEvt :: QueryNewPalette: if (hPalette) { HDC hDC = GetDC (hWnd); HPALETTE hOldPal = SelectPalette (hDC, hPalette, false); i = RealizePalette (hDC); SelectPalette (hDC, hOldPal, false); ReleaseDC (hWnd, hDC); if (i) InvalidateRect (hWnd, (LPRECT)NULL, true); } break; default: Default ((Event &)e); } } // Member für DragRectangleObject --------------------------------------------- void DragRectangleObject :: InflateRect (int iPixels) { pt.X() -= iPixels; pt.Y() += iPixels; dim.Width() += 2*iPixels; dim.Height() -= 2*iPixels; } // Rechteck ggf. kippen void DragRectangleObject :: CorrectCoOrds (void) { // Dimension ist bei Punkt (1, 1) !! if (dim.Width() < 1) { pt.X() = pt.X() + dim.Width(); dim.Width() = -dim.Width(); } if (dim.Height() > -1) { pt.Y() = pt.Y() + dim.Height(); dim.Height() = -dim.Height(); } } // Rechteck vergrößern/verkleinern -------------------------------------------- Rectangle InflateRect (Rectangle &R, short iDelta) { return Rectangle (R.Top() + iDelta, R.Left() - iDelta, R.Bottom() - iDelta, R.Right() + iDelta); } // Berechnung der ClientFlaeche unter Berücksichtigung der Rollbalken Rectangle IrisWind :: RealCanvasRect (void) { long dwStyle = GetWindowLong (Handle (API_CLIENT_HWND), GWL_STYLE); // FensterStil Rectangle Rc = CanvasRect(); if (dwStyle & WS_HSCROLL) Rc.Bottom() -= GetSystemMetrics (SM_CYHSCROLL); if (dwStyle & WS_VSCROLL) Rc.Right() -= GetSystemMetrics (SM_CXVSCROLL); return Rc; } // Dispatcher für das IrisWind ------------------------------------------------ extern bool g_fCtl3dInit; // CTL3D.DLL richtig initialisiert LRESULT EXPORTTRIAS IrisWind :: Dispatch (Event e) { register UINT uiMsg = ((NakedEvt &)e).wmsg(); switch (uiMsg) { case WM_DROPFILES: // Dragging bearbeiten return DragFunc (((NakedEvt &)e).wparam()); case WM_SYSCOLORCHANGE: if (g_fCtl3dInit) Ctl3dColorChange(); break; case WM_NCLBUTTONDOWN: case WM_NCRBUTTONDOWN: DELETE (g_pSODlg); // SignOn sicher freigeben break; case WM_CANCELMODE: if (m_fHandleCancelMode) GCancelFlag = GCFAbort; // Zeichnen abbrechen break; case WM_DEVMODECHANGE: // Druckereinstellung geändert ? { char *pT = (char *)((NakedEvt &)e).lparam(); } break; } return StrobeWindow :: Dispatch (e); }
71c44eff0076bacee6c3a7e39247a573da5ca496
faf8537eaa86668dba566fa27c4930b5fc5583a1
/Algorithms 1/QuickSort With Comparison Count from file (Course Way)/QuickSort (1st Element Pivot) With Comparison Count from file.cpp
fe011940e8a1761bac7a65db0466276a34bf2aa8
[]
no_license
agnostic-apollo/Coursera-Algorithms-1-and-2
58b48004f1ace54f8b1ced43fae45c0ea6414190
195ac518e9f20e4ba7765237b1b406237f11a4d4
refs/heads/master
2020-03-19T05:23:32.294841
2018-06-04T17:33:37
2018-06-04T17:33:37
135,926,014
4
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
QuickSort (1st Element Pivot) With Comparison Count from file.cpp
#include <iostream> #include<fstream> #include <stdlib.h> using namespace std; int partitioner(int [],int ,int ); void quicksort(int [],int ,int ); long long int comparisons=0; int main() { ifstream input; input.open("QuickSort.txt"); if(input.fail()) { cout<<"Error opening file\n"; exit(1); } int temp,num=0,i=0; while(input>>temp) num++; input.clear(); input.seekg(0); int *arr=new int[num]; while(!input.eof()) { input>>arr[i]; i++; } quicksort(arr,0,num-1); for(i=0;i<num;i++) cout<<arr[i]<<" "; cout<<endl<<"Comparison Count:"<<comparisons<<endl; delete[] arr; } void quicksort(int arr[],int l,int r) { if(l<r) { int p=partitioner(arr,l,r); comparisons+=r-l; quicksort(arr,l,p-1); quicksort(arr,p+1,r); } } int partitioner(int arr[],int l,int r) { int i=l+1,j,pivot=arr[l],temp; for(j=l+1;j<=r;j++) { if(arr[j]<arr[l]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; i++; } } i--; temp=arr[l]; arr[l]=arr[i]; arr[i]=temp; return i; }
8ec6ea366db72b5c08e6cd0249f8a7fdda0239fa
72e44ac6fcf22e124dc9ad755e9d7fab120ab442
/cs160_series/cplusplus/bowling2.cpp
caf76df5f46b28665c32dbae3103ec94ed7ee6d8
[]
no_license
jeffdeng1314/CS16x
2a550ee48d3d750b0fd8c2b349ab6620a4fef6f6
24204e4d87844c957b5c7a027b9c7a788527655d
refs/heads/master
2020-05-15T00:37:17.298336
2019-04-18T04:46:46
2019-04-18T04:46:46
182,014,947
0
0
null
null
null
null
UTF-8
C++
false
false
10,019
cpp
bowling2.cpp
/********************************************************************* * ** Program Filename: Bowling2 * ** Author:Jeff Deng * ** Date:4th March 2017 * ** Description: A program that allows the players to bowl and compete with friends * ** Input: Number of players, the names for the players, and "enter" to bowl * ** Output: The names for players and the score for each bowl. * *********************************************************************/ #include <iostream> #include <cstring> #include <ctime> #include <cstdlib> using std::cin; using std::cout; using std::endl; #define FRAMES 10 #define COLS 21 void deleting_name_mem(int number_players,char **&p); void layout(int i, char **&players,int bowl_score,int n,int k,int **&scores); /********************************************************************* * ** Function:players_amount * ** Description:asking for the number of players * ** Parameters:numbers_players * ** Pre-Conditions:called from main function * ** Post-Conditions:assigning names into the array in the heap * ** Return:n/a * *********************************************************************/ void players_amount(int &numbers_players){ bool input = true; while (input == true){ cout <<"How many players: "; cin >> numbers_players; cin.ignore(256,'\n'); if (cin.fail()||numbers_players < 0){ cout <<"Please enter the valid number of players!"<<endl; cin.clear(); cin.ignore(256,'\n'); } else{ input = false; } } } /********************************************************************* * ** Function:header * ** Description:print out the header for the score board * ** Parameters:n/a * ** Pre-Conditions:n/a * ** Post-Conditions:printing out the score board header * ** Return:n/a * *********************************************************************/ void header(){ cout <<"Name | "; cout <<" 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Total "<<endl; cout <<"-------------------------------------------------------------------------------------------------------------------------------------------------"<<endl; } int frame_total_score(int **scores,int i, int j){ return scores[i][j] + scores[i][j-1]; } int total_initialization(int number_players,int total[],int n){ int i; total[number_players]=total[number_players]; for ( i =0;i < number_players; i++){ total[i] = 0; } return total[i] = n; } /********************************************************************* * ** Function:board * ** Description:printing out the score board on screen * ** Parameters:number_players,scores,frame_array * ** Pre-Conditions:the number of players must exist, along with the scores * ** Post-Conditions:printing out the score board for each player * ** Return:n/a * *********************************************************************/ void board(int number_players, char **players,int **scores,int frame_array[][10]){ header(); int j,i,y,n; int total[number_players]; for(i =0; i < number_players;i++){ n = 0; cout << players[i]<<" | "; for(j=0;j<20;j++){ if (j % 2 == 0){ if (scores[i][j] == 10){ cout <<'x' << " "; continue; } else if (scores[i][j] == 0){ cout <<'-' << " "; } else{ cout <<scores[i][j]<<" "; } } else if (j % 2 == 1){ if (scores[i][j] == 10){ cout <<'x'; } else if (scores[i][j] == 0){ cout <<'-'; } else{ cout << scores[i][j]; } y = frame_total_score(scores,i,j); cout << " = " <<y << " | "; n = n +y; } total[i] = total_initialization(number_players,total,n); } cout <<total[i]; cout <<endl; cout <<"-------------------------------------------------------------------------------------------------------------------------------------------------"<<endl; /* * for(int k =0;k < 10;k++) * cout <<frame_array[i][k]<<" "; * */ cout<<endl; } } /********************************************************************* * ** Function: create_memories * ** Description: creating memories for the player names * ** Parameters: number_players, p * ** Pre-Conditions: called from main * ** Post-Conditions: assigning the names into an array * ** Return:n/a * *********************************************************************/ void create_memories(int number_players,char **&p){ char user_name[21]; p = new char*[number_players]; for (int i = 0; i < number_players; i++){ p[i] = new char[1]; } for (int i = 0; i < number_players; i++){ cout <<"Enter Player " << i + 1 << "'s name: "; cin.getline(user_name,20); strcpy(p[i],user_name); } } /********************************************************************* * ** Function:deleting_name_mem * ** Description:deleting the spaces for the player names in the heap * ** Parameters:number_players,p * ** Pre-Conditions:the array must exist in the heap * ** Post-Conditions: deleting the spaces in the heap after using them * ** Return:n/a * *********************************************************************/ void deleting_name_mem(int number_players,char **&p){/*use it at the end of the program*/ for (int x = 0; x < number_players; x++){ delete [] p[x]; } delete []p; p = NULL; } /********************************************************************* * ** Function:random_number * ** Description:random num generator for gutter, spare, and strike, or just regular bowling * ** Parameters:pins, random_num * ** Pre-Conditions: ctime library for random num * ** Post-Conditions: the random num will be the score for that chance for the user * ** Return:n/a * *********************************************************************/ int random_number(int &pins,int &random_num){/*random gen*/ if (random_num == 0 ){ cout <<"awe, you got a gutter ball, 0 pins" <<endl<<'\n'; return random_num; } else if (random_num == 10){ cout <<"Nice!!! You have landed a strike! 10 pins" <<endl<<'\n'; return random_num; } else{ cout <<"You knocked down " << random_num << " pins." <<endl<<'\n'; return random_num; } return 0; } void clear_array(int **scores,int number_players){ for (int m =0; m < number_players; m++){ delete scores[m]; } delete []scores; scores = NULL; } /********************************************************************* * ** Function: bowling * ** Description: allow the user to hit enter to bowl * ** Parameters:number_players,players * ** Pre-Conditions: called from main function and pre-defined values * ** Post-Conditions:players have their scores added to their frames * ** Return:N/A * *********************************************************************/ int bowling(int number_players, char **players){/*enter to bowl*/ int y,k,i; int **scores = new int*[number_players]; for (int m = 0; m < number_players; m++){ scores[m] = new int[20]; for(int j =0; j < 20; j++){ scores[m][j] = '\0'; } } for (k = 0; k < (FRAMES); k++){ for (i =0; i < number_players; i++){ int n = 2, pins = 10,frame_array[number_players][10],frame_score = 0; y = 0; while (n != 0){ cout <<"\nPlayer " << i + 1 << ", press enter to bowl."; cin.get(); int random_num = rand()%(11-y); y = random_number(pins,random_num); for(int m =0;m < 10;m++) frame_array[i][m] = 0; frame_array[i][k] = frame_score; if (y == 10){ layout(i,players,y,n,k,scores); board(number_players,players,scores,frame_array); break; } layout(i,players,y,n,k,scores); board(number_players,players,scores,frame_array); frame_score = frame_score + y; n--; } } } clear_array(scores,number_players); return 0; } /********************************************************************* * ** Function: layout * ** Description: each bowl has its own score placement, 2 scores per frame * ** Parameters: i, player, bowl_score,n,k,scores * ** Pre-Conditions:it has to be called from a function that declared n as 2 * ** Post-Conditions: adding scores to the scoring arrays * ** Return:none * *********************************************************************/ void layout(int i, char **&players,int bowl_score,int n,int k,int **&scores){ if (n == 2){ (scores)[i][k*2] = bowl_score; } if (n == 1){ (scores)[i][(k*2)+1] = bowl_score; } } /********************************************************************* * ** Function: main * ** Description: the main function * ** Parameters: n/a * ** Pre-Conditions:n/a * ** Post-Conditions:n/a * ** Return:n/a * *********************************************************************/ int main(){ srand ((unsigned int)time(NULL)); int number_players = 0; char **players; players_amount(number_players); create_memories(number_players,players); bowling(number_players,players); deleting_name_mem(number_players, players); return 0; }
9f1ed27bfcacac7341b5f8f84430dab0c5bd648f
ea8aa77c861afdbf2c9b3268ba1ae3f9bfd152fe
/cf758B.cpp
1b70ff063c491e61a1445e4b1dba371e6b8b422f
[]
no_license
lonelam/SolveSet
987a01e72d92f975703f715e6a7588d097f7f2e5
66a9a984d7270ff03b9c2dfa229d99b922907d57
refs/heads/master
2021-04-03T02:02:03.108669
2018-07-21T14:25:53
2018-07-21T14:25:53
62,948,874
9
3
null
null
null
null
UTF-8
C++
false
false
597
cpp
cf758B.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; const int inf = 0x3f3f3f3f; const int maxn = 100000; int main() { map<int, int> cnt; map<char, int> cl; string line; while(cin >> line) { for (int i = 0; i < line.length(); i++) { if (line[i] == '!') { cnt[i % 4]++; } else { cl[line[i]] = i % 4; } } cout << cnt[cl['R']] <<" "<< cnt[cl['B']] <<" "<< cnt[cl['Y']] <<" "<<cnt[cl['G']] <<endl; } }
a0d4a8d3401a084510932e4e27f789e2f652082e
2e66fc50589d666a0cd8b2938bf74178813dbdf9
/testC++++/110_平衡二叉树.cpp
2489645e2db52b570488c29efee04f2bbad21077
[]
no_license
kevinMkY/CPP_ALGO
dfae7e15d9ce75245b90ca1e6fe1e00ca13bee13
9bddfc60a9698e261aced5a4d6e4f90b3cc78865
refs/heads/master
2023-03-15T23:06:44.238375
2021-03-07T18:41:01
2021-03-07T18:41:01
294,155,521
1
0
null
null
null
null
UTF-8
C++
false
false
2,220
cpp
110_平衡二叉树.cpp
// // 110_平衡二叉树.cpp // testC++++ // // Created by yekaihua on 2020/12/26. // #import "110_平衡二叉树.hpp" #import "common.h" //给定一个二叉树,判断它是否是高度平衡的二叉树。 // //本题中,一棵高度平衡二叉树定义为: // //一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。 // // // //示例 1: // // //输入:root = [3,9,20,null,null,15,7] //输出:true //示例 2: // // //输入:root = [1,2,2,3,3,null,null,4,4] //输出:false //示例 3: // //输入:root = [] //输出:true // // //提示: // //树中的节点数在范围 [0, 5000] 内 //-104 <= Node.val <= 104 //通过次数159,913提交次数290,743 // //来源:力扣(LeetCode) //链接:https://leetcode-cn.com/problems/balanced-binary-tree //著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 //递归---自上向下,height重复调用太多 int highlength(TreeNode *root){ int h = 0; if (!root) { return h; } int lefthigh = highlength(root->left); int rightigh = highlength(root->right); return max(lefthigh, rightigh) + 1; } bool isBalanced1(TreeNode* root) { if (!root) { return true; } int leftres = highlength(root->left); int rightres = highlength(root->right); auto banlanceleft = isBalanced1(root->left); auto banlanceright = isBalanced1(root->right); auto res = abs(leftres-rightres) <=1; return res && banlanceleft && banlanceright; } int highlength2(TreeNode *root){ if (!root) { return 0; } auto leftres = highlength2(root->left); auto rightres = highlength2(root->right); if (leftres == -1 || rightres == -1 || abs(leftres - rightres) > 1) { return -1; }else{ return max(leftres, rightres)+1; } } //迭代---自下向上,减少height重复调用 bool isBalanced2(TreeNode* root) { return highlength2(root) >=0; } void _110_test() { vector<int> list1 = {1,2,2,3,NULL,NULL,3,4,NULL,NULL,4}; TreeNode *node1 = initTreeWithNULLVector(list1); bool res1 = isBalanced1(node1); bool res2 = isBalanced2(node1); }
da40f50aa8a578fcb07e13242ee6199e9725740b
1fc8763ffed1079b656f76a5e5a90decb87df110
/server/capturer/capturer.h
f6b42d8125416924682bac43acd7211d7c443c3f
[]
no_license
KunTjz/netpop
9f96b5c771762acb869f452b713491d2cc942b38
bc304a632c7c4a6817f5e4167bcb06818044be42
refs/heads/master
2021-05-27T16:38:50.949771
2013-11-07T13:34:09
2013-11-07T13:34:09
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
487
h
capturer.h
#ifndef __CAPTURE_H__ #define __CAPTURE_H__ #include "filter/filter.h" #include "../util/utilFunc.h" #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netinet/if_ether.h> typedef void (*callBack)(u_char *useless,const struct pcap_pkthdr* pkthdr,const u_char* packet); class capturer { public: capturer (const char* dev); void capturePackage (filter* fr, callBack func, int delay); private: std::string _dev; // Íø¿¨É豸Ãû³Æ }; #endif
adbdb674901814ea21baf0551557cc8d4bed8f85
92754bb891a128687f3fbc48a312aded752b6bcd
/Algorithms/C++/509-Fibonacci_Number.cpp
e1da9ecddaff56c16728058f63457986ff9547ee
[]
no_license
daidai21/Leetcode
ddecaf0ffbc66604a464c3c9751f35f3abe5e7e5
eb726b3411ed11e2bd00fee02dc41b77f35f2632
refs/heads/master
2023-03-24T21:13:31.128127
2023-03-08T16:11:43
2023-03-08T16:11:43
167,968,602
8
3
null
null
null
null
UTF-8
C++
false
false
292
cpp
509-Fibonacci_Number.cpp
// Runtime: 16 ms, faster than 15.35% of C++ online submissions for Fibonacci Number. // Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Fibonacci Number. class Solution { public: int fib(int N) { return N < 2 ? N : fib(N - 1) + fib(N - 2); } };
bdb8b41a734432479b57545c89227ace5aad4ce7
ca32d531ff2596425ce5218a8e2b732a6744faa0
/asterisk-cpp/asteriskcpp/manager/actions/QueueRemoveAction.h
dbf9e0d8b3a12046c16e74926e7476a2968773a9
[ "Apache-2.0" ]
permissive
augcampos/asterisk-cpp
a8a115a164194db6e9712c676111af164a8526fb
921423e0d1b6042d0ce2be6d7b9d98af4feb7460
refs/heads/master
2022-07-06T00:37:41.907214
2022-07-01T03:51:25
2022-07-01T03:51:25
2,310,863
22
15
null
2017-09-26T00:10:45
2011-09-01T23:05:30
C++
UTF-8
C++
false
false
1,754
h
QueueRemoveAction.h
/* * QueueRemoveAction.h * * Created on: Jun 27, 2013 * Author: augcampos */ #ifndef QUEUEREMOVEACTION_H_ #define QUEUEREMOVEACTION_H_ #include "AbstractManagerAction.h" namespace asteriskcpp { /** * The QueueRemoveAction removes a member from a queue.<p> * It is implemented in <code>apps/app_queue.c</code> * * @author augcampos * @version $Id$ */ class QueueRemoveAction : public AbstractManagerAction { public: /** * Creates a new empty QueueRemoveAction. */ QueueRemoveAction(); /** * Creates a new QueueRemoveAction that removes the member on the given * interface from the given queue. * * @param queue the name of the queue the member will be removed from * @param iface the interface of the member to remove * @since 0.2 */ QueueRemoveAction(const std::string& queue,const std::string& iface); virtual ~QueueRemoveAction(); /** * Returns the name of the queue the member will be removed from. * * @return the name of the queue the member will be removed from. */ const std::string& getQueue() const; /** * Sets the name of the queue the member will be removed from.<p> * This property is mandatory. * * @param queue the name of the queue the member will be removed from. */ void setQueue(const std::string& queue); /** * Returns the interface to remove. */ const std::string& getInterface() const; void setInterface(const std::string& iface); }; } //NAMESPACE #endif /*QUEUEREMOVEACTION_H_*/
e1edeb3b1983327520ad364020275ffda7478719
b3c47795e8b6d95ae5521dcbbb920ab71851a92f
/Codeforces/Codeforces Beta Round #86 (Div. 2)/e.cc
b18c1b2f4954846d4909b287c1f0c421da65a09c
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Wizmann/ACM-ICPC
6afecd0fd09918c53a2a84c4d22c244de0065710
7c30454c49485a794dcc4d1c09daf2f755f9ecc1
refs/heads/master
2023-07-15T02:46:21.372860
2023-07-09T15:30:27
2023-07-09T15:30:27
3,009,276
51
23
null
null
null
null
UTF-8
C++
false
false
487
cc
e.cc
#include <cstdio> #include <cstdlib> #include <cstring> #include <bitset> #include <algorithm> #include <iostream> const int SIZE=300000005; using namespace std; bitset<SIZE> prim; int main() { //freopen("e.txt","r",stdin); int l,r; scanf("%d%d",&l,&r); prim.set(); for(int i=3;i*i<=r;i+=2) { if(prim[i]) for(int j=i*i;j<=r;j+=(i<<1)) prim[j]=0; } int ans=0; if(l<=2&&r>=2) ans++; for(int i=5;i<=r;i+=4) { if(i>=l&&prim[i]) ans++; } printf("%d\n",ans); return 0; }
32dd6754540d74532e359001d891a019ec71af31
d4a72aff278e752ef04ce4a24f774d9d91128b6a
/PricingLib2/RandomNumber.h
6dc179c872d711eb335f9c880bae145681ab370c
[]
no_license
shiraishitaka/pricinglibrary
0a0939afa2b2b0f283f42d9c1619ec0c6e71c844
b4b2e5389132d9a774681ad80918b428beefde35
refs/heads/master
2021-05-17T10:40:56.666338
2020-04-14T07:53:30
2020-04-14T07:53:30
250,741,493
0
0
null
null
null
null
UTF-8
C++
false
false
287
h
RandomNumber.h
#pragma once #include "LibObject.h" namespace Lib { namespace Random { struct RandomParameter { int separate_per_year; int years; int iteration_num; double dt; }; std::vector<std::vector<double>> createPath(std::shared_ptr<RandomParameter> random_parameter); } }
15aff4eef83e42b223da0120d83194fcab719742
11dcefc3768cc67f6563f7e0e4713bae740cad63
/hyeyoo/3주차_DP_2/가장_긴_바이토닉_부분수열.cpp
546a259005d056253690f70d0195041ce4dd6fc2
[]
no_license
42somoim/42somoim1
dac54edee33aadf1a17f60768446e5faf07ed952
039e00085290d048a7345bcec7db797e4c7330d2
refs/heads/master
2023-05-06T13:07:01.242428
2021-05-28T12:07:45
2021-05-28T12:07:45
280,406,020
2
3
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
가장_긴_바이토닉_부분수열.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* 가장_긴_바이토닉_부분수열.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hyeyoo <hyeyoo@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/13 04:21:06 by hyeyoo #+# #+# */ /* Updated: 2020/08/13 04:28:53 by hyeyoo ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> using namespace std; int main(void) { int n; int *arr; int *lis_front; int *lis_back; cin >> n; arr = new int[n]; lis_front = new int[n]; lis_back = new int[n]; for(int i = 0; i < n; i++) cin >> arr[i]; for(int i = 0; i < n; i++) { lis_front[i] = 1; for(int j = 0; j < i; j++) { if (arr[j] < arr[i]) { lis_front[i] = max(lis_front[i], lis_front[j] + 1); } } } for(int i = n - 1; i >= 0; i--) { lis_back[i] = 1; for(int j = n - 1; j > i; j--) { if (arr[j] < arr[i]) { lis_back[i] = max(lis_back[i], lis_back[j] + 1); } } } int ans = 0; for(int i = 0; i < n; i++) { ans = max(ans, lis_back[i] + lis_front[i] - 1); } cout << ans << endl; }
8c787ea3529a07a0d36c23fa947da02c9fd1e230
a93d6cc34f2f205a82292443c56e4b408a9b2b2d
/test_vk/vk/vk_framebuffer.h
ea128b8d8fa6467a42d32413a69c044f12a23d1f
[]
no_license
teealal/test_vk2
d2e425dcf46a58641fd3ddf97894a42773bc9d51
712fdd5e7f9acd65374a781f73388c096209eaf0
refs/heads/master
2021-01-10T02:58:34.002587
2016-03-10T07:45:05
2016-03-10T07:45:05
53,284,290
0
0
null
null
null
null
UTF-8
C++
false
false
314
h
vk_framebuffer.h
#pragma once namespace vk { class Framebuffer { public: Framebuffer(); virtual ~Framebuffer(); VkResult create( uint32_t width, uint32_t height, VkRenderPass renderPass, uint32_t attachmentCount, const VkImageView* pAttachments); void destroy(); VkFramebuffer m_framebuffer; }; }
be64cd9ebd26c7fa10e2b970b95595a21fdf37be
e57b6a64143b43e1c13cd86a8c4c3ee02726cad1
/Tetrominoes/zblock.h
3d7739be93ddb116986181c2d12bf2270f12e2b8
[]
no_license
s1seo/Quadris
8fac4ab4d802653e2233623ae39254c1bcc4a631
ea6c83030e25bef786e53240411e8b0025aef2ca
refs/heads/master
2023-04-08T07:08:41.485884
2018-05-22T01:27:28
2018-05-22T01:27:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
347
h
zblock.h
#ifndef ZBLOCK_H #define ZBLOCK_H #include "tetromino.h" class ZBlock final: public Tetromino { ZBlock(const ZBlock *t); public: ZBlock(int level); ZBlock *left() const override; ZBlock *right() const override; ZBlock *down() const override; ZBlock *clockwise() const override; ZBlock *counterclockwise() const override; }; #endif
c98885d2ba4176eb0d7818231b39e0cacd69cd5a
04dc7cc05f9b33585228e649706dcb2fc1eb797b
/SPELLBOOK/src/hld.cpp
ec6c52feea3e32d511885ff414a51314883cb6a9
[ "Apache-2.0" ]
permissive
henviso/contests
4fc34cc86a42a3ff15e23e457a21bba10913f419
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
refs/heads/master
2016-09-14T19:14:29.266088
2016-05-12T00:02:59
2016-05-12T00:02:59
58,590,566
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
hld.cpp
#define MAX_NODES 30100 #define LOG2_MAX_NODES 15 int chainNo=0,chainHead[MAX_NODES],chainPos[MAX_NODES],chainInd[MAX_NODES],chainSize[MAX_NODES],chainAc[MAX_NODES]; int subsize[MAX_NODES]; int p[MAX_NODES], l[MAX_NODES]; int ac[MAX_NODES][LOG2_MAX_NODES]; void hld(int cur) { if(chainHead[chainNo] == -1){ chainHead[chainNo] = cur; chainAc[chainNo] = (chainNo == 0)? 0 : chainAc[chainNo-1] + chainSize[chainNo-1]; } chainInd[cur] = chainNo; chainPos[cur] = chainSize[chainNo]; ft_adjust(ft, chainAc[chainNo] + chainPos[cur]+1, P[cur]); chainSize[chainNo]++; int ind = -1, mai = -1; for(int i = 0; i < g[cur].size(); i++) { if(g[cur][i] != p[cur] && subsize[g[cur][i]] > mai) { mai = subsize[ g[cur][i] ]; ind = i; } } if(ind >= 0) hld( g[cur][ind] ); for(int i = 0; i < g[cur].size(); i++) { if(g[cur][i] != p[cur] && i != ind) { chainNo++; hld( g[cur][i] ); } } } int dfs(int v, int P, int L){ if(p[v]) return 0; p[v] = P; l[v] = L; subsize[v] = 1; REP(i, g[v].size()){ subsize[v] += dfs(g[v][i], v, L+1); } return subsize[v]; } void precalc(){ CLEAR0(ac); REPP(i, 1, n+1) ac[i][0] = p[i]; REPP(j, 1, 15) REPP(i, 1, n+1) if(ac[i][j-1]) ac[i][j] = ac[ac[i][j-1]][j-1]; } int lca(int u, int v){ int tmp, log, i; if(l[u] < l[v]) swap(u, v); for (log = 1; 1 << log <= l[u]; log++); log--; for (i = log; i >= 0; i--) if (l[u] - (1 << i) >= l[v]) u = ac[u][i]; if (u == v) return u; for (i = log; i >= 0; i--) if (ac[u][i] && ac[u][i] != ac[v][i]) u = ac[u][i], v = ac[v][i]; return p[u]; }
3a2e3afa39f0ad006e28bb3f081aec5a7ced743b
a46d51fddcdfe642f92e39f0404c2d983a0c2e08
/src/dao/mysql_dao_support.cc
3668b1b0b026ea6a06dba140d7e5c2536ee43372
[]
no_license
binsu8/CalculatedAd
6b766806e671c89b2645d1c6da340a7d03fe0af5
9554eb5be0b9d35d0337c8c8ecb03ca5d81234fd
refs/heads/master
2021-01-01T20:10:36.242335
2014-03-26T10:47:47
2014-03-26T10:47:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,543
cc
mysql_dao_support.cc
#include "utils/logger.h" #include "utils/time_util.h" #include "utils/configure.h" #include "utils/string_util.h" #include "utils/textconfig.h" #include "mysql_dao_support.h" #include <vector> #include <string> using std::vector; static CLogger & g_logger_mysql = CLogger::GetIntance("mysql"); int32_t MysqlProxy::Init() { return 0; } int32_t MysqlProxy::Uninit() { map<string, CMysqlConnPool*>::iterator it; for (it = pools_.begin(); it !=pools_.end(); it++) { if (NULL != it->second) { delete it->second; it->second = NULL; } } return 0; } int32_t MysqlProxy::AddNode (const SMysqlConf& node_desc, uint32_t conn_cnt) { if (NULL == pools_[node_desc.m_table]) { LOGGER_ERROR(g_logger_mysql, "err=no mysql server, key=%s", key.c_str()); return NULL; } return pool->GetConn(100); } void MysqlProxy::FreeConnByKey(const string& key, IMysqlConn* conn) { if (NULL == pools_[node_desc.m_table]) { LOGGER_ERROR(g_logger_mysql, "err=no mysql server, key=%s", key.c_str()); return; } CMysqlConnPool* pool = pools_[key]; if (NULL == pools_[node_desc.m_table]) { LOGGER_ERROR(g_logger_mysql, "err=no mysql server, key=%s", key.c_str()); delete conn; return; } pool->FreeConn(conn); } int32_t MysqlProxy::Query(const shared_ptr<MysqlProxyReq& req, IMysqlQueryRespParser* resp_parser) { if (NULL == req || NULL == resp_parser) { LOGGER_ERROR(g_logger_mysql, "err=null params"); return -1; } IMysqlConn* conn = this->GetConnByKey(req->type_); if (NULL == conn) { LOGGER_ERROR(g_logger_mysql, "err=get null mysql connection, db=%s", req->db_name_.c_str()); return -1; } uint64_t start_query = TimeUtil::GetTickUs(); MYSQL_RES* mysql_result = NULL; int32_t ret = conn->RealQuery(req->sql_.c_str(), static_cast<uint32_t>(req->sql_size()), &mysql_result); if (0 != ret) { LOGGER_ERROR(g_logger_mysql, "err=error in the process of query or no results found"); if (NULL != mysql_result) { mysql_free_result(mysql_result); mysql_result = NULL; } this->FreeConnByKey(req->type_,conn); reutrn ret; } uint64_t start_parse = TimeUtil::GetTickUs(); int32_t ret_parse = resp_parser->Parse(mysql_result); mysql_free_result(mysql_result); this->FreeConnBykey(req->type_, conn); return ret_parse; } MYSQL_RES* MysqlProxy::QueryWithoutParser(const shared_ptr<MysqlProxyReq>& req) { if (NULL == req) { LOGGER_ERROR(g_logger_mysql, "err=null params"); return NULL; } IMysqlConn* conn = this->GetConnByKey(req->type_); if (NULL == conn) { LOGGER_ERROR(g_logger_mysql, "err=get null mysql connection"); return NULL; } MYSQL_RES* mysql_result = NULL; int32_t ret = conn->RealQuery(req->sql_.c_str(), static_cast<uint32_t>(req->sql_size()), &mysql_result); if (0 != ret) { LOGGER_ERROR(g_logger_mysql, "err=error in the process of query or no results found"); if (NULL != mysql_result) { mysql_free_result(mysql_result); mysql_result = NULL; } this->FreeConnByKey(req->type_,conn); reutrn NULL; } this->FreeConnBykey(req->type_, conn); return mysql_result; } int32_t MysqlProxy::AddToTablePool(const string& db_name) { return 0; } int32_t MysqlProxy::LoadOneTable(IMysqlConn* conn, const string& table_name, const string& db_name) { return 0; } int32_t MysqlProxy::InitColumnFromRes(MYSQL_RES* res, vector<ColumnInfo>& columns, string& order_by) { return 0; }
f52c8fd27a7a536b94864cfb66a08261bb52eacc
8688f265e46102c30f01f094d20dc767df1af182
/header/friedrichdb/old/abstract_database.hpp
b527785a82ebbfb7e25523cbef2dfcbcaabb0021
[ "BSD-3-Clause" ]
permissive
cyberduckninja/friedrichdb
2398a4c82222be9fdf7cb975c63a538909c3e9ec
313180fee8f230b2a406000b948210c77c4253a3
refs/heads/master
2023-05-25T03:15:41.236942
2020-03-09T11:25:03
2020-03-09T11:25:03
94,206,993
0
0
null
null
null
null
UTF-8
C++
false
false
622
hpp
abstract_database.hpp
#pragma once #include <unordered_map> #include <cstdint> #include <condition_variable> #include <mutex> #include <friedrichdb/query.hpp> namespace friedrichdb { enum class storage_type : uint8_t { memory = 0x00, disk }; struct abstract_database { abstract_database(storage_type); virtual ~abstract_database() = default; virtual auto apply(query&&) -> output_query = 0; storage_type type() const; protected: std::mutex mutex; std::condition_variable condition_variable; private: storage_type type_; }; }
cbf93d629a609dbefee1c075e8a27ed9efe02c2b
3845c459700053560244d0062c8eb65e3013b59e
/main.cpp
fcc159d8502b9487eb2ea700f177b0cc1c5d0cac
[]
no_license
rudnevr/gcpp
195e543ae78ddabec9bd1c2903fc90ce07a128b4
52a8ec556972b2a6762c845ece6dd68dd7fcc685
refs/heads/master
2022-03-12T04:11:42.327242
2017-12-03T04:09:58
2017-12-03T04:09:58
112,105,008
0
0
null
null
null
null
UTF-8
C++
false
false
4,007
cpp
main.cpp
#include <iostream> #include "Customer.h" #include "PState.h" #include <windows.h> #include <string> #include <iostream> #include <regex> #include <list> using namespace std; extern "C" { #include "foo.h" //a C header, so wrap it in extern "C" } HWND current; HHOOK KeyboardHook; BOOL shift = FALSE; BOOL ctrl = FALSE; BOOL alt = FALSE; BOOL tab = FALSE; BOOL caps = FALSE; string mapCodeToText(int code) { if (code == VK_F12) { return "IntelliJ"; } if (code == VK_F1) { return "Firefox"; } if (code == VK_F3) { return "Chrome"; } if (code == VK_F4) { return "cmd"; } if (code == VK_F7) { return "MINGW"; } if (code == VK_F6) { return "Sky"; } if (code == VK_F5) { return "PyCharm"; } printf("ret null"); return string(""); } BOOL CALLBACK enumWindowsProc( HWND hWnd, LPARAM lParam ) { int length = ::GetWindowTextLength(hWnd); if (0 == length) return TRUE; regex *regex1 = reinterpret_cast<std::regex *>(lParam); char cWindow[length]; GetWindowTextA(hWnd, cWindow, length); // printf("lparam %s\r\n", regex1); // printf("cWindows %s\r\n", cWindow); const string sout = string(cWindow); if (std::regex_match(sout, *regex1)) { cout << sout << std::endl; if (hWnd != current) { cout << "match!" << std::endl; current = hWnd; return FALSE; } return TRUE; } return TRUE; } void press(int code, BOOL up) { INPUT input; WORD vkey = code; input.type = INPUT_KEYBOARD; input.ki.wScan = 0; input.ki.time = 0; input.ki.dwExtraInfo = 0; input.ki.wVk = vkey; input.ki.dwFlags = 0; SendInput(1, &input, sizeof(INPUT)); if (up) input.ki.dwFlags = KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); } void pressCtrlCode(int code) { press(VK_LCONTROL, FALSE); press(code, TRUE); press(VK_LCONTROL, TRUE); } LRESULT CALLBACK HookProcedure2(int nCode, WPARAM wParam, LPARAM lParam) { KBDLLHOOKSTRUCT *p = (KBDLLHOOKSTRUCT *) lParam; if (nCode == HC_ACTION) { printf("code %lu\n", p->vkCode); string te = mapCodeToText(p->vkCode); if (!te.empty() && GetAsyncKeyState(VK_LSHIFT)) { press(VK_LSHIFT, TRUE); printf("%s mapped to %lu\n", te, p->vkCode); std::regex txt_regex(te); EnumWindows(enumWindowsProc, reinterpret_cast<LPARAM >(&txt_regex)); return -1; } else { if (p->vkCode == VK_F11) { press(VK_LSHIFT, TRUE); press(VK_LWIN, TRUE); return -1; } if (p->vkCode == VK_F8) { press(VK_LSHIFT, TRUE); press(VK_LMENU, FALSE); press(VK_TAB, TRUE); pressCtrlCode('T'); return -1; } if (p->vkCode == VK_F2) { press(VK_LSHIFT, TRUE); UnhookWindowsHookEx(KeyboardHook); return -1; } } } return CallNextHookEx(NULL, nCode, wParam, lParam); } Keys keys = NULL; PState pState = NULL; void createState() { keys = Keys(GetAsyncKeyState(VK_CAPITAL), GetAsyncKeyState(VK_SHIFT), GetAsyncKeyState(VK_MENU), GetAsyncKeyState(VK_SHIFT), GetAsyncKeyState(VK_CONTROL), GetAsyncKeyState(VK_LWIN)); } int main() { cout << "startt" << endl; current = GetForegroundWindow(); KeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL, HookProcedure2, GetModuleHandle(NULL), 0 ); MSG Msg; while (GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); printf("in mess\n"); DispatchMessage(&Msg); } printf("unhook\n"); UnhookWindowsHookEx(KeyboardHook); // EnumWindows(enumWindowsProc, reinterpret_cast<LPARAM >(&txt_regex)); // EnumWindows(enumWindowsProc, reinterpret_cast<LPARAM >(&txt_regex)); return 0; }
0b54f92c51de0cc09420aa34be8173c4de278245
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/chrome/common/search.mojom-params-data.h
4fecad0a73758e1898c9522238b31c3abda38bec
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
90,905
h
search.mojom-params-data.h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_COMMON_SEARCH_MOJOM_PARAMS_DATA_H_ #define CHROME_COMMON_SEARCH_MOJOM_PARAMS_DATA_H_ #include "base/logging.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/buffer.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif namespace chrome { namespace mojom { namespace internal { class EmbeddedSearchConnector_Connect_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearchConnector_Connect_Params_Data)); new (data()) EmbeddedSearchConnector_Connect_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearchConnector_Connect_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearchConnector_Connect_Params_Data>(index_); } EmbeddedSearchConnector_Connect_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::AssociatedEndpointHandle_Data embedded_search; mojo::internal::AssociatedInterface_Data client; uint8_t padfinal_[4]; private: EmbeddedSearchConnector_Connect_Params_Data(); ~EmbeddedSearchConnector_Connect_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearchConnector_Connect_Params_Data) == 24, "Bad sizeof(EmbeddedSearchConnector_Connect_Params_Data)"); class EmbeddedSearch_FocusOmnibox_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_FocusOmnibox_Params_Data)); new (data()) EmbeddedSearch_FocusOmnibox_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_FocusOmnibox_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_FocusOmnibox_Params_Data>(index_); } EmbeddedSearch_FocusOmnibox_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t focus : 1; uint8_t padfinal_[3]; private: EmbeddedSearch_FocusOmnibox_Params_Data(); ~EmbeddedSearch_FocusOmnibox_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_FocusOmnibox_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_FocusOmnibox_Params_Data)"); class EmbeddedSearch_DeleteMostVisitedItem_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_DeleteMostVisitedItem_Params_Data)); new (data()) EmbeddedSearch_DeleteMostVisitedItem_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_DeleteMostVisitedItem_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_DeleteMostVisitedItem_Params_Data>(index_); } EmbeddedSearch_DeleteMostVisitedItem_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<::url::mojom::internal::Url_Data> url; private: EmbeddedSearch_DeleteMostVisitedItem_Params_Data(); ~EmbeddedSearch_DeleteMostVisitedItem_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_DeleteMostVisitedItem_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_DeleteMostVisitedItem_Params_Data)"); class EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data)); new (data()) EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data>(index_); } EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t padfinal_[4]; private: EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data(); ~EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data)"); class EmbeddedSearch_UndoMostVisitedDeletion_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_UndoMostVisitedDeletion_Params_Data)); new (data()) EmbeddedSearch_UndoMostVisitedDeletion_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_UndoMostVisitedDeletion_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_UndoMostVisitedDeletion_Params_Data>(index_); } EmbeddedSearch_UndoMostVisitedDeletion_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<::url::mojom::internal::Url_Data> url; private: EmbeddedSearch_UndoMostVisitedDeletion_Params_Data(); ~EmbeddedSearch_UndoMostVisitedDeletion_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_UndoMostVisitedDeletion_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_UndoMostVisitedDeletion_Params_Data)"); class EmbeddedSearch_AddCustomLink_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_AddCustomLink_Params_Data)); new (data()) EmbeddedSearch_AddCustomLink_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_AddCustomLink_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_AddCustomLink_Params_Data>(index_); } EmbeddedSearch_AddCustomLink_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<::url::mojom::internal::Url_Data> url; mojo::internal::Pointer<mojo::internal::String_Data> title; private: EmbeddedSearch_AddCustomLink_Params_Data(); ~EmbeddedSearch_AddCustomLink_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_AddCustomLink_Params_Data) == 32, "Bad sizeof(EmbeddedSearch_AddCustomLink_Params_Data)"); class EmbeddedSearch_AddCustomLink_ResponseParams_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_AddCustomLink_ResponseParams_Data)); new (data()) EmbeddedSearch_AddCustomLink_ResponseParams_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_AddCustomLink_ResponseParams_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_AddCustomLink_ResponseParams_Data>(index_); } EmbeddedSearch_AddCustomLink_ResponseParams_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t success : 1; uint8_t padfinal_[7]; private: EmbeddedSearch_AddCustomLink_ResponseParams_Data(); ~EmbeddedSearch_AddCustomLink_ResponseParams_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_AddCustomLink_ResponseParams_Data) == 16, "Bad sizeof(EmbeddedSearch_AddCustomLink_ResponseParams_Data)"); class EmbeddedSearch_UpdateCustomLink_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_UpdateCustomLink_Params_Data)); new (data()) EmbeddedSearch_UpdateCustomLink_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_UpdateCustomLink_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_UpdateCustomLink_Params_Data>(index_); } EmbeddedSearch_UpdateCustomLink_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<::url::mojom::internal::Url_Data> url; mojo::internal::Pointer<::url::mojom::internal::Url_Data> new_url; mojo::internal::Pointer<mojo::internal::String_Data> new_title; private: EmbeddedSearch_UpdateCustomLink_Params_Data(); ~EmbeddedSearch_UpdateCustomLink_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_UpdateCustomLink_Params_Data) == 40, "Bad sizeof(EmbeddedSearch_UpdateCustomLink_Params_Data)"); class EmbeddedSearch_UpdateCustomLink_ResponseParams_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_UpdateCustomLink_ResponseParams_Data)); new (data()) EmbeddedSearch_UpdateCustomLink_ResponseParams_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_UpdateCustomLink_ResponseParams_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_UpdateCustomLink_ResponseParams_Data>(index_); } EmbeddedSearch_UpdateCustomLink_ResponseParams_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t success : 1; uint8_t padfinal_[7]; private: EmbeddedSearch_UpdateCustomLink_ResponseParams_Data(); ~EmbeddedSearch_UpdateCustomLink_ResponseParams_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_UpdateCustomLink_ResponseParams_Data) == 16, "Bad sizeof(EmbeddedSearch_UpdateCustomLink_ResponseParams_Data)"); class EmbeddedSearch_ReorderCustomLink_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ReorderCustomLink_Params_Data)); new (data()) EmbeddedSearch_ReorderCustomLink_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ReorderCustomLink_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ReorderCustomLink_Params_Data>(index_); } EmbeddedSearch_ReorderCustomLink_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; int32_t new_pos; mojo::internal::Pointer<::url::mojom::internal::Url_Data> url; private: EmbeddedSearch_ReorderCustomLink_Params_Data(); ~EmbeddedSearch_ReorderCustomLink_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ReorderCustomLink_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_ReorderCustomLink_Params_Data)"); class EmbeddedSearch_DeleteCustomLink_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_DeleteCustomLink_Params_Data)); new (data()) EmbeddedSearch_DeleteCustomLink_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_DeleteCustomLink_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_DeleteCustomLink_Params_Data>(index_); } EmbeddedSearch_DeleteCustomLink_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<::url::mojom::internal::Url_Data> url; private: EmbeddedSearch_DeleteCustomLink_Params_Data(); ~EmbeddedSearch_DeleteCustomLink_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_DeleteCustomLink_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_DeleteCustomLink_Params_Data)"); class EmbeddedSearch_DeleteCustomLink_ResponseParams_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_DeleteCustomLink_ResponseParams_Data)); new (data()) EmbeddedSearch_DeleteCustomLink_ResponseParams_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_DeleteCustomLink_ResponseParams_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_DeleteCustomLink_ResponseParams_Data>(index_); } EmbeddedSearch_DeleteCustomLink_ResponseParams_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t success : 1; uint8_t padfinal_[7]; private: EmbeddedSearch_DeleteCustomLink_ResponseParams_Data(); ~EmbeddedSearch_DeleteCustomLink_ResponseParams_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_DeleteCustomLink_ResponseParams_Data) == 16, "Bad sizeof(EmbeddedSearch_DeleteCustomLink_ResponseParams_Data)"); class EmbeddedSearch_UndoCustomLinkAction_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_UndoCustomLinkAction_Params_Data)); new (data()) EmbeddedSearch_UndoCustomLinkAction_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_UndoCustomLinkAction_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_UndoCustomLinkAction_Params_Data>(index_); } EmbeddedSearch_UndoCustomLinkAction_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t padfinal_[4]; private: EmbeddedSearch_UndoCustomLinkAction_Params_Data(); ~EmbeddedSearch_UndoCustomLinkAction_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_UndoCustomLinkAction_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_UndoCustomLinkAction_Params_Data)"); class EmbeddedSearch_ResetCustomLinks_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ResetCustomLinks_Params_Data)); new (data()) EmbeddedSearch_ResetCustomLinks_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ResetCustomLinks_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ResetCustomLinks_Params_Data>(index_); } EmbeddedSearch_ResetCustomLinks_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t padfinal_[4]; private: EmbeddedSearch_ResetCustomLinks_Params_Data(); ~EmbeddedSearch_ResetCustomLinks_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ResetCustomLinks_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_ResetCustomLinks_Params_Data)"); class EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data)); new (data()) EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data>(index_); } EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t padfinal_[4]; private: EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data(); ~EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data)"); class EmbeddedSearch_ToggleShortcutsVisibility_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ToggleShortcutsVisibility_Params_Data)); new (data()) EmbeddedSearch_ToggleShortcutsVisibility_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ToggleShortcutsVisibility_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ToggleShortcutsVisibility_Params_Data>(index_); } EmbeddedSearch_ToggleShortcutsVisibility_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t padfinal_[4]; private: EmbeddedSearch_ToggleShortcutsVisibility_Params_Data(); ~EmbeddedSearch_ToggleShortcutsVisibility_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ToggleShortcutsVisibility_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_ToggleShortcutsVisibility_Params_Data)"); class EmbeddedSearch_LogEvent_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_LogEvent_Params_Data)); new (data()) EmbeddedSearch_LogEvent_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_LogEvent_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_LogEvent_Params_Data>(index_); } EmbeddedSearch_LogEvent_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; int32_t event; mojo::internal::Pointer<::mojo_base::mojom::internal::TimeDelta_Data> time; private: EmbeddedSearch_LogEvent_Params_Data(); ~EmbeddedSearch_LogEvent_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_LogEvent_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_LogEvent_Params_Data)"); class EmbeddedSearch_LogSuggestionEventWithValue_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_LogSuggestionEventWithValue_Params_Data)); new (data()) EmbeddedSearch_LogSuggestionEventWithValue_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_LogSuggestionEventWithValue_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_LogSuggestionEventWithValue_Params_Data>(index_); } EmbeddedSearch_LogSuggestionEventWithValue_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; int32_t event; int32_t data; uint8_t pad2_[4]; mojo::internal::Pointer<::mojo_base::mojom::internal::TimeDelta_Data> time; private: EmbeddedSearch_LogSuggestionEventWithValue_Params_Data(); ~EmbeddedSearch_LogSuggestionEventWithValue_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_LogSuggestionEventWithValue_Params_Data) == 32, "Bad sizeof(EmbeddedSearch_LogSuggestionEventWithValue_Params_Data)"); class EmbeddedSearch_LogMostVisitedImpression_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_LogMostVisitedImpression_Params_Data)); new (data()) EmbeddedSearch_LogMostVisitedImpression_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_LogMostVisitedImpression_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_LogMostVisitedImpression_Params_Data>(index_); } EmbeddedSearch_LogMostVisitedImpression_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<internal::NTPTileImpression_Data> impression; private: EmbeddedSearch_LogMostVisitedImpression_Params_Data(); ~EmbeddedSearch_LogMostVisitedImpression_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_LogMostVisitedImpression_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_LogMostVisitedImpression_Params_Data)"); class EmbeddedSearch_LogMostVisitedNavigation_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_LogMostVisitedNavigation_Params_Data)); new (data()) EmbeddedSearch_LogMostVisitedNavigation_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_LogMostVisitedNavigation_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_LogMostVisitedNavigation_Params_Data>(index_); } EmbeddedSearch_LogMostVisitedNavigation_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<internal::NTPTileImpression_Data> impression; private: EmbeddedSearch_LogMostVisitedNavigation_Params_Data(); ~EmbeddedSearch_LogMostVisitedNavigation_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_LogMostVisitedNavigation_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_LogMostVisitedNavigation_Params_Data)"); class EmbeddedSearch_PasteAndOpenDropdown_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_PasteAndOpenDropdown_Params_Data)); new (data()) EmbeddedSearch_PasteAndOpenDropdown_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_PasteAndOpenDropdown_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_PasteAndOpenDropdown_Params_Data>(index_); } EmbeddedSearch_PasteAndOpenDropdown_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t pad0_[4]; mojo::internal::Pointer<::mojo_base::mojom::internal::String16_Data> text_to_be_pasted; private: EmbeddedSearch_PasteAndOpenDropdown_Params_Data(); ~EmbeddedSearch_PasteAndOpenDropdown_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_PasteAndOpenDropdown_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_PasteAndOpenDropdown_Params_Data)"); class EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data)); new (data()) EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data>(index_); } EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<::url::mojom::internal::Url_Data> background_url; mojo::internal::Pointer<mojo::internal::String_Data> attribution_line_1; mojo::internal::Pointer<mojo::internal::String_Data> attribution_line_2; mojo::internal::Pointer<::url::mojom::internal::Url_Data> action_url; private: EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data(); ~EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data) == 40, "Bad sizeof(EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data)"); class EmbeddedSearch_SelectLocalBackgroundImage_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_SelectLocalBackgroundImage_Params_Data)); new (data()) EmbeddedSearch_SelectLocalBackgroundImage_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_SelectLocalBackgroundImage_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_SelectLocalBackgroundImage_Params_Data>(index_); } EmbeddedSearch_SelectLocalBackgroundImage_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: EmbeddedSearch_SelectLocalBackgroundImage_Params_Data(); ~EmbeddedSearch_SelectLocalBackgroundImage_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_SelectLocalBackgroundImage_Params_Data) == 8, "Bad sizeof(EmbeddedSearch_SelectLocalBackgroundImage_Params_Data)"); class EmbeddedSearch_BlocklistSearchSuggestion_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_BlocklistSearchSuggestion_Params_Data)); new (data()) EmbeddedSearch_BlocklistSearchSuggestion_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_BlocklistSearchSuggestion_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_BlocklistSearchSuggestion_Params_Data>(index_); } EmbeddedSearch_BlocklistSearchSuggestion_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t task_version; uint8_t pad0_[4]; int64_t task_id; private: EmbeddedSearch_BlocklistSearchSuggestion_Params_Data(); ~EmbeddedSearch_BlocklistSearchSuggestion_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_BlocklistSearchSuggestion_Params_Data) == 24, "Bad sizeof(EmbeddedSearch_BlocklistSearchSuggestion_Params_Data)"); class EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data)); new (data()) EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data>(index_); } EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t task_version; uint8_t pad0_[4]; int64_t task_id; mojo::internal::Pointer<mojo::internal::Array_Data<uint8_t>> hash; private: EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data(); ~EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data) == 32, "Bad sizeof(EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data)"); class EmbeddedSearch_SearchSuggestionSelected_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_SearchSuggestionSelected_Params_Data)); new (data()) EmbeddedSearch_SearchSuggestionSelected_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_SearchSuggestionSelected_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_SearchSuggestionSelected_Params_Data>(index_); } EmbeddedSearch_SearchSuggestionSelected_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t task_version; uint8_t pad0_[4]; int64_t task_id; mojo::internal::Pointer<mojo::internal::Array_Data<uint8_t>> hash; private: EmbeddedSearch_SearchSuggestionSelected_Params_Data(); ~EmbeddedSearch_SearchSuggestionSelected_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_SearchSuggestionSelected_Params_Data) == 32, "Bad sizeof(EmbeddedSearch_SearchSuggestionSelected_Params_Data)"); class EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data)); new (data()) EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data>(index_); } EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data(); ~EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data) == 8, "Bad sizeof(EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data)"); class EmbeddedSearch_ApplyDefaultTheme_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ApplyDefaultTheme_Params_Data)); new (data()) EmbeddedSearch_ApplyDefaultTheme_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ApplyDefaultTheme_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ApplyDefaultTheme_Params_Data>(index_); } EmbeddedSearch_ApplyDefaultTheme_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: EmbeddedSearch_ApplyDefaultTheme_Params_Data(); ~EmbeddedSearch_ApplyDefaultTheme_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ApplyDefaultTheme_Params_Data) == 8, "Bad sizeof(EmbeddedSearch_ApplyDefaultTheme_Params_Data)"); class EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data)); new (data()) EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data>(index_); } EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint32_t color; uint8_t padfinal_[4]; private: EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data(); ~EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data) == 16, "Bad sizeof(EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data)"); class EmbeddedSearch_RevertThemeChanges_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_RevertThemeChanges_Params_Data)); new (data()) EmbeddedSearch_RevertThemeChanges_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_RevertThemeChanges_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_RevertThemeChanges_Params_Data>(index_); } EmbeddedSearch_RevertThemeChanges_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: EmbeddedSearch_RevertThemeChanges_Params_Data(); ~EmbeddedSearch_RevertThemeChanges_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_RevertThemeChanges_Params_Data) == 8, "Bad sizeof(EmbeddedSearch_RevertThemeChanges_Params_Data)"); class EmbeddedSearch_ConfirmThemeChanges_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearch_ConfirmThemeChanges_Params_Data)); new (data()) EmbeddedSearch_ConfirmThemeChanges_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearch_ConfirmThemeChanges_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearch_ConfirmThemeChanges_Params_Data>(index_); } EmbeddedSearch_ConfirmThemeChanges_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: EmbeddedSearch_ConfirmThemeChanges_Params_Data(); ~EmbeddedSearch_ConfirmThemeChanges_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearch_ConfirmThemeChanges_Params_Data) == 8, "Bad sizeof(EmbeddedSearch_ConfirmThemeChanges_Params_Data)"); class EmbeddedSearchClient_SetPageSequenceNumber_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearchClient_SetPageSequenceNumber_Params_Data)); new (data()) EmbeddedSearchClient_SetPageSequenceNumber_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearchClient_SetPageSequenceNumber_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearchClient_SetPageSequenceNumber_Params_Data>(index_); } EmbeddedSearchClient_SetPageSequenceNumber_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t page_seq_no; uint8_t padfinal_[4]; private: EmbeddedSearchClient_SetPageSequenceNumber_Params_Data(); ~EmbeddedSearchClient_SetPageSequenceNumber_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearchClient_SetPageSequenceNumber_Params_Data) == 16, "Bad sizeof(EmbeddedSearchClient_SetPageSequenceNumber_Params_Data)"); class EmbeddedSearchClient_FocusChanged_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearchClient_FocusChanged_Params_Data)); new (data()) EmbeddedSearchClient_FocusChanged_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearchClient_FocusChanged_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearchClient_FocusChanged_Params_Data>(index_); } EmbeddedSearchClient_FocusChanged_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t new_focus_state; int32_t reason; private: EmbeddedSearchClient_FocusChanged_Params_Data(); ~EmbeddedSearchClient_FocusChanged_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearchClient_FocusChanged_Params_Data) == 16, "Bad sizeof(EmbeddedSearchClient_FocusChanged_Params_Data)"); class EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data)); new (data()) EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data>(index_); } EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::InstantMostVisitedInfo_Data> most_visited_info; private: EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data(); ~EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data) == 16, "Bad sizeof(EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data)"); class EmbeddedSearchClient_SetInputInProgress_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearchClient_SetInputInProgress_Params_Data)); new (data()) EmbeddedSearchClient_SetInputInProgress_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearchClient_SetInputInProgress_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearchClient_SetInputInProgress_Params_Data>(index_); } EmbeddedSearchClient_SetInputInProgress_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t input_in_progress : 1; uint8_t padfinal_[7]; private: EmbeddedSearchClient_SetInputInProgress_Params_Data(); ~EmbeddedSearchClient_SetInputInProgress_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearchClient_SetInputInProgress_Params_Data) == 16, "Bad sizeof(EmbeddedSearchClient_SetInputInProgress_Params_Data)"); class EmbeddedSearchClient_ThemeChanged_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(EmbeddedSearchClient_ThemeChanged_Params_Data)); new (data()) EmbeddedSearchClient_ThemeChanged_Params_Data(); } bool is_null() const { return !serialization_buffer_; } EmbeddedSearchClient_ThemeChanged_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<EmbeddedSearchClient_ThemeChanged_Params_Data>(index_); } EmbeddedSearchClient_ThemeChanged_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::ThemeBackgroundInfo_Data> value; private: EmbeddedSearchClient_ThemeChanged_Params_Data(); ~EmbeddedSearchClient_ThemeChanged_Params_Data() = delete; }; static_assert(sizeof(EmbeddedSearchClient_ThemeChanged_Params_Data) == 16, "Bad sizeof(EmbeddedSearchClient_ThemeChanged_Params_Data)"); class SearchBouncer_SetNewTabPageURL_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(SearchBouncer_SetNewTabPageURL_Params_Data)); new (data()) SearchBouncer_SetNewTabPageURL_Params_Data(); } bool is_null() const { return !serialization_buffer_; } SearchBouncer_SetNewTabPageURL_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<SearchBouncer_SetNewTabPageURL_Params_Data>(index_); } SearchBouncer_SetNewTabPageURL_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<::url::mojom::internal::Url_Data> new_tab_page_url; private: SearchBouncer_SetNewTabPageURL_Params_Data(); ~SearchBouncer_SetNewTabPageURL_Params_Data() = delete; }; static_assert(sizeof(SearchBouncer_SetNewTabPageURL_Params_Data) == 16, "Bad sizeof(SearchBouncer_SetNewTabPageURL_Params_Data)"); } // namespace internal class EmbeddedSearchConnector_Connect_ParamsDataView { public: EmbeddedSearchConnector_Connect_ParamsDataView() {} EmbeddedSearchConnector_Connect_ParamsDataView( internal::EmbeddedSearchConnector_Connect_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> UserType TakeEmbeddedSearch() { UserType result; bool ret = mojo::internal::Deserialize<::chrome::mojom::EmbeddedSearchAssociatedRequestDataView>( &data_->embedded_search, &result, context_); DCHECK(ret); return result; } template <typename UserType> UserType TakeClient() { UserType result; bool ret = mojo::internal::Deserialize<::chrome::mojom::EmbeddedSearchClientAssociatedPtrInfoDataView>( &data_->client, &result, context_); DCHECK(ret); return result; } private: internal::EmbeddedSearchConnector_Connect_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_FocusOmnibox_ParamsDataView { public: EmbeddedSearch_FocusOmnibox_ParamsDataView() {} EmbeddedSearch_FocusOmnibox_ParamsDataView( internal::EmbeddedSearch_FocusOmnibox_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } bool focus() const { return data_->focus; } private: internal::EmbeddedSearch_FocusOmnibox_Params_Data* data_ = nullptr; }; class EmbeddedSearch_DeleteMostVisitedItem_ParamsDataView { public: EmbeddedSearch_DeleteMostVisitedItem_ParamsDataView() {} EmbeddedSearch_DeleteMostVisitedItem_ParamsDataView( internal::EmbeddedSearch_DeleteMostVisitedItem_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUrl(UserType* output) { auto* pointer = data_->url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_DeleteMostVisitedItem_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_UndoAllMostVisitedDeletions_ParamsDataView { public: EmbeddedSearch_UndoAllMostVisitedDeletions_ParamsDataView() {} EmbeddedSearch_UndoAllMostVisitedDeletions_ParamsDataView( internal::EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } private: internal::EmbeddedSearch_UndoAllMostVisitedDeletions_Params_Data* data_ = nullptr; }; class EmbeddedSearch_UndoMostVisitedDeletion_ParamsDataView { public: EmbeddedSearch_UndoMostVisitedDeletion_ParamsDataView() {} EmbeddedSearch_UndoMostVisitedDeletion_ParamsDataView( internal::EmbeddedSearch_UndoMostVisitedDeletion_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUrl(UserType* output) { auto* pointer = data_->url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_UndoMostVisitedDeletion_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_AddCustomLink_ParamsDataView { public: EmbeddedSearch_AddCustomLink_ParamsDataView() {} EmbeddedSearch_AddCustomLink_ParamsDataView( internal::EmbeddedSearch_AddCustomLink_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUrl(UserType* output) { auto* pointer = data_->url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } inline void GetTitleDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadTitle(UserType* output) { auto* pointer = data_->title.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_AddCustomLink_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_AddCustomLink_ResponseParamsDataView { public: EmbeddedSearch_AddCustomLink_ResponseParamsDataView() {} EmbeddedSearch_AddCustomLink_ResponseParamsDataView( internal::EmbeddedSearch_AddCustomLink_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool success() const { return data_->success; } private: internal::EmbeddedSearch_AddCustomLink_ResponseParams_Data* data_ = nullptr; }; class EmbeddedSearch_UpdateCustomLink_ParamsDataView { public: EmbeddedSearch_UpdateCustomLink_ParamsDataView() {} EmbeddedSearch_UpdateCustomLink_ParamsDataView( internal::EmbeddedSearch_UpdateCustomLink_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUrl(UserType* output) { auto* pointer = data_->url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } inline void GetNewUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadNewUrl(UserType* output) { auto* pointer = data_->new_url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } inline void GetNewTitleDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadNewTitle(UserType* output) { auto* pointer = data_->new_title.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_UpdateCustomLink_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_UpdateCustomLink_ResponseParamsDataView { public: EmbeddedSearch_UpdateCustomLink_ResponseParamsDataView() {} EmbeddedSearch_UpdateCustomLink_ResponseParamsDataView( internal::EmbeddedSearch_UpdateCustomLink_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool success() const { return data_->success; } private: internal::EmbeddedSearch_UpdateCustomLink_ResponseParams_Data* data_ = nullptr; }; class EmbeddedSearch_ReorderCustomLink_ParamsDataView { public: EmbeddedSearch_ReorderCustomLink_ParamsDataView() {} EmbeddedSearch_ReorderCustomLink_ParamsDataView( internal::EmbeddedSearch_ReorderCustomLink_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUrl(UserType* output) { auto* pointer = data_->url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } int32_t new_pos() const { return data_->new_pos; } private: internal::EmbeddedSearch_ReorderCustomLink_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_DeleteCustomLink_ParamsDataView { public: EmbeddedSearch_DeleteCustomLink_ParamsDataView() {} EmbeddedSearch_DeleteCustomLink_ParamsDataView( internal::EmbeddedSearch_DeleteCustomLink_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUrl(UserType* output) { auto* pointer = data_->url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_DeleteCustomLink_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_DeleteCustomLink_ResponseParamsDataView { public: EmbeddedSearch_DeleteCustomLink_ResponseParamsDataView() {} EmbeddedSearch_DeleteCustomLink_ResponseParamsDataView( internal::EmbeddedSearch_DeleteCustomLink_ResponseParams_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool success() const { return data_->success; } private: internal::EmbeddedSearch_DeleteCustomLink_ResponseParams_Data* data_ = nullptr; }; class EmbeddedSearch_UndoCustomLinkAction_ParamsDataView { public: EmbeddedSearch_UndoCustomLinkAction_ParamsDataView() {} EmbeddedSearch_UndoCustomLinkAction_ParamsDataView( internal::EmbeddedSearch_UndoCustomLinkAction_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } private: internal::EmbeddedSearch_UndoCustomLinkAction_Params_Data* data_ = nullptr; }; class EmbeddedSearch_ResetCustomLinks_ParamsDataView { public: EmbeddedSearch_ResetCustomLinks_ParamsDataView() {} EmbeddedSearch_ResetCustomLinks_ParamsDataView( internal::EmbeddedSearch_ResetCustomLinks_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } private: internal::EmbeddedSearch_ResetCustomLinks_Params_Data* data_ = nullptr; }; class EmbeddedSearch_ToggleMostVisitedOrCustomLinks_ParamsDataView { public: EmbeddedSearch_ToggleMostVisitedOrCustomLinks_ParamsDataView() {} EmbeddedSearch_ToggleMostVisitedOrCustomLinks_ParamsDataView( internal::EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } private: internal::EmbeddedSearch_ToggleMostVisitedOrCustomLinks_Params_Data* data_ = nullptr; }; class EmbeddedSearch_ToggleShortcutsVisibility_ParamsDataView { public: EmbeddedSearch_ToggleShortcutsVisibility_ParamsDataView() {} EmbeddedSearch_ToggleShortcutsVisibility_ParamsDataView( internal::EmbeddedSearch_ToggleShortcutsVisibility_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } private: internal::EmbeddedSearch_ToggleShortcutsVisibility_Params_Data* data_ = nullptr; }; class EmbeddedSearch_LogEvent_ParamsDataView { public: EmbeddedSearch_LogEvent_ParamsDataView() {} EmbeddedSearch_LogEvent_ParamsDataView( internal::EmbeddedSearch_LogEvent_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } template <typename UserType> WARN_UNUSED_RESULT bool ReadEvent(UserType* output) const { auto data_value = data_->event; return mojo::internal::Deserialize<::chrome::mojom::NTPLoggingEventType>( data_value, output); } NTPLoggingEventType event() const { return static_cast<NTPLoggingEventType>(data_->event); } inline void GetTimeDataView( ::mojo_base::mojom::TimeDeltaDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadTime(UserType* output) { auto* pointer = data_->time.Get(); return mojo::internal::Deserialize<::mojo_base::mojom::TimeDeltaDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_LogEvent_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_LogSuggestionEventWithValue_ParamsDataView { public: EmbeddedSearch_LogSuggestionEventWithValue_ParamsDataView() {} EmbeddedSearch_LogSuggestionEventWithValue_ParamsDataView( internal::EmbeddedSearch_LogSuggestionEventWithValue_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } template <typename UserType> WARN_UNUSED_RESULT bool ReadEvent(UserType* output) const { auto data_value = data_->event; return mojo::internal::Deserialize<::chrome::mojom::NTPSuggestionsLoggingEventType>( data_value, output); } NTPSuggestionsLoggingEventType event() const { return static_cast<NTPSuggestionsLoggingEventType>(data_->event); } int32_t data() const { return data_->data; } inline void GetTimeDataView( ::mojo_base::mojom::TimeDeltaDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadTime(UserType* output) { auto* pointer = data_->time.Get(); return mojo::internal::Deserialize<::mojo_base::mojom::TimeDeltaDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_LogSuggestionEventWithValue_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_LogMostVisitedImpression_ParamsDataView { public: EmbeddedSearch_LogMostVisitedImpression_ParamsDataView() {} EmbeddedSearch_LogMostVisitedImpression_ParamsDataView( internal::EmbeddedSearch_LogMostVisitedImpression_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetImpressionDataView( NTPTileImpressionDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadImpression(UserType* output) { auto* pointer = data_->impression.Get(); return mojo::internal::Deserialize<::chrome::mojom::NTPTileImpressionDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_LogMostVisitedImpression_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_LogMostVisitedNavigation_ParamsDataView { public: EmbeddedSearch_LogMostVisitedNavigation_ParamsDataView() {} EmbeddedSearch_LogMostVisitedNavigation_ParamsDataView( internal::EmbeddedSearch_LogMostVisitedNavigation_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetImpressionDataView( NTPTileImpressionDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadImpression(UserType* output) { auto* pointer = data_->impression.Get(); return mojo::internal::Deserialize<::chrome::mojom::NTPTileImpressionDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_LogMostVisitedNavigation_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_PasteAndOpenDropdown_ParamsDataView { public: EmbeddedSearch_PasteAndOpenDropdown_ParamsDataView() {} EmbeddedSearch_PasteAndOpenDropdown_ParamsDataView( internal::EmbeddedSearch_PasteAndOpenDropdown_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } inline void GetTextToBePastedDataView( ::mojo_base::mojom::String16DataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadTextToBePasted(UserType* output) { auto* pointer = data_->text_to_be_pasted.Get(); return mojo::internal::Deserialize<::mojo_base::mojom::String16DataView>( pointer, output, context_); } private: internal::EmbeddedSearch_PasteAndOpenDropdown_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView { public: EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView() {} EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView( internal::EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetBackgroundUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadBackgroundUrl(UserType* output) { auto* pointer = data_->background_url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } inline void GetAttributionLine1DataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadAttributionLine1(UserType* output) { auto* pointer = data_->attribution_line_1.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } inline void GetAttributionLine2DataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadAttributionLine2(UserType* output) { auto* pointer = data_->attribution_line_2.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } inline void GetActionUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadActionUrl(UserType* output) { auto* pointer = data_->action_url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } private: internal::EmbeddedSearch_SetCustomBackgroundURLWithAttributions_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_SelectLocalBackgroundImage_ParamsDataView { public: EmbeddedSearch_SelectLocalBackgroundImage_ParamsDataView() {} EmbeddedSearch_SelectLocalBackgroundImage_ParamsDataView( internal::EmbeddedSearch_SelectLocalBackgroundImage_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::EmbeddedSearch_SelectLocalBackgroundImage_Params_Data* data_ = nullptr; }; class EmbeddedSearch_BlocklistSearchSuggestion_ParamsDataView { public: EmbeddedSearch_BlocklistSearchSuggestion_ParamsDataView() {} EmbeddedSearch_BlocklistSearchSuggestion_ParamsDataView( internal::EmbeddedSearch_BlocklistSearchSuggestion_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t task_version() const { return data_->task_version; } int64_t task_id() const { return data_->task_id; } private: internal::EmbeddedSearch_BlocklistSearchSuggestion_Params_Data* data_ = nullptr; }; class EmbeddedSearch_BlocklistSearchSuggestionWithHash_ParamsDataView { public: EmbeddedSearch_BlocklistSearchSuggestionWithHash_ParamsDataView() {} EmbeddedSearch_BlocklistSearchSuggestionWithHash_ParamsDataView( internal::EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t task_version() const { return data_->task_version; } int64_t task_id() const { return data_->task_id; } inline void GetHashDataView( mojo::ArrayDataView<uint8_t>* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadHash(UserType* output) { auto* pointer = data_->hash.Get(); return mojo::internal::Deserialize<mojo::ArrayDataView<uint8_t>>( pointer, output, context_); } private: internal::EmbeddedSearch_BlocklistSearchSuggestionWithHash_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_SearchSuggestionSelected_ParamsDataView { public: EmbeddedSearch_SearchSuggestionSelected_ParamsDataView() {} EmbeddedSearch_SearchSuggestionSelected_ParamsDataView( internal::EmbeddedSearch_SearchSuggestionSelected_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t task_version() const { return data_->task_version; } int64_t task_id() const { return data_->task_id; } inline void GetHashDataView( mojo::ArrayDataView<uint8_t>* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadHash(UserType* output) { auto* pointer = data_->hash.Get(); return mojo::internal::Deserialize<mojo::ArrayDataView<uint8_t>>( pointer, output, context_); } private: internal::EmbeddedSearch_SearchSuggestionSelected_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearch_OptOutOfSearchSuggestions_ParamsDataView { public: EmbeddedSearch_OptOutOfSearchSuggestions_ParamsDataView() {} EmbeddedSearch_OptOutOfSearchSuggestions_ParamsDataView( internal::EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::EmbeddedSearch_OptOutOfSearchSuggestions_Params_Data* data_ = nullptr; }; class EmbeddedSearch_ApplyDefaultTheme_ParamsDataView { public: EmbeddedSearch_ApplyDefaultTheme_ParamsDataView() {} EmbeddedSearch_ApplyDefaultTheme_ParamsDataView( internal::EmbeddedSearch_ApplyDefaultTheme_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::EmbeddedSearch_ApplyDefaultTheme_Params_Data* data_ = nullptr; }; class EmbeddedSearch_ApplyAutogeneratedTheme_ParamsDataView { public: EmbeddedSearch_ApplyAutogeneratedTheme_ParamsDataView() {} EmbeddedSearch_ApplyAutogeneratedTheme_ParamsDataView( internal::EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } uint32_t color() const { return data_->color; } private: internal::EmbeddedSearch_ApplyAutogeneratedTheme_Params_Data* data_ = nullptr; }; class EmbeddedSearch_RevertThemeChanges_ParamsDataView { public: EmbeddedSearch_RevertThemeChanges_ParamsDataView() {} EmbeddedSearch_RevertThemeChanges_ParamsDataView( internal::EmbeddedSearch_RevertThemeChanges_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::EmbeddedSearch_RevertThemeChanges_Params_Data* data_ = nullptr; }; class EmbeddedSearch_ConfirmThemeChanges_ParamsDataView { public: EmbeddedSearch_ConfirmThemeChanges_ParamsDataView() {} EmbeddedSearch_ConfirmThemeChanges_ParamsDataView( internal::EmbeddedSearch_ConfirmThemeChanges_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::EmbeddedSearch_ConfirmThemeChanges_Params_Data* data_ = nullptr; }; class EmbeddedSearchClient_SetPageSequenceNumber_ParamsDataView { public: EmbeddedSearchClient_SetPageSequenceNumber_ParamsDataView() {} EmbeddedSearchClient_SetPageSequenceNumber_ParamsDataView( internal::EmbeddedSearchClient_SetPageSequenceNumber_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t page_seq_no() const { return data_->page_seq_no; } private: internal::EmbeddedSearchClient_SetPageSequenceNumber_Params_Data* data_ = nullptr; }; class EmbeddedSearchClient_FocusChanged_ParamsDataView { public: EmbeddedSearchClient_FocusChanged_ParamsDataView() {} EmbeddedSearchClient_FocusChanged_ParamsDataView( internal::EmbeddedSearchClient_FocusChanged_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> WARN_UNUSED_RESULT bool ReadNewFocusState(UserType* output) const { auto data_value = data_->new_focus_state; return mojo::internal::Deserialize<::chrome::mojom::OmniboxFocusState>( data_value, output); } OmniboxFocusState new_focus_state() const { return static_cast<OmniboxFocusState>(data_->new_focus_state); } template <typename UserType> WARN_UNUSED_RESULT bool ReadReason(UserType* output) const { auto data_value = data_->reason; return mojo::internal::Deserialize<::chrome::mojom::OmniboxFocusChangeReason>( data_value, output); } OmniboxFocusChangeReason reason() const { return static_cast<OmniboxFocusChangeReason>(data_->reason); } private: internal::EmbeddedSearchClient_FocusChanged_Params_Data* data_ = nullptr; }; class EmbeddedSearchClient_MostVisitedInfoChanged_ParamsDataView { public: EmbeddedSearchClient_MostVisitedInfoChanged_ParamsDataView() {} EmbeddedSearchClient_MostVisitedInfoChanged_ParamsDataView( internal::EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetMostVisitedInfoDataView( InstantMostVisitedInfoDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadMostVisitedInfo(UserType* output) { auto* pointer = data_->most_visited_info.Get(); return mojo::internal::Deserialize<::chrome::mojom::InstantMostVisitedInfoDataView>( pointer, output, context_); } private: internal::EmbeddedSearchClient_MostVisitedInfoChanged_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class EmbeddedSearchClient_SetInputInProgress_ParamsDataView { public: EmbeddedSearchClient_SetInputInProgress_ParamsDataView() {} EmbeddedSearchClient_SetInputInProgress_ParamsDataView( internal::EmbeddedSearchClient_SetInputInProgress_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool input_in_progress() const { return data_->input_in_progress; } private: internal::EmbeddedSearchClient_SetInputInProgress_Params_Data* data_ = nullptr; }; class EmbeddedSearchClient_ThemeChanged_ParamsDataView { public: EmbeddedSearchClient_ThemeChanged_ParamsDataView() {} EmbeddedSearchClient_ThemeChanged_ParamsDataView( internal::EmbeddedSearchClient_ThemeChanged_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetValueDataView( ThemeBackgroundInfoDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadValue(UserType* output) { auto* pointer = data_->value.Get(); return mojo::internal::Deserialize<::chrome::mojom::ThemeBackgroundInfoDataView>( pointer, output, context_); } private: internal::EmbeddedSearchClient_ThemeChanged_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class SearchBouncer_SetNewTabPageURL_ParamsDataView { public: SearchBouncer_SetNewTabPageURL_ParamsDataView() {} SearchBouncer_SetNewTabPageURL_ParamsDataView( internal::SearchBouncer_SetNewTabPageURL_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetNewTabPageUrlDataView( ::url::mojom::UrlDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadNewTabPageUrl(UserType* output) { auto* pointer = data_->new_tab_page_url.Get(); return mojo::internal::Deserialize<::url::mojom::UrlDataView>( pointer, output, context_); } private: internal::SearchBouncer_SetNewTabPageURL_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; inline void EmbeddedSearch_DeleteMostVisitedItem_ParamsDataView::GetUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_UndoMostVisitedDeletion_ParamsDataView::GetUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_AddCustomLink_ParamsDataView::GetUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_AddCustomLink_ParamsDataView::GetTitleDataView( mojo::StringDataView* output) { auto pointer = data_->title.Get(); *output = mojo::StringDataView(pointer, context_); } inline void EmbeddedSearch_UpdateCustomLink_ParamsDataView::GetUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_UpdateCustomLink_ParamsDataView::GetNewUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->new_url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_UpdateCustomLink_ParamsDataView::GetNewTitleDataView( mojo::StringDataView* output) { auto pointer = data_->new_title.Get(); *output = mojo::StringDataView(pointer, context_); } inline void EmbeddedSearch_ReorderCustomLink_ParamsDataView::GetUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_DeleteCustomLink_ParamsDataView::GetUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_LogEvent_ParamsDataView::GetTimeDataView( ::mojo_base::mojom::TimeDeltaDataView* output) { auto pointer = data_->time.Get(); *output = ::mojo_base::mojom::TimeDeltaDataView(pointer, context_); } inline void EmbeddedSearch_LogSuggestionEventWithValue_ParamsDataView::GetTimeDataView( ::mojo_base::mojom::TimeDeltaDataView* output) { auto pointer = data_->time.Get(); *output = ::mojo_base::mojom::TimeDeltaDataView(pointer, context_); } inline void EmbeddedSearch_LogMostVisitedImpression_ParamsDataView::GetImpressionDataView( NTPTileImpressionDataView* output) { auto pointer = data_->impression.Get(); *output = NTPTileImpressionDataView(pointer, context_); } inline void EmbeddedSearch_LogMostVisitedNavigation_ParamsDataView::GetImpressionDataView( NTPTileImpressionDataView* output) { auto pointer = data_->impression.Get(); *output = NTPTileImpressionDataView(pointer, context_); } inline void EmbeddedSearch_PasteAndOpenDropdown_ParamsDataView::GetTextToBePastedDataView( ::mojo_base::mojom::String16DataView* output) { auto pointer = data_->text_to_be_pasted.Get(); *output = ::mojo_base::mojom::String16DataView(pointer, context_); } inline void EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView::GetBackgroundUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->background_url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView::GetAttributionLine1DataView( mojo::StringDataView* output) { auto pointer = data_->attribution_line_1.Get(); *output = mojo::StringDataView(pointer, context_); } inline void EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView::GetAttributionLine2DataView( mojo::StringDataView* output) { auto pointer = data_->attribution_line_2.Get(); *output = mojo::StringDataView(pointer, context_); } inline void EmbeddedSearch_SetCustomBackgroundURLWithAttributions_ParamsDataView::GetActionUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->action_url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } inline void EmbeddedSearch_BlocklistSearchSuggestionWithHash_ParamsDataView::GetHashDataView( mojo::ArrayDataView<uint8_t>* output) { auto pointer = data_->hash.Get(); *output = mojo::ArrayDataView<uint8_t>(pointer, context_); } inline void EmbeddedSearch_SearchSuggestionSelected_ParamsDataView::GetHashDataView( mojo::ArrayDataView<uint8_t>* output) { auto pointer = data_->hash.Get(); *output = mojo::ArrayDataView<uint8_t>(pointer, context_); } inline void EmbeddedSearchClient_MostVisitedInfoChanged_ParamsDataView::GetMostVisitedInfoDataView( InstantMostVisitedInfoDataView* output) { auto pointer = data_->most_visited_info.Get(); *output = InstantMostVisitedInfoDataView(pointer, context_); } inline void EmbeddedSearchClient_ThemeChanged_ParamsDataView::GetValueDataView( ThemeBackgroundInfoDataView* output) { auto pointer = data_->value.Get(); *output = ThemeBackgroundInfoDataView(pointer, context_); } inline void SearchBouncer_SetNewTabPageURL_ParamsDataView::GetNewTabPageUrlDataView( ::url::mojom::UrlDataView* output) { auto pointer = data_->new_tab_page_url.Get(); *output = ::url::mojom::UrlDataView(pointer, context_); } } // namespace mojom } // namespace chrome #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif #endif // CHROME_COMMON_SEARCH_MOJOM_PARAMS_DATA_H_
4c1f3da598f73de97086e7bb4d27cbe1a7bf573b
df4af7d6295cfbabf16351cfc4fdeab95c137d9b
/src/gui/GameGUI.cpp
a52ad57de24661046932bb152f13f1595eb526cb
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
O-Boll/geotrainer
7ff1c09ef8e71d77e588e31f280a6ddb4b418724
a8112f3614cf93de181fc4dfc950093429bac3d2
refs/heads/master
2021-04-15T17:36:30.067279
2018-03-29T03:13:42
2018-03-29T03:13:42
126,738,823
0
0
null
null
null
null
ISO-8859-1
C++
false
false
18,991
cpp
GameGUI.cpp
/*---------------------------------------------------------------------------- This file is part of GeoTrainer. MIT License Copyright (c) 2018 Olle Eriksson 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 <fstream> #include "GameGUI.h" #include "../misc/StrFcns.h" GameGUI::GameGUI() {} GameGUI::GameGUI(std::string n_map_name, int n_game_mode) { main_ts = Typesetter(s_screen, width, height, &def_tw); main_ts.setBox(5, 0, width - 10, height); main_ts.setSlowTyping(slow_typing); time_ts = Typesetter(s_screen, width, height, &def_tw); time_ts.setBox(5, height - 25, 50, 25); particles = Particles(s_screen, width, height); selected_region = -1; chosen_region = -1; mouse_x = 0; mouse_y = 0; scroll_x = 0; scroll_y = 0; selected_x = 0; selected_y = 0; city_select_distance = 10; run_game = true; help_button_pressed = false; plus_button_pressed = false; setSearchMode(0); unlockInput(); turnDialogOff(); setMousePosition(width / 2, height / 2); game_mode = n_game_mode; map_name = n_map_name; startGame(n_map_name); } GameGUI::~GameGUI() { Sounds::haltSound(); } void GameGUI::startGame(std::string map_name) { resetSelection(); std::string f_name; f_name = "MAPS/" + map_name + "/" + map_name + "_regions.bmp"; loadRegionMap(f_name); f_name = "MAPS/" + map_name + "/" + map_name + "_regions.txt"; loadRegionInfo(f_name); f_name = "MAPS/" + map_name + "/" + map_name + "_cities.bmp"; loadCityCoordinates(f_name); f_name = "MAPS/" + map_name + "/" + map_name + "_cities.txt"; loadCityNames(f_name); /* center mouse position */ setMousePosition(width / 2, height / 2); scroll_x = -(mouse_x * (region_map.getWidth() - width)) / width; scroll_y = -(mouse_y * (region_map.getHeight() - height)) / height; run_game = true; } void GameGUI::loadRegionMap(std::string f_name) { region_map.loadRegionBMP(f_name.c_str(), region_center_x, region_center_y); } void GameGUI::loadRegionInfo(std::string f_name) { region_info.clear(); std::ifstream c_file(f_name); std::string line; while (std::getline(c_file, line)) region_info.push_back(line); } void GameGUI::loadCityCoordinates(std::string f_name) { city_info.clear(); Img* coord_map = new Img(); coord_map->loadBMP(f_name.c_str()); if(coord_map == 0) return; Uint32* pixels = coord_map->getPixels(); int s = coord_map->getWidth() * coord_map->getHeight(); int n_coords = 0; for(int i = 0; i < s; i++) { if((pixels[i] & 0x00FFFFFF) != 0x00FFFFFF) { n_coords++; } } while((int) city_info.size() < n_coords) city_info.push_back(City(0, 0, "")); for(int i = 0; i < s; i++) { Uint32 n = pixels[i] & 0x00FFFFFF; if(n != 0x00FFFFFF) { int x = i % coord_map->getWidth(); int y = i / coord_map->getWidth(); city_info[n].setCoordinates(x, y); } } delete coord_map; } void GameGUI::loadCityNames(std::string f_name) { std::ifstream c_file(f_name.c_str()); if(!c_file) return; std::string line; int n = 0; while (std::getline(c_file, line)) { if(n < (int) city_info.size()) city_info[n].setName(line); else city_info.push_back(City(0, 0, line)); n++; } } void GameGUI::step() { main_ts.step(); time_ts.step(); palette.step(); particles.setOffset(scroll_x, scroll_y); particles.step(); } void GameGUI::draw() { drawRegionMap(); drawCities(); particles.draw(); if(mouse_y < main_ts.getTextHeight() + 10) { main_ts.type(); } else { main_ts.type(); } if( mouse_y > height - time_ts.getTextHeight() - 25 && mouse_x < time_ts.getTextWidth() + 25) time_ts.type(); else time_ts.type(); drawCursor(); render(-scale * scroll_x, -scale * scroll_y); } void GameGUI::drawCities() { for(int i = 0; i < (int) city_info.size(); i++) { City c = city_info[i]; int x = c.getXCoordinate() + scroll_x; int y = c.getYCoordinate() + scroll_y; unsigned int flags = 0x0000; if(isSelectedCity(i) && searchCities()) { flags += Palette::CITY_IS_SELECTED; } if(mouseOverCity(i) && searchCities()) { flags += Palette::CITY_IS_ACTIVE; } Img *c_sym = palette.getCitySymbol(i, flags); if(c_sym != 0) { int offset = c_sym->getWidth() / 2; drawImg(c_sym, x - offset, y - offset); } } } void GameGUI::drawImg(const Img *Im, int x, int y) { if(Im == 0) { return; } int high = y + Im->getHeight(); if(high > height) { high = height; } int start_v = 0; int low = y; if(low < 0) { start_v = -low; low = 0; } int left = x; int start_u = 0; if(left < 0) { start_u = -left; left = 0; } int right = x + Im->getWidth(); if(right > width) { right = width; } int v = start_v; int u_add = 1; for(int cy = low; cy < high; cy++) { int u = start_u; for(int cx = left; cx < right; cx++) { Uint32 color = Im->getPixelAt(u, v); if(color != 0xFF00FF00) { s_screen[cy * width + cx] = color, s_screen[cy * width + cx]; } u += u_add; } v++; } } void GameGUI::drawRegionMap() { int x = scroll_x; int y = scroll_y; for(int j = 0; j < region_map.getHeight(); j++) { for(int i = 0; i < region_map.getWidth(); i++) { if(i + x >= 0 && i + x < width && j + y >= 0 && j + y < height) { int cur_x = i + x; int cur_y = j + y; int region_number = getRegionNumber(cur_x, cur_y); unsigned int flags = 0x0000; if(isSelectedRegion(region_number) && searchRegions()) { flags += Palette::IS_SELECTED; } else if(mouseOverRegion(region_number) && searchRegions()) { flags += Palette::IS_ACTIVE; } if(region_map.isBorder(i, j, palette.getBorderMode())) { flags += Palette::IS_BORDER; } s_screen[(j + y) * width + i + x] = palette.getColor(region_number, i, j, flags); } } } } char GameGUI::readInput(SDL_Keycode k) { if (k == SDLK_0) return '0'; else if(k == SDLK_1) return '1'; else if(k == SDLK_2) return '2'; else if(k == SDLK_3) return '3'; else if(k == SDLK_4) return '4'; else if(k == SDLK_5) return '5'; else if(k == SDLK_6) return '6'; else if(k == SDLK_7) return '7'; else if(k == SDLK_8) return '8'; else if(k == SDLK_9) return '9'; else if(k == SDLK_a) return 'A'; else if(k == SDLK_b) return 'B'; else if(k == SDLK_c) return 'C'; else if(k == SDLK_d) return 'D'; else if(k == SDLK_e) return 'E'; else if(k == SDLK_f) return 'F'; else if(k == SDLK_g) return 'G'; else if(k == SDLK_h) return 'H'; else if(k == SDLK_i) return 'I'; else if(k == SDLK_j) return 'J'; else if(k == SDLK_k) return 'K'; else if(k == SDLK_l) return 'L'; else if(k == SDLK_m) return 'M'; else if(k == SDLK_n) return 'N'; else if(k == SDLK_o) return 'O'; else if(k == SDLK_p) return 'P'; else if(k == SDLK_q) return 'Q'; else if(k == SDLK_r) return 'R'; else if(k == SDLK_s) return 'S'; else if(k == SDLK_t) return 'T'; else if(k == SDLK_u) return 'U'; else if(k == SDLK_v) return 'V'; else if(k == SDLK_w) return 'W'; else if(k == SDLK_x) return 'X'; else if(k == SDLK_y) return 'Y'; else if(k == SDLK_z) return 'Z'; else if(k == SDLK_SPACE) return ' '; else if(k == SDLK_COMMA) return ','; else if(k == SDLK_PERIOD) return '.'; /* ATT GÖRA: KOMPLETTERA OVANSTÅENDE LISTA AV KEYCODES */ else if(k == SDLK_BACKSPACE) return 1; return 0; } void GameGUI::handleEvents() { while(SDL_PollEvent(&event)){ if(event.type == SDL_QUIT) cont = false; else if (event.type == SDL_KEYDOWN) { SDL_Keycode cur_key = event.key.keysym.sym; if (cur_key == SDLK_ESCAPE ) { startMenu(); break; } else if (dialogOn()) { if (cur_key == SDLK_RETURN ) { dialog_ok = true; } else if(cur_key == SDLK_ESCAPE ) { dialog_no = true; } if(input_dialog_on) { char c = readInput(cur_key); if(c == 1) { if(input_dialog_input.size() > 0) input_dialog_input.erase(input_dialog_input.end() - 1, input_dialog_input.end()); } else if(c != 0) { if(input_dialog_input.size() < input_dialog_max_input_length) input_dialog_input += c; else if(input_dialog_max_input_length > 0) input_dialog_input[input_dialog_max_input_length - 1] = c; } if(c != 0) { main_ts.removeLine(main_ts.getNumberOfLines() - 1); printMain(input_dialog_input, 100000.0, 0xFFFFFFFF); } } } else if (isLocked() ) { } else if (cur_key == SDLK_h ) { help_button_pressed = true; } else if (cur_key == SDLK_PLUS || cur_key == SDLK_KP_PLUS ) { plus_button_pressed = true; } } if(isLocked()) { } else if(event.type == SDL_MOUSEMOTION ) { handleMouseMotion(); } else if(event.type == SDL_MOUSEBUTTONDOWN && dialogOn() == false) { handleMouseButtonDown(); chosen_region = selected_region; selected_region = -1; chosen_cities.clear(); chosen_cities = selected_cities; } } } void GameGUI::setMousePosition(int x, int y) { GUI::setMousePosition(x, y); setScroll(); } void GameGUI::handleMouseMotion() { int win_w, win_h; SDL_GetWindowSize(win ,&win_w, &win_h); mouse_x = (event.motion.x * width) / win_w; mouse_y = (event.motion.y * height) / win_h; setScroll(); } void GameGUI::setScroll() { scroll_x = -(mouse_x * (region_map.getWidth() - width)) / width; scroll_y = -(mouse_y * (region_map.getHeight() - height)) / height; } void GameGUI::handleMouseButtonDown() { selected_x = mouse_x - scroll_x; selected_y = mouse_y - scroll_y; int region_number = getRegionNumber(mouse_x, mouse_y); if(region_number >= 0 && region_number == selected_region) { selected_region = -1; } else if(region_number >= 0 && region_number < (int) region_info.size()) { selected_region = region_number; } else { selected_region = -1; } selected_cities.clear(); selected_cities = getCityNumbers(mouse_x, mouse_y); } int GameGUI::getRegionNumber(int rel_x, int rel_y) const { int region_number = -1; int x = rel_x - scroll_x; int y = rel_y - scroll_y; if(x >= 0 && x < region_map.getWidth() && y >= 0 && y < region_map.getHeight()) { region_number = (int) ((region_map.getPixelAt(x, y) << 8) >> 8); } if(region_number == 0xFF00) { region_number = -1; } else if(region_number == 0x9900) { region_number = -2; } return region_number; } bool GameGUI::mouseOverRegion(int region_number) const { if(region_number >= 0 && region_number == getRegionNumber(mouse_x, mouse_y)) return true; return false; } std::string GameGUI::getRegionName(int region_number) const { if(region_number >= 0 && region_number < (int) region_info.size()) return region_info[region_number]; return 0; } int GameGUI::getRegionXCoordinate(int region_number) const { return (region_center_x[region_number] * width) / region_map.getWidth(); } int GameGUI::getRegionYCoordinate(int region_number) const { return (region_center_y[region_number] * height) / region_map.getHeight(); } std::vector<int> GameGUI::getCityNumbers(int rel_x, int rel_y) const { std::vector<int> c_numbers; int max_dist = city_select_distance; int x = rel_x - scroll_x; int y = rel_y - scroll_y; for(int i = 0; i < (int) city_info.size(); i++) { City c = city_info[i]; int sqr_dist = (x - c.getXCoordinate()) * (x - c.getXCoordinate()) + (y - c.getYCoordinate()) * (y - c.getYCoordinate()); if(sqr_dist <= max_dist * max_dist) { c_numbers.push_back(i); } } return c_numbers; } bool GameGUI::mouseOverCity(int city_number) const { std::vector<int> temp_v = getCityNumbers(mouse_x, mouse_y); for(int i = 0; i < temp_v.size(); i++) if(temp_v[i] == city_number) return true; return false; } bool GameGUI::noChosenCities() const { return chosen_cities.empty(); } bool GameGUI::isSelectedCity(int city_number) const { for(int i = 0; i < selected_cities.size(); i++) if(selected_cities[i] == city_number) return true; return false; } bool GameGUI::isChosenCity(int city_number) const { for(int i = 0; i < chosen_cities.size(); i++) if(chosen_cities[i] == city_number) return true; return false; } std::vector<int> GameGUI::getChosenCities() const { std::vector<int> cc_copy = chosen_cities; return cc_copy; } void GameGUI::deselectCities() { selected_cities.clear(); chosen_cities.clear(); } std::string GameGUI::getCityName(int city_number) const { if(city_number >= 0 && city_number < (int) city_info.size()) return city_info[city_number].getName();; return 0; } int GameGUI::getCityXCoordinate(int city_number) const { return (city_info[city_number].getXCoordinate() * width) / region_map.getWidth(); } int GameGUI::getCityYCoordinate(int city_number) const { return (city_info[city_number].getYCoordinate() * height) / region_map.getHeight(); } void GameGUI::alertDialog(std::string message, std::string s) { turnDialogOff(); /* reset */ printMain(message + " " + s, 100000.0, 0xFFFFFFFF); alert_dialog_on = true; } void GameGUI::alertDialog(std::string message) { alertDialog(message, " Press Return to continue."); } void GameGUI::inputDialog(std::string message, unsigned int max_length) { turnDialogOff(); /* reset */ printMain(message, 100000.0, 0xFFFFFFFF); input_dialog_on = true; input_dialog_input = ""; input_dialog_max_input_length = max_length; printMain(input_dialog_input, 100000.0, 0xFFFFFFFF); } void GameGUI::inputDialog(std::string message) { inputDialog(message, 100000.0); } void GameGUI::yesNoDialog(std::string message, std::string s) { turnDialogOff(); /* reset */ printMain(message + " " + s, 100000.0, 0xFFFFFFFF); yes_no_dialog_on = true; } void GameGUI::yesNoDialog(std::string message) { yesNoDialog(message, " Press Return to continue or Esc to exit."); } bool GameGUI::dialogOK() { return dialog_ok; } std::string GameGUI::dialogInput() { return input_dialog_input; } bool GameGUI::dialogNo() { return dialog_no && yes_no_dialog_on; } void GameGUI::turnDialogOff() { clearMain(); alert_dialog_on = input_dialog_on = yes_no_dialog_on = dialog_ok = dialog_no = false; } bool GameGUI::dialogOn() { return alert_dialog_on || input_dialog_on || yes_no_dialog_on; } bool GameGUI::helpButtonPressed() const { return help_button_pressed; } void GameGUI::resetHelpButton() { help_button_pressed = false; } bool GameGUI::plusButtonPressed() const { return plus_button_pressed; } void GameGUI::resetPlusButton() { plus_button_pressed = false; } void GameGUI::printMain(std::string s, double life, Uint32 color) { main_ts.addLine(s, life, color); } void GameGUI::clearMain() { main_ts.clearLines(); } void GameGUI::printTime(int t, Uint32 color) { time_ts.clearLines(); time_ts.addLine(strfcns::itos(t), 100000.0, color); } void GameGUI::printTime(int t) { time_ts.clearLines(); time_ts.addLine(strfcns::itos(t)); } void GameGUI::regionBeacon(int region_number, double time, Uint32 color) { palette.setBeacon(region_number, time, color); } void GameGUI::cityBeacon(std::vector<int> city_numbers, double time, int symbol) { palette.setCityBeacon(city_numbers, time, symbol); } void GameGUI::createParticles(uint32_t n) { particles.create(selected_x, selected_y, n); } std::string GameGUI::getMapName() const { return map_name; } bool GameGUI::noChosenRegion() const { return chosen_region == -1; } bool GameGUI::isSelectedRegion(int region_number) const { // != -1 ??? return region_number >= 0 && selected_region == region_number; } bool GameGUI::isChosenRegion(int region_number) const { // != -1 ??? return region_number >= 0 && chosen_region == region_number; } int GameGUI::getChosenRegion() const { return chosen_region; } void GameGUI::deselectRegion() { selected_region = -1; chosen_region = -1; } int GameGUI::getNumberOfRegions() const { return region_info.size(); } int GameGUI::getNumberOfCities() const { return city_info.size(); } int GameGUI::getGameState() const { return game_state; } void GameGUI::setCitySelectDistance(int d) { city_select_distance = d; } void GameGUI::setSearchMode(int m) { search_mode = m; } bool GameGUI::searchRegions() const { if(search_mode == 0 || search_mode == 1) return true; return false; } bool GameGUI::searchCities() const { if(search_mode == 0 || search_mode == 2) return true; return false; } void GameGUI::resetSelection() { selected_region = -1; chosen_region = -1; selected_cities.clear(); chosen_cities.clear(); } void GameGUI::lockInput() { lock_input = true; } void GameGUI::unlockInput() { lock_input = false; } bool GameGUI::isLocked() const { if(lock_input ) return true; return false; } bool GameGUI::getCloseGUI() const { return !run_game; } void GameGUI::startMenu() { regionBeacon(selected_region, 0.0, 0); cityBeacon(selected_cities, 0.0, 0); resetSelection(); run_game = false; }
66d0353eab9291b530954df02f7df232a3b5687d
5674ce7101033cdefbe64112455a5c902a3ad2f2
/DataManage/CVaoVboManager.h
8d0505571432644c8844310aec4fc6880368a711
[]
no_license
ElectronicsWorks/oscilloscopeQtMVC
97011798d076bc988e162c6b6145cbfe85ea4959
cf7a29bb187f63ad034f26a35cb8f15e48d1d050
refs/heads/master
2021-05-12T07:24:46.342775
2018-01-10T09:17:58
2018-01-10T09:17:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
662
h
CVaoVboManager.h
#ifndef CVAOVBOMANAGE_H #define CVAOVBOMANAGE_H #include <QGLWidget> #include <map> #include <vector> #include <QOpenGLFunctions_4_3_Core> using std::vector; using std::map; class CVaoVboManager : protected QOpenGLFunctions_4_3_Core { public: CVaoVboManager(); ~CVaoVboManager(); void prepare(); GLuint allocVAO(QGLWidget* _widget); GLuint allocVBO(QGLWidget* _widget); void delVAOVBO(QGLWidget*_widget); void delVAO(QGLWidget *_widget, GLuint _vao); void delVBO(QGLWidget *_widget, GLuint _vbo); private: map<QGLWidget*, vector<GLuint>> m_mapVaos; map<QGLWidget*, vector<GLuint>> m_mapVbos; }; #endif // CVAOVBOMANAGE_H
0529ac1bfde43cb6a2caf8c753d0d60b165e6398
3aa684df8c6c4ef8e777a42426fda0c72dd4df6e
/src/graphics/render_graph/colour_node.cpp
9f6e77394c9e95822c362782e9806d7108235738
[ "MIT", "BSD-3-Clause", "Zlib", "BSL-1.0", "Unlicense" ]
permissive
ojas0419/iris
02f9f053e30bd179e02a2d7badd4da933e20966f
cbc2f571bd8d485cdd04f903dcb867e699314682
refs/heads/main
2023-08-21T16:11:10.480107
2021-10-16T06:20:25
2021-10-16T06:20:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
770
cpp
colour_node.cpp
//////////////////////////////////////////////////////////////////////////////// // Distributed under the Boost Software License, Version 1.0. // // (See accompanying file LICENSE or copy at // // https://www.boost.org/LICENSE_1_0.txt) // //////////////////////////////////////////////////////////////////////////////// #include "graphics/render_graph/colour_node.h" #include "core/colour.h" #include "graphics/render_graph/shader_compiler.h" namespace iris { ColourNode::ColourNode(const Colour &colour) : colour_(colour) { } void ColourNode::accept(ShaderCompiler &compiler) const { compiler.visit(*this); } Colour ColourNode::colour() const { return colour_; } }
54d2b5147859e09e66d83da44b35a5b080a20bbb
f3456fc75243defc162de2544ecdaa44e43e22c0
/Exceptions.h
99bb78fc01ddc204b08fa87127a3b303df923704
[]
no_license
trefatim/DZ
c4e499b10e6220927f54a3b9597ef2b30f216e50
42e0b8d613a74c146096ad35307321da10912d22
refs/heads/master
2020-05-17T11:25:16.201170
2015-04-21T15:45:32
2015-04-21T15:45:32
33,079,420
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
h
Exceptions.h
// Copyright 2015 <Anton Sidorov> #pragma once #include <iostream> #include <exception> #include <string> using std::cout; using std::cin; using std::exception; using std::string; class NoAnyGroup : public exception { public: const char* what() const; }; class GroupNotFound : public exception { string group; public: explicit GroupNotFound(const string& gr); const char* what() const; }; class StudentAlreadyExist : public exception { string name; public: StudentAlreadyExist(const string& SN, const string& FN, const string& PT); const char* what() const; }; class GroupAlreadyExist : public exception { string group; public: explicit GroupAlreadyExist(const string& gr); const char* what() const; }; class WrongSubjectIndex : public exception { public: const char* what() const; }; class StudentNotFound : public exception { string name; public: StudentNotFound(const string& SN, const string& FN, const string& PT); const char* what() const; }; class SubjectNotFound : public exception { string subject; public: explicit SubjectNotFound(const string& sub); const char* what() const; }; class StudentIndexNotFound : public exception { string str; public: explicit StudentIndexNotFound(int ind); const char* what() const; }; class NoAnyStudents : public exception { string Str; public: explicit NoAnyStudents(const string& Gr); const char* what() const; };
a2a9b4cf6a8674ed9af4e067494a7efb7f2f04e4
1beaf6796a6bafc6000586c315a8a7b1f9eaa9e0
/Octree/octreenode.cpp
429e7393e3d3dd09f7e483975119e821b00ddc7b
[]
no_license
AlexPrime2018/TestProjectWithRayTracing
7a7aec436f60c268a6eb8b694825c98a3afb8646
b011a1b07b2c1fa3840e172ad790ae1e5a56f449
refs/heads/master
2022-02-13T13:59:21.280706
2019-08-05T13:40:11
2019-08-05T13:40:11
198,026,593
0
0
null
null
null
null
UTF-8
C++
false
false
4,897
cpp
octreenode.cpp
#include "octreenode.h" #include <QDebug> #include "triangle3d.h" unsigned int OctreeNode::LEVEL_MAX = 4; unsigned int OctreeNode::LIMIT_MAX = 10; OctreeNode::OctreeNode(const QVector3D &center, const QVector3D &size, const unsigned int& level, OctreeNode* parent) : m_center(center), m_size(size), m_level(level), m_parent(parent) { float x = m_center.x(); float y = m_center.y(); float z = m_center.z(); m_limitReached = true; m_childCenter[0].setX(x - m_size.x() / 2.0f); m_childCenter[0].setY(y + m_size.y() / 2.0f); m_childCenter[0].setZ(z - m_size.z() / 2.0f); m_childCenter[1].setX(x + m_size.x() / 2.0f); m_childCenter[1].setY(y + m_size.y() / 2.0f); m_childCenter[1].setZ(z - m_size.z() / 2.0f); m_childCenter[2].setX(x - m_size.x() / 2.0f); m_childCenter[2].setY(y - m_size.y() / 2.0f); m_childCenter[2].setZ(z - m_size.z() / 2.0f); m_childCenter[3].setX(x + m_size.x() / 2.0f); m_childCenter[3].setY(y - m_size.y() / 2.0f); m_childCenter[3].setZ(z - m_size.z() / 2.0f); m_childCenter[4].setX(x - m_size.x() / 2.0f); m_childCenter[4].setY(y + m_size.y() / 2.0f); m_childCenter[4].setZ(z + m_size.z() / 2.0f); m_childCenter[5].setX(x + m_size.x() / 2.0f); m_childCenter[5].setY(y + m_size.y() / 2.0f); m_childCenter[5].setZ(z + m_size.z() / 2.0f); m_childCenter[6].setX(x - m_size.x() / 2.0f); m_childCenter[6].setY(y - m_size.y() / 2.0f); m_childCenter[6].setZ(z + m_size.z() / 2.0f); m_childCenter[7].setX(x + m_size.x() / 2.0f); m_childCenter[7].setY(y - m_size.y() / 2.0f); m_childCenter[7].setZ(z + m_size.z() / 2.0f); for (int indexChild = 0; indexChild < 8; indexChild++) m_child[indexChild] = nullptr; } OctreeNode::~OctreeNode() { for (int indexChild = 0; indexChild < 8; indexChild++) if (m_child[indexChild]) delete m_child[indexChild]; } bool OctreeNode::intersection(const Ray &ray, Triangle3D *closestTriangle) { bool hasIntersection = false; QVector3D half_size = m_size / 2.0f; if (!HelperFunctions::rayIntersectionAABB(ray, m_center, m_size)) return false; if (HelperFunctions::rayIntersectionAABB(ray, m_center, m_size)) { if (!m_limitReached || m_level == LEVEL_MAX) { for (Triangle3D *tri : m_trianglesThisNode) { if (tri->intersection(ray, IntersectionPoint)) { closestTriangle = tri; hasIntersection = true; } } } else { std::multimap<float, int> cubeOrder; for (int i = 0; i < 8; i++) { float tmpDist = std::numeric_limits<float>::max(); if (m_child[i] && HelperFunctions::rayIntersectionAABB(ray, m_childCenter[i], half_size)) { cubeOrder.insert(std::pair<float, int>(tmpDist, i)); } } for (std::pair<float, int> order : cubeOrder) { int childIndex = order.second; if (m_child[childIndex] && m_child[childIndex]->intersection(ray, closestTriangle)) { hasIntersection = true; } } } } return hasIntersection; } void OctreeNode::addTriangle(Triangle3D *triangles) { QVector3D half_size = m_size / 2.0f; if (m_level == LEVEL_MAX) { m_trianglesThisNode.push_back(triangles); if (m_trianglesThisNode.size() >= LIMIT_MAX && m_level < LEVEL_MAX) { m_limitReached = true; for (Triangle3D *tri : m_trianglesThisNode) { QVector3D p0 = tri->getP0(); QVector3D p1 = tri->getP1(); QVector3D p2 = tri->getP2(); for (int i = 0; i < 8; i++) { if (HelperFunctions::triangleInsideAABB(p0, p1, p2, m_childCenter[i], half_size)) { if (!m_child[i]) m_child[i] = new OctreeNode(m_childCenter[i], half_size, m_level + 1, this); m_child[i]->addTriangle(tri); } } } m_trianglesThisNode.clear(); } } else { QVector3D p0 = triangles->getP0(); QVector3D p1 = triangles->getP1(); QVector3D p2 = triangles->getP2(); for (int i = 0; i < 8; i++) { if (HelperFunctions::triangleInsideAABB(p0, p1, p2, m_childCenter[i], half_size)) { if (!m_child[i]) m_child[i] = new OctreeNode(m_childCenter[i], half_size, m_level + 1, this); m_child[i]->addTriangle(triangles); } } } }
2185ccb5bdd28747a975dcf085205e718a9f3252
e105335bd8f40dcd5f8fabc365ae43d9c1eb26fe
/算法练习/Algorithm/Algorithm/main.cpp
1f289ac455780aaf10a11c88d681e7857ca0a180
[ "MIT" ]
permissive
faterap/blogs
7b7203602d6de0b413df3d332c1641e1944c28d3
971bd46c26bd6eabdb18608d15930f196154d790
refs/heads/master
2023-06-11T19:44:30.355664
2021-07-03T14:53:30
2021-07-03T14:53:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
main.cpp
// // main.cpp // Algorithm // // Created by chenzebin on 2020/4/23. // Copyright © 2020 chenzebin. All rights reserved. // #include <iostream> #include "HexConvert.cpp" int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; } void HexConvert() { HexConvert hexConvert; }
e3a9d704092ccfa575f27431d72cc57cad7687a8
837bb07334c264fc1cd83fd454ba059b442f8f86
/MediaDatabase/media.cpp
b8f324d334641d0f18ad0b122e09676b651ea865
[]
no_license
tejaprakki/C-Projects
65ccaa098e59c3b8ba412dbbfcb594176e4a1b1f
61624a4277e07e2a3ca86d02f25f063de95dd0d2
refs/heads/master
2020-07-19T02:12:36.417560
2020-04-10T18:23:08
2020-04-10T18:23:08
206,357,548
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
media.cpp
//Media File #include <iostream> #include <cstring> #include "media.h" using namespace std; Media::Media() { title = new char[100]; year = 0; } int Media::getType() { return 0; } int Media::getYear() { return year; } char* Media::getTitle() { return title; }
7a1caf5b3600593f3299f1b7492acab2d17664c2
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/third_party/blink/public/mojom/frame/find_in_page.mojom-forward.h
e28d3023e0847f9b46b068edee23c7ca6e32fd8e
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
2,377
h
find_in_page.mojom-forward.h
// third_party/blink/public/mojom/frame/find_in_page.mojom-forward.h is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_PUBLIC_MOJOM_FRAME_FIND_IN_PAGE_MOJOM_FORWARD_H_ #define THIRD_PARTY_BLINK_PUBLIC_MOJOM_FRAME_FIND_IN_PAGE_MOJOM_FORWARD_H_ #include <stdint.h> #include "mojo/public/cpp/bindings/struct_forward.h" #include "mojo/public/cpp/bindings/deprecated_interface_types_forward.h" #include "mojo/public/interfaces/bindings/native_struct.mojom-forward.h" namespace blink { namespace mojom { class FindOptionsDataView; enum class StopFindAction : int32_t; enum class FindMatchUpdateType : int32_t; class FindOptions; using FindOptionsPtr = mojo::StructPtr<FindOptions>; class FindInPage; using FindInPagePtr = mojo::InterfacePtr<FindInPage>; using FindInPagePtrInfo = mojo::InterfacePtrInfo<FindInPage>; using ThreadSafeFindInPagePtr = mojo::ThreadSafeInterfacePtr<FindInPage>; using FindInPageRequest = mojo::InterfaceRequest<FindInPage>; using FindInPageAssociatedPtr = mojo::AssociatedInterfacePtr<FindInPage>; using ThreadSafeFindInPageAssociatedPtr = mojo::ThreadSafeAssociatedInterfacePtr<FindInPage>; using FindInPageAssociatedPtrInfo = mojo::AssociatedInterfacePtrInfo<FindInPage>; using FindInPageAssociatedRequest = mojo::AssociatedInterfaceRequest<FindInPage>; class FindInPageClient; using FindInPageClientPtr = mojo::InterfacePtr<FindInPageClient>; using FindInPageClientPtrInfo = mojo::InterfacePtrInfo<FindInPageClient>; using ThreadSafeFindInPageClientPtr = mojo::ThreadSafeInterfacePtr<FindInPageClient>; using FindInPageClientRequest = mojo::InterfaceRequest<FindInPageClient>; using FindInPageClientAssociatedPtr = mojo::AssociatedInterfacePtr<FindInPageClient>; using ThreadSafeFindInPageClientAssociatedPtr = mojo::ThreadSafeAssociatedInterfacePtr<FindInPageClient>; using FindInPageClientAssociatedPtrInfo = mojo::AssociatedInterfacePtrInfo<FindInPageClient>; using FindInPageClientAssociatedRequest = mojo::AssociatedInterfaceRequest<FindInPageClient>; } // namespace mojom } // namespace blink #endif // THIRD_PARTY_BLINK_PUBLIC_MOJOM_FRAME_FIND_IN_PAGE_MOJOM_FORWARD_H_
78894be7032c142cd8cede35933934f32284e806
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/shell/osshell/cpls/usb/usbpopup.cpp
e8be40f9074996e5e58abbd5e70ee87aea6caa2d
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
19,573
cpp
usbpopup.cpp
/******************************************************************************* * * (C) COPYRIGHT MICROSOFT CORP., 1993-1995 * TITLE: USBPOPUP.CPP * VERSION: 1.0 * AUTHOR: jsenior * DATE: 10/28/1998 * ******************************************************************************** * * CHANGE LOG: * * DATE REV DESCRIPTION * ---------- ------- ---------------------------------------------------------- * 10/28/1998 jsenior Original implementation. * *******************************************************************************/ #include "UsbPopup.h" #include "PropPage.h" #include "debug.h" #include "usbutil.h" UINT CALLBACK UsbPopup::StaticDialogCallback(HWND Hwnd, UINT Msg, LPPROPSHEETPAGE Page) { UsbPopup *that; switch (Msg) { case PSPCB_CREATE: return TRUE; // return TRUE to continue with creation of page case PSPCB_RELEASE: that = (UsbPopup*) Page->lParam; DeleteChunk(that); delete that; return 0; // return value ignored default: break; } return TRUE; } USBINT_PTR APIENTRY UsbPopup::StaticDialogProc(IN HWND hDlg, IN UINT uMessage, IN WPARAM wParam, IN LPARAM lParam) { UsbPopup *that; that = (UsbPopup *) UsbGetWindowLongPtr(hDlg, USBDWLP_USER); if (!that && uMessage != WM_INITDIALOG) return FALSE; //DefDlgProc(hDlg, uMessage, wParam, lParam); switch (uMessage) { case WM_COMMAND: return that->OnCommand(HIWORD(wParam), LOWORD(wParam), (HWND) lParam); case WM_TIMER: return that->OnTimer(); case WM_INITDIALOG: that = (UsbPopup *) lParam; UsbSetWindowLongPtr(hDlg, USBDWLP_USER, (USBLONG_PTR) that); that->hWnd = hDlg; return that->OnInitDialog(hDlg); case WM_NOTIFY: return that->OnNotify(hDlg, (int) wParam, (LPNMHDR) lParam); case WM_DEVICECHANGE: return that->OnDeviceChange(hDlg, wParam, (PDEV_BROADCAST_HDR)lParam); default: break; } return that->ActualDialogProc(hDlg, uMessage, wParam, lParam); } BOOL UsbPopup::OnCommand(INT wNotifyCode, INT wID, HWND hCtl) { switch (wID) { case IDOK: EndDialog(hWnd, wID); return TRUE; } return FALSE; } BOOL UsbPopup::OnNotify(HWND hDlg, int nID, LPNMHDR pnmh) { switch (nID) { case IDC_LIST_CONTROLLERS: if (pnmh->code == NM_DBLCLK) { // // Display properties on this specific device on double click // UsbPropertyPage::DisplayPPSelectedListItem(hDlg, hListDevices); } return TRUE; case IDC_TREE_HUBS: if (pnmh->code == NM_DBLCLK) { // // Display properties on this specific device on double click // UsbPropertyPage::DisplayPPSelectedTreeItem(hDlg, hTreeDevices); } return TRUE; } return 0; } BOOL UsbPopup::CustomDialog( DWORD DialogBoxId, DWORD IconId, DWORD FormatStringId, DWORD TitleStringId) { HRESULT hr; // // Make sure the device hasn't gone away. // if (UsbItem::UsbItemType::Empty == deviceItem.itemType) { return FALSE; } TCHAR buf[MAX_PATH]; TCHAR formatString[MAX_PATH]; LoadString(gHInst, FormatStringId, formatString, MAX_PATH); UsbSprintf(buf, formatString, deviceItem.configInfo->deviceDesc.c_str()); LoadString(gHInst, TitleStringId, formatString, MAX_PATH); pun->SetBalloonRetry(-1, -1, 0); pun->SetIconInfo(LoadIcon(gHInst, MAKEINTRESOURCE(IDI_USB)), formatString); pun->SetBalloonInfo(formatString, buf, IconId); // // Query me every 2 seconds. // hr = pun->Show(this, 2000); pun->Release(); if (S_OK == hr) { if (-1 == DialogBoxParam(gHInst, MAKEINTRESOURCE(DialogBoxId), NULL, StaticDialogProc, (LPARAM) this)) { return FALSE; } } return TRUE; } STDMETHODIMP_(ULONG) UsbPopup::AddRef() { return InterlockedIncrement(&RefCount); } STDMETHODIMP_(ULONG) UsbPopup::Release() { assert( 0 != RefCount ); ULONG cRef = InterlockedDecrement(&RefCount); if ( 0 == cRef ) { // // TODO: gpease 27-FEB-2002 // Figure out why someone commented out this delete. What's the use of having // the RefCount if it is meaningless? // // delete this; } return cRef; } HRESULT UsbPopup::QueryInterface(REFIID iid, void **ppv) { if ((iid == IID_IUnknown) || (iid == IID_IQueryContinue)) { *ppv = (void *)(IQueryContinue *)this; } else { *ppv = NULL; // null the out param return E_NOINTERFACE; } AddRef(); return S_OK; } HRESULT UsbPopup::QueryContinue() { USB_NODE_CONNECTION_INFORMATION connectionInfo; ULONG nBytes; HANDLE hHubDevice; String hubName = HubAcquireInfo->Buffer; // // Try to open the hub device // hHubDevice = GetHandleForDevice(hubName); if (hHubDevice == INVALID_HANDLE_VALUE) { return S_FALSE; } // // Find out if we still have an underpowered device attached . // nBytes = sizeof(USB_NODE_CONNECTION_INFORMATION); ZeroMemory(&connectionInfo, nBytes); connectionInfo.ConnectionIndex = ConnectionNotification->ConnectionNumber; if ( !DeviceIoControl(hHubDevice, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION, &connectionInfo, nBytes, &connectionInfo, nBytes, &nBytes, NULL)) { return S_FALSE; } CloseHandle(hHubDevice); switch (ConnectionNotification->NotificationType) { case InsufficentBandwidth: return connectionInfo.ConnectionStatus == DeviceNotEnoughBandwidth ? S_OK : S_FALSE; case EnumerationFailure: return connectionInfo.ConnectionStatus == DeviceFailedEnumeration ? S_OK : S_FALSE; case InsufficentPower: return connectionInfo.ConnectionStatus == DeviceNotEnoughPower ? S_OK : S_FALSE; case OverCurrent: return connectionInfo.ConnectionStatus == DeviceCausedOvercurrent ? S_OK : S_FALSE; case ModernDeviceInLegacyHub: return connectionInfo.ConnectionStatus == DeviceConnected ? S_OK : S_FALSE; case HubNestedTooDeeply: return connectionInfo.ConnectionStatus == DeviceHubNestedTooDeeply ? S_OK : S_FALSE; } return S_FALSE; } void UsbPopup::Make(PUSB_CONNECTION_NOTIFICATION vUsbConnectionNotification, LPTSTR strInstanceName) { ULONG result; HRESULT hr; String hubName; InstanceName = strInstanceName; ConnectionNotification = vUsbConnectionNotification; result = WmiOpenBlock((LPGUID) &GUID_USB_WMI_STD_DATA, 0, &WmiHandle); if (result != ERROR_SUCCESS) { goto UsbPopupMakeError; } hWnd = GetDesktopWindow(); InitCommonControls(); // // Get the hub name and from that, get the name of the device to display in // the dialog and display it. // We'll use the port number which the device is attached to. This is: // ConnectionNotification->ConnectionNumber; HubAcquireInfo = GetHubName(WmiHandle, strInstanceName, ConnectionNotification); if (!HubAcquireInfo) { goto UsbPopupMakeError; } hubName = HubAcquireInfo->Buffer; // // Make sure that the condition still exists. // if (S_FALSE == QueryContinue()) { USBTRACE((_T("Erorr does not exist anymore. Exitting.\n"))); goto UsbPopupMakeError; } if (!deviceItem.GetDeviceInfo(hubName, ConnectionNotification->ConnectionNumber)) { goto UsbPopupMakeError; } if (!IsPopupStillValid()) { // // We already saw the error for this device. Usbhub is being // repetitive. // goto UsbPopupMakeError; } hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (FAILED(hr)) { hr = CoInitializeEx(NULL, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE); } if (FAILED(hr)) { goto UsbPopupMakeError; } hr = CoCreateInstance(CLSID_UserNotification, NULL, CLSCTX_ALL, IID_PPV_ARG(IUserNotification, &pun)); if (!FAILED(hr)) { CustomDialogWrap(); } CoUninitialize(); UsbPopupMakeError: USBTRACE((_T("UsbPopupMakeError\n"))); if (WmiHandle != INVALID_HANDLE_VALUE) { WmiCloseBlock(WmiHandle); } } BOOL UsbPopup::OnInitDialog(HWND HWnd) { hWnd = HWnd; HANDLE hExclamation; HICON hIcon; if (RegisterForDeviceReattach) { // // Try to open the hub device // String hubName = HubAcquireInfo->Buffer; HANDLE hHubDevice = GetHandleForDevice(hubName); if (hHubDevice != INVALID_HANDLE_VALUE) { // // Register for notification for when the device is re-attached. We want // to do this before we see the device get detached because we are polling // and may miss the re-attach if we register when the device is removed. // // Allocate configuration information structure and get config mgr info // ConfigInfo = new UsbConfigInfo(); AddChunk(ConfigInfo); if (ConfigInfo) { String driverKeyName = GetDriverKeyName(hHubDevice, ConnectionNotification->ConnectionNumber); if (!driverKeyName.empty()) { GetConfigMgrInfo(driverKeyName, ConfigInfo); // ISSUE: leak, jsenior, 4/19/00 } else { USBWARN((_T("Couldn't get driver key name. Error: (%x)."), GetLastError())); } CHAR guidBuf[MAX_PATH]; DEV_BROADCAST_DEVICEINTERFACE devInterface; DWORD len = MAX_PATH; if (CM_Get_DevNode_Registry_PropertyA(ConfigInfo->devInst, CM_DRP_CLASSGUID, NULL, guidBuf, &len, 0) == CR_SUCCESS) { ZeroMemory(&devInterface, sizeof(DEV_BROADCAST_DEVICEINTERFACE)); if (StrToGUID(guidBuf, &devInterface.dbcc_classguid)) { devInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); devInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; hNotifyArrival = RegisterDeviceNotification( HWnd, &devInterface, DEVICE_NOTIFY_WINDOW_HANDLE); if (!hNotifyArrival){ USBWARN((_T("RegisterDeviceNotification failure (%x)."), GetLastError())); } } else { USBWARN((_T("GUID conversion didn't work."))); } USBWARN((_T("GUID data: %x-%x-%x-%x-%x-%x-%x-%x-%x-%x-%x"), devInterface.dbcc_classguid.Data1, devInterface.dbcc_classguid.Data2, devInterface.dbcc_classguid.Data3, devInterface.dbcc_classguid.Data4[0], devInterface.dbcc_classguid.Data4[1], devInterface.dbcc_classguid.Data4[2], devInterface.dbcc_classguid.Data4[3], devInterface.dbcc_classguid.Data4[4], devInterface.dbcc_classguid.Data4[5], devInterface.dbcc_classguid.Data4[6], devInterface.dbcc_classguid.Data4[7])); } else { // // If this fails, we need to default to the old functionality! // ISSUE: jsenior // } } CloseHandle(hHubDevice); } } // // Set the Icon to an exclamation mark // if (NULL == (hIcon = LoadIcon(NULL, (LPTSTR) IDI_EXCLAMATION)) || NULL == (hExclamation = GetDlgItem(hWnd, IDC_ICON_POWER))) { return FALSE; } SendMessage((HWND) hExclamation, STM_SETICON, (WPARAM) hIcon, NULL); // // Get a persistent handle to the tree view control // if (NULL == (hTreeDevices = GetDlgItem(HWnd, IDC_TREE_HUBS))) { return FALSE; } TreeView_SetImageList(hTreeDevices, ImageList.ImageList(), TVSIL_NORMAL); return Refresh(); } PUSB_ACQUIRE_INFO UsbPopup::GetHubName(WMIHANDLE WmiHandle, UsbString InstanceName, PUSB_CONNECTION_NOTIFICATION ConnectionNotification) { ULONG res, size; PUSB_ACQUIRE_INFO usbAcquireInfo; // // zero all the vars, get the controllers name // size = ConnectionNotification->HubNameLength * sizeof(WCHAR) + sizeof(USB_ACQUIRE_INFO); usbAcquireInfo = (PUSB_ACQUIRE_INFO) LocalAlloc(LMEM_ZEROINIT, size); if (!usbAcquireInfo) { USBERROR((_T("Acquire info allocation failed."))); return NULL; } usbAcquireInfo->NotificationType = AcquireHubName; usbAcquireInfo->TotalSize = size; res = WmiExecuteMethod(WmiHandle, InstanceName.c_str(), AcquireHubName, size, usbAcquireInfo, &size, usbAcquireInfo ); if (res != ERROR_SUCCESS) { usbAcquireInfo = (PUSB_ACQUIRE_INFO) LocalFree(usbAcquireInfo); } return usbAcquireInfo; } BOOLEAN UsbPopup::GetBusNotification(WMIHANDLE WmiHandle, PUSB_BUS_NOTIFICATION UsbBusNotification) { ULONG res, size; memset(UsbBusNotification, 0, sizeof(USB_BUS_NOTIFICATION)); UsbBusNotification->NotificationType = AcquireBusInfo; size = sizeof(USB_BUS_NOTIFICATION); res = WmiExecuteMethod(WmiHandle, InstanceName.c_str(), AcquireBusInfo, size, UsbBusNotification, &size, UsbBusNotification ); if (res != ERROR_SUCCESS) { return FALSE; } return TRUE; } PUSB_ACQUIRE_INFO UsbPopup::GetControllerName(WMIHANDLE WmiHandle, UsbString InstanceName) { ULONG res, size; USB_BUS_NOTIFICATION usbBusNotification; PUSB_ACQUIRE_INFO usbAcquireInfo; memset(&usbBusNotification, 0, sizeof(USB_BUS_NOTIFICATION)); usbBusNotification.NotificationType = AcquireBusInfo; size = sizeof(USB_BUS_NOTIFICATION); res = WmiExecuteMethod(WmiHandle, InstanceName.c_str(), AcquireBusInfo, size, &usbBusNotification, &size, &usbBusNotification ); if (res != ERROR_SUCCESS) { return NULL; } // // zero all the vars, get the controllers name // size = usbBusNotification.ControllerNameLength * sizeof(WCHAR) + sizeof(USB_ACQUIRE_INFO); usbAcquireInfo = (PUSB_ACQUIRE_INFO) LocalAlloc(LMEM_ZEROINIT, size); usbAcquireInfo->NotificationType = AcquireControllerName; usbAcquireInfo->TotalSize = size; res = WmiExecuteMethod(WmiHandle, InstanceName.c_str(), AcquireControllerName, size, usbAcquireInfo, &size, usbAcquireInfo ); if (res != ERROR_SUCCESS) { usbAcquireInfo = (PUSB_ACQUIRE_INFO) LocalFree(usbAcquireInfo); } return usbAcquireInfo; } BOOL UsbPopup::OnDeviceChange(HWND hDlg, WPARAM wParam, PDEV_BROADCAST_HDR devHdr) { PDEV_BROADCAST_DEVICEINTERFACE devInterface = (PDEV_BROADCAST_DEVICEINTERFACE) devHdr; USBTRACE((_T("Device change notification, type %x."), wParam)); switch (wParam) { case DBT_DEVICEARRIVAL: USBTRACE((_T("Device arrival."))); if (devHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { USBTRACE((_T("Device: %s"),devInterface->dbcc_name)); // New device arrival. // Compare the device description of this puppy to that of the one // that we have. // if (devInterface->dbcc_name == ConfigInfo->deviceDesc && deviceState == DeviceDetachedError) { USBTRACE((_T("Device name match on arrival!"))); // // The device has been reattached! // deviceState = DeviceReattached; Refresh(); } } break; case DBT_DEVICEREMOVECOMPLETE: USBTRACE((_T("Device removal."))); if (devHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { USBTRACE((_T("Device: %s"),devInterface->dbcc_name)); // New device arrival. // Compare the device description of this puppy to that of the one // that we have. // if (devInterface->dbcc_name == ConfigInfo->deviceDesc && deviceState == DeviceAttachedError) { USBTRACE((_T("Device name match on remove!"))); // // The device has been reattached! // deviceState = DeviceDetachedError; Refresh(); } } break; } return TRUE; }
f41543ebdf98c6b134e317f9f8a23086eb1fd648
58017319ededd71d2c8ec051a11a7aad096f53b1
/AvecSynth.h
f7bad197d5b839dead36e2db73e524329a8c66ce
[]
no_license
t-nelson/AvecSynth
ebc2aac80a97d871e2703f89eafa914983709dae
dd167717d9e4fa283ab6e99217467aa02c9fd97b
refs/heads/master
2021-01-17T05:40:51.359294
2012-01-06T02:44:52
2012-01-06T02:44:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
568
h
AvecSynth.h
#ifndef AVECSYNTH_H__ #define AVECSYNTH_H__ #include <../MIDI/MIDI.h> #include <stdlib.h> struct avec_sample { unsigned long delay_ms; kMIDIType type; byte channel; byte data1; byte data2; }; class CAvecSynth { public: CAvecSynth(); virtual ~CAvecSynth(); void begin(const byte inChannel=1); void Record(struct avec_sample* buf, size_t nsamples, byte Channel = 1); void Play(const struct avec_sample* buf, size_t nsamples, byte Channel = 1); }; extern CAvecSynth AvecSynth; #endif // AVECSYNTH_H__
60d83d11145d29c7ed81fb03bc2d1873c75ff634
6322afe42dd32f0cc72cfe637c109f042ec4af39
/include/lvr2/algorithm/raycasting/CLRaycaster.hpp
815a5b570860677b92c444b8066fe0ae8f6a37a4
[]
permissive
uos/lvr2
3c94d640f3e315e23fd194d85c2bd8e6877cd674
9bb03a30441b027c39db967318877e03725112d5
refs/heads/develop
2023-06-22T11:49:52.100143
2021-10-08T15:58:07
2021-10-08T15:58:07
173,213,176
66
16
BSD-3-Clause
2023-05-28T19:10:14
2019-03-01T01:18:58
C++
UTF-8
C++
false
false
6,587
hpp
CLRaycaster.hpp
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück 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 University Osnabrück 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. */ /* * CLRaycaster.hpp * * @date 25.01.2020 * @author Johan M. von Behren <johan@vonbehren.eu> * @author Alexander Mock <amock@uos.de> */ #ifndef LVR2_ALGORITHM_RAYCASTING_CLRAYCASTER #define LVR2_ALGORITHM_RAYCASTING_CLRAYCASTER #include <chrono> #include "lvr2/io/MeshBuffer.hpp" #include "lvr2/types/MatrixTypes.hpp" #include "lvr2/algorithm/raycasting/BVHRaycaster.hpp" #define CL_HPP_ENABLE_EXCEPTIONS #define CL_HPP_MINIMUM_OPENCL_VERSION 120 // Need to set to 120 on CUDA 8 #define CL_HPP_TARGET_OPENCL_VERSION 120 // Need to set to 120 on CUDA 8 // hard cl2 depencency #include <CL/cl2.hpp> // if your code can handle cl.hpp and cl2.hpp use: // #if defined LVR2_USE_OPENCL_NEW_API // #include <CL/cl2.hpp> // #else // #include <CL/cl.hpp> // #endif #include "lvr2/util/CLUtil.hpp" #include "Intersection.hpp" namespace lvr2 { /** * @brief CLRaycaster: GPU OpenCL version of BVH Raycasting */ template<typename IntT> class CLRaycaster : public BVHRaycaster<IntT> { public: /** * @brief Constructor: Generate BVH tree on mesh, loads CL kernels */ CLRaycaster(const MeshBufferPtr mesh, unsigned int stack_size = 32); /// Overload functions /// /** * @brief Cast a single ray onto the mesh. Hint: Better not use it on GPU. * * @param[in] origin Ray origin * @param[in] direction Ray direction * @param[out] intersection User defined intersection output * @return true Intersection found * @return false Not intersection found */ bool castRay( const Vector3f& origin, const Vector3f& direction, IntT& intersection); using BVHRaycaster<IntT>::castRays; /** * @brief Cast a ray from single origin * with multiple directions onto the mesh * * @param[in] origin Origin of the ray * @param[in] directions Directions of the ray * @param[out] intersections User defined intersections output * @param[out] hits Intersection found or not */ void castRays( const Vector3f& origin, const std::vector<Vector3f>& directions, std::vector<IntT>& intersections, std::vector<uint8_t>& hits) override; /** * @brief Cast from multiple ray origin/direction * pairs onto the mesh * * @param[in] origin Origin of the ray * @param[in] directions Directions of the ray * @param[out] intersections User defined intersections output * @param[out] hits Intersection found or not */ void castRays( const std::vector<Vector3f>& origins, const std::vector<Vector3f>& directions, std::vector<IntT>& intersections, std::vector<uint8_t>& hits) override; struct ClTriangleIntersectionResult { cl_uchar hit = 0; cl_uint pBestTriId; cl_float3 pointHit; cl_float hitDist; }; protected: using BVHRaycaster<IntT>::barycentric; using BVHRaycaster<IntT>::m_bvh; using BVHRaycaster<IntT>::m_vertices; using BVHRaycaster<IntT>::m_faces; private: /** * @brief Initializes OpenCL related stuff */ void initOpenCL(); /** * @brief TODO */ void getDeviceInformation(); /** * @brief TODO docu */ void initOpenCLTreeBuffer(); /** * @brief TODO */ // void initOpenCLRayBuffer( // int num_origins, // int num_rays); void initOpenCLBuffer( size_t num_origins, size_t num_dirs ); /** * @brief TODO */ void copyBVHToGPU(); /** * @brief TODO */ void createKernel(); // /** // * @brief TODO // */ // void copyRayDataToGPU( // const vector<float>& origins, // const vector<float>& rays // ); // /** // * @brief TODO // */ // void copyRayDataToGPU( // const float* origin_buffer, size_t origin_buffer_size, // const float* ray_buffer, size_t ray_buffer_size // ); // Member vars // OpenCL Device information cl_uint m_mps; cl_uint m_threads_per_block; size_t m_max_work_group_size; size_t m_warp_size; cl_ulong m_device_global_memory; // OpenCL variables cl::Platform m_platform; cl::Device m_device; cl::Context m_context; cl::Program m_program; cl::CommandQueue m_queue; cl::Kernel m_kernel_one_one; cl::Kernel m_kernel_one_multi; cl::Kernel m_kernel_multi_multi; /// BUFFER /// // buffer bvh tree cl::Buffer m_bvhIndicesOrTriListsBuffer; cl::Buffer m_bvhLimitsnBuffer; cl::Buffer m_bvhTriangleIntersectionDataBuffer; cl::Buffer m_bvhTriIdxListBuffer; // buffer rays cl::Buffer m_rayBuffer; cl::Buffer m_rayOriginBuffer; // buffer results cl::Buffer m_resultBuffer; // cl::Buffer m_resultHitsBuffer; }; } // namespace lvr2 #include "CLRaycaster.tcc" #endif // LVR2_ALGORITHM_RAYCASTING_CLRAYCASTER
79b7ab6625fdf98f743dfe83ab4de4751de33346
9af6753b03f7857a0f5583ee477e84d893ba578d
/Project Linked List/LinkedList.cpp
9acb7d79d5b8eea1b66a93a82e98ab266509f417
[]
no_license
WittySkates/COP3503-Programming-2
3033e370018ab4cf7b7a86c6544ccde28bb45041
193dcb129ef09cbb21597cf9fa6cf29284eaabc4
refs/heads/master
2022-12-04T07:25:58.110234
2020-08-31T23:26:45
2020-08-31T23:26:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
46
cpp
LinkedList.cpp
#include "LinkedList.h" #include <iostream>
09d907f5786ccfd07a3af4855d73f333fb0c4c37
1b3959b25ca0b5053c45f2df5b0427102e5862ed
/CGJProject/CGJProject/src/Shader/ShaderProgram.cpp
2884f45ffcdb43cbde30ef3a289b24c1566b2e95
[ "MIT" ]
permissive
goncasmage1/OpenGL
c97cfdb1d0c88bab9e31edcdfa763e3529a230a2
3eaeb94d4a6d41d48e7d84af74bbef9ee083bd84
refs/heads/master
2021-06-27T10:02:32.537045
2020-10-13T11:47:44
2020-10-13T11:47:44
150,716,612
2
0
null
null
null
null
UTF-8
C++
false
false
2,310
cpp
ShaderProgram.cpp
#include "ShaderProgram.h" #include "Shader.h" #define VERTICES 0 #define COLORS 1 /////////////////////// // ShaderAttribute /////////////////////// ShaderAttribute::ShaderAttribute(int newIndex, const GLchar * newName) : index(newIndex), name(newName) { } /////////////////////// // ShaderProgram /////////////////////// ShaderProgram::ShaderProgram() { std::vector<ShaderAttribute> shaderAttributes = { ShaderAttribute(0, "in_Position"), ShaderAttribute(1, "in_Coordinates"), ShaderAttribute(2, "in_Normal") }; std::vector<std::string> shaderPaths = { "src/Shader/GLSL/WhiteShader.glsl", "src/Shader/GLSL/FragmentShader.glsl" }; BuildShader(shaderAttributes, shaderPaths); } ShaderProgram::ShaderProgram(const std::vector<ShaderAttribute> Attributes, const std::vector<std::string> ShaderPaths) { BuildShader(Attributes, ShaderPaths); } void ShaderProgram::BuildShader(const std::vector<ShaderAttribute> Attributes, const std::vector<std::string> ShaderPaths) { size_t NumOfShaders = ShaderPaths.size(); std::vector<Shader> shaders; std::vector<GLenum> shaderTypes = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER }; int i = 0; for (i = 0; i < NumOfShaders; i++) shaders.push_back(Shader(ShaderPaths[i], shaderTypes[i])); ProgramId = glCreateProgram(); for (i = 0; i < NumOfShaders; i++) shaders[i].Attach(ProgramId); for (ShaderAttribute attr : Attributes) glBindAttribLocation(ProgramId, attr.index, attr.name); glLinkProgram(ProgramId); CheckLinkage(); glUniformBlockBinding(ProgramId, GetUboId("SharedMatrices"), UBO_BP); for (i = 0; i < NumOfShaders; i++) shaders[i].DetachAndDelete(ProgramId); } void ShaderProgram::CheckLinkage() { GLint linked; glGetProgramiv(ProgramId, GL_LINK_STATUS, &linked); if (linked == GL_FALSE) { GLint length; glGetProgramiv(ProgramId, GL_INFO_LOG_LENGTH, &length); GLchar* const log = new char[length]; glGetProgramInfoLog(ProgramId, length, &length, log); std::cerr << "[LINK] " << std::endl << log << std::endl; delete log; } } void ShaderProgram::Use() { glUseProgram(ProgramId); if (glGetUniformLocation(ProgramId, "plane")) { glUniform4f(glGetUniformLocation(ProgramId, "plane"), plane.x, plane.y, plane.z, plane.w); } } void ShaderProgram::Destroy() { glUseProgram(0); glDeleteProgram(ProgramId); }
1866c30e562f61470d6182f9c3a0826ba79bb368
96fcd26ec8852682e2ffa7b78a92e430df81bb1e
/programmers/42577.cc
65bd59663c0f37a0112a1a741bf4ba47862bc464
[]
no_license
harang90/algorithm
c3a945f097c842d575cfe2058df04005b895e1da
4088893550d2b80387457ab8bcffd42ff3e581e5
refs/heads/master
2020-09-13T04:41:43.189385
2020-04-20T12:30:39
2020-04-20T12:30:39
222,657,186
1
0
null
null
null
null
UTF-8
C++
false
false
869
cc
42577.cc
#include <iostream> // 전화번호 목록 // 접두어 #include <string> #include <vector> #include <algorithm> using namespace std; // if first should come before second return true bool compare(const string& a, const string& b) { auto iterA = a.begin(); auto iterB = b.begin(); do { if (*iterA > *iterB) return false; else if (*iterA < *iterB) return true; iterA++; iterB++; if (iterA == a.end()) return true; if (iterB == b.end()) return false; } while (1); } bool solution(vector<string> phone_book) { bool answer = true; sort(phone_book.begin(), phone_book.end(), compare); for (auto i = phone_book.begin(); i != phone_book.end() - 1; i++) { if ((i+1)->substr(0, i->length()).compare(*i) == 0) return false; } return true; } int main() { vector<string> phone_book{"123", "456", "789"}; cout << solution(phone_book) << "\n"; }
77576eacae94552545677ec42170f78de00d5968
0e280a7139d175aa6bf7c910cbb0e2e011943975
/helloworld/Classes/Heroscene.cpp
fcbf77dd2fa0cd85b85cef0b307b04ecfaf5efdb
[]
no_license
yc111348/-
848f0834cbe39f25d29943246283929a3ec3bc1a
286e77dafd7476b32637751afc8aba34b870de5a
refs/heads/master
2020-05-25T03:48:16.380904
2019-06-17T16:00:12
2019-06-17T16:00:12
187,612,313
2
1
null
2023-03-13T01:30:04
2019-05-20T09:43:18
C++
UTF-8
C++
false
false
86,170
cpp
Heroscene.cpp
// // hero.cpp // yc // // Created by mac on 2019/6/10. // #include "Heroscene.hpp" #include "SimpleAudioEngine.h" #include "EndGameScene.hpp" USING_NS_CC; bool Hero::isKeyPressed(EventKeyboard::KeyCode keyCode) { if(keys[keyCode]) { return true; } else { return false; } } static void problemLoading(const char* filename) { printf("Error while loading: %s\n", filename); printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n"); } Scene* Hero::createScene() { return Hero::create(); } // Print useful error message instead of segfaulting when files are not there. // on "init" you need to initialize your instance bool Hero::init() { ////////////////////////////// // 1. super init first if ( !Scene::init() ) { return false; } Vec2 origin = Director::getInstance()->getVisibleOrigin(); map = TMXTiledMap::create("mapres/map.tmx"); addChild(map,1); auto mapgo = map->getLayer("move"); mapgo->setVisible(false); weaponnum = UserDefault::getInstance()->getIntegerForKey("weapon"); if(weaponnum==1) { bullet = Sprite::create("item/greenball.png"); } if(weaponnum==2) { bullet = Sprite::create("item/fireball.png"); } bullet2 = Sprite::create("item/bullet2.png"); bullet3 = Sprite::create("item/bullet4.png"); bullet4 = Sprite::create("item/bullet3.png"); addChild(bullet,4); addChild(bullet2,4); addChild(bullet3,4); addChild(bullet4,4); bullet->setVisible(false); bullet2->setVisible(false); bullet3->setVisible(false); bullet4->setVisible(false); bullet->setPosition(50,50); bullet2->setPosition(50,50); bullet3->setPosition(50,50); bullet4->setPosition(50,50); bullet3->setScale(0.7,0.7); bullet4->setScale(0.5,0.5); if(weaponnum==2) { bullet->setScale(0.3,0.3); } // 获取地图属性 // auto mapProperties = map->getProperties(); // //地图名字本身的属性 // auto str=mapProperties["type"].asString(); // log("属性是%s",str.c_str()); // // //获取图层属性 // auto scenelayer=map->getLayer("scene"); // //先找到图层 // auto layerp=scenelayer->getProperties(); // //找到图层的属性 // log("属性是%s",layerp["type"].asString().c_str()); // //找到对应的属性,用数组的方式输出 // // // //获取对象属性 // auto obje = map->getObjectGroup("ob"); // //获取对象组 // auto obj=obje->getObject("juxing1"); // //修改颜色 // auto color=obje->getObject("juxing1"); // auto colorx=color["x"].asFloat(); // auto colory=color["y"].asFloat(); // auto colorw=color["width"].asInt()/8; // auto colorh=color["height"].asInt()/8; // // for(int x=colorx;x<colorx+colorw;x++) // { // for(int y=colory;y<colorh+colory;y++) // { //// auto sprite=scenelayer->getTileAt(Vec2(map->getMapSize().width-x,map->getMapSize().height-y)); // auto sprite=scenelayer->getTileAt(Vec2(x=colorx,colory)); // sprite->setColor(Color3B(255,0,0)); // } // } //武器属性 if(weaponnum==1) { hero_speed=3; hero_shecheng=250; hero_blood=0; } if(weaponnum==2) { hero_speed=5; hero_shecheng=200; hero_blood=0; } //结束 // add a label shows "Hello World" // create and initialize a label int heronum = UserDefault::getInstance()->getIntegerForKey("hero"); // //1.读取素材文件 SpriteFrameCache* cache3 = SpriteFrameCache::getInstance(); cache3->addSpriteFramesWithFile("hero1/waklleft1.plist"); //从plist中加载图片信息 SpriteFrameCache* cache2 = SpriteFrameCache::getInstance(); cache2->addSpriteFramesWithFile("hero1/walkback1.plist"); //从plist中加载图片信息 SpriteFrameCache* cache1 = SpriteFrameCache::getInstance(); cache1->addSpriteFramesWithFile("hero1/walkfront1.plist"); //从plist中加载图片信息 SpriteFrameCache* cache4 = SpriteFrameCache::getInstance(); cache4->addSpriteFramesWithFile("hero1/walkright1.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache3 = SpriteFrameCache::getInstance(); s_cache3->addSpriteFramesWithFile("hero1/standleft1.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache2 = SpriteFrameCache::getInstance(); s_cache2->addSpriteFramesWithFile("hero1/standback1.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache1 = SpriteFrameCache::getInstance(); s_cache1->addSpriteFramesWithFile("hero1/standfront1.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache4 = SpriteFrameCache::getInstance(); s_cache4->addSpriteFramesWithFile("hero1/standright1.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy_cache3 = SpriteFrameCache::getInstance(); enemy_cache3->addSpriteFramesWithFile("A monster/monsterwalkleft.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy_cache2 = SpriteFrameCache::getInstance(); enemy_cache2->addSpriteFramesWithFile("A monster/monsterwalkfront.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy_cache1 = SpriteFrameCache::getInstance(); enemy_cache1->addSpriteFramesWithFile("A monster/monsterwalkback.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy_cache4 = SpriteFrameCache::getInstance(); enemy_cache4->addSpriteFramesWithFile("A monster/monsterwalkright.plist"); //从plist中加载图片信息 //怪物2素材 SpriteFrameCache* enemy2_cache3 = SpriteFrameCache::getInstance(); enemy2_cache3->addSpriteFramesWithFile("monster2/mon1walkleft.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy2_cache2 = SpriteFrameCache::getInstance(); enemy2_cache2->addSpriteFramesWithFile("monster2/mon1walkfront.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy2_cache1 = SpriteFrameCache::getInstance(); enemy2_cache1->addSpriteFramesWithFile("monster2/mon1walkback.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy2_cache4 = SpriteFrameCache::getInstance(); enemy2_cache4->addSpriteFramesWithFile("monster2/mon1walkright.plist"); //从plist中加载图片信息 //结束 //角色2的素材 SpriteFrameCache* cache7 = SpriteFrameCache::getInstance(); cache7->addSpriteFramesWithFile("hero2/walkleft2.plist"); //从plist中加载图片信息 SpriteFrameCache* cache6 = SpriteFrameCache::getInstance(); cache6->addSpriteFramesWithFile("hero2/walkback2.plist"); //从plist中加载图片信息 SpriteFrameCache* cache5 = SpriteFrameCache::getInstance(); cache5->addSpriteFramesWithFile("hero2/walkfront2.plist"); //从plist中加载图片信息 SpriteFrameCache* cache8 = SpriteFrameCache::getInstance(); cache8->addSpriteFramesWithFile("hero2/walkright2.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache7 = SpriteFrameCache::getInstance(); s_cache7->addSpriteFramesWithFile("hero2/standleft2.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache6 = SpriteFrameCache::getInstance(); s_cache6->addSpriteFramesWithFile("hero2/standback2.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache5 = SpriteFrameCache::getInstance(); s_cache5->addSpriteFramesWithFile("hero2/standfront2.plist"); //从plist中加载图片信息 SpriteFrameCache* s_cache8 = SpriteFrameCache::getInstance(); s_cache8->addSpriteFramesWithFile("hero2/standright2.plist"); //从plist中加载图片信息 //结束 //怪物3素材 SpriteFrameCache* enemy3_cache3 = SpriteFrameCache::getInstance(); enemy3_cache3->addSpriteFramesWithFile("monster3/mon2walkleft.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy3_cache2 = SpriteFrameCache::getInstance(); enemy3_cache2->addSpriteFramesWithFile("monster3/mon2walkfront.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy3_cache1 = SpriteFrameCache::getInstance(); enemy3_cache1->addSpriteFramesWithFile("monster3/mon2walkback.plist"); //从plist中加载图片信息 SpriteFrameCache* enemy3_cache4 = SpriteFrameCache::getInstance(); enemy3_cache4->addSpriteFramesWithFile("monster3/mon2walkright.plist"); //从plist中加载图片信息 //结束 //2.创建逐帧数组 //front if(heronum==1) { char str1[100] = {0}; for (int i = 1231; i<1240; i++) { sprintf(str1, "%d.png", i); SpriteFrame* pFrame1 = cache1->getSpriteFrameByName(str1); animFrames1.pushBack(pFrame1); } //back char str2[100] = {0}; for (int i = 1131; i<1140; i++) { sprintf(str2, "%d.png", i); SpriteFrame* pFrame2 = cache2->getSpriteFrameByName(str2); animFrames2.pushBack(pFrame2); } //left char str3[100] = {0}; for (int i = 1331; i<1340; i++) { sprintf(str3, "%d.png", i); SpriteFrame* pFrame3 = cache3->getSpriteFrameByName(str3); animFrames3.pushBack(pFrame3); } //right char str4[100] = {0}; for (int i = 1431; i<1440; i++) { sprintf(str4, "%d.png", i); SpriteFrame* pFrame4 = cache4->getSpriteFrameByName(str4); animFrames4.pushBack(pFrame4); } char s_str1[100] = {0}; for (int i = 1211; i<1219; i++) { sprintf(s_str1, "%d.png", i); SpriteFrame* s_pFrame1 = s_cache1->getSpriteFrameByName(s_str1); s_animFrames1.pushBack(s_pFrame1); } char s_str2[100] = {0}; for (int i = 1111; i<1119; i++) { sprintf(s_str2, "%d.png", i); SpriteFrame* s_pFrame2 = s_cache2->getSpriteFrameByName(s_str2); s_animFrames2.pushBack(s_pFrame2); } char s_str3[100] = {0}; for (int i = 1311; i<1319; i++) { sprintf(s_str3, "%d.png", i); SpriteFrame* s_pFrame3 = s_cache3->getSpriteFrameByName(s_str3); s_animFrames3.pushBack(s_pFrame3); } char s_str4[100] = {0}; for (int i = 1411; i<1419; i++) { sprintf(s_str4, "%d.png", i); SpriteFrame* s_pFrame4 = s_cache4->getSpriteFrameByName(s_str4); s_animFrames4.pushBack(s_pFrame4); } } if(heronum==2) { char str1[100] = {0}; for (int i = 2231; i<2240; i++) { sprintf(str1, "%d.png", i); SpriteFrame* pFrame1 = cache5->getSpriteFrameByName(str1); animFrames1.pushBack(pFrame1); } //back char str2[100] = {0}; for (int i = 2131; i<2140; i++) { sprintf(str2, "%d.png", i); SpriteFrame* pFrame2 = cache6->getSpriteFrameByName(str2); animFrames2.pushBack(pFrame2); } //left char str3[100] = {0}; for (int i = 2331; i<2340; i++) { sprintf(str3, "%d.png", i); SpriteFrame* pFrame3 = cache7->getSpriteFrameByName(str3); animFrames3.pushBack(pFrame3); } //right char str4[100] = {0}; for (int i = 2431; i<2440; i++) { sprintf(str4, "%d.png", i); SpriteFrame* pFrame4 = cache8->getSpriteFrameByName(str4); animFrames4.pushBack(pFrame4); } char s_str1[100] = {0}; for (int i = 2211; i<2219; i++) { sprintf(s_str1, "%d.png", i); SpriteFrame* s_pFrame1 = s_cache5->getSpriteFrameByName(s_str1); s_animFrames1.pushBack(s_pFrame1); } char s_str2[100] = {0}; for (int i = 2111; i<2119; i++) { sprintf(s_str2, "%d.png", i); SpriteFrame* s_pFrame2 = s_cache6->getSpriteFrameByName(s_str2); s_animFrames2.pushBack(s_pFrame2); } char s_str3[100] = {0}; for (int i = 2311; i<2319; i++) { sprintf(s_str3, "%d.png", i); SpriteFrame* s_pFrame3 = s_cache7->getSpriteFrameByName(s_str3); s_animFrames3.pushBack(s_pFrame3); } char s_str4[100] = {0}; for (int i = 2411; i<2419; i++) { sprintf(s_str4, "%d.png", i); SpriteFrame* s_pFrame4 = s_cache8->getSpriteFrameByName(s_str4); s_animFrames4.pushBack(s_pFrame4); } } char enemy_str1[100] = {0}; for (int i = 4001; i<4009; i++) { sprintf(enemy_str1, "%d.png", i); SpriteFrame* enemy_pFrame1 = enemy_cache1->getSpriteFrameByName(enemy_str1); enemy_animFrames1.pushBack(enemy_pFrame1); } char enemy_str2[100] = {0}; for (int i = 1001; i<1009; i++) { sprintf(enemy_str2, "%d.png", i); SpriteFrame* enemy_pFrame2 = enemy_cache2->getSpriteFrameByName(enemy_str2); enemy_animFrames2.pushBack(enemy_pFrame2); } char enemy_str3[100] = {0}; for (int i = 3001; i<3009; i++) { sprintf(enemy_str3, "%d.png", i); SpriteFrame* enemy_pFrame3 = enemy_cache3->getSpriteFrameByName(enemy_str3); enemy_animFrames3.pushBack(enemy_pFrame3); } char enemy_str4[100] = {0}; for (int i = 2001; i<2009; i++) { sprintf(enemy_str4, "%d.png", i); SpriteFrame* enemy_pFrame4 = enemy_cache4->getSpriteFrameByName(enemy_str4); enemy_animFrames4.pushBack(enemy_pFrame4); } //怪物2 char enemy2_str1[100] = {0}; for (int i = 14001; i<14009; i++) { sprintf(enemy2_str1, "%d.png", i); SpriteFrame* enemy2_pFrame1 = enemy2_cache1->getSpriteFrameByName(enemy2_str1); enemy2_animFrames1.pushBack(enemy2_pFrame1); } char enemy2_str2[100] = {0}; for (int i = 11001; i<11009; i++) { sprintf(enemy2_str2, "%d.png", i); SpriteFrame* enemy2_pFrame2 = enemy2_cache2->getSpriteFrameByName(enemy2_str2); enemy2_animFrames2.pushBack(enemy2_pFrame2); } char enemy2_str3[100] = {0}; for (int i = 13001; i<13009; i++) { sprintf(enemy2_str3, "%d.png", i); SpriteFrame* enemy2_pFrame3 = enemy2_cache3->getSpriteFrameByName(enemy2_str3); enemy2_animFrames3.pushBack(enemy2_pFrame3); } char enemy2_str4[100] = {0}; for (int i = 12001; i<12009; i++) { sprintf(enemy2_str4, "%d.png", i); SpriteFrame* enemy2_pFrame4 = enemy2_cache4->getSpriteFrameByName(enemy2_str4); enemy2_animFrames4.pushBack(enemy2_pFrame4); } //结束 //怪物3 char enemy3_str1[100] = {0}; for (int i = 24001; i<24009; i++) { sprintf(enemy3_str1, "%d.png", i); SpriteFrame* enemy3_pFrame1 = enemy3_cache1->getSpriteFrameByName(enemy3_str1); enemy3_animFrames1.pushBack(enemy3_pFrame1); } char enemy3_str2[100] = {0}; for (int i = 21001; i<21009; i++) { sprintf(enemy3_str2, "%d.png", i); SpriteFrame* enemy3_pFrame2 = enemy3_cache2->getSpriteFrameByName(enemy3_str2); enemy3_animFrames2.pushBack(enemy3_pFrame2); } char enemy3_str3[100] = {0}; for (int i = 23001; i<23009; i++) { sprintf(enemy3_str3, "%d.png", i); SpriteFrame* enemy3_pFrame3 = enemy3_cache3->getSpriteFrameByName(enemy3_str3); enemy3_animFrames3.pushBack(enemy3_pFrame3); } char enemy3_str4[100] = {0}; for (int i = 22001; i<22009; i++) { sprintf(enemy3_str4, "%d.png", i); SpriteFrame* enemy3_pFrame4 = enemy3_cache4->getSpriteFrameByName(enemy3_str4); enemy3_animFrames4.pushBack(enemy3_pFrame4); } //结束 //3.设置起始帧 if(heronum==1) { hero = Sprite::createWithSpriteFrameName("1231.png"); } if(heronum==2) { hero = Sprite::createWithSpriteFrameName("2231.png"); } addChild(hero,2); hero->setPosition(500,500); auto s_animation1 = Animation::createWithSpriteFrames(s_animFrames1, 0.3); hero->runAction(RepeatForever::create(Animate::create(s_animation1))); //测试动画 //--------------------加入用户昵称------------------// std::string name = UserDefault::getInstance()->getStringForKey("Username"); auto username = Label::createWithTTF(name,"fonts/chicken.ttf" , 20); username -> setColor(Color3B(0,0,0)); username -> setPosition(hero_x+315,hero_y+450); hero -> addChild(username,100); //--------------------结 束-------------------// //4.执行动画 // s_animation1 = Animation::createWithSpriteFrames(s_animFrames1, 0.3); // hero->runAction(RepeatForever::create(Animate::create(s_animation1))); //测试动画 // animation1 = Animation::createWithSpriteFrames(animFrames1, 0.3); // hero->runAction(RepeatForever::create(Animate::create(animation1))); //测试动画 // animation2 = Animation::createWithSpriteFrames(animFrames2, 0.3); // hero->runAction(RepeatForever::create(Animate::create(animation2))); //测试动画 auto listener = EventListenerKeyboard::create(); listener->onKeyPressed = [=](EventKeyboard::KeyCode keyCode, Event* event){ keys[keyCode] = true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); listener->onKeyReleased = [=](EventKeyboard::KeyCode keyCode, Event* event){ keys[keyCode] = false; }; this->scheduleUpdate(); //道具 // auto shoes = Sprite::create("shoes.png"); // addChild(shoes,3); // shoes->setScale(0.5); // shoes->setPosition(visibleSize.width/2,visibleSize.height/2); //结束 //结束 //血条消失术 m_pProgressView = new ProgressView(); m_pProgressView->setScale(1,0.5); m_pProgressView->setPosition(hero_x+315,hero_y+430); m_pProgressView->setBackgroundTexture("item/noblood.png"); m_pProgressView->setForegroundTexture("item/heroblood.png"); m_pProgressView->setTotalProgress(100.0f); m_pProgressView->setCurrentProgress(100.0f); hero -> addChild(m_pProgressView,1); hero_blood=100; //结束 //子弹发射术 auto listenermouse = EventListenerTouchOneByOne::create();// listenermouse->onTouchBegan = CC_CALLBACK_2(Hero::touch,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listenermouse, this); //结束 auto listeners = EventListenerTouchOneByOne::create(); listeners->onTouchBegan = [=](Touch *t, Event *e){ return true; }; //-------------------实时积分------------------// ranklist = Label::createWithTTF("积分:", "fonts/chicken.ttf", 40); ranklist -> setColor(Color3B(255,69,0)); addChild(ranklist,10); scorettf = Label::createWithTTF("0", "fonts/chicken.ttf", 40); scorettf -> setColor(Color3B(255,69,0)); addChild(scorettf,10); //-------------------结 束-------------------// //-------------------死亡文字------------------// deadttf = Label::createWithTTF("游戏结束!", "fonts/chicken.ttf", 70); deadttf -> setColor(Color3B(255,69,0)); deadttf -> setVisible(false); addChild(deadttf,10); //-------------------结 束------------------// return true; } void Hero::menuCloseCallback(Ref* pSender) { //Close the cocos2d-x game scene and quit the application Director::getInstance()->end(); /*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() as given above,instead trigger a custom event created in RootViewController.mm as below*/ //EventCustom customEndEvent("game_scene_close_event"); //_eventDispatcher->dispatchEvent(&customEndEvent); } void Hero::update(float delta) { enemyforup(); enemy2forup(); enemy3forup(); time+=1; if( (!bulletinwall)&&(isbullet) ) { couldbulletgo(); } heropos= hero->getPosition(); hero_x = hero->getPositionX(); hero_y = hero->getPositionY(); Node::update(delta); auto leftArrow = EventKeyboard::KeyCode::KEY_A, rightArrow = EventKeyboard::KeyCode::KEY_D,upArrow = EventKeyboard::KeyCode::KEY_W,downArrow = EventKeyboard::KeyCode::KEY_S; if(isKeyPressed(leftArrow)) { keyPressedDuration(leftArrow); } else if(isKeyPressed(rightArrow)) { keyPressedDuration(rightArrow); } else if(isKeyPressed(upArrow)) { keyPressedDuration(upArrow); } else if(isKeyPressed(downArrow)) { keyPressedDuration(downArrow); } if((!isKeyPressed(leftArrow))&&(!isKeyPressed(rightArrow))&&(!isKeyPressed(upArrow))&&(!isKeyPressed(downArrow))) { if(before==1) { hero->stopAllActions(); auto s_animation1 = Animation::createWithSpriteFrames(s_animFrames1, 0.3); hero->runAction(RepeatForever::create(Animate::create(s_animation1))); //测试动画 } if(before==2) { hero->stopAllActions(); auto s_animation2 = Animation::createWithSpriteFrames(s_animFrames2, 0.3); hero->runAction(RepeatForever::create(Animate::create(s_animation2))); //测试动画 } if(before==3) { hero->stopAllActions(); auto s_animation3 = Animation::createWithSpriteFrames(s_animFrames3, 0.3); hero->runAction(RepeatForever::create(Animate::create(s_animation3))); //测试动画 } if(before==4) { hero->stopAllActions(); auto s_animation4 = Animation::createWithSpriteFrames(s_animFrames4, 0.3); hero->runAction(RepeatForever::create(Animate::create(s_animation4))); //测试动画 } before=-1; } auto vsize = Director::getInstance()->getVisibleSize(); auto mapTN=map->getMapSize(); auto tiledSize = map->getTileSize(); auto mapsize = Size(mapTN.width*tiledSize.width,mapTN.height*tiledSize.height); auto hpos=hero->getPosition(); auto x = MAX(hpos.x,vsize.width/2); auto y = MAX(hpos.y,vsize.height/2); x = MIN(x,mapsize.width-vsize.width/2); y = MIN(y,mapsize.height-vsize.height/2); auto destpos=Vec2(x,y); auto centerpos = Vec2(vsize.width/2,vsize.height/2); viewpos = centerpos - destpos; this -> setPosition(viewpos); popif(1); popif(2); popif(3); popif(4); popif(5); popif(6); if(time==itemtime) { itemtimecoming(); itemtime+=300; } itempop(); //----------排行榜位置-------------// ranklist -> setPosition(-viewpos.x+100,-viewpos.y+700); scorettf -> setPosition(-viewpos.x+200,-viewpos.y+700); scorettf -> setString(__String::createWithFormat("%i",score)->getCString()); //----------结 束-------------// //----------死亡 文字-------------// deadttf -> setPosition(-viewpos.x+500, -viewpos.y+400); if(ifendgame == 1) { auto * listenerEndGame = EventListenerTouchOneByOne::create(); listenerEndGame->onTouchBegan = [this](Touch * touch,Event * event) { Director::getInstance()->replaceScene(TransitionProgressInOut::create(0.5, EndGameScene::createScene())); return false; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listenerEndGame,this); this->unscheduleUpdate(); } //----------结 束-------------// } void Hero::keyPressedDuration(EventKeyboard::KeyCode code) { float offsetX = 0, offsetY = 0; switch (code) { case EventKeyboard::KeyCode::KEY_A: dirchange(3); if(couldgo(3)) { offsetX = -hero_speed; } break; case EventKeyboard::KeyCode::KEY_W: dirchange(2); if(couldgo(2)) { offsetY = hero_speed; } break; case EventKeyboard::KeyCode::KEY_S: dirchange(1); if(couldgo(1)) { offsetY = -hero_speed; } break; case EventKeyboard::KeyCode::KEY_D: dirchange(4); if(couldgo(4)) { offsetX = hero_speed; } break; default: offsetY = offsetX = 0; break; } auto moveTo = MoveTo::create(0.01, Vec2(hero->getPositionX() + offsetX, hero->getPositionY() + offsetY)); hero->runAction(moveTo); } bool Hero::touch(Touch * touch,Event *event) { if(isbullet==0 && !ifendgame) { auto visiblesize = Director::getInstance()->getVisibleSize(); Point pt = touch->getLocation(); pt = Director::getInstance()->convertToGL(pt); pt.x = pt.x - viewpos.x; pt.y = pt.y + viewpos.y; point_x = pt.x; point_y = pt.y; float deltx,delty; deltx = point_x - hero_x; delty = visiblesize.height - point_y - hero_y; float delta = sqrt(deltx*deltx + delty*delty); float ex = deltx/delta; float ey = delty/delta; bullet->setPosition(hero_x, hero_y); bullet->setVisible(true); auto fire = MoveBy::create(0.3,Vec2(hero_shecheng*ex,hero_shecheng*ey)); isbullet=1; auto callbackfunc = [=]() { isbullet=0; bullet->setVisible(false); bullet->setPosition(50,50); }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(fire,DelayTime::create(0.15),callFunc,NULL); bullet->runAction(actions); } return true; } void Hero::dirchange(int dir) { if(dir!=before) { before=dir; if(dir==1) { hero->stopAllActions(); auto animation1 = Animation::createWithSpriteFrames(animFrames1, 0.15); hero->runAction(RepeatForever::create(Animate::create(animation1))); //测试动画 } if(dir==2) { hero->stopAllActions(); auto animation2 = Animation::createWithSpriteFrames(animFrames2, 0.15); hero->runAction(RepeatForever::create(Animate::create(animation2))); //测试动画 } if(dir==3) { hero->stopAllActions(); auto animation3 = Animation::createWithSpriteFrames(animFrames3, 0.15); hero->runAction(RepeatForever::create(Animate::create(animation3))); //测试动画 } if(dir==4) { hero->stopAllActions(); auto animation4 = Animation::createWithSpriteFrames(animFrames4, 0.15); hero->runAction(RepeatForever::create(Animate::create(animation4))); //测试动画 } } } Point Hero::positiontrans(cocos2d::Point pos) { auto mapTiledNum = map->getMapSize(); auto tiledSize = map->getTileSize(); float x = pos.x/tiledSize.width; float y=(2880-pos.y)/tiledSize.height; if(x>0) { x-=1; } if(y>0) { y-=0; } return Point(x,y); } bool Hero::couldgo(int direction) { Point temp=Point(0,0); Point herotemp=Point(0,0); if(direction==1) { temp=Point(1,1); } if(direction==2) { temp=Point(1,-1); } if(direction==3) { temp=Point(0,0); } if(direction==4) { temp=Point(2,0); } auto maplayer = map->getLayer("move"); Point pos=positiontrans(heropos); int tiledID = maplayer -> getTileGIDAt(pos+temp); if(tiledID==0) { return true; } if(tiledID!=0) { return false; } else { return true; } } void Hero::couldbulletgo() { Point pos=positiontrans(bullet->getPosition()); int tiledID = map->getLayer("move")-> getTileGIDAt(pos); if(tiledID) { bulletinwall=1; bullet->stopAllActions(); bulletinenemy=0; auto callbackfunc = [=]() { isbullet=0; bullet->setVisible(false); bullet->setPosition(Director::getInstance()->getVisibleSize().width/2,Director::getInstance()->getVisibleSize().height/2); isbullet=0; bulletinwall=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet->runAction(actions); } } void Hero::enemycoming() { enemy= Sprite::createWithSpriteFrameName("1001.png"); addChild(enemy,2); enemy->setPosition(getenemypos()); auto enemy_animation1 = Animation::createWithSpriteFrames(enemy_animFrames1, 0.3); enemy->runAction(RepeatForever::create(Animate::create(enemy_animation1))); //测试动画 enemylive=1; enemyblood=100; if(enemy_speed<=30) { enemy_speed+=2; } if(enemy_shesu>=50) { enemy_shesu-=10; } if(enemy_gongjili<=50) { enemy_gongjili+=5; } if(enemy_shecheng<=600) { enemy_shecheng+=30; } enemy_x = enemy->getPositionX(); enemy_y=enemy->getPositionY(); enemy_pProgressView = new ProgressView(); enemy_pProgressView->setScale(1,0.5); enemy_pProgressView->setPosition(330,450); enemy_pProgressView->setBackgroundTexture("item/noblood.png"); enemy_pProgressView->setForegroundTexture("item/fullblood.png"); enemy_pProgressView->setTotalProgress(100.0f); enemy_pProgressView->setCurrentProgress(100.0f); enemy -> addChild(enemy_pProgressView,5); } void Hero::enemymove() { getenemydirection(1); int i = enemydirection; for(;;) { if(canenemygo(i)) { break; } i = random(1, 4); } switch (i) { case 1: { enemy->stopAllActions(); auto enemy_animation1 = Animation::createWithSpriteFrames(enemy_animFrames1, 0.3); enemy->runAction(RepeatForever::create(Animate::create(enemy_animation1))); //测试动画 auto moveby=MoveBy::create(0.3,Point(0,-enemy_speed)); enemy->runAction(moveby); break; } case 2: { enemy->stopAllActions(); auto enemy_animation2 = Animation::createWithSpriteFrames(enemy_animFrames2, 0.3); enemy->runAction(RepeatForever::create(Animate::create(enemy_animation2))); //测试动画 auto moveby=MoveBy::create(0.3,Point(0,enemy_speed)); enemy->runAction(moveby); break; } case 3: { enemy->stopAllActions(); auto enemy_animation3 = Animation::createWithSpriteFrames(enemy_animFrames3, 0.3); enemy->runAction(RepeatForever::create(Animate::create(enemy_animation3))); //测试动画 auto moveby=MoveBy::create(0.3,Point(-enemy_speed,0)); enemy->runAction(moveby); break; } case 4: { enemy->stopAllActions(); auto enemy_animation4 = Animation::createWithSpriteFrames(enemy_animFrames4, 0.3); enemy->runAction(RepeatForever::create(Animate::create(enemy_animation4))); //测试动画 auto moveby=MoveBy::create(0.3,Point(enemy_speed,0)); enemy->runAction(moveby); break; } } } bool Hero::canenemygo(int direction) { Point temp=Point(0,0); Point enemytemp=Point(0,0); if(direction==1) { temp=Point(1,1); } if(direction==2) { temp=Point(1,-3); } if(direction==3) { temp=Point(0,-2); } if(direction==4) { temp=Point(3,0); } auto maplayer = map->getLayer("move"); Point pos=positiontrans(enemy->getPosition()); int tiledID = maplayer -> getTileGIDAt(pos+temp); // if( ( (enemy->getPositionX ()) < (enemy2->getPositionX() ) ) // && ( (enemy2->getPositionX()) < (enemy->getPositionX ()+60) ) // && ( (enemy->getPositionY()) < (enemy2->getPositionY () ) ) // && ( (enemy2->getPositionY())< (enemy->getPositionY ()+80) ) ) // { // tiledID = 1 ; // } if(tiledID==0) { return true; } else { return false; } } void Hero::popif(int whobeatwho) { if(whobeatwho==1) { if( (!bullet2inhero)&&(bullet2inair) ) { if(((hero->getPositionX()-20) < (bullet2->getPositionX())) && ( (bullet2->getPositionX())< (hero->getPositionX()+60) ) &&((hero->getPositionY()) < (bullet2->getPositionY())) && ( (bullet2->getPositionY())< (hero->getPositionY()+80) ) ) { popgo(1); } } } if(whobeatwho==2) { if( (!bulletinenemy)&&enemylive&&isbullet) { if(((enemy->getPositionX()-20) < (bullet->getPositionX())) && ( (bullet->getPositionX())< (enemy->getPositionX()+85) ) &&((enemy->getPositionY()) < (bullet->getPositionY())) && ( (bullet->getPositionY())< (enemy->getPositionY()+128) ) ) { popgo(2); } } } if(whobeatwho==3) { if( (!bullet3inhero)&&(bullet3inair) ) { if(((hero->getPositionX()-20) < (bullet3->getPositionX())) && ( (bullet3->getPositionX())< (hero->getPositionX()+60) ) &&((hero->getPositionY()) < (bullet3->getPositionY())) && ( (bullet3->getPositionY())< (hero->getPositionY()+80) ) ) { popgo(3); } } } if(whobeatwho==4) { if( (!bulletinenemy)&&enemy2live&&isbullet) { if(((enemy2->getPositionX()-20) < (bullet->getPositionX())) && ( (bullet->getPositionX())< (enemy2->getPositionX()+85) ) &&((enemy2->getPositionY()) < (bullet->getPositionY())) && ( (bullet->getPositionY())< (enemy2->getPositionY()+128) ) ) { popgo(4); } } } if(whobeatwho==5) { if( (!bullet4inhero)&&(bullet4inair) ) { if(((hero->getPositionX()-20) < (bullet4->getPositionX())) && ( (bullet4->getPositionX())< (hero->getPositionX()+60) ) &&((hero->getPositionY()) < (bullet4->getPositionY())) && ( (bullet4->getPositionY())< (hero->getPositionY()+80) ) ) { popgo(5); } } } if(whobeatwho==6) { if( (!bulletinenemy)&&enemy3live&&isbullet) { if(((enemy3->getPositionX()-20) < (bullet->getPositionX())) && ( (bullet->getPositionX())< (enemy3->getPositionX()+85) ) &&((enemy3->getPositionY()) < (bullet->getPositionY())) && ( (bullet->getPositionY())< (enemy3->getPositionY()+128) ) ) { popgo(6); } } } } void Hero::popgo(int whogodie) { if(whogodie==1) { hero_blood-=enemy_gongjili; bullet2inhero=1; bullet2->stopAllActions(); m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()-enemy_gongjili); auto callbackfunc = [=]() { bullet2inair=0; bullet2->setVisible(false); bullet2->setPosition(50,50); bullet2inhero=0; }; auto callFunc= CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet2->runAction(actions); if(hero_blood<=0) { gotodie(1); } } if(whogodie==2) { enemyblood-=10; bulletinenemy=1; bullet->stopAllActions(); enemy_pProgressView->setCurrentProgress(enemy_pProgressView->getCurrentProgress()-10);//更改血量 score += 10; auto callbackfunc = [=]() { isbullet=0; bullet->setVisible(false); bullet->setPosition(50,50); bulletinenemy=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet->runAction(actions); if(enemyblood<=0) { score += 50; gotodie(2); } } if(whogodie==3) { hero_blood-=enemy2_gongjili; bullet3inhero=1; bullet3->stopAllActions(); m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()-enemy2_gongjili); auto callbackfunc = [=]() { bullet3inair=0; bullet3->setVisible(false); bullet3->setPosition(50,50); bullet3inhero=0; }; auto callFunc= CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet3->runAction(actions); if(hero_blood<=0) { gotodie(1); } } if(whogodie==4) { enemy2blood-=10; bulletinenemy=1; bullet->stopAllActions(); enemy2_pProgressView->setCurrentProgress(enemy2_pProgressView->getCurrentProgress()-10);//更改血量 score += 10; auto callbackfunc = [=]() { isbullet=0; bullet->setVisible(false); bullet->setPosition(50,50); bulletinenemy=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet->runAction(actions); if(enemy2blood<=0) { score += 50; gotodie(3); } } if(whogodie==5) { hero_blood-=enemy3_gongjili; bullet4inhero=1; bullet4->stopAllActions(); m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()-enemy3_gongjili); auto callbackfunc = [=]() { bullet4inair=0; bullet4->setVisible(false); bullet4->setPosition(50,50); bullet4inhero=0; }; auto callFunc= CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet4->runAction(actions); if(hero_blood<=0) { gotodie(1); } } if(whogodie==6) { enemy3blood-=10; bulletinenemy=1; bullet->stopAllActions(); enemy3_pProgressView->setCurrentProgress(enemy3_pProgressView->getCurrentProgress()-10);//更改血量 score += 10; auto callbackfunc = [=]() { isbullet=0; bullet->setVisible(false); bullet->setPosition(50,50); bulletinenemy=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet->runAction(actions); if(enemy3blood<=0) { score += 50; gotodie(4); } } } void Hero::gotodie(int who) { if(who==1) { UserDefault::getInstance()->setIntegerForKey("score", score); auto callbackfunc1 = [=]() { deadttf -> setVisible(true); }; auto callbackfunc2 = [=]() { deadttf -> setVisible(false); }; auto callbackfunc3 = [=]() { ifendgame = 1; }; hero->stopAllActions(); auto callfunc3=CallFunc::create(callbackfunc3); auto callFunc1=CallFunc::create(callbackfunc1); auto callFunc2=CallFunc::create(callbackfunc2); auto actions = Sequence::create(callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,callfunc3,NULL); deadttf->runAction(actions); } if(who==2) { enemylive = 0; auto callbackfunc1 = [=]() { enemy->setVisible(false); }; auto callbackfunc2 = [=]() { enemy->setVisible(true); }; auto callbackfunc3 = [=]() { bullet2->setVisible(false); bullet2->setPosition(50,50); enemy->setPosition(250,250); enemy->removeFromParent(); }; enemy->stopAllActions(); auto callFunc1=CallFunc::create(callbackfunc1); auto callFunc2=CallFunc::create(callbackfunc2); auto callFunc3=CallFunc::create(callbackfunc3); auto actions = Sequence::create(callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,callFunc3,NULL); enemy->runAction(actions); enemytime = time + 300; } if(who==3) { enemy2live = 0; auto callbackfunc1 = [=]() { enemy2->setVisible(false); }; auto callbackfunc2 = [=]() { enemy2->setVisible(true); }; auto callbackfunc3 = [=]() { bullet3->setVisible(false); bullet3->setPosition(50,50); enemy2->setPosition(250,250); enemy2->removeFromParent(); }; enemy2->stopAllActions(); auto callFunc1=CallFunc::create(callbackfunc1); auto callFunc2=CallFunc::create(callbackfunc2); auto callFunc3=CallFunc::create(callbackfunc3); auto actions = Sequence::create(callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,callFunc3,NULL); enemy2->runAction(actions); enemy2time = time + 300; } if(who==4) { enemy3live = 0; auto callbackfunc1 = [=]() { enemy3->setVisible(false); }; auto callbackfunc2 = [=]() { enemy3->setVisible(true); }; auto callbackfunc3 = [=]() { bullet4->setVisible(false); bullet4->setPosition(50,50); enemy3->setPosition(250,250); enemy3->removeFromParent(); }; enemy3->stopAllActions(); auto callFunc1=CallFunc::create(callbackfunc1); auto callFunc2=CallFunc::create(callbackfunc2); auto callFunc3=CallFunc::create(callbackfunc3); auto actions = Sequence::create(callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,DelayTime::create(0.2),callFunc2,DelayTime::create(0.2),callFunc1,callFunc3,NULL); enemy3->runAction(actions); enemy3time = time + 300; } } void Hero::getenemydirection(int enemycode) { if(enemycode==1) { if((enemy_x-hero_x)>=0) { if((enemy_y-hero_y)>=0) { if((enemy_y-hero_y)>=(enemy_x-hero_x)) { enemydirection=1; } else { enemydirection=3; } } if((enemy_y-hero_y)<0) { if((hero_y-enemy_y)>=(enemy_x-hero_x)) { enemydirection=2; } else { enemydirection=3; } } } if((enemy_x-hero_x)<0) { if((enemy_y-hero_y)>0) { if((hero_x-enemy_x)>=(enemy_y-hero_y)) { enemydirection=4; } else { enemydirection=1; } } if((enemy_y-hero_y)<0) { if((hero_x-enemy_x)>=(hero_y-enemy_y)) { enemydirection=4; } else { enemydirection=2; } } } } } void Hero::enemyattack() { bullet2->setVisible(true); float deltx,delty; deltx = enemy_x - hero_x; delty = enemy_y - hero_y; float delta = sqrt(deltx*deltx + delty*delty); float ex = deltx/delta; float ey = delty/delta; int n = enemy_shecheng;//shecheng bullet2->setPosition(enemy_x, enemy_y); bullet2->setVisible(true); bullet2inair=1; auto fire = MoveBy::create(0.3,Vec2(-n*ex,-n*ey)); auto callbackfunc = [=]() { bullet2->setVisible(false); bullet2->setPosition(50,50); bullet2inair=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(fire,DelayTime::create(0.15),callFunc,NULL); bullet2->runAction(actions); } void Hero::itemtimecoming() { for(int i=1;i<11;i++) { if(isitemlive[i]==0) { if(i==1) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item1 = Sprite::create("item/shoes.png"); item1->setPosition(pos); addChild(item1,5); item1->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item1 = Sprite::create("item/healthpotion.png"); item1->setPosition(pos); addChild(item1,5); item1->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item1 = Sprite::create("item/attackboost.png"); item1->setPosition(pos); addChild(item1,5); item1->setScale(0.5,0.5); } break; } if(i==2) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item2 = Sprite::create("item/shoes.png"); item2->setPosition(pos); addChild(item2,5); item2->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item2 = Sprite::create("item/healthpotion.png"); item2->setPosition(pos); addChild(item2,5); item2->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item2 = Sprite::create("item/attackboost.png"); item2->setPosition(pos); addChild(item2,5); item2->setScale(0.5,0.5); } break; } if(i==3) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item3 = Sprite::create("item/shoes.png"); item3->setPosition(pos); addChild(item3,5); item3->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item3 = Sprite::create("item/healthpotion.png"); item3->setPosition(pos); addChild(item3,5); item3->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item3 = Sprite::create("item/attackboost.png"); item3->setPosition(pos); addChild(item3,5); item3->setScale(0.5,0.5); } break; } if(i==4) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item4 = Sprite::create("item/shoes.png"); item4->setPosition(pos); addChild(item4,5); item4->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item4 = Sprite::create("item/healthpotion.png"); item4->setPosition(pos); addChild(item4,5); item4->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item4 = Sprite::create("item/attackboost.png"); item4->setPosition(pos); addChild(item4,5); item4->setScale(0.5,0.5); } break; } if(i==5) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item5 = Sprite::create("item/shoes.png"); item5->setPosition(pos); addChild(item5,5); item5->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item5 = Sprite::create("item/healthpotion.png"); item5->setPosition(pos); addChild(item5,5); item5->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item5 = Sprite::create("item/attackboost.png"); item5->setPosition(pos); addChild(item5,5); item5->setScale(0.5,0.5); } break; } if(i==6) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item6 = Sprite::create("item/shoes.png"); item6->setPosition(pos); addChild(item6,5); item6->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item6 = Sprite::create("item/healthpotion.png"); item6->setPosition(pos); addChild(item6,5); item6->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item6 = Sprite::create("item/attackboost.png"); item6->setPosition(pos); addChild(item6,5); item6->setScale(0.5,0.5); } break; } if(i==7) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item7 = Sprite::create("item/shoes.png"); item7->setPosition(pos); addChild(item7,5); item7->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item7 = Sprite::create("item/healthpotion.png"); item7->setPosition(pos); addChild(item7,5); item7->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item7 = Sprite::create("item/attackboost.png"); item7->setPosition(pos); addChild(item7,5); item7->setScale(0.5,0.5); } break; } if(i==8) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item8 = Sprite::create("item/shoes.png"); item8->setPosition(pos); addChild(item8,5); item8->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item8 = Sprite::create("item/healthpotion.png"); item8->setPosition(pos); addChild(item8,5); item8->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item8 = Sprite::create("item/attackboost.png"); item8->setPosition(pos); addChild(item8,5); item8->setScale(0.5,0.5); } break; } if(i==9) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item9 = Sprite::create("item/shoes.png"); item9->setPosition(pos); addChild(item9,5); item9->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item9 = Sprite::create("item/healthpotion.png"); item9->setPosition(pos); addChild(item9,5); item9->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item9 = Sprite::create("item/attackboost.png"); item9->setPosition(pos); addChild(item9,5); item9->setScale(0.5,0.5); } break; } if(i==10) { auto pos = getitemcreatpos(); int ran = random(1, 10); log(" %d is %f %f",i,pos.x,pos.y); if(ran<4) { isitemlive[i]=1; item10 = Sprite::create("item/shoes.png"); item10->setPosition(pos); addChild(item10,5); item10->setScale(0.5,0.5); } else if(ran<8) { isitemlive[i]=2; item10 = Sprite::create("item/healthpotion.png"); item10->setPosition(pos); addChild(item10,5); item10->setScale(0.2,0.2); } else if(ran<11) { isitemlive[i]=3; item10 = Sprite::create("item/attackboost.png"); item10->setPosition(pos); addChild(item10,5); item10->setScale(0.5,0.5); } break; } } } } Point Hero::getitemcreatpos() { float x=0,y=0; for(;;) { x=random(350 , 3500); y=random(350 , 2500); Point pos=positiontrans(Point(x+30,y+30)); if( !(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x+1,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y+1))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x-1,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y-1))) ) { break; } } return Point(x,y); } void Hero::itempop() { for(int i=1;i<11;i++) { if(isitemlive[i]) { if(i==1) { if( ( ( hero_x < item1->getPosition().x+50 ) && ( hero_x+90 > item1->getPosition().x+50 ) && ( hero_y < item1->getPosition().y+35 ) && ( hero_y+90 > item1->getPosition().y+35 ) ) ) { item1->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==2) { if(( hero_x < item2->getPosition().x+50 ) && ( hero_x+90 > item2->getPosition().x+50 ) && ( hero_y < item2->getPosition().y+35 ) && ( hero_y+90 > item2->getPosition().y+35 ) ) { item2->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==3) { if(( hero_x < item3->getPosition().x+50 ) && ( hero_x+90 > item3->getPosition().x+50 ) && ( hero_y < item3->getPosition().y+35 ) && ( hero_y+90 > item3->getPosition().y+35 ) ) { item3->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==4) { if(( hero_x < item4->getPosition().x+50 ) && ( hero_x+90 > item4->getPosition().x+50 ) && ( hero_y < item4->getPosition().y+35 ) && ( hero_y+90 > item4->getPosition().y+35 ) ) { item4->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==5) { if(( hero_x < item5->getPosition().x+50 ) && ( hero_x+90 > item5->getPosition().x+50 ) && ( hero_y < item5->getPosition().y+35 ) && ( hero_y+90 > item5->getPosition().y+35 ) ) { item5->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==6) { if(( hero_x < item6->getPosition().x+50 ) && ( hero_x+90 > item6->getPosition().x+50 ) && ( hero_y < item6->getPosition().y+35 ) && ( hero_y+90 > item6->getPosition().y+35 ) ) { item6->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==7) { if(( hero_x < item7->getPosition().x+50 ) && ( hero_x+90 > item7->getPosition().x+50 ) && ( hero_y < item7->getPosition().y+35 ) && ( hero_y+90 > item7->getPosition().y+35 ) ) { item7->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==8) { if(( hero_x < item8->getPosition().x+50 ) && ( hero_x+90 > item8->getPosition().x+50 ) && ( hero_y < item8->getPosition().y+35 ) && ( hero_y+90 > item8->getPosition().y+35 ) ) { item8->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==9) { if(( hero_x < item9->getPosition().x+50 ) && ( hero_x+90 > item9->getPosition().x+50 ) && ( hero_y < item9->getPosition().y+35 ) && ( hero_y+90 > item9->getPosition().y+35 ) ) { item9->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } if(i==10) { if(( hero_x < item10->getPosition().x+50 ) && ( hero_x+90 > item10->getPosition().x+50 ) && ( hero_y < item10->getPosition().y+35 ) && ( hero_y+90 > item10->getPosition().y+35 ) ) { item10->removeFromParent(); if(isitemlive[i]==1&&hero_speed<=10) { hero_speed+=0.5; } if(isitemlive[i]==2&&hero_blood<100) { int n=100-hero_blood; if(n>30) { n = 30; } m_pProgressView->setCurrentProgress(m_pProgressView->getCurrentProgress()+n); hero_blood+=n; } if(isitemlive[i]==3) { if(hero_shecheng<400) { hero_shecheng+=15; }; } isitemlive[i]=0; } } } } } void Hero::enemyforup() { if(time==enemytime&&!enemylive) { enemycoming(); enemymovetime=enemytime; enemyacktime=enemytime; } if(enemylive) { enemy_x = enemy->getPositionX(); enemy_y = enemy->getPositionY(); if(time==enemymovetime) { enemymove(); enemymovetime+=18; } if(time==enemyacktime) { enemyattack(); enemyacktime+=enemy_shesu; } } if( (bullet2inair) &&(!bullet2inwall) ) { couldbullet2go(); } } void Hero::couldbullet2go() { Point pos=positiontrans(bullet2->getPosition()); int tiledID = map->getLayer("move")->getTileGIDAt(pos); if(tiledID) { bullet2inwall=1; bullet2->stopAllActions(); auto callbackfunc = [=]() { bullet2inair=0; bullet2->setVisible(false); bullet2->setPosition(50,50); bullet2inwall=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions=Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet2->runAction(actions); } } Point Hero::getenemypos() { float x=0,y=0; for(;;) { x = random(500 , 3200); y = random(500 , 2000); Point pos = positiontrans(Point(x+30,y+30)); if( !(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x+3,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y+3))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x-3,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y-3))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x+2,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y+2))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x-2,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y-2))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x+1,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y+1))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x-1,pos.y))) &&!(map->getLayer("move")-> getTileGIDAt(Point(pos.x,pos.y-1))) ) { break; } } return Point(x,y); } void Hero::enemy2coming() { enemy2= Sprite::createWithSpriteFrameName("11001.png"); addChild(enemy2,2); enemy2->setPosition(getenemypos()); auto enemy2_animation1 = Animation::createWithSpriteFrames(enemy2_animFrames1, 0.3); enemy2->runAction(RepeatForever::create(Animate::create(enemy2_animation1))); //测试动画 enemy2live=1; enemy2blood=100; if(enemy2_speed<=30) { enemy2_speed+=2; } if(enemy2_shesu>=50) { enemy2_shesu-=10; } if(enemy2_gongjili<=50) { enemy2_gongjili+=5; } if(enemy2_shecheng<=600) { enemy2_shecheng+=30; } enemy2_x=enemy2->getPositionX(); enemy2_y=enemy2->getPositionY(); enemy2_pProgressView = new ProgressView(); enemy2_pProgressView->setScale(1,0.5); enemy2_pProgressView->setPosition(330,450); enemy2_pProgressView->setBackgroundTexture("item/noblood.png"); enemy2_pProgressView->setForegroundTexture("item/fullblood.png"); enemy2_pProgressView->setTotalProgress(100.0f); enemy2_pProgressView->setCurrentProgress(100.0f); enemy2->addChild(enemy2_pProgressView,5); } void Hero::enemy2forup() { if(time==enemy2time&&!enemy2live) { enemy2coming(); enemy2movetime=enemy2time; enemy2acktime=enemy2time; } if(enemy2live) { enemy2_x = enemy2->getPositionX(); enemy2_y = enemy2->getPositionY(); if(time==enemy2movetime) { enemy2move(); enemy2movetime+=18; } if(time==enemy2acktime+15) { enemy2attack(); enemy2acktime+=enemy2_shesu; } } if( (bullet3inair) &&(!bullet3inwall) ) { couldbullet3go(); } } void Hero::enemy2move() { getenemy2direction(1); int i = enemy2direction; for(;;) { if(canenemy2go(i)) { break; } i = random(1, 4); } switch (i) { case 1: { enemy2->stopAllActions(); auto enemy2_animation1 = Animation::createWithSpriteFrames(enemy2_animFrames1, 0.3); enemy2->runAction(RepeatForever::create(Animate::create(enemy2_animation1))); //测试动画 auto moveby=MoveBy::create(0.3,Point(0,-enemy2_speed)); enemy2->runAction(moveby); break; } case 2: { enemy2->stopAllActions(); auto enemy2_animation2 = Animation::createWithSpriteFrames(enemy2_animFrames2, 0.3); enemy2->runAction(RepeatForever::create(Animate::create(enemy2_animation2))); //测试动画 auto moveby=MoveBy::create(0.3,Point(0,enemy2_speed)); enemy2->runAction(moveby); break; } case 3: { enemy2->stopAllActions(); auto enemy2_animation3 = Animation::createWithSpriteFrames(enemy2_animFrames3, 0.3); enemy2->runAction(RepeatForever::create(Animate::create(enemy2_animation3))); //测试动画 auto moveby=MoveBy::create(0.3,Point(-enemy2_speed,0)); enemy2->runAction(moveby); break; } case 4: { enemy2->stopAllActions(); auto enemy2_animation4 = Animation::createWithSpriteFrames(enemy2_animFrames4, 0.3); enemy2->runAction(RepeatForever::create(Animate::create(enemy2_animation4))); //测试动画 auto moveby=MoveBy::create(0.3,Point(enemy2_speed,0)); enemy2->runAction(moveby); break; } } } void Hero::enemy2attack() { bullet3->setVisible(true); float deltx,delty; deltx = enemy2_x - hero_x; delty = enemy2_y - hero_y; float delta = sqrt(deltx*deltx + delty*delty); float ex = deltx/delta; float ey = delty/delta; int n = enemy2_shecheng;//shecheng bullet3->setPosition(enemy2_x, enemy2_y); bullet3->setVisible(true); bullet3inair=1; auto fire = MoveBy::create(0.3,Vec2(-n*ex,-n*ey)); auto callbackfunc = [=]() { bullet3->setVisible(false); bullet3->setPosition(50,50); bullet3inair=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(fire,DelayTime::create(0.15),callFunc,NULL); bullet3->runAction(actions); } void Hero::couldbullet3go() { Point pos=positiontrans(bullet3->getPosition()); int tiledID = map->getLayer("move")->getTileGIDAt(pos); if(tiledID) { bullet3inwall=1; bullet3->stopAllActions(); auto callbackfunc = [=]() { bullet3inair=0; bullet3->setVisible(false); bullet3->setPosition(50,50); bullet3inwall=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions=Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet3->runAction(actions); } } bool Hero::canenemy2go(int direction) { Point temp=Point(0,0); Point enemy2temp=Point(0,0); if(direction==1) { temp=Point(1,1); } if(direction==2) { temp=Point(1,-3); } if(direction==3) { temp=Point(0,-2); } if(direction==4) { temp=Point(3,0); } auto maplayer = map->getLayer("move"); Point pos=positiontrans(enemy2->getPosition()); int tiledID = maplayer -> getTileGIDAt(pos+temp); // if( ( (enemy2->getPositionX ()) < (enemy3->getPositionX () ) ) // && ( (enemy3->getPositionX() ) < (enemy2->getPositionX ()+60) ) // && ( (enemy2->getPositionY() ) < (enemy3->getPositionY () ) ) // && ( (enemy3->getPositionY() ) < (enemy2->getPositionY ()+80) ) ) // { // tiledID = 1 ; // } if(tiledID==0) { return true; } else if(tiledID!=0) { return false; } } void Hero::getenemy2direction(int enemy2code) { if(enemy2code==1) { if((enemy2_x-hero_x)>=0) { if((enemy2_y-hero_y)>=0) { if((enemy2_y-hero_y)>=(enemy2_x-hero_x)) { enemy2direction=1; } else { enemy2direction=3; } } if((enemy2_y-hero_y)<0) { if((hero_y-enemy2_y)>=(enemy2_x-hero_x)) { enemy2direction=2; } else { enemy2direction=3; } } } if((enemy2_x-hero_x)<0) { if((enemy2_y-hero_y)>0) { if((hero_x-enemy2_x)>=(enemy2_y-hero_y)) { enemy2direction=4; } else { enemy2direction=1; } } if((enemy2_y-hero_y)<0) { if((hero_x-enemy2_x)>=(hero_y-enemy2_y)) { enemy2direction=4; } else { enemy2direction=2; } } } } } //enemy3 void Hero::enemy3coming() { enemy3= Sprite::createWithSpriteFrameName("11001.png"); addChild(enemy3,2); enemy3->setPosition(getenemypos()); auto enemy3_animation1 = Animation::createWithSpriteFrames(enemy3_animFrames1, 0.3); enemy3->runAction(RepeatForever::create(Animate::create(enemy3_animation1))); //测试动画 enemy3live=1; enemy3blood=100; if(enemy3_speed<=30) { enemy3_speed+=2; } if(enemy3_shesu>=50) { enemy3_shesu-=10; } if(enemy3_gongjili<=50) { enemy3_gongjili+=5; } if(enemy3_shecheng<=600) { enemy3_shecheng+=30; } enemy3_x=enemy3->getPositionX(); enemy3_y=enemy3->getPositionY(); enemy3_pProgressView = new ProgressView(); enemy3_pProgressView->setScale(1,0.5); enemy3_pProgressView->setPosition(330,450); enemy3_pProgressView->setBackgroundTexture("item/noblood.png"); enemy3_pProgressView->setForegroundTexture("item/fullblood.png"); enemy3_pProgressView->setTotalProgress(100.0f); enemy3_pProgressView->setCurrentProgress(100.0f); enemy3->addChild(enemy3_pProgressView,5); } void Hero::enemy3forup() { if(time==enemy3time&&!enemy3live) { enemy3coming(); enemy3movetime=enemy3time; enemy3acktime=enemy3time; } if(enemy3live) { enemy3_x = enemy3->getPositionX(); enemy3_y = enemy3->getPositionY(); if(time==enemy3movetime) { enemy3move(); enemy3movetime+=18; } if(time==enemy3acktime+30) { enemy3attack(); enemy3acktime+=enemy3_shesu; } } if( (bullet4inair) &&(!bullet4inwall) ) { couldbullet4go(); } } void Hero::enemy3move() { getenemy3direction(1); int i = enemy3direction; for(;;) { if(canenemy3go(i)) { break; } i = random(1, 4); } switch (i) { case 1: { enemy3->stopAllActions(); auto enemy3_animation1 = Animation::createWithSpriteFrames(enemy3_animFrames1, 0.3); enemy3->runAction(RepeatForever::create(Animate::create(enemy3_animation1))); //测试动画 auto moveby=MoveBy::create(0.3,Point(0,-enemy3_speed)); enemy3->runAction(moveby); break; } case 2: { enemy3->stopAllActions(); auto enemy3_animation2 = Animation::createWithSpriteFrames(enemy3_animFrames2, 0.3); enemy3->runAction(RepeatForever::create(Animate::create(enemy3_animation2))); //测试动画 auto moveby=MoveBy::create(0.3,Point(0,enemy3_speed)); enemy3->runAction(moveby); break; } case 3: { enemy3->stopAllActions(); auto enemy3_animation3 = Animation::createWithSpriteFrames(enemy3_animFrames3, 0.3); enemy3->runAction(RepeatForever::create(Animate::create(enemy3_animation3))); //测试动画 auto moveby=MoveBy::create(0.3,Point(-enemy3_speed,0)); enemy3->runAction(moveby); break; } case 4: { enemy3->stopAllActions(); auto enemy3_animation4 = Animation::createWithSpriteFrames(enemy3_animFrames4, 0.3); enemy3->runAction(RepeatForever::create(Animate::create(enemy3_animation4))); //测试动画 auto moveby=MoveBy::create(0.3,Point(enemy3_speed,0)); enemy3->runAction(moveby); break; } } } void Hero::enemy3attack() { bullet4->setVisible(true); float deltx,delty; deltx = enemy3_x - hero_x; delty = enemy3_y - hero_y; float delta = sqrt(deltx*deltx + delty*delty); float ex = deltx/delta; float ey = delty/delta; int n = enemy3_shecheng;//shecheng bullet4->setPosition(enemy3_x, enemy3_y); bullet4->setVisible(true); bullet4inair=1; auto fire = MoveBy::create(0.3,Vec2(-n*ex,-n*ey)); auto callbackfunc = [=]() { bullet4->setVisible(false); bullet4->setPosition(50,50); bullet4inair=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions = Sequence::create(fire,DelayTime::create(0.15),callFunc,NULL); bullet4->runAction(actions); } void Hero::couldbullet4go() { Point pos=positiontrans(bullet4->getPosition()); int tiledID = map->getLayer("move")->getTileGIDAt(pos); if(tiledID) { bullet4inwall=1; bullet4->stopAllActions(); auto callbackfunc = [=]() { bullet4inair=0; bullet4->setVisible(false); bullet4->setPosition(50,50); bullet4inwall=0; }; auto callFunc=CallFunc::create(callbackfunc); auto actions=Sequence::create(DelayTime::create(0.15),callFunc,NULL); bullet4->runAction(actions); } } bool Hero::canenemy3go(int direction) { Point temp=Point(0,0); Point enemy3temp=Point(0,0); if(direction==1) { temp=Point(1,1); } if(direction==2) { temp=Point(1,-3); } if(direction==3) { temp=Point(0,-2); } if(direction==4) { temp=Point(3,0); } auto maplayer = map->getLayer("move"); Point pos=positiontrans(enemy3->getPosition()); int tiledID = maplayer -> getTileGIDAt(pos+temp); // if( ( (enemy3->getPositionX ()) < (enemy->getPositionX () ) ) // && ( (enemy->getPositionX() ) < (enemy3->getPositionX ()+60) ) // && ( (enemy3->getPositionY() ) < (enemy->getPositionY () ) ) // && ( (enemy->getPositionY() ) < (enemy3->getPositionY ()+80) ) ) // { // tiledID = 1 ; // } if(tiledID==0) { return true; } else if(tiledID!=0) { return false; } } void Hero::getenemy3direction(int enemy3code) { if(enemy3code==1) { if((enemy3_x-hero_x)>=0) { if((enemy3_y-hero_y)>=0) { if((enemy3_y-hero_y)>=(enemy3_x-hero_x)) { enemy3direction=1; } else { enemy3direction=3; } } if((enemy3_y-hero_y)<0) { if((hero_y-enemy3_y)>=(enemy3_x-hero_x)) { enemy3direction=2; } else { enemy3direction=3; } } } if((enemy3_x-hero_x)<0) { if((enemy3_y-hero_y)>0) { if((hero_x-enemy3_x)>=(enemy3_y-hero_y)) { enemy3direction=4; } else { enemy3direction=1; } } if((enemy3_y-hero_y)<0) { if((hero_x-enemy3_x)>=(hero_y-enemy3_y)) { enemy3direction=4; } else { enemy3direction=2; } } } } } //end
06942639f71edf21e263a99be0a8c13cc20f6367
33cf18fe652ce3cd697bf27aa4ddffe6f4e71e1c
/main.cpp
73327d39215256ccf08729a1748ea0d26526e551
[]
no_license
ievau99/CppLietuviskai
a390682861ee8bbcba85eb68c3dbdaa04196ef79
f0eab98151e3a9154514efa2223f9800de095e74
refs/heads/master
2023-03-22T19:09:40.853289
2021-03-23T14:13:59
2021-03-23T14:13:59
349,104,555
0
0
null
null
null
null
UTF-8
C++
false
false
751
cpp
main.cpp
//Studentas ruošiasi įsigyti naują kompiuterį. Apie kompiuterio kainą jis samprotauja taip: // //- jeigu kompiuteris pigesnis nei 1000 Eur, tai jis pernelyg pigus; //- jeigu kompiuteris brangesnis nei 2500 Eur, tai jis pernelyg brangus; //- jeigu kompiuterio kaina nuo 1000 iki 2500 Eur, tai jis yra toks, kokį pirkčiau. #include <iostream> using namespace std; int main() { int a; cout << "Iveskite kompiuterio kaina:"; cin >>a; if(a>0 && a<1000) cout <<"Studentui kompiuteris pernelyg pigus"; if(a<=0) cout << "Neteisingai ivesta kaina"; if(a>2500) cout<<"Studentui kompiuteris pernelyg brangus"; if(a>=1000 && a<=2500) cout<<"Studentui kompiuterio kaina tinkama"; return 0; }
dca34dc0d1f524a2ccfa79787c745a336ae1d4a4
7175b03f72d69577f7945793315242d04ba1765c
/dinput8/config.cpp
4727dc39697c3cce9355754fcddb9ea9265761c4
[ "WTFPL" ]
permissive
Stunext/LANVP
6ee9f345423379fa44fcfc32e32e1c68235a5aff
cecabc5cae7048411935a657f0ef72d878fc21a3
refs/heads/master
2023-07-27T12:53:17.711376
2021-09-11T20:14:20
2021-09-11T20:14:20
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
11,243
cpp
config.cpp
//----------------------------------------------------------------------------- // config.cpp // // Releases: // 1.0 - Initial release // 1.1 - "FPS Unlock" & "Aspect Correction" improvements, "Launcher Check", // "Skip Logo&Legals" & "FPS Lock" added, "Force Resolution" bugfix. // 1.1a - Added "Force DX11" option, fixed a bug with force resolution. // // Copyright (c) 2021 Václav AKA Vaana //----------------------------------------------------------------------------- #include "config.h" void Config::Init() { // // Load and parse ini // options = new Options; options->patchEnabled = true; options->fpsUnlock = true; options->aspectCorrection = true; options->fpsLock = 0; options->fovMultiplier = 1.0f; options->skipLauncherCheck = false; options->skipLogos = false; options->forceBorderlessWindow = true; options->forceResolutionWidth = 0; options->forceResolutionHeight = 0; // // Since version 2663, R* has removed 32-bit support, because // the new launcher is 64-bit. However, the game itself is // still 32-bit. Here we detect if an 32-bit OS is running, // and skip the launcher check if it is, to restore support. // // Note: doesn't work as intended options->skipLauncherCheck = !IsSystem32Bit(); // // By default, the game launches in DirectX 9 mode, which offers // worse performance to DirectX 11. This is a problem, especially // since the old launcher was removed, people don't bother // switching to DirectX 11 manually. // The solution is to enforce DX11. First we check if the user // has a Direct3D 11 capable GPU, and if so, we force the game // to use DX11 all the time. // options->forceDx11 = IsD3D11Supported(); // todo: Detect if the user has an unsupported resolution int width, height; if (GetScreenSize(width, height)) { options->forceResolutionWidth = width; options->forceResolutionHeight = height; } if (ini_parse(INI_FILE, Handler, options) < 0 || generateNew) { GenerateConfig(); } } bool Config::IsD3D11Supported() { HMODULE d3d11Lib = LoadLibraryW(L"d3d11"); if (d3d11Lib != NULL) { typedef HRESULT(WINAPI* D3D11CreateDevice_t) (void*, int, HMODULE, UINT, const void*, UINT, UINT, void**, void*, void**); D3D11CreateDevice_t pD3D11CreateDevice; // D3D11CreateDevice must be loaded dynamically, since d3d11.dll // might not exist if the API is not supported. pD3D11CreateDevice = (D3D11CreateDevice_t)GetProcAddress(d3d11Lib, "D3D11CreateDevice"); // HRESULT hr = E_FAIL; // // if (pD3D11CreateDevice != NULL) // { // int featureLevels[] = // { // 0xb000, // D3D_FEATURE_LEVEL_11_0 // 0xa100, // D3D_FEATURE_LEVEL_10_1 // 0xa000 // D3D_FEATURE_LEVEL_10_0 // }; // // int featureLevel = 0xb000; // // hr = pD3D11CreateDevice(NULL, // pAdapter // 1, // D3D_DRIVER_TYPE_SOFTWARE // NULL, // 0 // 2, // 0 // &featureLevels, // &pFeatureLevels // 3, // 3u // 7, // 7u // NULL, // &ppDevice, // &featureLevel, // &pFeatureLevel // NULL); // &ppImmediateContext // } FreeLibrary(d3d11Lib); // if (SUCCEEDED(hr)) if (pD3D11CreateDevice != NULL) { return true; } } return false; } bool Config::IsSystem32Bit() { typedef BOOL(WINAPI* IsWow64Process_t) (HANDLE, PBOOL); IsWow64Process_t pIsWow64Process; BOOL IsWow64 = FALSE; // IsWow64Process must be loaded dynamically, since some older // Windows versions don't have this function available. pIsWow64Process = (IsWow64Process_t)GetProcAddress(GetModuleHandleW(L"kernel32"), "IsWow64Process"); if (pIsWow64Process == NULL || !pIsWow64Process(GetCurrentProcess(), &IsWow64) || !IsWow64) { return false; } return true; } bool Config::GetScreenSize(int& width, int& height) { // // Gather the necessary info to create a new config. // DEVMODEW devMode = { }; devMode.dmSize = sizeof(DEVMODE); devMode.dmDriverExtra = 0; if (EnumDisplaySettingsW(NULL, ENUM_CURRENT_SETTINGS, &devMode)) { width = devMode.dmPelsWidth; height = devMode.dmPelsHeight; return true; } return false; } int Config::Handler(void* user, const char* section, const char* name, const char* value) { #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 #define ERROR(msg) MessageBoxW(NULL, msg, L"[V-Patch] Error while loading config.", MB_OK); Options* pOptions = (Options*)user; // // Determines whether V-Patch is loaded or not. // Setting this value to 0 will disable all subsequent options. // // 1 = enabled (default) // 0 = disabled // if (MATCH("general", "patch_enabled")) { int patchEnabled = atoi(value); if (patchEnabled < 0 || patchEnabled > 1) { ERROR(L"patch_enabled was set to an invalid value. Using defaults..."); return 0; } pOptions->patchEnabled = patchEnabled; } // // Removes the FPS cap and corrects the car braking values. // // If you are unable to progress due to an issue caused by // the unlocked framerate, set this option to 0, pass the // current mission and re-enable the option by setting it to 1. // // 1 = enabled (default) // 0 = disabled // else if (MATCH("patches", "fps_unlock")) { int fpsUnlock = atoi(value); if (fpsUnlock < 0 || fpsUnlock > 1) { ERROR(L"fps_unlock was set to an invalid value. Using defaults..."); return 0; } pOptions->fpsUnlock = fpsUnlock; } // // Removes black bars on aspect ratios slimmer than 16:9 // (16:10, 4:3, 5:4) and corrects the FOV value and // interface size to match the current aspect ratio. // // 1 = enabled (default) // 0 = disabled // else if (MATCH("patches", "aspect_correction")) { int aspectCorrection = atoi(value); if (aspectCorrection < 0 || aspectCorrection > 1) { ERROR(L"aspect_correction was set to an invalid value. Using defaults..."); return 0; } pOptions->aspectCorrection = aspectCorrection; } // // Allows the user to set a custom FPS cap. Useful if // your framerate fluctuates rapidly, making the game // unplayable. This value should not be lower than 30! // fps_unlock must be enabled for this to work! // // 0 = disabled (default) // example: fps_lock=30 // else if (MATCH("options", "fps_lock")) { int fpsLock = atoi(value); if (fpsLock != 0 && fpsLock < 30) { ERROR(L"fps_lock was set to an invalid value. Using defaults..."); return 0; } pOptions->fpsLock = fpsLock; } // // Allows the user to increase/decrease the fov, in case // the game feels too zoomed in/out. It is recommended // that this value does not exceed 2.0! // fov_correction must be enabled for this to work! // // default: 1.0 // else if (MATCH("options", "fov_multiplier")) { float fovMultiplier = atof(value); if (fovMultiplier <= 0.0f) { ERROR(L"fov_multiplier was set to an invalid value. Using defaults..."); return 0; } pOptions->fovMultiplier = fovMultiplier; } // // Skips the intro logos and legal screen which plays // every time the game is launched. Useful for modding. // // 1 = enabled (default) // 0 = disabled // else if (MATCH("options", "skip_launcher_check")) { int skipLauncherCheck = atoi(value); if (skipLauncherCheck < 0 || skipLauncherCheck > 1) { ERROR(L"skip_launcher_check was set to an invalid value. Using defaults..."); return 0; } pOptions->skipLauncherCheck = skipLauncherCheck; } // // Skips the intro logos and legal screen which plays // every time the game is launched. Useful for modding. // // 1 = enabled (default) // 0 = disabled // else if (MATCH("options", "skip_logos")) { int skipLogos = atoi(value); if (skipLogos < 0 || skipLogos > 1) { ERROR(L"skip_logos was set to an invalid value. Using defaults..."); return 0; } pOptions->skipLogos = skipLogos; } // // Enforces DirectX 11 mode for better performance. // Only enabled if the users PC has a Direct3D 11 // capable graphics card. // // 1 = enabled // 0 = disabled // else if (MATCH("options", "force_dx11")) { int forceDx11 = atoi(value); if (forceDx11 < 0 || forceDx11 > 1) { ERROR(L"force_dx11 was set to an invalid value. Using defaults..."); return 0; } pOptions->forceDx11 = forceDx11; } // // Starts the game in borderless window mode. Recommended // for faster switching between applications. // // 1 = enabled (default) // 0 = disabled // else if (MATCH("options", "force_borderless_window")) { int forceBorderlessWindow = atoi(value); if (forceBorderlessWindow < 0 || forceBorderlessWindow > 1) { ERROR(L"force_borderless_window was set to an invalid value. Using defaults..."); return 0; } pOptions->forceBorderlessWindow = forceBorderlessWindow; } // // Allows you to set a custom resolution not supported // by the game, as it is in case of ultrawide resolutions. // // By default, this is set to your current resolution. // Leave this option blank to disable it. // // example: force_resolution=1920x1080 // else if (MATCH("options", "force_resolution")) { int width = atoi(value); const char* fx = (char*)((int)strchr(value, 'x') + 1); if (fx == (char*)(NULL + 1)) return 0; int height = atoi(fx); if (width < 0 || height < 0) return 0; pOptions->forceResolutionWidth = width; pOptions->forceResolutionHeight = height; } else { if (!generateNew) { ERROR(L"Config is invalid. A new config will be generated."); generateNew = true; } return 0; } return 1; } bool Config::GenerateConfig() { #define ERROR(msg) MessageBoxW(NULL, msg, L"[V-Patch] Error while generating config.", MB_OK); // // Fill out template and write to disk. // size_t configSize = sizeof(configTemplate) + 32; char* config = new char[configSize]; size_t bytesWritten = sprintf_s(config, configSize, configTemplate, options->patchEnabled, // patch_enabled options->fpsUnlock, // fps_unlock options->aspectCorrection, // aspect_correction options->fpsLock, // fps_lock options->fovMultiplier, // fov_multiplier options->skipLauncherCheck, // skip_launcher_check options->skipLogos, // skip_logos options->forceDx11, // force_dx11 options->forceBorderlessWindow, // force_borderless_window options->forceResolutionWidth, // force_resolution width options->forceResolutionHeight); // force_resolution heigth if (bytesWritten == -1 || bytesWritten == 0) { ERROR(L"Failed to create a new config. sprintf_s didn't write any characters."); return false; } HANDLE file = CreateFileW(TEXT(INI_FILE), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (file == INVALID_HANDLE_VALUE) { ERROR(L"Failed to create a new config. File handle invalid."); return false; } DWORD fileBytesWritten; if (!WriteFile(file, config, bytesWritten, &fileBytesWritten, nullptr) || fileBytesWritten == 0) { ERROR(L"Failed to create a new config. No bytes written."); return false; } delete[] config; CloseHandle(file); return true; }
bfbaf9e5d801895090f137f47d547be028ead63f
033107c05feff81c17f9f39d984e08f5884863f4
/BarProject/implementations/src/InterpolateEntityPositionAction.h
f997945ff5c43e0c7152e0f36b9e4a3bd36e079b
[]
no_license
ravaliB/SYMA2
7def2f665591a9777f5ca486d23dfafe4e2c1fb6
168118e1426ccc8cc652a55f39883eb93a742375
refs/heads/master
2016-09-05T16:52:00.930854
2014-12-19T13:23:14
2014-12-19T13:23:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,583
h
InterpolateEntityPositionAction.h
#ifndef BARMAN_IMPL_LIB_INTERPOLATEENTITYPOSITIONACTION_H #define BARMAN_IMPL_LIB_INTERPOLATEENTITYPOSITIONACTION_H #include <mlv/behavior/AbstractTypedAction.h> namespace barman { namespace impl_lib { class InterpolateEntityPositionInput : public mlv::utils::StaticObject { MLV_DEFINE_STATIC_OBJECT(barman::impl_lib::InterpolateEntityPositionInput,"79bfc5d7-dc5d-4d8f-ba5f-bbcc5bb52000",setMetadata); public: InterpolateEntityPositionInput(); mlv::utils::String name; //!< The name of the target entity. mlv::utils::Real time; //!< The interpolation time. private: static bool setMetadata( mlv::utils::TypeManager& manager, mlv::utils::AbstractLogger* logger ); }; class InterpolateEntityPositionOutput : public mlv::utils::StaticObject { MLV_DEFINE_STATIC_OBJECT(barman::impl_lib::InterpolateEntityPositionOutput,"9B572FF0-0A86-4B2F-B3C8-2F01389299E9",setMetadata); public: InterpolateEntityPositionOutput(); bool wantToDrink; //!< The target, interpolated, entity position private: static bool setMetadata( mlv::utils::TypeManager& manager, mlv::utils::AbstractLogger* logger ); }; /** ApproachEntity action. */ class InterpolateEntityPositionAction: public mlv::behavior::AbstractTypedAction<InterpolateEntityPositionInput, InterpolateEntityPositionOutput> { public: InterpolateEntityPositionAction(); ~InterpolateEntityPositionAction(); double computeLookAhead(double dist, double speed); private: virtual mlv::behavior::action::Status doStart(mlv::behavior::EntityKnowledgeFacade& entity, mlv::behavior::ActionRequestHandle requestId, const InterpolateEntityPositionInput& input, InterpolateEntityPositionOutput& output); virtual mlv::behavior::action::Status doUpdate(mlv::behavior::EntityKnowledgeFacade& entity, mlv::behavior::ActionRequestHandle requestId, const InterpolateEntityPositionInput& input, InterpolateEntityPositionOutput& output, const mlv::utils::Time& dt); virtual mlv::behavior::action::Status doCancel(mlv::behavior::EntityKnowledgeFacade& entity, mlv::behavior::ActionRequestHandle requestId, const InterpolateEntityPositionInput& input, const mlv::utils::Time& dt); mlv::utils::EntityIndex findEntity(const mlv::behavior::EntityKnowledgeFacade& facade, const char* entityName) const; }; } } #endif
c7611fbd23ebe399371166864955f1e4f935ea9d
efdeb174bc211ce20f5806063d73d6ff7e5610fc
/libs/NotesCApi508/notesapi/samples/basic/capierr/capierrd.h
32328a37ece2f0c31e4ddc7e40c6287ce9be3ec1
[]
no_license
eviskum/MFAQS-notes
c14af2475f1126d9864018d8652e8da654045cd3
9669614b3769fd6b30ed9d60a55ca1dffd9c9bce
refs/heads/master
2023-04-20T07:01:18.887868
2021-05-12T15:49:49
2021-05-12T15:49:49
366,767,342
0
0
null
null
null
null
UTF-8
C++
false
false
970
h
capierrd.h
// CapiErrD.h : header file // ///////////////////////////////////////////////////////////////////////////// // CCapiErrD dialog #define LINEOTEXT 256 class CCapiErrD : public CDialog { // Construction public: CCapiErrD(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CCapiErrD) enum { IDD = IDD_CapiErr_DIALOG }; CString m_errCode; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCapiErrD) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CCapiErrD) virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnDestroy(); afx_msg void OnGetErrorClick(); afx_msg void OnDecClick(); afx_msg void OnHexClick(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
42459bfa4887954254f54492962b99d7ed862d0b
8c39f17ab30d3b65d73136048679c2029446f665
/render2.cpp
3f0c58e5d4b84604a776b956b4aa64ebf7adb589
[]
no_license
giuliomoro/keyfeature
d2d890ca9011ba4d5374da1d175ba270713f37c5
8d35113feb1de64f6dac04371284a4458c9202eb
refs/heads/master
2020-04-18T14:36:10.870062
2019-02-04T20:22:16
2019-02-04T20:26:31
167,593,064
0
0
null
null
null
null
UTF-8
C++
false
false
5,482
cpp
render2.cpp
#include <Bela.h> #include <Keys.h> #include <algorithm> #include <cmath> #include <math_neon.h> #include "KeyboardState.h" extern float gKey; extern float gPos; extern float gGate; extern float gPerc; extern float gAux; #define SCOPE #define SCANNER #define KEYPOSITIONTRACKER #ifdef SCOPE #include <Scope.h> Scope scope; #endif /* SCOPE */ #include <Keys.h> Keys* keys; BoardsTopology bt; int gKeyOffset = 34; int gNumKeys = 38; float gBendingKeyTwoThreshold = 0.3; float gGatePosThresholdOn = 0.5; float gGatePosThresholdOff = 0.1; #ifdef KEYPOSITIONTRACKER #include "KeyPositionTracker.h" #include "KeyboardState.h" KeyboardState keyboardState; KeyBuffers keyBuffers; std::vector<KeyBuffer> keyBuffer; std::vector<KeyPositionTracker> keyPositionTrackers; #endif /* KEYPOSITIONTRACKER */ //#define SINGLE_KEY void Bela_userSettings2(BelaInitSettings* settings) { settings->pruNumber = 0; settings->useDigital = 0; printf("Bela__user_settings2\n"); } void postCallback(void* arg, float* buffer, unsigned int length){ Keys* keys = (Keys*)arg; int firstKey = gKeyOffset; int lastKey = gKeyOffset + gNumKeys + 1; unsigned int key = 46; #ifdef KEYPOSITIONTRACKER static int count; { for(unsigned int n = 0; n < length; ++n) { // INVERTING INPUTS buffer[n] = 1.f - buffer[n]; } keyBuffers.postCallback(buffer, length); for(unsigned int n = 0; n < length; ++n) { if(n >= firstKey && n < lastKey) { #ifdef SINGLE_KEY if(n == key) #endif /* SINGLE_KEY */ keyPositionTrackers[n].triggerReceived(count / 1000.f); } } count++; } keyboardState.render(buffer, keyPositionTrackers, firstKey, lastKey); gKey = keyboardState.getKey() - gKeyOffset + keyboardState.getBend(); gPos = keyboardState.getPosition(); static float lastPerc = 0; float newPerc = keyboardState.getPercussiveness(); if(newPerc != lastPerc && newPerc) { gPerc = newPerc;/// keyboardState.avVel; gPerc *= 10.f; gPerc *= gPerc; rt_printf("%d]oldPerc: %f, newPerc: %f\n", count, newPerc, gPerc); } gPerc *= 0.99f; lastPerc = newPerc; static float prevPos = 0; #ifndef SINGLE_KEY scope.log( buffer[keyboardState.getKey()], //(gKey - key + gKeyOffset) / 8.f, gPos - prevPos, //keyPositionTrackers[key].dynamicOnsetThreshold_, //newPerc, keyPositionTrackers[key].currentState() / (float) kPositionTrackerStateReleaseFinished, 0, 0 ); #endif /* SINGLE_KEY */ prevPos = gPos; if(gPos < 0.13) gPos = 0; //printing { static int count = 0; count++; int newKey = keyboardState.getKey(); int newOtherKey = keyboardState.getOtherKey(); static int oldKey = 0; static int oldOtherKey = 0; if( ((newKey != oldKey && newKey != 0) && (newOtherKey != oldOtherKey && newOtherKey != 0)) ) { if(1) rt_printf("perc: %6.4f, bend: %6.3f (%3d at %6.3f %50s), key: %3d, %6.3f, %s\n", gPerc, keyboardState.getBend(), keyboardState.getOtherKey(), keyboardState.getOtherPosition(), statesDesc[keyPositionTrackers[keyboardState.getOtherKey()].currentState()].c_str(), keyboardState.getKey(), keyboardState.getPosition(), statesDesc[keyPositionTrackers[keyboardState.getKey()].currentState()].c_str() ); count = 0; } oldKey = newKey; oldOtherKey = newOtherKey; } #endif /* KEYPOSITIONTRACKER */ } bool setup2(BelaContext *context, void *userData) { printf("Setup2\n"); #ifdef SCOPE scope.setup(8, 1000); #endif /* SCOPE */ #ifdef SCANNER printf("Setting up scanner\n"); if(context->digitalFrames != 0) { fprintf(stderr, "You should disable digitals and run on PRU 0 for the scanner to work.\n"); return false; } keys = new Keys; bt.setLowestNote(0); bt.setBoard(0, 0, 24); bt.setBoard(1, 0, 23); bt.setBoard(2, 0, 23); #ifdef KEYPOSITIONTRACKER int bottomKey = bt.getLowestNote(); int topKey = bt.getHighestNote(); int numKeys = topKey - bottomKey + 1; keyBuffers.setup(numKeys, 1000); keyBuffer.reserve(numKeys); // avoid reallocation in the loop below for(unsigned int n = 0; n < numKeys; ++n) { keyBuffer.emplace_back( keyBuffers.positionBuffer[n], keyBuffers.timestamps[n], keyBuffers.firstSampleIndex, keyBuffers.writeIdx ); keyPositionTrackers.emplace_back( 10, keyBuffer[n] ); keyPositionTrackers.back().engage(); } keyboardState.setup(numKeys); #endif /* KEYPOSITIONTRACKER */ keys->setPostCallback(postCallback, keys); int ret = keys->start(&bt, NULL); if(ret < 0) { fprintf(stderr, "Error while starting the scan of the keys: %d %s\n", ret, strerror(-ret)); delete keys; keys = NULL; } keys->startTopCalibration(); keys->loadInverseSquareCalibrationFile("/root/out.calib", 0); #endif /* SCANNER */ return true; } unsigned int gSampleCount = 0; void render2(BelaContext *context, void *userData) { float phaseStep = 2.f * (float) M_PI * powf(2, gKey/12.f) * 233.082f / context->audioSampleRate; for(unsigned int n = 0; n < context->audioFrames; ++n) { static float phase = 0; static float amp = 0; float ampSmooth = 0.995; amp = amp * ampSmooth - gPos * (1.f - ampSmooth); static int count = 0; phase += phaseStep; if(phase >= M_PI) phase -= 2.f * (float) M_PI; float out = sinf_neon(phase) * amp * amp * 0.7f + gPerc * random()/(float)RAND_MAX; for(unsigned int ch = 0; ch < context->audioOutChannels; ++ch) { audioWrite(context, n, ch, out); } } } void cleanup2(BelaContext *context, void *userData) { #ifdef SCANNER delete keys; #endif /* SCANNER */ }
5fa0e4392ecfedece6a8718c9396f06451c3d7e1
895e3e10d0669af7d935c89f9f6322e8071bb4b5
/core/pp/core/pp/pp_first_arg.hpp
f2f6cd57c01f313b109b9c9d91834dbef86a65e3
[]
no_license
SlyrisOrg/core-v2
cfece79d1baa392d10d667d3a46974c8126ed9bc
c2c3b13d7bfdb6c65a32b7ada1a75c3dd48b5f1e
refs/heads/master
2021-03-27T13:05:53.803959
2018-04-11T19:52:31
2018-04-11T20:02:22
120,018,498
3
0
null
null
null
null
UTF-8
C++
false
false
338
hpp
pp_first_arg.hpp
// // Created by doom on 03/10/17. // #ifndef CORE_PP_FIRST_ARG_HPP #define CORE_PP_FIRST_ARG_HPP #ifdef _MSC_VER #define __FIRST_ARG_(f, ...) f #define __FIRST_ARG(args) __FIRST_ARG_ args #define pp_first_arg(...) __FIRST_ARG((__VA_ARGS__)) #else #define pp_first_arg(f, ...) f #endif #endif //CORE_PP_FIRST_ARG_HPP
d7acf3ff959879d50ad68568659ea17dc62a9094
b9c4a6bd1788c40f10eeda32bff73b60825a983c
/Linked_Lists_C++/delete_node.cpp
bc8820db0bd8361c4465a7869b6a95313bd9c67d
[]
no_license
Lakshit-Chiranjiv/hacktoberfest2021-4
008c5bfe36906a8f7e3938df8645e7e9c4e42682
8ee733884bc6b172e9242bc90f4c65279df40435
refs/heads/main
2023-08-23T02:06:39.712540
2021-10-19T05:03:29
2021-10-19T05:03:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,380
cpp
delete_node.cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; struct Linkedlist{ ll data; struct Linkedlist *next; }; typedef struct Linkedlist *node; int main() { ll n,i,x,pos; cin>>n; node head,temp,p; head=NULL; //assigning nothing to head node head=(node)malloc(sizeof(struct Linkedlist)); temp=head; for(i=0;i<n;i++) { cin>>x; p=NULL; //assigning nothing to node p; p=(node)malloc(sizeof(struct Linkedlist)); p->data=x; temp->next=p; //assigning next pointer of temp as p temp=temp->next; } temp->next=NULL; //deleting the node at given position.If value is given as input then find if that element exist in list and find it's previous node cin>>pos; //pos of node which should be deleted (node are 1 indexed) i=1; temp=head; //we have taken temp as head and not head->next because, we could have been asked to delete the first node(so node previous to first node is head only) while(i<pos) { temp=temp->next; i++; } //after loop completes we got the pointer previous to node which we want to delete if(temp->next->next==NULL) //if last element is to be deleted { p=temp->next; free(p); temp->next=NULL; } else { p=temp->next; temp->next=p->next; free(p); } head=head->next; while(head!=NULL) //output the created list { cout<<head->data<<" "; head=head->next; } cout<<"\n"; return 0; }
f796ba5635123eb59ba9c54075ab0825ef9d5dd4
c1f4fbdebc8b8ef075d4b34a161b2404d1f5d59d
/Hodograf/Hodograf/Simulation.h
264428faaf5f883d4452d6be4b450a36c5d4b74a
[]
no_license
McThrok/Hodograf
4e20fd9f44ae5506bdb43253e2f352d8cd15e6d8
a002362a2785d1d7d977c30d7ece50e7908f4e2d
refs/heads/master
2022-04-03T07:37:32.164507
2020-01-18T16:44:09
2020-01-18T16:44:09
233,443,790
0
0
null
null
null
null
UTF-8
C++
false
false
758
h
Simulation.h
#pragma once #include <d3d11.h> #include <vector> #include <math.h> #include <DirectXMath.h> #include <SimpleMath.h> #include "Graphics/Vertex.h" #include <random> #include "Graphics/MyImGui.h" using namespace std; using namespace DirectX; using namespace DirectX::SimpleMath; class Simulation { public: float delta_time; float time; bool paused; float simulationSpeed; vector<ImVec2> x; vector<ImVec2> xt; vector<ImVec2> xtt; vector<ImVec2> state; ImVec2 minX, maxX; ImVec2 minXt, maxXt; ImVec2 minXtt, maxXtt; ImVec2 minState, maxState; float omega, L, R, alpha, disturbed_L, e0; int diffOffset = 1; mt19937 gen{ std::random_device{}() }; void DisturbL(); void Init(); void Reset(); void Update(float dt); void Update(); };
77051ae38b93aec280a3222162aad147e4ba05c2
3db48713c39b90d5967615e3d1c874d88055ba70
/tests/std/tests/P0896R4_views_drop_while_death/test.cpp
9cce078838daea873cfff1e72b92942506967969
[ "Apache-2.0", "LLVM-exception", "LicenseRef-scancode-object-form-exception-to-mit", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-mit-old-style", "LicenseRef-scancode-other-permissive", "CC0-1.0", "BSL-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
microsoft/STL
4b1a6a625402e04b857e8dfc3c22efd9bc798f01
6c69a73911b33892919ec628c0ea5bbf0caf8a6a
refs/heads/main
2023-09-04T08:50:17.559497
2023-08-31T16:49:43
2023-08-31T16:49:43
204,593,825
9,862
1,629
NOASSERTION
2023-09-14T21:57:47
2019-08-27T01:31:18
C++
UTF-8
C++
false
false
1,326
cpp
test.cpp
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #define _CONTAINER_DEBUG_LEVEL 1 #include <cassert> #include <cstddef> #include <ranges> #include <span> #include <test_death.hpp> using namespace std; struct test_predicate { struct tag {}; test_predicate() = default; test_predicate(const test_predicate&) { throw tag{}; } test_predicate& operator=(const test_predicate&) = delete; constexpr bool operator()(int i) const { return i == 42; } }; auto with_no_predicate() { using DWV = decltype(ranges::drop_while_view{span<int, 0>{}, test_predicate{}}); DWV r; try { r = DWV{}; } catch (const test_predicate::tag&) { } return r; } void test_view_predicate() { auto r = with_no_predicate(); (void) r.pred(); // drop_while_view has no predicate } void test_view_begin() { auto r = with_no_predicate(); (void) r.begin(); // N4885 [range.drop.while.view] forbids calling begin on a drop_while_view with no predicate } int main(int argc, char* argv[]) { std_testing::death_test_executive exec; exec.add_death_tests({ test_view_predicate, test_view_begin, }); return exec.run(argc, argv); }
729d94e9fe3d814f0e2fe80a884bb60957896e5f
9a56773118def963a564512cd6964feb0417d7e3
/core/source/core/fonts/font_builder.hpp
22cc5e37b9f59f95869643e8eac886c7d6958473
[ "MIT" ]
permissive
Karlashenko/engine-2d
b5a0a8120d02352e72840bfd3ad1aacef68cf9d0
842c67fb6a7f19eaf16550b441ec7b79af2a0b7a
refs/heads/main
2023-04-05T23:22:47.524527
2021-04-20T11:40:14
2021-04-20T11:40:14
359,793,252
0
0
null
null
null
null
UTF-8
C++
false
false
631
hpp
font_builder.hpp
#pragma once #include <stb_truetype.h> #include "glyph.hpp" #include "character_range.hpp" #include "../io/file_system.hpp" class FontBuilder final { public: FontBuilder() = delete; FontBuilder(U32 p_texture_width, U32 p_texture_height, U32 p_glyph_height); void add_glyphs(List<U8> p_font_data, const List<CharacterRange>& p_character_ranges); [[nodiscard]] Shared<Font> build() const; private: U32 m_texture_width; U32 m_texture_height; U32 m_glyph_height; U8* m_pixels = nullptr; U32 m_pixels_size; stbtt_pack_context* m_stbtt_context = nullptr; HashMap<U32, Glyph> m_glyphs; };
b4b45afbcb76d20d8f69a218fd66fac22a29e555
1bd347f71c78374ba3ef7f449a7f79a3b5078998
/Computer-Graphics-Lab/10. Practice/mid point circle.cpp
21c841cfb2059e2c19d57b1352b723f899aeede0
[]
no_license
Ruman-Hossain/Computer-Graphics-Lab
17e5dde1c37f84525d64ba10aa92062926590c62
f0a1fe15e138ce48ff57f9bdd47e51a02fbe853e
refs/heads/master
2021-01-27T04:04:51.509246
2020-02-27T08:51:13
2020-02-27T08:51:13
243,472,522
0
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
mid point circle.cpp
#include<bits/stdc++.h> #include<graphics.h> using namespace std; void circleDrawing(int xc,int yc,int x,int y){ putpixel(xc+x,yc+y,WHITE); putpixel(xc-x,yc+y,WHITE); putpixel(xc+x,yc-y,WHITE); putpixel(xc-x,yc-y,WHITE); putpixel(xc+y,yc+x,WHITE); putpixel(xc-y,yc+x,WHITE); putpixel(xc+y,yc-x,WHITE); putpixel(xc-y,yc-x,WHITE); delay(100); } void midpoint(int xc,int yc, int r){ int x=0, y=r; int p=1-r; void circleDrawing(int, int, int , int); circleDrawing(xc,yc,x,y); while(x<y){ x++; if(p<0){ p+=2*x +1; }else{ y--; p+=2*(x-y)+1; } circleDrawing(xc,yc,x,y); delay(100); } } int main(){ int gd=DETECT,gm; initgraph(&gd,&gm,""); int xc,yc,r; cout<<"Enter Center(xc,yc) and Radius(r) :"; cin>>xc>>yc>>r; //setcolor(BLUE); //circle(xc,yc,r); midpoint(xc,yc,r); delay(4000); closegraph(); }
a5404be9a0f597c108ad7a34b62ecc4fa3d09bf9
911146e6de655c73df43e2675da970c65a2eb66c
/Classes/GameOverState.h
b1d9321bc0349d9285d06224c7ef8f4fac3c20dc
[]
no_license
kosomoN/top-down-shooter
e6061900678b2dc4d17dc3f867933a60a1be4b18
eafc50f286301509381bdcd1254b7b2c94dc9db6
refs/heads/master
2021-01-18T01:26:50.310183
2015-03-07T16:14:05
2015-03-07T16:20:08
30,365,697
1
0
null
null
null
null
UTF-8
C++
false
false
237
h
GameOverState.h
#ifndef GAME_OVER_STATE_H #define GAME_OVER_STATE_H #include "cocos2d.h" using namespace cocos2d; class GameOverState : public Layer { public: static Scene* createScene(); virtual bool init(); CREATE_FUNC(GameOverState) } #endif
fbfd9c7ab262e9450ef78caa2e1eb741a35d5f5d
6a0eff35f0cde76f92575d6397946af72cbd1f09
/Implementasi Stack(tumpukan2)25nov2019.cpp
7fb7c6934e28da4341846d0ef8d18a2b02c5c619
[ "MIT" ]
permissive
saddam18/struktur-data-praktek
2578b569100c3dd1579566ff0c3b9ce25da50296
8a1b6e037530fbadeef63ada6bf1d8147f01779a
refs/heads/master
2020-08-13T14:57:17.139723
2020-01-18T03:33:32
2020-01-18T03:33:32
214,988,194
0
0
MIT
2019-11-12T16:51:37
2019-10-14T08:24:59
null
UTF-8
C++
false
false
1,109
cpp
Implementasi Stack(tumpukan2)25nov2019.cpp
#include <iostream> #include <stdio.h> #include <conio.h> #include <stdlib.h> struct stack { int data[5]; int atas; }; stack tumpuk; int main() { system("CLS"); int pilihan, baru, i; tumpuk.atas=-1; do { system("CLS"); printf("1. PUSH DATA\n"); printf("2. POP DATA\n"); printf("3. PRINT DATA\n"); printf("MASUKKAN PILIHAN : "); scanf("%d",&pilihan); switch (pilihan) { case 1 : if(tumpuk.atas==5-1) { printf("TUMPUKAN PENUH"); getch(); } else { printf("MASUKKAN DATA : "); scanf("%d",&baru); tumpuk.atas++; tumpuk.data[tumpuk.atas]=baru; } break; case 2 : if(tumpuk.atas==-1) { printf("TUMPUKAN KOSONG"); getch(); } else { printf("DATA YANG AKAN DI POP = %d",tumpuk.data[tumpuk.atas]); tumpuk.atas--; getch(); } break; case 3 : if(tumpuk.atas==-1) { printf("TUMPUKAN KOSONG"); getch(); } else { printf("DATA - \n"); for(i=tumpuk.atas; i>=0; i--) { printf("- %d -\n",tumpuk.data[i]); } getch(); } break; default : printf("TIDAK ADA DALAM PILIHAN"); break; } } while((pilihan>=1) && (pilihan<=3)); getch(); }
5e3d76d8fbb835b504253aa3b8c91b9e37306723
35f8cbb3b196b07c597d54d9beb4d8013f1607e0
/FlappyBird/Pillar.h
93e281ec86e6aed471fcc404b7141314d3397967
[]
no_license
Cookiezby/Cocos2dx-stuff
d903558ac2a76408187ed4d3cf7f8331ccaf5f8a
4b5e959048f32b7bc99dad9ad0f8391ccff619de
refs/heads/master
2020-04-26T03:38:26.306755
2015-06-27T14:53:45
2015-06-27T14:53:45
38,163,401
0
0
null
null
null
null
UTF-8
C++
false
false
233
h
Pillar.h
#ifndef __PILLAR_H__ #define __PILLAR_H__ class Pillar { public: Pillar(void); ~Pillar(void); void SetX(float x); int GetX(); void SetBY(float y); int GetBY(); public: float m_x; float m_blanky; }; #endif
94b129e574567f9673314ea9be054155d08c6036
a1f8e6dd0bf47e46083206bf1084d48aa4d7802e
/ImageReaderLibraries/src/DecoderTIFF.cpp
8425e69d2eb117e83780fbebe327fb112c07685c
[]
no_license
aliakbarRashidi/ImageReader
b0b5782d87ceeb09eba500298a332e63d45d4238
32325fa10a4100f210941b92651502a1753179ae
refs/heads/master
2020-06-19T10:21:54.047170
2018-03-19T12:58:23
2018-03-19T12:58:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
cpp
DecoderTIFF.cpp
// This is an open source non-commercial project. Dear PVS-Studio, please check // it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "Decoder.hpp" #include <tiffio.h> #include <tiffio.hxx> #include <boost/interprocess/streams/bufferstream.hpp> using bufferstream = boost::interprocess::bufferstream; namespace Decoder { class TiffDecoder : public DecoderInterface { public: bool decode(std::vector<uchar> &_inputPtr, std::vector<uchar> &_output, int &_width, int &_height, int &_channel) override { bufferstream input_stream(reinterpret_cast<char *>(_inputPtr.data()), _inputPtr.size()); auto buffer = dynamic_cast<std::istream *>(&input_stream); if (buffer == nullptr) { return false; } TIFF *mem_TIFF = TIFFStreamOpen("MemTIFF", buffer); TIFFGetField(mem_TIFF, TIFFTAG_IMAGEWIDTH, &_width); TIFFGetField(mem_TIFF, TIFFTAG_IMAGELENGTH, &_height); _channel = 4; _output.resize(_width * _height * _channel); return TIFFReadRGBAImageOriented(mem_TIFF, _width, _height, reinterpret_cast<uint32 *>(_output.data()), 0) == 1; } }; } // namespace Decoder
6e6cdcac4c5397a611d7913e8c8b30e51b4c0d4c
cb2fe0a9a10a7418bc683df6eedb238c657f4c8a
/Basics of C++/tutorial_2_calculator.cpp
2002dca9ea4f529a12cd6cc3b76e0713eedab753
[]
no_license
withoutwaxaryan/programming-basics
bf33c32545e89deba13c6ab33a1568e69f40c693
93c0c57bf36acd1190f65ec3f2b6d316d59eaaf0
refs/heads/master
2023-03-07T04:58:37.451151
2021-02-20T12:26:14
2021-02-20T12:26:14
181,515,433
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
tutorial_2_calculator.cpp
#include <iostream> using namespace std; void printSomething(); // prototyping a function- letting the compiler know that this function exists and will be defined later void printNumber(int); int addNumbers(int, int); int main() { int a, b, sum, subtract, product, quotient, remainder; // arithmetic operators cout<<"Enter a number"<<endl; cin>>a>>b; // input stream object sum = a + b; subtract = a - b; product = a * b; quotient = a/b; remainder = a % b; cout<<sum<<endl<<subtract<<endl<<product<<endl<<quotient<<endl<<remainder; cout<<endl; // relational operators if(3>1) { cout<<"Aryan rocks"; } if (3 == 3){ // != , >, < , = etc cout<<"lol"; } printSomething(); printNumber(23); cout<<addNumbers(46,22)<<endl; return 0; } void printSomething() { cout<<"YO"; } void printNumber(int x) { cout<<"Fav number is "<<x<<endl; } int addNumbers(int x, int y) { int answer; answer = x + y; return answer; }
b49b16e9b055e2b186d311dc8584862a901d5482
00bc388bb8db90703f03b06ba64adbc8814eb755
/part1/saurabh_shuklaClasses and Object/stlpair.cpp
928cd3cf9a4f6f344052efed5f6b8a8cfda51850
[]
no_license
Sahilnegi-code/Have_practised_Dsa
43e6f103a02be14c78331f8bead4de9871db9aa8
554a67df9660a333024fa3eb201d6333e16ed4f8
refs/heads/master
2023-06-27T04:26:04.229673
2021-07-31T04:21:32
2021-07-31T04:21:32
391,246,076
1
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
stlpair.cpp
#include<bits/stdc++.h> // #include<pair> using namespace std; class student{ string name; int age; public: void set(string s ,int a){ name=s; age = a; } void show(){ cout<<"name:"<<name<<endl; cout<<"age :"<<age<<endl; } }; int main(){ pair <string,int>p1; pair <string ,string>p2; pair<string , float> p3; pair<int ,student> p4; p1=make_pair("sahil",19); p2=make_pair("india ","new delhi"); p3=make_pair("drill",34.2); student s1; p4=make_pair(21,s1); s1.set("a",23); cout<<p1.first<<endl; cout<<p1.second<<endl; cout<<p2.first<<endl; cout<<p2.second<<endl; cout<<p3.first<<endl; cout<<p3.second<<endl; return 0; }
22df07df5cd20ada76362662c860143275564067
edbef8de66535c982f590075a25a67d9adf2f3f5
/orthopol.cpp
2b26b8f46f4b0402d6d915774bbc4f2a7dfac4d4
[]
no_license
andresgit/WignerDist
32151ce3861e80cad92f3d4b60d42ea01effde2c
cd613f461a30d44ed5094d7ea012ce6ec30e9940
refs/heads/master
2020-04-26T20:46:36.582534
2019-03-04T22:15:49
2019-03-04T22:15:49
173,821,203
0
0
null
null
null
null
UTF-8
C++
false
false
5,954
cpp
orthopol.cpp
#include "orthopol.h" #include "orthogonalChebyshev.h" #include <iostream> // standard I/O routines, prefix with "std::" #include <vector> #include "ap.h" #include "integration.h" #include "orthogonalLaguerre.h" using namespace std; // [STYLE] this is common practice, although sometimes discouraged const double OrthogonalPolynomial::tolerance=1.e-13; const double OrthogonalPolynomial::infty=DBL_MAX; void OrthogonalPolynomial::valDer(int N, const double X, std::vector<double> &Val, std::vector<double> &Der) const { // reserve storage Val.resize(N); Der.resize(N); // degree = 0 if(N>0){ Val[0]=val0(); Der[0]=0; } // degree = 1 if (N>1) { Val[1]=a(1)* X*Val[0] + b(1); Der[1]=a(1)*(X*Der[0]+Val[0]); } // degree > 1: use two-point recurrence for (int n=2; n<N; n++){ Val[n] = (a(n)*X + b(n)) * Val[n-1] + c(n)*Val[n-2]; Der[n] = (a(n)*X + b(n)) * Der[n-1] + a(n)*Val[n-1] + c(n)*Der[n-2]; } } /// values at X up to degree N-1 vector<double> OrthogonalPolynomial::val(int N, const double X) const{ vector<double> _val,dum; valDer(N,X,_val,dum); return _val; } /// derivatives at X up to degree N-1 vector<double> OrthogonalPolynomial::der(int N, const double X) const{ vector<double> _der,dum; valDer(N,X,dum,_der); return _der; } bool OrthogonalPolynomial::Test(){ bool good=true; good=good and OrthogonalLegendre().test(40,true,true); good=good and OrthogonalChebyshev().test(40,true,true); good=good and OrthogonalLaguerre().test(40,true,true); return good; } bool OrthogonalPolynomial::compareLiterature(bool Verbose){ bool good=true; // verify for 11 points for(int k=0;k<11;k++){ // boundaries can be infty, restrict range within [-5,5] double X=max(lowerBoundary(),-5.)+ 0.1*k+(min(upperBoundary(),5.)-max(lowerBoundary(),-5.)); // direct and recursive evaluation vector<double>valRec,derRec,valDir; valDir=directVal(X); valDer(valDir.size(),X,valRec,derRec); for(int n=0;n<valDir.size();n++){ good=good and (abs(valDir[n]-valRec[n])<tolerance); } } if(Verbose){ if(directVal(0).size()==0) cout<<"no comparison literature: directVal() not defined for "<<name()<<endl; else if(good) cout<<"OK compares literature: "<<name()<<" up to degree "<<directVal(0).size()-1<<endl; else cout<<"BAD comparison to literature failed: "<<name()<<" up to degree "<<directVal(0).size()-1<<endl; } return good; } bool OrthogonalPolynomial::test(int Order, bool Print, bool Plot){ // get quadrature points and weights vector<double> pts,wgs; quadrature(Order,pts,wgs); // integrals int dx w(x) Qn(x) Qm(x) for m<=n vector<double> ints((Order*(Order+1))/2,0.); // reserve storage and initialize =0 // sum over quadrature points for(int k=0;k<pts.size();k++) { // store values of all polynomials for argument x=pts[k] vector<double> vals(val(Order,pts[k])); // add into integrals for(int n=0,mn=0;n<Order;n++){ double valnw=vals[n]*wgs[k]; // [PERFORMANCE] pull multiplication out of loop for(int m=0;m<=n;m++,mn++) ints[mn]+=valnw*vals[m]; /* [PERFORMANCE] if you have more than one multiplication in innermost loop * you probably overlooked something (can cost a factor ~2 in time) */ } } // check orthogonality int nCheck=0; double epsMin=DBL_MAX,epsMax=0; int mMin,nMin,mMax,nMax; for(int n=0,mn=0;n<Order;n++){ for(int m=0;m<=n;m++,mn++){ if(n==m)continue; // do not check diagonal nCheck++; double eps=ints[mn]/sqrt(ints[(n*(n+1))/2+n]*ints[(m*(m+1))/2+m]); if(eps>tolerance){ if(eps<epsMin){epsMin=eps; mMin=m; nMin=n;} if(eps>epsMax){epsMax=eps; mMax=m; nMax=n;} } } } // report if desired if(Print){ cout<<endl; if(epsMax>tolerance) cout<<"FAILED "<<name()<<" at order="<<Order<<": epsMin="<<epsMin<<"("<<mMin<<","<<nMin<<"), epsMax="<<epsMax<<"("<<mMax<<","<<nMax<<")"<<endl; else cout<<"OK "<<name()<<" orthogonal at order="<<Order<<", "<<nCheck<<" integrals checked"<<endl; } // here we should open a file and write base-points and values to it if(Plot) cout<<"Plot==true not implemented yet"<<endl; // return true if error below tolerance return epsMax<tolerance and compareLiterature(Print); ; } void OrthogonalPolynomial::quadrature(int N, vector<double>& Points, vector<double>& Weights) const { alglib::real_1d_array alpha; alglib::real_1d_array beta; alglib::ae_int_t info; alglib::real_1d_array xq; alglib::real_1d_array wq; // convert to general recurrence coefficients as used in alglib alpha.setlength(N); beta.setlength(N); if(N>0){ alpha[0]=-b(1)/a(1); beta[0] =0.; } for(unsigned int n=1;n<N;n++){ alpha[n]=-b(n+1)/a(n+1); beta[n] =-c(n+1)/(a(n+1)*a(n)); } // generate the rules alglib::gqgeneraterec(alpha,beta,normsq0(),N,info,xq,wq); switch(info){ case 1: break; // success case -3: cout<<"QuadratureRule: internal eigenproblem solver hasn't converged"<<endl;exit(1); case -2: cout<<"QuadratureRule: Beta[i]<=0"<<endl;exit(1); case -1: cout<<"QuadratureRule: incorrect N was passed"<<endl;exit(1); default: cout<<"QuadratureRule: error value info = "<<info<<endl;exit(1); } // transfer to std::vector Points.resize(N); Weights.resize(N); for (int i=0; i<Weights.size(); i++) { Points[i]=xq[i]; Weights[i]=wq[i]; }; }
c73ec29f39a118f943caadf445cb6e062aa75650
0aa596fc3c2e1e4f542e49170111a86054b11762
/test/unittests/execute_call_test.cpp
a29945110190e16fbdbb65903e375a3068f9459c
[ "Apache-2.0" ]
permissive
hugo-dc/fizzy
6c46f550d9983f9d18239e285c7766baa21a26bb
5aa6926930772d16a9def4e90e19fa97e7d950e8
refs/heads/master
2021-01-16T14:49:39.978039
2020-02-25T21:17:48
2020-02-25T21:17:48
243,157,981
0
0
Apache-2.0
2020-02-26T03:18:43
2020-02-26T03:18:42
null
UTF-8
C++
false
false
9,747
cpp
execute_call_test.cpp
#include "execute.hpp" #include "limits.hpp" #include "parser.hpp" #include <gtest/gtest.h> #include <test/utils/asserts.hpp> #include <test/utils/hex.hpp> using namespace fizzy; TEST(execute_call, call) { Module module; module.typesec.emplace_back(FuncType{{}, {ValType::i32}}); module.funcsec.emplace_back(TypeIdx{0}); module.funcsec.emplace_back(TypeIdx{0}); module.codesec.emplace_back(Code{0, {Instr::i32_const, Instr::end}, {42, 0, 42, 0}}); module.codesec.emplace_back(Code{0, {Instr::call, Instr::end}, {0, 0, 0, 0}}); const auto [trap, ret] = execute(module, 1, {}); ASSERT_FALSE(trap); ASSERT_EQ(ret.size(), 1); EXPECT_EQ(ret[0], 0x2a002a); } TEST(execute_call, call_trap) { Module module; module.typesec.emplace_back(FuncType{{}, {ValType::i32}}); module.funcsec.emplace_back(TypeIdx{0}); module.funcsec.emplace_back(TypeIdx{0}); module.codesec.emplace_back(Code{0, {Instr::unreachable, Instr::end}, {}}); module.codesec.emplace_back(Code{0, {Instr::call, Instr::end}, {0, 0, 0, 0}}); const auto [trap, ret] = execute(module, 1, {}); ASSERT_TRUE(trap); } TEST(execute_call, call_with_arguments) { /* wat2wasm (module (func $calc (param $a i32) (param $b i32) (result i32) local.get 1 local.get 0 i32.sub ;; a - b ) (func (result i32) i32.const 13 i32.const 17 call $calc ;; 17 - 13 => 4 ) ) */ const auto wasm = from_hex( "0061736d01000000010b0260027f7f017f6000017f03030200010a12020700200120006b0b0800410d41111000" "0b"); EXPECT_RESULT(execute(parse(wasm), 1, {}), 4); } TEST(execute_call, call_indirect) { /* wat2wasm (type $out-i32 (func (result i32))) (table anyfunc (elem $f3 $f2 $f1 $f4 $f5)) (func $f1 (result i32) i32.const 1) (func $f2 (result i32) i32.const 2) (func $f3 (result i32) i32.const 3) (func $f4 (result i64) i64.const 4) (func $f5 (result i32) unreachable) (func (param i32) (result i32) (call_indirect (type $out-i32) (get_local 0)) ) */ const auto bin = from_hex( "0061736d01000000010e036000017f6000017e60017f017f03070600000001000204050170010505090b010041" "000b0502010003040a2106040041010b040041020b040041030b040042040b0300000b070020001100000b"); const Module module = parse(bin); for (const auto param : {0u, 1u, 2u}) { constexpr uint64_t expected_results[]{3, 2, 1}; const auto [trap, ret] = execute(module, 5, {param}); ASSERT_FALSE(trap); ASSERT_EQ(ret.size(), 1); EXPECT_EQ(ret[0], expected_results[param]); } // immediate is incorrect type EXPECT_TRUE(execute(module, 5, {3}).trapped); // called function traps EXPECT_TRUE(execute(module, 5, {4}).trapped); // argument out of table bounds EXPECT_TRUE(execute(module, 5, {5}).trapped); } TEST(execute_call, call_indirect_with_argument) { /* wat2wasm (module (type $bin_func (func (param i32 i32) (result i32))) (table anyfunc (elem $f1 $f2 $f3)) (func $f1 (param i32 i32) (result i32) (i32.div_u (get_local 0) (get_local 1))) (func $f2 (param i32 i32) (result i32) (i32.sub (get_local 0) (get_local 1))) (func $f3 (param i32) (result i32) (i32.mul (get_local 0) (get_local 0))) (func (param i32) (result i32) i32.const 31 i32.const 7 (call_indirect (type $bin_func) (get_local 0)) ) ) */ const auto bin = from_hex( "0061736d01000000010c0260027f7f017f60017f017f03050400000101040501700103030909010041000b0300" "01020a25040700200020016e0b0700200020016b0b0700200020006c0b0b00411f410720001100000b"); const Module module = parse(bin); EXPECT_RESULT(execute(module, 3, {0}), 31 / 7); EXPECT_RESULT(execute(module, 3, {1}), 31 - 7); // immediate is incorrect type EXPECT_TRUE(execute(module, 3, {2}).trapped); } TEST(execute_call, call_indirect_imported_table) { /* wat2wasm (module (type $out_i32 (func (result i32))) (import "m" "t" (table 5 20 anyfunc)) (func $f1 (result i32) i32.const 1) (func $f2 (result i32) i32.const 2) (func $f3 (result i32) i32.const 3) (func $f4 (result i64) i64.const 4) (func $f5 (result i32) unreachable) (func (param i32) (result i32) (call_indirect (type $out_i32) (get_local 0)) ) ) */ const auto bin = from_hex( "0061736d01000000010e036000017f6000017e60017f017f020a01016d01740170010514030706000000010002" "0a2106040041010b040041020b040041030b040042040b0300000b070020001100000b"); const Module module = parse(bin); std::vector<FuncIdx> table{2, 1, 0, 3, 4}; auto instance = instantiate(module, {}, {{&table, {5, 20}}}); for (const auto param : {0u, 1u, 2u}) { constexpr uint64_t expected_results[]{3, 2, 1}; const auto [trap, ret] = execute(instance, 5, {param}); ASSERT_FALSE(trap); ASSERT_EQ(ret.size(), 1); EXPECT_EQ(ret[0], expected_results[param]); } // immediate is incorrect type EXPECT_TRUE(execute(instance, 5, {3}).trapped); // called function traps EXPECT_TRUE(execute(instance, 5, {4}).trapped); // argument out of table bounds EXPECT_TRUE(execute(instance, 5, {5}).trapped); } TEST(execute_call, imported_function_call) { Module module; module.typesec.emplace_back(FuncType{{}, {ValType::i32}}); module.importsec.emplace_back(Import{"mod", "foo", ExternalKind::Function, {0}}); module.funcsec.emplace_back(TypeIdx{0}); module.codesec.emplace_back(Code{0, {Instr::call, Instr::end}, {0, 0, 0, 0}}); auto host_foo = [](Instance&, std::vector<uint64_t>) -> execution_result { return {false, {42}}; }; auto instance = instantiate(module, {host_foo}); const auto [trap, ret] = execute(instance, 1, {}); ASSERT_FALSE(trap); ASSERT_EQ(ret.size(), 1); EXPECT_EQ(ret[0], 42); } TEST(execute_call, imported_function_call_with_arguments) { Module module; module.typesec.emplace_back(FuncType{{ValType::i32}, {ValType::i32}}); module.importsec.emplace_back(Import{"mod", "foo", ExternalKind::Function, {0}}); module.funcsec.emplace_back(TypeIdx{0}); module.codesec.emplace_back( Code{0, {Instr::local_get, Instr::call, Instr::i32_const, Instr::i32_add, Instr::end}, {0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0}}); auto host_foo = [](Instance&, std::vector<uint64_t> args) -> execution_result { return {false, {args[0] * 2}}; }; auto instance = instantiate(module, {host_foo}); const auto [trap, ret] = execute(instance, 1, {20}); ASSERT_FALSE(trap); ASSERT_EQ(ret.size(), 1); EXPECT_EQ(ret[0], 42); } TEST(execute_call, imported_functions_call_indirect) { /* wat2wasm (module (type $ft (func (param i32) (result i64))) (func $sqr (import "env" "sqr") (param i32) (result i64)) (func $isqrt (import "env" "isqrt") (param i32) (result i64)) (func $double (param i32) (result i64) get_local 0 i64.extend_u/i32 get_local 0 i64.extend_u/i32 i64.add ) (func $main (param i32) (param i32) (result i64) get_local 1 get_local 0 call_indirect (type $ft) ) (table anyfunc (elem $double $sqr $isqrt)) ) */ const auto wasm = from_hex( "0061736d01000000010c0260017f017e60027f7f017e02170203656e7603737172000003656e76056973717274" "00000303020001040501700103030909010041000b030200010a150209002000ad2000ad7c0b09002001200011" "00000b"); const auto module = parse(wasm); ASSERT_EQ(module.typesec.size(), 2); ASSERT_EQ(module.importsec.size(), 2); ASSERT_EQ(module.codesec.size(), 2); constexpr auto sqr = [](Instance&, std::vector<uint64_t> args) -> execution_result { return {false, {args[0] * args[0]}}; }; constexpr auto isqrt = [](Instance&, std::vector<uint64_t> args) -> execution_result { return {false, {(11 + args[0] / 11) / 2}}; }; auto instance = instantiate(module, {sqr, isqrt}); EXPECT_RESULT(execute(instance, 3, {0, 10}), 20); // double(10) EXPECT_RESULT(execute(instance, 3, {1, 9}), 81); // sqr(9) EXPECT_RESULT(execute(instance, 3, {2, 50}), 7); // isqrt(50) } TEST(execute_call, imported_function_from_another_module) { /* wat2wasm (module (func $sub (param $lhs i32) (param $rhs i32) (result i32) get_local $lhs get_local $rhs i32.sub) (export "sub" (func $sub)) ) */ const auto bin1 = from_hex( "0061736d0100000001070160027f7f017f030201000707010373756200000a09010700200020016b0b"); const auto module1 = parse(bin1); auto instance1 = instantiate(module1); /* wat2wasm (module (func $sub (import "m1" "sub") (param $lhs i32) (param $rhs i32) (result i32)) (func $main (param i32) (param i32) (result i32) get_local 0 get_local 1 call $sub ) ) */ const auto bin2 = from_hex( "0061736d0100000001070160027f7f017f020a01026d31037375620000030201000a0a0108002000200110000" "b"); const auto module2 = parse(bin2); const auto func_idx = fizzy::find_exported_function(module1, "sub"); ASSERT_TRUE(func_idx.has_value()); auto sub = [&instance1, func_idx](Instance&, std::vector<uint64_t> args) -> execution_result { return fizzy::execute(instance1, *func_idx, std::move(args)); }; auto instance2 = instantiate(module2, {sub}); EXPECT_RESULT(execute(instance2, 1, {44, 2}), 42); }
c992eee08b86b0b65df9769e092ca943701cc116
6ce50678b68d595f57d0edda7b454d158c7c691a
/src/MPD/Statistics.cc
1c9ebe57be18fb6c6f63b5992a3415f208d7eaa7
[]
no_license
studentkittens/Freya
6832931bc1af0c929c79dbfc0bd63b148d1ad7a8
95dd03a65b83086bfee834ce28a4a9bd99c7e3de
refs/heads/master
2021-01-23T06:59:00.143643
2012-07-17T13:20:19
2012-07-17T13:20:19
2,526,052
4
0
null
null
null
null
UTF-8
C++
false
false
2,246
cc
Statistics.cc
/*********************************************************** * This file is part of Freya * - A free MPD Gtk3 MPD Client - * * Authors: Christopher Pahl, Christoph Piechula, * Eduard Schneider * * Copyright (C) [2011-2012] * Hosted at: https://github.com/studentkittens/Freya * * __..--''``---....___ _..._ __ * /// //_.-' .-/"; ` ``<._ ``.''_ `. / // / * ///_.-' _..--.'_ `( ) ) // // * / (_..-' // (< _ ;_..__ ; `' / /// * / // // // `-._,_)' // / ``--...____..-' /// / // * Ascii-Art by Felix Lee <flee@cse.psu.edu> * * Freya 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. * * Freya 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 Freya. If not, see <http://www.gnu.org/licenses/>. **************************************************************/ #include "Statistics.hh" namespace MPD { Statistics::Statistics(mpd_stats& statistics) { mp_Statistics = &statistics; } Statistics::~Statistics() { if(mp_Statistics) { mpd_stats_free(mp_Statistics); } } unsigned Statistics::get_number_of_artists() { return mpd_stats_get_number_of_artists(mp_Statistics); } unsigned Statistics::get_number_of_albums() { return mpd_stats_get_number_of_albums(mp_Statistics); } unsigned Statistics::get_number_of_songs() { return mpd_stats_get_number_of_songs(mp_Statistics); } unsigned long Statistics::get_uptime() { return mpd_stats_get_uptime(mp_Statistics); } unsigned long Statistics::get_db_update_time() { return mpd_stats_get_db_update_time(mp_Statistics); } unsigned long Statistics::get_play_time() { return mpd_stats_get_play_time(mp_Statistics); } unsigned long Statistics::get_db_play_time(void) { return mpd_stats_get_db_play_time(mp_Statistics); } }
f4fdc8e2c0744f3e45e001d5dfaa09a4ce612887
88c68b614dbb46f2020fb233e4a06998d8758c52
/Practica1/Examen/fuma_ex.cpp
f3a0a1729fd5aee76896f96acd4c03946c52a43c
[]
no_license
juanAFernandez/SistemasConcurrentesyDistribuidos
4ee3c94dd071d4111254d12c377af0c224db9918
21acb5250872d62107ea08b59a9025c03935ce3a
refs/heads/master
2020-06-04T02:16:06.015799
2015-01-21T15:53:51
2015-01-21T15:53:51
24,674,157
0
0
null
null
null
null
UTF-8
C++
false
false
11,300
cpp
fuma_ex.cpp
/* ## Problema fumadores de EXAMEN ## @brief En este caso habrá 6 hebras fumadoras. Cada vez que el estanquero coloque un ingrediente en la mesa despierta a uno de los dos fumadores que necesitan ese ingrediente (da igual cual). El estanquero podrá colocar dos ingredientes en el mostrador (de forma aleatoria), entonces sólo se debe bloquear cuando haya dos ingredientes sin retirar en la mesa. @Autor: Juan Antonio Fernández Sánchez @Fecha: Noviembre 2014 @version: examen */ #include <iostream> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <stdlib.h> using namespace std; //El mostrador será considerado como dos unidades donde puede haber tres cosas: // 0--> ningun ingrediente 1--> tabaco 2--> papel 3--> cerillas int mostradorA=0; int mostradorB=0; //Semáforo para la exclusión mutua de las dos unidades del mostrador. sem_t mutexA; sem_t semaforoFumadorA, semaforoFumadorB, semaforoFumadorC, semaforoFumadorD, semaforoFumadorE, semaforoFumadorF; sem_t semEstanquero; void* suministrar(void *p){ /* "El estanquero selecciona aleatoriamente un ingrediente de los tres que se necesitan, lo pone en el mostrador, desbloquea al fumador que necesita dicho ingrediente y después se bloquea, esperando la retirada del ingrediente. */ while(true){ //Miestras el estanquero no esté libre no podrá producir sem_wait(&semEstanquero); sem_wait(&mutex); //Acción de poner ingredientes en el mostrador // Selección aleatoria del ingrediente a suministrar mostradorA = rand()%3+1; mostradorB = rand()%3+1; cout << "En el mostradorA se deja: "; if(mostradorA == 1) cout << "tabaco" << endl; if(mostradorA == 2) cout << "papel" << endl; if(mostradorA == 3) cout << "cerillas" << endl; cout << "En el mostradorB se deja: "; if(mostradorB == 1) cout << "tabaco" << endl; if(mostradorB == 2) cout << "papel" << endl; if(mostradorB == 3) cout << "cerillas" << endl; // Según el ingrediente que se produzca se desbloquea a un fumador o a otro // 0--> ningun ingrediente 1--> tabaco 2--> papel 3--> cerillas int eleccionFumador; //Si en el mostrador A o en el mostrador B se deja tabaco... if( (mostradorA==1) || (mostradorB==1) ){ // ... se selecciona al azar uno de los dos fumadores que lo necesitan (el B o el E)... eleccionFumador=rand()%2+1; if(eleccionFumador==1) // ... y se desbloquea. sem_post(&semaforoFumadorB); else if(eleccionFumador==2) // ... y se desbloquea. sem_post(&semaforoFumadorE); } //Si en el mostrador A o en el mostrador B se dejan cerillas... if( (mostradorA==3) || (mostradorB==3) ){ // ... se selecciona al azar uno de los dos fumadores que lo necesitan (el A o el D)... eleccionFumador=rand()%2+1; if(eleccionFumador==1) // ... y se desbloquea. sem_post(&semaforoFumadorA); else if(eleccionFumador==2) // ... y se desbloquea. sem_post(&semaforoFumadorD); } //Si en el mostrador A o en el mostrador B se deja papel... if( (mostradorA==2) || (mostradorB==2) ){ // ... se selecciona al azar uno de los dos fumadores que lo necesitan (el C o el F)... eleccionFumador=rand()%2+1; if(eleccionFumador==1) // ... y se desbloquea. sem_post(&semaforoFumadorC); else if(eleccionFumador==2) // ... y se desbloquea. sem_post(&semaforoFumadorF); } sem_post(&mutex); }//FIN WHILE } void fumar(){ //Calcula un número aleatorio de milisegundos (entre 1/10 y 2 segundos) const unsigned miliseg = 100U + (rand() % 1900U); usleep(1000U*miliseg); //retraso bloqueado durante miliseg milisegundos. } void* fumaFumadorA(void *p){ while(true){ //El fumador A no puede fumar hasta que el estanquero lo desbloquee cuando haya servido su ingrediente sem_wait(&semaforoFumadorA); //Tras entrar una vez no podrá volver a entrar hasta que alguien vuelva a desbloquear su entrada. //Recoger el producto sem_wait(&mutex); //Se encierra en una zona de exclusión mutua para asegurar que mientras que el accede al mostrador del estanquero nadie lo haga. //Si su ingrediente está en el mostrador A if(mostradorA==3) //Consume el ingrediente mostradorA=0; //Si su ingrediente está en el mostrador B if(mostradorB==3) //Consume el ingrediente mostradorB=0; cout << "Fumador A recoge cerillas y se pone a fumar! " << endl; //Se recoge el producto y se libera al estanquero para que produzca otro. sem_post(&semEstanquero); sem_post(&mutex); //Se libera el mostrador para que lo pueda utilizar quien quiera. fumar(); cout << "Fumador A ha terminado de fumar! " << endl; }//Fin while } void* fumaFumadorB(void *p){ while(true){ //El fumador A no puede fumar hasta que el estanquero lo desbloquee cuando haya servido su ingrediente sem_wait(&semaforoFumadorB); //Tras entrar una vez no podrá volver a entrar hasta que alguien vuelva a desbloquear su entrada. //Recoger el producto sem_wait(&mutex); //Se encierra en una zona de exclusión mutua para asegurar que mientras que el accede al mostrador del estanquero nadie lo haga. //Si su ingrediente está en el mostrador A if(mostradorA==1) //Consume el ingrediente mostradorA=0; //Si su ingrediente está en el mostrador B if(mostradorB==1) //Consume el ingrediente mostradorB=0; cout << "Fumador B recoge tabaco y se pone a fumar! " << endl; //Se recoge el producto y se libera al estanquero para que produzca otro. sem_post(&semEstanquero); sem_post(&mutex); //Se libera el mostrador para que lo pueda utilizar quien quiera. fumar(); cout << "Fumador B ha terminado de fumar! " << endl; }//Fin while } void* fumaFumadorC(void *p){ while(true){ //El fumador A no puede fumar hasta que el estanquero lo desbloquee cuando haya servido su ingrediente sem_wait(&semaforoFumadorC); //Tras entrar una vez no podrá volver a entrar hasta que alguien vuelva a desbloquear su entrada. //Recoger el producto sem_wait(&mutex); //Se encierra en una zona de exclusión mutua para asegurar que mientras que el accede al mostrador del estanquero nadie lo haga. //Si su ingrediente está en el mostrador A if(mostradorA==2) //Consume el ingrediente mostradorA=0; //Si su ingrediente está en el mostrador B if(mostradorB==2) //Consume el ingrediente mostradorB=0; cout << "Fumador C recoge papel y se pone a fumar! " << endl; //Se recoge el producto y se libera al estanquero para que produzca otro. sem_post(&semEstanquero); sem_post(&mutex); //Se libera el mostrador para que lo pueda utilizar quien quiera. fumar(); cout << "Fumador C ha terminado de fumar! " << endl; }//Fin while } void* fumaFumadorD(void *p){ while(true){ //El fumador A no puede fumar hasta que el estanquero lo desbloquee cuando haya servido su ingrediente sem_wait(&semaforoFumadorD); //Tras entrar una vez no podrá volver a entrar hasta que alguien vuelva a desbloquear su entrada. //Recoger el producto sem_wait(&mutex); //Se encierra en una zona de exclusión mutua para asegurar que mientras que el accede al mostrador del estanquero nadie lo haga. //Si su ingrediente está en el mostrador A if(mostradorA==3) //Consume el ingrediente mostradorA=0; //Si su ingrediente está en el mostrador B if(mostradorB==3) //Consume el ingrediente mostradorB=0; cout << "Fumador D recoge cerillas y se pone a fumar! " << endl; //Se recoge el producto y se libera al estanquero para que produzca otro. sem_post(&semEstanquero); sem_post(&mutex); //Se libera el mostrador para que lo pueda utilizar quien quiera. fumar(); cout << "Fumador D ha terminado de fumar! " << endl; }//Fin while } void* fumaFumadorE(void *p){ while(true){ //El fumador A no puede fumar hasta que el estanquero lo desbloquee cuando haya servido su ingrediente sem_wait(&semaforoFumadorE); //Tras entrar una vez no podrá volver a entrar hasta que alguien vuelva a desbloquear su entrada. //Recoger el producto sem_wait(&mutex); //Se encierra en una zona de exclusión mutua para asegurar que mientras que el accede al mostrador del estanquero nadie lo haga. //Si su ingrediente está en el mostrador A if(mostradorA==1) //Consume el ingrediente mostradorA=0; //Si su ingrediente está en el mostrador B if(mostradorB==1) //Consume el ingrediente mostradorB=0; cout << "Fumador E recoge tabaco y se pone a fumar! " << endl; //Se recoge el producto y se libera al estanquero para que produzca otro. sem_post(&semEstanquero); sem_post(&mutex); //Se libera el mostrador para que lo pueda utilizar quien quiera. fumar(); cout << "Fumador E ha terminado de fumar! " << endl; }//Fin while } void* fumaFumadorF(void *p){ while(true){ //El fumador A no puede fumar hasta que el estanquero lo desbloquee cuando haya servido su ingrediente sem_wait(&semaforoFumadorF); //Tras entrar una vez no podrá volver a entrar hasta que alguien vuelva a desbloquear su entrada. //Recoger el producto sem_wait(&mutex); //Se encierra en una zona de exclusión mutua para asegurar que mientras que el accede al mostrador del estanquero nadie lo haga. //Si su ingrediente está en el mostrador A if(mostradorA==2) //Consume el ingrediente mostradorA=0; //Si su ingrediente está en el mostrador B if(mostradorB==2) //Consume el ingrediente mostradorB=0; cout << "Fumador F recoge papel y se pone a fumar! " << endl; //Se recoge el producto y se libera al estanquero para que produzca otro. sem_post(&semEstanquero); sem_post(&mutex); //Se libera el mostrador para que lo pueda utilizar quien quiera. fumar(); cout << "Fumador F ha terminado de fumar! " << endl; }//Fin while } int main(){ // Inicializamos la semilla aleatoria srand(time (NULL)); sem_init(&mutex, 0, 1); //El semáforo que bloquea al fumador A debe inicializarse a 0 ya que al empezar la ejecución este no tendrá por que tener su ingrediente en el mostrador. sem_init(&semaforoFumadorA, 0, 0); sem_init(&semaforoFumadorB, 0, 0); sem_init(&semaforoFumadorC, 0, 0); sem_init(&semaforoFumadorD, 0, 0); sem_init(&semaforoFumadorE, 0, 0); sem_init(&semaforoFumadorF, 0, 0); sem_init(&semEstanquero,0,1); pthread_t estanquero, fumadorA, fumadorB, fumadorC, fumadorD, fumadorE, fumadorF; pthread_create(&estanquero, NULL, suministrar, NULL); pthread_create(&fumadorA, NULL, fumaFumadorA, NULL); pthread_create(&fumadorB, NULL, fumaFumadorB, NULL); pthread_create(&fumadorC, NULL, fumaFumadorC, NULL); pthread_create(&fumadorD, NULL, fumaFumadorD, NULL); pthread_create(&fumadorE, NULL, fumaFumadorE, NULL); pthread_create(&fumadorF, NULL, fumaFumadorF, NULL); //Punto de espera a las hebras pthread_join(fumadorA, NULL); pthread_join(fumadorB, NULL); pthread_join(fumadorC, NULL); pthread_join(fumadorD, NULL); pthread_join(fumadorE, NULL); pthread_join(fumadorF, NULL); pthread_join(estanquero,NULL); //Destruimos todos los semáforos creados. sem_destroy(&mutex); sem_destroy(&semaforoFumadorA); sem_destroy(&semaforoFumadorB); sem_destroy(&semaforoFumadorC); sem_destroy(&semaforoFumadorD); sem_destroy(&semaforoFumadorE); sem_destroy(&semaforoFumadorF); sem_destroy(&semEstanquero); }
0abab621e4860f61fd5ddb1c152ccaaca37fd724
389b851790b9f7277d7e3b689a0e96a8a35c316e
/GameServer/ServerStarter/const.h
cb07934a2b562a865f75a4927c698c3bc429cbe8
[]
no_license
micyril/AIWars
2eeab9f15ee26d429269fe73ae798783c02a863a
e978dffe6e11832854e04e506bb5cc461cf2db40
refs/heads/master
2021-01-20T12:04:59.850468
2013-12-19T13:12:45
2013-12-19T13:12:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
87
h
const.h
#include <string> const std::string ack = "ACK\r\n"; const std::string eog = "EOG\r\n";
6148da6d87de465dbd713e085db10b32e9eaa255
472e20731939b9f4ad721976db0f2ab167d07c26
/TestSoftware/arduino/audio/player_objif/player_objif.ino
d29a2f4ca9d1ab3c32da5c21173633d9b5d9e266
[]
no_license
XinghuaXHu/spresense-test-structure-change
504ad68698581cf473de83d1ab9b466d592a7419
25e71da1716aa1e9f7b358baf5f23a3021529646
refs/heads/master
2021-01-15T05:35:00.742393
2020-03-02T08:17:35
2020-03-02T08:17:35
242,887,626
0
0
null
null
null
null
UTF-8
C++
false
false
7,016
ino
player_objif.ino
/* * player_ObjIf.ino - Object I/F based sound player example application * Copyright 2018 Sony Semiconductor Solutions Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <SDHCI.h> #include <MediaPlayer.h> #include <OutputMixer.h> #include <MemoryUtil.h> #include <arch/chip/pm.h> #include <arch/board/board.h> SDClass theSD; MediaPlayer *thePlayer; OutputMixer *theMixer; File myFile; bool ErrEnd = false; char cmd[16] = {0}; /** * @brief Audio attention callback * * When audio internal error occurc, this function will be called back. */ static void attention_cb(const ErrorAttentionParam *atprm) { puts("Attention!"); if (atprm->error_code >= AS_ATTENTION_CODE_WARNING) { ErrEnd = true; } } /** * @brief Mixer done callback procedure * * @param [in] requester_dtq MsgQueId type * @param [in] reply_of MsgType type * @param [in,out] done_param AsOutputMixDoneParam type pointer */ static void outputmixer_done_callback(MsgQueId requester_dtq, MsgType reply_of, AsOutputMixDoneParam *done_param) { return; } /** * @brief Mixer data send callback procedure * * @param [in] identifier Device identifier * @param [in] is_end For normal request give false, for stop request give true */ static void outmixer_send_callback(int32_t identifier, bool is_end) { AsRequestNextParam next; next.type = (!is_end) ? AsNextNormalRequest : AsNextStopResRequest; AS_RequestNextPlayerProcess(AS_PLAYER_ID_0, &next); return; } /** * @brief Player done callback procedure * * @param [in] event AsPlayerEvent type indicator * @param [in] result Result * @param [in] sub_result Sub result * * @return true on success, false otherwise */ static bool mediaplayer_done_callback(AsPlayerEvent event, uint32_t result, uint32_t sub_result) { printf("mp cb %x %x %x\n", event, result, sub_result); return true; } /** * @brief Player decode callback procedure * * @param [in] pcm_param AsPcmDataParam type */ void mediaplayer_decode_callback(AsPcmDataParam pcm_param) { { /* You can process a data here. */ signed short *ptr = (signed short *)pcm_param.mh.getPa(); for (unsigned int cnt = 0; cnt < pcm_param.size; cnt += 4) { *ptr = *ptr + 0; ptr++; *ptr = *ptr + 0; ptr++; } } theMixer->sendData(OutputMixer0, outmixer_send_callback, pcm_param); } /** * @brief Setup Player and Mixer * * Set output device to Speakers/Headphones <br> * Initialize main player to decode stereo mp3 stream with 48 kb/s sample rate <br> * System directory "/mnt/sd0/BIN" will be searched for MP3 decoder (MP3DEC file) * Open "Sound.mp3" file <br> * Set volume to -16.0 dB */ void setup() { if (!theSD.begin()) { printf("SD card is not present\n"); } printf("Please input cmd:\n"); gets(cmd); if (strcmp(cmd, "usbmsc") == 0) { if (theSD.beginUsbMsc()) { printf("UsbMsc connect error\n"); exit(1); } printf("<<< Begin USB Mass Storage Operation\n"); gets(cmd); gets(cmd); if (theSD.endUsbMsc()) { printf("UsbMsc disconnect error\n"); exit(1); } printf("<<< Finish USB Mass Storage Operation\n"); delay(1000); up_pm_reboot(); } /* Initialize memory pools and message libs */ initMemoryPools(); createStaticPools(MEM_LAYOUT_PLAYER); /* start audio system */ thePlayer = MediaPlayer::getInstance(); theMixer = OutputMixer::getInstance(); thePlayer->begin(); puts("initialization Audio Library"); /* Activate Baseband */ theMixer->activateBaseband(); /* Create Objects */ thePlayer->create(MediaPlayer::Player0, attention_cb); theMixer->create(attention_cb); /* Set rendering clock */ theMixer->setRenderingClkMode(OUTPUTMIXER_RNDCLK_NORMAL); /* Activate Player Object */ thePlayer->activate(MediaPlayer::Player0, mediaplayer_done_callback); /* Activate Mixer Object. * Set output device to speaker with 2nd argument. * If you want to change the output device to I2S, * specify "I2SOutputDevice" as an argument. */ theMixer->activate(OutputMixer0, HPOutputDevice, outputmixer_done_callback); usleep(100 * 1000); /* * Initialize main player to decode stereo mp3 stream with 48 kb/s sample rate * Search for MP3 codec in "/mnt/sd0/BIN" directory */ thePlayer->init(MediaPlayer::Player0, AS_CODECTYPE_MP3, "/mnt/sd0/BIN", AS_SAMPLINGRATE_48000, AS_CHANNEL_STEREO); myFile = theSD.open("Sound.mp3"); /* Verify file open */ if (!myFile) { printf("File open error\n"); exit(1); } printf("Open! %d\n", myFile); /* Send first frames to be decoded */ err_t err = thePlayer->writeFrames(MediaPlayer::Player0, myFile); if (err != MEDIAPLAYER_ECODE_OK) { printf("File Read Error! =%d\n",err); myFile.close(); exit(1); } puts("Play!"); /* Main volume set to -16.0 dB, Main player and sub player set to 0 dB */ theMixer->setVolume(-160, 0, 0); // Start Player thePlayer->start(MediaPlayer::Player0, mediaplayer_decode_callback); } /** * @brief Play audio frames until file ends */ void loop() { puts("loop!!"); /* Send new frames to decode in a loop until file ends */ err_t err = thePlayer->writeFrames(MediaPlayer::Player0, myFile); /* Tell when player file ends */ if (err == MEDIAPLAYER_ECODE_FILEEND) { printf("Main player File End!\n"); } /* Show error code from player and stop */ if (err) { printf("Main player error code: %d\n", err); goto stop_player; } if (ErrEnd) { printf("Error End\n"); goto stop_player; } /* This sleep is adjusted by the time to read the audio stream file. Please adjust in according with the processing contents being processed at the same time by Application. */ usleep(40000); /* Don't go further and continue play */ return; stop_player: sleep(1); thePlayer->stop(MediaPlayer::Player0); thePlayer->deactivate(MediaPlayer::Player0); myFile.close(); delay(1000); up_pm_reboot(); }
f8a867810349f2f96600d221ef94a4b3a61564e2
79b77f974365870bd6966e45496b5ce0524e1acb
/Sources/robotController/Client/BBException.hpp
b02a5032589e482bb65914f9f975d6d453d50ee0
[]
no_license
cintiaf/LittleThumb
7d82c44e14477d7b865808430ccbfcbc0321ae23
16f707376633688064f555e37a38e2d62d3d921e
refs/heads/master
2016-09-14T19:19:19.263328
2016-04-21T07:29:13
2016-04-21T07:29:13
55,951,140
0
0
null
null
null
null
UTF-8
C++
false
false
366
hpp
BBException.hpp
#pragma once #include <iostream> #include <sstream> #include <vector> #include <exception> class BBException : public std::exception { public: BBException(const std::string &message) throw(); BBException(const std::string &message, int line) throw(); virtual ~BBException() throw (); const char * what() const throw(); protected: std::string _message; };
59e8bcb64577d7f43c05f85e888d3486a5398e47
dc5fd9e482bd87d72695b14b9e0fd383b2ee9dcf
/src/main/train_ner.cc
2b496425a3648ac9e573bcab8d075d75bdb85f2b
[]
no_license
Ambier/crf
34dbe42e0c1468480a1222d64f46cf04cb451196
4cb7c8c3ef0537fe519d27a778e5a6272545069f
refs/heads/master
2020-05-25T16:39:44.036071
2013-04-16T08:39:19
2013-04-16T08:39:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
183
cc
train_ner.cc
#include "base.h" #include "crf.h" #include "crf/main.h" #include "main.h" int run(int argc, char *argv[]) { return NLP::CRF::run_train<NLP::CRF::NER>(argc, argv, "", "lbfgs"); }
958c5f9145fe5113e3a617393b08717ed34f047c
60e284d357878ec65ca4527c182d95defac18d13
/io/FileInputStream.cpp
d1758007c94a299d1b8e9f6163388e48ee6395f0
[]
no_license
keyguansz/Obotcha
ee2198bc403e6d7ae76dbb5f0c758f35f0a4d0ad
c0cc39294d90abc9d7b92f79970bf4de573f70c8
refs/heads/master
2020-05-13T03:28:25.797363
2019-04-09T14:25:30
2019-04-09T14:25:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
784
cpp
FileInputStream.cpp
#include "FileInputStream.hpp" namespace obotcha { _FileInputStream::_FileInputStream(File f) { mPath = createString(f->getAbsolutePath()); } _FileInputStream::_FileInputStream(String path) { mPath = createString(path); } int _FileInputStream::read() { //TODO } int _FileInputStream::read(ByteArray buff) { fstream.read(buff->toValue(),buff->size()); return fstream.gcount(); } ByteArray _FileInputStream::readAll() { //TODO } bool _FileInputStream::open() { fstream.open(mPath->toChars()); return fstream.is_open(); } void _FileInputStream::close() { fstream.close(); } String _FileInputStream::readLine() { std::string s; if(std::getline(fstream,s)) { return createString(s.data()); } return nullptr; } }
8fd4c541449c1e4117462ac13230feb33d1a955c
b2ee7279be8680b597a52953cb83ba035e169693
/WinGUI/NewGUI/AMSEdit.h
a406f6efd2d7afe7431577f8810e0123259d8c3f
[]
no_license
xt9852/KeePassXT
6ce8b9ec4de7987086790abea9fed48dad9be2a3
ca2f7e56078310f50e33a704334461de893ff262
refs/heads/master
2021-01-20T19:56:39.351759
2017-12-25T08:52:47
2017-12-25T08:52:47
61,785,904
5
1
null
null
null
null
UTF-8
C++
false
false
31,620
h
AMSEdit.h
#if !defined(AFX_AMS_EDIT_H__AC5ACB94_4363_11D3_9123_00105A6E5DE4__INCLUDED_) #define AFX_AMS_EDIT_H__AC5ACB94_4363_11D3_9123_00105A6E5DE4__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // Edit.h : header file // Created by: Alvaro Mendez - 07/17/2000 // Modified by: Dominik Reichl - 26/02/2005 // // #include <afxwin.h> // #include <afxtempl.h> // To export this code from an MFC Extension DLL uncomment the following line and then define _AMSEDIT_EXPORT inside the DLL's Project Settings. // #define AMSEDIT_IN_DLL // Import/Export macro for the classes below #if defined(AMSEDIT_IN_DLL) #if defined(_AMSEDIT_EXPORT) #define AMSEDIT_EXPORT _declspec(dllexport) #else #define AMSEDIT_EXPORT _declspec(dllimport) #endif #else #define AMSEDIT_EXPORT #endif // The following IDs are assigned for each class below to allow us to set which ones we need compiled #define AMSEDIT_ALPHANUMERIC_CLASS 0x01 #define AMSEDIT_MASKED_CLASS 0x02 #define AMSEDIT_NUMERIC_CLASS 0x04 #define AMSEDIT_INTEGER_CLASS (AMSEDIT_NUMERIC_CLASS | 0x08) #define AMSEDIT_CURRENCY_CLASS (AMSEDIT_NUMERIC_CLASS | 0x10) #define AMSEDIT_DATE_CLASS 0x20 #define AMSEDIT_TIME_CLASS 0x40 #define AMSEDIT_DATETIME_CLASS (AMSEDIT_DATE_CLASS | AMSEDIT_TIME_CLASS) #define AMSEDIT_ALL_CLASSES (AMSEDIT_ALPHANUMERIC_CLASS | AMSEDIT_MASKED_CLASS | AMSEDIT_INTEGER_CLASS | AMSEDIT_CURRENCY_CLASS | AMSEDIT_DATETIME_CLASS) // If your program does not need all the CAMSEdit classes below, you can reduce // the size of your executable by selecting just the classes you want to be compiled // via the following macro. Use the IDs defined above and "OR" together the classes you need. // #define AMSEDIT_COMPILED_CLASSES AMSEDIT_ALL_CLASSES #define AMSEDIT_COMPILED_CLASSES AMSEDIT_DATETIME_CLASS ///////////////////////////////////////////////////////////////////////////// // CAMSEdit window // Class CAMSEdit is the base class for all the other AMS CEdit classes. // It provides some base functionality to set and get the text and change // its text and background color. // class AMSEDIT_EXPORT CAMSEdit : public CEdit { public: // Construction/destruction CAMSEdit(); virtual ~CAMSEdit(); // Operations void SetText(const CString& strText); CString GetText() const; CString GetTrimmedText() const; void SetBackgroundColor(COLORREF rgb); COLORREF GetBackgroundColor() const; void SetTextColor(COLORREF rgb); COLORREF GetTextColor() const; bool IsReadOnly() const; protected: virtual void Redraw(); virtual CString GetValidText() const; virtual BOOL OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult); virtual bool ShouldEnter(TCHAR c) const; protected: CBrush m_brushBackground; COLORREF m_rgbText; private: enum InternalFlags { None = 0x0000, TextColorHasBeenSet = 0x0001 }; UINT m_uInternalFlags; public: // Class SelectionSaver is used to save an edit box's current // selection and then restore it on destruction. class AMSEDIT_EXPORT SelectionSaver { public: SelectionSaver(CEdit* pEdit); SelectionSaver(CEdit* pEdit, int nStart, int nEnd); ~SelectionSaver(); void MoveTo(int nStart, int nEnd); void MoveBy(int nStart, int nEnd); void MoveBy(int nPos); void operator+=(int nPos); int GetStart() const; int GetEnd() const; void Update(); void Disable(); protected: CEdit* m_pEdit; int m_nStart, m_nEnd; }; // Class Behavior is an abstract base class used to define how an edit // box will behave when it is used. Note that its virtual member functions start // with an underscore; this avoids naming conflicts when multiply inheriting. class AMSEDIT_EXPORT Behavior { protected: Behavior(CAMSEdit* pEdit); virtual ~Behavior(); public: bool ModifyFlags(UINT uAdd, UINT uRemove); UINT GetFlags() const; public: virtual CString _GetValidText() const = 0; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags) = 0; virtual void _OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKillFocus(CWnd* pNewWnd); virtual LRESULT _OnPaste(WPARAM wParam, LPARAM lParam); protected: // Wrappers to allow access to protected members of CAMSEdit virtual LRESULT _Default(); virtual void _Redraw(); virtual bool _ShouldEnter(TCHAR c) const; protected: CAMSEdit* m_pEdit; UINT m_uFlags; }; friend class Behavior; #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_ALPHANUMERIC_CLASS) // The AlphanumericBehavior class is used to allow entry of alphanumeric // characters. It can be restricted in terms of what characters cannot // be inputed as well as how many are allowed altogether. class AMSEDIT_EXPORT AlphanumericBehavior : public Behavior { public: AlphanumericBehavior(CAMSEdit* pEdit, int nMaxChars = 0, const CString& strInvalidChars = _T("%'*\"+?><:\\")); // Operations void SetInvalidCharacters(const CString& strInvalidChars); const CString& GetInvalidCharacters() const; void SetMaxCharacters(int nMaxChars); int GetMaxCharacters() const; protected: virtual CString _GetValidText() const; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); protected: int m_nMaxChars; CString m_strInvalidChars; }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_ALPHANUMERIC_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_MASKED_CLASS) // The MaskedBehavior class is used to allow entry of numeric characters // based on a given mask containing '#' characters to hold digits. class AMSEDIT_EXPORT MaskedBehavior : public Behavior { public: // Construction MaskedBehavior(CAMSEdit* pEdit, const CString& strMask = _T("")); public: // Operations void SetMask(const CString& strMask); const CString& GetMask() const; CString GetNumericText() const; // The Symbol class represents a character which may be added to the mask and then interpreted by the // MaskedBehavior class to validate the input from the user and possibly convert it to something else. class AMSEDIT_EXPORT Symbol { public: #ifndef _UNICODE typedef int (*ValidationFunction)(UINT); // designed for functions such as _istdigit, _istalpha typedef UINT (*ConversionFunction)(UINT); // designed for functions such as _totupper, _totlower #else typedef int (*ValidationFunction)(WCHAR); typedef WCHAR (*ConversionFunction)(WCHAR); #endif Symbol(); Symbol(TCHAR cSymbol, ValidationFunction fnValidation, ConversionFunction fnConversion = NULL); virtual ~Symbol(); virtual bool Validate(TCHAR c) const; virtual TCHAR Convert(TCHAR c) const; void Set(TCHAR cSymbol); TCHAR Get() const; operator TCHAR() const; protected: TCHAR m_cSymbol; ValidationFunction m_fnValidation; ConversionFunction m_fnConversion; }; typedef CArray<Symbol, Symbol const&> SymbolArray; SymbolArray& GetSymbolArray(); protected: virtual CString _GetValidText() const; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); protected: // Attributes CString m_strMask; SymbolArray m_arraySymbols; }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_MASKED_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_NUMERIC_CLASS) // The NumericBehavior class is used to allow the entry of an actual numeric // value into the edit control. It may be restricted by the number of digits // before or after the decimal point (if any). If can also be set to use // commas to separate and group thousands. class AMSEDIT_EXPORT NumericBehavior : public Behavior { public: // Construction NumericBehavior(CAMSEdit* pEdit, int nMaxWholeDigits = 9, int nMaxDecimalPlaces = 4); public: // Operations void SetDouble(double dText, bool bTrimTrailingZeros = true); double GetDouble() const; void SetInt(int nText); int GetInt() const; void SetMaxWholeDigits(int nMaxWholeDigits); int GetMaxWholeDigits() const; void SetMaxDecimalPlaces(int nMaxDecimalPlaces); int GetMaxDecimalPlaces() const; void AllowNegative(bool bAllowNegative = true); bool IsNegativeAllowed() const; void SetDigitsInGroup(int nDigitsInGroup); int GetDigitsInGroup() const; void SetSeparators(TCHAR cDecimal, TCHAR cGroup); void GetSeparators(TCHAR* pcDecimal, TCHAR* pcGroup) const; void SetPrefix(const CString& strPrefix); const CString& GetPrefix() const; void SetMask(const CString& strMask); CString GetMask() const; void SetRange(double dMin, double dMax); void GetRange(double* pdMin, double* pdMax) const; virtual bool IsValid() const; bool CheckIfValid(bool bShowErrorIfNotValid = true); enum Flags { None = 0x0000, CannotBeNegative = 0x1000, AddDecimalAfterMaxWholeDigits = 0x2000, PadWithZerosAfterDecimalWhenTextChanges = 0x4000, PadWithZerosAfterDecimalWhenTextIsSet = 0x8000, OnKillFocus_Beep_IfInvalid = 0x0001, OnKillFocus_Beep_IfEmpty = 0x0002, OnKillFocus_Beep = 0x0003, OnKillFocus_SetValid_IfInvalid = 0x0004, OnKillFocus_SetValid_IfEmpty = 0x0008, OnKillFocus_SetValid = 0x000C, OnKillFocus_SetFocus_IfInvalid = 0x0010, OnKillFocus_SetFocus_IfEmpty = 0x0020, OnKillFocus_SetFocus = 0x0030, OnKillFocus_ShowMessage_IfInvalid = 0x0050, OnKillFocus_ShowMessage_IfEmpty = 0x00A0, OnKillFocus_ShowMessage = 0x00F0, OnKillFocus_PadWithZerosBeforeDecimal = 0x0100, OnKillFocus_PadWithZerosAfterDecimal = 0x0200, OnKillFocus_DontPadWithZerosIfEmpty = 0x0400, OnKillFocus_RemoveExtraLeadingZeros = 0x0800, OnKillFocus_Max = 0x0FFF }; protected: virtual CString _GetValidText() const; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKillFocus(CWnd* pNewWnd); int GetGroupSeparatorCount(const CString& strText) const; CString GetNumericText(const CString& strText, bool bUseMathSymbols = false) const; CString GetDoubleText(double dText, bool bTrimTrailingZeros = true) const; CString GetSeparatedText(const CString& strText) const; void AdjustSeparators(int nCurrentSeparatorCount); static void InsertZeros(CString* pStrText, int nPos, int nCount); virtual void ShowErrorMessage() const; void AdjustWithinRange(); protected: // Attributes int m_nMaxWholeDigits; int m_nMaxDecimalPlaces; TCHAR m_cNegativeSign; TCHAR m_cDecimalPoint; TCHAR m_cGroupSeparator; int m_nDigitsInGroup; CString m_strPrefix; double m_dMin; double m_dMax; private: bool m_bAdjustingSeparators; }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_NUMERIC_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATE_CLASS) // The DateBehavior class is used to allow the entry of date values. class AMSEDIT_EXPORT DateBehavior : virtual public Behavior { public: // Construction DateBehavior(CAMSEdit* pEdit); public: // Operations void SetDate(int nYear, int nMonth, int nDay); void SetDate(const CTime& date); void SetDate(const COleDateTime& date); void SetDateToToday(); CTime GetDate() const; COleDateTime GetOleDate() const; int GetYear() const; int GetMonth() const; int GetDay() const; void SetYear(int nYear); void SetMonth(int nMonth); void SetDay(int nDay); virtual bool IsValid() const; bool CheckIfValid(bool bShowErrorIfNotValid = true); void SetRange(const CTime& dateMin, const CTime& dateMax); void SetRange(const COleDateTime& dateMin, const COleDateTime& dateMax); void GetRange(CTime* pDateMin, CTime* pDateMax) const; void GetRange(COleDateTime* pDateMin, COleDateTime* pDateMax) const; void SetSeparator(TCHAR cSep); TCHAR GetSeparator() const; void ShowDayBeforeMonth(bool bDayBeforeMonth = true); bool IsDayShownBeforeMonth() const; enum Flags { None = 0x0000, DayBeforeMonth = 0x1000, OnKillFocus_Beep_IfInvalid = 0x0001, OnKillFocus_Beep_IfEmpty = 0x0002, OnKillFocus_Beep = 0x0003, OnKillFocus_SetValid_IfInvalid = 0x0004, OnKillFocus_SetValid_IfEmpty = 0x0008, OnKillFocus_SetValid = 0x000C, OnKillFocus_SetFocus_IfInvalid = 0x0010, OnKillFocus_SetFocus_IfEmpty = 0x0020, OnKillFocus_SetFocus = 0x0030, OnKillFocus_ShowMessage_IfInvalid = 0x0050, OnKillFocus_ShowMessage_IfEmpty = 0x00A0, OnKillFocus_ShowMessage = 0x00F0, OnKillFocus_Max = 0x00FF }; protected: virtual CString _GetValidText() const; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKillFocus(CWnd* pNewWnd); protected: // Helpers bool AdjustMaxMonthAndDay(); bool AdjustMaxDay(); int GetValidMonth() const; int GetMaxMonth() const; int GetMinMonth() const; int GetMonthStartPosition() const; TCHAR GetMaxMonthDigit(int nPos) const; TCHAR GetMinMonthDigit(int nPos) const; bool IsValidMonthDigit(TCHAR c, int nPos) const; bool IsValidMonth(int nMonth) const; int GetValidDay() const; int GetMaxDay() const; int GetMinDay() const; int GetDayStartPosition() const; TCHAR GetMaxDayDigit(int nPos) const; TCHAR GetMinDayDigit(int nPos) const; bool IsValidDayDigit(TCHAR c, int nPos) const; bool IsValidDay(int nDay) const; int GetValidYear() const; int GetYearStartPosition() const; TCHAR GetMaxYearDigit(int nPos) const; TCHAR GetMinYearDigit(int nPos, bool bValidYear = false) const; bool IsValidYearDigit(TCHAR c, int nPos) const; bool IsValidYear(int nYear) const; virtual bool IsWithinRange(const COleDateTime& date, bool bDateOnly = true) const; virtual void ShowErrorMessage() const; CString GetFormattedDate(int nYear, int nMonth, int nDay) const; public: static bool IsLeapYear(int nYear); static CString GetString(int nValue, bool bTwoDigitWithLeadingZero = true); static int GetMaxDayOfMonth(int nMonth, int nYear); protected: // Attributes COleDateTime m_dateMin; COleDateTime m_dateMax; TCHAR m_cSep; }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATE_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_TIME_CLASS) // The TimeBehavior class is used to allow the entry of time values. class AMSEDIT_EXPORT TimeBehavior : virtual public Behavior { public: // Construction TimeBehavior(CAMSEdit* pEdit); public: // Operations void SetTime(int nHour, int nMinute, int nSecond = 0); void SetTime(const CTime& time); void SetTime(const COleDateTime& time); void SetTimeToNow(); CTime GetTime() const; COleDateTime GetOleTime() const; int GetHour() const; int GetMinute() const; int GetSecond() const; CString GetAMPM() const; void SetHour(int nYear); void SetMinute(int nMonth); void SetSecond(int nDay); void SetAMPM(bool bAM); virtual bool IsValid() const; bool IsValid(bool bCheckRangeAlso) const; bool CheckIfValid(bool bShowErrorIfNotValid = true); void SetRange(const CTime& dateMin, const CTime& dateMax); void SetRange(const COleDateTime& dateMin, const COleDateTime& dateMax); void GetRange(CTime* pDateMin, CTime* pDateMax) const; void GetRange(COleDateTime* pDateMin, COleDateTime* pDateMax) const; void SetSeparator(TCHAR cSep); TCHAR GetSeparator() const; void Show24HourFormat(bool bShow24HourFormat = true); bool IsShowing24HourFormat() const; void ShowSeconds(bool bShowSeconds = true); bool IsShowingSeconds() const; void SetAMPMSymbols(const CString& strAM, const CString& strPM); void GetAMPMSymbols(CString* pStrAM, CString* pStrPM) const; enum Flags { None = 0x0000, TwentyFourHourFormat = 0x2000, WithSeconds = 0x4000, OnKillFocus_Beep_IfInvalid = 0x0001, OnKillFocus_Beep_IfEmpty = 0x0002, OnKillFocus_Beep = 0x0003, OnKillFocus_SetValid_IfInvalid = 0x0004, OnKillFocus_SetValid_IfEmpty = 0x0008, OnKillFocus_SetValid = 0x000C, OnKillFocus_SetFocus_IfInvalid = 0x0010, OnKillFocus_SetFocus_IfEmpty = 0x0020, OnKillFocus_SetFocus = 0x0030, OnKillFocus_ShowMessage_IfInvalid = 0x0050, OnKillFocus_ShowMessage_IfEmpty = 0x00A0, OnKillFocus_ShowMessage = 0x00F0, OnKillFocus_Max = 0x00FF }; protected: virtual CString _GetValidText() const; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKillFocus(CWnd* pNewWnd); protected: // Helpers int GetValidHour(bool b24HourFormat = false) const; int GetMaxHour(bool b24HourFormat = false) const; int GetMinHour(bool b24HourFormat = false) const; int GetHourStartPosition() const; TCHAR GetMaxHourDigit(int nPos) const; TCHAR GetMinHourDigit(int nPos) const; bool IsValidHourDigit(TCHAR c, int nPos) const; bool IsValidHour(int nHour, bool b24HourFormat = false) const; int ConvertTo24Hour(int nHour, const CString& strAMPM) const; int ConvertToAMPMHour(int nHour, CString* pStrAMPM = NULL) const; int GetValidMinute() const; int GetMaxMinute() const; int GetMinMinute() const; int GetMaxSecond() const; int GetMinSecond() const; int GetMinuteStartPosition() const; TCHAR GetMaxMinuteDigit(int nPos) const; TCHAR GetMinMinuteDigit(int nPos) const; bool IsValidMinuteDigit(TCHAR c, int nPos) const; bool IsValidMinute(int nMinute) const; int GetValidSecond() const; int GetSecondStartPosition() const; TCHAR GetMaxSecondDigit(int nPos) const; TCHAR GetMinSecondDigit(int nPos) const; bool IsValidSecondDigit(TCHAR c, int nPos) const; bool IsValidSecond(int nSecond) const; void ShowAMPM(); bool ChangeAMPM(TCHAR c); CString GetValidAMPM() const; int GetAMPMStartPosition() const; bool IsValidAMPM(const CString& strAMPM) const; int GetAMPMPosition(const CString& strText) const; virtual bool IsWithinRange(const COleDateTime& date, bool bDateOnly = true) const; virtual void ShowErrorMessage() const; CString GetFormattedTime(int nHour, int nMinute, int nSecond, const CString& strAMPM = _T("")) const; void AdjustWithinRange(); protected: // Attributes COleDateTime m_timeMin; COleDateTime m_timeMax; TCHAR m_cSep; CString m_strAM; CString m_strPM; int m_nAMPMLength; int m_nHourStart; }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_TIME_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATETIME_CLASS) == AMSEDIT_DATETIME_CLASS // The DateTimeBehavior class is used to allow the entry of date and time values. class AMSEDIT_EXPORT DateTimeBehavior : public DateBehavior, public TimeBehavior { public: // Construction DateTimeBehavior(CAMSEdit* pEdit); void SetDateTime(int nYear, int nMonth, int nDay, int nHour, int nMinute, int nSecond = 0); void SetDateTime(const CTime& dt); void SetDateTime(const COleDateTime& dt); void SetToNow(); CTime GetDateTime() const; COleDateTime GetOleDateTime() const; virtual bool IsValid() const; void SetRange(const CTime& dateMin, const CTime& dateMax); void SetRange(const COleDateTime& dateMin, const COleDateTime& dateMax); void GetRange(CTime* pDateMin, CTime* pDateMax) const; void GetRange(COleDateTime* pDateMin, COleDateTime* pDateMax) const; void SetSeparator(TCHAR cSep, bool bDate); TCHAR GetSeparator(bool bDate) const; bool ModifyFlags(UINT uAdd, UINT uRemove); enum Flags { DateOnly = 0x0100, TimeOnly = 0x0200, OnKillFocus_Beep_IfInvalid = 0x0001, OnKillFocus_Beep_IfEmpty = 0x0002, OnKillFocus_Beep = 0x0003, OnKillFocus_SetValid_IfInvalid = 0x0004, OnKillFocus_SetValid_IfEmpty = 0x0008, OnKillFocus_SetValid = 0x000C, OnKillFocus_SetFocus_IfInvalid = 0x0010, OnKillFocus_SetFocus_IfEmpty = 0x0020, OnKillFocus_SetFocus = 0x0030, OnKillFocus_ShowMessage_IfInvalid = 0x0050, OnKillFocus_ShowMessage_IfEmpty = 0x00A0, OnKillFocus_ShowMessage = 0x00F0, OnKillFocus_Max = 0x00FF }; protected: virtual CString _GetValidText() const; virtual void _OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); virtual void _OnKillFocus(CWnd* pNewWnd); protected: virtual bool IsWithinRange(const COleDateTime& date, bool bDateOnly = true) const; virtual void ShowErrorMessage() const; }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATETIME_CLASS) == AMSEDIT_DATETIME_CLASS // Generated message map functions (for CAMSEdit) protected: //{{AFX_MSG(CAMSEdit) //}}AFX_MSG afx_msg LRESULT OnCut(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnPaste(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnClear(WPARAM wParam, LPARAM lParam); afx_msg LRESULT OnSetText(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_ALPHANUMERIC_CLASS) ///////////////////////////////////////////////////////////////////////////// // CAMSAlphanumericEdit window // The CAMSAlphanumericEdit is a CAMSEdit control which supports the AlphanumericBehavior class. // class AMSEDIT_EXPORT CAMSAlphanumericEdit : public CAMSEdit, public CAMSEdit::AlphanumericBehavior { public: // Construction CAMSAlphanumericEdit(int nMaxChars = 0, const CString& strInvalidChars = _T("%'*\"+?><:\\")); protected: virtual CString GetValidText() const; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSAlphanumericEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSAlphanumericEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_ALPHANUMERIC_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_MASKED_CLASS) ///////////////////////////////////////////////////////////////////////////// // CAMSMaskedEdit window // The CAMSMaskedEdit is a CAMSEdit control which supports the MaskedBehavior class. // class AMSEDIT_EXPORT CAMSMaskedEdit : public CAMSEdit, public CAMSEdit::MaskedBehavior { public: // Construction CAMSMaskedEdit(const CString& strMask = _T("")); protected: virtual CString GetValidText() const; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSMaskedEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSMaskedEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_MASKED_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_NUMERIC_CLASS) ///////////////////////////////////////////////////////////////////////////// // CAMSNumericEdit window // The CAMSNumericEdit is a CAMSEdit control which supports the NumericBehavior class. // class AMSEDIT_EXPORT CAMSNumericEdit : public CAMSEdit, public CAMSEdit::NumericBehavior { public: CAMSNumericEdit(int nMaxWholeDigits = 9, int nMaxDecimalPlaces = 4); protected: virtual CString GetValidText() const; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSNumericEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSNumericEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_NUMERIC_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_INTEGER_CLASS) == AMSEDIT_INTEGER_CLASS ///////////////////////////////////////////////////////////////////////////// // CAMSIntegerEdit window // The CAMSNumericEdit is a CAMSEdit control which supports the NumericBehavior class // restricted to only allow integer values. // class AMSEDIT_EXPORT CAMSIntegerEdit : public CAMSNumericEdit { public: // Construction CAMSIntegerEdit(int nMaxWholeDigits = 9); private: // Hidden members -- they don't make sense here void SetDouble(double dText, bool bTrimTrailingZeros = true); double GetDouble() const; void SetMaxDecimalPlaces(int nMaxDecimalPlaces); // always 0 public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSIntegerEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSIntegerEdit) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_INTEGER_CLASS) == AMSEDIT_INTEGER_CLASS #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_CURRENCY_CLASS) == AMSEDIT_CURRENCY_CLASS ///////////////////////////////////////////////////////////////////////////// // CAMSCurrencyEdit window // The CAMSNumericEdit is a CAMSEdit control which supports the NumericBehavior class // modified to put the '$' character in front of the value and use commas to separate the thousands. // class AMSEDIT_EXPORT CAMSCurrencyEdit : public CAMSNumericEdit { public: // Construction CAMSCurrencyEdit(); public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSCurrencyEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSCurrencyEdit) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_CURRENCY_CLASS) == AMSEDIT_CURRENCY_CLASS #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATE_CLASS) ///////////////////////////////////////////////////////////////////////////// // CAMSDateEdit window // The CAMSDateEdit is a CAMSEdit control which supports the DateBehavior class. // class AMSEDIT_EXPORT CAMSDateEdit : public CAMSEdit, public CAMSEdit::DateBehavior { public: // Construction CAMSDateEdit(); protected: virtual CString GetValidText() const; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSDateEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSDateEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG afx_msg LRESULT OnPaste(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATE_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_TIME_CLASS) ///////////////////////////////////////////////////////////////////////////// // CAMSTimeEdit window // The CAMSTimeEdit is a CAMSEdit control which supports the TimeBehavior class. // class AMSEDIT_EXPORT CAMSTimeEdit : public CAMSEdit, public CAMSEdit::TimeBehavior { public: // Construction CAMSTimeEdit(); protected: virtual CString GetValidText() const; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSTimeEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSTimeEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG afx_msg LRESULT OnPaste(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_TIME_CLASS) #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATETIME_CLASS) == AMSEDIT_DATETIME_CLASS ///////////////////////////////////////////////////////////////////////////// // CAMSDateTimeEdit window // The CAMSDateTimeEdit is a CAMSEdit control which supports the // DateBehavior and TimeBehavior classes. // class AMSEDIT_EXPORT CAMSDateTimeEdit : public CAMSEdit, public CAMSEdit::DateTimeBehavior { public: // Construction CAMSDateTimeEdit(); protected: virtual CString GetValidText() const; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSDateTimeEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSDateTimeEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG afx_msg LRESULT OnPaste(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_DATETIME_CLASS) == AMSEDIT_DATETIME_CLASS #if (AMSEDIT_COMPILED_CLASSES & AMSEDIT_ALL_CLASSES) == AMSEDIT_ALL_CLASSES ///////////////////////////////////////////////////////////////////////////// // CAMSMultiMaskedEdit window // The CAMSMultiMaskedEdit class is a CAMSEdit control which can support the // AlphanumericBehavior, NumericBehavior, MaskedBehavior, DateBehavior, or // TimeBehavior behavior classes. It uses the mask to determine the current behavior. // class AMSEDIT_EXPORT CAMSMultiMaskedEdit : public CAMSEdit, public CAMSEdit::AlphanumericBehavior, public CAMSEdit::NumericBehavior, public CAMSEdit::MaskedBehavior, public CAMSEdit::DateTimeBehavior { public: CAMSMultiMaskedEdit(); const CString& GetMask() const; void SetMask(const CString& strMask); protected: virtual CString GetValidText() const; // Attributes Behavior* m_pCurrentBehavior; public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAMSMultiMaskedEdit) //}}AFX_VIRTUAL // Generated message map functions protected: //{{AFX_MSG(CAMSMultiMaskedEdit) afx_msg void OnChar(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyDown(UINT uChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKillFocus(CWnd* pNewWnd); //}}AFX_MSG afx_msg LRESULT OnPaste(WPARAM wParam, LPARAM lParam); DECLARE_MESSAGE_MAP() }; #endif // (AMSEDIT_COMPILED_CLASSES & AMSEDIT_ALL_CLASSES) == AMSEDIT_ALL_CLASSES #define AMS_MIN_NUMBER -1.7976931348623158e+308 #define AMS_MAX_NUMBER 1.7976931348623158e+308 #define AMS_MIN_CTIME CTime(1970, 1, 1, 0, 0, 0) #define AMS_MAX_CTIME CTime(2037, 12, 31, 23, 59, 59) #define AMS_MIN_OLEDATETIME COleDateTime(1900, 1, 1, 0, 0, 0) #define AMS_MAX_OLEDATETIME COleDateTime(9998, 12, 31, 23, 59, 59) #define AMS_AM_SYMBOL _T("AM") #define AMS_PM_SYMBOL _T("PM") ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_AMS_EDIT_H__AC5ACB94_4363_11D3_9123_00105A6E5DE4__INCLUDED_)
c196b11b9e3d7182b83db657b673a87770045a2d
8967fc8b81710a463d54350144bd672c2b6c4f6f
/Graph Algorithms/FlightRoutesCheck.cpp
b71e2d97d0ba6d3538348fed4ca93f8b544b23e3
[]
no_license
shuba400/CSES_Problem_Set
98623cae3eb33ba2867259b14c9cff2a9e8fb478
428fd4a2592d4ab1a3537eb85a7378bf3d8f2ef4
refs/heads/main
2023-04-27T04:31:42.883658
2021-05-16T10:52:22
2021-05-16T10:52:22
306,539,577
0
0
null
null
null
null
UTF-8
C++
false
false
2,856
cpp
FlightRoutesCheck.cpp
/* This is a standard application of Strongly Connected Components(SCC) in graph.For solving this question all you need to know is what exactly is Strongly Connected Component. Since this is simple application I have linked down some resources to understand SCC https://cp-algorithms.com/graph/strongly-connected-components.html#toc-tgt-3 So you must have read about SCC, now only thing left in this question is to check is number of SCC in graph. If nums(SCC) == 1 we can simply print the answer else we have to print no and check for non reachable nodes. How to check non reachable nodes? Simple - Take elements of 2 SCCs(node u and v),Run a dfs from u and check if we can reach node v or not If we cannot than by deafult answer will be u v Else answer will be v u.(Think about this on your own) */ #include<bits/stdc++.h> #define _USE_MATH_DEFINES using namespace std; #define ll long long int #define ld double #define pb push_back #define rep(i , j , n) for(ll i = j ; i < n ; i++) #define pre(i , j , n) for(ll i = j ; i >= n ; i--) #define all(x) x.begin(), x.end() typedef pair<int, int> pii; typedef pair<ll, ll> pl; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<double> vd; typedef vector<bool> vb; typedef pair<ll,ll> pll; #define br "\n" #define ff first #define ss second #define debug(a...) cout<<#a<<": ";for(auto it:a)cout<<it<<" ";cout<<endl; ll MAX = 1e6 + 1; ll mod = 1e9 + 7; stack<ll> s; vector<vll> g1,g2,comp; vb vis; void dfs1(ll u){ vis[u] = 1; for(auto &x:g1[u]){ if(vis[x]) continue; dfs1(x); } s.push(u); } void dfs2(ll u,vll &v){ vis[u] = 1; for(auto &x:g2[u]){ if(vis[x]) continue; dfs2(x,v); } v.pb(u); } void solve(){ ll n,m; cin >> n >> m; g1.resize(n + 1); g2.resize(n + 1); vis.assign(n + 1,false); rep(i,0,m){ ll a,b; cin >> a >> b; g1[a].pb(b); g2[b].pb(a); } rep(i,1,n + 1){ if(!vis[i]) dfs1(i); } vis.clear(); vis.assign(n + 1,false); while(!s.empty()){ ll i = s.top(); s.pop(); if(!vis[i]){ vll temp; dfs2(i,temp); comp.pb(temp); } } if(comp.size() == 1){ cout << "YES" << br; return; } vis.clear(); vis.assign(n + 1,false); ll u = comp[0][0],v = comp[1][0]; dfs1(u); cout << "NO" << br; if(vis[v]) cout << v << " " << u; else cout << u << " " << v; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ll t = 1; // calc(); // cin >> t; // calc(); rep(i,0,t){ // cout << "Case #" << i + 1 << ": "; solve(); // test(); } }
cdd75a42630e2e47ae1997cb5da800c7fd552571
5c54ecf35c8706e44b9942bc4376333b17e15fa2
/NEETGameMaker/WindowSceneUpdater.cpp
0d0dd3c5fa861aa6f432c91a920efaf59f18db11
[]
no_license
Nekokino/NEET01
643789065e008f04ea2164acfbaefdc2e4a18681
9c2d85c85dce14e04e865a3a33ab27549852d40c
refs/heads/master
2020-03-25T19:28:16.355256
2018-09-03T02:37:40
2018-09-03T02:37:40
144,084,620
0
0
null
2018-08-09T01:19:01
2018-08-09T01:10:31
C++
UTF-8
C++
false
false
461
cpp
WindowSceneUpdater.cpp
#include "WindowSceneUpdater.h" #include "GameSystem.h" #include "NTPieceWindow.h" #include <InputSystem.h> #include <NTWinShortCut.h> WindowSceneUpdater::WindowSceneUpdater() { } WindowSceneUpdater::~WindowSceneUpdater() { } void WindowSceneUpdater::SceneUpdate() { GameSystem::TimeUpdate(); if (InputSystem::IsDown(L"Key3") == true) { NTWinShortCut::GetMainSceneSystem().ChangeScene(L"DebugScene"); } } void WindowSceneUpdater::SceneStart() { }
fe9daf49e7bace40a9f992467295354870485045
bdf817af2b2d1dbf114b96a72da8012041dd591e
/src/lib/pdata.cpp
aa5ceb8b2d4af36b719d87b7c190ceae6afd43cd
[]
no_license
IBirdSoft/openfpm_pdata_3.0.0
8f64fc90ba656009879325adea9020cdb452f1e4
3c7c35f66f2b244b48f7968941240f19f099bddc
refs/heads/master
2022-12-30T10:24:11.648481
2020-10-18T00:47:26
2020-10-18T00:47:26
272,805,498
0
1
null
null
null
null
UTF-8
C++
false
false
1,663
cpp
pdata.cpp
/* * pdata.cpp * * Created on: Feb 5, 2016 * Author: Pietro Incardona */ #include "pdata.hpp" #include "SubdomainGraphNodes.hpp" #include "memory/CudaMemory.cuh" template<> const std::string nm_v<10>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<9>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<7>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<6>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<5>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<4>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<3>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<2>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; template<> const std::string nm_v<1>::attributes::name[] = {"x","migration","computation","global_id","id","sub_id","proc_id","id","fake_v"}; const std::string nm_e::attributes::name[] = {"communication","srcgid","dstgid"}; const std::string nm_part_v::attributes::name[] = {"id","sub_id"}; const std::string nm_part_e::attributes::name[] = {"id"};
e89119f807225d03a92ea7b8bfaab0ebd6b9a726
ddfc7ca35daa03bbee886422af9d6175a328161e
/deck.h
d70b077b1446c57e42f92056f65cbfd745108b0b
[]
no_license
lucaspalmer8/Hearts
04377b6955aa3fcddfa2d0546c5d8158b83e668b
c6c6378040d16c47b03d97521895c3ac7c1bddbe
refs/heads/master
2021-01-13T02:26:51.749962
2016-01-15T04:55:07
2016-01-15T04:55:07
35,779,243
1
0
null
null
null
null
UTF-8
C++
false
false
360
h
deck.h
#ifndef __deck__h #define __deck__h #include<vector> #include"card.h" #include<iostream> class Deck { public: static int instance; static int isDeck(); Deck(); ~Deck(); void Shuffle(); static void addinstance(); static void subinstance(); std::vector<Card*> deckofcards; }; std::ostream& operator<<(std::ostream& out, const Deck& d); #endif
7e03575564de6f672e23dce02516e753bdaa734a
f9dcd8bbcd2038c5fd5a014ee395aaa71dbf3a05
/util.cpp
000cd2c14bcaa224e8a5a4337899165c036a0b53
[]
no_license
locchuong/autocomplete
2de982ac2810d20595eb1d18e40e04c86d99b7ff
fa2cef8b3fdccecc74de4fb03b4272633289d73e
refs/heads/master
2022-12-06T12:42:45.790329
2020-08-24T22:27:45
2020-08-24T22:27:45
289,876,018
5
1
null
null
null
null
UTF-8
C++
false
false
4,558
cpp
util.cpp
#include <iostream> #include <sstream> #include "util.hpp" using std::istream; using std::endl; using std::cout; using std::istringstream; using std::string; using std::vector; /** * Starts the timer. Saves the current time. */ void Timer::begin_timer() { start = std::chrono::high_resolution_clock::now(); } /** * Ends the timer. Compares end time with the start time and returns number of nanoseconds */ long long Timer::end_timer() { std::chrono::time_point<std::chrono::high_resolution_clock> end; end = std::chrono::high_resolution_clock::now(); return (long long)std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count(); } /** * Parse a line by taking the number at the beginning of a file. * This might be helpful if you want make your own test files of * the following format: * * ---- * 7 word * 8 words * 9 wordlike * ---- * * For example, you could use the following snippet: * * getline(words, line); * if (words.eof()) * break; * unsigned int freq = Utils::stripFrequency(line); * dict.insert(line, freq); * * Input: a line from a dictionary file. This line will be modified. */ unsigned int Utils::stripFrequency(string& line) { // Count the number of characters past the first space int count = 0; string::iterator last = line.end(); for (string::iterator it = line.begin(); it != last; ++it) { count++; if (*it == ' ') { break; } } unsigned int freq = std::stoi(line.substr(0, count)); line.erase(0, count); return freq; } /** * Parses all the tokens on a given line, returning them * in a vector. */ vector<string> Utils::getWordsFromLine(string& line) { vector<string> words; std::stringstream ss(line); string word; while (!ss.eof()) { ss >> word; words.push_back(word); } return words; } /* * Load the words in the file into the dictionary trie */ void Utils::load_dict(DictionaryTrie& dict, istream& words) { unsigned int freq; string data = ""; string temp_word = ""; string word = ""; vector<string> word_string; unsigned int i = 0; while(getline(words, data)) { if(words.eof()) break; temp_word = ""; word = ""; data = data + " ."; istringstream iss(data); iss >> freq; while(1) { iss >> temp_word; if(temp_word == ".") break; if(temp_word.length() > 0) word_string.push_back(temp_word); } for(i = 0; i < word_string.size(); i++) { if(i > 0) word = word + " "; word = word + word_string[i]; } dict.insert(word, freq); word_string.clear(); } } /* * Load num_words from words stream into the dictionary trie */ void Utils::load_dict(DictionaryTrie& dict, istream& words, unsigned int num_words) { unsigned int freq; string data = ""; string temp_word = ""; string word = ""; vector<string> word_string; unsigned int i = 0; unsigned int j = 0; for(; j < num_words; j++) { getline(words, data); if(words.eof()) break; temp_word = ""; word = ""; data = data + " ."; istringstream iss(data); iss >> freq; while(1) { iss >> temp_word; if(temp_word == ".") break; if(temp_word.length() > 0) word_string.push_back(temp_word); } for(i = 0; i < word_string.size(); i++) { if(i > 0) word = word + " "; word = word + word_string[i]; } dict.insert(word, freq); word_string.clear(); } } void Utils::load_dict(vector<string>& dict, istream& words) { unsigned int junk; string data = ""; string temp_word = ""; string word = ""; vector<string> word_string; unsigned int i = 0; while(getline(words, data)) { if(words.eof()) break; temp_word = ""; word = ""; data = data + " ."; istringstream iss(data); iss >> junk; while(1) { iss >> temp_word; if(temp_word == ".") break; if(temp_word.length() > 0) word_string.push_back(temp_word); } for(i = 0; i < word_string.size(); i++) { if(i > 0) word = word + " "; word = word + word_string[i]; } dict.push_back(word); word_string.clear(); } }
79027efc9aa2febd648c3a6892b5eae05fe80c88
c52af50c82e70fb00e1c64c17d76b9a289876293
/regularized_decomposition/src/q5.cpp
c139da17369dae8f2a38e3a1fa184c251b0f4a1b
[]
no_license
davidlove/omrp
7686c7968c8941b3e66dfc2e5c599c3ccba82623
829ddcfd0f18542f7f8feea049bdc1663044cafa
refs/heads/master
2016-09-06T09:50:52.658757
2014-07-14T00:50:27
2014-07-14T00:50:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,650
cpp
q5.cpp
/*------------------------------------------------------------------------------ FILE Q5 Routines for advanced matrix operations Q5ADRW - PLANE REFLECTIONS TO ADD A ROW, Q5DLCO - PLANE REFLECTIONS TO DELETE A COLUMN, Q5DLRW - PLANE REFLECTIONS TO DELETE A ROW, Q5GVNS - TO COMPUTE THE GIVENS REFLECTOR, Q5REFL - TO APPLY THE REFLECTOR TO TWO VECTORS, Q5REXP - TO ADD A COLUMN TO A TRIANGULAR MATRIX STORED BY ROWS, Q5RPCK - TO DELETE A COLUMN AND THE FOLLOWING DIAGONAL ELEMENTS FROM A MATRIX STORED BY ROWS, Q5TRIS - TO SOLVE A TRIANGULAR SYSTEM OF EQUATIONS. -------------------------------------------------------------------------------- WRITTEN BY A. RUSZCZYNSKI , INSTITUT FUER OPERATIONS RESEARCH, UNIVERSITAET ZUERICH, FEBRUARY 1985. DATE LAST MODIFIED: OCTOBER 1985. ------------------------------------------------------------------------------*/ /* q5.f -- translated by f2c (version 19940705.1). You must link the resulting object file with the libraries: -lf2c -lm (in that order) -------------------------------------------------------------------------------- Modified by Artur Swietanowski. */ #include <math.h> #ifndef __QDX_LOC_H__ # include "qdx_loc.h" #endif /* Table of constant values */ static Int_T q5_c_1 = 1; int q5adrw_( Int_T *m, Real_T *r, Real_T *z, Real_T *w, Real_T *pi, // ) Real_T *zlast, Real_T *wlast ) { /* Local variables */ Real_T c; Int_T i; Real_T p, s; Int_T ir, len; /*-------------------------------------------------------------------------- PURPOSE: APPLIES REFLECTIONS TO ROWS OF R AND TO PI TO ANNULATE PI WHILE PRESERVING UPPER TRIANGULARITY OF R. --------------------------------------------------------------------------*/ /* Parameter adjustments */ --pi; --w; --z; --r; /* Function Body */ if (*m < 1) return 0; ir = 1; len = *m; for (i = 1; i <= *m; ++i) { q5gvns_(&r[ir], &pi[i], &c, &s, &p); ++ir; --len; if (s != 0.) { q5refl_(&len, &r[ir], &pi[i + 1], &c, &s, &p); q5refl_(&q5_c_1, &z[i], zlast, &c, &s, &p); q5refl_(&q5_c_1, &w[i], wlast, &c, &s, &p); } ir += len; } return 0; } /* -----END OF Q5ADRW----------------------------------------------------- */ int q5dlco_( Int_T *m, Int_T *idel, Real_T *r, Real_T *z, Real_T *w ) { /* Local variables */ Int_T imax; Real_T c; Int_T i; Real_T p, s; Int_T ix, iy, lenrow; /*-------------------------------------------------------------------------- SUBROUTINES CALLED Q5GVNS,Q5RPCK,Q5REFL. PURPOSE: DELETES COLUMN IDEL FROM A QR FACTORIZATION BY DELETING COLUMN IDEL FROM R AND RESTORING UPPER TRIANGULAR FORM OF R BY GIVENS REFLECTIONS (ROW OPERATIONS). REFLECTIONS ARE APPLIED ALSO TO VECTORS Z AND W AND TOP PARTS OF Z AND W STILL SATISFY EQUATIONS Z=Q'C AND R'W=B (B,C - FIXED ). NOTE THAT R IS STORED BY ROWS AND Q IS NOT STORED AT ALL. --------------------------------------------------------------------------*/ /* Parameter adjustments */ --w; --z; --r; /* Function Body */ if (*m < 1) return 0; if (*idel != *m) { iy = Int_T( (*idel - 1) * ((*m << 1) - *idel + 2) / 2 + 2 ); lenrow = Int_T( *m - *idel ); imax = Int_T( *m - 1 ); for (i = *idel; i <= imax; ++i) { ix = iy; iy += lenrow; --lenrow; q5gvns_(&r[ix], &r[iy], &c, &s, &p); ++iy; if (s != 0.) { q5refl_(&lenrow, &r[ix + 1], &r[iy], &c, &s, &p); q5refl_(&q5_c_1, &z[i], &z[i + 1], &c, &s, &p); q5refl_(&q5_c_1, &w[i], &w[i + 1], &c, &s, &p); } } } q5rpck_(m, &r[1], idel); return 0; } /* ----END OF Q5DLCO----------------------------------------------------- */ int q5dlrw_( Int_T *m, Real_T *r, Real_T *z, Real_T *w, Real_T *pi, // ) Real_T *col, Real_T *rho, Real_T *zlast, Real_T *wlast ) { /* Local variables */ Real_T c; Int_T i; Real_T p, s; Int_T ir, len; /*-------------------------------------------------------------------------- PURPOSE: APPLIES REFLECTIONS TO COL AND RHO TO MAKE COL ZERO AND RHO ONE WHILE PRESERVING UPPER TRIANGULARITY OF R. --------------------------------------------------------------------------*/ /* Parameter adjustments */ --col; --pi; --w; --z; --r; /* Function Body */ if (*m < 1) return 0; dzero_(*m, &pi[1]); i = Int_T( *m + 1 ); ir = Int_T( *m * i / 2 + 1 ); for (len = 1; len <= *m; ++len) { ir -= len; --i; q5gvns_(rho, &col[i], &c, &s, &p); if (s != 0.) { q5refl_(&len, &pi[i], &r[ir], &c, &s, &p); q5refl_(&q5_c_1, zlast, &z[i], &c, &s, &p); q5refl_(&q5_c_1, wlast, &w[i], &c, &s, &p); } } return 0; } /* -----END OF Q5DLRW----------------------------------------------------- */ int q5gvns_( Real_T *x, Real_T *y, Real_T *c, Real_T *s, Real_T *p ) { /* Local variables */ Real_T t; /*-------------------------------------------------------------------------- PURPOSE: COMPUTES PARAMETERS FOR THE GIVENS MATRIX G FOR WHICH (X,Y)G = (Z,0). REPLACES (X,Y) BY (Z,0). --------------------------------------------------------------------------*/ if (*y == 0.) { *c = 1.; *s = 0.; *p = 0.; } else if (*x == 0.) { *c = 0.; *s = 1.; *p = 1.; *x = *y; *y = 0.; } else { /* Computing 2nd power */ t = sqrt( *x * *x + *y * *y ); t = ( *x > 0.0 ) ? t : -t; *c = *x / t; *s = *y / t; *p = *y / (t + *x); *x = t; *y = 0.; } return 0; } /* -----END OF Q5GVNS----------------------------------------------------- */ int q5refl_( Int_T *n, Real_T *x, Real_T *y, Real_T *c, Real_T *s, Real_T *p ) { /* Local variables */ Int_T i; Real_T u; /*-------------------------------------------------------------------------- PURPOSE: REPLACES THE TWO-COLUMN MATRIX (X,Y) BY (X,Y)G , WHERE G IS THE GIVENS MATRIX FROM SUBROUTINE Q5GVNS. --------------------------------------------------------------------------*/ /* Parameter adjustments */ --y; --x; /* Function Body */ if (*n < 1) return 0; if (*c == 0.) for (i = 1; i <= *n; ++i) { u = x[i]; x[i] = y[i]; y[i] = u; } else for (i = 1; i <= *n; ++i) { u = x[i]; x[i] = u * *c + y[i] * *s; y[i] = (x[i] + u) * *p - y[i]; } return 0; } /* -----END OF Q5REFL----------------------------------------------------- */ int q5rexp_( Int_T *m, Real_T *r, Real_T *c ) { /* Local variables */ Int_T iold, inew, j, jdummy; /*-------------------------------------------------------------------------- PURPOSE: AUGMENTS THE UPPER TRIANGULAR MATRIX R STORED BY ROWS, R11,R12,...,R1M,R22,...,R2M,...,RMM, BY ADDING THE COLUMN C, WHICH YIELDS THE NEW R OF THE FORM R11,...,R1M,C(1),R22,...,R2M,C(2),R33,...,RMM,C(M),C(M+1). --------------------------------------------------------------------------*/ /* Parameter adjustments */ --c; --r; /* Function Body */ j = Int_T( *m + 1 ); iold = Int_T( *m * j / 2 + 1 ); inew = Int_T( iold + *m ); r[inew] = c[j]; while( j != 1 ) { --j; --inew; r[inew] = c[j]; for (jdummy = j; jdummy <= *m; ++jdummy) { --inew; --iold; r[inew] = r[iold]; } } return 0; } /* -----END OF Q5REXP----------------------------------------------------- */ int q5rpck_( Int_T *m, Real_T *r, Int_T *idel ) { Int_T iold, inew; Int_T lbreak, len; /*-------------------------------------------------------------------------- SUBROUTINES CALLED DCOPY PURPOSE DELETES COLUMN IDEL FROM AN UPPER TRIANGULAR MATRIX R STORED BY ROWS: R11, ..., R1M, R22, ...,R2M, ..., RMM. DELETES ALSO DIAGONAL ELEMENTS FOR I GREATER THAN IDEL. --------------------------------------------------------------------------*/ /* Parameter adjustments */ --r; /* Function Body */ inew = *idel; iold = Int_T( *idel + 1 ); lbreak = Int_T( *m - *idel ); for( len = Int_T( *m - 2 ); len >= lbreak; len-- ) { dcopy_(len, &r[iold], &r[inew]); iold = Int_T( inew + *m ); inew += len; } for( len = lbreak; len >= 1; len-- ) { dcopy_(len, &r[iold], &r[inew]); iold = Int_T( iold + len + 1 ); inew += len; } return 0; } /* -----END OF Q5RPCK----------------------------------------------------- */ int q5tris_( Int_T *m, Real_T *u, Real_T *x, Bool_T *trans ) { /* Local variables */ Int_T lrow, i; Real_T s; Int_T iu; /*-------------------------------------------------------------------------- SUBROUTINES CALLED DSTEP PURPOSE SUBROUTINE FOR SOLVING A SYSTEM OF M LINEAR EQUATIONS WITH AN UPPER TRIANGULAR MATRIX U, WHICH IS STORED BY ROWS, I.E. U11, U12, ..., U1M, U22, ..., U2M, U33, ..., UMM. (U' LOWER TRIANGULAR AND STORED BY COLUMNS). X IS THE RIGHT HAND SIDE AND IS OVERWRITTEN BY THE SOLUTION. IF TRANS IS .TRUE. THE SYSTEM WITH U(TRANSPOSE) IS SOLVED. --------------------------------------------------------------------------*/ /* Parameter adjustments */ --x; --u; /* Function Body */ if (*m < 1) return 0; if( ! *trans ) { // MULTIPLY X BY THE INVERSE OF U. // s = 0.; for( iu = Int_T( *m * (*m + 1) / 2 ), i = *m, lrow = 1; ; iu--, i--, lrow++ ) { x[i] = (x[i] - s) / u[iu]; if( i == 1 ) break; iu -= lrow; s = ddot_(lrow, &u[iu], &x[i]); } } else { // MULTIPLY X BY THE INVERSE OF THE TRANSPOSE OF U. // for( iu = 1, i = 1, lrow = Int_T( *m - 1 ); ; lrow-- ) { x[i] /= u[iu]; if( i == *m ) break; s = x[i]; ++i; ++iu; dstep_(lrow, &x[i], &u[iu], -s); iu += lrow; } } return 0; } /* -----END OF Q5TRIS----------------------------------------------------- */
3706aa7ea9b0a1dfd87b4a1303f4a4f3b42b72f2
4d36e47f8f02ce5b7135f866803b2f3ea7c4891d
/common/events/camerareplacedevent.cpp
3ffcecb22cf40770bf881a0b7cdc5b52ae829c9d
[]
no_license
bshkola/StreetSimulator
bb426c999e223aed40ab6595763106fdbabdc87b
1c0afbf0dc5fb83c9a9bc309f49ebc2152c648f4
refs/heads/master
2016-09-16T09:47:11.755240
2015-01-25T23:03:49
2015-01-25T23:03:49
25,729,779
0
1
null
null
null
null
UTF-8
C++
false
false
479
cpp
camerareplacedevent.cpp
//Author: Bogdan Shkola //Implementation of CameraReplacedEvent class #include "../../common/events/camerareplacedevent.h" CameraReplacedEvent::CameraReplacedEvent(int id, Coordinates new_coordinates) : IEvent(), id_(id), new_coordinates_(new_coordinates) { } std::string CameraReplacedEvent::getName() { return "CameraReplaced"; } int CameraReplacedEvent::getId() { return id_; } Coordinates CameraReplacedEvent::getNewCoordinates() { return new_coordinates_; }
eae0a9f47d0531dc8f06383399657a775f21755a
46f9f7f2595768ec48f8636e9b70ada23c6304ab
/4.1.class and object/main.cpp
5f29fcce71e2550aabc740145967173a3be5a480
[]
no_license
ChaselWu/CPP-Learning
66acd173f427c468a3de8612f93e7dfd083b93f3
e54bf403f35b78ec58385d23c074c32b8aa0c36c
refs/heads/master
2023-04-02T01:02:39.976446
2021-04-10T10:09:48
2021-04-10T10:09:48
340,542,261
0
0
null
null
null
null
UTF-8
C++
false
false
602
cpp
main.cpp
#include <iostream> using std::cout; using std::endl; class rectangle { public: double wid, len; rectangle() { wid = 1.0; len = 1.0; } rectangle(double w) { wid = w; len = w; } rectangle(double w, double l) { len = l; wid = w; } double getArea() { return (len * wid); } double getPerimeter() { return (2 * (len + wid)); } }; int main() { rectangle rec1{}; rectangle rec2{2.5}; rectangle rec3{3.0, 4.0}; cout << rec1.len << endl<<rec2.len<<rec2.wid<<endl<<rec3.len<<rec3.wid; rectangle rec4 = rec3; return 0; }
ae49b2e61b453204d8268af6feef214af6ea615d
c6fa53212eb03017f9e72fad36dbf705b27cc797
/FastSimulation/TrackingRecHitProducer/src/FastStripCPE.h
15dc4820dbd9baa55f1ec3ee96c10a5b9c2fd4c4
[]
no_license
gem-sw/cmssw
a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608
5893ef29c12b2718b3c1385e821170f91afb5446
refs/heads/CMSSW_6_2_X_SLHC
2022-04-29T04:43:51.786496
2015-12-16T16:09:31
2015-12-16T16:09:31
12,892,177
2
4
null
2018-11-22T13:40:31
2013-09-17T10:10:26
C++
UTF-8
C++
false
false
1,315
h
FastStripCPE.h
#ifndef FastSimulation_TrackingRecHitProducer_FastStripCPE_H #define FastSimulation_TrackingRecHitProducer_FastStripCPE_H #include "DataFormats/GeometryVector/interface/LocalPoint.h" #include "DataFormats/GeometrySurface/interface/LocalError.h" #include "RecoLocalTracker/ClusterParameterEstimator/interface/StripClusterParameterEstimator.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include <ext/hash_map> #include <map> class FastStripCPE : public StripClusterParameterEstimator { public: FastStripCPE(){;} //Standard method used //LocalValues is typedef for std::pair<LocalPoint,LocalError> StripClusterParameterEstimator::LocalValues localParameters( const SiStripCluster & cl,const GeomDetUnit& det) const { return localParameters(cl); }; StripClusterParameterEstimator::LocalValues localParameters( const SiStripCluster & cl)const; //Put information into the map. void enterLocalParameters(uint32_t id, uint16_t firstStrip, std::pair<LocalPoint,LocalError> pos_err_info) const; //Clear the map. void clearParameters() const { pos_err_map.clear(); } LocalVector driftDirection(const StripGeomDetUnit* det)const; private: mutable std::map<std::pair<uint32_t, uint16_t>,std::pair<LocalPoint, LocalError> > pos_err_map; }; #endif
5f2e612e2654c24e300f7e39b353c45327477058
652d0577d5f9716423cf7f1aae116a7bfd190c6f
/WaterBox/firmware/library/ArduinoJson/test/JsonBuffer/parse.cpp
70e57918c41cff8df18b236933ad1ed6416e4462
[ "MIT" ]
permissive
LinkItONEDevGroup/LASS
714cf74a07840161ce6a3cd9a9ac525a3d5d88d3
f06bd202f37f2a8fafe932feabcb119a292f016e
refs/heads/master
2023-04-30T09:03:36.609950
2023-04-27T00:03:26
2023-04-27T00:03:26
38,099,296
174
108
MIT
2021-02-05T10:09:21
2015-06-26T08:14:22
C
UTF-8
C++
false
false
2,051
cpp
parse.cpp
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #include <ArduinoJson.h> #include <catch.hpp> using namespace Catch::Matchers; TEST_CASE("JsonBuffer::parse()") { DynamicJsonBuffer jb; SECTION("EmptyObject") { JsonVariant variant = jb.parse("{}"); REQUIRE(variant.success()); REQUIRE(variant.is<JsonObject>()); } SECTION("EmptyArray") { JsonVariant variant = jb.parse("[]"); REQUIRE(variant.success()); REQUIRE(variant.is<JsonArray>()); } SECTION("Integer") { JsonVariant variant = jb.parse("-42"); REQUIRE(variant.success()); REQUIRE(variant.is<int>()); REQUIRE_FALSE(variant.is<bool>()); REQUIRE(variant == -42); } SECTION("Double") { JsonVariant variant = jb.parse("-1.23e+4"); REQUIRE(variant.success()); REQUIRE_FALSE(variant.is<int>()); REQUIRE(variant.is<double>()); REQUIRE(variant.as<double>() == Approx(-1.23e+4)); } SECTION("Double quoted string") { JsonVariant variant = jb.parse("\"hello world\""); REQUIRE(variant.success()); REQUIRE(variant.is<char*>()); REQUIRE_THAT(variant.as<char*>(), Equals("hello world")); } SECTION("Single quoted string") { JsonVariant variant = jb.parse("\'hello world\'"); REQUIRE(variant.success()); REQUIRE(variant.is<char*>()); REQUIRE_THAT(variant.as<char*>(), Equals("hello world")); } SECTION("True") { JsonVariant variant = jb.parse("true"); REQUIRE(variant.success()); REQUIRE(variant.is<bool>()); REQUIRE(variant == true); } SECTION("False") { JsonVariant variant = jb.parse("false"); REQUIRE(variant.success()); REQUIRE(variant.is<bool>()); REQUIRE(variant == false); } SECTION("OpenBrace") { JsonVariant variant = jb.parse("{"); REQUIRE_FALSE(variant.success()); } SECTION("Incomplete string") { JsonVariant variant = jb.parse("\"hello"); REQUIRE(variant.success()); REQUIRE(variant.is<char*>()); REQUIRE_THAT(variant.as<char*>(), Equals("hello")); } }
1ff128a2f6d921dd230090cbe45dd14b947d8106
6278ebc0117fb866e30d7488cfac8a14152bbafa
/tests/SimCore/BattlefieldGraphicsActorTests.cpp
4c2ae7f3ad499432fdb181a27f5f04b91183e12b
[]
no_license
delta3d/SimulationCore
4970bc5de3baf2a466eef42a668cebc31b152d8a
631291491d17746f7a3dbe0efe665f42309fe882
refs/heads/master
2021-01-11T03:30:08.328507
2016-02-26T18:43:12
2016-02-26T18:43:12
71,003,826
6
3
null
null
null
null
UTF-8
C++
false
false
5,536
cpp
BattlefieldGraphicsActorTests.cpp
/* -*-c++-*- * Simulation Core - BattlefieldGraphicsActorTests.cpp - Using 'The MIT License' * Copyright 2011, Alion Science and Technology * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * This software was developed by Alion Science and Technology Corporation under * circumstances in which the U. S. Government may have rights in the software. * * David Guthrie */ #include <prefix/SimCorePrefix.h> #include <cppunit/extensions/HelperMacros.h> #include <dtGame/gamemanager.h> #include <SimCore/Actors/EntityActorRegistry.h> #include <SimCore/Actors/BattlefieldGraphicsActor.h> #include <SimCore/VisibilityOptions.h> #include <UnitTestMain.h> #include <dtUtil/configproperties.h> #include <dtUtil/mathdefines.h> namespace SimCore { namespace Actors { ////////////////////////////////////////////////////////////////////////// // TESTS OBJECT ////////////////////////////////////////////////////////////////////////// class BattlefieldGraphicsActorTests : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE(BattlefieldGraphicsActorTests); CPPUNIT_TEST(TestEnumColor); CPPUNIT_TEST(TestActorProperties); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); // Test Methods void TestEnumColor(); void TestActorProperties(); void TestVisibilityOptions(); private: dtCore::RefPtr<dtGame::GameManager> mGM; dtCore::RefPtr<BattlefieldGraphicsActorProxy> mActor; }; CPPUNIT_TEST_SUITE_REGISTRATION(BattlefieldGraphicsActorTests); ////////////////////////////////////////////////////////////////////////// void BattlefieldGraphicsActorTests::setUp() { try { // Create the Game Manager. mGM = new dtGame::GameManager( *GetGlobalApplication().GetScene() ); mGM->SetApplication(GetGlobalApplication()); // Create a proxy. mGM->CreateActor(*SimCore::Actors::EntityActorRegistry::BATTLEFIELD_GRAPHICS_ACTOR_TYPE, mActor); } catch (const dtUtil::Exception& ex) { CPPUNIT_FAIL(ex.ToString()); } } ////////////////////////////////////////////////////////////////////////// void BattlefieldGraphicsActorTests::tearDown() { try { mActor = NULL; mGM->DeleteAllActors(true); mGM = NULL; } catch (const dtUtil::Exception& ex) { CPPUNIT_FAIL(ex.ToString()); } } ////////////////////////////////////////////////////////////////////////// void BattlefieldGraphicsActorTests::TestEnumColor() { dtUtil::ConfigProperties& confProp = mGM->GetConfiguration(); BattlefieldGraphicsTypeEnum::EnumerateListType::const_iterator i, iend; i = BattlefieldGraphicsTypeEnum::EnumerateType().begin(); iend = BattlefieldGraphicsTypeEnum::EnumerateType().end(); // Declare outside the loop to prevent reallocating over and over. std::string confStr; for (; i != iend; ++i) { BattlefieldGraphicsTypeEnum& curEnum = **i; confStr = BattlefieldGraphicsTypeEnum::CONFIG_PREFIX + curEnum.GetName(); std::string confVal = confProp.GetConfigPropertyValue(confStr, ""); CPPUNIT_ASSERT(confVal.empty()); CPPUNIT_ASSERT_EQUAL(curEnum.GetDefaultColor(), curEnum.GetColor(confProp)); osg::Vec3 newColor(1.0f, 0.986f, 0.317f); confProp.SetConfigPropertyValue(confStr, "1.0 0.986 0.317"); CPPUNIT_ASSERT(dtUtil::Equivalent(newColor, curEnum.GetColor(confProp), 0.001f)); confProp.RemoveConfigPropertyValue(confStr); } } ////////////////////////////////////////////////////////////////////////// void BattlefieldGraphicsActorTests::TestActorProperties() { try { } catch (const dtUtil::Exception& ex) { CPPUNIT_FAIL(ex.ToString()); } } void BattlefieldGraphicsActorTests::TestVisibilityOptions() { IGActor* drawable = NULL; mActor->GetDrawable(drawable); CPPUNIT_ASSERT(drawable != NULL); dtCore::RefPtr<VisibilityOptions> vo = new VisibilityOptions(); BasicVisibilityOptions bvo; bvo.SetAllFalse(); bvo.mBattlefieldGraphics = true; vo->SetBasicOptions(bvo); CPPUNIT_ASSERT(drawable->ShouldBeVisible(*vo)); bvo.SetAllTrue(); bvo.mBattlefieldGraphics = false; vo->SetBasicOptions(bvo); CPPUNIT_ASSERT(!drawable->ShouldBeVisible(*vo)); } } }
7f4260cbb49ba3e6a182c62f9e84d270ac996f6f
fde0bdee8fbdbfc7a528bb01178110e698b87e20
/filter.cpp
e001308f2ceceb2f81c207a691d2a7a82769789a
[]
no_license
gromakovski/Homework_2
afeb58f716a07267d1c29eede9c65642648f6a9f
b6e0e0e55b133047c11caff18dce5aa1fea9af4e
refs/heads/master
2020-04-17T18:17:59.832484
2019-06-16T14:09:34
2019-06-16T14:09:34
166,820,334
0
0
null
null
null
null
UTF-8
C++
false
false
3,058
cpp
filter.cpp
#include "filter.h" #include "define.h" std::vector<std::string> ip::set_subs (const std::string &str, const char end_subs) { std::vector<std::string> ip_adress; std::string::size_type start = 0; std::string::size_type stop = str.find_first_of(end_subs); while(stop != std::string::npos) { ip_adress.push_back(str.substr(start, stop - start)); start = stop + 1; stop = str.find_first_of(end_subs, start); } ip_adress.push_back(str.substr(start)); return ip_adress; } void ip::set_ip_pool() { for(std::string line; std::getline(std::cin, line);) { auto v = ip::set_subs(line, END_IP_ADRESS); //ip::set_subs(ip_adress.at(0), '.'); ip_pool.push_back(ip::set_subs(v.at(0), END_IP)); } } void ip::sort_reverse_all() { std::sort(ip_pool.begin(), ip_pool.end(), [](auto a, auto b) { if (a[0]==b[0]) { if (a[1]==b[1]) { if (a[2]==b[2]) return atoi(a[3].c_str()) > atoi(b[3].c_str()); else return atoi(a[2].c_str()) > atoi(b[2].c_str()); } else return atoi(a[1].c_str()) > atoi(b[1].c_str()); } else return atoi(a[0].c_str()) > atoi(b[0].c_str()); } ); } std::vector<std::vector<std::string>> ip::search_one_byte(const std::string one_byte) { std::vector<std::vector<std::string>> search_ip_pool; for (auto ip = ip_pool.begin(); ip != ip_pool.end(); ++ip) { if (*ip->begin()==one_byte) search_ip_pool.push_back(*ip); } return search_ip_pool; } std::vector<std::vector<std::string>> ip::search_two_byte (const std::string one_byte, const std::string two_byte) { std::vector<std::vector<std::string>> search_ip_pool; for (auto ip = ip_pool.begin(); ip != ip_pool.end(); ++ip) { if (*ip->begin()==one_byte and (*ip)[1]==two_byte) search_ip_pool.push_back(*ip); } return search_ip_pool; } void ip::get() { for(auto ip = ip_pool.cbegin(); ip != ip_pool.cend(); ++ip) { for(auto ip_part = ip->cbegin(); ip_part != ip->cend(); ++ip_part) { if (ip_part != ip->cbegin()) { std::cout << "."; } std::cout << *ip_part; } std::cout << std::endl; } } void ip::push_back_ip_pool(std::vector<std::vector<std::string>> in_ip_pool) { for (auto ip = in_ip_pool.begin(); ip != in_ip_pool.end(); ++ip) ip_pool.push_back(*ip); }
bdfb4ec9bdff320f623ba0b3b70d4936b3ff134c
2250008ba0cbe0cd56a2cc2ef8516e748fe49750
/Executive/Executive.h
a3a29b00a6d679a2d288f7be6df5e2873bb77a20
[]
no_license
RohithEngu/Remote-File-ManagementSystem
3aade558ff5b13fc5b7926a86e4e504280dbdd2d
078a0656a0a6399645876774c6712722bc10bf78
refs/heads/master
2021-01-17T17:35:34.215555
2016-08-12T05:20:43
2016-08-12T05:20:43
65,524,734
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
h
Executive.h
#ifndef EXECUTIVE_H #define EXECUTIVE_H /************************************************************************************************** *FileName : Exectuive.h - Header file for Executing file Catalog. *Author : Rohith Engu, SUID : 678923180, CE Fall'14, Syracuse University * roengu@syr.edu, (315) 560-6468 *Version : 1.0 *Langage : C++11 *Platform : Windows 7 ultimate, Asus N51Vn -64bit(core2duo), Microsoft Visual Studio Ultimate 2013. *Application : Project # 4 ,Object Oriented Design CSE 687 *Reference : Prof.Jim Fawcett's Code help on DataStore ***************************************************************************************************/ /* * Module Operations: * ------------------ * This Module provides an interface for saving all the files in a data structure. * It has a main class DataStore, which has all the methods for saving. * * Interface: * ---------- * Executive exec(argc, argv); * exec.processCommands(); * exec.generateFileCatalog(); * * Maintenance History: * -------------------- * ver 1.0 : 25 Jan 2014 * - first release * */ #include <string> #include <vector> #include "DataStore.h" using namespace std; class Executive{ public: Executive(); Executive(int argc, char* argv[]); using filemap = DataStore::Store; void processCommands(); void checkCommands(); void generateFileCatalog(); bool isSubDirectorySearch(); bool isKeywordSearch(); bool isDupFileList(); void searchFilesForKey(string keywrd); void searchFilesForKeyAndPatterns(string keywrd, vector<string> pattrns); void addPattern(string& pattern); string getKeyword(); void briefSummary(string path); private: int _argc; char** _argv; string path; vector<string> patterns; bool isSubDir; bool isDup; bool isSearchKwd; filemap finalFileSet; filemap matchedfiles; string keyword; }; #endif
975120ecf93f21d095f15baed80ea1817803d285
954ac366e5fe2052f771a312437ebba0c79568d5
/include/hpp/core/nearest-neighbor.hh
31bd4e82df609f75d70de4fc8c0f001c3a11b75e
[ "BSD-2-Clause" ]
permissive
nim65s/hpp-core
040ef4da4d73171482ed938e3ecd4bc52f478f4e
e0363c599865bddc7150f0a984f1f0974e43d729
refs/heads/master
2023-01-23T14:18:33.820811
2023-01-18T14:54:18
2023-01-18T14:54:18
86,066,682
0
0
null
2017-03-24T12:40:19
2017-03-24T12:40:19
null
UTF-8
C++
false
false
4,197
hh
nearest-neighbor.hh
// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. #ifndef HPP_CORE_NEAREST_NEIGHBOR_HH #define HPP_CORE_NEAREST_NEIGHBOR_HH #include <hpp/core/fwd.hh> #include <hpp/util/serialization-fwd.hh> namespace hpp { namespace core { /// Optimization of the nearest neighbor search class NearestNeighbor { public: virtual void clear() = 0; virtual void addNode(const NodePtr_t& node) = 0; /** * @brief search Return the closest node of the given configuration * @param configuration * @param connectedComponent * @param distance * @param reverse if true, compute distance from given configuration to nodes * in roadmap, if false from nodes in roadmap to given configuration * @return */ virtual NodePtr_t search(const Configuration_t& configuration, const ConnectedComponentPtr_t& connectedComponent, value_type& distance, bool reverse = false) = 0; virtual NodePtr_t search(const NodePtr_t& node, const ConnectedComponentPtr_t& connectedComponent, value_type& distance) = 0; /// \param[out] distance to the Kth closest neighbor /// \return the K nearest neighbors virtual Nodes_t KnearestSearch( const Configuration_t& configuration, const ConnectedComponentPtr_t& connectedComponent, const std::size_t K, value_type& distance) = 0; /// \param[out] distance to the Kth closest neighbor /// \return the K nearest neighbors virtual Nodes_t KnearestSearch( const NodePtr_t& node, const ConnectedComponentPtr_t& connectedComponent, const std::size_t K, value_type& distance) = 0; /// Return the K nearest nodes in the whole roadmap /// \param configuration, the configuration to which distance is computed, /// \param K the number of nearest neighbors to return /// \retval distance to the Kth closest neighbor /// \return the K nearest neighbors virtual Nodes_t KnearestSearch(const Configuration_t& configuration, const RoadmapPtr_t& roadmap, const std::size_t K, value_type& distance) = 0; /// \return all the nodes closer than \c maxDistance to \c configuration /// within \c connectedComponent. virtual NodeVector_t withinBall(const Configuration_t& configuration, const ConnectedComponentPtr_t& cc, value_type maxDistance) = 0; // merge two connected components in the whole tree virtual void merge(ConnectedComponentPtr_t cc1, ConnectedComponentPtr_t cc2) = 0; // Get distance function virtual DistancePtr_t distance() const = 0; virtual ~NearestNeighbor(){}; private: HPP_SERIALIZABLE(); }; // class NearestNeighbor } // namespace core } // namespace hpp #endif // HPP_CORE_NEAREST_NEIGHBOR_HH
1725237a3ce28ed25eeea944936023024b2787d7
857e12986cccde20e5b736a8b9bc46de1de89c14
/ORDE/include/extraction/action.hpp
452bab9897d2e80815e6177ee9e98f4ebbb2583d
[ "MIT" ]
permissive
zeFresk/osu-anticheat
157a9bf4335b0132826f2097784a7d1870725ad5
e6c9cc751cd17cf852897e6a6be60365d6c10cbe
refs/heads/master
2021-01-12T11:47:26.743359
2016-10-08T17:16:50
2016-10-08T17:16:50
69,744,775
1
0
null
null
null
null
UTF-8
C++
false
false
269
hpp
action.hpp
/* action struct */ #pragma once #include "types.hpp" namespace orde { struct Action { using w_t = Long; using x_t = Float; using y_t = Float; using z_t = Integer; Long time_since_last_action; Float x_coord; Float y_coord; Integer pressed; }; }
48b157c25187a11e3bfa369208dfb0e0e39eef1a
e016b0b04a6db80b0218a4f095e6aa4ea6fcd01c
/Classes/Native/Mapbox_Json_Mapbox_Json_Linq_JTokenWriter2104426008.h
a2ff55e509e6330a2a59294f082698479fb3e62e
[ "MIT" ]
permissive
rockarts/MountainTopo3D
5a39905c66da87db42f1d94afa0ec20576ea68de
2994b28dabb4e4f61189274a030b0710075306ea
refs/heads/master
2021-01-13T06:03:01.054404
2017-06-22T01:12:52
2017-06-22T01:12:52
95,056,244
1
1
null
null
null
null
UTF-8
C++
false
false
2,891
h
Mapbox_Json_Mapbox_Json_Linq_JTokenWriter2104426008.h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "Mapbox_Json_Mapbox_Json_JsonWriter1886137423.h" // Mapbox.Json.Linq.JContainer struct JContainer_t1655356485; // Mapbox.Json.Linq.JValue struct JValue_t987754451; // Mapbox.Json.Linq.JToken struct JToken_t221585239; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mapbox.Json.Linq.JTokenWriter struct JTokenWriter_t2104426008 : public JsonWriter_t1886137423 { public: // Mapbox.Json.Linq.JContainer Mapbox.Json.Linq.JTokenWriter::_token JContainer_t1655356485 * ____token_14; // Mapbox.Json.Linq.JContainer Mapbox.Json.Linq.JTokenWriter::_parent JContainer_t1655356485 * ____parent_15; // Mapbox.Json.Linq.JValue Mapbox.Json.Linq.JTokenWriter::_value JValue_t987754451 * ____value_16; // Mapbox.Json.Linq.JToken Mapbox.Json.Linq.JTokenWriter::_current JToken_t221585239 * ____current_17; public: inline static int32_t get_offset_of__token_14() { return static_cast<int32_t>(offsetof(JTokenWriter_t2104426008, ____token_14)); } inline JContainer_t1655356485 * get__token_14() const { return ____token_14; } inline JContainer_t1655356485 ** get_address_of__token_14() { return &____token_14; } inline void set__token_14(JContainer_t1655356485 * value) { ____token_14 = value; Il2CppCodeGenWriteBarrier(&____token_14, value); } inline static int32_t get_offset_of__parent_15() { return static_cast<int32_t>(offsetof(JTokenWriter_t2104426008, ____parent_15)); } inline JContainer_t1655356485 * get__parent_15() const { return ____parent_15; } inline JContainer_t1655356485 ** get_address_of__parent_15() { return &____parent_15; } inline void set__parent_15(JContainer_t1655356485 * value) { ____parent_15 = value; Il2CppCodeGenWriteBarrier(&____parent_15, value); } inline static int32_t get_offset_of__value_16() { return static_cast<int32_t>(offsetof(JTokenWriter_t2104426008, ____value_16)); } inline JValue_t987754451 * get__value_16() const { return ____value_16; } inline JValue_t987754451 ** get_address_of__value_16() { return &____value_16; } inline void set__value_16(JValue_t987754451 * value) { ____value_16 = value; Il2CppCodeGenWriteBarrier(&____value_16, value); } inline static int32_t get_offset_of__current_17() { return static_cast<int32_t>(offsetof(JTokenWriter_t2104426008, ____current_17)); } inline JToken_t221585239 * get__current_17() const { return ____current_17; } inline JToken_t221585239 ** get_address_of__current_17() { return &____current_17; } inline void set__current_17(JToken_t221585239 * value) { ____current_17 = value; Il2CppCodeGenWriteBarrier(&____current_17, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
ab539c6a219cb47b94362fbae3c46a84c1d63c74
60e7a2a198c6e42ab4288dfd2f596d04b5341f1f
/src/Jet.cxx
ce016bc70acc2cd87511c921188ecbed953cb1fe
[]
no_license
dguest/tagging-performance
2a53c07d57dc96d8e09b2894b8f8d5d577aaba66
505b4d1b5eceea8c503803fb77611158a8f2e4f4
refs/heads/master
2021-01-01T17:28:29.300501
2015-11-20T14:11:08
2015-11-20T14:11:08
15,324,783
0
0
null
2014-01-11T16:39:05
2013-12-19T22:49:03
Python
UTF-8
C++
false
false
1,862
cxx
Jet.cxx
#include "Jet.hh" #include "TreeBuffer.hh" #include "PetersBuffer.hh" #include <cassert> TagTriple::TagTriple() : pu(-999), pc(-999), pb(-999) { } TagTriple::TagTriple(const TagVectors& buff, int index): pu(buff.pu->at(index)), pc(buff.pc->at(index)), pb(buff.pb->at(index)) { } TagTriple::TagTriple(const TagArrays& buff, int index): pu(buff.pu[index]), pc(buff.pc[index]), pb(buff.pb[index]) { } bool TagTriple::allNonzero() const { return pu && pb && pc; } Jet::Jet() : pt(-999), valid(false), truth_label(Flavor::ERROR) { } Jet::Jet(const TreeBuffer& buff, int index) : event(buff.entry()), pt(buff.jet_pt->at(index)), eta(buff.jet_eta->at(index)), jvf(-999), valid(true), mv1(buff.jet_MV1->at(index)), mv1c(buff.jet_MV1c->at(index)), mv2c00(buff.jet_MV2c00->at(index)), mv2c10(buff.jet_MV2c10->at(index)), mv2c20(buff.jet_MV2c20->at(index)), mvb(buff.jet_MVb->at(index)), truth_label(getFlavor(buff.jet_flavor_truth_label->at(index))), gaia(buff.gaia, index), jfit(buff.jfit, index), jfc(buff.jfc, index), gaia_valid(buff.jet_gaia_isValid->at(index)) { } Jet::Jet(const PetersBuffer& buff, int index) : event(buff.entry()), pt(buff.jet_pt[index] * 1e3), eta(buff.jet_eta[index]), jvf(buff.jvf[index]), valid(true), mv1(-999), mv1c(-999), mv2c00(-999), mv2c10(-999), mv2c20(-999), mvb(-999), truth_label(getFlavor(buff.jet_flavor_truth_label[index])), jfit(buff.jfit, index), jfc(buff.jfc, index), gaia_valid(false) { assert(buff.n_jets > index); } Flavor Jet::getFlavor(int ftl) { switch(ftl) { case 5: return Flavor::B; case 4: return Flavor::C; case 0: return Flavor::U; case 15: return Flavor::T; default: return Flavor::ERROR; } } // ===== exceptions ===== BadJetError::BadJetError(const std::string& problem) : std::range_error(problem) { }
f9625bffe7c593ea0924d917bc639d19a22bbfa9
afec3b619926d18d7c5748c84a7873e82cbb8418
/widget.cpp
73a00347cba7ede0f3cd54b438fd02b3d8b4afe6
[]
no_license
lianghuashow/FFmpegPlayerWithQt
41aa5fd75cc4553c09b02d1a12ba09d2b347813a
b81c62eaccfe65755155cc32d4e6dc860fa5697b
refs/heads/master
2023-02-08T05:32:59.930464
2020-12-31T01:47:53
2020-12-31T01:47:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
widget.cpp
#include "widget.h" #include "ui_widget.h" #include <QTextCodec> #include <QFileDialog> #include <chrono> #include <thread> #include <string> #include <stdio.h> Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) ,m_player(new MediaPlayer) { ui->setupUi(this); } Widget::~Widget() { delete ui; delete m_player; } void Widget::on_openFileBtn_clicked() { QString filename = QFileDialog::getOpenFileName(this, QObject::tr("Open Video"), ".", "*.mp4 *.flv") ; if (filename.isEmpty()) { return; } m_player->registerRenderWindowsCallback(ui->widget); m_player->start_play(filename.toUtf8().data()); } void Widget::on_play_paush_btn_clicked() { m_player->pause_resume_play(); }
1d745cd4ccd210bbf4524ccccd2051c2ffaa9fbe
0e83634cde0fccede67f58640e6d94a3d0baf19e
/Source/GameRoomVR/GameRoomVR.cpp
0ab617cb27015f2e10d1dc2839e857ae13dcff5b
[]
no_license
chadyo/GameRoomVR
27821775943649643271e4513b351daca4cf1d49
f02ce7d1b6d79e0309ec0460ad8c62e01cb5554f
refs/heads/master
2021-01-01T15:59:51.870618
2014-06-07T15:17:50
2014-06-07T15:17:50
20,311,325
0
1
null
null
null
null
UTF-8
C++
false
false
147
cpp
GameRoomVR.cpp
#include "GameRoomVR.h" #include "GameRoomVR.generated.inl" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, GameRoomVR, "GameRoomVR" );
94fb931c9f49b623b3278f072562e90592e7761a
e088bf8de2dcc1205e999bb06074c9985ca32383
/Chapter13/13.28.h
951b0ec8d22fa9a56d3490051b872e47d1e66877
[]
no_license
YsingYang/CPP-Primer-Practice
cc257b599d6f94d80eed71ada5dd4ac23c4f32c9
2d8e223e3c80ac12ec549a6e49a25d3e28789207
refs/heads/master
2021-06-13T09:30:36.515915
2017-04-17T12:59:46
2017-04-17T12:59:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
765
h
13.28.h
#include<stdio.h> #include<iostream> class TreeNode{ public: /** 构造函数 */ TreeNode():value(string()),count(0),left(nullptr),right(nullptr){} TreeNode(TreeNode &rtn){ value = rtn.value; count = rtn.count; left = rtn.left; right = rtn.right; } /** 拷贝控制 */ TreeNode &operator=(TreeNode &rtn){ value = rtn.value; count = rtn.count; delete(left); left = rtn.left; delete(right); right = rtn.right; return *this; } /** 析构函数 */ ~TreeNode(){ delete(left); delete(right); } private: std::string value; int count; TreeNode *left; TreeNode *right; };
85a5b1dd8d6629246302666a7b285d0b3cde331f
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_1559.cpp
55a8fdee9e690ee12755ea6c3943db5a497c7e0d
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
57
cpp
Kitware_CMake_repos_basic_block_block_1559.cpp
(chain == 0) // Loop ran zero times. regnode(NOTHING)
4d178f57a7cfed1a801273d171cd65431c5b9c60
ee9dff0e88086d32f1997006ec001b95afd84de5
/Programowanie Obiektowe Laboratorium Nr 2 - 2/PoLab2-2/PoLab2-2.cpp
8ef0197e2723cbc7fcf161b9a7b076c6b4e4e577
[]
no_license
Kontekst/SemestII-Laboratoria-Projekty
df823268348b887631823d0f3622a7108f3db7fc
a8781950dba6109b7f9329f5e13c46071a289c6c
refs/heads/master
2021-01-19T09:55:47.940869
2017-04-10T11:04:53
2017-04-10T11:04:53
87,800,206
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,060
cpp
PoLab2-2.cpp
#include <iostream> #include <fstream> #include "stdafx.h" #include "Biblioteka.h" #include "KsiazkaC.h" #include "KsiazkaCpp.h" using namespace std; int main() { ifstream wejscie("we.txt"); ofstream wyjscie("wy.txt"); if (!wyjscie) { cout << "Blad otwierania pliku!!!!!!!!!" << endl; } if (!wyjscie) { cout << "Blad otwierania pliku!!!!!!!!!" << endl; } { Ksiazka *wskaznik; KsiazkaCpp A("Metrologia"); KsiazkaCpp B("LOTR"); KsiazkaCpp C("Harry Potter"); KsiazkaCpp D("Straż Nocna"); KsiazkaCpp E("Pieklo Pocztowe"); KsiazkaC F("Alfa i Omega"); KsiazkaC G("Przygody Beniamina"); KsiazkaC H("Mount & Blade"); KsiazkaC I(H); cout << "||||||||" << endl; cout << "Wypisanie nazw czterech ksiazek" << endl; A.wypisz(); B.wypisz(); G.wypisz(); H.wypisz(); cout << "||||||||" << endl; Biblioteka ETI; wskaznik = &A; ETI.dodaj(A); wskaznik = &B; ETI.dodaj(B); wskaznik = &C; ETI.dodaj(C); wskaznik = &D; ETI.dodaj(D); wskaznik = &F; ETI.dodaj(F); wskaznik = &G; ETI.dodaj(G); cout << "||||||||" << endl; cout << "A teraz wypisanie ETI" << endl; cout << ETI; cout << "||||||||" << endl; Biblioteka EIA; EIA = ETI; cout << "||||||||" << endl; cout << "A teraz wypisanie EIA :" << endl; cout << EIA; cout << "||||||||" << endl; Biblioteka OIO(ETI); wskaznik = &I; OIO.dodaj(I); cout << "||||||||" << endl; cout << "A teraz wypisanie OIO :" << endl; cout << OIO; cout << "||||||||" << endl; cout << "Kolejne wypisanie ETI" << endl; cout << ETI; cout << "||||||||" << endl; cout << "Wpisanie biblioteki do pliku tekstowego" << endl; wyjscie << ETI; cout << "||||||||" << endl; wejscie >> ETI; cout << "Nowa ilosc z CINa " << ETI.ilosc << endl;; cout << ETI; cout << "||||||||" << endl; cout << "KONIEC PROGRAMU" << endl; } cout << "Wcisnij dowolny klawisz aby zakonczyc dzialanie programu" << endl; getchar(); getchar(); return 0; }
145f137d7bf4808622299105a4764653123d53ca
4c1023e196133e0b7d4312bbc7e430796a35b6b1
/Alte concursuri/ciclueulerian/main.cpp
746cdc1260fc57e03289108fd6baa90f6ed48bfb
[]
no_license
PetreCatalin/Concursuri-Programare-Competitiva
0551bd141b071b1224c1e5e81516cd2ec23b90ce
58e355f73cb52f078e22284350c8ba197fe6fbca
refs/heads/master
2021-01-23T00:39:48.827093
2017-05-31T10:56:21
2017-05-31T10:56:21
92,826,697
1
1
null
null
null
null
UTF-8
C++
false
false
716
cpp
main.cpp
#include <fstream> #include <vector> using namespace std; vector <long int> v[1000]; long int n,m,i,x,y,nr,a[1000]; inline void df(long int x) { long int i,poz,j; for (i=0;i<v[x].size();i++) { v[x].erase(v[x].begin()+i); for (j=0;j<v[v[x][i]].size();j++) if (v[v[x][i]][j]==x) {poz=j;break;} v[v[x][i]].erase(v[v[x][i]].begin()+poz); df(i); } nr++; a[nr]=x; } int main() { ifstream f("ce.in"); ofstream g("ce.out"); f>>n>>m; for (i=1;i<=m;i++) { f>>x>>y; v[x].push_back(y); v[y].push_back(x); } nr=0; df(1); for (i=1;i<=nr;i++) g<<a[nr]<<' '; f.close(); g.close(); return 0; }
20a11d299ea94319afbde272bff45f39831fefc0
52ae9752c3c705afca3bf8ff2156d587a597503a
/GrottoEscape/GrottoEscape/GrottoEscape.cpp
9c3eaff17f7caaca7bc23eb9edc786ea3b990500
[]
no_license
madnotdead/GrottoEscape
be73f12c155240f7b2eed2d2ca59b4db2c215066
9cbf8a3a2268d43fd83959e2229967fdea99c9a0
refs/heads/master
2021-01-01T15:19:08.547807
2015-07-03T13:27:36
2015-07-03T13:27:36
33,523,124
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
GrottoEscape.cpp
#include "stdafx.h" #include "windows.h" int main() { ShowWindow(GetConsoleWindow(), SW_HIDE); Game* _game = new Game(800, 600); _game->MainLoop(); return EXIT_SUCCESS; }
dd9efdcec07d7159fbebc61427ae56cc397bf4ba
29cfe0006032574437bc0133eadf9637bfebc0f1
/Spotlight/src/Spotlight/Core/Input.h
0271e2369cfea4b675eacf8e06f6593bcfc53304
[ "MIT" ]
permissive
JustARegularPlayer/Spotlight
3b4be0a99944f1498a6d1b842307ffcf1ba6b0f6
248b1fd75a518ea5506a0929402afe9c8addd2dd
refs/heads/main
2023-09-02T18:46:20.844135
2021-10-21T07:17:00
2021-10-21T07:17:00
394,851,107
0
0
null
null
null
null
UTF-8
C++
false
false
856
h
Input.h
#pragma once #include "splpch.h" namespace Spotlight { class Input { public: inline static bool IsKeyPressed(int keycode) { return sm_Instance->IsKeyPressedImpl(keycode); } inline static bool IsMouseButtonPressed(int button) { return sm_Instance->IsMouseButtonPressedImpl(button); } inline static std::pair<float, float> GetMousePos() { return sm_Instance->GetMousePosImpl(); } inline static float GetMouseXPos() { return sm_Instance->GetMouseXPosImpl(); } inline static float GetMouseYPos() { return sm_Instance->GetMouseYPosImpl(); } protected: virtual bool IsKeyPressedImpl(int keycode) = 0; virtual bool IsMouseButtonPressedImpl(int button) = 0; virtual std::pair<float, float> GetMousePosImpl() = 0; virtual float GetMouseXPosImpl() = 0; virtual float GetMouseYPosImpl() = 0; private: static Input* sm_Instance; }; }
ec1405ae3f2ba415b8d80340d5a027077177746f
1afd48f0afb2940c1512cccb9f1377a96384587e
/model.hpp
df915f01dfdd0217ed5901ea624ec2c16d20bb91
[]
no_license
Walter0697/Imitator
b069cce18a299b3eda072e02e3590cb8e33bbb5a
675e6794037e8811554a21e7060fc1fe72326ef2
refs/heads/master
2022-01-14T20:46:54.474407
2019-08-03T06:20:31
2019-08-03T06:20:31
100,320,379
0
0
null
null
null
null
UTF-8
C++
false
false
2,508
hpp
model.hpp
#pragma once #include "updateable.hpp" #include "player.hpp" #include "bulletSet.hpp" #include "enemyset.hpp" #include "toolSet.hpp" #include "Tools/shield.hpp" #include "Tools/radShield.hpp" #include "Mode/story.hpp" #include "Mode/dropRate.hpp" #include "Mode/record.hpp" #include "collision.hpp" class Model { public: Model(); //constructor ~Model(); //destructor sf::Vector2f screen_tl; //corners of the screen sf::Vector2f screen_br; std::vector<Updateable *> updateables; //all the updateables Player* player; //player BulletSet* playerSet; //player bullets set BulletSet* enemyBulletSet; //enemies bullets set EnemySet* enemySet; //enemies sets ToolSet* toolSet; //tools dropped by enemies in the screen Shield* shield; //two shields of the player RadShield* radShield; Collision coll; //collision check DropRate* droprate; //drop rate Record* record; //record of the player Story* story; //story mode int gamemode; //gamemode bool pause = false; //if the game is paused float timer; //timer int reward_type = 0; //reward screen will show up if this is not 0 int tool_type = 0; float choas_timer; //related information for choas mode float choas_max; int boss_chance; void updateRewards(sf::Time&); //all update function for different screen void updateStory(sf::Time&); void updateChoas(sf::Time&); void updateGame(sf::Time&); void update(sf::Time&); void modeAdjust(int); //balancing the boss information according to different mode void shoot(); //player shooting void initAll(); //initialize everything void specialBulletCheck(); //check for the special bullet void checkHit(); //check for the collision void enemyShootCount(); //check if enemies should shoot void bossShootCount(); //check if the boss should shoot void enemyDie(Enemy&, Bullet&, int, int, int); //drop items and add score if enemy die void elementHit(sf::Time); //if on fire, player or enemy will get damage int playerDamage(Bullet&, Hitbox&); //check if player should get damage void bulletDisappear(Bullet&); //move away the bullet after collision void enemyDamage(Bullet&, Enemy&, int); //check if the enemies get damage void enemyDamage(Enemy&, int, int); void checkDie(Enemy&, int); //check if the enemies die private: sf::Vector2f findTarget(sf::Vector2f&); //find the target for homing };
ec17ff3e90f81044e366117fcef3b818d5f0adad
8dcf1a5808ac13a3c3e95d3dfc7299eee814e5e3
/TD/TD/LightInfantry.cpp
820e2f2c2fa41c72ca36acb21ee6e405a7e83337
[]
no_license
SlaykSD/OOP_NEW
5c49d06bfcb0a8b2e29519196dcd039063f32834
9d224e12cd5707c37fcce2bd3810acdb9882e1e0
refs/heads/master
2023-04-12T08:09:40.244641
2021-04-29T19:11:20
2021-04-29T19:11:20
299,862,256
0
0
null
2020-11-13T16:17:55
2020-09-30T08:53:53
C++
WINDOWS-1251
C++
false
false
678
cpp
LightInfantry.cpp
#include "LightInfantry.h" LightInfantry::LightInfantry(std::list<sf::Vector2i> l) :Enemy(l,EnemyType::Light_Infantry) { sf::Rect <int> rect(0, 0, 64, 64); sf::Image widget; //создаем объект Image (изображение) widget.loadFromFile("data/light_infantry.png");//загружаем в него файл widget.createMaskFromColor(sf::Color(255, 255, 255)); texture.loadFromImage(widget); sprite.setTexture(texture); sprite.setTextureRect(rect); } void LightInfantry::draw(sf::RenderWindow* window) { if (visible) { //rectHealthbar.setTexture(&healthbar); sprite.setTexture(texture); window->draw(sprite); window->draw(rectHealthbar); } }
72f111ba352c2879fb0630bbcbfee4fbc55ad411
6e0c03a6b5fc05cf346eb392c48c48dfa1b280c7
/Qt/VIsualHearingAid/DeviceDirection.h
081e4e765e20684f551859af5d6ce60cec37c6b0
[]
no_license
degeable/bachelor-thesis
7ce40fee54c45a39b5c9f789af0e9510398fc31b
570140186a82ca583bbd72aa0f5946d3c6ec0c7d
refs/heads/master
2022-12-19T03:30:45.568097
2020-09-21T09:52:11
2020-09-21T09:52:11
297,292,885
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
h
DeviceDirection.h
#ifndef DEVICEDIRECTION_H #define DEVICEDIRECTION_H #include <QObject> #include <QDebug> #include <iostream> #include <QtSensors/QCompassFilter> using std::cout; using std::endl; /** * The CompassSensor class uses the QCompass class from the QtSensors * module to retrieve the current azimuth values from the compass sensor of the device. */ class DeviceDirection : public QObject, public QCompassFilter { Q_OBJECT // The property to access the azimuth value of the compass sensor Q_PROPERTY(qreal azimuth READ azimuth NOTIFY azimuthChanged) public: DeviceDirection(QObject *parent = 0); // The accessor method for the azimuth property qreal azimuth() const; void calibrateOffset(); int getCalibrationOffset() const; Q_SIGNALS: // The change notification signal of the azimuth property void azimuthChanged(); protected: /** * This method is reimplemented from the QCompassFilter interface and is * called by the QCompass whenever new values are available. */ bool filter(QCompassReading *reading); private: // The compass sensor QCompass m_compassSensor; // The azimuth value int calibrationOffset; qreal m_azimuth; }; #endif // DEVICEDIRECTION_H
e52043c1c3554cf01ab0752a602832e2670c7f92
57f949c24d3ad70a35e5c4e10fb8a0962cef0fc9
/Strings/RomanToInteger.cpp
c4155f07334e807e2806bbcd3c3c989522ce81c8
[]
no_license
harshitmuhal/InterviewBit
98eae44cb2eaa5484a30e2f5141873d8d82a7b5a
c1be2b214de85b64c3cea43024bfacdd1f7f7e11
refs/heads/master
2022-12-23T19:56:08.913716
2020-10-01T07:26:50
2020-10-01T07:26:50
265,763,901
0
1
null
2020-05-21T05:37:06
2020-05-21T05:37:05
null
UTF-8
C++
false
false
989
cpp
RomanToInteger.cpp
/* Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. Read more details about roman numerals at Roman Numeric System Example : Input : "XIV" Return : 14 Input : "XX" Output : 20 LINK: https://www.interviewbit.com/problems/roman-to-integer/ */ int val(char c) { if(c=='I') return 1; if(c=='V') return 5; if(c=='X') return 10; if(c=='L') return 50; if(c=='C') return 100; if(c=='D') return 500; if(c=='M') return 1000; } int Solution::romanToInt(string s) { int res = 0; int len = s.length(); for(int i=0;i<len;i++) { int v1 = val(s[i]); if(i<len-1) { int v2 = val(s[i+1]); if(v2>v1) { res += v2-v1; i++; } else res += v1; } else res += v1; } return res; }
38335f3dfc50333929de83a3bcf8fdebb7fc6e88
c036e62d11520ad869994e6547aec40758e2f518
/src/marsupial_node.cpp
571ac25c5d5f36fb9fc4a428613a4db84d7f7387
[]
no_license
wuyou33/marsupial_optimizer
798f319f4dcc783c5a97fe568dc885754b9fafa9
bc74480d9800fdea3982fa15f5e38039725fb5f5
refs/heads/g2o
2023-07-30T22:48:48.769160
2021-03-03T07:33:46
2021-03-03T07:33:46
411,654,734
1
0
null
2021-09-29T11:56:40
2021-09-29T11:56:39
null
UTF-8
C++
false
false
1,196
cpp
marsupial_node.cpp
#include "marsupial.hpp" #include "ros/ros.h" #include <dynamic_reconfigure/server.h> #include "marsupial_optimizer/OptimizationParamsConfig.h" // ============= Global Variables ================ // =========== Function declarations ============= void dynamicReconfigureCallback(marsupial_optimizer::OptimizationParamsConfig &config, uint32_t level){ // ROS_INFO("Dynamic reconfigure ready to use !!!"); } // =============== Main function ================= using namespace std; int main(int argc, char** argv) { ros::init(argc, argv, "marsupial_node"); ROS_INFO("Starting MARSUPIAL_NODE for Optimization trajectory"); ros::NodeHandle nh; ros::NodeHandle pnh("~"); Marsupial m_(nh, pnh, "marsupial_node"); // ros::Rate r(ros::Duration(10)); ros::Rate r(5); dynamic_reconfigure::Server<marsupial_optimizer::OptimizationParamsConfig> server_; dynamic_reconfigure::Server<marsupial_optimizer::OptimizationParamsConfig>::CallbackType f_; f_ = boost::bind(&dynamicReconfigureCallback,_1,_2); server_.setCallback(f_); while (ros::ok()) { ros::spinOnce(); // m_.executeOptimization(); m_.tfBroadcaster(); r.sleep(); } return 0; }
71bc6907da9278eb139439f3f80b551fd4b14f5e
a6589aad075014bca394c8f5385ba948443eada6
/source/pepper/freelook_camera_controller.cpp
e855801428231f18caadb48f91a2fa75c8cef152
[ "MIT" ]
permissive
omnigoat/shiny
ee6dbec6dd318297c0e57663a4ceee7b28859fc9
e5ecaeaca7fdacf660939b2bb21de6e9f97b9463
refs/heads/master
2021-01-24T06:13:40.900853
2018-09-09T06:13:18
2018-09-09T06:13:18
7,682,780
4
0
null
null
null
null
UTF-8
C++
false
false
3,246
cpp
freelook_camera_controller.cpp
#include <pepper/freelook_camera_controller.hpp> #include <fooey/events/mouse.hpp> #include <fooey/keys.hpp> using namespace pepper; using pepper::freelook_camera_controller_t; #pragma warning(disable: 4351) freelook_camera_controller_t::freelook_camera_controller_t(fooey::window_ptr const& window) : window_(window) , require_mousedown_() , position_(0.f, 0.f, -2.f, 1.f) , walk_direction_(0.f, 0.f, 1.f, 0.f) , strafe_direction_(1.f, 0.f, 0.f, 0.f) , phi_(), theta_() , WASD_{} , MB_() , ctrl_() , old_x_(-1), old_y_(-1) { window_->on({ {"mouse-enter", [&](fooey::events::mouse_t const& e) { old_x_ = e.x(); old_y_ = e.y(); }}, {"mouse-move", [&](fooey::events::mouse_t const& e) { if (!require_mousedown_ || MB_) { auto dp = e.x() - old_x_; phi_ += dp * 0.01f; auto dt = e.y() - old_y_; theta_ -= dt * 0.01f; } old_x_ = e.x(); old_y_ = e.y(); }}, {"mouse-down.left", [&](fooey::events::mouse_t const& e) { old_x_ = e.x(); old_y_ = e.y(); MB_ = true; }}, {"mouse-up.left", [&]{ MB_ = false; }}, {"mouse-leave", [&]{ MB_ = false; }} }); window->key_state.on_key_down(fooey::key_t::W, [&] { WASD_[0] = true; }); window->key_state.on_key_down(fooey::key_t::A, [&] { WASD_[1] = true; }); window->key_state.on_key_down(fooey::key_t::S, [&] { WASD_[2] = true; }); window->key_state.on_key_down(fooey::key_t::D, [&] { WASD_[3] = true; }); window->key_state.on_key_down(fooey::key_t::Ctrl, [&] { ctrl_ = true; }); window->key_state.on_key_up(fooey::key_t::W, [&] { WASD_[0] = false; }); window->key_state.on_key_up(fooey::key_t::A, [&] { WASD_[1] = false; }); window->key_state.on_key_up(fooey::key_t::S, [&] { WASD_[2] = false; }); window->key_state.on_key_up(fooey::key_t::D, [&] { WASD_[3] = false; }); window->key_state.on_key_up(fooey::key_t::Ctrl, [&] { ctrl_ = false; }); } auto freelook_camera_controller_t::camera() const -> shiny::camera_t const& { return camera_; } auto freelook_camera_controller_t::update(uint timestep_in_ms) -> void { if (MB_ || !require_mousedown_) { if (theta_ > aml::pi_over_two - 0.1) theta_ = aml::pi_over_two - 0.1f; else if (theta_ < -aml::pi_over_two + 0.1f) theta_ = -aml::pi_over_two + 0.1f; } walk_direction_ = aml::normalize(aml::vector4f(sin(phi_) * cos(theta_), sin(theta_), cos(phi_) * cos(theta_), 0.f)); strafe_direction_ = aml::cross_product(aml::vector4f(0.f, 1.f, 0.f, 0.f), walk_direction_); auto up = aml::cross_product(walk_direction_, strafe_direction_); auto walk_speed = 0.02f; if (ctrl_) walk_speed *= 0.1f; if (WASD_[0]) position_ += walk_direction_ * walk_speed; if (WASD_[1]) position_ -= strafe_direction_ * walk_speed; if (WASD_[2]) position_ -= walk_direction_ * walk_speed; if (WASD_[3]) position_ += strafe_direction_ * walk_speed; camera_ = shiny::camera_t( aml::look_at(position_, position_ + walk_direction_, up), aml::perspective_fov(aml::pi_over_two, (float)window_->height() / window_->width(), 0.001f, 100.f)); } auto freelook_camera_controller_t::require_mousedown_for_rotation(bool x) -> void { require_mousedown_ = x; }
9663f8325d330f12947e63170b991d3797a2c204
ce451e155d7fca644780a7adacefc239c52fa7a3
/lib/spd_nogit/shortest_path_decomposition/include/GraphWrapper.hpp
69d0f038dd03465d2c363d336548c1ec5631e73f
[]
no_license
mooori/ba
25f9d4215734f25a62128283ec0dd2e9ace95381
237cae137e584d97624830235e8b328c5c2c8911
refs/heads/master
2021-08-16T09:49:15.009723
2017-11-19T14:43:49
2017-11-19T14:43:49
110,585,651
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
hpp
GraphWrapper.hpp
#pragma once #include <stdlib.h> #include <iostream> #include <iterator> #include <utility> #include <string> #include <queue> #include <stack> #include "Common.h" #include "Path.hpp" class GraphWrapper { public: GraphWrapper(Vertex_Descr const vert_array[], const int sizeV, Edge const edge_array[], const int sizeE); GraphWrapper(); GraphWrapper(GraphWrapper &g_in); GraphWrapper& operator=(GraphWrapper &g_in); ~GraphWrapper(); Vertex_Descr arbitraryVertex(); void addVertices(Vertex_Descr v); void removeVertex(Vertex_Descr v, bool conv); void removeVertices(Vertex_Vec vertices, bool conv); Vertex_Descr getArbitraryBorderVertex(Vertex_Descr v); Path* shortestPath(Vertex_Vec sources, Vertex_Vec targets); Vertex_Vec neighbours(Vertex_Descr u, bool conv); Vertex_Vec neighbours(Vertex_Vec &vertices, bool conv); Vertex_Vec bfsVertices(Vertex_Descr v, int r, bool conv); GraphWrapper* bfsGraph(Vertex_Descr v, int r, bool conv); void addEdges(Vertex_Descr u, Vertex_Descr v); bool hasEdge(Vertex_Descr u, Vertex_Descr v, bool conv); Vertex_Vec getVertices(); int getSize(); std::vector<Edge> getEdges(); void print(); Graph getGraph(); private: Graph g; Vertex_Map map_l, map_r; };
0d11bfd179902b203a559156259987bc22d6f854
f90415d84bcc2789b518d5c95802bbc5a3dc8ce4
/src/PSBase/PS3DMath.h
b55e2c98bcb14d7733eb40936cad7b925811dbfd
[]
no_license
Realitian/PowerSystem3D
8df733a3efe8fdf9dd9d6cba4f8ad755dd7aaae5
248624b8d002f925c861bcbd62859aff198411cc
refs/heads/master
2023-04-30T05:08:11.749659
2008-11-10T19:12:23
2008-11-10T19:12:23
367,035,341
0
0
null
null
null
null
UTF-8
C++
false
false
23,540
h
PS3DMath.h
#ifndef _PS_3DMATH_H_ #define _PS_3DMATH_H_ #include <assert.h> #include <math.h> #ifdef _WIN32 #include <limits> #else #include <limits.h> #endif #include <memory.h> #include <stdlib.h> #include <float.h> typedef float ps_scalar; #define ps_zero ps_scalar(0) #define ps_zero_5 ps_scalar(0.5) #define ps_one ps_scalar(1.0) #define ps_two ps_scalar(2) #define ps_half_pi ps_scalar(3.14159265358979323846264338327950288419716939937510582 * 0.5) #define ps_quarter_pi ps_scalar(3.14159265358979323846264338327950288419716939937510582 * 0.25) #define ps_pi ps_scalar(3.14159265358979323846264338327950288419716939937510582) #define ps_two_pi ps_scalar(3.14159265358979323846264338327950288419716939937510582 * 2.0) #define ps_oo_pi ps_one / ps_pi #define ps_oo_two_pi ps_one / ps_two_pi #define ps_oo_255 ps_one / ps_scalar(255) #define ps_oo_128 ps_one / ps_scalar(128) #define ps_to_rad ps_pi / ps_scalar(180) #define ps_to_deg ps_scalar(180) / ps_pi #define ps_eps ps_scalar(10e-6) #define ps_double_eps ps_scalar(10e-6) * ps_two #define ps_big_eps ps_scalar(10e-2) #define ps_small_eps ps_scalar(10e-6) #define ps_sqrthalf ps_scalar(0.7071067811865475244) #define ps_scalar_max ps_scalar(FLT_MAX) #define ps_scalar_min ps_scalar(FLT_MIN) struct vec2; struct vec2t; struct vec3; struct vec3t; struct vec4; struct vec4t; struct vec2 { vec2() { } vec2(ps_scalar x, ps_scalar y) : x(x), y(y) { } vec2(const ps_scalar* xy) : x(xy[0]), y(xy[1]) { } vec2(const vec2& u) : x(u.x), y(u.y) { } vec2(const vec3&); bool operator==(const vec2 & u) const { return (u.x == x && u.y == y) ? true : false; } bool operator!=(const vec2 & u) const { return !(*this == u ); } vec2 & operator*=(const ps_scalar & lambda) { x*= lambda; y*= lambda; return *this; } vec2 & operator-=(const vec2 & u) { x-= u.x; y-= u.y; return *this; } vec2 & operator+=(const vec2 & u) { x+= u.x; y+= u.y; return *this; } ps_scalar & operator[](int i) { return vec_array[i]; } const ps_scalar operator[](int i) const { return vec_array[i]; } ps_scalar sq_norm() const { return x * x + y * y; } ps_scalar norm() const { return sqrtf(sq_norm()); } union { struct { ps_scalar x,y; // standard names for components }; struct { ps_scalar s,t; // standard names for components }; ps_scalar vec_array[2]; // array access }; }; inline const vec2 operator+(const vec2& u, const vec2& v) { return vec2(u.x + v.x, u.y + v.y); } inline const vec2 operator-(const vec2& u, const vec2& v) { return vec2(u.x - v.x, u.y - v.y); } inline const vec2 operator*(const ps_scalar s, const vec2& u) { return vec2(s * u.x, s * u.y); } inline const vec2 operator/(const vec2& u, const ps_scalar s) { return vec2(u.x / s, u.y / s); } inline const vec2 operator*(const vec2&u, const vec2&v) { return vec2(u.x * v.x, u.y * v.y); } struct vec3 { vec3() { } vec3(ps_scalar x, ps_scalar y, ps_scalar z) : x(x), y(y), z(z) { } vec3(const ps_scalar* xyz) : x(xyz[0]), y(xyz[1]), z(xyz[2]) { } vec3(const vec2& u) : x(u.x), y(u.y), z(1.0f) { } vec3(const vec3& u) : x(u.x), y(u.y), z(u.z) { } vec3(const vec4&); bool operator==(const vec3 & u) const { return (u.x == x && u.y == y && u.z == z) ? true : false; } bool operator!=( const vec3& rhs ) const { return !(*this == rhs ); } vec3 & operator*=(const ps_scalar & lambda) { x*= lambda; y*= lambda; z*= lambda; return *this; } vec3 operator - () const { return vec3(-x, -y, -z); } vec3 & operator-=(const vec3 & u) { x-= u.x; y-= u.y; z-= u.z; return *this; } vec3 & operator+=(const vec3 & u) { x+= u.x; y+= u.y; z+= u.z; return *this; } ps_scalar normalize(); void orthogonalize( const vec3& v ); void orthonormalize( const vec3& v ) { orthogonalize( v ); // just orthogonalize... normalize(); // ...and normalize it } ps_scalar sq_norm() const { return x * x + y * y + z * z; } ps_scalar norm() const { return sqrtf(sq_norm()); } ps_scalar & operator[](int i) { return vec_array[i]; } const ps_scalar operator[](int i) const { return vec_array[i]; } union { struct { ps_scalar x,y,z; // standard names for components }; struct { ps_scalar s,t,r; // standard names for components }; ps_scalar vec_array[3]; // array access }; }; inline const vec3 operator+(const vec3& u, const vec3& v) { return vec3(u.x + v.x, u.y + v.y, u.z + v.z); } inline const vec3 operator-(const vec3& u, const vec3& v) { return vec3(u.x - v.x, u.y - v.y, u.z - v.z); } inline const vec3 operator^(const vec3& u, const vec3& v) { return vec3(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x); } inline const vec3 operator*(const ps_scalar s, const vec3& u) { return vec3(s * u.x, s * u.y, s * u.z); } inline const vec3 operator/(const vec3& u, const ps_scalar s) { return vec3(u.x / s, u.y / s, u.z / s); } inline const vec3 operator*(const vec3& u, const vec3& v) { return vec3(u.x * v.x, u.y * v.y, u.z * v.z); } inline vec2::vec2(const vec3& u) { ps_scalar k = 1 / u.z; x = k * u.x; y = k * u.y; } struct vec4 { vec4() { } vec4(ps_scalar x, ps_scalar y, ps_scalar z, ps_scalar w) : x(x), y(y), z(z), w(w) { } vec4(const ps_scalar* xyzw) : x(xyzw[0]), y(xyzw[1]), z(xyzw[2]), w(xyzw[3]) { } vec4(const vec3& u) : x(u.x), y(u.y), z(u.z), w(1.0f) { } vec4(const vec4& u) : x(u.x), y(u.y), z(u.z), w(u.w) { } bool operator==(const vec4 & u) const { return (u.x == x && u.y == y && u.z == z && u.w == w) ? true : false; } bool operator!=( const vec4& rhs ) const { return !(*this == rhs ); } vec4 & operator*=(const ps_scalar & lambda) { x*= lambda; y*= lambda; z*= lambda; w*= lambda; return *this; } vec4 & operator-=(const vec4 & u) { x-= u.x; y-= u.y; z-= u.z; w-= u.w; return *this; } vec4 & operator+=(const vec4 & u) { x+= u.x; y+= u.y; z+= u.z; w+= u.w; return *this; } vec4 operator - () const { return vec4(-x, -y, -z, -w); } ps_scalar & operator[](int i) { return vec_array[i]; } const ps_scalar operator[](int i) const { return vec_array[i]; } union { struct { ps_scalar x,y,z,w; // standard names for components }; struct { ps_scalar s,t,r,q; // standard names for components }; ps_scalar vec_array[4]; // array access }; }; inline const vec4 operator+(const vec4& u, const vec4& v) { return vec4(u.x + v.x, u.y + v.y, u.z + v.z, u.w + v.w); } inline const vec4 operator-(const vec4& u, const vec4& v) { return vec4(u.x - v.x, u.y - v.y, u.z - v.z, u.w - v.w); } inline const vec4 operator*(const ps_scalar s, const vec4& u) { return vec4(s * u.x, s * u.y, s * u.z, s * u.w); } inline const vec4 operator/(const vec4& u, const ps_scalar s) { return vec4(u.x / s, u.y / s, u.z / s, u.w / s); } inline const vec4 operator*(const vec4& u, const vec4& v) { return vec4(u.x * v.x, u.y * v.y, u.z * v.z, u.w * v.w); } inline vec3::vec3(const vec4& u) { x = u.x; y = u.y; z = u.z; } // quaternion struct quat; /* for all the matrices...a<x><y> indicates the element at row x, col y For example: a01 <-> row 0, col 1 */ struct mat3 { mat3(); mat3(const ps_scalar * array); mat3(const mat3 & M); mat3( const ps_scalar& f0, const ps_scalar& f1, const ps_scalar& f2, const ps_scalar& f3, const ps_scalar& f4, const ps_scalar& f5, const ps_scalar& f6, const ps_scalar& f7, const ps_scalar& f8 ) : a00( f0 ), a10( f1 ), a20( f2 ), a01( f3 ), a11( f4 ), a21( f5 ), a02( f6 ), a12( f7 ), a22( f8) { } const vec3 col(const int i) const { return vec3(&mat_array[i * 3]); } const vec3 operator[](int i) const { return vec3(mat_array[i], mat_array[i + 3], mat_array[i + 6]); } const ps_scalar& operator()(const int& i, const int& j) const { return mat_array[ j * 3 + i ]; } ps_scalar& operator()(const int& i, const int& j) { return mat_array[ j * 3 + i ]; } mat3 & operator*=(const ps_scalar & lambda) { for (int i = 0; i < 9; ++i) mat_array[i] *= lambda; return *this; } mat3 & operator-=(const mat3 & M) { for (int i = 0; i < 9; ++i) mat_array[i] -= M.mat_array[i]; return *this; } void set_row(int i, const vec3 & v) { mat_array[i] = v.x; mat_array[i + 3] = v.y; mat_array[i + 6] = v.z; } void set_col(int i, const vec3 & v) { mat_array[i * 3] = v.x; mat_array[i * 3 + 1] = v.y; mat_array[i * 3 + 2] = v.z; } void set_rot(const ps_scalar & theta, const vec3 & v); void set_rot(const vec3 & u, const vec3 & v); // Matrix norms... // Compute || M || // 1 ps_scalar norm_one(); // Compute || M || // +inf ps_scalar norm_inf(); union { struct { ps_scalar a00, a10, a20; // standard names for components ps_scalar a01, a11, a21; // standard names for components ps_scalar a02, a12, a22; // standard names for components }; ps_scalar mat_array[9]; // array access }; }; const vec3 operator*(const mat3&, const vec3&); const vec3 operator*(const vec3&, const mat3&); struct mat4 { mat4(); mat4(const ps_scalar * array); mat4(const mat4 & M); mat4( const ps_scalar& f0, const ps_scalar& f1, const ps_scalar& f2, const ps_scalar& f3, const ps_scalar& f4, const ps_scalar& f5, const ps_scalar& f6, const ps_scalar& f7, const ps_scalar& f8, const ps_scalar& f9, const ps_scalar& f10, const ps_scalar& f11, const ps_scalar& f12, const ps_scalar& f13, const ps_scalar& f14, const ps_scalar& f15 ) : a00( f0 ), a10( f1 ), a20( f2 ), a30( f3 ), a01( f4 ), a11( f5 ), a21( f6 ), a31( f7 ), a02( f8 ), a12( f9 ), a22( f10), a32( f11), a03( f12), a13( f13), a23( f14), a33( f15) { } const vec4 col(const int i) const { return vec4(&mat_array[i * 4]); } const vec4 operator[](const int& i) const { return vec4(mat_array[i], mat_array[i + 4], mat_array[i + 8], mat_array[i + 12]); } const ps_scalar& operator()(const int& i, const int& j) const { return mat_array[ j * 4 + i ]; } ps_scalar& operator()(const int& i, const int& j) { return mat_array[ j * 4 + i ]; } void set_col(int i, const vec4 & v) { mat_array[i * 4] = v.x; mat_array[i * 4 + 1] = v.y; mat_array[i * 4 + 2] = v.z; mat_array[i * 4 + 3] = v.w; } void set_row(int i, const vec4 & v) { mat_array[i] = v.x; mat_array[i + 4] = v.y; mat_array[i + 8] = v.z; mat_array[i + 12] = v.w; } mat3 & get_rot(mat3 & M) const; quat & get_rot(quat & q) const; void set_rot(const quat & q); void set_rot(const mat3 & M); void set_rot(const ps_scalar & theta, const vec3 & v); void set_rot(const vec3 & u, const vec3 & v); void set_scale(const vec3& s); vec3& get_scale(vec3& s) const; void set_translation(const vec3 & t); vec3 & get_translation(vec3 & t) const; mat4 operator*(const mat4&) const; union { struct { ps_scalar a00, a10, a20, a30; // standard names for components ps_scalar a01, a11, a21, a31; // standard names for components ps_scalar a02, a12, a22, a32; // standard names for components ps_scalar a03, a13, a23, a33; // standard names for components }; struct { ps_scalar _11, _12, _13, _14; // standard names for components ps_scalar _21, _22, _23, _24; // standard names for components ps_scalar _31, _32, _33, _34; // standard names for components ps_scalar _41, _42, _43, _44; // standard names for components }; union { struct { ps_scalar b00, b10, b20, p; // standard names for components ps_scalar b01, b11, b21, q; // standard names for components ps_scalar b02, b12, b22, r; // standard names for components ps_scalar x, y, z, w; // standard names for components }; }; ps_scalar mat_array[16]; // array access }; }; const vec4 operator*(const mat4&, const vec4&); const vec4 operator*(const vec4&, const mat4&); // quaternion struct quat { public: quat(); quat(ps_scalar x, ps_scalar y, ps_scalar z, ps_scalar w); quat(const quat& quat); quat(const vec3& axis, ps_scalar angle); quat(const mat3& rot); quat& operator=(const quat& quat); quat operator-() { return quat(-x, -y, -z, -w); } quat Inverse(); void Normalize(); void FromMatrix(const mat3& mat); void ToMatrix(mat3& mat) const; quat& operator*=(const quat& q); static const quat Identity; ps_scalar& operator[](int i) { return comp[i]; } const ps_scalar operator[](int i) const { return comp[i]; } union { struct { ps_scalar x, y, z, w; }; ps_scalar comp[4]; }; }; const quat operator*(const quat&, const quat&); extern quat & add_quats(quat & p, const quat & q1, const quat & q2); extern ps_scalar dot(const quat & p, const quat & q); extern quat & dot(ps_scalar s, const quat & p, const quat & q); extern quat & slerp_quats(quat & p, ps_scalar s, const quat & q1, const quat & q2); extern quat & axis_to_quat(quat & q, const vec3 & a, const ps_scalar phi); extern mat3 & quat_2_mat(mat3 &M, const quat &q ); extern quat & mat_2_quat(quat &q,const mat3 &M); // constant algebraic values static const ps_scalar array16_id[] = { ps_one, ps_zero, ps_zero, ps_zero, ps_zero, ps_one, ps_zero, ps_zero, ps_zero, ps_zero, ps_one, ps_zero, ps_zero, ps_zero, ps_zero, ps_one}; static const ps_scalar array16_null[] = { ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero}; static const ps_scalar array16_scale_bias[] = { ps_zero_5, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero_5, ps_zero, ps_zero, ps_zero, ps_zero, ps_zero_5, ps_zero, ps_zero_5, ps_zero_5, ps_zero_5, ps_one}; static const ps_scalar array9_id[] = { ps_one, ps_zero, ps_zero, ps_zero, ps_one, ps_zero, ps_zero, ps_zero, ps_one}; static const vec2 vec2_null(ps_zero,ps_zero); static const vec4 vec4_one(ps_one,ps_one,ps_one,ps_one); static const vec3 vec3_one(ps_one,ps_one,ps_one); static const vec3 vec3_null(ps_zero,ps_zero,ps_zero); static const vec3 vec3_x(ps_one,ps_zero,ps_zero); static const vec3 vec3_y(ps_zero,ps_one,ps_zero); static const vec3 vec3_z(ps_zero,ps_zero,ps_one); static const vec3 vec3_neg_x(-ps_one,ps_zero,ps_zero); static const vec3 vec3_neg_y(ps_zero,-ps_one,ps_zero); static const vec3 vec3_neg_z(ps_zero,ps_zero,-ps_one); static const vec4 vec4_null(ps_zero,ps_zero,ps_zero,ps_zero); static const vec4 vec4_x(ps_one,ps_zero,ps_zero,ps_zero); static const vec4 vec4_neg_x(-ps_one,ps_zero,ps_zero,ps_zero); static const vec4 vec4_y(ps_zero,ps_one,ps_zero,ps_zero); static const vec4 vec4_neg_y(ps_zero,-ps_one,ps_zero,ps_zero); static const vec4 vec4_z(ps_zero,ps_zero,ps_one,ps_zero); static const vec4 vec4_neg_z(ps_zero,ps_zero,-ps_one,ps_zero); static const vec4 vec4_w(ps_zero,ps_zero,ps_zero,ps_one); static const vec4 vec4_neg_w(ps_zero,ps_zero,ps_zero,-ps_one); static const quat quat_id(ps_zero,ps_zero,ps_zero,ps_one); static const mat4 mat4_id(array16_id); static const mat3 mat3_id(array9_id); static const mat4 mat4_null(array16_null); static const mat4 mat4_scale_bias(array16_scale_bias); // normalizes a vector and return a reference of itself extern vec2 & normalize(vec2 & u); extern vec3 & normalize(vec3 & u); extern vec4 & normalize(vec4 & u); // Computes the squared magnitude inline ps_scalar ps_sq_norm(const vec3 & n) { return n.x * n.x + n.y * n.y + n.z * n.z; } inline ps_scalar ps_sq_norm(const vec4 & n) { return n.x * n.x + n.y * n.y + n.z * n.z + n.w * n.w; } // Computes the magnitude inline ps_scalar ps_norm(const vec3 & n) { return sqrtf(ps_sq_norm(n)); } inline ps_scalar ps_norm(const vec4 & n) { return sqrtf(ps_sq_norm(n)); } // computes the cross product ( v cross w) and stores the result in u // i.e. u = v cross w extern vec3 & cross(vec3 & u, const vec3 & v, const vec3 & w); // computes the dot product ( v dot w) and stores the result in u // i.e. u = v dot w extern ps_scalar & dot(ps_scalar & u, const vec3 & v, const vec3 & w); extern ps_scalar dot(const vec3 & v, const vec3 & w); extern ps_scalar & dot(ps_scalar & u, const vec4 & v, const vec4 & w); extern ps_scalar dot(const vec4 & v, const vec4 & w); extern ps_scalar & dot(ps_scalar & u, const vec3 & v, const vec4 & w); extern ps_scalar dot(const vec3 & v, const vec4 & w); extern ps_scalar & dot(ps_scalar & u, const vec4 & v, const vec3 & w); extern ps_scalar dot(const vec4 & v, const vec3 & w); // compute the reflected vector R of L w.r.t N - vectors need to be // normalized // // R N L // _ _ // |\ ^ /| // \ | / // \ | / // \|/ // + extern vec3 & reflect(vec3 & r, const vec3 & n, const vec3 & l); // Computes u = v * lambda + u extern vec3 & madd(vec3 & u, const vec3 & v, const ps_scalar & lambda); // Computes u = v * lambda extern vec3 & mult(vec3 & u, const vec3 & v, const ps_scalar & lambda); // Computes u = v * w extern vec3 & mult(vec3 & u, const vec3 & v, const vec3 & w); // Computes u = v + w extern vec3 & add(vec3 & u, const vec3 & v, const vec3 & w); // Computes u = v - w extern vec3 & sub(vec3 & u, const vec3 & v, const vec3 & w); // Computes u = u * s extern vec2 & scale(vec2 & u, const ps_scalar s); extern vec3 & scale(vec3 & u, const ps_scalar s); extern vec4 & scale(vec4 & u, const ps_scalar s); // Computes u = M * v extern vec3 & mult(vec3 & u, const mat3 & M, const vec3 & v); extern vec4 & mult(vec4 & u, const mat4 & M, const vec4 & v); // Computes u = v * M extern vec3 & mult(vec3 & u, const vec3 & v, const mat3 & M); extern vec4 & mult(vec4 & u, const vec4 & v, const mat4 & M); // Computes u = M(4x4) * v and divides by w extern vec3 & mult_pos(vec3 & u, const mat4 & M, const vec3 & v); // Computes u = M(4x4) * v extern vec3 & mult_dir(vec3 & u, const mat4 & M, const vec3 & v); // Computes u = M(4x4) * v and does not divide by w (assumed to be 1) extern vec3 & mult(vec3& u, const mat4& M, const vec3& v); // Computes u = v * M(4x4) and divides by w extern vec3 & mult_pos(vec3 & u, const vec3 & v, const mat4 & M); // Computes u = v * M(4x4) extern vec3 & mult_dir(vec3 & u, const vec3 & v, const mat4 & M); // Computes u = v * M(4x4) and does not divide by w (assumed to be 1) extern vec3 & mult(vec3& u, const vec3& v, const mat4& M); // Computes A += B extern mat4 & add(mat4 & A, const mat4 & B); extern mat3 & add(mat3 & A, const mat3 & B); // Computes C = A + B extern mat4 & add(mat4 & C, const mat4 & A, const mat4 & B); extern mat3 & add(mat3 & C, const mat3 & A, const mat3 & B); // Computes C = A * B extern mat4 & mult(mat4 & C, const mat4 & A, const mat4 & B); extern mat3 & mult(mat3 & C, const mat3 & A, const mat3 & B); // Compute M = -M extern mat4 & negate(mat4 & M); extern mat3 & negate(mat3 & M); // Computes B = Transpose(A) // T // B = A extern mat3 & transpose(mat3 & B, const mat3 & A); extern mat4 & transpose(mat4 & B, const mat4 & A); // Computes B = Transpose(B) // T // B = B extern mat3 & transpose(mat3 & B); extern mat4 & transpose(mat4 & B); // Computes B = inverse(A) // -1 // B = A extern mat4 & invert(mat4 & B, const mat4 & A); extern mat3 & invert(mat3 & B, const mat3 & A); // Computes B = inverse(A) // T T // (R t) (R -R t) // assuming that A = (0 1) so that B = (0 1) // B = A extern mat4 & invert_rot_trans(mat4 & B, const mat4 & A); extern mat4 & look_at(mat4 & M, const vec3 & eye, const vec3 & center, const vec3 & up); extern mat4 & frustum(mat4 & M, const ps_scalar l, const ps_scalar r, const ps_scalar b, const ps_scalar t, const ps_scalar n, const ps_scalar f); extern mat4 & perspective(mat4 & M, const ps_scalar fovy, const ps_scalar aspect, const ps_scalar n, const ps_scalar f); extern mat4 & ortho(mat4 & M, const ps_scalar left, const ps_scalar right, const ps_scalar bottom, const ps_scalar top, const ps_scalar n, const ps_scalar f); /* Decompose Affine Matrix * A = TQS, where * A is the affine transform * T is the translation vector * Q is the rotation (quaternion) * S is the scale vector * f is the sign of the determinant */ extern void decomp_affine(const mat4 & A, vec3 & T, quat & Q, quat & U, vec3 & S, ps_scalar & f); // quaternion extern quat & normalize(quat & p); extern quat & conj(quat & p); extern quat & conj(quat & p, const quat & q); extern quat & add_quats(quat & p, const quat & q1, const quat & q2); extern quat & axis_to_quat(quat & q, const vec3 & a, const ps_scalar phi); extern mat3 & quat_2_mat(mat3 &M, const quat &q ); extern quat & mat_2_quat(quat &q,const mat3 &M); extern quat & mat_2_quat(quat &q,const mat4 &M); // surface properties extern mat3 & tangent_basis(mat3 & basis,const vec3 & v0,const vec3 & v1,const vec3 & v2,const vec2 & t0,const vec2 & t1,const vec2 & t2, const vec3 & n); // linear interpolation inline ps_scalar lerp(ps_scalar t, ps_scalar a, ps_scalar b) { return a * (ps_one - t) + t * b; } inline vec3 & lerp(vec3 & w, const ps_scalar & t, const vec3 & u, const vec3 & v) { w.x = lerp(t, u.x, v.x); w.y = lerp(t, u.y, v.y); w.z = lerp(t, u.z, v.z); return w; } inline vec4 & lerp(vec4 & w, const ps_scalar & t, const vec4 & u, const vec4 & v) { w.x = lerp(t, u.x, v.x); w.y = lerp(t, u.y, v.y); w.z = lerp(t, u.z, v.z); w.w = lerp(t, u.w, v.w); return w; } // utilities inline ps_scalar ps_min(const ps_scalar & lambda, const ps_scalar & n) { return (lambda < n ) ? lambda : n; } inline ps_scalar ps_max(const ps_scalar & lambda, const ps_scalar & n) { return (lambda > n ) ? lambda : n; } inline ps_scalar ps_clamp(ps_scalar u, const ps_scalar min, const ps_scalar max) { u = (u < min) ? min : u; u = (u > max) ? max : u; return u; } extern ps_scalar ps_random(); extern quat & trackball(quat & q, vec2 & pt1, vec2 & pt2, ps_scalar trackballsize); extern vec3 & cube_map_normal(int i, int x, int y, int cubesize, vec3 & v); // Componentwise maximum and minium inline void ps_max(vec3 & vOut, const vec3 & vFirst, const vec3 & vSecond) { vOut.x = ps_max(vFirst.x, vSecond.x); vOut.y = ps_max(vFirst.y, vSecond.y); vOut.z = ps_max(vFirst.z, vSecond.z); } inline void ps_min(vec3 & vOut, const vec3 & vFirst, const vec3 & vSecond) { vOut.x = ps_min(vFirst.x, vSecond.x); vOut.y = ps_min(vFirst.y, vSecond.y); vOut.z = ps_min(vFirst.z, vSecond.z); } // geometry // computes the area of a triangle extern ps_scalar ps_area(const vec3 & v1, const vec3 & v2, const vec3 &v3); // computes the perimeter of a triangle extern ps_scalar ps_perimeter(const vec3 & v1, const vec3 & v2, const vec3 &v3); // find the inscribed circle extern ps_scalar ps_find_in_circle( vec3 & center, const vec3 & v1, const vec3 & v2, const vec3 &v3); // find the circumscribed circle extern ps_scalar ps_find_circ_circle( vec3 & center, const vec3 & v1, const vec3 & v2, const vec3 &v3); // fast cosine functions extern ps_scalar fast_cos(const ps_scalar x); extern ps_scalar ffast_cos(const ps_scalar x); // determinant ps_scalar det(const mat3 & A); extern void ps_is_valid(const vec3& v); extern void ps_is_valid(ps_scalar lambda); #endif //_PS_3DMATH_H_
6beb76a44a03a73d3fe987607a8318844afb06ce
3b64a90159b5cce61226c96ae45c30126fb9a4ec
/source/Rectangular.cpp
9f68f5b7678d910f38bb2b08776258fef5a7de76
[]
no_license
xHeler/zad5_3-RafalSzyinski1
38616dda18df9c31c29a9635c2b9f99e634531bd
9d7d7d8d9f31a40595f0a7e89f04d0afe7a91c50
refs/heads/main
2023-05-29T12:22:22.158305
2021-06-13T13:12:10
2021-06-13T13:12:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,067
cpp
Rectangular.cpp
/** * @file Rectangular.cpp * Definition of Rectangular class */ #include "Rectangular.h" #include <sstream> #include <utility> /// Single class constructor. Rectangular::Rectangular(std::vector<double> _x, std::vector<double> _y, std::vector<double> _z, std::vector<double> _startPoint, std::string _color) : X(std::move(_x)), Y(std::move(_y)), Z(std::move(_z)), StartPoint(std::move(_startPoint)), color(std::move(_color)) { if (StartPoint.empty()) StartPoint = std::vector<double>(X.size()); if (X.size() != Y.size() || X.size() != Z.size() || X.size() != StartPoint.size()) throw std::invalid_argument("ERROR Rectangular: x.size() != y.size() || x.size() != z.size() || x.size() != startPoint.size()"); } /// Function comparing two Rectangular. \n Using operator== from VectorAction.h. bool operator==(const Rectangular& rec1, const Rectangular& rec2) { if ((rec1.X == rec2.X) && (rec1.Y == rec2.Y) && (rec1.Z == rec2.Z) && (rec1.StartPoint == rec2.StartPoint)) return true; return false; } /// Multiplication by matrix. Multiply every vector of Rectangular by mat. \n Using MatrixAction.h. Rectangular Rectangular::operator*(const matrix<double>& mat) const { using MatrixAction::operator*; Rectangular ret(mat * X, mat * Y, mat * Z, mat * StartPoint); return ret; } /// Translation by vector. Adding vector to starting point of Rectangular. \n Using VectorAction.h Rectangular Rectangular::operator+(const std::vector<double>& vec) const { using VectorAction::operator+; Rectangular ret(X, Y, Z, StartPoint + vec); return ret; } /// @return const vector x. const std::vector<double>& Rectangular::x() const { return X; } /// @return const vector y. const std::vector<double>& Rectangular::y() const { return Y; } /// @return const vector z. const std::vector<double>& Rectangular::z() const { return Z; } /// @return const vector startPoint. const std::vector<double>& Rectangular::startPoint() const { return StartPoint; } /// @return vector with center of mass std::vector<double> Rectangular::centerOfMass() const { using VectorAction::operator*; using VectorAction::operator+; return (X + Y + Z) * (1.0/2.0); } const std::string Rectangular::getColor() const { return color; } /// Transform function helping to rotate Rectangular around center of mass in Z axis Rectangular Transform::rotateRectangularAroundCenterZ(const Rectangular& rec, double angle) { using namespace VectorAction; using namespace MatrixAction; matrix<double> m({{std::cos(M_PI/180 * angle), -std::sin(M_PI/180 * angle), 0}, {std::sin(M_PI/180 * angle), std::cos(M_PI/180 * angle), 0}, {0, 0, 1}}); Rectangular temp(rec.centerOfMass() - rec.x(), rec.centerOfMass() - rec.y(), rec.centerOfMass() - rec.z(), -rec.centerOfMass()); temp = temp * m; return Rectangular(temp.x() + temp.startPoint() , temp.y() + temp.startPoint(), temp.z() + temp.startPoint(), (rec.centerOfMass() - temp.startPoint()) + rec.startPoint()); }
ea82d93a27f048bd7ec21d38d6ba902139469f3b
1d552838d392fbe3bf767e75d1a79685708c4641
/app/src/main/cpp/soft/ljsdl_audio.cpp
ce56273b0337171b60ab2f7cee38c89fcdb1a838
[]
no_license
MisterrWu/Splayer
44aa3e54c98cc84123e424b551c642705b569173
e4908011e3a71a4bce1bce865c47d5343e2a2d3b
refs/heads/master
2020-08-15T10:34:08.532396
2019-10-25T07:02:23
2019-10-25T07:02:23
215,326,121
1
0
null
null
null
null
UTF-8
C++
false
false
1,563
cpp
ljsdl_audio.cpp
// // Created by wh on 2018/1/16. // #include "ljsdl_audio.h" int SDL_OpenAudio(SDL_Aout* aout,SDL_AudioSpec* wanted_spec, SDL_AudioSpec* spec){ int res; spec->channels = 1; ///Number of channels: 1 mono, 2 stereo spec->freq = 16000; spec->format = SDL_AUDIO_S16; ///Audio data format spec->silence = 0; ///Audio buffer silence value (calculated) spec->samples = 160*3; ///3 of 10ms 16000HZ sample rate spec->callback = wanted_spec->callback; spec->userdata = wanted_spec->userdata; spec->size = 2*spec->channels*spec->samples; ///Audio buffer size in samples (in bytes) if(NULL==aout->android_opensles) aout->android_opensles = new AndroidOpenSLES(0); aout->android_opensles->AttachAudioBuffer(spec->callback,spec->userdata); res = aout->android_opensles->Init(); if(0!=res){ return -1; } //bool ok; res = aout->android_opensles->InitPlayout(); if(0!=res){ return -1; } return 0; } int SDL_PauseAudio(SDL_Aout* aout,int start){ if(!aout->android_opensles){ return -1; } if(start){ return aout->android_opensles->StartPlayout(); }else{ return aout->android_opensles->StopPlayout(); } } //play voice int SDL_CloseAudio(SDL_Aout* aout){ if(aout->android_opensles){ aout->android_opensles->StopPlayout(); aout->android_opensles->Terminate(); delete aout->android_opensles; aout->android_opensles = NULL; } return 0; }
fc3d95f42fd84829cde3cca47d4f4c6d5a8a8a03
fdab372bdcea4b7c2da145648480667647e9d5ef
/artificialSweetner.cpp
bf503ffc6edf61f633903e89bb00c37d905f8969
[]
no_license
AlissonRoss/CPP
728abf95052395efb058de1199363848ab0e64ba
509f828d889b964c6c949150f60bc69e77cc11bc
refs/heads/master
2020-07-07T23:19:51.927892
2019-08-21T04:03:59
2019-08-21T04:03:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,882
cpp
artificialSweetner.cpp
/*Alisson Ross 8/20/19 Artificial Sweetner problem to practice variables*/ //include a library for input/output #include <iostream> //standard namespace using namespace std; int main() { //Declaring variables- Doubles are for decimal; integers are for whole numbers int mouseDosage, mouseMass, canDeath; double personMass, sodaMass, sweetnerCan, personGrams, personDosage; /* USER INPUT */ cout << "Please enter the grams of your soda: " << endl; cin >> sodaMass; //input for mouse grams cout << "Please enter the grams of your mouse: " << endl; cin >> mouseMass; //to kill the mouse cout << "Please enter the grams of artificial sweetner to the kill the mouse: " << endl; cin >> mouseDosage; //input for person in pounds cout << "Please enter in the desired weight of the person in pounds: " << endl; cin >> personMass; /* CALCULATIONS */ //convert weight from pounds to grams personGrams = (personMass * 45400) / 100; //you can reduce it to (personMass*454) cout << "personGram:" << personGrams << endl; //initializing sweetner in one can since we now have sodaMass initialized sweetnerCan = (0.001) * sodaMass; //amount of artificial sweetner in one can cout << "sweetnerCan:" << sweetnerCan << endl; //(mouseDosage * personMass) was wrong!!! Be careful! personDosage = (mouseDosage * personGrams) / mouseMass; cout << "personDosage:" << personDosage << endl; //amount that will kill the person canDeath = personDosage / sweetnerCan; cout << "canDeath:" << canDeath << endl; /* OUTPUT */ cout << "Artifical Sweetner in 1 can of soda is " << sweetnerCan << "\nThe person's weight in grams is " << sweetnerCan << "\nThe amount of artificial sweetner to kill that person is " << personDosage << " grams" << "\nThe amount of soda cans needed to kill person " << canDeath << endl; }
dbc869d52c25354113d6d3e4e7427c7cd216b905
0be8bd65e0d9fd5ea4bf7be3419bd05be2d57d36
/branches/SmartGis.1.1.vs08/src/SmtGeoCore/geo_geometry.cpp
e11638eecca51b895d66924b57742c25e15832cc
[]
no_license
jsccl1988/smartgis
d6b8018b115f43c6542c3156b63f187995a7920c
6c5cbdbd3d939012eebb8bd19964815b60215bb4
refs/heads/master
2022-12-14T09:45:54.540512
2022-12-07T08:43:12
2022-12-07T08:43:12
55,857,404
4
3
null
null
null
null
UTF-8
C++
false
false
2,579
cpp
geo_geometry.cpp
#include "geo_geometry.h" using namespace Smt_Core; namespace Smt_Geo { SmtGeometry::SmtGeometry() { m_nCoordDimension = 2; } SmtGeometry::~SmtGeometry() { } void SmtGeometry::SetCoordinateDimension( int nNewDimension ) { m_nCoordDimension = nNewDimension; } int SmtGeometry::GetCoordinateDimension() const { return m_nCoordDimension; } bool SmtGeometry::IsValid() const { return false; } bool SmtGeometry::IsSimple() const { return false; } bool SmtGeometry::IsRing() const { return false; } // SpatialRelation bool SmtGeometry::Intersects(const SmtGeometry * poGeo) const { return false; } bool SmtGeometry::Disjoint( const SmtGeometry * poGeo) const { return false; } bool SmtGeometry::Touches( const SmtGeometry * poGeo) const { return false; } bool SmtGeometry::Crosses( const SmtGeometry * poGeo) const { return false; } bool SmtGeometry::Within( const SmtGeometry * poGeo) const { return false; } bool SmtGeometry::Contains( const SmtGeometry * poGeo) const { return false; } bool SmtGeometry::Overlaps( const SmtGeometry * poGeo) const { return false; } SmtGeometry *SmtGeometry::GetBoundary() const { return NULL; } double SmtGeometry::Distance( const SmtGeometry * poGeo) const { return -1.0; } SmtGeometry *SmtGeometry::ConvexHull() const { return NULL; } SmtGeometry *SmtGeometry::Buffer( double dfDist, int nQuadSegs ) const { return NULL; } SmtGeometry *SmtGeometry::Intersection( const SmtGeometry * poGeo) const { if (NULL == poGeo) { return NULL; } return NULL; } SmtGeometry *SmtGeometry::Union( const SmtGeometry * poGeo) const { if (NULL == poGeo) { return NULL; } return NULL; } SmtGeometry *SmtGeometry::Difference( const SmtGeometry * poGeo) const { if (NULL == poGeo) { return NULL; } return NULL; } long SmtGeometry::Relationship( const SmtGeometry *,float fMargin) const { return -2; } SmtGeometry *SmtGeometry::SymmetricDifference( const SmtGeometry * poGeo) const { if (NULL == poGeo) { return NULL; } return NULL; } // backward compatibility methods. bool SmtGeometry::Intersect( SmtGeometry * poGeo) const { if (NULL == poGeo) { return false; } return NULL; } bool SmtGeometry::Equal( SmtGeometry * poGeo) const { if (NULL == poGeo) { return NULL; } return false; } }