blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
3839a18d9a68ea2125bc9850de5062156e36e208
b4d8ba34bc68f94e837843ef24f3d4ac0877681c
/MAX6952Display.ino
02ee383364c2d1339baec3b71c3562398233dd16
[]
no_license
wallace3043/MAX6952Display
b4b58b5f81b4c269ba758e1ed0cd8baf56a8ebe6
ee0a1fb6bb671c96dc1469edf5266a142d8b62aa
refs/heads/master
2020-12-13T13:06:23.928410
2020-01-20T09:00:33
2020-01-20T09:00:33
231,735,117
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
ino
// Visual Micro is in vMicro>General>Tutorial Mode // /* Name: MAX6952Display.ino Created: 2020-01-03 12:58:38 AM Author: Wallace Long */ // The setup() function runs once each time the micro-controller starts /* MAX6952 Arduino - MAX6952 (SSOP package) 5V - 35, 36, 37 GND - 4, 5, 6, 18 Pin 10 SS <--> 21 CS Pin 11 MOSI <--> 18 DIN Pin 12 MISO <--> 20 DOUT Pin 13 SCK <--> 19 CLK I've chosen 68k for Rset and 33pF for Cset which works fine so far */ #include "MAX6952Display.h" #include <SPI.h> const int CS_pin = 10; // Pin for chip select MAX6952Display display(CS_pin); void setup() { pinMode(LED_BUILTIN, OUTPUT); SPI.begin(); SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0)); display.init(); display.printString("Hi there"); delay(1000); display.printString("This is a"); delay(1000); display.printString("Counter!"); } void loop() { for(int i = 0; i < 10000; i++) { display.printInt(i); delay(1000); } }
[ "noreply@github.com" ]
wallace3043.noreply@github.com
aadfdc0c72a4c93cb044f8db4540856e3cd0f765
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/providers/nteventprovider/dll/ntevtprov.cpp
10a6fd17b234c4a7680758e7e1f710e907ab1b1d
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,622
cpp
//*************************************************************************** // // NTEVTPROV.CPP // // Module: WBEM NT EVENT PROVIDER // // Purpose: Contains the WBEM interface for event provider classes // // Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved // //*************************************************************************** #include "precomp.h" #include "ql.h" #include "analyser.h" BOOL ObtainedSerialAccess(CMutex* pLock) { BOOL bResult = FALSE; if (pLock != NULL) { if (pLock->Lock()) { bResult = TRUE; } } return bResult; } void ReleaseSerialAccess(CMutex* pLock) { if (pLock != NULL) { pLock->Unlock(); } } void CNTEventProvider::AllocateGlobalSIDs() { SID_IDENTIFIER_AUTHORITY t_WorldAuthoritySid = SECURITY_WORLD_SID_AUTHORITY; if (!AllocateAndInitializeSid( &t_WorldAuthoritySid, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &s_WorldSid)) { s_WorldSid = NULL; } SID_IDENTIFIER_AUTHORITY t_NTAuthoritySid = SECURITY_NT_AUTHORITY; if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 1, SECURITY_ANONYMOUS_LOGON_RID, 0, 0, 0, 0, 0, 0, 0, &s_AnonymousLogonSid)) { s_AnonymousLogonSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &s_AliasAdminsSid)) { s_AliasAdminsSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &s_LocalSystemSid )) { s_LocalSystemSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_GUESTS, 0,0,0,0,0,0, &s_AliasGuestsSid )) { s_AliasGuestsSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_SYSTEM_OPS, 0,0,0,0,0,0, &s_AliasSystemOpsSid )) { s_AliasSystemOpsSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_BACKUP_OPS, 0,0,0,0,0,0, &s_AliasBackupOpsSid )) { s_AliasBackupOpsSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 1, SECURITY_LOCAL_SERVICE_RID, 0, 0, 0, 0, 0, 0, 0, &s_LocalServiceSid )) { s_LocalServiceSid = NULL; } if (!AllocateAndInitializeSid( &t_NTAuthoritySid, 1, SECURITY_NETWORK_SERVICE_RID, 0, 0, 0, 0, 0, 0, 0, &s_NetworkServiceSid )) { s_NetworkServiceSid = NULL; } } void CNTEventProvider::FreeGlobalSIDs() { if (s_NetworkServiceSid) { FreeSid(s_NetworkServiceSid); s_NetworkServiceSid = NULL; } if (s_LocalServiceSid) { FreeSid(s_LocalServiceSid); s_LocalServiceSid = NULL; } if (s_AliasBackupOpsSid) { FreeSid(s_AliasBackupOpsSid); s_AliasBackupOpsSid = NULL; } if (s_AliasSystemOpsSid) { FreeSid(s_AliasSystemOpsSid); s_AliasSystemOpsSid = NULL; } if (s_AliasGuestsSid) { FreeSid(s_AliasGuestsSid); s_AliasGuestsSid = NULL; } if (s_LocalSystemSid) { FreeSid(s_LocalSystemSid); s_LocalSystemSid = NULL; } if (s_AliasAdminsSid) { FreeSid(s_AliasAdminsSid); s_AliasAdminsSid = NULL; } if (s_AnonymousLogonSid) { FreeSid(s_AnonymousLogonSid); s_AnonymousLogonSid = NULL; } if (s_WorldSid) { FreeSid(s_WorldSid); s_WorldSid = NULL; } } BOOL CNTEventProvider::GlobalSIDsOK() { return (s_NetworkServiceSid && s_LocalServiceSid && s_AliasBackupOpsSid && s_AliasSystemOpsSid && s_AliasGuestsSid && s_LocalSystemSid && s_AliasAdminsSid && s_AnonymousLogonSid && s_WorldSid); } STDMETHODIMP CNTEventProvider::AccessCheck ( LPCWSTR wszQueryLanguage, LPCWSTR wszQuery, LONG lSidLength, const BYTE __RPC_FAR *pSid ) { HRESULT t_Status = WBEM_E_ACCESS_DENIED; SetStructuredExceptionHandler seh; try { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::AccessCheck\r\n"); ) if (lSidLength > 0) { if (pSid != NULL) { // permanent consumer: hope core did its job return WBEM_S_SUBJECT_TO_SDS; } else { return WBEM_E_ACCESS_DENIED; } } if (FAILED(CImpNTEvtProv::GetImpersonation())) { return WBEM_E_ACCESS_DENIED; } QL_LEVEL_1_RPN_EXPRESSION* pExpr; CTextLexSource Source(wszQuery); QL1_Parser Parser(&Source); if(Parser.Parse(&pExpr) == 0) { // Analyze this QL_LEVEL_1_RPN_EXPRESSION* pNewExpr; CPropertyName MyProp; MyProp.AddElement(TARGET_PROP); MyProp.AddElement(LOGFILE_PROP); if(SUCCEEDED(CQueryAnalyser::GetNecessaryQueryForProperty(pExpr, MyProp, pNewExpr))) { CStringArray t_wsVals; HRESULT t_hres = CQueryAnalyser::GetValuesForProp(pNewExpr, MyProp, t_wsVals); if(SUCCEEDED(t_hres)) { //grant access and set false if a failure occurs... t_Status = S_OK; // awsVals contains the list of files for (int x = 0; x < t_wsVals.GetSize(); x++) { DWORD t_dwReason = 0; HANDLE t_hEvtlog = CEventLogFile::OpenLocalEventLog(t_wsVals[x], &t_dwReason); if (t_hEvtlog == NULL) { if (t_dwReason != ERROR_FILE_NOT_FOUND) { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::AccessCheck - Failed to verify logfile access\r\n"); ) t_Status = WBEM_E_ACCESS_DENIED; break; } else { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::AccessCheck - Logfile not found assuming access allowed for log\r\n"); ) } } else { CloseEventLog(t_hEvtlog); } } } else if(t_hres == WBEMESS_E_REGISTRATION_TOO_BROAD) { // user asked for all, check all logs.... HKEY hkResult = NULL; LONG t_lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, EVENTLOG_BASE, 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &hkResult); if (t_lErr == ERROR_SUCCESS) { DWORD iValue = 0; WCHAR t_logname[MAX_PATH+1]; DWORD t_lognameSize = MAX_PATH; //grant access and set false if a failure occurs... t_Status = S_OK; // read all entries under this key to find all logfiles... while ((t_lErr = RegEnumKey(hkResult, iValue, t_logname, t_lognameSize)) != ERROR_NO_MORE_ITEMS) { // if error during read if (t_lErr != ERROR_SUCCESS) { // indicate error t_Status = WBEM_E_ACCESS_DENIED; break; } //open logfile DWORD t_dwReason = 0; HANDLE t_hEvtlog = CEventLogFile::OpenLocalEventLog(t_logname, &t_dwReason); if (t_hEvtlog == NULL) { if (t_dwReason != ERROR_FILE_NOT_FOUND) { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::AccessCheck - Failed to verify logfile access\r\n"); ) t_Status = WBEM_E_ACCESS_DENIED; break; } else { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::AccessCheck - Logfile not found assuming access allowed for log\r\n"); ) } } else { CloseEventLog(t_hEvtlog); } // read next parameter iValue++; } // end while RegCloseKey(hkResult); } } t_wsVals.RemoveAll(); delete pNewExpr; } delete pExpr; } WbemCoRevertToSelf(); DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Leaving CNTEventProvider::AccessCheck\r\n"); ) } catch(Structured_Exception e_SE) { WbemCoRevertToSelf(); t_Status = WBEM_E_UNEXPECTED; } catch(Heap_Exception e_HE) { WbemCoRevertToSelf(); t_Status = WBEM_E_OUT_OF_MEMORY; } catch(...) { WbemCoRevertToSelf(); t_Status = WBEM_E_UNEXPECTED; } return t_Status; } STDMETHODIMP CNTEventProvider::Initialize ( LPWSTR pszUser, LONG lFlags, LPWSTR pszNamespace, LPWSTR pszLocale, IWbemServices *pCIMOM, // For anybody IWbemContext *pCtx, IWbemProviderInitSink *pInitSink // For init signals ) { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::Initialize\r\n"); ) HRESULT t_Status = WBEM_NO_ERROR; SetStructuredExceptionHandler seh; try { if (GlobalSIDsOK()) { m_pNamespace = pCIMOM; m_pNamespace->AddRef(); m_Mgr->SetFirstSinceLogon(pCIMOM, pCtx); pInitSink->SetStatus ( WBEM_S_INITIALIZED , 0 ); } else { pInitSink->SetStatus ( WBEM_E_UNEXPECTED , 0 ); } DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Leaving CNTEventProvider::Initialize with SUCCEEDED\r\n"); ) } catch(Structured_Exception e_SE) { t_Status = WBEM_E_UNEXPECTED; } catch(Heap_Exception e_HE) { t_Status = WBEM_E_OUT_OF_MEMORY; } catch(...) { t_Status = WBEM_E_UNEXPECTED; } return t_Status; } STDMETHODIMP CNTEventProvider::ProvideEvents(IWbemObjectSink* pSink, LONG lFlags) { HRESULT t_Status = WBEM_NO_ERROR; SetStructuredExceptionHandler seh; try { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Entering CNTEventProvider::ProvideEvents\r\n"); ) m_pEventSink = pSink; m_pEventSink->AddRef(); if (!m_Mgr->Register(this)) { DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Leaving CNTEventProvider::ProvideEvents with FAILED\r\n"); ) return WBEM_E_FAILED; } DebugOut( CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__, L"Leaving CNTEventProvider::ProvideEvents with SUCCEEDED\r\n"); ) } catch(Structured_Exception e_SE) { t_Status = WBEM_E_UNEXPECTED; } catch(Heap_Exception e_HE) { t_Status = WBEM_E_OUT_OF_MEMORY; } catch(...) { t_Status = WBEM_E_UNEXPECTED; } return t_Status; } CNTEventProvider::~CNTEventProvider() { if (m_pNamespace != NULL) { m_pNamespace->Release(); } if (m_pEventSink != NULL) { m_pEventSink->Release(); } } CNTEventProvider::CNTEventProvider(CEventProviderManager* mgr) : m_pNamespace(NULL), m_pEventSink(NULL) { m_Mgr = mgr; m_ref = 0; } IWbemServices* CNTEventProvider::GetNamespace() { m_pNamespace->AddRef(); return m_pNamespace; } IWbemObjectSink* CNTEventProvider::GetEventSink() { m_pEventSink->AddRef(); return m_pEventSink; } void CNTEventProvider::ReleaseAll() { //release dependencies m_pNamespace->Release(); m_pEventSink->Release(); Release(); } void CNTEventProvider::AddRefAll() { //addref dependencies m_pNamespace->AddRef(); m_pEventSink->AddRef(); AddRef(); } STDMETHODIMP_( ULONG ) CNTEventProvider::AddRef() { SetStructuredExceptionHandler seh; try { InterlockedIncrement(&(CNTEventProviderClassFactory::objectsInProgress)); return InterlockedIncrement ( &m_ref ) ; } catch(Structured_Exception e_SE) { return 0; } catch(Heap_Exception e_HE) { return 0; } catch(...) { return 0; } } STDMETHODIMP_(ULONG) CNTEventProvider::Release() { SetStructuredExceptionHandler seh; try { long ret; if ( 0 == (ret = InterlockedDecrement(&m_ref)) ) { delete this; } else if ( 1 == ret ) { m_Mgr->UnRegister(this); } InterlockedDecrement(&(CNTEventProviderClassFactory::objectsInProgress)); return ret; } catch(Structured_Exception e_SE) { return 0; } catch(Heap_Exception e_HE) { return 0; } catch(...) { return 0; } } STDMETHODIMP CNTEventProvider::QueryInterface(REFIID riid, PVOID* ppv) { SetStructuredExceptionHandler seh; try { *ppv = NULL; if (IID_IUnknown == riid) { *ppv=(IWbemEventProvider*)this; } else if (IID_IWbemEventProvider == riid) { *ppv=(IWbemEventProvider*)this; } else if (IID_IWbemProviderInit == riid) { *ppv= (IWbemProviderInit*)this; } else if (IID_IWbemEventProviderSecurity == riid) { *ppv= (IWbemEventProviderSecurity*)this; } if (NULL==*ppv) { return E_NOINTERFACE; } //AddRef any interface we'll return. ((LPUNKNOWN)*ppv)->AddRef(); return NOERROR; } catch(Structured_Exception e_SE) { return E_UNEXPECTED; } catch(Heap_Exception e_HE) { return E_OUTOFMEMORY; } catch(...) { return E_UNEXPECTED; } }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
0f40bf1b3e0df596c14ca17287fa9ef43491e3a5
94db0bd95a58fabfd47517ed7d7d819a542693cd
/client/ClientRes/IOSAPI/Classes/Native/AssemblyU2DCSharp_EditerType4017711417.h
88b3e8e66e62437373bbd7db4f769974b7b17005
[]
no_license
Avatarchik/card
9fc6efa058085bd25f2b8831267816aa12b24350
d18dbc9c7da5cf32c963458ac13731ecfbf252fa
refs/heads/master
2020-06-07T07:01:00.444233
2017-12-11T10:52:17
2017-12-11T10:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
916
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Enum2459695545.h" #include "AssemblyU2DCSharp_EditerType4017711417.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // EditerType struct EditerType_t4017711417 { public: // System.Int32 EditerType::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(EditerType_t4017711417, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "1" ]
1
cf9dc3b898d492358b10c4c99be35e77fa7c633d
f04bb40794f407e077cf47aab643e8536a7384ec
/Video/cutImageTest/cutImageTest.cpp
eb550a8e40a59500d8818ec7b5451458f1a0e95d
[]
no_license
elfmedy/2013
50f98ca39ff723b869631912df4b2e0c64f52c26
fdc3bac5b17871baa22b1d044afd0a5a0e1fcbdc
refs/heads/master
2020-05-19T07:49:06.318059
2014-01-03T17:58:53
2014-01-03T17:58:53
10,138,872
2
0
null
null
null
null
GB18030
C++
false
false
223
cpp
// cutImageTest.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "cutImage.h" int _tmain(int argc, _TCHAR* argv[]) { CutImage(10, 10, 100, 200, "in\\2.jpg", "out\\s2.jpg"); return 0; }
[ "flyoverthecity@gmail.com" ]
flyoverthecity@gmail.com
3fbab48a9c0ac2a3556e9203c4cabe1958c0f89d
e4a8a6ccd4430bf12ae4262132d74211cf476d5b
/main.cpp
8a82faa3f28715a6d0c63d6c82a5c96f287a548a
[]
no_license
sebadec/Ksiazka_Adresowa_Wektor_Uzytkownicy
99ad59d037e7ba78138d59fccffb9e7d88e31695
4b60bb7a777679bb330e7ff1c15923bf3a142cb2
refs/heads/main
2023-03-30T10:17:19.840127
2021-04-07T09:40:25
2021-04-07T09:40:25
345,739,228
0
0
null
null
null
null
UTF-8
C++
false
false
20,142
cpp
#include <iostream> #include <vector> #include <fstream> #include <string> #include <cstdio> #include <algorithm> using namespace std; struct Uzytkownik { int idUzytkownika; string nazwa, haslo; }; struct Adresat { int idAdresata, idUzytkownika; string imie, nazwisko, numerTelefonu, email, adres; }; void wyswietlanieWszystkichAdresatow(vector <Adresat> &adresaci); void wczytywanieAdresatowZPliku(vector <Adresat> &adresaci, int idUzytkownikaStala); void dodawanieCalejLiniiDoStruktur(vector <Adresat> &adresaci, string linia, int idUzytkownikaStala); void dodajAdresata(vector<Adresat> &adresaci, int idUzytkownikaStala); void wczytywanieAdresatowPoImieniu(vector<Adresat> &adresaci); void wczytywanieAdresatowPoNazwisku(vector<Adresat> &adresaci); void usuwanieAdresata(vector<Adresat> &adresaci, int idUzytkownikaStala); void edytowanieAdresata(vector<Adresat> &adresaci, int idUzytkownikaStala); void aktualizowanieAdresatowPrzenoszenieStrukturDoPliku(vector <Adresat> &adresaci, int idUzytkownikaStala, int idAdresataDoEdycji, int numerAdresataWStrukturze); void menu(vector <Uzytkownik> uzytkownicy, int idUzytkownikaStala); void dodajUzytkownika(vector <Uzytkownik> &uzytkownicy); void wczytywanieUzytkownikowZPliku(vector <Uzytkownik> &uzytkownicy); void dodawanieCalejLiniiDoStrukturUzytkownicy(vector <Uzytkownik> &uzytkownicy, string linia); void logowanieUzytkownika(vector <Uzytkownik> &uzytkownicy); int wyznaczanieMaxIdAdresata (); void zmianaHasla (vector <Uzytkownik> &uzytkownicy, int idUzytkownikaStala); int main() { vector <Uzytkownik> uzytkownicy; char wybor; Adresat adres; wczytywanieUzytkownikowZPliku(uzytkownicy); while (true) { system("cls"); cout << "1. Logowanie" << endl; cout << "2. Rejestracja" << endl; cout << "3. Zamknij program" << endl; cin >> wybor; if (wybor == '1') { uzytkownicy.clear(); wczytywanieUzytkownikowZPliku (uzytkownicy); logowanieUzytkownika(uzytkownicy); } else if (wybor == '2') { dodajUzytkownika(uzytkownicy); } else if (wybor == '3') { exit(0); } } return 0; } int wyznaczanieMaxIdAdresata () { int maxIdAdresataStala = 1; vector <string> IdAdresatow; string linia; fstream plik; plik.open("Adresaci.txt", ios::in); if (plik.good() == false) { maxIdAdresataStala = 0; return maxIdAdresataStala; } else { for (int i = 0; !plik.eof(); i++) { cin.sync(); getline (plik,linia); if (linia!="") { string s = linia; string delimiter = "|"; string token = s.substr(0, s.find(delimiter)); IdAdresatow.push_back(token); } } } sort(IdAdresatow.begin(),IdAdresatow.end()); maxIdAdresataStala = atoi(IdAdresatow.back().c_str()); plik.close(); return maxIdAdresataStala; } void logowanieUzytkownika(vector <Uzytkownik> &uzytkownicy) { //system("cls"); string imieUzytkownika, hasloUzytkownika; int idUzytkownikaStala, maxIdAdresataStala; cout << "Podaj login: "; cin >> imieUzytkownika; for (int i = 0; i<uzytkownicy.size(); i++) { if (imieUzytkownika == uzytkownicy[i].nazwa) { cout << "Podaj haslo: "; cin >> hasloUzytkownika; if (hasloUzytkownika == uzytkownicy[i].haslo) { cout << "Logowanie udane" << endl; idUzytkownikaStala = uzytkownicy[i].idUzytkownika; menu(uzytkownicy, idUzytkownikaStala); return; } else { cout << "Podane haslo jest nieprawidlowe." << endl; system("pause"); return; } } } cout << "Brak uzytkownika o podanym loginie." << endl; system("pause"); return; } void dodajUzytkownika(vector <Uzytkownik> &uzytkownicy) { Uzytkownik adres; if (uzytkownicy.size()==0) { adres.idUzytkownika = 1; } else { adres.idUzytkownika = uzytkownicy[uzytkownicy.size()-1].idUzytkownika+1; } cout << "Podaj login:"; cin >> adres.nazwa; cout << "Podaj haslo:"; cin >> adres.haslo; uzytkownicy.push_back(adres); fstream plik; plik.open("Uzytkownicy.txt", ios::out | ios::app); if (plik.good()) { plik << adres.idUzytkownika << "|" << adres.nazwa << "|" << adres.haslo << "|" << endl; plik.close(); cout << "Uzytkownik zostala dodany." << endl; } else { cout << "Nie mozna otworzyc pliku: Uzytkownicy.txt" << endl; } system("pause"); } void menu(vector <Uzytkownik> uzytkownicy, int idUzytkownikaStala) { vector <Adresat> adresaci; int iloscUzytkowikow = 0; char wybor; wczytywanieAdresatowZPliku(adresaci, idUzytkownikaStala); while (true) { system("cls"); cout << "1. Dodaj adresata" << endl; cout << "2. Wyszukaj po imieniu" << endl; cout << "3. Wyszukaj po nazwisku" << endl; cout << "4. Wyswietl wszystkich adresatow" << endl; cout << "5. Usun adresata" << endl; cout << "6. Edytuj adresata" << endl; cout << "7. Zmien haslo" << endl; cout << "9. Wyloguj sie" << endl; cin >> wybor; if (wybor == '1') { dodajAdresata(adresaci, idUzytkownikaStala); } else if (wybor == '2') { wczytywanieAdresatowPoImieniu(adresaci); } else if (wybor == '3') { wczytywanieAdresatowPoNazwisku(adresaci); } else if (wybor == '4') { wyswietlanieWszystkichAdresatow(adresaci); } else if (wybor == '5') { usuwanieAdresata(adresaci, idUzytkownikaStala); } else if (wybor == '6') { edytowanieAdresata(adresaci, idUzytkownikaStala); } else if (wybor == '7') { zmianaHasla (uzytkownicy, idUzytkownikaStala); } else if (wybor == '9') { break; } } } void zmianaHasla (vector <Uzytkownik> &uzytkownicy, int idUzytkownikaStala) { string noweHaslo; cout << "Podaj nowe haslo: "; cin >> noweHaslo; uzytkownicy[idUzytkownikaStala-1].haslo = noweHaslo; string linia; fstream plik; plik.open("Uzytkownicy.txt", ios::out | ios::in); fstream tymczasowyPlik; tymczasowyPlik.open("UzytkownicyKopia.txt", ios::out | ios::app); for (int i = 0; !plik.eof(); i++) { getline (plik,linia); if (linia!="") { string s = linia; string delimiter = "|"; size_t pos = 0; string token[2]; int i = 0; while ((pos = s.find(delimiter)) != string::npos) { token[i] = s.substr(0, pos); s.erase(0, pos + delimiter.length()); i++; } if (atoi(token[0].c_str()) == idUzytkownikaStala) { tymczasowyPlik << token[0] << "|" << token[1] << "|" << noweHaslo << "|" << endl; } else { tymczasowyPlik << linia << endl; } } } plik.close(); tymczasowyPlik.close(); remove("Uzytkownicy.txt"); rename("UzytkownicyKopia.txt","Uzytkownicy.txt"); cout << "Zakonczono pocerudre aktualizacji" << endl; uzytkownicy.clear(); wczytywanieUzytkownikowZPliku (uzytkownicy); system("pause"); } void wczytywanieAdresatowZPliku(vector <Adresat> &adresaci, int idUzytkownikaStala) { string linia; fstream plik; plik.open("Adresaci.txt", ios::in); if (plik.good() == false) { } else { for (int i = 0; !plik.eof(); i++) { getline (plik,linia); if (linia!="") { dodawanieCalejLiniiDoStruktur (adresaci, linia, idUzytkownikaStala); } } } system("pause"); plik.close(); } void wczytywanieUzytkownikowZPliku(vector <Uzytkownik> &uzytkownicy) { string linia; fstream plik; plik.open("Uzytkownicy.txt", ios::in); if (plik.good() == false) { } else { for (int i = 0; !plik.eof(); i++) { getline (plik,linia); if (linia!="") { dodawanieCalejLiniiDoStrukturUzytkownicy (uzytkownicy, linia); } } } plik.close(); } void dodawanieCalejLiniiDoStrukturUzytkownicy(vector <Uzytkownik> &uzytkownicy, string linia) { string s = linia; string delimiter = "|"; size_t pos = 0; string token[2]; int i = 0; while ((pos = s.find(delimiter)) != string::npos) { token[i] = s.substr(0, pos); s.erase(0, pos + delimiter.length()); i++; } Uzytkownik adres; adres.idUzytkownika = atoi(token[0].c_str()); adres.nazwa = token[1]; adres.haslo = token[2]; uzytkownicy.push_back(adres); } void usuwanieAdresata(vector<Adresat> &adresaci, int idUzytkownikaStala) { cout << "Podaj id adresata ktorego zamierzasz usunac" << endl; string idAdresataDoUsuniecia; cin >> idAdresataDoUsuniecia; cin.sync(); cout << "Potwierdzasz? Tego wybory nie da sie cofnac (t/n): " << endl; char wybor; wybor = getchar(); while (true) { if (wybor=='t') { string linia; fstream plik; plik.open("Adresaci.txt", ios::out | ios::in); fstream tymczasowyPlik; tymczasowyPlik.open("AdresaciKopia.txt", ios::out | ios::app); for (int i = 0; !plik.eof(); i++) { getline (plik,linia); if (linia!="") { string s = linia; string delimiter = "|"; string token = s.substr(0, s.find(delimiter)); if (token == idAdresataDoUsuniecia) { cout << "Adresat zostal usuniety" << endl; } else { tymczasowyPlik << linia << endl; } } } plik.close(); tymczasowyPlik.close(); remove("Adresaci.txt"); rename("AdresaciKopia.txt","Adresaci.txt"); cout << "Zakonczono pocerudre usuwania" << endl; adresaci.clear(); wczytywanieAdresatowZPliku(adresaci, idUzytkownikaStala); break; } else if (wybor=='n') { break; } else { cout << "Nieprawidlowy znak, powrot do poprzedniego menu" << endl; system("pause"); return; } } } void edytowanieAdresata(vector<Adresat> &adresaci, int idUzytkownikaStala) { cout << "Podaj id adresata ktorego zamierzasz edytowac" << endl; int idAdresataDoEdycji, numerAdresataWStrukturze; cin >> idAdresataDoEdycji; cin.sync(); string nowyParametr; cout << "Jaki parametr chcesz edytowac?" << endl; for (int i = 0; i<adresaci.size(); i++) { if (idAdresataDoEdycji == adresaci[i].idAdresata) { cout << "ID adresata: " << adresaci[i].idAdresata << endl; cout << "ID uzytkownika: " << adresaci[i].idUzytkownika << endl; cout << "1 - imie: " << adresaci[i].imie << endl; cout << "2 - nazwisko: " << adresaci[i].nazwisko << endl; cout << "3 - numer telefonu: " << adresaci[i].numerTelefonu << endl; cout << "4 - email: " << adresaci[i].email << endl; cout << "5 - adres: " << adresaci[i].adres << endl; cout << "6 - powrot do menu" << endl; cout << "-------------------------" << endl; numerAdresataWStrukturze = i; } } char wybor; wybor = getchar(); while (true) { if (wybor=='1') { cout << "Podaj nowe imie: " << endl; cin >> nowyParametr; adresaci[numerAdresataWStrukturze].imie = nowyParametr; break; } if (wybor=='2') { cout << "Podaj nowe nazwisko: " << endl; cin >> nowyParametr; adresaci[numerAdresataWStrukturze].nazwisko = nowyParametr; break; } if (wybor=='3') { cout << "Podaj nowy numer telefonu: " << endl; cin.sync(); getline(cin, adresaci[numerAdresataWStrukturze].numerTelefonu); break; } if (wybor=='4') { cout << "Podaj nowy email: " << endl; cin >> nowyParametr; adresaci[numerAdresataWStrukturze].email = nowyParametr; break; } if (wybor=='5') { cout << "Podaj nowy adres: " << endl; cin.sync(); getline(cin, adresaci[numerAdresataWStrukturze].adres); break; } if (wybor=='6') { cout << "Powrot " << endl; break; } } aktualizowanieAdresatowPrzenoszenieStrukturDoPliku(adresaci, idUzytkownikaStala, idAdresataDoEdycji, numerAdresataWStrukturze); } void aktualizowanieAdresatowPrzenoszenieStrukturDoPliku(vector <Adresat> &adresaci, int idUzytkownikaStala, int idAdresataDoEdycji, int numerAdresataWStrukturze) { string linia; fstream plik; plik.open("Adresaci.txt", ios::out | ios::in); fstream tymczasowyPlik; tymczasowyPlik.open("AdresaciKopia.txt", ios::out | ios::app); for (int i = 0; !plik.eof(); i++) { getline (plik,linia); if (linia!="") { string s = linia; string delimiter = "|"; string token = s.substr(0, s.find(delimiter)); if (atoi(token.c_str()) == idAdresataDoEdycji) { tymczasowyPlik << adresaci[numerAdresataWStrukturze].idAdresata << "|" << adresaci[numerAdresataWStrukturze].idUzytkownika << "|" << adresaci[numerAdresataWStrukturze].imie << "|" << adresaci[numerAdresataWStrukturze].nazwisko << "|" << adresaci[numerAdresataWStrukturze].numerTelefonu << "|" << adresaci[numerAdresataWStrukturze].email << "|" << adresaci[numerAdresataWStrukturze].adres << "|" << endl; } else { tymczasowyPlik << linia << endl; } } } plik.close(); tymczasowyPlik.close(); remove("Adresaci.txt"); rename("AdresaciKopia.txt","Adresaci.txt"); cout << "Zakonczono pocerudre aktualizacji" << endl; adresaci.clear(); wczytywanieAdresatowZPliku(adresaci, idUzytkownikaStala); } void dodawanieCalejLiniiDoStruktur(vector <Adresat> &adresaci, string linia, int idUzytkownikaStala) { string s = linia; string delimiter = "|"; size_t pos = 0; string token[6]; int i = 0; while ((pos = s.find(delimiter)) != string::npos) { token[i] = s.substr(0, pos); s.erase(0, pos + delimiter.length()); i++; } if ((atoi(token[1].c_str())) == idUzytkownikaStala) { Adresat adres; adres.idAdresata = atoi(token[0].c_str()); adres.idUzytkownika = atoi(token[1].c_str()); adres.imie = token[2]; adres.nazwisko = token[3]; adres.numerTelefonu = token[4]; adres.email = token[5]; adres.adres = token[6]; adresaci.push_back(adres); } } void dodajAdresata(vector<Adresat> &adresaci, int idUzytkownikaStala) { Adresat adres; adres.idUzytkownika = idUzytkownikaStala; adres.idAdresata = wyznaczanieMaxIdAdresata()+1; cout << "Podaj imie:"; cin >> adres.imie; cout << "Podaj nazwisko:"; cin >> adres.nazwisko; cout << "Podaj numer telefonu:"; cin.sync(); getline(cin, adres.numerTelefonu); cout << "Podaj e-mail:"; cin >> adres.email; cout << "Podaj adres:"; cin.sync(); getline(cin, adres.adres); adresaci.push_back(adres); fstream plik; plik.open("Adresaci.txt", ios::out | ios::app); if (plik.good()) { plik << adres.idAdresata << "|" << adres.idUzytkownika << "|" << adres.imie << "|" << adres.nazwisko << "|" << adres.numerTelefonu << "|" << adres.email << "|" << adres.adres << "|" << endl; plik.close(); cout << "Osoba zostala dodana." << endl; } else { cout << "Nie mozna otworzyc pliku: Adresaci.txt" << endl; } system("pause"); } void wczytywanieAdresatowPoImieniu(vector<Adresat> &adresaci) { system("cls"); string imieUzytkownika; cout << "Podaj imie adresata: "; cin >> imieUzytkownika; for (int i = 0; i<adresaci.size(); i++) { if (imieUzytkownika == adresaci[i].imie) { cout << "id adresata to : " << adresaci[i].idAdresata << endl; cout << "id uzytkownika to : " << adresaci[i].idUzytkownika << endl; cout << "imie adresata to : " << adresaci[i].imie << endl; cout << "nazwisko adresata to : " << adresaci[i].nazwisko << endl; cout << "numerTelefonuefon adresata to : " << adresaci[i].numerTelefonu << endl; cout << "email adresata to : " << adresaci[i].email << endl; cout << "adres adresata to : " << adresaci[i].adres << endl; cout << "-------------------------" << endl; } } system("pause"); } void wczytywanieAdresatowPoNazwisku(vector<Adresat> &adresaci) { system("cls"); string nazwiskoAdresata; cout << "Podaj nazwisko adresata: "; cin >> nazwiskoAdresata; for (int i = 0; i<adresaci.size(); i++) { if (nazwiskoAdresata == adresaci[i].nazwisko) { cout << "id adresata to : " << adresaci[i].idAdresata << endl; cout << "id uzytkownika to : " << adresaci[i].idUzytkownika << endl; cout << "imie adresata to : " << adresaci[i].imie << endl; cout << "nazwisko adresata to : " << adresaci[i].nazwisko << endl; cout << "numerTelefonuefon adresata to : " << adresaci[i].numerTelefonu << endl; cout << "email adresata to : " << adresaci[i].email << endl; cout << "adres adresata to : " << adresaci[i].adres << endl; cout << "-------------------------" << endl; } } system("pause"); } void wyswietlanieWszystkichAdresatow(vector <Adresat> &adresaci) { system("cls"); for (int i = 0; i<adresaci.size(); i++) { cout << "id adresata to : " << adresaci[i].idAdresata << endl; cout << "id uzytkownika to : " << adresaci[i].idUzytkownika << endl; cout << "imie adresata to : " << adresaci[i].imie << endl; cout << "nazwisko adresata to : " << adresaci[i].nazwisko << endl; cout << "numerTelefonuefon adresata to : " << adresaci[i].numerTelefonu << endl; cout << "email adresata to : " << adresaci[i].email << endl; cout << "adres adresata to : " << adresaci[i].adres << endl; cout << "-------------------------" << endl; } system("pause"); }
[ "noreply@github.com" ]
sebadec.noreply@github.com
d47546a32b5232a983a35ef2edf4a8bc0c020a98
978f387f5280b3f9a0c43bf9896de9376602fbf0
/全局钩子注入/keyhook/keyhook/keyhook.cpp
08c647310258ed4811149ae64c2ba5faa6140624
[]
no_license
Neilai/game-hack
313228d347592c5423d15e7fdfa088eda8e4eb81
0c42ad71fbfcb2cd89bd05e11071616dcaae727c
refs/heads/master
2020-05-23T20:59:08.039503
2019-05-16T03:29:54
2019-05-16T03:29:54
186,942,572
2
1
null
null
null
null
UTF-8
C++
false
false
88
cpp
// keyhook.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h"
[ "1131894367@qq.com" ]
1131894367@qq.com
9cb4f059ed372a0a4f3041cea31f267f1da36885
a4bb94cfe9c0bee937a6ec584e10f6fe126372ff
/Drivers/Video/Console/Console.cpp
61c3ebf8a02b2cd6a3ad948192fecf6816fce2aa
[]
no_license
MatiasNAmendola/magneto
564d0bdb3534d4b7118e74cc8b50601afaad10a0
33bc34a49a34923908883775f94eb266be5af0f9
refs/heads/master
2020-04-05T23:36:22.535156
2009-07-04T09:14:01
2009-07-04T09:14:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,172
cpp
/* * Module Name: Console * File: Silver\Console\Console.cpp * */ #include "Drivers\Video\Console\Console.h" #if !defined ( __CONSOLE_CPP_ ) #define __CONSOLE_CPP_ char Console::is_console; unsigned int Console::last_result; unsigned char * Console::vid_mem; unsigned int Console::curr_x, Console::curr_y, Console::c_maxx, Console::c_maxy, Console::textattrib, Console::fgcolor, Console::bgcolor; const char * CONSOLE_ID = "CONSOLE"; Console console; unsigned char _40x25_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x08, 0x03, 0x00, 0x02, /* CRTC */ 0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F, 0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0xA0, 0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _40x50_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x08, 0x03, 0x00, 0x02, /* CRTC */ 0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F, 0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x04, 0x60, 0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _80x25_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x00, 0x03, 0x00, 0x02, /* CRTC */ 0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F, 0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x50, 0x9C, 0x0E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00 }; unsigned char _80x50_text[] = { /* MISC */ 0x67, /* SEQ */ 0x03, 0x00, 0x03, 0x00, 0x02, /* CRTC */ 0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F, 0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x01, 0x40, 0x9C, 0x8E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _90x30_text[] = { /* MISC */ 0xE7, /* SEQ */ 0x03, 0x01, 0x03, 0x00, 0x02, /* CRTC */ 0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E, 0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x00, 0xEA, 0x0C, 0xDF, 0x2D, 0x10, 0xE8, 0x05, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char _90x60_text[] = { /* MISC */ 0xE7, /* SEQ */ 0x03, 0x01, 0x03, 0x00, 0x02, /* CRTC */ 0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E, 0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00, 0xEA, 0x0C, 0xDF, 0x2D, 0x08, 0xE8, 0x05, 0xA3, 0xFF, /* GC */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00, 0xFF, /* AC */ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x0C, 0x00, 0x0F, 0x08, 0x00, }; unsigned char g_8x8_font[2048] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0xBD, 0x99, 0x81, 0x7E, 0x7E, 0xFF, 0xDB, 0xFF, 0xC3, 0xE7, 0xFF, 0x7E, 0x6C, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x38, 0x7C, 0x38, 0xFE, 0xFE, 0x92, 0x10, 0x7C, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x7C, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0x0F, 0x07, 0x0F, 0x7D, 0xCC, 0xCC, 0xCC, 0x78, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x67, 0xE6, 0xC0, 0x99, 0x5A, 0x3C, 0xE7, 0xE7, 0x3C, 0x5A, 0x99, 0x80, 0xE0, 0xF8, 0xFE, 0xF8, 0xE0, 0x80, 0x00, 0x02, 0x0E, 0x3E, 0xFE, 0x3E, 0x0E, 0x02, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00, 0x7F, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x00, 0x3E, 0x63, 0x38, 0x6C, 0x6C, 0x38, 0x86, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, 0x18, 0xFF, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x24, 0x66, 0xFF, 0x66, 0x24, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x18, 0x7E, 0xC0, 0x7C, 0x06, 0xFC, 0x18, 0x00, 0x00, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xC6, 0x00, 0x38, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00, 0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x7C, 0xCE, 0xDE, 0xF6, 0xE6, 0xC6, 0x7C, 0x00, 0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xFC, 0x00, 0x78, 0xCC, 0x0C, 0x38, 0x60, 0xCC, 0xFC, 0x00, 0x78, 0xCC, 0x0C, 0x38, 0x0C, 0xCC, 0x78, 0x00, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x1E, 0x00, 0xFC, 0xC0, 0xF8, 0x0C, 0x0C, 0xCC, 0x78, 0x00, 0x38, 0x60, 0xC0, 0xF8, 0xCC, 0xCC, 0x78, 0x00, 0xFC, 0xCC, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x78, 0xCC, 0xCC, 0x7C, 0x0C, 0x18, 0x70, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30, 0x18, 0x30, 0x60, 0xC0, 0x60, 0x30, 0x18, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x3C, 0x66, 0x0C, 0x18, 0x18, 0x00, 0x18, 0x00, 0x7C, 0xC6, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x30, 0x78, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x66, 0x66, 0xFC, 0x00, 0x3C, 0x66, 0xC0, 0xC0, 0xC0, 0x66, 0x3C, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0xFE, 0x62, 0x68, 0x78, 0x68, 0x62, 0xFE, 0x00, 0xFE, 0x62, 0x68, 0x78, 0x68, 0x60, 0xF0, 0x00, 0x3C, 0x66, 0xC0, 0xC0, 0xCE, 0x66, 0x3A, 0x00, 0xCC, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0xCC, 0x00, 0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00, 0xE6, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0x00, 0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xD6, 0x7C, 0x0E, 0x00, 0xFC, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0xE6, 0x00, 0x7C, 0xC6, 0xE0, 0x78, 0x0E, 0xC6, 0x7C, 0x00, 0xFC, 0xB4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00, 0xC6, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0xC6, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x30, 0x78, 0x00, 0xFE, 0xC6, 0x8C, 0x18, 0x32, 0x66, 0xFE, 0x00, 0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00, 0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x02, 0x00, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0xE0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xC0, 0xCC, 0x78, 0x00, 0x1C, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0x38, 0x6C, 0x64, 0xF0, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8, 0xE0, 0x60, 0x6C, 0x76, 0x66, 0x66, 0xE6, 0x00, 0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x0C, 0x00, 0x1C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0xE0, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0xE6, 0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x00, 0xCC, 0xFE, 0xFE, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, 0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x7C, 0x60, 0xF0, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0x1E, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x7C, 0xC0, 0x70, 0x1C, 0xF8, 0x00, 0x10, 0x30, 0xFC, 0x30, 0x30, 0x34, 0x18, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8, 0x00, 0x00, 0xFC, 0x98, 0x30, 0x64, 0xFC, 0x00, 0x1C, 0x30, 0x30, 0xE0, 0x30, 0x30, 0x1C, 0x00, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00, 0xE0, 0x30, 0x30, 0x1C, 0x30, 0x30, 0xE0, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0x00, 0x7C, 0xC6, 0xC0, 0xC6, 0x7C, 0x0C, 0x06, 0x7C, 0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x1C, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0x7E, 0x81, 0x3C, 0x06, 0x3E, 0x66, 0x3B, 0x00, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0xE0, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0x30, 0x30, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0x78, 0x0C, 0x38, 0x7E, 0x81, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00, 0xCC, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0xE0, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00, 0xCC, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x7C, 0x82, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00, 0xE0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0xC6, 0x10, 0x7C, 0xC6, 0xFE, 0xC6, 0xC6, 0x00, 0x30, 0x30, 0x00, 0x78, 0xCC, 0xFC, 0xCC, 0x00, 0x1C, 0x00, 0xFC, 0x60, 0x78, 0x60, 0xFC, 0x00, 0x00, 0x00, 0x7F, 0x0C, 0x7F, 0xCC, 0x7F, 0x00, 0x3E, 0x6C, 0xCC, 0xFE, 0xCC, 0xCC, 0xCE, 0x00, 0x78, 0x84, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0xCC, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0xE0, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x78, 0x84, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0xE0, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0xCC, 0x00, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8, 0xC3, 0x18, 0x3C, 0x66, 0x66, 0x3C, 0x18, 0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x18, 0x18, 0x7E, 0xC0, 0xC0, 0x7E, 0x18, 0x18, 0x38, 0x6C, 0x64, 0xF0, 0x60, 0xE6, 0xFC, 0x00, 0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x30, 0xFC, 0x30, 0xF8, 0xCC, 0xCC, 0xFA, 0xC6, 0xCF, 0xC6, 0xC3, 0x0E, 0x1B, 0x18, 0x3C, 0x18, 0x18, 0xD8, 0x70, 0x1C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00, 0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00, 0x00, 0x1C, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x1C, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0xF8, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0x00, 0xFC, 0x00, 0xCC, 0xEC, 0xFC, 0xDC, 0xCC, 0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x18, 0x00, 0x18, 0x18, 0x30, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x0C, 0x0C, 0x00, 0x00, 0xC6, 0xCC, 0xD8, 0x36, 0x6B, 0xC2, 0x84, 0x0F, 0xC3, 0xC6, 0xCC, 0xDB, 0x37, 0x6D, 0xCF, 0x03, 0x18, 0x00, 0x18, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0xDB, 0xF6, 0xDB, 0x6F, 0xDB, 0x7E, 0xD7, 0xED, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xC8, 0xDC, 0x76, 0x00, 0x00, 0x78, 0xCC, 0xF8, 0xCC, 0xF8, 0xC0, 0xC0, 0x00, 0xFC, 0xCC, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0xFC, 0xCC, 0x60, 0x30, 0x60, 0xCC, 0xFC, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xC0, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x00, 0xFC, 0x30, 0x78, 0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x38, 0x6C, 0xC6, 0xFE, 0xC6, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x6C, 0xEE, 0x00, 0x1C, 0x30, 0x18, 0x7C, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x06, 0x0C, 0x7E, 0xDB, 0xDB, 0x7E, 0x60, 0xC0, 0x38, 0x60, 0xC0, 0xF8, 0xC0, 0x60, 0x38, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xFC, 0x00, 0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xFC, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0x70, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x3C, 0x1C, 0x58, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x70, 0x98, 0x30, 0x60, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char g_8x16_font[4096] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0x81, 0xBD, 0x99, 0x81, 0x81, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xFF, 0xDB, 0xFF, 0xFF, 0xC3, 0xE7, 0xFF, 0xFF, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0xFE, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0xE7, 0xE7, 0xE7, 0x99, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x1E, 0x0E, 0x1A, 0x32, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x63, 0x63, 0x67, 0xE7, 0xE6, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0xDB, 0x3C, 0xE7, 0x3C, 0xDB, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0E, 0x1E, 0x3E, 0xFE, 0x3E, 0x1E, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xDB, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x6C, 0xFE, 0x6C, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7C, 0x7C, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x7C, 0x7C, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7C, 0xC6, 0xC2, 0xC0, 0x7C, 0x06, 0x86, 0xC6, 0x7C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0xC6, 0x0C, 0x18, 0x30, 0x60, 0xC6, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xCE, 0xD6, 0xD6, 0xE6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x06, 0x06, 0x3C, 0x06, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xFC, 0x0E, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x60, 0xC0, 0xC0, 0xFC, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0x06, 0x06, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x06, 0x06, 0x0C, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x0C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xDE, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x66, 0x66, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xDE, 0xC6, 0xC6, 0x66, 0x3A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE6, 0x66, 0x6C, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xDE, 0x7C, 0x0C, 0x0E, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x60, 0x38, 0x0C, 0x06, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x6C, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0x86, 0x0C, 0x18, 0x30, 0x60, 0xC2, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x78, 0x6C, 0x66, 0x66, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x0C, 0x0C, 0x3C, 0x6C, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xCC, 0x78, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x6C, 0x76, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x00, 0x0E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0xE0, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEC, 0xFE, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x30, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xCC, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x0C, 0x06, 0x7C, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x38, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x60, 0x66, 0x3C, 0x0C, 0x06, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0xFE, 0x66, 0x60, 0x7C, 0x60, 0x60, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x76, 0x36, 0x7E, 0xD8, 0xD8, 0x6E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x6C, 0xCC, 0xCC, 0xFE, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x78, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0x78, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0xCC, 0xCC, 0xF8, 0xC4, 0xCC, 0xDE, 0xCC, 0xCC, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x1B, 0x18, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x60, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xC0, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x60, 0xCE, 0x93, 0x06, 0x0C, 0x1F, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xCE, 0x9A, 0x3F, 0x06, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xD8, 0xD8, 0xD8, 0xDC, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC6, 0xFC, 0xC6, 0xC6, 0xFC, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0xC6, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x18, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x6C, 0x6C, 0x6C, 0xEE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x30, 0x18, 0x0C, 0x3E, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x7E, 0xCF, 0xDB, 0xF3, 0x7E, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x30, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60, 0x30, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x6C, 0x3C, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD8, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x98, 0x30, 0x60, 0xC8, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; Console::Console() { is_console = 0; if(detect_card_type()==COLOR_CARD) vid_mem = (unsigned char*) 0xB8000; else if(detect_card_type()==MONO_CARD) vid_mem = (unsigned char*) 0xB0000; curr_x = curr_y = 0; c_maxx = 79; c_maxy = 24; last_result = 0; textattrib = WHITE; bgcolor = BLACK; fgcolor = WHITE; set_res(TEXT_90x30); clrscr(); } Console::~Console() { ; } int Console::detect_card_type() { /* check for monochrome or color VGA emulation */ if((inportb(VGA_MISC_READ) & 0x01) == 1) return COLOR_CARD; else return MONO_CARD; } void Console::update_cursor() { unsigned int position = (curr_y * (c_maxx + 1) + curr_x); outportb(0x3D4, 0x0F); outportb(0x3D5, (unsigned char)(position&0xFF)); outportb(0x3D4, 0x0E); outportb(0x3D5, (unsigned char)((position>>8)&0xFF)); } void Console::scroll_line_up(void) { memcpy(vid_mem, vid_mem + (c_maxx+1)*2, (c_maxy*(c_maxx+1)*2)); memsetb(vid_mem + (c_maxx+1) * (c_maxy)*2, NULL, (c_maxx+1)*2); } void Console::write_regs(unsigned char *regs) { unsigned i; /* write MISCELLANEOUS reg */ outportb(VGA_MISC_WRITE, *regs); regs++; outportb(VGA_INSTAT_READ, 0x00); /* write SEQUENCER regs */ for(i = 0; i < VGA_NUM_SEQ_REGS; i++) { outportb(VGA_SEQ_INDEX, i); outportb(VGA_SEQ_DATA, *regs); regs++; } /* unlock CRTC registers */ outportb(VGA_CRTC_INDEX, 0x03); outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 0x80); outportb(VGA_CRTC_INDEX, 0x11); outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~0x80); /* make sure they remain unlocked */ regs[0x03] |= 0x80; regs[0x11] &= ~0x80; /* write CRTC regs */ for(i = 0; i < VGA_NUM_CRTC_REGS; i++) { outportb(VGA_CRTC_INDEX, i); outportb(VGA_CRTC_DATA, *regs); regs++; } /* write GRAPHICS CONTROLLER regs */ for(i = 0; i < VGA_NUM_GC_REGS; i++) { outportb(VGA_GC_INDEX, i); outportb(VGA_GC_DATA, *regs); regs++; } /* write ATTRIBUTE CONTROLLER regs */ for(i = 0; i < VGA_NUM_AC_REGS; i++) { (void)inportb(VGA_INSTAT_READ); outportb(VGA_AC_INDEX, i); outportb(VGA_AC_WRITE, *regs); regs++; } /* lock 16-color palette and unblank display */ (void)inportb(VGA_INSTAT_READ); outportb(VGA_AC_INDEX, 0x20); } int Console::init() { if(is_console == 1) { last_result = CONSOLE_ALREADY_INITIALIZED; return KMSG_FALIURE; } else { is_console = 1; cout<<"\nConsole:"; cout<<"\n\tColor Emulation Detected"; cout<<"\n\tVGA+ "; cout<<c_maxx + 1<<" x "<<c_maxy + 1; cout<<"\n\tUsing WHITE on BLACK"; return KMSG_SUCCESS; } return last_result; } int Console::set_res(unsigned int mode) { switch(mode) { case TEXT_40x25: write_regs(_40x25_text); c_maxx = 39; c_maxy = 24; break; case TEXT_40x50: write_regs(_40x50_text); c_maxx = 39; c_maxy = 49; break; case TEXT_80x25: write_regs(_80x25_text); c_maxx = 79; c_maxy = 24; break; case TEXT_80x50: write_regs(_80x50_text); c_maxx = 79; c_maxy = 49; break; case TEXT_90x30: write_regs(_90x30_text); c_maxx = 89; c_maxy = 29; break; case TEXT_90x60: write_regs(_90x60_text); c_maxx = 89; c_maxy = 59; break; default: last_result = MODE_NOT_SUPPORTED; break; }; clrscr(); return last_result; } void Console::settextbackground(int col) { if(col>7); else if(col<0); else bgcolor=col; textattrib=(bgcolor*16)+fgcolor; } void Console::settextcolor(int col) { if(col > 15); else if(col < 0); else fgcolor = col; textattrib = (bgcolor*16) + fgcolor; } void Console::settextattrib(int col) { textattrib = col; } int Console::gettextcolor() { return fgcolor; } int Console::gettextbgcolor() { return bgcolor; } int Console::gettextattrib() { return textattrib; } int Console::wherex(void) { return curr_x + 1; } int Console::wherey(void) { return curr_y + 1; } int Console::getmaxx() { return c_maxx + 1; } int Console::getmaxy() { return c_maxy + 1; } void Console::gotoxy(unsigned int x, unsigned int y) { if((y < 1)&&(x < 1)); else if((y>c_maxy)&&(x>c_maxx)); else { curr_x = x - 1; curr_y = y - 1; update_cursor(); } } void Console::clrscr() { unsigned int i; for (i=0; i != (c_maxx * c_maxy); i=i+1) putch(' '); curr_x = 0; curr_y = 0; update_cursor(); } void Console::putch(const unsigned char ch) { int i; switch(ch) { case BUFFER_UNDERFLOW: break; case BUFFER_OVERFLOW: break; case '\r': case '\n': curr_x = 0; curr_y = curr_y + 1; if(curr_y > c_maxy) { curr_x = 0; curr_y = c_maxy; scroll_line_up(); } break; case '\t': for(i=0; i!=TAB; i=i+1) { putch(' '); } break; case '\b': curr_x = curr_x - 1; //Bug at pos 0,0 if(curr_x < 0) { curr_x = c_maxx; curr_y = curr_y - 1; } if(curr_y < 0) { curr_x = 0; curr_y = 0; } vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ' '; vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib; break; default: if(ch >= ' ') { vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ch; vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib; curr_x = curr_x + 1; if(curr_x > c_maxx) { putch('\n'); } } break; } update_cursor(); } int Console::writeln(const char *buf) { while(*buf != '\0') { putch(*buf); buf++; } } void Console::writeint(const unsigned int num) { unsigned _num = num; char _tnum[6]; int _i=0; while(_num!=0) { _tnum[_i]=itoa(_num%10); _num=_num/10; _i=_i+1; } _tnum[_i]='\0'; for(_i=0;_tnum[_i]!='\0';_i=_i+1); for(_i=_i-1;_i>=0;_i=_i-1) { putch(_tnum[_i]); } } void Console::writeint(const int num) { int _num = num; if(_num < 0) { _num = _num * -1; putch('-'); } char _tnum[10]; int _i=0; while(_num!=0) { _tnum[_i]=itoa(_num%10); _num=_num/10; _i=_i+1; } _tnum[_i]='\0'; for(_i=0;_tnum[_i]!='\0';_i=_i+1); for(_i=_i-1;_i>=0;_i=_i-1) { putch(_tnum[_i]); } } #endif
[ "codemaster.snake@gmail.com" ]
codemaster.snake@gmail.com
e806a2fa13a3b535b0b1363fc49aa2bf0d7de57f
16a022f0ff5c3dbe6e4e1009014e452c4af62e74
/src/qt/mintingview.cpp
9a227e8565e14d4cdc0edf4ff2b53823c3696911
[ "MIT" ]
permissive
likecoin-script/novacoin
bc51b2d34cb224463f688402a7133a221c07236a
3ee4915dfcd6f53516c9d649063c69ff1d61ca2e
refs/heads/master
2021-01-17T11:42:00.846171
2014-11-29T23:47:31
2014-11-29T23:47:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,957
cpp
#include "mintingview.h" #include "mintingfilterproxy.h" #include "transactionrecord.h" #include "mintingtablemodel.h" #include "walletmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "csvmodelwriter.h" #include <QHBoxLayout> #include <QHeaderView> #include <QVBoxLayout> #include <QTableView> #include <QScrollBar> #include <QLabel> #include <QLineEdit> #include <QComboBox> #include <QMessageBox> #include <QMenu> MintingView::MintingView(QWidget *parent) : QWidget(parent), model(0), mintingView(0) { QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(0,0,0,0); QString legendBoxStyle = "background-color: rgb(%1,%2,%3); border: 1px solid black;"; QLabel *youngColor = new QLabel(" "); youngColor->setMaximumHeight(15); youngColor->setMaximumWidth(10); youngColor->setStyleSheet(legendBoxStyle.arg(COLOR_MINT_YOUNG.red()).arg(COLOR_MINT_YOUNG.green()).arg(COLOR_MINT_YOUNG.blue())); QLabel *youngLegend = new QLabel(tr("transaction is too young")); youngLegend->setContentsMargins(5,0,15,0); QLabel *matureColor = new QLabel(" "); matureColor->setMaximumHeight(15); matureColor->setMaximumWidth(10); matureColor->setStyleSheet(legendBoxStyle.arg(COLOR_MINT_MATURE.red()).arg(COLOR_MINT_MATURE.green()).arg(COLOR_MINT_MATURE.blue())); QLabel *matureLegend = new QLabel(tr("transaction is mature")); matureLegend->setContentsMargins(5,0,15,0); QLabel *oldColor = new QLabel(" "); oldColor->setMaximumHeight(15); oldColor->setMaximumWidth(10); oldColor->setStyleSheet(legendBoxStyle.arg(COLOR_MINT_OLD.red()).arg(COLOR_MINT_OLD.green()).arg(COLOR_MINT_OLD.blue())); QLabel *oldLegend = new QLabel(tr("transaction has reached maximum probability")); oldLegend->setContentsMargins(5,0,15,0); QHBoxLayout *legendLayout = new QHBoxLayout(); legendLayout->setContentsMargins(10,10,0,0); legendLayout->addWidget(youngColor); legendLayout->addWidget(youngLegend); legendLayout->addWidget(matureColor); legendLayout->addWidget(matureLegend); legendLayout->addWidget(oldColor); legendLayout->addWidget(oldLegend); legendLayout->insertStretch(-1); QLabel *mintingLabel = new QLabel(tr("Display minting probability within : ")); mintingCombo = new QComboBox(); mintingCombo->addItem(tr("10 min"), Minting10min); mintingCombo->addItem(tr("24 hours"), Minting1day); mintingCombo->addItem(tr("7 days"), Minting7days); mintingCombo->addItem(tr("30 days"), Minting30days); mintingCombo->addItem(tr("60 days"), Minting60days); mintingCombo->addItem(tr("90 days"), Minting90days); mintingCombo->setFixedWidth(120); hlayout->insertStretch(0); hlayout->addWidget(mintingLabel); hlayout->addWidget(mintingCombo); QVBoxLayout *vlayout = new QVBoxLayout(this); vlayout->setContentsMargins(0,0,0,0); vlayout->setSpacing(0); QTableView *view = new QTableView(this); vlayout->addLayout(hlayout); vlayout->addWidget(view); vlayout->addLayout(legendLayout); vlayout->setSpacing(0); int width = view->verticalScrollBar()->sizeHint().width(); // Cover scroll bar width with spacing #ifdef Q_WS_MAC hlayout->addSpacing(width+2); #else hlayout->addSpacing(width); #endif // Always show scroll bar view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); view->setTabKeyNavigation(false); view->setContextMenuPolicy(Qt::CustomContextMenu); mintingView = view; connect(mintingCombo, SIGNAL(activated(int)), this, SLOT(chooseMintingInterval(int))); // Actions QAction *copyTxIDAction = new QAction(tr("Copy transaction ID of input"), this); QAction *copyAddressAction = new QAction(tr("Copy address of input"), this); QAction *showHideAddressAction = new QAction(tr("Show/hide 'Address' column"), this); QAction *showHideTxIDAction = new QAction(tr("Show/hide 'Transaction' column"), this); contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyTxIDAction); contextMenu->addAction(showHideAddressAction); contextMenu->addAction(showHideTxIDAction); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID())); connect(showHideAddressAction, SIGNAL(triggered()), this, SLOT(showHideAddress())); connect(showHideTxIDAction, SIGNAL(triggered()), this, SLOT(showHideTxID())); connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); } void MintingView::setModel(WalletModel *model) { this->model = model; if(model) { mintingProxyModel = new MintingFilterProxy(this); mintingProxyModel->setSourceModel(model->getMintingTableModel()); mintingProxyModel->setDynamicSortFilter(true); mintingProxyModel->setSortRole(Qt::EditRole); mintingView->setModel(mintingProxyModel); mintingView->setAlternatingRowColors(true); mintingView->setSelectionBehavior(QAbstractItemView::SelectRows); mintingView->setSelectionMode(QAbstractItemView::ExtendedSelection); mintingView->setSortingEnabled(true); mintingView->sortByColumn(MintingTableModel::CoinDay, Qt::DescendingOrder); mintingView->verticalHeader()->hide(); mintingView->horizontalHeader()->resizeSection( MintingTableModel::Age, 60); mintingView->horizontalHeader()->resizeSection( MintingTableModel::Balance, 80); mintingView->horizontalHeader()->resizeSection( MintingTableModel::CoinDay,60); mintingView->horizontalHeader()->resizeSection( MintingTableModel::MintProbability, 105); #if QT_VERSION < 0x050000 mintingView->horizontalHeader()->setResizeMode( MintingTableModel::MintReward, QHeaderView::Stretch); #else mintingView->horizontalHeader()->setSectionResizeMode( MintingTableModel::MintReward, QHeaderView::Stretch); #endif mintingView->horizontalHeader()->resizeSection( MintingTableModel::Address, 245); mintingView->horizontalHeader()->resizeSection( MintingTableModel::TxHash, 75); } } void MintingView::chooseMintingInterval(int idx) { int interval = 10; switch(mintingCombo->itemData(idx).toInt()) { case Minting10min: interval = 10; break; case Minting1day: interval = 60*24; break; case Minting7days: interval = 60*24*7; break; case Minting30days: interval = 60*24*30; break; case Minting60days: interval = 60*24*60; break; case Minting90days: interval = 60*24*90; break; } model->getMintingTableModel()->setMintingInterval(interval); mintingProxyModel->invalidate(); } void MintingView::exportClicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Minting Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(mintingProxyModel); writer.addColumn(tr("Address"),MintingTableModel::Address,0); writer.addColumn(tr("Transaction"),MintingTableModel::TxHash,0); writer.addColumn(tr("Age"), MintingTableModel::Age,0); writer.addColumn(tr("CoinDay"), MintingTableModel::CoinDay,0); writer.addColumn(tr("Balance"), MintingTableModel::Balance,0); writer.addColumn(tr("MintingProbability"), MintingTableModel::MintProbability,0); writer.addColumn(tr("MintingReward"), MintingTableModel::MintReward,0); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void MintingView::copyTxID() { GUIUtil::copyEntryData(mintingView, MintingTableModel::TxHash, 0); } void MintingView::copyAddress() { GUIUtil::copyEntryData(mintingView, MintingTableModel::Address, 0 ); } void MintingView::showHideAddress() { mintingView->horizontalHeader()->setSectionHidden(MintingTableModel::Address, !(mintingView->horizontalHeader()->isSectionHidden(MintingTableModel::Address))); } void MintingView::showHideTxID() { mintingView->horizontalHeader()->setSectionHidden(MintingTableModel::TxHash, !(mintingView->horizontalHeader()->isSectionHidden(MintingTableModel::TxHash))); } void MintingView::contextualMenu(const QPoint &point) { QModelIndex index = mintingView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } }
[ "fsb4000@yandex.ru" ]
fsb4000@yandex.ru
70b15375465e21643b7f68523bef55b45f1c4833
334c5c96b7ab8085b086d6403b75153e83371a05
/Leetcode/128. Longest Consecutive Sequence/LongestConsecutiveSequence.cpp
3077fd4e878cb8649c296256764b415334ba41d3
[]
no_license
fenix0111/Algorithm
d536c901df4843e80376c4ad4ca1a520fb77acb6
9ed08d536ec84695b28152abaaaea2c6a55ae01f
refs/heads/master
2023-07-23T08:14:41.173782
2023-07-08T13:44:26
2023-07-08T13:44:26
102,463,797
0
0
null
null
null
null
UTF-8
C++
false
false
1,075
cpp
// Leetcode 128. Longest Consecutive Sequence // https://leetcode.com/problems/longest-consecutive-sequence/description/ // Runtime: 4ms // the time complexity of this solution is O(NlogN) because of sorting class Solution { public: int longestConsecutive(vector<int>& nums) { int ret = 0; if (nums.size() == 0) return 0; vector<int> v(nums); sort(v.begin(), v.end()); int tmp = 0; for (int i = 0; i < v.size() - 1; i++) { // in case of negative number if (abs(v[i + 1] - v[i]) == 1) { tmp++; } else if (v[i + 1] - v[i] == 0) { continue; } else { if (tmp > ret) { ret = tmp; } tmp = 0; } } // do not forget this final comparison if (tmp > ret) ret = tmp; return ret + 1; } };
[ "noreply@github.com" ]
fenix0111.noreply@github.com
1f7b72cab0a0bb8e47da77df247bdc6b6b59a3fa
abdb28b3a907236ee75cdd8a8a49c4a8280c3c33
/FinalProject/StockAccount.cpp
239278fe72bd6dabc02f8dd53cc582bfa514b14f
[]
no_license
Aaron723/503Assignments-new-
81d92db8dacf289d25ce7e8ee904e502a07cf8ae
1788626c0d8d49d8e6ee47ed78f33f5f213081d1
refs/heads/master
2020-04-01T01:54:29.191928
2018-12-17T22:41:48
2018-12-17T22:41:48
152,757,388
0
0
null
null
null
null
UTF-8
C++
false
false
9,034
cpp
// // Created by Zi Wan on 12/9/18. // #include "StockAccount.h" void StockAccount::setCASH_BALANCE(double stockBalance) { CASH_BALANCE=stockBalance; } StockAccount::StockAccount(){ readPortfolio();//every time construct stock account, we need portfolio information } StockAccount::~StockAccount() {} void StockAccount::buyStock(string stockName, int shares, double amount) { if(shares<0) { cout<<"Error: The shares number you want to buy can't be negative"<<endl; return; } else if(shares==0) { cout<<"Error: You didn't buy anything"<<endl; return; } iofile iofile1; char*fileName=iofile1.selectFile(); if(iofile1.SearchName(fileName,stockName)!="") { double price=atof((iofile1.SearchName(fileName,stockName)).c_str()); timeCall timeCall1; string time; string date; if(price*shares<=CASH_BALANCE&&amount>=price) { CASH_BALANCE-=price*shares; iofile iofile2; char *a=CASHBALANCE; iofile2.writeTofile(a,CASH_BALANCE); if(stockList->changeStockShares(stockName,shares,price, true))//true means buy, false means sell { iofile iofile3; iofile3.writeToPortfolio(stockList);//every time buy stock, write it in portfolio, bankhistory and transaction history time=timeCall1.getTime(); date=timeCall1.getDate(); iofile1.writeToBankHistory(date,CASH_BALANCE,price*shares,3); iofile1.writeToTransactionHistory(stockName,time,price,shares,true); //should I sort with random value red from results? Or just use the old value? } else { Node *newNode=new Node(stockName,price,shares);//add new stock to the end if this stock is not in the portfolio stockList->addToEnd(newNode); iofile iofile3; iofile3.writeToPortfolio(stockList); time=timeCall1.getTime(); date=timeCall1.getDate(); iofile1.writeToBankHistory(date,CASH_BALANCE,price*shares,3); iofile1.writeToTransactionHistory(stockName,time,price,shares,true); } //true means buy, false means sell } else if(price*shares>CASH_BALANCE) { cout<<"Your cash balance is not enough! Fail to buy!"<<endl; } else if(price>amount) { cout<<"The current price is more expensive than you want!Fail to buy!"<<endl; } } else { cout<<"This stock is not in the results!"<<endl; } } void StockAccount::sellStock(string stockName, int shares, double amount) {// similar to what we do in buy, but remove stock if share==0 if(shares<0) { cout<<"Error: The shares number you want to sell can't be negative"<<endl; return; } else if(shares==0) { cout<<"You didn't sell anything"<<endl; return; } iofile iofile1; char*fileName=iofile1.selectFile(); if(iofile1.SearchName(fileName,stockName)!="") { double price=atof((iofile1.SearchName(fileName,stockName)).c_str()); if(price<amount) cout<<"current price is lower than your expect price! Fail to sell!"<<endl; else if(stockList->changeStockShares(stockName,shares,price,false)) { char *a=CASHBALANCE; CASH_BALANCE+=shares*price; iofile1.writeTofile(a,CASH_BALANCE); cout<<"Sucessfully sell the stock!"<<endl; timeCall timeCall1; string time=timeCall1.getTime(); string date=timeCall1.getDate(); iofile1.writeToBankHistory(date,CASH_BALANCE,price*shares,4); iofile1.writeToTransactionHistory(stockName,time,price,shares,false); iofile iofile2; iofile2.writeToPortfolio(stockList); } } else { cout<<"This stock is not in the results! Fail to sell!"<<endl; } } //read stock from stocklist, update each stock's price and sort stock list, then print portfolio. void StockAccount::printPortfolio() { iofile iofile1; double sum=0; if(stockList->getMySize()!=0) { Node* currentNode=stockList->getMyHead(); while (currentNode!=stockList->getMyTail()) { string name=currentNode->getStockName(); if(name=="") break; double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str()); currentNode->setStockPrice(price); sum+=price*currentNode->getShares(); currentNode=currentNode->getNext(); } if(currentNode==stockList->getMyTail()) { string name=currentNode->getStockName(); double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str()); currentNode->setStockPrice(price); sum+=price*currentNode->getShares(); } Sorter sorter; cout<<"Please choose if you want to print in decent order or ascend order(1 means decent, 2 means asecnd)\n"; int i; cin>>i; if(i<1||i>2) { cout<<"Wrong sort choice, please enter again"<<endl; cin>>i; } else if(i==2) sorter.Sort(stockList,make_shared<ascendSortStrategy>()); else if(i==1) sorter.Sort(stockList,make_shared<decentSortStrategy>()); string cashbal=iofile1.readCashBalance(); cout<<setiosflags(ios::fixed)<<setprecision(2); cout << "Cash Balance = $" << cashbal << endl; cout << std::left << setw(20) << "Company Symbol" << std::left << setw(10) << "Number" << std::left << setw(10) << "Price" << std::left << setw(15) << "Total value" << "\n"; stockList->printList(); cout<<"Total portfolio = $"<<CASH_BALANCE+sum<<endl; } else { cout<<"There is no stock in the portfolio"<<endl; cout<<setiosflags(ios::fixed)<<setprecision(2); string cashbal=iofile1.readCashBalance(); cout << "Cash Balance = $" << cashbal << endl; cout<<"Total portfolio = $"<<CASH_BALANCE+sum<<endl; } } void StockAccount::printTransactionHistory() { char line[100]; ifstream file; char*a=TRANACTIONHISTORY; file.open(a); if(file.is_open()) { while (!file.eof()) { file.getline(line, 100); string str=line; cout << str << endl; } file.close(); } else { file.close(); // cout<<"Error: fail to open transactionHistory.txt"<<endl; } } void StockAccount::readPortfolio() { char*a=PORTFOLIO; ifstream file(a); if(!file.is_open()) { // cout<<"There is no stock in your portfolio."<<endl; } else { double totalValue=0; while(!file.eof()) { char line[100]; file.getline(line,100); string str=line; stringstream ss(str); string name; getline(ss,name,'\t'); string shares; getline(ss,shares,'\t'); if(name=="") return; iofile iofile1; double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str()); int int_shares=atoi(shares.c_str()); Node* newNode=new Node(name,price,int_shares); stockList->addToEnd(newNode); totalValue+=price*int_shares; } totalPortfolio=totalValue+CASH_BALANCE; Sorter sorter; sorter.Sort(stockList,make_shared<decentSortStrategy>()); } } void StockAccount::updatePortfolio() { iofile iofile1; double sum=0; if(stockList->getMySize()!=0) { Node* currentNode=stockList->getMyHead(); while (currentNode!=stockList->getMyTail()) { string name=currentNode->getStockName(); if(name=="") break; double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str()); currentNode->setStockPrice(price); sum+=price*currentNode->getShares(); currentNode=currentNode->getNext(); } if(currentNode==stockList->getMyTail()) { string name=currentNode->getStockName(); double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str()); currentNode->setStockPrice(price); sum+=price*currentNode->getShares(); } } sum+=CASH_BALANCE; timeCall timeCall1; string time=timeCall1.getTime(); string date=timeCall1.getDate(); iofile1.writeTototalValue(sum,time,date); }
[ "w745207699@gmail.com" ]
w745207699@gmail.com
a0e7e627330bec274fb795baa3a91f4fafa07f3b
1a60c841c4cf4159d9badacbe3e3c05dd4340d73
/week_2/2292_tjdwn9410.cpp
5e059555ae54c2c8aefb2a330725e5baf1bb8a8c
[]
no_license
sungjunyoung/algorithm-study
e5d38f0569ec7b639ebd905f0ef79398862696d2
5fb4bc9fa9f96a0d17a097ed641de01f378ead27
refs/heads/master
2020-12-03T03:46:05.244078
2017-10-14T08:01:25
2017-10-14T08:04:59
95,769,994
9
12
null
2017-10-14T08:05:00
2017-06-29T11:16:04
C++
UTF-8
C++
false
false
299
cpp
// // Created by MAC on 2017. 7. 3.. // #include<iostream> using std::cout; using std::endl; using std::cin; int main() { int N; int startValue=1; int res=1; cin>>N; while(N>startValue) { startValue += res*6; res++; } cout<<res<<endl; return 0; }
[ "abc3176@nate.com" ]
abc3176@nate.com
d274282d4c07683cddc7ebd32f133de1f7deab01
d2219fea4d37b8e608e52b9b9a7518d6b213bbbd
/Database/Strategy.cpp
dae67a30aecd0ea78ce764dd75306c4d357ee2e2
[ "BSD-3-Clause" ]
permissive
qijiezhao/gStore
a42403cd4a4f3f18489a466697f52b0e71833ee4
e33617ab9b096be4fecdd41710bde46a643c0a7a
refs/heads/master
2021-01-11T08:15:31.247834
2016-09-18T12:23:50
2016-09-18T12:23:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,218
cpp
/*============================================================================= # Filename: Strategy.cpp # Author: Bookug Lobert # Mail: zengli-bookug@pku.edu.cn # Last Modified: 2016-05-07 16:31 # Description: implement functions in Strategy.h =============================================================================*/ #include "Strategy.h" using namespace std; Strategy::Strategy() { this->method = 0; this->kvstore = NULL; this->vstree = NULL; //this->prepare_handler(); } Strategy::Strategy(KVstore* _kvstore, VSTree* _vstree) { this->method = 0; this->kvstore = _kvstore; this->vstree = _vstree; //this->prepare_handler(); } Strategy::~Strategy() { //delete[] this->dispatch; } //void //Strategy::prepare_handler() //{ //this->dispatch = new QueryHandler[Strategy::QUERY_HANDLER_NUM]; //this->dispatch[0] = Strategy::handler0; //} //NOTICE: 2-triple case ?s1 p1 c0 ?s2 p2 c0 is viewed as an unconnected graph //however, this can be dealed due to several basicquery and linking bool Strategy::handle(SPARQLquery& _query) { #ifdef MULTI_INDEX Util::logging("IN GeneralEvaluation::handle"); vector<BasicQuery*>& queryList = _query.getBasicQueryVec(); // enumerate each BasicQuery and retrieve their variables' mapping entity in the VSTree. vector<BasicQuery*>::iterator iter = queryList.begin(); for (; iter != queryList.end(); iter++) { this->method = 0; vector<int*>& result_list = (*iter)->getResultList(); //int select_var_num = (*iter)->getSelectVarNum(); int varNum = (*iter)->getVarNum(); //the num of vars needing to be joined int total_num = (*iter)->getTotalVarNum(); int pre_varNum = (*iter)->getPreVarNum(); if ((*iter)->getTripleNum() == 1 && pre_varNum == 1) { Triple triple = (*iter)->getTriple(0); int* id_list = NULL; int id_list_len = 0; result_list.clear(); if (total_num == 2) { //TODO:consider special case, select ?s (?p) ?o where { ?s ?p ?o . } //filter and join is too costly, should enum all predicates and use p2so //maybe the selected vars are ?s (?p) or ?o (?p) cerr << "not supported now!" << endl; } else if (total_num == 1) { //TODO:if just select s/o, use o2s/s2o //if only p is selected, use s2p or o2p //only if both s/o and p are selected, use s2po or o2ps if (triple.subject[0] != '?') //constant { int sid = (this->kvstore)->getIDByEntity(triple.subject); this->kvstore->getpreIDobjIDlistBysubID(sid, id_list, id_list_len); } else if (triple.object[0] != '?') //constant { int oid = (this->kvstore)->getIDByEntity(triple.object); if (oid == -1) { oid = (this->kvstore)->getIDByLiteral(triple.object); } this->kvstore->getpreIDsubIDlistByobjID(oid, id_list, id_list_len); } //always place s/o before p in result list for (int i = 0; i < id_list_len; i += 2) { int* record = new int[2]; //2 vars selected record[1] = id_list[i]; //for the pre var record[0] = id_list[i + 1]; //for the s/o var result_list.push_back(record); } } else if (total_num == 0) //only ?p { //just use so2p int sid = (this->kvstore)->getIDByEntity(triple.subject); int oid = (this->kvstore)->getIDByEntity(triple.object); if (oid == -1) { oid = (this->kvstore)->getIDByLiteral(triple.object); } this->kvstore->getpreIDlistBysubIDobjID(sid, oid, id_list, id_list_len); //copy to result list for (int i = 0; i < id_list_len; ++i) { int* record = new int[1]; record[0] = id_list[i]; result_list.push_back(record); } } delete[] id_list; continue; } if (pre_varNum == 0 && (*iter)->getTripleNum() == 1) //only one triple and no predicates { //only one variable and one triple: ?s pre obj or sub pre ?o if (total_num == 1) { this->method = 1; } //only two vars: ?s pre ?o else if (total_num == 2) { if (varNum == 1) //the selected id should be 0 { this->method = 2; } else //==2 { this->method = 3; } } //cerr << "this BasicQuery use query strategy 2" << endl; //cerr<<"Final result size: "<<(*iter)->getResultList().size()<<endl; //continue; } //QueryHandler dispatch; //dispatch[0] = handler0; switch (this->method) { case 0: this->handler0(*iter, result_list); break; case 1: this->handler1(*iter, result_list); break; case 2: this->handler2(*iter, result_list); break; case 3: this->handler3(*iter, result_list); break; default: cerr << "not support this method" << endl; } cerr << "Final result size: " << (*iter)->getResultList().size() << endl; //BETTER: use function pointer array in C++ class } #else cerr << "this BasicQuery use original query strategy" << endl; long tv_handle = Util::get_cur_time(); (this->vstree)->retrieve(_query); long tv_retrieve = Util::get_cur_time(); cout << "after Retrieve, used " << (tv_retrieve - tv_handle) << "ms." << endl; this->join = new Join(kvstore); this->join->join_sparql(_query); delete this->join; long tv_join = Util::get_cur_time(); cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl; #endif Util::logging("OUT Strategy::handle"); return true; } bool Strategy::handle(SPARQLquery& _query, int myRank, string &internal_tag_str) { #ifdef MULTI_INDEX Util::logging("IN GeneralEvaluation::handle"); vector<BasicQuery*>& queryList = _query.getBasicQueryVec(); // enumerate each BasicQuery and retrieve their variables' mapping entity in the VSTree. vector<BasicQuery*>::iterator iter=queryList.begin(); for(; iter != queryList.end(); iter++) { this->method = 0; vector<int*>& result_list = (*iter)->getResultList(); int select_var_num = (*iter)->getSelectVarNum(); int varNum = (*iter)->getVarNum(); //the num of vars needing to be joined int total_num = (*iter)->getTotalVarNum(); int pre_varNum = (*iter)->getPreVarNum(); if((*iter)->getTripleNum() == 1 && pre_varNum == 1) { Triple triple = (*iter)->getTriple(0); int* id_list = NULL; int id_list_len = 0; result_list.clear(); if(total_num == 2) { //TODO:consider special case, select ?s (?p) ?o where { ?s ?p ?o . } //filter and join is too costly, should enum all predicates and use p2so //maybe the selected vars are ?s (?p) or ?o (?p) cerr << "not supported now!" << endl; } else if(total_num == 1) { //TODO:if just select s/o, use o2s/s2o //if only p is selected, use s2p or o2p //only if both s/o and p are selected, use s2po or o2ps if(triple.subject[0] != '?') //constant { int sid = (this->kvstore)->getIDByEntity(triple.subject); this->kvstore->getpreIDobjIDlistBysubID(sid, id_list, id_list_len); } else if(triple.object[0] != '?') //constant { int oid = (this->kvstore)->getIDByEntity(triple.object); if(oid == -1) { oid = (this->kvstore)->getIDByLiteral(triple.object); } this->kvstore->getpreIDsubIDlistByobjID(oid, id_list, id_list_len); } //always place s/o before p in result list for(int i = 0; i < id_list_len; i += 2) { int* record = new int[2]; //2 vars selected record[1] = id_list[i]; //for the pre var record[0] = id_list[i+1]; //for the s/o var result_list.push_back(record); } } else if(total_num == 0) //only ?p { //just use so2p int sid = (this->kvstore)->getIDByEntity(triple.subject); int oid = (this->kvstore)->getIDByEntity(triple.object); if(oid == -1) { oid = (this->kvstore)->getIDByLiteral(triple.object); } this->kvstore->getpreIDlistBysubIDobjID(sid, oid, id_list, id_list_len); //copy to result list for(int i = 0; i < id_list_len; ++i) { int* record = new int[1]; record[0] = id_list[i]; result_list.push_back(record); } } delete[] id_list; continue; } if(pre_varNum == 0 && (*iter)->getTripleNum() == 1) //only one triple and no predicates { //only one variable and one triple: ?s pre obj or sub pre ?o if(total_num == 1) { this->method = 1; } //only two vars: ?s pre ?o else if(total_num == 2) { if(varNum == 1) //the selected id should be 0 { this->method = 2; } else //==2 { this->method = 3; } } //cerr << "this BasicQuery use query strategy 2" << endl; //cerr<<"Final result size: "<<(*iter)->getResultList().size()<<endl; //continue; } //QueryHandler dispatch; //dispatch[0] = handler0; switch(this->method) { case 0: this->handler0_0(*iter, result_list, internal_tag_str); break; case 1: this->handler1(*iter, result_list); break; case 2: this->handler2(*iter, result_list); break; case 3: this->handler3(*iter, result_list); break; default: cerr << "not support this method" << endl; } //cerr<<"Final result size: "<<(*iter)->getResultList().size()<<endl; //BETTER: use function pointer array in C++ class } #else cerr << "this BasicQuery use original query strategy" << endl; long tv_handle = Util::get_cur_time(); (this->vstree)->retrieve(_query); long tv_retrieve = Util::get_cur_time(); cout << "after Retrieve, used " << (tv_retrieve - tv_handle) << "ms." << endl; this->join = new Join(kvstore); this->join->join_sparql(_query); delete this->join; long tv_join = Util::get_cur_time(); cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl; #endif Util::logging("OUT Strategy::handle"); return true; } void Strategy::handler0_0(BasicQuery* _bq, vector<int*>& _result_list, string &internal_tag_str) { int star_flag = 0; if(star_flag == 0){ _bq->setRetrievalTag(); } long before_filter = Util::get_cur_time(); long tv_handle = Util::get_cur_time(); int varNum = _bq->getVarNum(); //the num of vars needing to be joined for(int i = 0; i < varNum; ++i) { if(_bq->if_need_retrieve(i) == false) continue; bool flag = _bq->isLiteralVariable(i); const EntityBitSet& entityBitSet = _bq->getVarBitSet(i); IDList* idListPtr = &( _bq->getCandidateList(i) ); this->vstree->retrieveEntity(entityBitSet, idListPtr); if(!flag) { _bq->setReady(i); } //the basic query should end if one non-literal var has no candidates if(idListPtr->size() == 0 && !flag) { //break; } } long tv_retrieve = Util::get_cur_time(); //printf("join_pe !!!! \n"); Join *join = new Join(kvstore); if(star_flag == 1){ join->join_basic(_bq); }else{ join->join_pe(_bq, internal_tag_str); } delete join; long tv_join = Util::get_cur_time(); //cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl; } void Strategy::handler0(BasicQuery* _bq, vector<int*>& _result_list) { //long before_filter = Util::get_cur_time(); cerr << "this BasicQuery use query strategy 0" << endl; //BETTER:not all vars in join filtered by vstree //(A)-B-c: B should by vstree, then by c, but A should be generated in join(first set A as not) //if A not in join, just filter B by pre //divided into star graphs, join core vertices, generate satellites //join should also start from a core vertex(neighbor can be constants or vars) if available // //QUERY: is there any case that a node should be retrieved by other index?(instead of vstree or generate whne join) // //we had better treat 1-triple case(no ?p) as special, and then in other cases, core vertex exist(if connected) //However, if containing ?p and 1-triple, we should treat it also as a special case, or select a variable as core vertex //and retrieved (for example, ?s ?p o or s ?p ?o, generally no core vertex in these cases) long tv_handle = Util::get_cur_time(); int varNum = _bq->getVarNum(); //the num of vars needing to be joined for (int i = 0; i < varNum; ++i) { if (_bq->if_need_retrieve(i) == false) continue; bool flag = _bq->isLiteralVariable(i); const EntityBitSet& entityBitSet = _bq->getVarBitSet(i); IDList* idListPtr = &(_bq->getCandidateList(i)); this->vstree->retrieveEntity(entityBitSet, idListPtr); if (!flag) { _bq->setReady(i); } //the basic query should end if one non-literal var has no candidates if (idListPtr->size() == 0 && !flag) { break; } } //if(_bq->isReady(0)) //cout<<"error: var 0 is ready?"<<endl; //TODO:end directly if one is empty! long tv_retrieve = Util::get_cur_time(); cout << "after Retrieve, used " << (tv_retrieve - tv_handle) << "ms." << endl; Join *join = new Join(kvstore); join->join_basic(_bq); delete join; long tv_join = Util::get_cur_time(); cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl; } void Strategy::handler1(BasicQuery* _bq, vector<int*>& _result_list) { long before_filter = Util::get_cur_time(); cerr << "this BasicQuery use query strategy 1" << endl; //int neighbor_id = (*_bq->getEdgeNeighborID(0, 0); //constant, -1 char edge_type = _bq->getEdgeType(0, 0); int triple_id = _bq->getEdgeID(0, 0); Triple triple = _bq->getTriple(triple_id); int pre_id = _bq->getEdgePreID(0, 0); int* id_list = NULL; int id_list_len = 0; if (edge_type == Util::EDGE_OUT) { //cerr<<"edge out!!!"<<endl; int nid = (this->kvstore)->getIDByEntity(triple.object); if (nid == -1) { nid = (this->kvstore)->getIDByLiteral(triple.object); } this->kvstore->getsubIDlistByobjIDpreID(nid, pre_id, id_list, id_list_len); } else { //cerr<<"edge in!!!"<<endl; this->kvstore->getobjIDlistBysubIDpreID(this->kvstore->getIDByEntity(triple.subject), pre_id, id_list, id_list_len); } long after_filter = Util::get_cur_time(); cerr << "after filter, used " << (after_filter - before_filter) << "ms" << endl; _result_list.clear(); //cerr<<"now to copy result to list"<<endl; for (int i = 0; i < id_list_len; ++i) { int* record = new int[1]; //only this var is selected record[0] = id_list[i]; //cerr<<this->kvstore->getEntityByID(record[0])<<endl; _result_list.push_back(record); } long after_copy = Util::get_cur_time(); cerr << "after copy to result list: used " << (after_copy - after_filter) << " ms" << endl; delete[] id_list; cerr << "Final result size: " << _result_list.size() << endl; } void Strategy::handler2(BasicQuery* _bq, vector<int*>& _result_list) { long before_filter = Util::get_cur_time(); cerr << "this BasicQuery use query strategy 2" << endl; int triple_id = _bq->getEdgeID(0, 0); Triple triple = _bq->getTriple(triple_id); int pre_id = _bq->getEdgePreID(0, 0); int var1_id = _bq->getIDByVarName(triple.subject); int var2_id = _bq->getIDByVarName(triple.object); int* id_list = NULL; int id_list_len = 0; if (var1_id == 0) //subject var selected { //use p2s directly this->kvstore->getsubIDlistBypreID(pre_id, id_list, id_list_len); } else if (var2_id == 0) //object var selected { //use p2o directly this->kvstore->getobjIDlistBypreID(pre_id, id_list, id_list_len); } else { cerr << "ERROR in Database::handle(): no selected var!" << endl; } long after_filter = Util::get_cur_time(); cerr << "after filter, used " << (after_filter - before_filter) << "ms" << endl; _result_list.clear(); for (int i = 0; i < id_list_len; ++i) { int* record = new int[1]; //only one var record[0] = id_list[i]; _result_list.push_back(record); } long after_copy = Util::get_cur_time(); cerr << "after copy to result list: used " << (after_copy - after_filter) << " ms" << endl; delete[] id_list; cerr << "Final result size: " << _result_list.size() << endl; } void Strategy::handler3(BasicQuery* _bq, vector<int*>& _result_list) { long before_filter = Util::get_cur_time(); cerr << "this BasicQuery use query strategy 3" << endl; int triple_id = _bq->getEdgeID(0, 0); Triple triple = _bq->getTriple(triple_id); int pre_id = _bq->getEdgePreID(0, 0); int* id_list = NULL; int id_list_len = 0; this->kvstore->getsubIDobjIDlistBypreID(pre_id, id_list, id_list_len); int var1_id = _bq->getIDByVarName(triple.subject); int var2_id = _bq->getIDByVarName(triple.object); long after_filter = Util::get_cur_time(); cerr << "after filter, used " << (after_filter - before_filter) << "ms" << endl; _result_list.clear(); for (int i = 0; i < id_list_len; i += 2) { int* record = new int[2]; //2 vars and selected record[var1_id] = id_list[i]; record[var2_id] = id_list[i + 1]; _result_list.push_back(record); } long after_copy = Util::get_cur_time(); cerr << "after copy to result list: used " << (after_copy - after_filter) << " ms" << endl; delete[] id_list; cerr << "Final result size: " << _result_list.size() << endl; }
[ "zengli-bookug@pku.edu.cn" ]
zengli-bookug@pku.edu.cn
906524470a23235e0bfd0ec52aa885e8964af022
8da8b1d69950e9e3a0b9e91ebce9bafcf4ee9e6b
/examples/two_axis_ads_demo/two_axis_ads_demo.ino
687187f3c24c028de4e650b8692bf51b25e477ee
[]
no_license
bendlabs/two_axis_ads
b8d6468880cfaf5ed57c53ea0f3e65da66f8e807
5d4afb75110fcf656a019b1d38910df77dda28c8
refs/heads/master
2023-06-26T05:35:18.727176
2023-04-26T14:17:01
2023-04-26T14:17:01
146,693,823
8
9
null
2023-04-26T14:17:02
2018-08-30T04:03:06
C
UTF-8
C++
false
false
3,574
ino
#if defined(ARDUINO_SAMD_ZERO) && defined(SERIAL_PORT_USBVIRTUAL) // Required for Serial on Zero based boards #define Serial SERIAL_PORT_USBVIRTUAL #endif #include "Arduino.h" #include "ads_two_axis.h" #define ADS_RESET_PIN (4) // Pin number attached to ads reset line. #define ADS_INTERRUPT_PIN (3) // Pin number attached to the ads data ready line. // function prototypes void ads_data_callback(float * sample); void deadzone_filter(float * sample); void signal_filter(float * sample); void parse_serial_port(void); float ang[2]; volatile bool newData = false; void signal_filter(float * sample) { static float filter_samples[2][6]; for(uint8_t i=0; i<2; i++) { filter_samples[i][5] = filter_samples[i][4]; filter_samples[i][4] = filter_samples[i][3]; filter_samples[i][3] = (float)sample[i]; filter_samples[i][2] = filter_samples[i][1]; filter_samples[i][1] = filter_samples[i][0]; // 20 Hz cutoff frequency @ 100 Hz Sample Rate filter_samples[i][0] = filter_samples[i][1]*(0.36952737735124147f) - 0.19581571265583314f*filter_samples[i][2] + \ 0.20657208382614792f*(filter_samples[i][3] + 2*filter_samples[i][4] + filter_samples[i][5]); sample[i] = filter_samples[i][0]; } } void deadzone_filter(float * sample) { static float prev_sample[2]; float dead_zone = 0.5f; for(uint8_t i=0; i<2; i++) { if(fabs(sample[i]-prev_sample[i]) > dead_zone) prev_sample[i] = sample[i]; else sample[i] = prev_sample[i]; } } void ads_data_callback(float * sample) { // Low pass IIR filter signal_filter(sample); // Deadzone filter deadzone_filter(sample); ang[0] = sample[0]; ang[1] = sample[1]; newData = true; } void setup() { Serial.begin(115200); delay(2000); Serial.println("Initializing Two Axis sensor"); ads_init_t init; init.sps = ADS_100_HZ; init.ads_sample_callback = &ads_data_callback; init.reset_pin = ADS_RESET_PIN; // Pin connected to ADS reset line init.datardy_pin = ADS_INTERRUPT_PIN; // Pin connected to ADS data ready interrupt // Initialize ADS hardware abstraction layer, and set the sample rate int ret_val = ads_two_axis_init(&init); if(ret_val == ADS_OK) { Serial.println("Two Axis ADS initialization succeeded"); } else { Serial.print("Two Axis ADS initialization failed with reason: "); Serial.println(ret_val); } delay(100); // Start reading data! ads_two_axis_run(true); } void loop() { // put your main code here, to run repeatedly: if(newData) { newData = false; Serial.print(ang[0]); Serial.print(","); Serial.println(ang[1]); } if(Serial.available()) { parse_serial_port(); } } /* Function parses received characters from the COM port for commands */ void parse_serial_port(void) { char key = Serial.read(); if(key == '0') ads_two_axis_calibrate(ADS_CALIBRATE_FIRST, 0); else if(key == 'f') ads_two_axis_calibrate(ADS_CALIBRATE_FLAT, 90); else if(key == 'p') ads_two_axis_calibrate(ADS_CALIBRATE_PERP, 90); else if(key == 'c') ads_two_axis_calibrate(ADS_CALIBRATE_CLEAR, 0); else if(key == 'r') ads_two_axis_run(true); else if(key == 's') ads_two_axis_run(false); else if(key == 'f') ads_two_axis_set_sample_rate(ADS_200_HZ); else if(key == 'u') ads_two_axis_set_sample_rate(ADS_10_HZ); else if(key == 'n') ads_two_axis_set_sample_rate(ADS_100_HZ); }
[ "coltonottley@gmail.com" ]
coltonottley@gmail.com
bac5520dcbb84a30a8178f39e66441b4668bc6be
599aa4ba4755d6021d1329ea6495b0d460af7606
/Platforms/hackerEarth/monthlyEasy/mtd.cpp
f860fbde58d4643896acea5d17afccf07ca079a4
[]
no_license
manosriram/Algorithms
96109c86bb38a0bad43f6d6c465b224051145123
894a37d420aa65fab1e45bcef8d9f1ef262f4aaa
refs/heads/master
2022-12-21T21:32:53.005160
2020-09-24T15:50:58
2020-09-24T15:50:58
159,975,079
7
3
null
null
null
null
UTF-8
C++
false
false
658
cpp
#include <iostream> using namespace std; void removeE(int g, int arr[],int n) { for (int t=n;t>=0;t--) { if (arr[t] == g) { for (int h=t;h<n-t;h++) { arr[h] = arr[h+1]; } } } } int main() { int n,a,b,arr[10000]; int i,j,t; int count=1; int sum1=0; cin >> n >> a >> b; for (t=0;t<n;t++) cin >> arr[t]; for (i=0;i<n;i++) { for (j=i+1;j<n-i;j++) { if (arr[i] == arr[j]) count++; if (count >=3) break; } if (count == 3) { sum1 += a+b; count=1; int g = arr[i]; removeE(g,arr,n); } if (count==2) { sum1 += b; count=1; } } cout << sum1; }
[ "mano.sriram0@gmail.com" ]
mano.sriram0@gmail.com
26583c7774b6bf1ac93c1be00ad27ae7ca6aaacc
081c75d11a4a8eb139f1685f087d9cc85a4fa072
/include/nmtools/array/view/swapaxes.hpp
9af2656b620076d3c1b67a1b402538387c5e3176
[]
no_license
alifahrri/nmtools
c0a9d63b4101193b484f3e05bce606d58c3b85e2
fa8a45bc3ddb373b7f547dfea3c2c7bea3056e06
refs/heads/master
2023-08-28T19:36:41.814434
2023-08-20T08:28:40
2023-08-20T08:28:40
190,819,342
7
0
null
2023-08-20T08:28:41
2019-06-07T22:43:35
C++
UTF-8
C++
false
false
122
hpp
#ifndef NMTOOLS_ARRAY_VIEW_SWAPAXES_HPP #define NMTOOLS_ARRAY_VIEW_SWAPAXES_HPP #endif // NMTOOLS_ARRAY_VIEW_SWAPAXES_HPP
[ "noreply@github.com" ]
alifahrri.noreply@github.com
6f402149560789ca4042cdf028cc5e744cd0c7ad
512f6474f03964da335a32b7a6834ce1bbf4b651
/Player.cpp
0881b6ac9452bd9603911c871b20dd0d9207f7eb
[]
no_license
Eliaslb/Zelda
c797b1537f08ae39ae66f062012cfd1100b915a2
1a739871c670f6bf39a55233b11fd78fd49d7fb5
refs/heads/master
2021-01-20T11:01:05.316666
2017-08-28T16:30:34
2017-08-28T16:30:34
101,663,985
0
0
null
null
null
null
UTF-8
C++
false
false
3,220
cpp
#include "Player.h" Player::Player(Arduboy2 &arduboy, Animation2 &PlayerLEFTanim1, Animation2 &PlayerRIGHTanim1, Animation2 &PlayerUPanim1, Animation2 &PlayerDOWNanim1) { this->ardu = &arduboy; this->PlayerLEFTanim = &PlayerLEFTanim1; this->PlayerRIGHTanim = &PlayerRIGHTanim1; this->PlayerUPanim = &PlayerUPanim1; this->PlayerDOWNanim = &PlayerDOWNanim1; x = 64; y = 32; } void Player::draw(void){ if (Player::GetMovement() == 0) { if (Player::GetDirection() == 0) { PlayerLEFTanim->play(Player::GetX(),Player::GetY()); } else if (Player::GetDirection() == 1) { PlayerUPanim->play(Player::GetX(),Player::GetY()); } else if (Player::GetDirection() == 2) { PlayerRIGHTanim->play(Player::GetX(),Player::GetY()); } else if (Player::GetDirection() == 3) { PlayerDOWNanim->play(Player::GetX(),Player::GetY()); } } else if (Player::GetMovement() == 4) { if (Player::GetDirection() == 0) { ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerLEFT1,16,16,BLACK); } else if (Player::GetDirection() == 1) { ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerUP1,16,16,BLACK); } else if (Player::GetDirection() == 2) { ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerRIGHT1,16,16,BLACK); } else if (Player::GetDirection() == 3) { ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerDOWN1,16,16,BLACK); } } else if (Player::GetMovement() == 1) { if (Player::GetDirection() == 0) { ardu->drawBitmap(Player::GetX() - 13, Player::GetY() + 3, SwordLEFT,16,16,BLACK); ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerLEFT2,16,16,BLACK); } else if (Player::GetDirection() == 1) { ardu->drawBitmap(Player::GetX(), Player::GetY() - 14, SwordUP,16,16,BLACK); ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerUP2,16,16,BLACK); } else if (Player::GetDirection() == 2) { ardu->drawBitmap(Player::GetX() + 12, Player::GetY() + 2, SwordRIGHT,16,16,BLACK); ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerRIGHT2,16,16,BLACK); } else if (Player::GetDirection() == 3) { ardu->drawBitmap(Player::GetX(), Player::GetY() + 14, SwordDOWN,16,16,BLACK); ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerDOWN2,16,16,BLACK); } } } void Player::init(void){ } int Player::GetX(void){ return x; } int Player::GetY(void){ return y; } int Player::GetMovement(void){ return movement; } int Player::GetDirection(void){ return direction; } void Player::moveLeft(void){ //x -= moveSpeed; direction = 0; movement = 0; if (x > 4) { x -= moveSpeed; } } void Player::moveRight(void){ //x += moveSpeed; direction = 2; movement = 0; if (x < 112) { x += moveSpeed; } } void Player::moveUp(void){ //y -= moveSpeed; direction = 1; movement = 0; if (y > 10) { y -= moveSpeed; } } void Player::moveDown(void){ //y += moveSpeed; direction = 3; movement = 0; if (y < 48) { y += moveSpeed; } } void Player::Idle(void){ movement = 4; } void Player::Slash(void){ movement = 1; }
[ "eliaslb584@gmail.com" ]
eliaslb584@gmail.com
d6a6819b69fe3a6bb68a0208cf37c4afd9fb06a4
eef9cdafb7476427d194374cc11a54a068c30325
/overallControl.cpp
61bd3e32b26c32e93d61056c0605554b2396ebdb
[]
no_license
geetika016/FindMeAPet
3988ecbb87fa0c92c2424f8b628d741cf99810b6
43a7dcceb1c01a170d3101c30017a541df89b02b
refs/heads/master
2020-06-20T09:43:33.569960
2019-07-15T22:44:58
2019-07-15T22:44:58
197,078,766
0
0
null
null
null
null
UTF-8
C++
false
false
40,316
cpp
#include "overallControl.h" OverAllControl::OverAllControl() { proxy = new Proxy; } OverAllControl::~OverAllControl() { delete proxy; } void OverAllControl::launch() { dbControl = new DatabaseControl; if (initializeDB()) proxy->displayRequest(); } void OverAllControl::initializeHelper(QHash<QString, QString> &hash, QString *fields, QString *data, int size, QString table) { for(int i=0; i<size ;i++) hash[fields[i]] = data[i]; QString errMsg; DBSettings settings; settings.table = table; if (!dbControl->dbRequest(&hash, NULL, &settings, WRITE, &errMsg)) QMessageBox::critical(NULL, QObject::tr("Database error"), errMsg); hash.clear(); } bool OverAllControl::initializeDB() { if (!dbControl->openDB("cuACS_DB")) return false; bool hasTable; DBSettings settings;//dummy, used when setting fields QHash<QString, QString> input; input["results"] = "(matching_id integer not null primary key, " "client_id integer not null, " "client_name varchar not null," "total_score_client_get float not null, " "animal_id integer not null, " "animal_name varchar not null, " "total_score_animal_get float not null," "details char(4) default 'More', " "type_afc varchar," "breed_afc varchar," "gender_afc varchar, " "size_afc varchar, " "age_afc varchar," "weight_afc double," "expected_life_span_afc varchar," "colour_afc varchar," "coat_pattern_afc varchar," "coat_length_afc varchar, " "coat_layers_afc varchar," "shedding_afc varchar default null," "hypoallergenic_afc varchar," "good_new_owners_afc varchar," "good_with_being_alone_afc varchar," "kid_friendly_afc varchar," "vocality_afc varchar," "trainability_afc varchar," "playful_afc varchar," "energetic_afc varchar," "intelligence_afc varchar," "good_other_pets_afc varchar default null," "affection_owner_afc varchar," "affection_family_afc varchar," "affection_stranger_afc varchar," "budget_afc double," "special_needs_afc varchar," "dietary_afc varchar," "vet_visits_afc varchar," "grooming_afc varchar," "weather_afc varchar," "attention_afc varchar," "exercise_afc varchar," "space_afc varchar default null," "independent_afc varchar default null," "social_afc varchar default null," "pair_afc varchar default null," "interactive_afc varchar default null," "temperament_afc varchar default null," "tamed_afc varchar default null," "sensitivity_afc varchar default null," "nocturnal_afc varchar default null," "feeding_afc varchar default null," "cleaning_afc varchar default null,"//////// "space_cfa varchar," "weather_cfa varchar," "at_home_mostly_cfa varchar," "allergies_cfa varchar," "pair_cfa varchar," "first_pet_cfa varchar," "kids_cfa varchar," "budget_cfa double," "breed_cfa varchar," "gender_cfa varchar," "size_cfa varchar," "age_cfa varchar," "colour_cfa varchar," "shedding_cfa varchar," "grooming_cfa varchar," "dietary_needs_cfa varchar," "special_needs_cfa varchar," "vet_visits_cfa varchar," "other_pets_cfa varchar," "attention_cfa varchar," "energetic_cfa varchar," "trainability_cfa varchar," "intelligence_cfa varchar," "exercise_cfa varchar," "vocality_cfa varchar," "playful_cfa varchar," "affection_owner_cfa varchar," "affection_family_cfa varchar," "affection_stranger_cfa varchar)"; if(!dbControl->dbRequest(&input, NULL, &settings, CREATE_TABLE, NULL)) QMessageBox::critical(NULL, "Database Error", "Fail to create table"); input.clear(); input["users"] = "(id integer not null primary key autoincrement, " "username varchar not null unique, " "password varchar not null, " "role varchar not null)"; if(!dbControl->dbRequest(&input, &hasTable, &settings, CREATE_TABLE, NULL)) QMessageBox::critical(NULL, "Database Error", "Fail to create table"); //hasTable = true; input.clear(); if(!hasTable) { QString usersFields[4] = {"id", "username", "password", "role"}; QString usersData1[4] = {"1","Joe", "joe", "client"}; QString usersData2[4] = {"2","Lars", "lars", "client"}; QString usersData3[4] = {"3","Leo", "leo", "client"}; QString usersData4[4] = {"4","Lora", "lora", "client"}; QString usersData5[4] = {"5","Jacob", "jacob", "client"}; QString usersData6[4] = {"6","Jonathan", "jonathan", "client"}; QString usersData7[4] = {"7","Sam", "sam", "client"}; QString usersData8[4] = {"8","Tony", "tony", "client"}; QString usersData9[4] = {"9","Chandler", "chandler", "client"}; QString usersData10[4] = {"10","Monica", "monica", "client"}; QString usersData11[4] = {"11","Rachel", "rachel", "client"}; QString usersData12[4] = {"12","Phoebe", "phoebe", "client"}; QString usersData13[4] = {"13","Sammie", "sammie", "client"}; QString usersData14[4] = {"14","Charles", "charles", "client"}; QString usersData15[4] = {"15","Chen", "chen", "client"}; QString usersData16[4] = {"16","Jamaica", "jamaica", "client"}; QString usersData17[4] = {"17","Sally", "sally", "client"}; QString usersData18[4] = {"18","Jonas", "jonas", "client"}; QString usersData19[4] = {"19","Joseph", "joseph", "client"}; QString usersData20[4] = {"20","Lily", "lily", "client"}; QString staffData1[4] = {"21","matilda23", "matilda23", "staff"}; initializeHelper(input, usersFields, usersData1, 4, "users"); initializeHelper(input, usersFields, usersData2, 4, "users"); initializeHelper(input, usersFields, usersData3, 4, "users"); initializeHelper(input, usersFields, usersData4, 4, "users"); initializeHelper(input, usersFields, usersData5, 4, "users"); /*initializeHelper(input, usersFields, usersData6, 4, "users"); initializeHelper(input, usersFields, usersData7, 4, "users"); initializeHelper(input, usersFields, usersData8, 4, "users"); initializeHelper(input, usersFields, usersData9, 4, "users"); initializeHelper(input, usersFields, usersData10, 4, "users"); initializeHelper(input, usersFields, usersData11, 4, "users"); initializeHelper(input, usersFields, usersData12, 4, "users"); initializeHelper(input, usersFields, usersData13, 4, "users"); initializeHelper(input, usersFields, usersData14, 4, "users"); initializeHelper(input, usersFields, usersData15, 4, "users"); initializeHelper(input, usersFields, usersData16, 4, "users"); initializeHelper(input, usersFields, usersData17, 4, "users"); initializeHelper(input, usersFields, usersData18, 4, "users"); initializeHelper(input, usersFields, usersData19, 4, "users"); initializeHelper(input, usersFields, usersData20, 4, "users");*/ initializeHelper(input, usersFields, staffData1, 4, "users"); } input["animals"] = "(id integer primary key ," "name varchar not null," "type varchar," "breed varchar," "gender varchar, " "size integer, " "age integer," "weight double," "expected_life_span varchar," "colour varchar," "coat_pattern varchar," "coat_length varchar, " "coat_layers varchar," "shedding varchar default null," "hypoallergenic varchar," "good_new_owners varchar," "good_with_being_alone varchar," "kid_friendly varchar," "vocality varchar," "trainability varchar," "playful integer," "energetic integer," "intelligence integer," "good_other_pets varchar default null," "affection_owner integer," "affection_family integer," "affection_stranger integer," "budget double," "special_needs varchar," "dietary varchar," "vet_visits varchar," "grooming varchar," "weather varchar," "attention integer," "exercise integer," "space varchar default null," "independent integer default null," "social integer default null," "pair varchar default null," "interactive integer default null," "temperament varchar default null," "tamed varchar default null," "sensitivity integer default null," "nocturnal varchar default null," "feeding integer default null," "cleaning integer default null," "details char(4) default 'More')"; if(!dbControl->dbRequest(&input, &hasTable, &settings, CREATE_TABLE, NULL)) hasTable = true; input.clear(); if(!hasTable) { QString dogFields[ATTRIBUTES_NUM_DOG] = {"name","type","breed","gender","size","age","weight","expected_life_span","colour","coat_length", "coat_layers","shedding","hypoallergenic","good_new_owners","good_with_being_alone","kid_friendly","vocality", "trainability","playful","energetic","intelligence","good_other_pets","affection_owner","affection_family", "affection_stranger","budget","special_needs","dietary","vet_visits","grooming","weather","attention","exercise","space"}; QString dog_data1[ATTRIBUTES_NUM_DOG] = {"Pooh","Dog","Beagle","Female","Small","1","15","12-15","Brown","Short(less than 1 inch)", "1-Layer","Infrequent","No","Yes","No","Yes","Likes to be vocal", "Trained","4","4","4","DBHRG","5","5", "3","700","Yes","No","Monthly","Once a week","Hot","3","5","SL"}; QString dog_data2[ATTRIBUTES_NUM_DOG]= {"Bowie","Dog","Siberian","Male","Large","7","89.6","11-14","Brown","Medium(1-3 inches)", "1-Layer","Frequent","No","Yes","No","Yes","Likes to be vocal", "Docile(easy to train)","5","5","5","DCBRHG","5","5", "4","600","No","Yes","Every 2 months","Once a week","Moderate","5","5","L"}; QString dog_data3[ATTRIBUTES_NUM_DOG] = {"QTPie","Dog","Poodle","Female","Large","2","70.3","12-15","Grey","Medium(1-3 inches)", "1-Layer","Regularly","Yes","No","No","Yes","Infrequent", "Trained","4","3","4","DBC","5","4", "4","1100","Yes","Yes","Half-Yearly","Daily","Moderate","4","4","SL"}; QString dog_data4[ATTRIBUTES_NUM_DOG] = {"Peirce","Dog","St. Bernard","Male","Large","3","93.2","13-16","White", "Medium(1-3 inches)","2-Layer","Seasonal","Yes","No","Yes","Yes", "Only when necessary","Trained","4","4","5","RD","4","4","3", "1100","Yes","No","Half-Yearly","Daily","Cold","4","5","L"}; QString dog_data5[ATTRIBUTES_NUM_DOG] = {"Percy","Dog","St. Bernard","Male","Large","2","68.4","12-13","White", "Medium(1-3 inches)","1-Layer","Regularly","No","No","No","No","Frequent", "Agreeable","5","5","5","DGCBRH","5","5","3","600","No","Yes","Every 2 months", "Daily","Moderate","5","5","L"}; QString dog_data6[ATTRIBUTES_NUM_DOG] = {"Jack","Dog","Alaskan Malamute","Male","Large","7","141.06","8-10","Brown", "Short(less than 1 inch)","1-Layer","Frequent","Yes","Yes","No","Yes", "Only when necessary","Trained","3","3","4","DC","4","4","4","1250","No", "No","Monthly","2-3 times/week","Moderate","2","5","SL"}; QString dog_data7[ATTRIBUTES_NUM_DOG] = {"Walley","Dog","Pug","Female","Medium","8","68.4","12-15","White","Short(less than 1 inch", "2-Layer","Regularly","No","No","Yes","Yes","Only when necessary", "Trained","3","5","5","BHGC","5","4", "2","1500","No","Yes","Yearly","Daily","Cold","5","5","L"}; QString dog_data8[ATTRIBUTES_NUM_DOG] = {"Shadow","Dog","German Shepherd","Male","Large","4","89.03","9-13","Black", "Short(less than 1 inch)","1-Layer","Infrequent","Yes","No","No","Yes", "Frequent","Trained","3","5","5","B","5","3","1","700","Yes","No", "Half-Yearly","Once a week","Moderate","2","4","L" }; QString dog_data9[ATTRIBUTES_NUM_DOG] = {"Snowy","Dog","Pomeranian","Female","Small","6","7.8","12-18","White", "Medium(1-3 inches)","1-Layer","Frequent","Yes","Yes","Yes","Yes", "Likes to be Vocal","Docile(easy to train)","5","5","3", "DBCH","5","5","4","900","No","No","Every 2 months","2-3 times/week", "Moderate","4","4","ASL"}; QString dog_data10[ATTRIBUTES_NUM_DOG] = {"Bosco","Dog","German Shepherd","Female","Small","3","19.6","12-15","White","Short(less than 1 inch)", "1-Layer","Infrequent","No","No","Yes","Yes","Only when necessary","Trained", "5","3","2","CDGH","5","5","5","900","No","Yes","Half-Yearly", "Once a week","Moderate","3","4","ASL"}; initializeHelper(input, dogFields, dog_data1, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data2, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data3, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data4, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data5, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data6, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data7, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data8, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data9, ATTRIBUTES_NUM_DOG, "animals"); initializeHelper(input, dogFields, dog_data10, ATTRIBUTES_NUM_DOG, "animals"); QString catFields[ATTRIBUTES_NUM_CAT] = {"name","type","breed","gender","size","age","weight","expected_life_span","colour","coat_length", "coat_pattern","shedding","hypoallergenic","good_new_owners","kid_friendly","vocality", "trainability","independent","playful","energetic","intelligence","good_other_pets","affection_owner","affection_family", "affection_stranger","budget","special_needs","dietary","vet_visits","grooming","weather","attention","space","social","pair"}; QString cat_data1[ATTRIBUTES_NUM_CAT] = {"Murphy","Cat","Abyssinian","Female","Medium","3","15.0","6-8","White","Short(less than 1 inch)", "Solid(1-Colour)","Infrequent","No","Yes","Yes","Infrequent", "Docile","5","3","4","5","C","3","2", "1","400","No","No","Half-Yearly","Once a week","Moderate","2","I","2","No"}; QString cat_data2[ATTRIBUTES_NUM_CAT] = {"Sky","Cat","American Curl","Female","Medium","3","18","2-8","White","Short(less than 1 inch)", "Bi-colour","Infrequent","No","No","Yes","Infrequent", "Independent","5","4","3","5","C","3","3", "2","410","No","No","Half-Yearly","Once a week","Moderate","2","O","1","No"}; QString cat_data3[ATTRIBUTES_NUM_CAT] = {"Ivy","Cat","Persian","Female","Small","2","19","6-9","Golden Brown","Short(less than 1 inch)", "Stripped Tabby","Frequent","No","Yes","No","Infrequent", "Independent","5","5","5","5","C","3","2", "1","500","No","No","Every 2 months","Once a week","Cold","2","IO","3","No"}; QString cat_data4[ATTRIBUTES_NUM_CAT] = {"Garfield","Cat","Siamese","Male","Medium","1","14","8-10","Grey","Medium(1-3 inches)", "Solid(1-colour)","Regularly","No","No","Yes","Infrequent", "Independent","5","2","5","5","C","3","3", "2","600","No","No","Half-Yearly","Once a week","Hot","3","I","2","No"}; QString cat_data5[ATTRIBUTES_NUM_CAT] = {"Joana","Cat","Highlander","Female","Small","4","10","5-8","Chocolate Brown","Medium(1-3 inches)", "Calico(3-colour)","Ocassional","No","Yes","No","Infrequent", "Independent","5","5","5","5","C","3","3", "2","450","No","No","Every 2 months","Once a week","Moderate","2","I","3","No"}; QString cat_data6[ATTRIBUTES_NUM_CAT] = {"Tom","Cat","Savannah","Male","Medium","2","8","6-9","Black","Medium(1-3 inches)", "Tortoiseshell","Seasonal","No","No","Yes","Likes to be vocal", "Independent","5","3","5","5","C","4","3", "2","430","No","No","Half-Yearly","Once a week","Hot","3","O","2","No"}; initializeHelper(input, catFields, cat_data1, ATTRIBUTES_NUM_CAT, "animals"); initializeHelper(input, catFields, cat_data2, ATTRIBUTES_NUM_CAT, "animals"); initializeHelper(input, catFields, cat_data3, ATTRIBUTES_NUM_CAT, "animals"); initializeHelper(input, catFields, cat_data4, ATTRIBUTES_NUM_CAT, "animals"); initializeHelper(input, catFields, cat_data5, ATTRIBUTES_NUM_CAT, "animals"); initializeHelper(input, catFields, cat_data6, ATTRIBUTES_NUM_CAT, "animals"); QString birdFields[ATTRIBUTES_NUM_BIRD] = {"name","type","breed","gender","size","age","dietary","pair","weather","budget","colour","special_needs", "vet_visits","expected_life_span","vocality","shedding","interactive","intelligence"}; QString bird_data1[ATTRIBUTES_NUM_BIRD] = {"Nancy","Bird","Dove","Female","Tiny","1","Yes","No","Hot","200","White", "No","Yearly","4-8","Infrequent","Occationaly","4","3"}; QString bird_data2[ATTRIBUTES_NUM_BIRD] = {"Nona","Bird","Parrot","Female","Medium","2","Yes","No","Hot","150","Green","No", "Yearly","3-8","Likes to be vocal","Occationaly","5","5"}; QString bird_data3[ATTRIBUTES_NUM_BIRD] = {"Meethu","Bird","Mynah","Female","Tiny","1","Yes","No","Hot","175","Blue","No", "Yearly","4-7","Frequent","Occationaly","2","4"}; QString bird_data4[ATTRIBUTES_NUM_BIRD] = {"Stella","Bird","Conures","Female","Small","1","Yes","No","Hot","125","Blue","No", "Yearly","2-6","Frequent","Occationaly","3","3"}; QString bird_data5[ATTRIBUTES_NUM_BIRD] = {"Gypsy","Bird","Canaries","Female","Tiny","2","Yes","No","Moderate","300","Yellow","No", "Yearly","8-12","Frequent","Occationaly","3","4"}; initializeHelper(input, birdFields, bird_data1, ATTRIBUTES_NUM_BIRD, "animals"); initializeHelper(input, birdFields, bird_data2, ATTRIBUTES_NUM_BIRD, "animals"); initializeHelper(input, birdFields, bird_data3, ATTRIBUTES_NUM_BIRD, "animals"); initializeHelper(input, birdFields, bird_data4, ATTRIBUTES_NUM_BIRD, "animals"); initializeHelper(input, birdFields, bird_data5, ATTRIBUTES_NUM_BIRD, "animals"); QString rabbitFields[ATTRIBUTES_NUM_RABBIT] = {"name","type","gender","breed","colour","temperament","age","budget","expected_life_span","tamed", "hypoallergenic","good_other_pets","social","sensitivity"}; QString rabbit_data1[ATTRIBUTES_NUM_RABBIT] = {"Stuart","Rabbit","Male","Lionhead","Brown","Docile","1","400","2-4","Yes", "No","DCBRHG","3","3"}; QString rabbit_data2[ATTRIBUTES_NUM_RABBIT] = {"Ruby","Rabbit","Female","Angora","White","Calm","1","400","2-4","Yes", "No","DCBRHG","5","5"}; initializeHelper(input, rabbitFields, rabbit_data1, ATTRIBUTES_NUM_RABBIT, "animals"); initializeHelper(input, rabbitFields, rabbit_data2, ATTRIBUTES_NUM_RABBIT, "animals"); QString hamsterFields[ATTRIBUTES_NUM_HAMSTER] = {"name","type","gender","breed","colour","age","budget","hypoallergenic", "expected_life_span","nocturnal","tamed","social","attention","cleaning","feeding"}; QString hamster_data1[ATTRIBUTES_NUM_HAMSTER] = {"Joe","Hamster","Female","Syrian","Brown","1","200","Yes", "1-3","Yes","Yes","5","5","4","4"}; initializeHelper(input, hamsterFields, hamster_data1, ATTRIBUTES_NUM_HAMSTER, "animals"); QString guineaPigFields[ATTRIBUTES_NUM_GUINEA_PIGS] = {"name","type","gender","breed","colour","age","budget","hypoallergenic", "expected_life_span","tamed","social","attention","cleaning","feeding"}; QString guineaPig_data1[ATTRIBUTES_NUM_GUINEA_PIGS] = {"Jim","Guinea Pig","Female","Teddy","Chocolate","3","250","Yes", "4-8","Yes","4","4","5","5"}; initializeHelper(input, guineaPigFields, guineaPig_data1, ATTRIBUTES_NUM_GUINEA_PIGS, "animals"); } input["clients"] = "(id integer not null primary key autoincrement," "name varchar not null unique, " "phone_number varchar not null, " "email varchar not null," "animal_type varchar," "space varchar," "weather varchar," "at_home_mostly varchar," "allergies varchar," "first_pet varchar," "kids varchar," "budget double," "breed varchar," "gender varchar," "size varchar," "age varchar," "colour varchar," "shedding varchar," "grooming varchar," "dietary_needs varchar," "special_needs varchar," "vet_visits varchar," "coat_length varchar," "other_pets varchar," "attention integer," "energetic integer," "trainability integer," "intelligence integer," "exercise integer," "vocality integer," "playful integer," "affection_owner integer," "affection_family integer," "affection_stranger integer," "pair varchar," "coat_pattern varchar," "social integer," "independent integer," "interactive integer," "tamed varchar," "temperament integer," "sensitivity integer," "nocturnal varchar," "cleaning integer," "feeding integer," "details char(4) default 'More')"; if(!dbControl->dbRequest(&input, &hasTable, &settings, CREATE_TABLE, NULL)) hasTable = true; input.clear(); if(!hasTable) { QString clientFields[ATTRIBUTES_NUM_CLIENT] = {"id","name","phone_number","email","animal_type","space", "weather","at_home_mostly","allergies","first_pet","kids", "budget","breed","gender","size","age","colour","shedding", "grooming","dietary_needs","special_needs","vet_visits", "other_pets","attention","energetic","trainability","intelligence", "exercise", "vocality","playful","affection_owner", "affection_family","affection_stranger"}; QString clientData1[ATTRIBUTES_NUM_CLIENT] = {"1","Joe", "3423629617", "joe682@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","Yes","Yes","Yes","600","German Shepherd","Male", "Small","4","White","Infrequent","Daily", "Yes","No","Monthly","HGD","4","3","2","4","2","4","3","2","4","2"}; QString clientData2[ATTRIBUTES_NUM_CLIENT] = {"4","Jonathan", "6473629897", "jonathan@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pomeranian","Female", "Small","2","White","Infrequent","Daily", "No","No","Monthly","RG","4","3","2","4","2","4","3","2","4","2"}; QString clientData3[ATTRIBUTES_NUM_CLIENT] = {"3","Leo", "3423678997", "samantha@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","Yes","Yes","No","600","Alaskan Malamute","Male", "Small","1","White","Infrequent","Daily", "No","Yes","Monthly","CBR","4","3","2","4","2","4","3","2","4","2"}; QString clientData4[ATTRIBUTES_NUM_CLIENT] = {"2","Lars", "3423629897", "jack482@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","6","White","Infrequent","Daily", "Yes","Yes","Monthly","BC","4","3","2","4","2","4","3","2","4","2"}; QString clientData5[ATTRIBUTES_NUM_CLIENT] = {"5","Jacob", "7899629897", "joey@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","No","600","Alaskan Malamute","Male", "Small","1","White","Infrequent","Daily", "Yes","No","Monthly","BR","4","3","2","4","2","4","3","2","4","2"}; QString clientData6[ATTRIBUTES_NUM_CLIENT] = {"6","Lily", "3423629897", "lily@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","5","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData7[ATTRIBUTES_NUM_CLIENT] = {"7","Sam", "2133627897", "sam@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Labrador","Male", "Small","6","White","Infrequent","Daily", "Yes","Yes","Monthly","CRBD","4","3","2","4","2","4","3","2","4","2"}; QString clientData8[ATTRIBUTES_NUM_CLIENT] = {"8","Tony", "6893629851", "tony82@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Female", "Small","3","White","Infrequent","Daily", "Yes","Yes","Monthly","CBD","4","3","2","4","2","4","3","2","4","2"}; QString clientData9[ATTRIBUTES_NUM_CLIENT] = {"9","Chandler", "3424536298", "chandler16@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","5","White","Infrequent","Daily", "Yes","Yes","Monthly","C","4","3","2","4","2","4","3","2","4","2"}; QString clientData10[ATTRIBUTES_NUM_CLIENT] = {"10","Monica", "3423629897", "monica2@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Female", "Small","9","White","Infrequent","Daily", "Yes","Yes","Monthly","CH","4","3","2","4","2","4","3","2","4","2"}; QString clientData11[ATTRIBUTES_NUM_CLIENT] = {"11","Rachel", "4563629897", "rachel482@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","2","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData12[ATTRIBUTES_NUM_CLIENT] = {"12","Phoebe", "3424536298", "phoebe482@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","4","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData13[ATTRIBUTES_NUM_CLIENT] = {"13","Sammie", "3423629897", "sammie2@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","5","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData14[ATTRIBUTES_NUM_CLIENT] = {"14","Charles", "3423629897", "charles3@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","1","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData15[ATTRIBUTES_NUM_CLIENT] = {"15","Chen", "3423629897", "chen7@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","7","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData16[ATTRIBUTES_NUM_CLIENT] = {"16","Jamaica", "3423629897", "jamaica32@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","7","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData17[ATTRIBUTES_NUM_CLIENT] = {"17","Sally", "3423629897", "sally@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","5","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData18[ATTRIBUTES_NUM_CLIENT] = {"18","Jonas", "3423629897", "jonas21@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","4","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData19[ATTRIBUTES_NUM_CLIENT] = {"19","Joseph", "3423629897", "joseph23@cmail.carleton.ca","Dog", "Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male", "Small","7","White","Infrequent","Daily", "Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"}; QString clientData20[ATTRIBUTES_NUM_CLIENT] = {"20","Lora", "6457629897", "samuel@cmail.carleton.ca","Cat", "Appartment","Hot","Yes","No","Yes","No","600","Siamese","Male", "Small","6","White","Infrequent","Daily", "No","Yes","Monthly","DCBRHG","4","3","2","4","2","4","3","2","4","2"}; initializeHelper(input, clientFields, clientData1, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData2, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData3, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData4, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData5, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData6, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData7, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData8, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData9, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData10, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData11, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData12, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData13, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData14, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData15, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData16, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData17, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData18, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData19, ATTRIBUTES_NUM_CLIENT, "clients"); initializeHelper(input, clientFields, clientData20, ATTRIBUTES_NUM_CLIENT, "clients"); } return true; }
[ "geetika.shrma16@gmail.com" ]
geetika.shrma16@gmail.com
dd65570b9ce936d8b256816347695d10cda4f77f
8b63f0deb717cbd11a13f418d70f18a612c99d56
/Metos_Numericos/6-Runge-Kutte.cpp
3e63cc4ee1ded8b4cbe6bd79f5ffe8ff2355f4d9
[]
no_license
Israel-Eskape/C-
ebb5aeacbb6f9603b6b1ec79f51c81c033188a0a
58ac60d42d57634974bc8d73beed655d7683fb47
refs/heads/master
2022-04-19T23:40:40.912906
2020-04-21T01:46:09
2020-04-21T01:46:09
257,428,376
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include <stdio.h> #include <stdlib.h> #include <math.h> double yi(double y,double k1,double k2,double h){ return y+(0.5*k1+0.5*k2)*h; } double fun(double x,double y){ return x-y; } int main(){ double y,x,h,k1,k2,r; int yf=10; y=2; h=0.2; x=0; for(int i=0;i<yf/2;i++){ k1=fun(x,y); k2=fun(x+h,y+k1*h); y=yi(y,k1,k2,h); x+=h; printf("X(%d)= %g Y(%d)= %g\n",i+1,x,i+1,y); } system ("pause"); return 0; }
[ "isra.ixoye@gmail.com" ]
isra.ixoye@gmail.com
242f528738ee50c84dd2c6bd5ac9190d98315dd8
45874c847c5a2fc4e89e05a7fc8ad9b63d8c4860
/clang/test/SemaSYCL/intel-max-work-group-size-ast.cpp
59f80bb24695f1a913beaa94e59f60c55ce460f9
[ "LicenseRef-scancode-unknown-license-reference", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
intel/llvm
2f023cefec793a248d8a237267410f5e288116c5
a3d10cf63ddbdcc23712c45afd1b6b0a2ff5b190
refs/heads/sycl
2023-08-24T18:53:49.800759
2023-08-24T17:38:35
2023-08-24T17:38:35
166,008,577
1,050
735
NOASSERTION
2023-09-14T20:35:07
2019-01-16T09:05:33
null
UTF-8
C++
false
false
5,087
cpp
// RUN: %clang_cc1 %s -fsyntax-only -ast-dump -fsycl-is-device -internal-isystem %S/Inputs -sycl-std=2017 -triple spir64 | FileCheck %s // The test checks support and functionality of [[intel:::max_work_group_size()]] attribute. #include "sycl.hpp" using namespace sycl; queue q; [[intel::max_work_group_size(2, 2, 2)]] void func_do_not_ignore() {} struct FuncObj { [[intel::max_work_group_size(4, 4, 4)]] void operator()() const {} }; // Test that checks template parameter support on member function of class template. template <int SIZE, int SIZE1, int SIZE2> class KernelFunctor { public: [[intel::max_work_group_size(SIZE, SIZE1, SIZE2)]] void operator()() {} }; // Test that checks template parameter support on function. template <int N, int N1, int N2> [[intel::max_work_group_size(N, N1, N2)]] void func() {} int check() { // CHECK: ClassTemplateDecl {{.*}} {{.*}} KernelFunctor // CHECK: ClassTemplateSpecializationDecl {{.*}} {{.*}} class KernelFunctor definition // CHECK: CXXRecordDecl {{.*}} {{.*}} implicit class KernelFunctor // CHECK: SYCLIntelMaxWorkGroupSizeAttr // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 4 // CHECK-NEXT: SubstNonTypeTemplateParmExpr {{.*}} // CHECK-NEXT: NonTypeTemplateParmDecl {{.*}} // CHECK-NEXT: IntegerLiteral{{.*}}4{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 4 // CHECK-NEXT: SubstNonTypeTemplateParmExpr {{.*}} // CHECK-NEXT: NonTypeTemplateParmDecl {{.*}} // CHECK-NEXT: IntegerLiteral{{.*}}4{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 4 // CHECK-NEXT: SubstNonTypeTemplateParmExpr {{.*}} // CHECK-NEXT: NonTypeTemplateParmDecl {{.*}} // CHECK-NEXT: IntegerLiteral{{.*}}4{{$}} KernelFunctor<4, 4, 4>(); // CHECK: FunctionTemplateDecl {{.*}} {{.*}} func // CHECK: FunctionDecl {{.*}} {{.*}} used func 'void ()' // CHECK: SYCLIntelMaxWorkGroupSizeAttr {{.*}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 8 // CHECK: SubstNonTypeTemplateParmExpr {{.*}} // CHECK-NEXT: NonTypeTemplateParmDecl {{.*}} // CHECK-NEXT: IntegerLiteral{{.*}}8{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 8 // CHECK-NEXT: SubstNonTypeTemplateParmExpr {{.*}} // CHECK-NEXT: NonTypeTemplateParmDecl {{.*}} // CHECK-NEXT: IntegerLiteral{{.*}}8{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 8 // CHECK-NEXT: SubstNonTypeTemplateParmExpr {{.*}} // CHECK-NEXT: NonTypeTemplateParmDecl {{.*}} // CHECK-NEXT: IntegerLiteral{{.*}}8{{$}} func<8, 8, 8>(); return 0; } int main() { q.submit([&](handler &h) { // CHECK-LABEL: FunctionDecl {{.*}}test_kernel1 // CHECK: SYCLIntelMaxWorkGroupSizeAttr // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 4 // CHECK-NEXT: IntegerLiteral{{.*}}4{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 4 // CHECK-NEXT: IntegerLiteral{{.*}}4{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 4 // CHECK-NEXT: IntegerLiteral{{.*}}4{{$}} h.single_task<class test_kernel1>(FuncObj()); // CHECK-LABEL: FunctionDecl {{.*}}test_kernel2 // CHECK: SYCLIntelMaxWorkGroupSizeAttr // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 8 // CHECK-NEXT: IntegerLiteral{{.*}}8{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 8 // CHECK-NEXT: IntegerLiteral{{.*}}8{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 8 // CHECK-NEXT: IntegerLiteral{{.*}}8{{$}} h.single_task<class test_kernel2>( []() [[intel::max_work_group_size(8, 8, 8)]] {}); // CHECK-LABEL: FunctionDecl {{.*}}test_kernel3 // CHECK: SYCLIntelMaxWorkGroupSizeAttr // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 2 // CHECK-NEXT: IntegerLiteral{{.*}}2{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 2 // CHECK-NEXT: IntegerLiteral{{.*}}2{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 2 // CHECK-NEXT: IntegerLiteral{{.*}}2{{$}} h.single_task<class test_kernel3>( []() { func_do_not_ignore(); }); // Ignore duplicate attribute. h.single_task<class test_kernel10>( // CHECK-LABEL: FunctionDecl {{.*}}test_kernel10 // CHECK: SYCLIntelMaxWorkGroupSizeAttr // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 2 // CHECK-NEXT: IntegerLiteral{{.*}}2{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 2 // CHECK-NEXT: IntegerLiteral{{.*}}2{{$}} // CHECK-NEXT: ConstantExpr{{.*}}'int' // CHECK-NEXT: value: Int 2 // CHECK-NEXT: IntegerLiteral{{.*}}2{{$}} // CHECK-NOT: SYCLIntelMaxWorkGroupSizeAttr []() [[intel::max_work_group_size(2, 2, 2), intel::max_work_group_size(2, 2, 2)]] {}); }); return 0; }
[ "noreply@github.com" ]
intel.noreply@github.com
15b771928b361c5b13dc56109c65a3bc6d15ef4e
5885fd1418db54cc4b699c809cd44e625f7e23fc
/codeforces/1167/d.cpp
98262d5a7737484a17355b2854185cb07d3650cb
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
1,651
cpp
#include <bits/stdc++.h> using namespace std; #define _USE_MATH_DEFINES #define For(i,n) for (int i=0; i<n; i++) #define FOR(i,a,b) for (int i=a; i<=b; i++) #define Down(i,n) for (int i=n-1; i>=0; i--) #define DOWN(i,a,b) for (int i=b; i>=a; i--) typedef long long ll; typedef long double ld; typedef pair<int,int> pii; typedef pair<ld,ld> pdd; typedef complex<ld> pt; typedef vector<pt> pol; typedef vector<int> vi; const char nl = '\n'; const int INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3f3f; const ll MOD = 1e9+7; const ld EPS = 1e-10; mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); const int N = 2e5+1; vector<int> adj[N]; int par[N], col[N], depth[N], height[N]; void dfs(int u) { if (u) depth[u] = 1 + depth[par[u]]; for (int v : adj[u]) { dfs(v); height[u] = max(height[u], 1 + height[v]); } col[u] = (depth[u] > height[u]); } //#define FILEIO int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout << fixed << setprecision(10); #ifdef FILEIO freopen("test.in", "r", stdin); freopen("test.out", "w", stdout); #endif int n; cin >> n; string s; cin >> s; { int u = 0; int id = 1; for (char c : s) { if (c == '(') { par[id] = u; adj[u].push_back(id); u = id++; } else { u = par[u]; } } } dfs(0); { int u = 0; int id = 1; for (char c : s) { if (c == '(') { par[id] = u; adj[u].push_back(id); u = id++; cout << col[u]; } else { cout << col[u]; u = par[u]; } } cout << nl; } return 0; }
[ "henryxia9999@gmail.com" ]
henryxia9999@gmail.com
b5d4c2a972249ffed244f9592d42a62a2264ab8c
a565dc8a731c4166548d3e3bf8156c149d793162
/PLATFORM/TI_EVM_3530/SRC/DRIVERS/PM/DLL/pmrelation.cpp
689b19fed64d53a6d09859b9c68a3571d70956ce
[]
no_license
radtek/MTI_WINCE317_BSP
eaaf3147d3de9a731a011b61f30d938dc48be5b5
32ea5df0f2918036f4b53a4b3aabecb113213cc6
refs/heads/master
2021-12-08T13:09:24.823090
2016-03-17T15:27:44
2016-03-17T15:30:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,324
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES. // // // This module contains routines for handling power relationships. A // device such as NDIS or a bus driver can register as a parent of another // device. The parent will act as a proxy for all requests going to the // child device. Parent devices can register with the PM when they handle // the IOCTL_REGISTER_POWER_RELATIONSHIP message. // #include <pmimpl.h> // This routine sets up a proxy relationship between a parent device // and a child device. This will overwrite any other proxy relationships // created for the child device. Only one level of relationships is // supported; that is, a parent device cannot itself be a child device. // This routine passes back an handle to the relationship and sets the // global error status to: // ERROR_SUCCESS - relationship set up ok // ERROR_INVALID_PARAMETER - bad parameter of some sort // ERROR_FILE_EXISTS - child device already registered // Note that in this implementation, a device cannot register itself // (using AdvertiseInterface()) and then have a parent register to // proxy for it. EXTERN_C HANDLE WINAPI PmRegisterPowerRelationship(PVOID pvParent, PVOID pvChild, PPOWER_CAPABILITIES pCaps, DWORD dwFlags) { PDEVICEID pdiParent = NULL, pdiChild = NULL; PDEVICE_LIST pdlParent, pdlChild; PDEVICE_STATE pdsParent = NULL; PDEVICE_STATE pdsChild = NULL; DWORD dwStatus = ERROR_SUCCESS; SETFNAME(_T("PmRegisterPowerRelationship")); PMLOGMSG(ZONE_API, (_T("+%s\r\n"), pszFname)); // sanity check parameters if(pvParent == NULL || pvChild == NULL || (pdiParent = DeviceIdParseNameString((LPCTSTR) pvParent, dwFlags)) == NULL || (pdiChild = DeviceIdParseNameString((LPCTSTR) pvChild, dwFlags)) == NULL) { dwStatus = ERROR_INVALID_PARAMETER; } // parameters ok so far? if(dwStatus == ERROR_SUCCESS) { pdlChild = GetDeviceListFromClass(pdiChild->pGuid); if(dwStatus == ERROR_SUCCESS) { // Look up device lists for parent and child, plus the parent // and child device structures. The child cannot already exist. pdlParent = GetDeviceListFromClass(pdiParent->pGuid); if(pdlParent == NULL || pdlChild == NULL) { PMLOGMSG(ZONE_WARN, (_T("%s: can't find class for parent or child\r\n"), pszFname)); dwStatus = ERROR_INVALID_PARAMETER; } else if((pdsChild = DeviceStateFindList(pdlChild, pdiChild->pszName)) != NULL) { PMLOGMSG(ZONE_WARN, (_T("%s: child '%s' already exists\r\n"), pszFname, pdiChild->pszName)); DeviceStateDecRef(pdsChild); dwStatus = ERROR_FILE_EXISTS; } else { pdsParent = DeviceStateFindList(pdlParent, pdiParent->pszName); if(pdsParent == NULL) { PMLOGMSG(ZONE_WARN, (_T("%s: can't find parent '%s'\r\n"), pszFname, pdiParent->pszName)); dwStatus = ERROR_INVALID_PARAMETER; } else if(pdsParent->pParent != NULL) { PMLOGMSG(ZONE_WARN, (_T("%s: parent '%s' can't also be a child\r\n"), pszFname, pdsParent->pszName)); } } } } // if parameters were ok, proceed if(dwStatus == ERROR_SUCCESS) { // create and/or initialize the new device AddDevice(pdiChild->pGuid, pdiChild->pszName, pdsParent, pCaps); // get the return value pdsChild = DeviceStateFindList(pdlChild, pdiChild->pszName); if(pdsChild != NULL) { // we only want the pointer value for now DeviceStateDecRef(pdsChild); } else { // couldn't create the child device for some reason dwStatus = ERROR_GEN_FAILURE; } } // release resources if(pdsParent != NULL) DeviceStateDecRef(pdsParent); if(pdiParent != NULL) DeviceIdDestroy(pdiParent); if(pdiChild != NULL) DeviceIdDestroy(pdiChild); PMLOGMSG((dwStatus != ERROR_SUCCESS && ZONE_WARN) || ZONE_API, (_T("%s: returning 0x%08x, status is %d\r\n"), pszFname, pdsChild, dwStatus)); SetLastError(dwStatus); return (HANDLE) pdsChild; } // This routine releases a power relationship that was created with // PmRegisterPowerRelationship(). It returns // ERROR_SUCCESS - relationship removed // ERROR_INVALID_PARAMETER - bad handle // Deregistering a power relationship has the side effect of deregistering // the child device with the PM. Note that if the child exits while // the relationship is outstanding, the caller will get ERROR_INVALID_PARAMETER // when they attempt to release the relationship handle. EXTERN_C DWORD WINAPI PmReleasePowerRelationship(HANDLE h) { PDEVICE_STATE pds = (PDEVICE_STATE) h; DWORD dwStatus = ERROR_INVALID_PARAMETER; SETFNAME(_T("PmReleasePowerRelationship")); PMLOGMSG(ZONE_API, (_T("%s: releasing 0x%08x\r\n"), pszFname, h)); // make sure that this pointer is a child node with a parent if(pds != NULL) { BOOL fExists = CheckDevicePointer(pds); // increments refcnt if TRUE if(fExists) { // delete the device PREFAST_DEBUGCHK(pds->pListHead != NULL); RemoveDevice(pds->pListHead->pGuid, pds->pszName); // done with the pointer DeviceStateDecRef(pds); // return a good status dwStatus = ERROR_SUCCESS; } } PMLOGMSG(ZONE_API || (dwStatus != ERROR_SUCCESS && ZONE_WARN), (_T("%s: returning %d\r\n"), pszFname, dwStatus)); return dwStatus; }
[ "ruslan.sirota@micronet-inc.com" ]
ruslan.sirota@micronet-inc.com
7d24c20c45672137603f10ae304b6d51202d5e12
25f8cc14652d2d4a799fb4e946d79b2672d24662
/TestCases/main.cpp
0441bab5def7c96415d4610406c42e802cfe7941
[]
no_license
da-x-ace/openSSL-compatible-RSA-Engine
2c313fb693d23c4bab44cf399c0c0c62ab30d70d
899676109e699b996ed65fa73ef51ab94084f2c1
refs/heads/master
2016-08-03T14:43:15.560671
2013-01-31T02:44:14
2013-01-31T02:44:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
70,661
cpp
#include <iostream> #include <stdio.h> #include <gmp.h> #include <string.h> #include <vector> #include <fstream> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <openssl/evp.h> #include <sys/syscall.h> #include <openssl/sha.h> #define MODULUSSIZE 1024 //No. of bits in n #define SIZE (MODULUSSIZE/8) //No of bytes in n #define PRIMEBITS (MODULUSSIZE/2) #define BUFSIZE (MODULUSSIZE/8)/2 #define MSGSIZE SIZE-11 //MSG Length to be eligible for encrypting #define BLOCKSIZE (MODULUSSIZE/8)/2 #define OCTET 8 #define MD5SUM_BYTES 16 #define SIGNSIZE SIZE #define ENCRYPT 0 #define DEBUG 0 using namespace std; unsigned char* gen_md5_digest(char *); typedef unsigned char uint8_t ; struct publicKey{ mpz_t n; mpz_t e; }; struct privateKey{ //char* header; //char* algorithm; mpz_t n; mpz_t e; mpz_t d; mpz_t p; mpz_t q; mpz_t exp1; mpz_t exp2; mpz_t u; }; static const string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } int hexToInt(string strHex) { int decimalValue = 0; sscanf(strHex.c_str(), "%x", &decimalValue); // cout<<decimalValue<<endl; return decimalValue; } struct privateKey* getPrivateStructure(mpz_t n, mpz_t e, mpz_t d,mpz_t p,mpz_t q,mpz_t exp1,mpz_t exp2, mpz_t u) { struct privateKey* priKey = (struct privateKey*)malloc(sizeof(struct privateKey)); mpz_init(priKey->n); mpz_set(priKey->n, n); mpz_init(priKey->e); mpz_set(priKey->e, e); mpz_init(priKey->d); mpz_set(priKey->d, d); mpz_init(priKey->p); mpz_set(priKey->p, p); mpz_init(priKey->q); mpz_set(priKey->q, q); mpz_init(priKey->exp1); mpz_set(priKey->exp1, exp1); mpz_init(priKey->exp2); mpz_set(priKey->exp2, exp2); mpz_init(priKey->u); mpz_set(priKey->u, u); } void freePrivateStructure(struct privateKey* priKey) { mpz_clear(priKey->p); mpz_clear(priKey->q); mpz_clear(priKey->n); mpz_clear(priKey->e); mpz_clear(priKey->d); mpz_clear(priKey->exp1); mpz_clear(priKey->exp2); mpz_clear(priKey->u); free(priKey); } vector<string> myTokenizer(char* input) { vector<string> myList; int count = 2; int index = 0; int indexTemp = 0; char temp[2]; for(int i=0; i<strlen(input); i++) { if(index < 2) { temp[indexTemp++] = input[i]; index++; } if(index==2) { myList.push_back(temp); index=0; indexTemp=0; } } return myList; } /* Computes the multiplicative inverse of a number using Euclids algorithm. Computes x such that a * x mod n = 1, where 0 < a < n. */ static void mpz_mod_inverse(MP_INT *x, MP_INT *a, MP_INT *n) { MP_INT g0, g1, v0, v1, div, mod, aux; mpz_init_set(&g0, n); mpz_init_set(&g1, a); mpz_init_set_ui(&v0, 0); mpz_init_set_ui(&v1, 1); mpz_init(&div); mpz_init(&mod); mpz_init(&aux); while (mpz_cmp_ui(&g1, 0) != 0) { mpz_divmod(&div, &mod, &g0, &g1); mpz_mul(&aux, &div, &v1); mpz_sub(&aux, &v0, &aux); mpz_set(&v0, &v1); mpz_set(&v1, &aux); mpz_set(&g0, &g1); mpz_set(&g1, &mod); } if (mpz_cmp_ui(&v0, 0) < 0) mpz_add(x, &v0, n); else mpz_set(x, &v0); mpz_clear(&g0); mpz_clear(&g1); mpz_clear(&v0); mpz_clear(&v1); mpz_clear(&div); mpz_clear(&mod); mpz_clear(&aux); } //Base64 Encoder string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } char* base64Decoder(char *input) { int length = strlen(input); int outputLength; int countPad =0; unsigned char char_array_4[4], char_array_3[3]; for(int k=length-1; k> 0 ; k--) if(input[k]=='=') countPad++; else break; // printf("Pad length = %d\n", countPad); if(countPad == 0) outputLength = (length*3)/4; else if(countPad == 1) outputLength = ((length-4)*3)/4+ 2; else if(countPad == 2) outputLength = ((length-4)*3)/4+ 1; int finalLength = 4*outputLength; char* output = new char[finalLength]; memset(output, 0, finalLength); char temp[2]; int index=0, k=0, start=0; while (k<length && ( input[k] != '=') && is_base64(input[k])) { char_array_4[index++] = input[k++]; if(index == 4) { //printf("The segment is : %s \n", char_array_4); index=0; //printf("The segment is : %c \n", char_array_4[3]); for (int j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); //printf("The segment is : %d \n", char_array_4[3]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; sprintf(temp,"%02x", char_array_3[0]); strcat(output,temp); strcat(output," "); sprintf(temp,"%02x", char_array_3[1]); strcat(output,temp); strcat(output," "); sprintf(temp,"%02x", char_array_3[2]); strcat(output,temp); strcat(output," "); //printf("The value is : %02x \n", char_array_3[0]); //printf("The value is : %02x \n", char_array_3[1]); //printf("The value is : %02x \n", char_array_3[2]); //printf("Output : %s\n", output); } } if(index) { //printf("The segment is : %s \n", char_array_4); for (start = index; start <4; start++) char_array_4[start] = 0; //printf("The segment is : %c \n", char_array_4[2]); //printf("The segment is : %c \n", char_array_4[3]); //printf("The segment is : %s \n", char_array_4); for (start = 0; start <4; start++) char_array_4[start] = base64_chars.find(char_array_4[start]); // printf("The segment is : %d \n", char_array_4[3]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; sprintf(temp,"%02x", char_array_3[0]); strcat(output,temp); strcat(output," "); sprintf(temp,"%02x", char_array_3[1]); strcat(output,temp); //strcat(output,"\n"); //sprintf(temp,"%x", char_array_3[2]); //strcat(output,temp); //printf("The value is : %c \n", char_array_3[0]); //printf("The value is : %c \n", char_array_3[1]); //printf("The value is : %c \n", char_array_3[2]); // printf("Output : \n%s\n", output); } #if DEBUG printf("Output : \n%s\n", output); #endif return output; } int TLVHeaderDecoder(vector<string> myList, int start,int size, string& TLVLength) { int type = hexToInt(myList[start]); int length= hexToInt(myList[start+1]); #if DEBUG printf("Hiii = %d\n",hexToInt(myList[start+1])); #endif int blocksLength = 0; int index; if(length > 128) { blocksLength = length - 128; index = start+2; for(int i=0; i< blocksLength; i++) TLVLength = TLVLength + myList[index++]; #if DEBUG printf("Length = %s\n", TLVLength.c_str()); printf("Index = %d\n", index); #endif return index; } else { TLVLength = myList[start+1]; index = start+2; //printf("Index = %d\n", index); return index; } } int TLVDecoder(vector<string> myList, int start, int size, string& TLVLength, string& TLVValue) { int type = hexToInt(myList[start]); int length= hexToInt(myList[start+1]); int blocksLength = 0; int index; if(length > 128) { blocksLength = length - 128; index = start+2; for(int i=0; i< blocksLength; i++) TLVLength = TLVLength + myList[index++]; // printf("Length = %d\n", hexToInt(TLVLength)); // printf("Index = %d\n", index); for(int i=0; i<hexToInt(TLVLength); i++) { TLVValue = TLVValue+myList[index++]; } //cout<<TLVValue<<endl; return index; } else { TLVLength = myList[start+1]; index = start+2; #if DEBUG printf("Index TLV LEngth = %s\n", TLVLength.c_str()); #endif for(int i=0; i<hexToInt(TLVLength); i++) { TLVValue = TLVValue+myList[index++]; } // cout<<TLVValue<<endl; return index; } } struct publicKey* decodePublicKey(char* input) { vector<string> myList; char* parts; parts = strtok(input," "); while(parts) { //printf("%s\n",parts); myList.push_back(parts); parts = strtok(NULL," "); } #if DEBUG printf("Size of the vector: %d\n", myList.size()); #endif int value=0; string myTypeValue[2], mytempTypeValue; string myTypeLength[2], mytempTypeLength; string headerLength; string tempheaderLength; value = TLVHeaderDecoder(myList, value, 2, tempheaderLength); #if DEBUG printf("Index = %d\n", value); #endif value = TLVDecoder(myList, value, 2, mytempTypeLength, mytempTypeValue); // printf("Check best Index = %d\n", value); value = TLVHeaderDecoder(myList, value, 2, tempheaderLength); #if DEBUG printf("Index = %d\n", value); #endif value++; #if DEBUG printf("This Index = %d\n", value); #endif value = TLVHeaderDecoder(myList, value, 2, tempheaderLength); #if DEBUG printf("Index = %d\n", value); #endif for(int i=0; i<2; i++) { value = TLVDecoder(myList, value, 2, myTypeLength[i], myTypeValue[i]); #if DEBUG printf("you Index = %d\n", value); #endif } struct publicKey* pubKey = (struct publicKey*)malloc(sizeof(struct publicKey)); mpz_init(pubKey->n); mpz_init_set_str(pubKey->n, myTypeValue[0].c_str(), 16); mpz_init(pubKey->e); mpz_init_set_str(pubKey->e, myTypeValue[1].c_str(), 16); #if DEBUG gmp_printf("\n%Zd\n", pubKey->n); gmp_printf("\n%Zd\n", pubKey->e); #endif //if(mpz_cmp) //*n = pubKey->n; //*e = pubKey->e; //mpz_clear(pubKey->n); //mpz_clear(pubKey->e); return pubKey; } struct privateKey* decodePrivateKey(char* input) { char* parts; //Aim to fill the vector with 1 byte of hexdata vector<string> myList; parts = strtok(input," "); while(parts) { //printf("%s\n",parts); myList.push_back(parts); parts = strtok(NULL," "); } #if DEBUG printf("Size of the vector: %d\n", myList.size()); #endif int value; string myTypeValue[9]; string myTypeLength[9]; string headerLength; value = TLVHeaderDecoder(myList, 0, 2, headerLength); #if DEBUG printf("Index = %d\n", value); #endif for(int i=0; i<9; i++) { value = TLVDecoder(myList, value, 2, myTypeLength[i], myTypeValue[i]); #if DEBUG printf("Index = %d\n", value); #endif } struct privateKey* priKey = (struct privateKey*)malloc(sizeof(struct privateKey)); mpz_init(priKey->n); mpz_init_set_str(priKey->n, myTypeValue[1].c_str(), 16); mpz_init(priKey->e); mpz_init_set_str(priKey->e, myTypeValue[2].c_str(), 16); mpz_init(priKey->d); mpz_init_set_str(priKey->d, myTypeValue[3].c_str(), 16); mpz_init(priKey->p); mpz_init_set_str(priKey->p, myTypeValue[4].c_str(), 16); mpz_init(priKey->q); mpz_init_set_str(priKey->q, myTypeValue[5].c_str(), 16); mpz_init(priKey->exp1); mpz_init_set_str(priKey->exp1, myTypeValue[6].c_str(), 16); mpz_init(priKey->exp2); mpz_init_set_str(priKey->exp2, myTypeValue[7].c_str(), 16); mpz_init(priKey->u); mpz_init_set_str(priKey->u, myTypeValue[8].c_str(), 16); //mpz_t n; mpz_init(n); mpz_init_set_str(n, myTypeValue[1].c_str(), 16); mpz_t p; mpz_init(p); mpz_init_set_str(p, myTypeValue[4].c_str(), 16); mpz_t q; mpz_init(q); mpz_init_set_str(q, myTypeValue[5].c_str(), 16); mpz_t temp; mpz_init(temp); mpz_mul(temp, p, q); //gmp_printf("\n%Zd\n", priKey->n); //gmp_printf("\n%Zd\n", temp); mpz_clear(p); mpz_clear(q); return priKey; /* mpz_clear(priKey->p); mpz_clear(priKey->q); mpz_clear(priKey->n); mpz_clear(priKey->e); mpz_clear(priKey->d); mpz_clear(priKey->exp1); mpz_clear(priKey->exp2); mpz_clear(priKey->u); mpz_clear(temp); */ } //Certificate related stuff struct tlv{ string t; string l; string v; }; struct seq2{ string t; string l; struct tlv first; struct tlv second; }; struct set{ string t; string l; struct seq2 sequence; }; struct sequence_7{ string t; string l; struct set setArray[7]; }; struct keyInfoSeq{ string t; string l; struct seq2 sequence; struct set keyInfo; }; struct sequence1{ string t; string l; struct tlv myInt; struct seq2 s_1; struct sequence_7 s_2; struct seq2 s_3; struct sequence_7 s_4; struct keyInfoSeq s_5; }; struct certificate{ string t; string l; struct sequence1 s1; struct seq2 s2; struct tlv s3; }; int TLVHeaderDecoderNew(vector<string> myList, int start,int size, string& TLVTag, string& TLVLength) { int type = hexToInt(myList[start]); TLVTag = myList[start]; int length= hexToInt(myList[start+1]); int blocksLength = 0; int index; if(length > 128) { blocksLength = length - 128; index = start+2; for(int i=0; i< blocksLength; i++) TLVLength = TLVLength + myList[index++]; //printf("Length = %d\n", hexToInt(TLVLength)); //printf("Index = %d\n", index); return index; } else { TLVLength = myList[start+1]; index = start+2; //printf("Index = %d\n", index); return index; } } int TLVDecoderNew(vector<string> myList, int start, int size,string& TLVTag, string& TLVLength, string& TLVValue) { int type = hexToInt(myList[start]); TLVTag = myList[start]; int length= hexToInt(myList[start+1]); int blocksLength = 0; int index; if(length > 128) { blocksLength = length - 128; index = start+2; for(int i=0; i< blocksLength; i++) TLVLength = TLVLength + myList[index++]; // printf("Length = %d\n", hexToInt(TLVLength)); // printf("Index = %d\n", index); for(int i=0; i<hexToInt(TLVLength); i++) { TLVValue = TLVValue+myList[index++]; } //cout<<TLVValue<<endl; return index; } else { TLVLength = myList[start+1]; index = start+2; //printf("Index = %d\n", index); for(int i=0; i<hexToInt(TLVLength); i++) { TLVValue = TLVValue+myList[index++]; } // cout<<TLVValue<<endl; return index; } } struct seq2 sequenceWith2(vector<string> myList, int start, int& index) { int type; int length; //int index; string myTypeTag[2]; string myTypeValue[2]; string myTypeLength[2]; string headerLength; string headerType; struct seq2 mySeq; struct tlv myTLV[2]; index = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength); //printf("Index = %d\n", index); mySeq.t = headerType; mySeq.l = headerLength; //printf("Type:%s ", mySeq.t.c_str()); //printf("Length:%s\n", mySeq.l.c_str()); for(int i=0; i<2; i++) { //myTLV[i] = (struct tlv*) malloc(sizeof(struct tlv)); index = TLVDecoderNew(myList, index, 2, myTypeTag[i], myTypeLength[i], myTypeValue[i]); myTLV[i].t = myTypeTag[i]; myTLV[i].l = myTypeLength[i]; myTLV[i].v = myTypeValue[i]; if(i==0) mySeq.first = myTLV[i]; else mySeq.second = myTLV[i]; //free(myTLV); // printf("Index = %d\n", index); } //printf("Value 1:\n%s\n", (mySeq.first.v).c_str()); //printf("Value 2:\n%s\n", (mySeq.second.v).c_str()); //inputSeq = mySeq; //free(mySeq); return mySeq; } struct set makeSet(vector<string> myList, int start, int& value) { struct set mySet; struct seq2 mySeq; string headerLength; string headerType; start = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength); #if DEBUG printf("Index = %d\n", start); #endif mySet.t = headerType; mySet.l = headerLength; if(hexToInt(headerType) == 3) start++; mySeq = sequenceWith2(myList, start, value); mySet.sequence = mySeq; //printf("Value 1:\n%s\n", (mySet.sequence.first.v).c_str()); //printf("Value 2:\n%s\n", (mySet.sequence.second.v).c_str()); //printf("Index = %d\n", value); //return value; return mySet; } int decodeLargeSequence(vector<string> myList, int start, struct sequence_7& bigSeq) { //struct sequence_7 bigSeq; string headerLength; string headerType; struct set mySet[8]; start = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength); bigSeq.t = headerType; bigSeq.l = headerLength; //printf("Value 1:\n%s\n", bigSeq.t.c_str()); //printf("Value 2:\n%s\n", bigSeq.l.c_str()); int lengthSub = hexToInt(headerLength); //printf("Length of subsequence: %d\n", lengthSub); int offset = lengthSub+start; //printf("Index before offset= %d\n", start); int value = start; for(int i=0; i<8, value<offset; i++) { mySet[i] = makeSet(myList, value, start); bigSeq.setArray[i] = mySet[i]; value = start; //printf("Length at bigSeq for i= %d is %d\n", i, value); } //printf("Some random check : %s \n", bigSeq.setArray[3].sequence.first.v.c_str()); #if DEBUG printf("Index = %d\n", start); #endif return start; } int decodeAlgo(vector<string> myList, int start, struct seq2& seqAlgo) { int index=0; seqAlgo= sequenceWith2(myList,start,index); #if DEBUG printf("Algo type = %s\n", seqAlgo.first.v.c_str()); #endif return index; } int decodeTimeValidity(vector<string> myList, int start, struct seq2& timeValidity) { int index=0; timeValidity= sequenceWith2(myList,start,index); //printf("Time type = %s\n", timeValidity.first.t.c_str()); return index; } int decodeKeySequence(vector<string> myList, int start, struct keyInfoSeq& keyInformation) { string headerLength; string headerType; struct seq2 myObj; struct set keyInfoString; start = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength); keyInformation.t = headerType; keyInformation.l = headerLength; #if DEBUG printf("Index in decode key sequence = %d\n", start); #endif int index = start; myObj = sequenceWith2(myList,start,index); start = index; #if DEBUG printf("Index in decode key sequence = %d\n", start); #endif keyInfoString = makeSet(myList,start,index); keyInformation.sequence=myObj; keyInformation.keyInfo = keyInfoString; #if DEBUG printf("Check for key : %s\n", keyInformation.keyInfo.sequence.second.v.c_str()); printf("Index in decode key sequence = %d\n", index); #endif return index; } int sequence1Decoder(vector<string> myList, int value, struct sequence1& s1) { string myTypeTag[2]; string myTypeLength[2]; string myTypeValue[2]; value = TLVHeaderDecoderNew(myList, value, 2, myTypeTag[0], myTypeLength[0]); #if DEBUG printf("Index = %d\n", value); #endif s1.t = myTypeTag[0]; s1.l = myTypeLength[0]; value = TLVDecoderNew(myList, value, 2, myTypeTag[1], myTypeLength[1], myTypeValue[1]); #if DEBUG printf("Index = %d\n", value); #endif struct tlv myInteger; myInteger.t= myTypeTag[1]; myInteger.l = myTypeLength[1]; myInteger.v = myTypeValue[1]; s1.myInt = myInteger; #if DEBUG printf("Check Integer value= %s\n", s1.myInt.v.c_str()); printf("length = %s\n", myTypeValue[1].c_str()); #endif //Validity Set sequence struct seq2 seqAlgo; value = decodeAlgo(myList, value, seqAlgo); #if DEBUG printf("Index = %d\n", value); #endif s1.s_1 = seqAlgo; #if DEBUG printf("Check Algo Value= %s\n", s1.s_1.first.v.c_str()); #endif //After NULL //First 7 element set struct sequence_7 bigSeq1; value = decodeLargeSequence(myList, value, bigSeq1); #if DEBUG printf("Index = %d\n", value); #endif s1.s_2 = bigSeq1; #if DEBUG printf("Check sequence 7 first value= %s\n", s1.s_2.setArray[0].sequence.first.v.c_str()); #endif //printf("IMP check sequence 7 first value= %s\n", s1.s_2.setArray[7].sequence.first.v.c_str()); //printf("Some random check : %s \n", bigSeq1.setArray[3].sequence.first.v.c_str()); //Validity Set sequence struct seq2 seqValidity; value = decodeTimeValidity(myList, value, seqValidity); //printf("Index = %d\n", value); s1.s_3 = seqValidity; //printf("Check time validity= %s\n", s1.s_3.first.v.c_str()); //Second 7 element set struct sequence_7 bigSeq2; value = decodeLargeSequence(myList, value, bigSeq2); //printf("Index = %d\n", value); s1.s_4 = bigSeq2; #if DEBUG printf("Check sequence 7 second= %s\n", s1.s_4.setArray[0].sequence.first.v.c_str()); #endif //Decode double sequence struct keyInfoSeq keyInformation; value = decodeKeySequence(myList, value, keyInformation); #if DEBUG printf("Index = %d\n", value); #endif s1.s_5 = keyInformation; #if DEBUG printf("Check public key= %s\n", s1.s_5.keyInfo.sequence.first.v.c_str()); #endif return value; } int sequence2Decoder(vector<string> myList, int start, struct seq2& s2) { int index=0; s2= sequenceWith2(myList,start,index); #if DEBUG printf("Sequence 2 = %s\n", s2.first.v.c_str()); #endif return index; } struct certificate decodeX509(char* input) { vector<string> myList; char* parts; parts = strtok(input," "); while(parts) { //printf("%s\n",parts); myList.push_back(parts); parts = strtok(NULL," "); } //printf("Size of the vector: %d\n", myList.size()); struct certificate X509Structure; int value; string myTypeTag; string myTypeValue; string myTypeLength; string headerLength; value = TLVHeaderDecoder(myList, 0, 2, headerLength); #if DEBUG printf("Index = %d\n", value); #endif X509Structure.t = "30"; X509Structure.l = headerLength; struct sequence1 s1; value = sequence1Decoder(myList, value, s1); #if DEBUG printf("Index = %d\n", value); //printf("length = %s\n", headerLength.c_str()); //printf("length = %d\n", hexToInt(headerLength)); #endif struct seq2 s2; value = sequence2Decoder(myList, value, s2); #if DEBUG printf("Index = %d\n", value); #endif struct tlv s3; value = TLVDecoderNew(myList, value, 2, myTypeTag, myTypeLength, myTypeValue); #if DEBUG printf("Index = %d\n", value); #endif s3.t= myTypeTag; s3.l = myTypeLength; s3.v = myTypeValue; X509Structure.s1 = s1; X509Structure.s2 = s2; X509Structure.s3 = s3; return X509Structure; } struct publicKey* extractKeysFromCertificate(struct certificate cert) { int fp; #if DEBUG printf("Check modulus key= %s\n", cert.s1.s_5.keyInfo.sequence.first.v.c_str()); printf("Check e key= %s\n", cert.s1.s_5.keyInfo.sequence.second.v.c_str()); #endif struct publicKey* pubKey = (struct publicKey*)malloc(sizeof(struct publicKey)); mpz_init(pubKey->n); mpz_init_set_str(pubKey->n, cert.s1.s_5.keyInfo.sequence.first.v.c_str(), 16); mpz_init(pubKey->e); mpz_init_set_str(pubKey->e, cert.s1.s_5.keyInfo.sequence.second.v.c_str(), 16); #if DEBUG gmp_printf("\n%Zd\n", pubKey->n); gmp_printf("\n%Zd\n", pubKey->e); printf("Length of the certificate = %d\n", hexToInt(cert.l)); //printf("Length of the certificate = %s\n", cert.l.c_str()); #endif /*int index=0; fp =open("parseCert",O_WRONLY|O_CREAT); if ( fp < 0 ) { printf("unable to open file\n"); } write(fp, "Certificate:\n",13); write(fp, ); close(fp);*/ return pubKey; } //End the certificate related stuff uint8_t generateNonZeroOctet() { srand(time(NULL)); uint8_t temp = rand()% 0xFF; while(temp == 0x00) temp = rand()% 0xFF; temp |= 0x11; return temp; } uint8_t* rsaEncryption(mpz_t n,mpz_t e,char* m,int mLen) { uint8_t* EM = new uint8_t[SIZE]; memset(EM, 0, SIZE); uint8_t zeroByte=0x00; uint8_t padStart=0x02; uint8_t temp; uint8_t* msg = (uint8_t*)m; int start =0; int index=0; EM[index++]=zeroByte; EM[index++]=padStart; int padLen = SIZE - mLen -3; for(int i=0; i<padLen; i++) { temp =generateNonZeroOctet(); EM[index++]=temp; } EM[index++]=zeroByte; while(index<SIZE) EM[index++]=msg[start++]; #if DEBUG cout<<endl<<"Encryption thing"<<endl; #endif //for(int i=0; i<SIZE; i++) // printf("%02x", EM[i]); //cout<<endl; mpz_t msgNum; mpz_init(msgNum); mpz_t cipherNum; mpz_init(cipherNum); mpz_import(msgNum, SIZE, 1, sizeof(EM[0]),0,0, EM); #if DEBUG gmp_printf("\n%Zd\n", msgNum); printf("Size of the number : %d\n", mpz_sizeinbase(msgNum, 2)); #endif mpz_powm(cipherNum,msgNum,e,n); size_t cipherLen; uint8_t* cipher= (uint8_t *)mpz_export(NULL,&cipherLen,1,1,0,0,cipherNum); #if DEBUG printf("The length of the ciphertext = %d\n", cipherLen); #endif if(cipherLen != SIZE) { printf("Encryption Failed: Cipher Length != BitRsa/8"); } mpz_clear(msgNum); mpz_clear(cipherNum); return cipher; } uint8_t* leftPad(uint8_t* temp, int length, int size) { uint8_t* array = new uint8_t[size]; int diff = size-length; memset(array,0, size); memcpy(array+diff,temp, length); return array; } uint8_t* rsaDecryption(mpz_t n, mpz_t d, uint8_t* cipher, int* finalLength) { mpz_t cipherNum; mpz_init(cipherNum); mpz_t msgNum; mpz_init(msgNum); mpz_import(cipherNum, SIZE, 1, sizeof(cipher[0]),0,0, cipher); mpz_powm(msgNum, cipherNum, d, n); //gmp_printf("\n%Zd\n", msgNum); size_t msgLen; uint8_t* tempMsg= (uint8_t *)mpz_export(NULL,&msgLen,1,1,0,0,msgNum); //printf("The length of the message = %d\n", msgLen); uint8_t* msg; if(msgLen < SIZE) { msg = leftPad(tempMsg, msgLen, SIZE); msgLen = SIZE; } else if (msgLen == SIZE) { msg = tempMsg; } else { printf("Decryption Failed:The size of the ecrypted message > BitRsa/8"); } //for(int i=0; i<msgLen; i++) // printf("%02x", msg[i]); //cout<<endl; //Checks for the added padding while encrypting int index=0; if(msg[index++] != 0x00) { printf("Decryption Failed: First Byte != 0x00"); return NULL; } if(msg[index++] != 0x02) { printf("Decryption Failed: Second Byte != 0x02"); return NULL; } int countNonZero =0; while(msg[index++] != 0x00) { countNonZero++; } if(countNonZero <= 8) { printf("Decryption Failed: The psuedo random padding < 8"); return NULL; } #if DEBUG for(int i=0; i<SIZE; i++) printf("%02x",msg[i]); cout<<endl; #endif uint8_t* m = new uint8_t[SIZE]; memset(m, 0, SIZE); int j=0; int k=index; for(int i=index; i<SIZE; i++) m[j++]=msg[index++]; //m[j]='\0'; //memcpy *finalLength = SIZE-k; return m; } string TLVEncoderHeader(int length) { string format; char buf[2]; char typeHeader[2]; sprintf(typeHeader, "%02x", 48); format += typeHeader; if((length/2) <= 127) { sprintf(buf, "%02x", length/2); format += buf; } else if((length/2) < 65536) { if((length/2) < 256) { sprintf(buf, "%02x", 129); format += buf; sprintf(buf, "%02x", length/2); format += buf; } else { sprintf(buf, "%02x", 130); format += buf; char newBuf[4]; sprintf(newBuf, "%04x", length/2); format += newBuf; } } else { printf("Write code for this also x-( \n"); } return format; } string TLVEncoder(char *input) { int length = strlen(input); #if DEBUG printf("Length is = %d of \n%s\n", length, input); #endif string format; char *value; char firstChar; int temp=0; if(length%2) { value = (char *)malloc(length+2); memset(value, 0, length+2); value[0] = '0'; memcpy((value+1),input, length); } else { //value = input; //strcat(value, input); firstChar = input[0]; #if DEBUG printf("%c\n", firstChar); #endif if(isdigit(firstChar) && (temp=firstChar - '0')< 8) { #if DEBUG printf("No 00 \n"); #endif value = (char *)malloc(length+1); memset(value, 0, length+1); memcpy((value),input, length); } else { #if DEBUG printf("yes 00 \n"); #endif value = (char *)malloc(length+3); memset(value, 0, length+3); value[0] = '0'; value[1] = '0'; memcpy((value+2),input, length); } } length = strlen(value); //printf("%s\n", value); //printf("%d\n", length); char buf[2]; sprintf(buf, "%02x", 2); format += buf; if((length/2) <= 127) { sprintf(buf, "%02x", length/2); format += buf; } else if((length/2) < 65536) { if((length/2) < 256) { sprintf(buf, "%02x", 129); format += buf; sprintf(buf, "%02x", length/2); format += buf; } else { sprintf(buf, "%02x", 130); format += buf; char newBuf[4]; sprintf(newBuf, "%04x", length/2); format += newBuf; } } else { printf("Write code for this also x-( \n"); } format +=value; #if DEBUG cout<<"Format :"<<endl<<format<<endl<<endl; cout<<"Length : "<<format.size()<<endl<<endl; #endif return format; } uint8_t* NewEncoder(uint8_t *input, size_t length, size_t* outputSize) { uint8_t *output; int flag=0; size_t outputLength = length; size_t tempLength = length; //printf("%02x\n", input[0]); uint8_t first = input[0] & 0x80; //printf("%02x\n", first); //printf("Length is :%d\n", length); if(first == 0x80) { outputLength++; flag=1; } tempLength = outputLength; if(outputLength <=127) { outputLength++; } else if(outputLength > 127 && outputLength <= 255) { outputLength= outputLength+2; } else if(outputLength < 65536) { outputLength = outputLength+3; } outputLength = outputLength+1; //For byte of header output = new uint8_t[outputLength]; int index=0; output[index++]=0x02; if(tempLength <=127) { output[index++]=(uint8_t)tempLength; } else if(tempLength > 127 && tempLength <= 255) { output[index++]=0x81; output[index++]=(uint8_t)(tempLength); } else if(tempLength < 65536) { output[index++]=0x82; output[index++]=(uint8_t)((tempLength & 0x0000ff00) >> 8); output[index++]=(uint8_t)(tempLength); } if(flag==1) output[index++]=0x00; for(int i=0; i< length; i++) output[index++]=input[i]; #if DEBUG for(int i=0; i<outputLength; i++) printf("%02x", output[i]); cout<<endl; #endif *outputSize = outputLength; return output; } uint8_t* NewHeaderEncoder(size_t length, size_t* outputSize) { uint8_t *output; int flag=0; size_t outputLength = 0; size_t tempLength = length; //printf("%02x\n", input[0]); //printf("Length is :%d\n", length); if(tempLength <=127) { outputLength++; } else if(tempLength > 127 && tempLength <= 255) { outputLength= outputLength+2; } else if(tempLength < 65536) { outputLength = outputLength+3; } outputLength = outputLength+1; //For byte of header output = new uint8_t[outputLength]; int index=0; output[index++]=0x30; if(tempLength <=127) { output[index++]=(uint8_t)tempLength; } else if(tempLength > 127 && tempLength <= 255) { output[index++]=0x81; output[index++]=(uint8_t)(tempLength); } else if(tempLength < 65536) { output[index++]=0x82; output[index++]=(uint8_t)((tempLength & 0x0000ff00) >> 8); output[index++]=(uint8_t)(tempLength); } #if DEBUG for(int i=0; i<outputLength; i++) printf("%02x", output[i]); cout<<endl; #endif *outputSize = outputLength; return output; } uint8_t* BitStringHeaderEncoder(size_t length, size_t* outputSize) { uint8_t *output; int flag=0; size_t outputLength = 0; size_t tempLength = length; //printf("%02x\n", input[0]); //printf("Length is :%d\n", length); if(tempLength <=127) { outputLength++; } else if(tempLength > 127 && tempLength <= 255) { outputLength= outputLength+2; } else if(tempLength < 65536) { outputLength = outputLength+3; } outputLength = outputLength+1; //For byte of header output = new uint8_t[outputLength]; int index=0; output[index++]=0x03; if(tempLength <=127) { output[index++]=(uint8_t)tempLength; } else if(tempLength > 127 && tempLength <= 255) { output[index++]=0x81; output[index++]=(uint8_t)(tempLength); } else if(tempLength < 65536) { output[index++]=0x82; output[index++]=(uint8_t)((tempLength & 0x0000ff00) >> 8); output[index++]=(uint8_t)(tempLength); } #if DEBUG for(int i=0; i<outputLength; i++) printf("%02x", output[i]); cout<<endl; #endif *outputSize = outputLength; return output; } void encodePublicKey(mpz_t n, mpz_t e, char* publicKeyFileName) { //Modulus size_t mod_size; uint8_t *modulus_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,n); size_t nSize=0; uint8_t* nBytes = NewEncoder(modulus_bytes, mod_size, &nSize); // printf("Output Length is :%d\n\n", nSize); uint8_t *e_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,e); size_t eSize=0; uint8_t* eBytes = NewEncoder(e_bytes, mod_size, &eSize); // printf("Output Length is :%d\n\n", eSize); //Without Header size_t hSize = nSize+eSize; // cout<<"Length of the document w/o header length "<<hSize<<endl; //Header size_t hLength=0; uint8_t *hBytes = NewHeaderEncoder(hSize, &hLength); // printf("Output Length is :%d\n\n", hLength); //Total size_t docSize = hLength+hSize; // printf("Document size is :%d\n\n", docSize); uint8_t *docBytes = new uint8_t[docSize+22]; memset(docBytes,0, sizeof(uint8_t)*(docSize+22)); //int count=0; // while(count<docSize) int index=0; docBytes[index++]=0x30; docBytes[index++]=0x81; docBytes[index++]=0x9f; docBytes[index++]=0x30; docBytes[index++]=0x0d; docBytes[index++]=0x06; docBytes[index++]=0x09; docBytes[index++]=0x2a; docBytes[index++]=0x86; docBytes[index++]=0x48; docBytes[index++]=0x86; docBytes[index++]=0xf7; docBytes[index++]=0x0d; docBytes[index++]=0x01; docBytes[index++]=0x01; docBytes[index++]=0x01; docBytes[index++]=0x05; docBytes[index++]=0x00; docBytes[index++]=0x03; docBytes[index++]=0x81; docBytes[index++]=0x8d; docBytes[index++]=0x00; { memcpy(docBytes+index, hBytes, hLength); memcpy(docBytes+index+hLength, nBytes, nSize); memcpy(docBytes+index+hLength+nSize, eBytes, eSize); } /*for(int i=0; i<(docSize+index++); i++) printf("%02x", docBytes[i]); cout<<endl<<endl; */ docSize = docSize+index++; int DERFile; // for(int i=0; i<docSize; i++) // printf("%02x", docBytes[i]); DERFile =open("public_1k.der",O_WRONLY|O_CREAT); if ( DERFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<docSize; i++) write(DERFile, (const void*)&docBytes[i], 1); close(DERFile); string encoded = base64_encode(reinterpret_cast<const unsigned char*>(docBytes),docSize); // cout<<endl<<"Base64Coded string is:"<<endl<<encoded<<endl; int PEMFile; int counter = 0; index=0; const char* startPEM ="-----BEGIN PUBLIC KEY-----"; const char* endPEM="-----END PUBLIC KEY-----"; int encodedLength = encoded.size(); // printf("The size of encoded string is : %d\n", encodedLength); char* base64encoded = (char*)(encoded.c_str()); PEMFile =open(publicKeyFileName,O_RDWR|O_CREAT); if ( PEMFile < 0 ) { printf("unable to open file\n"); } write(PEMFile, startPEM, strlen(startPEM)); write(PEMFile,"\n", 1); for(int i=0; i<encodedLength ; i++) { write(PEMFile,(const char*)&base64encoded[i], 1); counter++; if(counter == 64) { counter=0; write(PEMFile,"\n", 1); } } write(PEMFile,"\n", 1); write(PEMFile, endPEM, strlen(endPEM)); write(PEMFile,"\n", 1); close(PEMFile); } void encodePrivateKey(mpz_t n, mpz_t pub_key, mpz_t pri_key, mpz_t p, mpz_t q, mpz_t exp1, mpz_t exp2, mpz_t coef, char* privateKeyFileName) { //Algorithm uint8_t aBytes[3]; aBytes[0]=0x02; aBytes[1]=0x01; aBytes[2]=0x00; size_t aSize=3; string algoString; algoString="020100"; size_t mod_size; //Modulus uint8_t *modulus_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,n); size_t nSize=0; uint8_t* nBytes = NewEncoder(modulus_bytes, mod_size, &nSize); // printf("Output Length is :%d\n\n", nSize); /* for(int i=0; i<nSize; i++) printf("%02x", nBytes[i]); cout<<endl; */ //string checkString = TLVEncoder((char *)modulus_bytes); //string nString; //nString = TLVEncoder(mpz_get_str(NULL, 16, n)); //Public key uint8_t *e_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,pub_key); size_t eSize=0; uint8_t* eBytes = NewEncoder(e_bytes, mod_size, &eSize); // printf("Output Length is :%d\n\n", eSize); //string eString; //eString = TLVEncoder(mpz_get_str(NULL, 16, pub_key)); //Private Key uint8_t *d_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,pri_key); size_t dSize=0; uint8_t* dBytes = NewEncoder(d_bytes, mod_size, &dSize); // printf("Output Length is :%d\n\n", dSize); //string dString; //dString = TLVEncoder(mpz_get_str(NULL, 16, pri_key)); //Prime p uint8_t *p_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,p); size_t pSize=0; uint8_t* pBytes = NewEncoder(p_bytes, mod_size, &pSize); // printf("Output Length is :%d\n\n", pSize); //string pString; //pString = TLVEncoder(mpz_get_str(NULL, 16, p)); //Prime q uint8_t *q_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,q); size_t qSize=0; uint8_t* qBytes = NewEncoder(q_bytes, mod_size, &qSize); // printf("Output Length is :%d\n\n", qSize); //string qString; //qString = TLVEncoder(mpz_get_str(NULL, 16, q)); //CRT EXP1 uint8_t *exp1_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,exp1); size_t exp1Size=0; uint8_t* exp1Bytes = NewEncoder(exp1_bytes, mod_size, &exp1Size); // printf("Output Length is :%d\n\n", exp1Size); //string exp1String; //exp1String = TLVEncoder(mpz_get_str(NULL, 16, exp1)); //CRT EXP2 uint8_t *exp2_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,exp2); size_t exp2Size=0; uint8_t* exp2Bytes = NewEncoder(exp2_bytes, mod_size, &exp2Size); // printf("Output Length is :%d\n\n", exp2Size); //string exp2String; //exp2String = TLVEncoder(mpz_get_str(NULL, 16, exp2)); //CRT COEF uint8_t *u_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,coef); size_t uSize=0; uint8_t* uBytes = NewEncoder(u_bytes, mod_size, &uSize); // printf("Output Length is :%d\n\n", uSize); //string uString; //uString = TLVEncoder(mpz_get_str(NULL, 16, coef)); //Without Header size_t hSize = aSize+nSize+eSize+dSize+pSize+qSize+exp1Size+exp2Size+uSize; // cout<<"Length of the document w/o header length "<<hSize<<endl; //string totalWithoutHeader; //totalWithoutHeader = algoString+nString+eString+dString+pString+qString+exp1String+exp2String+uString; //int headerLength = totalWithoutHeader.size(); //cout<<"Length of the document = header length "<<headerLength<<endl; cout<<endl<<endl; //cout<<totalWithoutHeader<<endl; //Header size_t hLength=0; uint8_t *hBytes = NewHeaderEncoder(hSize, &hLength); // printf("Output Length is :%d\n\n", hLength); //Total size_t docSize = hLength+hSize; // printf("Document size is :%d\n\n", docSize); uint8_t *docBytes = new uint8_t[docSize]; memset(docBytes,0, sizeof(uint8_t)*docSize); //int count=0; // while(count<docSize) { memcpy(docBytes, hBytes, hLength); memcpy(docBytes+hLength, aBytes, aSize); memcpy(docBytes+hLength+aSize, nBytes, nSize); memcpy(docBytes+hLength+aSize+nSize, eBytes, eSize); memcpy(docBytes+hLength+aSize+nSize+eSize, dBytes, dSize); memcpy(docBytes+hLength+aSize+nSize+eSize+dSize, pBytes, pSize); memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize, qBytes, qSize); memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize+qSize, exp1Bytes, exp1Size); memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize+qSize+exp1Size, exp2Bytes, exp2Size); memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize+qSize+exp1Size+exp2Size, uBytes, uSize); } #if DEBUG for(int i=0; i<docSize; i++) printf("%02x", docBytes[i]); cout<<endl<<endl; #endif //string headerString; //headerString = TLVEncoderHeader(headerLength); //cout<<"Header String is : "<<headerString<<endl; //string document; //document = headerString+totalWithoutHeader; cout<<endl<<endl; //cout<<document<<endl; //ofstream HEXFile; // HEXFile.open("private_1024.hex"); // HEXFile<<document; // HEXFile.close(); /* ofstream DERFile; DERFile.open("private_1024.der"); int index = 0; vector<string> myList = myTokenizer(const_cast<char*>(document.c_str())); for (vector<string>::iterator i = myList.begin();i != myList.end();i++) { //cout<< *i <<endl; index = hexToInt(*i); DERFile << (unsigned char)index; } DERFile.close(); */ int DERFile; #if DEBUG for(int i=0; i<docSize; i++) printf("%02x", docBytes[i]); #endif DERFile =open("private_1k.der",O_RDWR|O_CREAT); if ( DERFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<docSize; i++) write(DERFile, (const void*)&docBytes[i], 1); close(DERFile); string encoded = base64_encode(reinterpret_cast<const unsigned char*>(docBytes),docSize); #if DEBUG cout<<endl<<"Base64Coded string is:"<<endl<<encoded<<endl; #endif int PEMFile; int counter = 0; int index=0; const char* startPEM ="-----BEGIN RSA PRIVATE KEY-----"; const char* endPEM="-----END RSA PRIVATE KEY-----"; int encodedLength = encoded.size(); // printf("The size of encoded string is : %d\n", encodedLength); char* base64encoded = (char*)(encoded.c_str()); int newLineCheck = encodedLength; PEMFile =open(privateKeyFileName,O_WRONLY|O_CREAT); if ( PEMFile < 0 ) { printf("unable to open file\n"); } write(PEMFile, startPEM, strlen(startPEM)); write(PEMFile,"\n", 1); for(int i=0; i<encodedLength ; i++) { write(PEMFile,(const char*)&base64encoded[i], 1); counter++; if(counter == 64) { counter=0; if( i != (newLineCheck-1)) write(PEMFile,"\n", 1); } } write(PEMFile,"\n", 1); write(PEMFile, endPEM, strlen(endPEM)); close(PEMFile); } string readPEMFile(char* inputFile) { string output; string line; ifstream myfile (inputFile); if(myfile.is_open()) { while(myfile.good()) { getline(myfile,line); //cout<<line<<endl; if(line[0]=='-') continue; output.append(line.c_str()); //output.append("\n"); //break; } #if DEBUG cout<<output<<endl; #endif myfile.close(); } #if DEBUG printf("Length of the string array : %d\n",output.size()); printf("Length of the string array to char : %d\n",strlen(output.c_str())); #endif return output; } void encrypt(char* publicPEM, char* inputFileName, char* cipherFileName) { struct publicKey* pubKey; string output = readPEMFile(publicPEM); char *decoded = base64Decoder((char *)output.c_str()); pubKey = decodePublicKey(decoded); int fmsg; int msgLen; //char* inputFileName = new char[255]; //printf("Enter the Message filename :\n"); //scanf("%s", inputFileName); fmsg = open(inputFileName, O_RDONLY); if(fmsg<0) { printf("Unable to open a read File\n"); } char* textMessage = new char[SIZE-11]; memset(textMessage, 0, SIZE-11); int numRead = read(fmsg, textMessage, SIZE-11); #if DEBUG printf("The length read from file : %d\n", strlen(textMessage)); printf("Message is:\n%s\n", textMessage); #endif msgLen = strlen(textMessage); if(msgLen > MSGSIZE) { printf("Message too large for encryption\n"); exit(1); } //gmp_printf("\n%Zd\n", pubKey->e); //gmp_printf("\n%Zd\n", pubKey->n); uint8_t* encryptedText = rsaEncryption(pubKey->n,pubKey->e,textMessage,msgLen); // printf("Returned from encryption\n"); int cipherFile; //char* cipherFileName = new char[255]; //printf("Enter the Cipher filename :\n"); //scanf("%s", cipherFileName); cipherFile =open(cipherFileName,O_RDWR|O_CREAT); if ( cipherFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<SIZE; i++) write(cipherFile, (const void*)&encryptedText[i], 1); close(cipherFile); mpz_clear(pubKey->n); mpz_clear(pubKey->e); free(pubKey); } uint8_t* rsaSignature(mpz_t n,mpz_t d,uint8_t* EM,int mLen) { mpz_t msgNum; mpz_init(msgNum); mpz_t cipherNum; mpz_init(cipherNum); mpz_import(msgNum, SIZE, 1, sizeof(EM[0]),0,0, EM); //gmp_printf("\n%Zd\n", msgNum); //printf("Size of the number : %d\n", mpz_sizeinbase(msgNum, 2)); mpz_powm(cipherNum,msgNum,d,n); size_t cipherLen; uint8_t* cipher= (uint8_t *)mpz_export(NULL,&cipherLen,1,1,0,0,cipherNum); // printf("The length of the ciphertext = %d\n", cipherLen); if(cipherLen != SIGNSIZE) { printf("Encryption Failed: Cipher Length != BitRsa/8"); } mpz_clear(msgNum); mpz_clear(cipherNum); return cipher; } uint8_t* calculateT(uint8_t* hashMessage) { uint8_t* T = new uint8_t[SIGNSIZE]; memset(T, 0, SIGNSIZE); uint8_t algoInfo[15] ={0x30,0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14}; //20+15 T[0]= 0x00; T[1]= 0x01; int lengthPS = SIZE - 35 - 3; const uint8_t constantPad = 0xff; int index=2; for(int i=0; i<lengthPS; i++) { T[index++]=0xff; } T[index++]=0x00; memcpy(T+index, algoInfo, sizeof(uint8_t)*15); memcpy(T+index+15, hashMessage, sizeof(uint8_t)*20); #if DEBUG for(int i=0; i<SIGNSIZE; i++) printf("%02x ",T[i]); printf("\n"); #endif return T; } void signMessage(char* priPEM, char* inputFileName, char* cipherFileName) { struct privateKey* priKey; string output = readPEMFile(priPEM); char *decoded = base64Decoder((char *)output.c_str()); priKey = decodePrivateKey(decoded); int fmsg; int msgLen; //char* inputFileName = new char[255]; //printf("Enter the Message filename :\n"); //scanf("%s", inputFileName); fmsg = open(inputFileName, O_RDONLY); if(fmsg<0) { printf("Unable to open a read File\n"); } char* textMessage = new char[SIGNSIZE]; memset(textMessage, 0, SIGNSIZE); int numRead = read(fmsg, textMessage, SIGNSIZE); // printf("The length read from file : %d\n", strlen(textMessage)); // printf("Message is:\n%s\n", textMessage); msgLen = strlen(textMessage); uint8_t* hashMessage = new uint8_t[20]; memset(hashMessage, 0, 20); SHA1((const unsigned char*)textMessage,msgLen, hashMessage); // printf("Hash message = %s\n", hashMessage); uint8_t* T = calculateT(hashMessage); #if DEBUG for(int i=0; i<SIGNSIZE; i++) printf("%02x ",T[i]); printf("\n"); #endif //gmp_printf("\n%Zd\n", pubKey->e); //gmp_printf("\n%Zd\n", pubKey->n); uint8_t* encryptedText = rsaSignature(priKey->n,priKey->d,T, SIZE); // printf("Returned from encryption\n"); int cipherFile; //char* cipherFileName = new char[255]; //printf("Enter the Cipher sign filename :\n"); //scanf("%s", cipherFileName); cipherFile =open(cipherFileName,O_RDWR|O_CREAT); if ( cipherFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<SIGNSIZE; i++) write(cipherFile, (const void*)&encryptedText[i], 1); close(cipherFile); freePrivateStructure(priKey); } void encryptByCertificate(char* certPEM, char* inputFileName, char* cipherFileName) { string output; string line; ifstream myfile (certPEM); if(myfile.is_open()) { while(myfile.good()) { getline(myfile,line); //cout<<line<<endl; if(line[0]=='-') continue; output.append(line.c_str()); //output.append("\n"); //break; } #if DEBUG cout<<output<<endl; #endif myfile.close(); } char *decoded = base64Decoder((char *)output.c_str()); //char *decoded = base64Decoder(input); struct certificate structure; structure = decodeX509(decoded); struct publicKey* pubKey = extractKeysFromCertificate(structure); int fmsg; int msgLen; //char* inputFileName = new char[255]; //printf("Enter the Message filename :\n"); //scanf("%s", inputFileName); fmsg = open(inputFileName, O_RDONLY); if(fmsg<0) { printf("Unable to open a read File\n"); } char* textMessage = new char[SIZE-11]; memset(textMessage, 0, SIZE-11); int numRead = read(fmsg, textMessage, SIZE-11); #if DEBUG printf("The length read from file : %d\n", strlen(textMessage)); printf("Message is:\n%s\n", textMessage); #endif msgLen = strlen(textMessage); if(msgLen > MSGSIZE) { printf("Message too large for encryption\n"); exit(1); } //gmp_printf("\n%Zd\n", pubKey->e); //gmp_printf("\n%Zd\n", pubKey->n); uint8_t* encryptedText = rsaEncryption(pubKey->n,pubKey->e,textMessage,msgLen); // printf("Returned from encryption\n"); int cipherFile; //char* cipherFileName = new char[255]; //printf("Enter the Cipher filename :\n"); //scanf("%s", cipherFileName); cipherFile =open(cipherFileName,O_WRONLY|O_CREAT); if ( cipherFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<SIZE; i++) write(cipherFile, (const void*)&encryptedText[i], 1); close(cipherFile); mpz_clear(pubKey->n); mpz_clear(pubKey->e); free(pubKey); } void decrypt(char* privatePEM, char* cipherFileName, char* decipherFileName) { struct privateKey* priKey; string output = readPEMFile(privatePEM); char *decoded = base64Decoder((char *)output.c_str()); priKey = decodePrivateKey(decoded); //char* cipherFileName = new char[255]; //printf("Enter the encrypted File name :\n"); //scanf("%s", cipherFileName); int cmsg; cmsg = open(cipherFileName, O_RDONLY); if(cmsg<0) { printf("Unable to open a read File\n"); } uint8_t* encryptedText = new uint8_t[SIZE]; memset(encryptedText, 0, SIZE); int numRead = read(cmsg, encryptedText, SIZE); //printf("The length read from file : %d\n", strlen((unsigned char *)encryptedText)); int finalLength; uint8_t* decryptedText = rsaDecryption(priKey->n, priKey->d, encryptedText, &finalLength); //printf("FinalLength = %d\n", finalLength); int decryptedFile; decryptedFile =open(decipherFileName,O_RDWR|O_CREAT); if ( decryptedFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<finalLength; i++) write(decryptedFile, (const void*)&decryptedText[i], 1); close(decryptedFile); } void rsaVerify(mpz_t n, mpz_t e, uint8_t* cipher, int* finalLength, char* inputFileName) { mpz_t cipherNum; mpz_init(cipherNum); mpz_t msgNum; mpz_init(msgNum); mpz_import(cipherNum, SIZE, 1, sizeof(cipher[0]),0,0, cipher); mpz_powm(msgNum, cipherNum, e, n); //gmp_printf("\n%Zd\n", msgNum); size_t tempmsgLen; uint8_t* tempMsg= (uint8_t *)mpz_export(NULL,&tempmsgLen,1,1,0,0,msgNum); // printf("The length of the message = %d\n", tempmsgLen); uint8_t* msg; if(tempmsgLen < SIZE) { msg = leftPad(tempMsg, tempmsgLen, SIZE); tempmsgLen = SIZE; } else if (tempmsgLen == SIZE) { msg = tempMsg; } else { printf("Decryption Failed:The size of the ecrypted message > BitRsa/8"); } int fmsg; int msgLen; //char* inputFileName = new char[255]; //printf("Enter the Message filename :\n"); //scanf("%s", inputFileName); fmsg = open(inputFileName, O_RDONLY); if(fmsg<0) { printf("Unable to open a read File\n"); } char* textMessage = new char[SIGNSIZE]; memset(textMessage, 0, SIGNSIZE); int numRead = read(fmsg, textMessage, SIGNSIZE); #if DEBUG printf("The length read from file : %d\n", strlen(textMessage)); printf("Message is:\n%s\n", textMessage); #endif msgLen = strlen(textMessage); uint8_t* hashMessage = new uint8_t[20]; memset(hashMessage, 0, 20); SHA1((const unsigned char*)textMessage,msgLen, hashMessage); // printf("Hash message = %s\n", hashMessage); uint8_t* T = calculateT(hashMessage); if(memcmp(T, msg, SIGNSIZE) == 0) { printf("\nVerification OK\n"); } else { printf("\nVerification Failure\n"); } } void verifySign(char* pubPEM, char* cipherFileName, char* inputFileName) { struct publicKey* pubKey; string output = readPEMFile(pubPEM); char *decoded = base64Decoder((char *)output.c_str()); pubKey = decodePublicKey(decoded); //char* cipherFileName = new char[255]; //printf("Enter the encrypted Sig File name :\n"); //scanf("%s", cipherFileName); int cmsg; cmsg = open(cipherFileName, O_RDONLY); if(cmsg<0) { printf("Unable to open a read File\n"); } uint8_t* encryptedText = new uint8_t[SIZE]; memset(encryptedText, 0, SIZE); int numRead = read(cmsg, encryptedText, SIZE); //printf("The length read from file : %d\n", strlen((unsigned char *)encryptedText)); int finalLength; rsaVerify(pubKey->n, pubKey->e, encryptedText, &finalLength, inputFileName); } void verifySignByCertificate(char* certPEM, char* cipherFileName, char* inputFileName) { string output; string line; ifstream myfile (certPEM); if(myfile.is_open()) { while(myfile.good()) { getline(myfile,line); //cout<<line<<endl; if(line[0]=='-') continue; output.append(line.c_str()); //output.append("\n"); //break; } #if DEBUG cout<<output<<endl; #endif myfile.close(); } char *decoded = base64Decoder((char *)output.c_str()); //char *decoded = base64Decoder(input); struct certificate structure; structure = decodeX509(decoded); struct publicKey* pubKey = extractKeysFromCertificate(structure); int cmsg; cmsg = open(cipherFileName, O_RDONLY); if(cmsg<0) { printf("Unable to open a read File\n"); } uint8_t* encryptedText = new uint8_t[SIZE]; memset(encryptedText, 0, SIZE); int numRead = read(cmsg, encryptedText, SIZE); //printf("The length read from file : %d\n", strlen((unsigned char *)encryptedText)); int finalLength; rsaVerify(pubKey->n, pubKey->e, encryptedText, &finalLength, inputFileName); } void encodePublicKeyNew(mpz_t n, mpz_t e, char* publicKeyFileName) { // printf("Public key Part\n"); //Modulus size_t mod_size; uint8_t *modulus_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,n); size_t nSize=0; uint8_t* nBytes = NewEncoder(modulus_bytes, mod_size, &nSize); #if DEBUG printf("Output Length is :%d\n\n", nSize); #endif uint8_t *e_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,e); size_t eSize=0; uint8_t* eBytes = NewEncoder(e_bytes, mod_size, &eSize); #if DEBUG printf("Output Length is :%d\n\n", eSize); #endif //Without Header size_t hSize = nSize+eSize; // cout<<"Length of the document w/o header length "<<hSize<<endl; //Header size_t hLength=0; uint8_t *hBytes = NewHeaderEncoder(hSize, &hLength); // printf("Output Length is :%d\n\n", hLength); size_t bitStringSequenceLength = hLength+hSize+1; size_t bitStringHeaderLength=0; uint8_t *bitStringBytes = BitStringHeaderEncoder(bitStringSequenceLength, &bitStringHeaderLength); #if DEBUG printf("Output Length including bit string is :%d\n\n", bitStringHeaderLength); for(int i=0; i<(bitStringHeaderLength); i++) printf("%02x", bitStringBytes[i]); cout<<endl<<endl; #endif uint8_t bitpadByte = 0x00; size_t sequenceLength = 15; size_t lengthWOHeader = sequenceLength+bitStringHeaderLength+bitStringSequenceLength; // printf("Output Length except header is :%d\n\n", lengthWOHeader); size_t docHeaderLength=0; uint8_t *startBytes = NewHeaderEncoder(lengthWOHeader, &docHeaderLength); #if DEBUG printf("Output Header Length is :%d\n\n", docHeaderLength); for(int i=0; i<(docHeaderLength); i++) printf("%02x", startBytes[i]); cout<<endl<<endl; #endif //Total size_t docSize = docHeaderLength+lengthWOHeader; // printf("Document size is :%d\n\n", docSize); uint8_t *docBytes = new uint8_t[docSize]; memset(docBytes,0, sizeof(uint8_t)*(docSize)); //int count=0; // while(count<docSize) int index=0; memcpy(docBytes, startBytes, docHeaderLength); //docBytes[index++]=0x30; //docBytes[index++]=0x81; //docBytes[index++]=0x9f; index = docHeaderLength; docBytes[index++]=0x30; docBytes[index++]=0x0d; docBytes[index++]=0x06; docBytes[index++]=0x09; docBytes[index++]=0x2a; docBytes[index++]=0x86; docBytes[index++]=0x48; docBytes[index++]=0x86; docBytes[index++]=0xf7; docBytes[index++]=0x0d; docBytes[index++]=0x01; docBytes[index++]=0x01; docBytes[index++]=0x01; docBytes[index++]=0x05; docBytes[index++]=0x00; memcpy(docBytes+index,bitStringBytes, bitStringHeaderLength); index = index+bitStringHeaderLength; //docBytes[index++]=0x03; //docBytes[index++]=0x81; //docBytes[index++]=0x8d; docBytes[index++]=0x00; { memcpy(docBytes+index, hBytes, hLength); memcpy(docBytes+index+hLength, nBytes, nSize); memcpy(docBytes+index+hLength+nSize, eBytes, eSize); } #if DEBUG for(int i=0; i<(docSize); i++) printf("%02x", docBytes[i]); cout<<endl<<endl; #endif int DERFile; // for(int i=0; i<docSize; i++) // printf("%02x", docBytes[i]); DERFile =open("public_1k.der",O_WRONLY|O_CREAT); if ( DERFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<docSize; i++) write(DERFile, (const void*)&docBytes[i], 1); close(DERFile); string encoded = base64_encode(reinterpret_cast<const unsigned char*>(docBytes),docSize); #if DEBUG cout<<endl<<"Base64Coded string is:"<<endl<<encoded<<endl; #endif int PEMFile; int counter = 0; index=0; const char* startPEM ="-----BEGIN PUBLIC KEY-----"; const char* endPEM="-----END PUBLIC KEY-----"; int encodedLength = encoded.size(); // printf("The size of encoded string is : %d\n", encodedLength); char* base64encoded = (char*)(encoded.c_str()); int newLineCheck = encodedLength; PEMFile =open(publicKeyFileName,O_RDWR|O_CREAT); if ( PEMFile < 0 ) { printf("unable to open file\n"); } write(PEMFile, startPEM, strlen(startPEM)); write(PEMFile,"\n", 1); for(int i=0; i<encodedLength ; i++) { write(PEMFile,(const char*)&base64encoded[i], 1); counter++; if(counter == 64) { counter=0; if( i != (newLineCheck-1)) write(PEMFile,"\n", 1); } } write(PEMFile,"\n", 1); write(PEMFile, endPEM, strlen(endPEM)); write(PEMFile,"\n", 1); close(PEMFile); } void genKeys(char* privateKeyFile, char* publicKeyFile) { mpz_t pub_key; mpz_init(pub_key); mpz_t pri_key; mpz_init(pri_key); mpz_t p; mpz_init(p); mpz_t q; mpz_init(q); mpz_t phi; mpz_init(phi); mpz_t n; mpz_init(n); mpz_t temp; mpz_init(temp); mpz_t temp1; mpz_init(temp1); mpz_t check; mpz_init(check); mpz_t exp1; mpz_init(exp1); mpz_t exp2; mpz_init(exp2); mpz_t coef; mpz_init(coef); char buf[BUFSIZE]; char infile[100]; char outfile[100]; FILE *fin, *fout; long lFileLen; int index=0; //Initializing my public key //65,537 mpz_set_ui(pub_key, 0x10001); #if DEBUG printf("My Public key is :"); gmp_printf("\n%Zd\n", pub_key); #endif //srand(time(NULL)); for (int i=0; i< BUFSIZE; i++) { buf[i]= rand() % 0xFF; } //Set the initial bits of the buffer to 1, so te ensure we get a relatively large number buf[0] |= 0xC0; //Set the last bit of buffer to 1, so to get an odd number buf[BUFSIZE-1] |= 0x01; //Now convert this char buffer to an int mpz_import(temp, BUFSIZE, 1, sizeof(buf[0]), 0, 0, buf); //gmp_printf("\n%Zd\n", temp); mpz_nextprime(p, temp); //gmp_printf("\n%Zd\n", p); //printf("Check if p is coprime or not, Ideally it should be :) \n"); //mpz_mod(check,p,pub_key); //gmp_printf("%Zd\n",check); //printf("......Finished checking......\n"); memset(buf, 0, sizeof(buf)); do{ for (int i=0; i< BUFSIZE; i++) { buf[i]= rand() % 0xFF; } //Set the initial bits of the buffer to 1, so te ensure we get a relatively large number buf[0] |= 0xC0; //Set the last bit of buffer to 1, so to get an odd number buf[BUFSIZE-1] |= 0x01; //Now convert this char buffer to an int mpz_import(temp, BUFSIZE, 1, sizeof(buf[0]), 0, 0, buf); // gmp_printf("\n%Zd\n", temp); mpz_nextprime(q, temp); // gmp_printf("\n%Zd\n", q); // printf("Check if q is coprime or not, Ideally it should be :) \n"); // mpz_mod(check,q,pub_key); // gmp_printf("%Zd\n",check); // printf("......Finished checking......\n"); }while(mpz_cmp(p,q) == 0); //Computing and storing the value of n = p.q mpz_mul(n,p,q); //gmp_printf("\n Value of n \n%Zd\n", n); //Compute phi = (p-1).(q-1) mpz_sub_ui(temp, p, 1); mpz_sub_ui(temp1, q, 1); mpz_mul(phi, temp, temp1); //gmp_printf("\n Value of phi \n%Zd\n", phi); //if(mpz_cmp(n,phi) > 0) // printf("\n n > phi \n"); mpz_gcd(temp, pub_key, phi); if(mpz_cmp_ui(temp,1) != 0) { printf("\n Rechoose your public key or use different primes: e mod(phi)!=1\n"); exit(0); } //Calculating private key mpz_invert(pri_key, pub_key, phi); //gmp_printf("\n Value of private key \n%Zd\n", pri_key); mpz_mul(temp, pub_key, pri_key); mpz_mod(temp1, temp, phi); gmp_printf("\n e.d mod(phi) = %Zd\n", temp1); //gmp_printf("\n%Zd\n", p); //gmp_printf("\n%Zd\n", q); //Checking p<q /*if(mpz_cmp(p,q) > 0) { mpz_set(temp, p); mpz_set(p, q); mpz_set(q, temp); }*/ //gmp_printf("\n%Zd\n", p); //gmp_printf("\n%Zd\n", q); //Generating the chinese remainder coefficient mpz_sub_ui(temp, p, 1); mpz_sub_ui(temp1, q, 1); mpz_mod(exp1, pri_key, temp); mpz_mod(exp2, pri_key, temp1); mpz_mod_inverse(coef,q ,p); encodePrivateKey(n, pub_key, pri_key, p, q, exp1, exp2, coef, privateKeyFile); encodePublicKeyNew(n, pub_key, publicKeyFile); mpz_clear(pub_key); mpz_clear(pri_key); mpz_clear(p); mpz_clear(q); mpz_clear(n); mpz_clear(phi); mpz_clear(exp1); mpz_clear(exp2); mpz_clear(coef); mpz_clear(temp); mpz_clear(temp1); mpz_clear(check); exit(0); } void printUsage(char* execName) { printf("For generating private and public key pair\n"); printf("%s genra <privateKeyFileName> <publicKeyFileName>\n", execName); printf("For encryption\n"); printf("%s -e -key <PrivatePemFile> -in PlainTextFile -out CipherTextFile\n", execName); printf("For encryption from certificate\n"); printf("%s -e -crt <Certificate> -in PlainTextFile -out CipherTextFile\n", execName); printf("For decryption\n"); printf("%s -d -key <PublicPemFile> -in CipherTextFile -out DecipheredTextFile\n", execName); printf("For Signing data with Private Key\n"); printf("%s -s -key <PrivatePemFile> -in PlainTextFile -out SignedDataFile\n", execName); printf("For Verifying data with Public Key\n"); printf("%s -v -key <PublicPemFile> -signature SignedDataFile PlainTextFile\n", execName); printf("For Verifying data with Certificate\n"); printf("%s -v -crt <Certificate> -signature SignedDataFile PlainTextFile\n", execName); exit(0); } int main(int argc, char *argv[]) { char buf[BUFSIZE], message[MSGSIZE], *cipherText, *decreptedText; FILE *fin, *fout; long lFileLen; int index=0; const char *s1,*s2,*s3; const char *s4,*s5,*s6; const char *s7, *s8, *s9; const char *s10; const char *help; help="-h"; s1 = "genrsa"; s2 = "-e"; s3 = "-d"; s4 = "-key"; s5 ="-in"; s6 = "-out"; s7 = "-crt"; s8 = "-s"; s9 = "-v"; s10= "-signature"; int argCheck =0; //Command Line options if(argc == 2) { if(strcmp(argv[1],help) == 0) { printUsage(argv[0]); } exit(0); } if (argc == 4) { if(strcmp(argv[1], s1) == 0) { printf("Usage:\n%s genrsa\n", argv[0]); genKeys((char*)argv[2], (char*)argv[3]); } else if(strcmp(argv[1],help) == 0) { printUsage(argv[0]); } else { printf("Type:\n%s -h for help commands \n", argv[0]); exit(0); } exit(0); } //printf("In ecryption\n"); if((argc == 8) && ((strcmp(argv[1],s2)==0) || (strcmp(argv[1],s3)==0))) { //printf("In ecryption\n"); if((strcmp(argv[1],s2)==0) && (strcmp(argv[2], s4)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0)) { //printf("In ecryption\n"); encrypt((char*)argv[3], (char*)argv[5], (char*)argv[7]); exit(0); } else if((strcmp(argv[1],s2)==0) && (strcmp(argv[2], s7)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0)) { encryptByCertificate((char*)argv[3], (char*)argv[5], (char*)argv[7]); exit(0); } else if((strcmp(argv[1],s3)==0) && (strcmp(argv[2], s4)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0)) { decrypt((char*)argv[3], (char*)argv[5], (char*)argv[7]); exit(0); } else { printf("Type:\n%s -h for help commands \n", argv[0]); exit(0); } } else if((argc == 8) && ((strcmp(argv[1],s8)==0))) { if((strcmp(argv[2], s4)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0)) { signMessage((char*)argv[3], (char*)argv[5], (char*)argv[7]); exit(0); } else { printf("Type:\n%s -h for help commands \n", argv[0]); exit(0); } } if(argc == 7) { if((strcmp(argv[1],s9)==0) && (strcmp(argv[2], s4)==0) && (strcmp(argv[4], s10)==0) ) { verifySign((char*)argv[3], (char*)argv[5], (char*)argv[6]); exit(0); } else if((strcmp(argv[1],s9)==0) && (strcmp(argv[2], s7)==0) && (strcmp(argv[4], s10)==0)) { verifySignByCertificate((char*)argv[3], (char*)argv[5], (char*)argv[6]); exit(0); } } else { printf("Type:\n%s -h for help commands \n", argv[0]); exit(0); } printf("Type:\n%s -h for help commands \n", argv[0]); exit(0); exit(0); #if ENCRYPT char* pubFileName = new char[255]; printf("Enter the Public Key File for encryption:\n"); scanf("%s", pubFileName); encrypt((char *)pubFileName); char* priFileName = new char[255]; printf("Enter the Private Key File for signature:\n"); scanf("%s", priFileName); signMessage((char *)priFileName); char* pubSignFileName = new char[255]; printf("Enter the Public Key File for signature:\n"); scanf("%s", pubSignFileName); verifySign((char *)pubSignFileName); #endif #if ENCRYPT char* priPemFileName = new char[255]; printf("Enter the Private Key File for decryption:\n"); scanf("%s", priPemFileName); decrypt((char *)priPemFileName); #endif //encryptByCertificate(); #if ENCRYPT /** ** Code take cares of the decryption **/ char* decryptedText = rsaDecryption(n, pri_key, encryptedText); int decryptedFile; decryptedFile =open("decipheredText",O_WRONLY|O_CREAT); if ( decryptedFile < 0 ) { printf("unable to open file\n"); } for(int i=0; i<SIZE; i++) write(decryptedFile, (const void*)&decryptedText[i], 1); close(decryptedFile); #endif }
[ "prankur.07@gmail.com" ]
prankur.07@gmail.com
b31b67909a500246f4c3e972b4947bf2aea749ff
961f6147855cb608eefd2ccb7927e65311133efa
/library/binsaver/ut/binsaver_ut.cpp
20e4b45044a65ae5fd4efc22db00fcd35b755f8a
[ "Apache-2.0" ]
permissive
kyper999/catboost_yandex
55a79890be28d46748cb4f55dd7a8ad24ab7b354
91c41df3d4997dbab57fc1b8a990017270da47c6
refs/heads/master
2022-10-31T11:21:22.438222
2017-07-18T10:25:29
2017-07-18T10:25:29
97,590,200
0
1
NOASSERTION
2022-10-23T09:35:09
2017-07-18T11:27:38
C
UTF-8
C++
false
false
5,563
cpp
#include <library/binsaver/bin_saver.h> #include <library/binsaver/util_stream_io.h> #include <library/unittest/registar.h> #include <util/stream/buffer.h> #include <util/generic/map.h> struct TBinarySerializable { ui32 Data = 0; }; struct TNonBinarySerializable { ui32 Data = 0; TString StrData; }; struct TCustomSerializer { ui32 Data = 0; TString StrData; SAVELOAD(StrData, Data); }; struct TCustomOuterSerializer { ui32 Data = 0; TString StrData; }; void operator & (TCustomOuterSerializer& s, IBinSaver& f); struct TCustomOuterSerializerTmpl { ui32 Data = 0; TString StrData; }; struct TCustomOuterSerializerTmplDerived : public TCustomOuterSerializerTmpl { ui32 Data = 0; TString StrData; }; struct TMoveOnlyType { ui32 Data = 0; TMoveOnlyType() = default; TMoveOnlyType(TMoveOnlyType&&) = default; bool operator ==(const TMoveOnlyType& obj) const { return Data == obj.Data; } }; struct TTypeWithArray { ui32 Data = 1; TString Array[2][2]{{"test", "data"}, {"and", "more"}}; SAVELOAD(Data, Array); bool operator ==(const TTypeWithArray& obj) const { return Data == obj.Data && std::equal(std::begin(Array[0]), std::end(Array[0]), obj.Array[0]) && std::equal(std::begin(Array[1]), std::end(Array[1]), obj.Array[1]); } }; template<typename T, typename = std::enable_if_t<std::is_base_of<TCustomOuterSerializerTmpl, T>::value>> int operator & (T& s, IBinSaver& f); static bool operator==(const TBlob& l, const TBlob& r) { return TStringBuf(~l, +l) == TStringBuf(~r, +r); } SIMPLE_UNIT_TEST_SUITE(BinSaver) { SIMPLE_UNIT_TEST(HasTrivialSerializer) { UNIT_ASSERT( !IBinSaver::HasNonTrivialSerializer<TBinarySerializable>(0u) ); UNIT_ASSERT( !IBinSaver::HasNonTrivialSerializer<TNonBinarySerializable>(0u) ); UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomSerializer>(0u) ); UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomOuterSerializer>(0u) ); UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomOuterSerializerTmpl>(0u) ); UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomOuterSerializerTmplDerived>(0u) ); UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<yvector<TCustomSerializer>>(0u) ); } template<typename T> void TestSerialization(const T& original) { TBufferOutput out; { TYaStreamOutput yaOut(out); IBinSaver f(yaOut, false, false); f.Add(0, const_cast<T*>(&original)); } TBufferInput in(out.Buffer()); T restored; { TYaStreamInput yaIn(in); IBinSaver f(yaIn, true, false); f.Add(0, &restored); } UNIT_ASSERT_EQUAL(original, restored); } SIMPLE_UNIT_TEST(TestStroka) { TestSerialization(TString("QWERTY")); } SIMPLE_UNIT_TEST(TestMoveOnlyType) { TestSerialization(TMoveOnlyType()); } SIMPLE_UNIT_TEST(TestVectorStrok) { TestSerialization(yvector<TString>{"A", "B", "C"}); } SIMPLE_UNIT_TEST(TestCArray) { TestSerialization(TTypeWithArray()); } SIMPLE_UNIT_TEST(TestSets) { TestSerialization(yhash_set<TString>{"A", "B", "C"}); TestSerialization(yset<TString>{"A", "B", "C"}); } SIMPLE_UNIT_TEST(TestMaps) { TestSerialization(yhash<TString, ui32>{{"A", 1}, {"B", 2}, {"C", 3}}); TestSerialization(ymap<TString, ui32>{{"A", 1}, {"B", 2}, {"C", 3}}); } SIMPLE_UNIT_TEST(TestBlob) { TestSerialization(TBlob::FromStringSingleThreaded("qwerty")); } SIMPLE_UNIT_TEST(TestPod) { struct TPod { ui32 A = 5; ui64 B = 7; bool operator == (const TPod& other) const { return A == other.A && B == other.B; } }; TestSerialization(TPod()); TPod custom; custom.A = 25; custom.B = 37; TestSerialization(custom); TestSerialization(yvector<TPod>{ custom }); } SIMPLE_UNIT_TEST(TestSubPod) { struct TPod { struct TSub { ui32 X = 10; bool operator == (const TSub& other) const { return X == other.X; } }; yvector<TSub> B; int operator & (IBinSaver& f) { f.Add(0, &B); return 0; } bool operator == (const TPod& other) const { return B == other.B; } }; TestSerialization(TPod()); TPod::TSub sub; sub.X = 1; TPod custom; custom.B = { sub }; TestSerialization(yvector<TPod>{ custom }); } SIMPLE_UNIT_TEST(TestMemberAndOpIsMain) { struct TBase { TString S; virtual int operator & (IBinSaver& f) { f.Add(0, &S); return 0; } virtual ~TBase() = default; }; struct TDerived : public TBase { int A = 0; int operator & (IBinSaver& f) override { f.Add(0, static_cast<TBase*>(this)); f.Add(0, &A); return 0; } bool operator == (const TDerived& other) const { return A == other.A && S == other.S; } }; TDerived obj; obj.S = "TString"; obj.A = 42; TestSerialization(obj); } };
[ "exprmntr@pepe.search.yandex.net" ]
exprmntr@pepe.search.yandex.net
c6936387cf0bd8b26139ea46d938f1643fbf610a
34e11b37fada3d5290509b50d1f9c312225f613b
/InsertionSort.cpp
7d82977bfd96056b99248dd78d004f8d2b187551
[]
no_license
MiladEsp/cpp-algorithms
282ee498829ac0f048874f729a52aaaa16d9f6ec
f20ee6669d95b8ba3f87eeaa35c6fee7d39e985b
refs/heads/master
2022-12-25T12:18:55.639870
2020-10-05T02:05:56
2020-10-05T02:05:56
295,762,044
0
0
null
null
null
null
UTF-8
C++
false
false
1,058
cpp
#include <iostream> #include <vector> template <typename T> void insertionSort(std::vector<T> &vec, bool ascending) { int i, j; T key; for (j = 1; j < vec.size(); j++) { key = vec[j]; i = j - 1; if (ascending) { while (i >= 0 && vec[i] > key) { vec[i + 1] = vec[i]; i = i - 1; } } else { while (i >= 0 && vec[i] < key) { vec[i + 1] = vec[i]; i = i - 1; } } vec[i + 1] = key; } } int main() { std::vector<int> vec{5, 2, 4, 7, 1, 3, 2, 6, -5, 10, 0}; insertionSort(vec, true); for (auto item : vec) { std::cout << item << " "; } std::cout << std::endl; ///////////////////////// std::vector<double> vec1{-2.3, 0.5, 1.6, -10.5, 13.69}; insertionSort(vec1, true); for (auto item : vec1) { std::cout << item << " "; } std::cout << std::endl; return 0; }
[ "32962296+MiladEsp@users.noreply.github.com" ]
32962296+MiladEsp@users.noreply.github.com
daba678609848f35e837db30825e75b51624993c
c05238c76e2d1dff1bca000c1893d49fef58c963
/base/component/exception.cpp
0856c004ba9022a43711920a6ff7109c1978ae79
[]
no_license
firejh/server
949d371223abbd6890e7b4171a55417fbac7bb23
3a5beaf0890db6975e24eebda2fb9029d7ef61f6
refs/heads/master
2021-06-18T04:54:44.251910
2017-07-06T06:04:43
2017-07-06T06:04:43
95,762,205
1
0
null
null
null
null
UTF-8
C++
false
false
1,289
cpp
#include "exception.h" #include <iostream> #include <sstream> #include <string.h> #include <stdlib.h> namespace base{ namespace component{ ExceptionBase::ExceptionBase(const std::string& msg, const std::string& file, const std::string& func, int32_t line, int32_t sysErrno) noexcept : m_msg(msg), m_file(file), m_func(func), m_line(line), m_sysErrno(sysErrno) { } ExceptionBase::~ExceptionBase() noexcept { } std::string ExceptionBase::exceptionName() const noexcept { return "ExceptionBase"; } std::string ExceptionBase::msg() const noexcept { return m_msg; } const char* ExceptionBase::what() const noexcept { if (!m_what.empty()) return m_what.c_str(); if(m_sysErrno != 0) m_what = format("[{execptionName}], msg:[{m_msg}], file:[{m_file}+{m_line}], fun:[{m_func}], errno:[{m_sysErrno} {strerr}]", exceptionName(), m_msg, m_file, m_line, m_func, m_sysErrno, ::strerror(m_sysErrno)); else m_what = format("[{execptionName}], msg:[{m_msg}], file:[{m_file}+{m_line}], fun:[{m_func}]", exceptionName(), m_msg, m_file, m_line, m_func); return m_what.c_str(); } }}
[ "centos@localhost.localdomain" ]
centos@localhost.localdomain
7883b573bdc66f6999ae56ae24991fc9f42610e2
b8be015984622307394dc919ab711417da4fa911
/Length of Last Word.h
cd54d6144712901fa709405f2a7c4159a8594ed3
[]
no_license
boyxgc/Leetcode
de41651416e5aec30666f67653ab7736e0edc2aa
bd09a470628f7112198b70d52d63b30409cac12f
refs/heads/master
2021-01-22T06:37:00.824562
2014-12-05T03:16:11
2014-12-05T03:16:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
481
h
class Solution { public: int lengthOfLastWord(const char *s) { int size = 0; const char *s1 = s; while(*(s1++)) { size++; } int lastword = size-1; while(lastword >= 0 && s[lastword] == ' ') lastword--; int lastwordsize = 0; while(lastword >= 0 && s[lastword] != ' '){ lastwordsize++; lastword--; } return lastwordsize; } };
[ "boyxgc@gmail.com" ]
boyxgc@gmail.com
67df2629c6da09829d66ee120c50e9c896a84471
0f3d13bd7d68efbed8c7db1abcac57f8bd797458
/HEPfit/examples-src/LibMode_header/libmode_header.cpp
7a7dcee4c80eac0d32f702ec089e7dbbbdcaa00a
[ "DOC" ]
permissive
talismanbrandi/Belle_1809.03290
5b48b1fee290b12159326e04f72640898663540c
b6608353f9c685a95f9a9d2fe2677c3d128baf8a
refs/heads/master
2020-05-27T05:06:30.404976
2019-05-28T17:02:13
2019-05-28T17:02:13
188,494,216
0
0
null
null
null
null
UTF-8
C++
false
false
3,137
cpp
/* * Copyright (C) 2014 HEPfit Collaboration * * * For the licensing terms see doc/COPYING. */ /** * @example libmode_header.cpp * This is an example of how to compute observables from the input parameters * defined in the file InputParameters.h. * */ #include <iostream> #include <HEPfit.h> #include <InputParameters.h> int main(int argc, char** argv) { try { /* Define the name of the model to be used. */ std::string ModelName = "NPEpsilons"; /* Create an object of the class InputParameters. */ InputParameters IP; /* Read a map for the mandatory model parameters. (Default values in InputParameters.h) */ std::map<std::string, double> DPars_IN = IP.getInputParameters(ModelName); /* Change the default values of the mandatory model parameters if necessary. */ /* This can also be done with DPars after creating an object of ComputeObservables. */ DPars_IN["mcharm"] = 1.3; DPars_IN["mub"] = 4.2; /* Create objects of the classes ModelFactory and ThObsFactory */ ModelFactory ModelF; ThObsFactory ThObsF; /* Set the flags for the model being used, if necessary. */ std::map<std::string, std::string> DFlags; DFlags["epsilon2SM"] = "TRUE"; DFlags["epsilonbSM"] = "TRUE"; /* Create an object of the class ComputeObservables. */ ComputeObservables CO(ModelF, ThObsF, ModelName, DPars_IN, DFlags); /* Add the observables to be returned. */ CO.AddObservable("Mw"); CO.AddObservable("GammaZ"); CO.AddObservable("AFBbottom"); /* Remove a previously added observables if necessary. */ //CO.RemoveObservable("AFBbottom"); /* Get the map of observables if necessary. */ std::map<std::string, double> DObs = CO.getObservables(); /* Define a map for the parameters to be varied. */ std::map<std::string, double> DPars; for (int i = 0; i < 2; i++) { /* Vary the parameters that need to be varied in the analysis. */ DPars["epsilon_1"] = 0. + i * 0.01; DPars["epsilon_3"] = 0. + i * 0.01; /* Get the map of observables with the parameter values defined above. */ DObs = CO.compute(DPars); std::cout << "\nParameters[" << i + 1 << "]:"<< std::endl; for (std::map<std::string, double>::iterator it = DPars.begin(); it != DPars.end(); it++) { std::cout << it->first << " = " << it->second << std::endl; } std::cout << "\nObservables[" << i + 1 << "]:" << std::endl; for (std::map<std::string, double>::iterator it = DObs.begin(); it != DObs.end(); it++) { std::cout << it->first << " = " << it->second << std::endl; } } return EXIT_SUCCESS; } catch (const std::runtime_error& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } }
[ "apaul2@alumni.nd.edu" ]
apaul2@alumni.nd.edu
8421bd189ced236256f3be76fdc339ae7bdbfc86
74af32d04639d5c442f0e94b425beb68a2544b3c
/LeetCode/Normal/1400-1499/1431.cpp
228c14d475eea3e1b864489ef4375205c5454dc0
[]
no_license
dlvguo/NoobOJCollection
4e4bd570aa2744dfaa2924bacc34467a9eae8c9d
596f6c578d18c7beebdb00fa3ce6d6d329647360
refs/heads/master
2023-05-01T07:42:33.479091
2023-04-20T11:09:15
2023-04-20T11:09:15
181,868,933
8
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies) { int n = candies.size(); int maxCandies = *max_element(candies.begin(), candies.end()); vector<bool> ret; for (int i = 0; i < n; ++i) { ret.push_back(candies[i] + extraCandies >= maxCandies); } return ret; } };
[ "dlvguo@qq.com" ]
dlvguo@qq.com
58493d8bed5ecc0ae128aa4b5b0a1e1dec31af9b
4da66ea2be83b62a46d77bf53f690b5146ac996d
/modules/assimp/assimp/code/CreateAnimMesh.cpp
1a052849bb705597fcfab64c71d2d4430556b78a
[ "BSD-3-Clause", "Zlib" ]
permissive
blitz-research/monkey2
620855b08b6f41b40ff328da71d2e0d05d943855
3f6be81d73388b800a39ee53acaa7f4a0c6a9f42
refs/heads/develop
2021-04-09T17:13:34.240441
2020-06-28T04:26:30
2020-06-28T04:26:30
53,753,109
146
76
Zlib
2019-09-07T21:28:05
2016-03-12T20:59:51
Monkey
UTF-8
C++
false
false
3,731
cpp
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (C) 2016 The Qt Company Ltd. Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ #include <assimp/CreateAnimMesh.h> namespace Assimp { aiAnimMesh *aiCreateAnimMesh(const aiMesh *mesh) { aiAnimMesh *animesh = new aiAnimMesh; animesh->mVertices = NULL; animesh->mNormals = NULL; animesh->mTangents = NULL; animesh->mBitangents = NULL; animesh->mNumVertices = mesh->mNumVertices; if (mesh->mVertices) { animesh->mVertices = new aiVector3D[animesh->mNumVertices]; std::memcpy(animesh->mVertices, mesh->mVertices, mesh->mNumVertices * sizeof(aiVector3D)); } if (mesh->mNormals) { animesh->mNormals = new aiVector3D[animesh->mNumVertices]; std::memcpy(animesh->mNormals, mesh->mNormals, mesh->mNumVertices * sizeof(aiVector3D)); } if (mesh->mTangents) { animesh->mTangents = new aiVector3D[animesh->mNumVertices]; std::memcpy(animesh->mTangents, mesh->mTangents, mesh->mNumVertices * sizeof(aiVector3D)); } if (mesh->mBitangents) { animesh->mBitangents = new aiVector3D[animesh->mNumVertices]; std::memcpy(animesh->mBitangents, mesh->mBitangents, mesh->mNumVertices * sizeof(aiVector3D)); } for (int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) { if (mesh->mColors[i]) { animesh->mColors[i] = new aiColor4D[animesh->mNumVertices]; std::memcpy(animesh->mColors[i], mesh->mColors[i], mesh->mNumVertices * sizeof(aiColor4D)); } else { animesh->mColors[i] = NULL; } } for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) { if (mesh->mTextureCoords[i]) { animesh->mTextureCoords[i] = new aiVector3D[animesh->mNumVertices]; std::memcpy(animesh->mTextureCoords[i], mesh->mTextureCoords[i], mesh->mNumVertices * sizeof(aiVector3D)); } else { animesh->mTextureCoords[i] = NULL; } } return animesh; } } // end of namespace Assimp
[ "blitzmunter@gmail.com" ]
blitzmunter@gmail.com
2ce6f67ba7f336772b326ad9853252225a43a99a
5bb7cf6f6f38e8a96ef5d522d26cf78c7c097c41
/src/engine/server/library/serverGame/src/shared/command/CommandQueue.cpp
d581b8aeb5090b282605f42ba1df8338eab51244
[]
no_license
hackerlank/SWG_Client_Next_Main
1c88015af11bd42c662a7d7c4fe0807924f4077a
d737257b8fc28f7ad4d8d02113e7662682187194
refs/heads/master
2021-01-12T06:25:56.627527
2016-06-01T19:32:59
2016-06-01T19:32:59
77,359,203
6
4
null
2016-12-26T05:09:07
2016-12-26T05:09:06
null
UTF-8
C++
false
false
54,330
cpp
// ====================================================================== // // CommandQueue.cpp // // Copyright 2002 Sony Online Entertainment // // ====================================================================== #include "serverGame/FirstServerGame.h" #include "serverGame/CommandQueue.h" #include "UnicodeUtils.h" #include "serverGame/Chat.h" #include "serverGame/ConfigServerGame.h" #include "serverGame/CreatureController.h" #include "serverGame/CreatureObject.h" #include "serverGame/NameManager.h" #include "serverGame/PlayerObject.h" #include "serverGame/ServerSecureTrade.h" #include "serverGame/WeaponObject.h" #include "serverScript/GameScriptObject.h" #include "serverScript/ScriptParameters.h" #include "serverUtility/ServerClock.h" #include "sharedFoundation/Clock.h" #include "sharedFoundation/Crc.h" #include "sharedFoundation/FormattedString.h" #include "sharedFoundation/GameControllerMessage.h" #include "sharedGame/Command.h" #include "sharedGame/CommandTable.h" #include "sharedLog/Log.h" #include "sharedNetworkMessages/GenericValueTypeMessage.h" #include "sharedNetworkMessages/MessageQueueCommandQueueRemove.h" #include "sharedNetworkMessages/MessageQueueCommandTimer.h" #include "sharedNetworkMessages/MessageQueueGenericValueType.h" #include "sharedObject/NetworkIdManager.h" // -------------------------------------------------------------------------- namespace CommandQueueNamespace { /** * @brief whether or not to produce debug logging */ #ifdef _DEBUG const bool cs_debug = false; #endif /** * @brief used to assign sequence Ids to server-generated commands * that need to be replicated on the client. */ const uint32 cs_sequenceStart = 0x40000000; /** * @brief the maximum number of combat commands that are allowed in * the queue at any given time. */ const uint32 cs_maxQueuedCombatCommands = 2; /** * @brief the number of seconds in a real-time day. * * This value is used for sanity checking * @see setCommandTimerValue */ const float cs_secondsPerDay = 86400.f; /** * @brief the current time is cached in this class variable. * * this is used to reduce the number of calls to Clock::getCurrentTime(). * note it may not be appropriate to use this value in every * place in the code since there's guarantee that it's accurate from * every entry point in script. * * @see Clock::getCurrentTime */ double s_currentTime = 0.f; } using namespace CommandQueueNamespace; // -------------------------------------------------------------------------- CommandQueue::CommandQueue(ServerObject & owner) : Property(getClassPropertyId(), owner), m_status (Command::CEC_Success), m_statusDetail (0), m_state ( State_Waiting ), m_nextEventTime ( 0.f ), m_queue ( ), m_cooldowns ( ), m_commandTimes ( TimerClass_MAX ), m_combatCount ( 0 ), m_eventStartTime ( 0.0 ), m_logCommandEnqueue (false) { } // ---------------------------------------------------------------------- PropertyId CommandQueue::getClassPropertyId() { return PROPERTY_HASH(CommandQueue, 889825674); } // ---------------------------------------------------------------------- bool CommandQueue::isFull() const { // is it empty? if ( m_combatCount.get() == 0 ) { return false; } // is it at the max? if ( m_combatCount.get() >= cs_maxQueuedCombatCommands ) { return true; } // test to see if the current command is waiting on a cooldown. we're considered // full if we're waiting on a cooldown timer if ( m_state.get() == State_Waiting && !m_queue.empty() ) { const CommandQueueEntry &entry = *(m_queue.begin()); if ( (getCooldownTimeLeft( entry.m_command->m_coolGroup ) > 0.f) || (getCooldownTimeLeft( entry.m_command->m_coolGroup2) > 0.f) ) { return true; } } return false; } // ---------------------------------------------------------------------- void CommandQueue::enqueue(Command const &command, NetworkId const &targetId, Unicode::String const &params, uint32 sequenceId, bool clearable, Command::Priority priority) { DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::enqueue(%s, %s, %s, %d, %d, %d)\n", Clock::getCurrentTime(), command.m_commandName.c_str(), targetId.getValueString().c_str(), Unicode::wideToNarrow(params).c_str(), static_cast<int>(sequenceId), clearable ? 1 : 0, static_cast<int>(priority) )); // make sure the cooldown timer value is initialized if it's not in the map if(static_cast<int>(command.m_coolGroup) != -1) { if ( m_cooldowns.find( command.m_coolGroup ) == m_cooldowns.end() ) { m_cooldowns.set( command.m_coolGroup, std::make_pair( 0.f, 0.f ) ); } } if(static_cast<int>(command.m_coolGroup2) != -1) { if ( m_cooldowns.find( command.m_coolGroup2 ) == m_cooldowns.end() ) { m_cooldowns.set( command.m_coolGroup2, std::make_pair( 0.f, 0.f ) ); } } if ( priority == Command::CP_Default ) { priority = command.m_defaultPriority; } // // execute immediate commands imemdiately // if ( priority == Command::CP_Immediate ) { Command::ErrorCode status = Command::CEC_Success; int statusDetail = 0; executeCommand(command, targetId, params, status, statusDetail, false); notifyClientOfCommandRemoval(sequenceId, 0.0f, status, statusDetail); } else { if ( command.m_addToCombatQueue && isFull() ) { // we do special things if the command queue is full or the current command is waiting on a cooldown // timer of combat actions and the player tries to add another // combat action! // look in the queue for a command to replace this with for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); ) { EntryList::iterator j = it++; // if there's a command warming up or executing then we can skip the first command in the queue if ( m_state.get() != State_Waiting && j == m_queue.begin() ) { continue; } const CommandQueueEntry &entry = *j; // test to see of this command is a combat command if ( entry.m_command->m_addToCombatQueue ) { // remove command from queue m_queue.erase( j ); // we want to end this loop it = m_queue.end(); } } } // create the command queue entry object const CommandQueueEntry entry( command, targetId, params, sequenceId, clearable, priority, false ); m_queue.push( entry ); if ( command.m_addToCombatQueue ) { m_combatCount = m_combatCount.get() + 1; } // debug - /spewCommandQueue available from console if (m_logCommandEnqueue) spew(); // if there's only one thing in the command queue , // then its okay to start execution immediately. if ( ( m_queue.size() == 1 ) ) { executeCommandQueue(); } } } // ---------------------------------------------------------------------- void CommandQueue::remove(uint32 sequenceId) { DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::remove(0x%08x)\n", (int)sequenceId ) ); if ( sequenceId == 0 ) { // this would occur as a command from the client to cancel all pending combat actions // as a result of the player hitting ESC clearPendingCombatCommands(); } else { // sometimes the game server wants to remove a specific command from the queue // iterate over each item in the queue for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); /* no action */ ) { EntryList::iterator j = it++; if ( ( j != m_queue.begin() ) || ( m_state.get() != State_Execute ) ) // <- don't cancel an executing command { const CommandQueueEntry &entry = *j; if ( entry.m_sequenceId == sequenceId ) { if ( j == m_queue.begin() ) { m_nextEventTime = 0; m_state = State_Waiting; } handleEntryRemoved(entry ); m_queue.erase( j ); // force this loop to terminate, since sequenceIds must be unique // there's no way that if we removed a matching sequenceId that // there are any more of them in the command queue it = m_queue.end(); } } } } } // ---------------------------------------------------------------------- void CommandQueue::update(float time) { PROFILER_AUTO_BLOCK_DEFINE("CommandQueue::update"); executeCommandQueue(); } void CommandQueue::executeCommandQueue() { // cache the current time, so that we don't have to hit the getCurrentTime() method every time s_currentTime = Clock::getCurrentTime(); // // iterate through each command in the queue // while ( !m_queue.empty() ) { CommandQueueEntry &entry = *(m_queue.begin()); // try to recover from having a null command // maybe this should result in a fatal error? if ( entry.m_command == 0 ) { WARNING( true, ( "executeCommandQueue: entry.m_command was NULL! WTF?\n" ) ); m_queue.pop(); m_state = State_Waiting; m_nextEventTime = 0.f; continue; } // check the cooldown timer for this command's group const unsigned int cooldownGroup = entry.m_command->m_coolGroup; const unsigned int cooldownGroup2 = entry.m_command->m_coolGroup2; // if this group is still cooling down, we need to break // out of this loop and go do something else if(static_cast<int>(cooldownGroup) != -1) { float coolTimeLeft = getCooldownTimeLeft( cooldownGroup ); if ( coolTimeLeft > FLT_EPSILON ) { DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommandQueue(): waiting on cooldown group 0x%u: %f seconds left!\n", s_currentTime, cooldownGroup, coolTimeLeft ) ); break; } } if(static_cast<int>(cooldownGroup2) != -1) { float coolTimeLeft2 = getCooldownTimeLeft( cooldownGroup2 ); if ( coolTimeLeft2 > FLT_EPSILON ) { DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommandQueue(): waiting on cooldown group 2 0x%u: %f seconds left!\n", s_currentTime, cooldownGroup2, coolTimeLeft2 ) ); break; } } // if we need to wait more time before switching states, we should // just update the timer and leave now. if ( m_nextEventTime.get() > s_currentTime ) { DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommandQueue(): waiting on state %s: %f seconds left!\n", s_currentTime, getStateAsString((State) m_state.get() ), m_nextEventTime.get() - s_currentTime ) ); break; } switchState(); switch ( m_state.get() ) { case State_Waiting: { // don't call cancelCurrentCommand() here, because that method jacks with the command timer // so we do the work manually // NOTE RHanz: // this is the one place in this class that we're not calling // handleEntryRemoved when we're getting rid of an entry. // It was explicitly removed... if there seems to be a problem // with entries not being removed, this might be the culprit. // Leaving for the time being as it was explicitly removed. // NOTE SWyckoff: // Turns out that there were problems with not calling // handleEntryRemoved here that would cause the client to // trigger a cool down even if the command failed. Putting it // back in now. // This pop removes commands that were executed last frame and // need to be taken off the queue // switch state might have removed elements from the queue and invalidated entry // so we can't assume that we're still safe if(!m_queue.empty() && (&(*(m_queue.begin())) == &entry) && m_queue.begin()->m_command != NULL) { handleEntryRemoved(*(m_queue.begin()), true); m_queue.pop(); } break; } case State_Warmup: { // do something in script bool result = doWarmupTrigger(entry ); if ( result == false ) { cancelCurrentCommand(); } else { notifyClient(); } } break; case State_Execute: { // The matching m_queue.pop() for this doExecute is in the next frame's State_Waiting doExecute(entry ); } break; default: FATAL( true, ( "command queue is in an invalid state. value=%d", (int)m_state.get() ) ); break; } } } // ---------------------------------------------------------------------- void CommandQueue::doExecute(const CommandQueueEntry &entry ) { // execute command here m_status = Command::CEC_Success; m_statusDetail = 0; // push the command on the stack m_commandStack.push( &entry ); executeCommand( *entry.m_command, entry.m_targetId, entry.m_params, m_status, m_statusDetail, true ); FATAL( m_commandStack.empty(), ( "the command stack was empty! something is horribly wrong with the command queue!" ) ); // pop m_commandStack.pop(); // check to see if the command was not removed from the queue // or if the command failed if ( !m_queue.empty() && (*(m_queue.begin())).m_sequenceId == entry.m_sequenceId && m_status == Command::CEC_Success ) { // after executing the command, send execute and cooldown times to the client notifyClient(); } } // ---------------------------------------------------------------------- void CommandQueue::updateClient(TimerClass timerClass ) { CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if ( (creatureOwner == NULL) || !creatureOwner->getClient()) { return; } // // grab the command that's currently working // if ( m_queue.empty() ) return; const CommandQueueEntry &entry = *(m_queue.begin()); if ( entry.m_command == 0 ) // woah that's bad news! { WARNING( true, ( "CommandQueue::updateClient(): command was NULL!\n" ) ); return; } // create a message MessageQueueCommandTimer *msg = new MessageQueueCommandTimer( entry.m_sequenceId, entry.m_command->m_coolGroup, entry.m_command->m_coolGroup2, Crc::normalizeAndCalculate(entry.m_command->m_commandName.c_str()) ); float currentTimer = 0.f; // figure out what to put in the message based on our current state if ( ( timerClass == TimerClass_Warmup && m_state.get() == State_Warmup ) || ( timerClass == TimerClass_Execute && m_state.get() == State_Execute ) ) { currentTimer = static_cast< float > ( s_currentTime - m_eventStartTime.get() ); } switch ( timerClass ) { case TimerClass_Warmup: msg->setCurrentTime( MessageQueueCommandTimer::F_warmup, currentTimer ); msg->setMaxTime ( MessageQueueCommandTimer::F_warmup, m_commandTimes[ TimerClass_Warmup ] ); break; case TimerClass_Execute: msg->setCurrentTime( MessageQueueCommandTimer::F_execute, currentTimer ); msg->setMaxTime ( MessageQueueCommandTimer::F_execute, m_commandTimes[ TimerClass_Execute ] ); break; case TimerClass_Cooldown: msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown, currentTimer ); msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown, m_commandTimes[ TimerClass_Cooldown ] ); if(static_cast<int>(entry.m_command->m_coolGroup2) != -1) { msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown2, currentTimer ); msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown2, m_commandTimes[ TimerClass_Cooldown2] ); } break; case TimerClass_Cooldown2: DEBUG_WARNING(true, ("MessageQueueCommandTimer: updateClient; don't update cooldown 2 timer directly, please")); break; default: break; } // send message creatureOwner->getController()->appendMessage( static_cast< int >( CM_commandTimer ), 0.0f, msg, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT ); } // ---------------------------------------------------------------------- void CommandQueue::notifyClient() { CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if ( (creatureOwner == NULL) || !creatureOwner->getClient()) { return; } if ( m_queue.empty() ) { WARNING( true, ( "CommandQueue::notifyClient(): queue is empty!\n" ) ); return; } const CommandQueueEntry &entry = *(m_queue.begin()); if ( entry.m_command == 0 ) { WARNING( true, ( "CommandQueue::notifyClient(): command was NULL!\n" ) ); return; } MessageQueueCommandTimer *msg = new MessageQueueCommandTimer( entry.m_sequenceId, entry.m_command->m_coolGroup, entry.m_command->m_coolGroup2, Crc::normalizeAndCalculate(entry.m_command->m_commandName.c_str()) ); DEBUG_REPORT_LOG( cs_debug && creatureOwner->getClient(), ( "%f: CommandQueue::notifyClient() [%f] warmup=%f execute=%f cooldown=%f cooldown2=%f\n", s_currentTime, s_currentTime - m_eventStartTime.get(), m_commandTimes[ TimerClass_Warmup ], m_commandTimes[ TimerClass_Execute ], m_commandTimes[ TimerClass_Cooldown ], m_commandTimes[ TimerClass_Cooldown2 ]) ); switch ( m_state.get() ) { case State_Warmup: msg->setCurrentTime( MessageQueueCommandTimer::F_warmup, static_cast< float >( s_currentTime - m_eventStartTime.get() ) ); msg->setMaxTime ( MessageQueueCommandTimer::F_warmup, m_commandTimes[ TimerClass_Warmup ] ); break; case State_Execute: msg->setCurrentTime( MessageQueueCommandTimer::F_execute, static_cast< float >( s_currentTime - m_eventStartTime.get() ) ); msg->setMaxTime ( MessageQueueCommandTimer::F_execute, m_commandTimes[ TimerClass_Execute ] ); msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown, 0.f ); msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown, m_commandTimes[ TimerClass_Cooldown ] ); msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown2, 0.f ); msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown2, m_commandTimes[ TimerClass_Cooldown2 ] ); break; default: break; } creatureOwner->getController()->appendMessage( static_cast< int >( CM_commandTimer ), 0.0f, msg, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT ); } // ---------------------------------------------------------------------- bool CommandQueue::doWarmupTrigger(const CommandQueueEntry &entry ) { bool result = false; // make sure we could actually execute this command m_status = Command::CEC_Success; m_statusDetail = 0; CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if (creatureOwner != NULL) { creatureOwner->doWarmupChecks( *entry.m_command, entry.m_targetId, entry.m_params, m_status, m_statusDetail ); // if everything is okay, start the warmup trigger if ( m_status == Command::CEC_Success ) { FATAL( entry.m_command == 0, ( "entry had a null command\n" ) ); std::vector<float> timeValues; timeValues.push_back( entry.m_command->m_warmTime ); timeValues.push_back( entry.m_command->m_execTime ); timeValues.push_back( getCooldownTime(*entry.m_command) ); timeValues.push_back( entry.m_command->m_coolTime2 ); ScriptParams params; std::string entryParams( Unicode::wideToNarrow( entry.m_params ) ); params.addParam( entry.m_command->m_commandName.c_str() ); params.addParam( (int)entry.m_command->m_coolGroup ); params.addParam( (int)entry.m_command->m_coolGroup2 ); params.addParam( timeValues ); params.addParam( entryParams.c_str() ); params.addParam( entry.m_targetId ); result = SCRIPT_OVERRIDE != creatureOwner->getScriptObject()->trigAllScripts( Scripting::TRIG_BEGIN_WARMUP, params ); } } return result; } // ---------------------------------------------------------------------- uint32 CommandQueue::getCurrentCommand() const { if ( m_queue.empty() ) { return 0; } const CommandQueueEntry &entry = *(m_queue.begin()); if ( entry.m_command == 0 ) { WARNING( true, ( "CommandQueue::getCurrentCommand(): command was NULL!\n" ) ); return 0; } return Crc::calculate( entry.m_command->m_commandName.c_str() ); } // ---------------------------------------------------------------------- void CommandQueue::switchState() { if ( m_queue.empty() ) { WARNING( true, ( "CommandQueue::switchState(): queue is empty!\n" ) ); return; } const CommandQueueEntry &entry = *(m_queue.begin()); if ( entry.m_command == 0 ) { WARNING( true, ( "CommandQueue::switchState(): command was NULL!\n" ) ); return; } #if defined(COMMAND_QUEUE_ENTRY_LOGGING) CommandQueueEntry const entryCopy = entry; #endif m_eventStartTime = s_currentTime; const unsigned int savedQueueSize = m_queue.size(); switch ( m_state.get() ) { case State_Waiting: // set timing info for execute and cooldown timers m_commandTimes.set( TimerClass_Execute, entry.m_command->m_execTime ); m_commandTimes.set( TimerClass_Cooldown, getCooldownTime(*entry.m_command) ); m_commandTimes.set( TimerClass_Cooldown2, entry.m_command->m_coolTime2 ); DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): cooldown timer setting id=%lu time=%f id2=%lu time2=%f\n", entry.m_command->m_coolGroup, getCooldownTime(*entry.m_command), entry.m_command->m_coolGroup2, entry.m_command->m_coolTime2) ); if ( entry.m_command->m_warmTime < FLT_EPSILON ) { if( entry.m_command->m_execTime < FLT_EPSILON ) { // skipping both warmup and execute if both the timers are 0 m_nextEventTime = s_currentTime; doExecute(entry ); bool entryIsTopOfQueue = true; if (!m_queue.empty()) { entryIsTopOfQueue = &(*(m_queue.begin())) == &entry; #if defined(COMMAND_QUEUE_ENTRY_LOGGING) if (!entryIsTopOfQueue && m_queue.size() == savedQueueSize) { REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_INVALID: Entry does not match top of queue!\n")); Object const * const target = NetworkIdManager::getObjectById(entryCopy.m_targetId); bool const targetIsAuthoritative = target && target->isAuthoritative(); REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_COMMAND: commandName=[%s] commandHash=[%lu] owner=[%s][%s][%s] target=[%s][%s][%s] sequenceId=[%lu] params=[%s] clearable=[%s] priority=[%d]\n", entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "NULL", entryCopy.m_command ? entryCopy.m_command->m_commandHash : 0, NameManager::getInstance().getPlayerName(getOwner().getNetworkId()).c_str(), getOwner().getNetworkId().getValueString().c_str(), getOwner().isAuthoritative() ? "auth" : "proxy", NameManager::getInstance().getPlayerName(entryCopy.m_targetId).c_str(), entryCopy.m_targetId.getValueString().c_str(), targetIsAuthoritative ? "auth" : "proxy", entryCopy.m_sequenceId, Unicode::wideToNarrow(entryCopy.m_params).c_str(), entryCopy.m_clearable ? "true" : "false", entryCopy.m_priority) ); REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: state=State_Waiting queueSize=%d\n", m_queue.size())); EntryList::const_iterator itEntry = m_queue.begin(); for (; itEntry != m_queue.end(); ++itEntry) { REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "NULL")); } } #endif } else entryIsTopOfQueue = false; //Check the size of the queue. If it has shrunk then it means the entry was popped off the queue by cancelCurrentCommand, //most likely because the command failed. If this is the case, do not perform the following actions. if (m_queue.size() == savedQueueSize && entryIsTopOfQueue) { m_state = State_Waiting; // set the cooldown timer for this command group m_cooldowns.set( entry.m_command->m_coolGroup, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown ] ) ); m_cooldowns.set( entry.m_command->m_coolGroup2, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown2 ] ) ); // if the cool down value is large enough, persist it across // server restarts and character unloading and reloading from the DB if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() ) { persistCooldown( entry.m_command->m_coolGroup, static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) ); } if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() ) { persistCooldown( entry.m_command->m_coolGroup2, static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) ); } DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Waiting->Waiting all the way around : m_nextEventTime=%f m_commandTime=%f m_execTime=%f\n", m_nextEventTime.get(), m_commandTimes[ TimerClass_Execute ], entry.m_command->m_execTime ) ); handleEntryRemoved(entry, true); m_queue.pop(); } } else { // here we skip the warmup state if the default warmup timer is 0 m_state = State_Execute; m_nextEventTime = s_currentTime + entry.m_command->m_execTime; m_commandTimes.set( TimerClass_Warmup, 0.f ); DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Waiting->Execute\n" ) ); } } else { // otherwise we set up the warmup time m_state = State_Warmup; // set the command time state // m_commandTimes[ TimerClass_Warmup ] = entry.m_command->m_warmTime; m_commandTimes.set( TimerClass_Warmup, entry.m_command->m_warmTime ); // update the next event time value m_nextEventTime = s_currentTime + entry.m_command->m_warmTime; DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Waiting->Warmup\n" ) ); } break; case State_Warmup: if(entry.m_command->m_execTime < FLT_EPSILON) { m_nextEventTime = s_currentTime; doExecute(entry ); bool entryIsTopOfQueue = true; if (!m_queue.empty()) { entryIsTopOfQueue = &(*(m_queue.begin())) == &entry; #if defined(COMMAND_QUEUE_ENTRY_LOGGING) if (!entryIsTopOfQueue && m_queue.size() == savedQueueSize) { REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_INVALID: Entry does not match top of queue!\n")); Object const * const target = NetworkIdManager::getObjectById(entryCopy.m_targetId); bool const targetIsAuthoritative = target && target->isAuthoritative(); REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_COMMAND: commandName=[%s] commandHash=[%lu] owner=[%s][%s][%s] target=[%s][%s][%s] sequenceId=[%lu] params=[%s] clearable=[%s] priority=[%d]\n", entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "NULL", entryCopy.m_command ? entryCopy.m_command->m_commandHash : 0, NameManager::getInstance().getPlayerName(getOwner().getNetworkId()).c_str(), getOwner().getNetworkId().getValueString().c_str(), getOwner().isAuthoritative() ? "auth" : "proxy", NameManager::getInstance().getPlayerName(entryCopy.m_targetId).c_str(), entryCopy.m_targetId.getValueString().c_str(), targetIsAuthoritative ? "auth" : "proxy", entryCopy.m_sequenceId, Unicode::wideToNarrow(entryCopy.m_params).c_str(), entryCopy.m_clearable ? "true" : "false", entryCopy.m_priority) ); REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: state=State_Warmup queueSize=%d\n", m_queue.size())); EntryList::const_iterator itEntry = m_queue.begin(); for (; itEntry != m_queue.end(); ++itEntry) { REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "NULL")); } } #endif } else entryIsTopOfQueue = false; //Check the size of the queue. If it has shrunk then it means the entry was popped off the queue by cancelCurrentCommand, //most likely because the command failed. If this is the case, do not perform the following actions. if (m_queue.size() == savedQueueSize && entryIsTopOfQueue) { m_state = State_Waiting; // set the cooldown timer for this command group m_cooldowns.set( entry.m_command->m_coolGroup, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown ] ) ); m_cooldowns.set( entry.m_command->m_coolGroup2, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown2 ] ) ); // if the cool down value is large enough, persist it across // server restarts and character unloading and reloading from the DB if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() ) { persistCooldown( entry.m_command->m_coolGroup, static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) ); } if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() ) { persistCooldown( entry.m_command->m_coolGroup2, static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) ); } DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Warmup->Waiting m_nextEventTime=%f m_commandTime=%f m_execTime=%f\n", m_nextEventTime.get(), m_commandTimes[ TimerClass_Execute ], entry.m_command->m_execTime ) ); } } else { m_state = State_Execute; m_nextEventTime = s_currentTime + entry.m_command->m_execTime; DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Warmup->Execute m_nextEventTime=%f m_commandTime=%f m_execTime=%f\n", m_nextEventTime.get(), m_commandTimes[ TimerClass_Execute ], entry.m_command->m_execTime ) ); } break; case State_Execute: m_state = State_Waiting; // set the cooldown timer for this command group m_cooldowns.set( entry.m_command->m_coolGroup, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown ] ) ); m_cooldowns.set( entry.m_command->m_coolGroup2, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown2 ] ) ); DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Execute->%s\n", getStateAsString( (State)m_state.get() ) ) ); // if the cool down value is large enough, persist it across // server restarts and character unloading and reloading from the DB if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() ) { persistCooldown( entry.m_command->m_coolGroup, static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) ); } if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() ) { persistCooldown( entry.m_command->m_coolGroup2, static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) ); } break; default: WARNING( true, ( "CommandQueue::switchState(): queue is in an invalid state!\n" ) ); break; } } // ---------------------------------------------------------------------- void CommandQueue::clearPendingCombatCommands() { DEBUG_REPORT_LOG( cs_debug, ( "%s: attempting to cancel pending commands (queueSize=%d)\n", Unicode::wideToNarrow( getServerOwner().getObjectName() ).c_str(), m_queue.size() ) ); for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); ) { EntryList::iterator j = it++; const CommandQueueEntry &entry = *j; // if ( command is combat command ) // { // if ( ( command is at the top and is not executing ) or ( command is not at the top ) // { // remove command // } // } if ( entry.m_command->m_addToCombatQueue && ( j != m_queue.begin() || m_state.get() != State_Execute ) ) { handleEntryRemoved(entry ); if ( j == m_queue.begin() ) { cancelCurrentCommand(); } else { m_queue.erase( j ); } } } } // ---------------------------------------------------------------------- void CommandQueue::persistCooldown(uint32 cooldownGroupCrc, int cooldownTimeSeconds) { if (cooldownTimeSeconds <= 0) return; CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if (!creatureOwner) return; int const currentGameTime = static_cast<int>(ServerClock::getInstance().getGameTimeSeconds()); char buffer[256]; snprintf(buffer, sizeof(buffer)-1, "commandCooldown.beginTime.%lu", cooldownGroupCrc); buffer[sizeof(buffer)-1] = '\0'; std::string const coolDownBeginTime = buffer; snprintf(buffer, sizeof(buffer)-1, "commandCooldown.endTime.%lu", cooldownGroupCrc); buffer[sizeof(buffer)-1] = '\0'; std::string const coolDownEndTime = buffer; IGNORE_RETURN(creatureOwner->setObjVarItem(coolDownBeginTime, currentGameTime)); IGNORE_RETURN(creatureOwner->setObjVarItem(coolDownEndTime, (currentGameTime + cooldownTimeSeconds))); } // ---------------------------------------------------------------------- void CommandQueue::depersistCooldown() { CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if (!creatureOwner) return; DynamicVariableList const & objvars = creatureOwner->getObjVars(); std::map<uint32, std::pair<int, int> > commandCooldownTimers; for (DynamicVariableList::MapType::const_iterator iterObjVar = objvars.begin(); iterObjVar != objvars.end(); ++iterObjVar) { if (iterObjVar->first.find("commandCooldown.beginTime.") == 0) { uint32 cooldownGroupCrc = 0; if (1 == sscanf(iterObjVar->first.c_str(), "commandCooldown.beginTime.%lu", &cooldownGroupCrc)) { int beginTime = 0; if (iterObjVar->second.get(beginTime)) { std::map<uint32, std::pair<int, int> >::iterator iterFind = commandCooldownTimers.find(cooldownGroupCrc); if (iterFind == commandCooldownTimers.end()) { commandCooldownTimers[cooldownGroupCrc] = std::make_pair(beginTime, 0); } else { iterFind->second.first = beginTime; } } } } else if (iterObjVar->first.find("commandCooldown.endTime.") == 0) { uint32 cooldownGroupCrc = 0; if (1 == sscanf(iterObjVar->first.c_str(), "commandCooldown.endTime.%lu", &cooldownGroupCrc)) { int endTime = 0; if (iterObjVar->second.get(endTime)) { std::map<uint32, std::pair<int, int> >::iterator iterFind = commandCooldownTimers.find(cooldownGroupCrc); if (iterFind == commandCooldownTimers.end()) { commandCooldownTimers[cooldownGroupCrc] = std::make_pair(0, endTime); } else { iterFind->second.second = endTime; } } } } } char buffer[256]; int const currentGameTime = static_cast<int>(ServerClock::getInstance().getGameTimeSeconds()); double const currentTime = Clock::getCurrentTime(); for (std::map<uint32, std::pair<int, int> >::const_iterator iterCooldown = commandCooldownTimers.begin(); iterCooldown != commandCooldownTimers.end(); ++iterCooldown) { // update the command queue with any unexpired cooldowns if ((iterCooldown->second.first > 0) && (iterCooldown->second.second > 0) && (iterCooldown->second.first <= currentGameTime) && (currentGameTime < iterCooldown->second.second)) { m_cooldowns.set(iterCooldown->first, std::make_pair(currentTime - static_cast<double>(currentGameTime - iterCooldown->second.first), currentTime + static_cast<double>(iterCooldown->second.second - currentGameTime))); } else { // cleanup the objvars for any expired/invalid cooldowns snprintf(buffer, sizeof(buffer)-1, "commandCooldown.beginTime.%lu", iterCooldown->first); buffer[sizeof(buffer)-1] = '\0'; creatureOwner->removeObjVarItem(buffer); snprintf(buffer, sizeof(buffer)-1, "commandCooldown.endTime.%lu", iterCooldown->first); buffer[sizeof(buffer)-1] = '\0'; creatureOwner->removeObjVarItem(buffer); } } } // ---------------------------------------------------------------------- bool CommandQueue::hasCommandFromGroup(uint32 groupHash) const { for (EntryList::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) if ((*i).m_command->m_commandGroup == groupHash) return true; return false; } // ---------------------------------------------------------------------- void CommandQueue::clearCommandsFromGroup(uint32 groupHash, bool force) { // iterate over each command in the queue for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); /* nil */ ) { EntryList::iterator j = it++; const CommandQueueEntry &entry = *j; if ( entry.m_command->m_commandGroup == groupHash && ( force || entry.m_clearable ) ) { // decrement the combat entry count if this is a combat command // and update client handleEntryRemoved(entry ); // if this is the top of the queue, we need to put the queue into a waiting state if ( j == m_queue.begin() ) { cancelCurrentCommand(); } else { // remove item from queue m_queue.erase( j ); } } } } // ---------------------------------------------------------------------- void CommandQueue::handleEntryRemoved(CommandQueueEntry const &entry, bool notifyClient) { DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::handleEntryRemoved(%s, %d)\n", entry.m_command->m_commandName.c_str(), notifyClient ? 1 : 0 ) ); ServerObject const & serverOwner = getServerOwner(); if ( entry.m_command->m_addToCombatQueue && ( m_combatCount.get() > 0 ) ) { m_combatCount = m_combatCount.get() - 1; } // If we have a sequenceId, then the owner's client is interested in // hearing about the removal of that command. if (serverOwner.isAuthoritative() && notifyClient) { notifyClientOfCommandRemoval(entry.m_sequenceId, 0.0f, m_status, m_statusDetail); } } // ---------------------------------------------------------------------- void CommandQueue::notifyClientOfCommandRemoval(uint32 sequenceId, float waitTime, Command::ErrorCode status, int statusDetail) { DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::notifyClientOfCommandRemoval(%d, %f, %d, %d)\n", static_cast<int>(sequenceId), waitTime, status, statusDetail ) ); CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if ( (creatureOwner != NULL) && creatureOwner->getClient() && (sequenceId != 0)) { WARNING(status < 0 || status >= Command::CEC_Max, ("CommandQueue::notifyClientOfCommandRemoval received invalid status %d", static_cast<int>(status))); creatureOwner->getController()->appendMessage( static_cast<int>(CM_commandQueueRemove), 0.0f, new MessageQueueCommandQueueRemove(sequenceId, waitTime, static_cast<int>(status), statusDetail), GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); } } // ---------------------------------------------------------------------- const char *CommandQueue::getStateAsString( State state ) { static const char * states[] = { "waiting", "warmup", "execute", "?unknown?" }; if ( state > State_MAX ) { state = State_MAX; } return states[ state ]; } // ---------------------------------------------------------------------- bool CommandQueue::setCommandTimerValue(TimerClass timerClass, float newValue ) { FATAL( timerClass >= (int)m_commandTimes.size(), ( "CommandQueue::setCommandTimerValue(): invalid timer class %d\n", timerClass ) ); FATAL( fabsf( newValue ) > cs_secondsPerDay, ( "tried to set a command timer outside allowed range. (value=%f)\n", newValue ) ); if ( m_state.get() == State_Waiting ) { return false; } if ( ( timerClass == TimerClass_Warmup && m_state.get() == State_Warmup ) || ( timerClass == TimerClass_Execute && m_state.get() == State_Execute ) ) { m_nextEventTime = m_eventStartTime.get() + newValue; } m_commandTimes.set( timerClass, newValue ); DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::setCommandTimerValue() timerClass=%d m_nextEventTime=%f newValue=%f\n", timerClass, m_nextEventTime.get(), newValue ) ); updateClient(timerClass ); return true; } // ---------------------------------------------------------------------- void CommandQueue::cancelCurrentCommand() { DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::cancelCurrentCommand()\n" ) ); WARNING( m_queue.empty(), ( "queue was empty.\n " ) ); if ( !m_queue.empty() ) { const CommandQueueEntry &entry = *(m_queue.begin()); m_nextEventTime = 0.f; m_status = Command::CEC_Cancelled; m_state = State_Waiting; handleEntryRemoved(entry, true); m_queue.pop(); } } // ---------------------------------------------------------------------- CommandQueue::State CommandQueue::getCurrentCommandState() const { return (State)m_state.get(); } // ---------------------------------------------------------------------- void CommandQueue::addToPackage(Archive::AutoDeltaByteStream &bs) { bs.addVariable(m_queue); bs.addVariable(m_state); bs.addVariable(m_nextEventTime); bs.addVariable(m_combatCount); bs.addVariable(m_eventStartTime); bs.addVariable(m_cooldowns); bs.addVariable(m_commandTimes); } // ---------------------------------------------------------------------- float CommandQueue::getCooldownTimeLeft( uint32 cooldownId ) const { CooldownMapType::const_iterator it = m_cooldowns.find( cooldownId ); float result = 0.f; if ( it != m_cooldowns.end() ) { result = static_cast< float > ( (*it).second.second - Clock::getCurrentTime() ); } return result; } // ---------------------------------------------------------------------- float CommandQueue::getCooldownTimeLeft( const std::string &name ) const { return getCooldownTimeLeft( Crc::normalizeAndCalculate( name.c_str() ) ); } //----------------------------------------------------------------------- void CommandQueue::executeCommand(Command const &command, NetworkId const &targetId, Unicode::String const &params, Command::ErrorCode &status, int &statusDetail, bool commandIsFromCommandQueue) { DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommand(%s, %s, %s, %d, %d)\n", Clock::getCurrentTime(), command.m_commandName.c_str(), targetId.getValueString().c_str(), Unicode::wideToNarrow(params).c_str(), status, statusDetail)); status = Command::CEC_Success; static bool s_tradeAllowedCommandsInit = false; typedef stdvector<uint32>::fwd Uint32Vector; static Uint32Vector s_tradeAllowedCommands; if (!s_tradeAllowedCommandsInit) { s_tradeAllowedCommandsInit = true; s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("addFriend")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("addIgnore")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("closeContainer")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("combatSpam")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("find")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("gc")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getAttributes")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getAttributesBatch")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getFriendList")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getIgnoreList")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("groupChat")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("groupChat")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("gsay")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("gtell")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("guildsay")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("kneel")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("maskscent")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("meditate")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("newbiehelper")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("openContainer")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("prose")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("removeFriend")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("removeIgnore")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestBiography")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestCharacterMatch")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestDraftSlots")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestManfSchematicSlots")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestResourceWeights")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMatchMakingCharacterId")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMatchMakingPersonalId")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMood")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMoodInternal")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setSpokenLanguage")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("sitServer")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("social")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("socialInternal")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("spatialChat")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("spatialChatInternal")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("stand")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("synchronizedUiListen")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("synchronizedUiStopListening")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("target")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("tip")); s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("waypoint")); s_tradeAllowedCommands.push_back (CommandTable::getNullCommand().m_commandHash); std::sort (s_tradeAllowedCommands.begin (), s_tradeAllowedCommands.end ()); } CreatureObject * const creatureOwner = getServerOwner().asCreatureObject(); if (creatureOwner != NULL) { CreatureController * const creatureController = creatureOwner->getCreatureController(); if (creatureController && creatureController->getSecureTrade()) { if (!std::binary_search (s_tradeAllowedCommands.begin (), s_tradeAllowedCommands.end (), command.m_commandHash)) { LOG ("Command", ("CreatureObject [%s] trade canceled by [%s] command", creatureOwner->getNetworkId ().getValueString ().c_str (), command.m_commandName.c_str ())); creatureController->getSecureTrade()->cancelTrade(*creatureOwner); } } // posture and ability verification - don't execute the command // if we're in a posture for which the command is not valid, or // we do not have the ability required for the command (if any) creatureOwner->doWarmupChecks( command, targetId, params, status, statusDetail ); if (status == Command::CEC_Success && command.m_godLevel > 0) { Client const *client = creatureOwner->getClient(); if (!client) { status = Command::CEC_GodLevel; LOGU("CustomerService", ("Avatar:%s tried to execute command %s >%s with no client", PlayerObject::getAccountDescription(creatureOwner).c_str(), command.m_commandName.c_str(), targetId.getValueString().c_str()), params); } else if (client->getGodLevel() < command.m_godLevel) { status = Command::CEC_GodLevel; LOGU("CustomerService", ("Avatar:%s doesn't have adequate level for command %s >%s", PlayerObject::getAccountDescription(creatureOwner).c_str(), command.m_commandName.c_str(), targetId.getValueString().c_str()), params); } else { LOGU("CustomerService", ("Avatar:%s has executed command %s >%s", PlayerObject::getAccountDescription(creatureOwner).c_str(), command.m_commandName.c_str(), targetId.getValueString().c_str()), params); } } } TangibleObject * const tangibleOwner = getServerOwner().asTangibleObject(); if (tangibleOwner != NULL) { // Really execute the command - swap targets if necessary, and call // forceExecuteCommand (which will handle messaging if not authoritative) if (status == Command::CEC_Success) { if (!command.m_callOnTarget) { DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::executeCommand(): tangibleOwner->forceExecuteCommand(%s, %s, %s, %d)\n", command.m_commandName.c_str(), targetId.getValueString().c_str(), Unicode::wideToNarrow(params).c_str(), status)); tangibleOwner->forceExecuteCommand(command, targetId, params, status, commandIsFromCommandQueue); } else { TangibleObject * const tangibleTarget = TangibleObject::getTangibleObject(targetId); if (tangibleTarget) { DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::executeCommand(): tangibleTarget->forceExecuteCommand(%s, %s, %s, %d)\n", command.m_commandName.c_str(), tangibleOwner->getNetworkId().getValueString().c_str(), Unicode::wideToNarrow(params).c_str(), status)); tangibleTarget->forceExecuteCommand(command, tangibleOwner->getNetworkId(), params, status, commandIsFromCommandQueue); } } } } } // ---------------------------------------------------------------------- CommandQueue * CommandQueue::getCommandQueue(Object & object) { Property * const property = object.getProperty(getClassPropertyId()); return (property != NULL) ? (static_cast<CommandQueue *>(property)) : NULL; } // ---------------------------------------------------------------------- ServerObject & CommandQueue::getServerOwner() { return *getOwner().asServerObject(); } // ---------------------------------------------------------------------- ServerObject const & CommandQueue::getServerOwner() const { return *getOwner().asServerObject(); } // ---------------------------------------------------------------------- float CommandQueue::getCooldownTime(Command const &command) { if(command.isPrimaryCommand()) { CreatureObject * const creature = getServerOwner().asCreatureObject(); if(creature) { WeaponObject *weapon = creature->getCurrentWeapon(); if(weapon) return weapon->getAttackTime(); } } return command.m_coolTime; } // ---------------------------------------------------------------------- void CommandQueue::resetCooldowns() { m_commandTimes.set( TimerClass_Cooldown, 0.0f ); updateClient( TimerClass_Cooldown ); for (CooldownMapType::const_iterator iterCooldown = m_cooldowns.begin(); iterCooldown != m_cooldowns.end(); ++iterCooldown) { //has not expired if((*iterCooldown).second.second > (Clock::getCurrentTime() + FLT_EPSILON)) { //Reset the end of the cooldown to be right now m_cooldowns.set( (*iterCooldown).first, std::make_pair( (*iterCooldown).second.first, Clock::getCurrentTime() ) ); //notify client MessageQueueCommandTimer *msg = new MessageQueueCommandTimer( 0, (*iterCooldown).first, -1, 0 ); msg->setCurrentTime(MessageQueueCommandTimer::F_cooldown, 1.0f); msg->setMaxTime (MessageQueueCommandTimer::F_cooldown, 1.0f); CreatureObject * const creature = getServerOwner().asCreatureObject(); if(creature) { creature->getController()->appendMessage( static_cast< int >( CM_commandTimer ), 0.0f, msg, GameControllerMessageFlags::SEND | GameControllerMessageFlags::RELIABLE | GameControllerMessageFlags::DEST_AUTH_CLIENT); } } } } // ---------------------------------------------------------------------- void CommandQueue::spew(std::string * output) { CreatureObject * const creature = getServerOwner().asCreatureObject(); if(creature) { FormattedString<1024> fsOutput; char const * fsSprintfOutput; double const currentTime = Clock::getCurrentTime(); fsSprintfOutput = fsOutput.sprintf("%s current time [%.10f], m_queue size [%d], m_cooldowns size [%d], m_combatCount [%u]", creature->getNetworkId().getValueString().c_str(), currentTime, m_queue.size(), m_cooldowns.size(), m_combatCount.get()); if (output) { *output += fsSprintfOutput; *output += "\n"; } else { LOG("CommandQueueSpew", ("%s", fsSprintfOutput)); } for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); ) { EntryList::iterator j = it++; const CommandQueueEntry &entry = *j; fsSprintfOutput = fsOutput.sprintf("%s commandName [%s] hash[%lu] cd1[%lu] cd2[%lu]", creature->getNetworkId().getValueString().c_str(), entry.m_command->m_commandName.c_str(), entry.m_command->m_commandHash, entry.m_command->m_coolGroup, entry.m_command->m_coolGroup2); if (output) { *output += fsSprintfOutput; *output += "\n"; } else { LOG("CommandQueueSpew", ("%s", fsSprintfOutput)); } } for (CooldownMapType::const_iterator iterCooldown = m_cooldowns.begin(); iterCooldown != m_cooldowns.end(); ++iterCooldown) { fsSprintfOutput = fsOutput.sprintf("%s cooldown key [%lu] value1[%.10f] value2[%.10f] duration[%.10f] remaining[%.10f]", creature->getNetworkId().getValueString().c_str(), iterCooldown->first, iterCooldown->second.first, iterCooldown->second.second, iterCooldown->second.second - iterCooldown->second.first, iterCooldown->second.second - currentTime); if (output) { *output += fsSprintfOutput; *output += "\n"; } else { LOG("CommandQueueSpew", ("%s", fsSprintfOutput)); } } fsSprintfOutput = fsOutput.sprintf("%s m_commandTimes Warmup[%.10f] Execute[%.10f] Cooldown[%.10f] Cooldown2[%.10f]", creature->getNetworkId().getValueString().c_str(), m_commandTimes[TimerClass_Warmup], m_commandTimes[TimerClass_Execute], m_commandTimes[TimerClass_Cooldown], m_commandTimes[TimerClass_Cooldown2]); if (output) { *output += fsSprintfOutput; *output += "\n"; } else { LOG("CommandQueueSpew", ("%s", fsSprintfOutput)); } } } // ======================================================================
[ "lightlordmh@hotmail.com" ]
lightlordmh@hotmail.com
f250189da39de20a4448c28e9ec26ac17563d6ba
7121e3df80afdc58fdc10c664c08aee411a78181
/src/chrome/browser/ui/libgtkui/gtk_ui.cc
6bc83d0bfc97104f65da0c1a78ece232bdcc5b10
[ "BSD-3-Clause" ]
permissive
ochrisoyea/AccessControlListsintheDOM
93d0a1f77f7f3af864d4a2942e4590af9065a7d8
9a8796f899592d236628f4d3007337ff5743c32f
refs/heads/master
2020-06-08T14:31:37.838842
2019-06-22T16:17:41
2019-06-22T16:17:41
193,242,663
0
0
null
2019-06-22T14:24:31
2019-06-22T14:24:31
null
UTF-8
C++
false
false
43,883
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/libgtkui/gtk_ui.h" #include <dlfcn.h> #include <gdk/gdk.h> #include <math.h> #include <pango/pango.h> #include <cmath> #include <set> #include <utility> #include "base/command_line.h" #include "base/debug/leak_annotations.h" #include "base/environment.h" #include "base/i18n/rtl.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/protected_memory.h" #include "base/memory/protected_memory_cfi.h" #include "base/nix/mime_util_xdg.h" #include "base/nix/xdg_util.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/ui/libgtkui/app_indicator_icon.h" #include "chrome/browser/ui/libgtkui/chrome_gtk_frame.h" #include "chrome/browser/ui/libgtkui/gtk_event_loop.h" #include "chrome/browser/ui/libgtkui/gtk_key_bindings_handler.h" #include "chrome/browser/ui/libgtkui/gtk_status_icon.h" #include "chrome/browser/ui/libgtkui/gtk_util.h" #include "chrome/browser/ui/libgtkui/print_dialog_gtk.h" #include "chrome/browser/ui/libgtkui/printing_gtk_util.h" #include "chrome/browser/ui/libgtkui/select_file_dialog_impl.h" #include "chrome/browser/ui/libgtkui/skia_utils_gtk.h" #include "chrome/browser/ui/libgtkui/unity_service.h" #include "chrome/browser/ui/libgtkui/x11_input_method_context_impl_gtk.h" #include "printing/buildflags/buildflags.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkShader.h" #include "ui/base/resource/resource_bundle.h" #include "ui/display/display.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_render_params.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_source.h" #include "ui/gfx/skbitmap_operations.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/x/x11.h" #include "ui/gfx/x/x11_types.h" #include "ui/native_theme/native_theme.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/views/controls/button/blue_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/linux_ui/device_scale_factor_observer.h" #include "ui/views/linux_ui/window_button_order_observer.h" #include "ui/views/resources/grit/views_resources.h" #if GTK_MAJOR_VERSION == 2 #include "chrome/browser/ui/libgtkui/native_theme_gtk2.h" // nogncheck #elif GTK_MAJOR_VERSION == 3 #include "chrome/browser/ui/libgtkui/native_theme_gtk3.h" // nogncheck #include "chrome/browser/ui/libgtkui/nav_button_provider_gtk3.h" // nogncheck #include "chrome/browser/ui/libgtkui/settings_provider_gtk3.h" // nogncheck #endif #if defined(USE_GIO) #include "chrome/browser/ui/libgtkui/settings_provider_gsettings.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "printing/printing_context_linux.h" #endif #if BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS) #include "chrome/browser/ui/views/nav_button_provider.h" #endif // A minimized port of GtkThemeService into something that can provide colors // and images for aura. // // TODO(erg): There's still a lot that needs ported or done for the first time: // // - Render and inject the omnibox background. // - Make sure to test with a light on dark theme, too. namespace libgtkui { namespace { const double kDefaultDPI = 96; class GtkButtonImageSource : public gfx::ImageSkiaSource { public: GtkButtonImageSource(const char* idr_string, gfx::Size size) : width_(size.width()), height_(size.height()) { is_blue_ = !!strstr(idr_string, "IDR_BLUE"); focus_ = !!strstr(idr_string, "_FOCUSED_"); if (strstr(idr_string, "_DISABLED")) { state_ = ui::NativeTheme::kDisabled; } else if (strstr(idr_string, "_HOVER")) { state_ = ui::NativeTheme::kHovered; } else if (strstr(idr_string, "_PRESSED")) { state_ = ui::NativeTheme::kPressed; } else { state_ = ui::NativeTheme::kNormal; } } ~GtkButtonImageSource() override {} gfx::ImageSkiaRep GetImageForScale(float scale) override { int width = width_ * scale; int height = height_ * scale; SkBitmap border; border.allocN32Pixels(width, height); border.eraseColor(0); cairo_surface_t* surface = cairo_image_surface_create_for_data( static_cast<unsigned char*>(border.getAddr(0, 0)), CAIRO_FORMAT_ARGB32, width, height, width * 4); cairo_t* cr = cairo_create(surface); #if GTK_MAJOR_VERSION == 2 // Create a temporary GTK button to snapshot GtkWidget* window = gtk_offscreen_window_new(); GtkWidget* button = gtk_toggle_button_new(); if (state_ == ui::NativeTheme::kPressed) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), true); else if (state_ == ui::NativeTheme::kDisabled) gtk_widget_set_sensitive(button, false); gtk_widget_set_size_request(button, width, height); gtk_container_add(GTK_CONTAINER(window), button); if (is_blue_) TurnButtonBlue(button); gtk_widget_show_all(window); if (focus_) GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS); int w, h; GdkPixmap* pixmap; { // http://crbug.com/346740 ANNOTATE_SCOPED_MEMORY_LEAK; pixmap = gtk_widget_get_snapshot(button, nullptr); } gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h); GdkColormap* colormap = gdk_drawable_get_colormap(pixmap); GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable( nullptr, GDK_DRAWABLE(pixmap), colormap, 0, 0, 0, 0, w, h); gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0); cairo_paint(cr); g_object_unref(pixbuf); g_object_unref(pixmap); gtk_widget_destroy(window); #else ScopedStyleContext context = GetStyleContextFromCss( is_blue_ ? "GtkButton#button.default.suggested-action" : "GtkButton#button"); GtkStateFlags state_flags = StateToStateFlags(state_); if (focus_) { state_flags = static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_FOCUSED); } gtk_style_context_set_state(context, state_flags); gtk_render_background(context, cr, 0, 0, width, height); gtk_render_frame(context, cr, 0, 0, width, height); if (focus_) { gfx::Rect focus_rect(width, height); if (!GtkVersionCheck(3, 14)) { gint focus_pad; gtk_style_context_get_style(context, "focus-padding", &focus_pad, nullptr); focus_rect.Inset(focus_pad, focus_pad); if (state_ == ui::NativeTheme::kPressed) { gint child_displacement_x, child_displacement_y; gboolean displace_focus; gtk_style_context_get_style( context, "child-displacement-x", &child_displacement_x, "child-displacement-y", &child_displacement_y, "displace-focus", &displace_focus, nullptr); if (displace_focus) focus_rect.Offset(child_displacement_x, child_displacement_y); } } if (!GtkVersionCheck(3, 20)) { GtkBorder border; gtk_style_context_get_border(context, state_flags, &border); focus_rect.Inset(border.left, border.top, border.right, border.bottom); } gtk_render_focus(context, cr, focus_rect.x(), focus_rect.y(), focus_rect.width(), focus_rect.height()); } #endif cairo_destroy(cr); cairo_surface_destroy(surface); return gfx::ImageSkiaRep(border, scale); } private: bool is_blue_; bool focus_; ui::NativeTheme::State state_; int width_; int height_; DISALLOW_COPY_AND_ASSIGN(GtkButtonImageSource); }; class GtkButtonPainter : public views::Painter { public: explicit GtkButtonPainter(std::string idr) : idr_(idr) {} ~GtkButtonPainter() override {} gfx::Size GetMinimumSize() const override { return gfx::Size(); } void Paint(gfx::Canvas* canvas, const gfx::Size& size) override { gfx::ImageSkia image( std::make_unique<GtkButtonImageSource>(idr_.c_str(), size), 1); canvas->DrawImageInt(image, 0, 0); } private: std::string idr_; DISALLOW_COPY_AND_ASSIGN(GtkButtonPainter); }; struct GObjectDeleter { void operator()(void* ptr) { g_object_unref(ptr); } }; struct GtkIconInfoDeleter { void operator()(GtkIconInfo* ptr) { G_GNUC_BEGIN_IGNORE_DEPRECATIONS gtk_icon_info_free(ptr); G_GNUC_END_IGNORE_DEPRECATIONS } }; typedef std::unique_ptr<GIcon, GObjectDeleter> ScopedGIcon; typedef std::unique_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo; typedef std::unique_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf; // Prefix for app indicator ids const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_"; // Number of app indicators used (used as part of app-indicator id). int indicators_count; // The unknown content type. const char* kUnknownContentType = "application/octet-stream"; std::unique_ptr<SettingsProvider> CreateSettingsProvider(GtkUi* gtk_ui) { #if GTK_MAJOR_VERSION == 3 if (GtkVersionCheck(3, 14)) return std::make_unique<SettingsProviderGtk3>(gtk_ui); #endif #if defined(USE_GIO) return std::make_unique<SettingsProviderGSettings>(gtk_ui); #else return nullptr; #endif } // Returns a gfx::FontRenderParams corresponding to GTK's configuration. gfx::FontRenderParams GetGtkFontRenderParams() { GtkSettings* gtk_settings = gtk_settings_get_default(); CHECK(gtk_settings); gint antialias = 0; gint hinting = 0; gchar* hint_style = nullptr; gchar* rgba = nullptr; g_object_get(gtk_settings, "gtk-xft-antialias", &antialias, "gtk-xft-hinting", &hinting, "gtk-xft-hintstyle", &hint_style, "gtk-xft-rgba", &rgba, nullptr); gfx::FontRenderParams params; params.antialiasing = antialias != 0; if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) { params.hinting = gfx::FontRenderParams::HINTING_NONE; } else if (strcmp(hint_style, "hintslight") == 0) { params.hinting = gfx::FontRenderParams::HINTING_SLIGHT; } else if (strcmp(hint_style, "hintmedium") == 0) { params.hinting = gfx::FontRenderParams::HINTING_MEDIUM; } else if (strcmp(hint_style, "hintfull") == 0) { params.hinting = gfx::FontRenderParams::HINTING_FULL; } else { LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\""; params.hinting = gfx::FontRenderParams::HINTING_NONE; } if (!rgba || strcmp(rgba, "none") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE; } else if (strcmp(rgba, "rgb") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB; } else if (strcmp(rgba, "bgr") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR; } else if (strcmp(rgba, "vrgb") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB; } else if (strcmp(rgba, "vbgr") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR; } else { LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\""; params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE; } g_free(hint_style); g_free(rgba); return params; } views::LinuxUI::NonClientWindowFrameAction GetDefaultMiddleClickAction() { #if GTK_MAJOR_VERSION == 3 if (GtkVersionCheck(3, 14)) return views::LinuxUI::WINDOW_FRAME_ACTION_NONE; #endif std::unique_ptr<base::Environment> env(base::Environment::Create()); switch (base::nix::GetDesktopEnvironment(env.get())) { case base::nix::DESKTOP_ENVIRONMENT_KDE4: case base::nix::DESKTOP_ENVIRONMENT_KDE5: // Starting with KDE 4.4, windows' titlebars can be dragged with the // middle mouse button to create tab groups. We don't support that in // Chrome, but at least avoid lowering windows in response to middle // clicks to avoid surprising users who expect the KDE behavior. return views::LinuxUI::WINDOW_FRAME_ACTION_NONE; default: return views::LinuxUI::WINDOW_FRAME_ACTION_LOWER; } } #if GTK_MAJOR_VERSION > 2 // COLOR_TOOLBAR_TOP_SEPARATOR represents the border between tabs and the // frame, as well as the border between tabs and the toolbar. For this // reason, it is difficult to calculate the One True Color that works well on // all themes and is opaque. However, we can cheat to get a good color that // works well for both borders. The idea is we have two variables: alpha and // lightness. And we have two constraints (on lightness): // 1. the border color, when painted on |header_bg|, should give |header_fg| // 2. the border color, when painted on |tab_bg|, should give |tab_fg| // This gives the equations: // alpha*lightness + (1 - alpha)*header_bg = header_fg // alpha*lightness + (1 - alpha)*tab_bg = tab_fg // The algorithm below is just a result of solving those equations for alpha // and lightness. If a problem is encountered, like division by zero, or // |a| or |l| not in [0, 1], then fallback on |header_fg| or |tab_fg|. SkColor GetToolbarTopSeparatorColor(SkColor header_fg, SkColor header_bg, SkColor tab_fg, SkColor tab_bg) { using namespace color_utils; SkColor default_color = SkColorGetA(header_fg) ? header_fg : tab_fg; if (!SkColorGetA(default_color)) return SK_ColorTRANSPARENT; auto get_lightness = [](SkColor color) { HSL hsl; SkColorToHSL(color, &hsl); return hsl.l; }; double f1 = get_lightness(GetResultingPaintColor(header_fg, header_bg)); double b1 = get_lightness(header_bg); double f2 = get_lightness(GetResultingPaintColor(tab_fg, tab_bg)); double b2 = get_lightness(tab_bg); if (b1 == b2) return default_color; double a = (f1 - f2 - b1 + b2) / (b2 - b1); if (a == 0) return default_color; double l = (f1 - (1 - a) * b1) / a; if (a < 0 || a > 1 || l < 0 || l > 1) return default_color; // Take the hue and saturation from |default_color|, but use the // calculated lightness. HSL border; SkColorToHSL(default_color, &border); border.l = l; return HSLToSkColor(border, a * 0xff); } #endif #if GTK_MAJOR_VERSION > 2 using GdkSetAllowedBackendsFn = void (*)(const gchar*); // Place this function pointers in read-only memory after being resolved to // prevent it being tampered with. See crbug.com/771365 for details. PROTECTED_MEMORY_SECTION base::ProtectedMemory<GdkSetAllowedBackendsFn> g_gdk_set_allowed_backends; #endif } // namespace GtkUi::GtkUi() { window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_DOUBLE_CLICK] = views::LinuxUI::WINDOW_FRAME_ACTION_TOGGLE_MAXIMIZE; window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_MIDDLE_CLICK] = GetDefaultMiddleClickAction(); window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_RIGHT_CLICK] = views::LinuxUI::WINDOW_FRAME_ACTION_MENU; #if GTK_MAJOR_VERSION > 2 // Force Gtk to use Xwayland if it would have used wayland. libgtkui assumes // the use of X11 (eg. X11InputMethodContextImplGtk) and will crash under // other backends. // TODO(thomasanderson): Change this logic once Wayland support is added. static base::ProtectedMemory<GdkSetAllowedBackendsFn>::Initializer init( &g_gdk_set_allowed_backends, reinterpret_cast<void (*)(const gchar*)>( dlsym(GetGdkSharedLibrary(), "gdk_set_allowed_backends"))); if (GtkVersionCheck(3, 10)) DCHECK(*g_gdk_set_allowed_backends); if (*g_gdk_set_allowed_backends) base::UnsanitizedCfiCall(g_gdk_set_allowed_backends)("x11"); #endif #if GTK_MAJOR_VERSION >= 3 // Avoid GTK initializing atk-bridge, and let AuraLinux implementation // do it once it is ready. std::unique_ptr<base::Environment> env(base::Environment::Create()); env->SetVar("NO_AT_BRIDGE", "1"); #endif GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess()); #if GTK_MAJOR_VERSION == 2 native_theme_ = NativeThemeGtk2::instance(); fake_window_ = chrome_gtk_frame_new(); #elif GTK_MAJOR_VERSION == 3 native_theme_ = NativeThemeGtk3::instance(); fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); #else #error "Unsupported GTK version" #endif gtk_widget_realize(fake_window_); } GtkUi::~GtkUi() { gtk_widget_destroy(fake_window_); } void OnThemeChanged(GObject* obj, GParamSpec* param, GtkUi* gtkui) { gtkui->ResetStyle(); } void GtkUi::Initialize() { GtkSettings* settings = gtk_settings_get_default(); g_signal_connect_after(settings, "notify::gtk-theme-name", G_CALLBACK(OnThemeChanged), this); g_signal_connect_after(settings, "notify::gtk-icon-theme-name", G_CALLBACK(OnThemeChanged), this); GdkScreen* screen = gdk_screen_get_default(); // Listen for DPI changes. g_signal_connect_after(screen, "notify::resolution", G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk), this); // Listen for scale factor changes. We would prefer to listen on // |screen|, but there is no scale-factor property, so use an // unmapped window instead. g_signal_connect(fake_window_, "notify::scale-factor", G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk), this); LoadGtkValues(); #if BUILDFLAG(ENABLE_PRINTING) printing::PrintingContextLinux::SetCreatePrintDialogFunction( &PrintDialogGtk2::CreatePrintDialog); printing::PrintingContextLinux::SetPdfPaperSizeFunction( &GetPdfPaperSizeDeviceUnitsGtk); #endif // We must build this after GTK gets initialized. settings_provider_ = CreateSettingsProvider(this); indicators_count = 0; // Instantiate the singleton instance of Gtk2EventLoop. Gtk2EventLoop::GetInstance(); } bool GtkUi::GetTint(int id, color_utils::HSL* tint) const { switch (id) { // Tints for which the cross-platform default is fine. Before adding new // values here, specifically verify they work well on Linux. case ThemeProperties::TINT_BACKGROUND_TAB: // TODO(estade): Return something useful for TINT_BUTTONS so that chrome:// // page icons are colored appropriately. case ThemeProperties::TINT_BUTTONS: break; default: // Assume any tints not specifically verified on Linux aren't usable. // TODO(pkasting): Try to remove values from |colors_| that could just be // added to the group above instead. NOTREACHED(); } return false; } bool GtkUi::GetColor(int id, SkColor* color) const { ColorMap::const_iterator it = colors_.find(id); if (it != colors_.end()) { *color = it->second; return true; } return false; } SkColor GtkUi::GetFocusRingColor() const { return focus_ring_color_; } SkColor GtkUi::GetThumbActiveColor() const { return thumb_active_color_; } SkColor GtkUi::GetThumbInactiveColor() const { return thumb_inactive_color_; } SkColor GtkUi::GetTrackColor() const { return track_color_; } SkColor GtkUi::GetActiveSelectionBgColor() const { return active_selection_bg_color_; } SkColor GtkUi::GetActiveSelectionFgColor() const { return active_selection_fg_color_; } SkColor GtkUi::GetInactiveSelectionBgColor() const { return inactive_selection_bg_color_; } SkColor GtkUi::GetInactiveSelectionFgColor() const { return inactive_selection_fg_color_; } base::TimeDelta GtkUi::GetCursorBlinkInterval() const { // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is // the default value for gtk-cursor-blink-time. static const gint kGtkDefaultCursorBlinkTime = 1200; // Dividing GTK's cursor blink cycle time (in milliseconds) by this value // yields an appropriate value for // content::RendererPreferences::caret_blink_interval. This matches the // logic in the WebKit GTK port. static const double kGtkCursorBlinkCycleFactor = 2000.0; gint cursor_blink_time = kGtkDefaultCursorBlinkTime; gboolean cursor_blink = TRUE; g_object_get(gtk_settings_get_default(), "gtk-cursor-blink-time", &cursor_blink_time, "gtk-cursor-blink", &cursor_blink, nullptr); return cursor_blink ? base::TimeDelta::FromSecondsD( cursor_blink_time / kGtkCursorBlinkCycleFactor) : base::TimeDelta(); } ui::NativeTheme* GtkUi::GetNativeTheme(aura::Window* window) const { ui::NativeTheme* native_theme_override = nullptr; if (!native_theme_overrider_.is_null()) native_theme_override = native_theme_overrider_.Run(window); if (native_theme_override) return native_theme_override; return native_theme_; } void GtkUi::SetNativeThemeOverride(const NativeThemeGetter& callback) { native_theme_overrider_ = callback; } bool GtkUi::GetDefaultUsesSystemTheme() const { std::unique_ptr<base::Environment> env(base::Environment::Create()); switch (base::nix::GetDesktopEnvironment(env.get())) { case base::nix::DESKTOP_ENVIRONMENT_CINNAMON: case base::nix::DESKTOP_ENVIRONMENT_GNOME: case base::nix::DESKTOP_ENVIRONMENT_PANTHEON: case base::nix::DESKTOP_ENVIRONMENT_UNITY: case base::nix::DESKTOP_ENVIRONMENT_XFCE: return true; case base::nix::DESKTOP_ENVIRONMENT_KDE3: case base::nix::DESKTOP_ENVIRONMENT_KDE4: case base::nix::DESKTOP_ENVIRONMENT_KDE5: case base::nix::DESKTOP_ENVIRONMENT_OTHER: return false; } // Unless GetDesktopEnvironment() badly misbehaves, this should never happen. NOTREACHED(); return false; } void GtkUi::SetDownloadCount(int count) const { if (unity::IsRunning()) unity::SetDownloadCount(count); } void GtkUi::SetProgressFraction(float percentage) const { if (unity::IsRunning()) unity::SetProgressFraction(percentage); } bool GtkUi::IsStatusIconSupported() const { return true; } std::unique_ptr<views::StatusIconLinux> GtkUi::CreateLinuxStatusIcon( const gfx::ImageSkia& image, const base::string16& tool_tip) const { if (AppIndicatorIcon::CouldOpen()) { ++indicators_count; return std::unique_ptr<views::StatusIconLinux>(new AppIndicatorIcon( base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count), image, tool_tip)); } else { return std::unique_ptr<views::StatusIconLinux>( new Gtk2StatusIcon(image, tool_tip)); } } gfx::Image GtkUi::GetIconForContentType(const std::string& content_type, int size) const { // This call doesn't take a reference. GtkIconTheme* theme = gtk_icon_theme_get_default(); std::string content_types[] = {content_type, kUnknownContentType}; for (size_t i = 0; i < arraysize(content_types); ++i) { ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str())); ScopedGtkIconInfo icon_info(gtk_icon_theme_lookup_by_gicon( theme, icon.get(), size, static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE))); if (!icon_info) continue; ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), nullptr)); if (!pixbuf) continue; SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get()); DCHECK_EQ(size, bitmap.width()); DCHECK_EQ(size, bitmap.height()); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); image_skia.MakeThreadSafe(); return gfx::Image(image_skia); } return gfx::Image(); } std::unique_ptr<views::Border> GtkUi::CreateNativeBorder( views::LabelButton* owning_button, std::unique_ptr<views::LabelButtonBorder> border) { if (owning_button->GetNativeTheme() != native_theme_) return std::move(border); std::unique_ptr<views::LabelButtonAssetBorder> gtk_border( new views::LabelButtonAssetBorder(owning_button->style())); gtk_border->set_insets(border->GetInsets()); static struct { const char* idr; const char* idr_blue; bool focus; views::Button::ButtonState state; } const paintstate[] = { { "IDR_BUTTON_NORMAL", "IDR_BLUE_BUTTON_NORMAL", false, views::Button::STATE_NORMAL, }, { "IDR_BUTTON_HOVER", "IDR_BLUE_BUTTON_HOVER", false, views::Button::STATE_HOVERED, }, { "IDR_BUTTON_PRESSED", "IDR_BLUE_BUTTON_PRESSED", false, views::Button::STATE_PRESSED, }, { "IDR_BUTTON_DISABLED", "IDR_BLUE_BUTTON_DISABLED", false, views::Button::STATE_DISABLED, }, { "IDR_BUTTON_FOCUSED_NORMAL", "IDR_BLUE_BUTTON_FOCUSED_NORMAL", true, views::Button::STATE_NORMAL, }, { "IDR_BUTTON_FOCUSED_HOVER", "IDR_BLUE_BUTTON_FOCUSED_HOVER", true, views::Button::STATE_HOVERED, }, { "IDR_BUTTON_FOCUSED_PRESSED", "IDR_BLUE_BUTTON_FOCUSED_PRESSED", true, views::Button::STATE_PRESSED, }, { "IDR_BUTTON_DISABLED", "IDR_BLUE_BUTTON_DISABLED", true, views::Button::STATE_DISABLED, }, }; bool is_blue = owning_button->GetClassName() == views::BlueButton::kViewClassName; for (unsigned i = 0; i < arraysize(paintstate); i++) { std::string idr = is_blue ? paintstate[i].idr_blue : paintstate[i].idr; gtk_border->SetPainter( paintstate[i].focus, paintstate[i].state, border->PaintsButtonState(paintstate[i].focus, paintstate[i].state) ? std::make_unique<GtkButtonPainter>(idr) : nullptr); } return std::move(gtk_border); } void GtkUi::AddWindowButtonOrderObserver( views::WindowButtonOrderObserver* observer) { if (nav_buttons_set_) observer->OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_); window_button_order_observer_list_.AddObserver(observer); } void GtkUi::RemoveWindowButtonOrderObserver( views::WindowButtonOrderObserver* observer) { window_button_order_observer_list_.RemoveObserver(observer); } void GtkUi::SetWindowButtonOrdering( const std::vector<views::FrameButton>& leading_buttons, const std::vector<views::FrameButton>& trailing_buttons) { leading_buttons_ = leading_buttons; trailing_buttons_ = trailing_buttons; nav_buttons_set_ = true; for (views::WindowButtonOrderObserver& observer : window_button_order_observer_list_) { observer.OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_); } } void GtkUi::SetNonClientWindowFrameAction( NonClientWindowFrameActionSourceType source, NonClientWindowFrameAction action) { window_frame_actions_[source] = action; } std::unique_ptr<ui::LinuxInputMethodContext> GtkUi::CreateInputMethodContext( ui::LinuxInputMethodContextDelegate* delegate, bool is_simple) const { return std::unique_ptr<ui::LinuxInputMethodContext>( new X11InputMethodContextImplGtk2(delegate, is_simple)); } gfx::FontRenderParams GtkUi::GetDefaultFontRenderParams() const { static gfx::FontRenderParams params = GetGtkFontRenderParams(); return params; } void GtkUi::GetDefaultFontDescription(std::string* family_out, int* size_pixels_out, int* style_out, gfx::Font::Weight* weight_out, gfx::FontRenderParams* params_out) const { *family_out = default_font_family_; *size_pixels_out = default_font_size_pixels_; *style_out = default_font_style_; *weight_out = default_font_weight_; *params_out = default_font_render_params_; } ui::SelectFileDialog* GtkUi::CreateSelectFileDialog( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) const { return SelectFileDialogImpl::Create(listener, std::move(policy)); } views::LinuxUI::NonClientWindowFrameAction GtkUi::GetNonClientWindowFrameAction( NonClientWindowFrameActionSourceType source) { return window_frame_actions_[source]; } void GtkUi::NotifyWindowManagerStartupComplete() { // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO // from http://standards.freedesktop.org/startup-notification-spec/ instead. gdk_notify_startup_complete(); } void GtkUi::AddDeviceScaleFactorObserver( views::DeviceScaleFactorObserver* observer) { device_scale_factor_observer_list_.AddObserver(observer); } void GtkUi::RemoveDeviceScaleFactorObserver( views::DeviceScaleFactorObserver* observer) { device_scale_factor_observer_list_.RemoveObserver(observer); } bool GtkUi::PreferDarkTheme() const { gboolean dark = false; g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", &dark, nullptr); return dark; } #if BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS) std::unique_ptr<views::NavButtonProvider> GtkUi::CreateNavButtonProvider() { if (GtkVersionCheck(3, 14)) return std::make_unique<libgtkui::NavButtonProviderGtk3>(); return nullptr; } #endif base::flat_map<std::string, std::string> GtkUi::GetKeyboardLayoutMap() { GdkDisplay* display = gdk_display_get_default(); GdkKeymap* keymap = gdk_keymap_get_for_display(display); auto map = base::flat_map<std::string, std::string>(); if (!keymap) return map; for (unsigned int i = 0; i < ui::kWritingSystemKeyDomCodeEntries; ++i) { ui::DomCode domcode = ui::writing_system_key_domcodes[i]; guint16 keycode = ui::KeycodeConverter::DomCodeToNativeKeycode(domcode); GdkKeymapKey* keys = nullptr; guint* keyvals = nullptr; gint n_entries = 0; // The order of the layouts is based on the system default ordering in // Keyboard Settings. The currently active layout does not affect this // order. if (gdk_keymap_get_entries_for_keycode(keymap, keycode, &keys, &keyvals, &n_entries)) { for (gint i = 0; i < n_entries; ++i) { // There are 4 entries per layout, one each for shift level 0..3. // We only care about the unshifted values (level = 0). if (keys[i].level != 0 || keyvals[i] >= 255) continue; char keystring[2]; keystring[0] = keyvals[i]; keystring[1] = '\0'; map.emplace(ui::KeycodeConverter::DomCodeToCodeString(domcode), keystring); break; } } g_free(keys); keys = nullptr; g_free(keyvals); keyvals = nullptr; } return map; } bool GtkUi::MatchEvent(const ui::Event& event, std::vector<ui::TextEditCommandAuraLinux>* commands) { // Ensure that we have a keyboard handler. if (!key_bindings_handler_) key_bindings_handler_.reset(new Gtk2KeyBindingsHandler); return key_bindings_handler_->MatchEvent(event, commands); } void GtkUi::OnDeviceScaleFactorMaybeChanged(void*, GParamSpec*) { UpdateDeviceScaleFactor(); } void GtkUi::SetScrollbarColors() { thumb_active_color_ = SkColorSetRGB(244, 244, 244); thumb_inactive_color_ = SkColorSetRGB(234, 234, 234); track_color_ = SkColorSetRGB(211, 211, 211); GetChromeStyleColor("scrollbar-slider-prelight-color", &thumb_active_color_); GetChromeStyleColor("scrollbar-slider-normal-color", &thumb_inactive_color_); GetChromeStyleColor("scrollbar-trough-color", &track_color_); } void GtkUi::LoadGtkValues() { // TODO(erg): GtkThemeService had a comment here about having to muck with // the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd // regress startup time. Figure out how to do that when we can't access the // prefs system from here. UpdateDeviceScaleFactor(); UpdateCursorTheme(); #if GTK_MAJOR_VERSION == 2 const color_utils::HSL kDefaultFrameShift = {-1, -1, 0.4}; SkColor frame_color = native_theme_->GetSystemColor(ui::NativeTheme::kColorId_WindowBackground); frame_color = color_utils::HSLShift(frame_color, kDefaultFrameShift); GetChromeStyleColor("frame-color", &frame_color); colors_[ThemeProperties::COLOR_FRAME] = frame_color; GtkStyle* style = gtk_rc_get_style(fake_window_); SkColor temp_color = color_utils::HSLShift( GdkColorToSkColor(style->bg[GTK_STATE_INSENSITIVE]), kDefaultFrameShift); GetChromeStyleColor("inactive-frame-color", &temp_color); colors_[ThemeProperties::COLOR_FRAME_INACTIVE] = temp_color; temp_color = color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito); GetChromeStyleColor("incognito-frame-color", &temp_color); colors_[ThemeProperties::COLOR_FRAME_INCOGNITO] = temp_color; temp_color = color_utils::HSLShift(frame_color, kDefaultTintFrameIncognitoInactive); GetChromeStyleColor("incognito-inactive-frame-color", &temp_color); colors_[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] = temp_color; SkColor tab_color = native_theme_->GetSystemColor(ui::NativeTheme::kColorId_DialogBackground); SkColor label_color = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_LabelEnabledColor); colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] = color_utils::DeriveDefaultIconColor(label_color); colors_[ThemeProperties::COLOR_TAB_TEXT] = label_color; colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = label_color; colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] = color_utils::BlendTowardOppositeLuma(label_color, 50); inactive_selection_bg_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldReadOnlyBackground); inactive_selection_fg_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldReadOnlyColor); // We pick the text and background colors for the NTP out of the // colors for a GtkEntry. We do this because GtkEntries background // color is never the same as |tab_color|, is usually a white, // and when it isn't a white, provides sufficient contrast to // |tab_color|. Try this out with Darklooks, HighContrastInverse // or ThinIce. colors_[ThemeProperties::COLOR_NTP_BACKGROUND] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultBackground); colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultColor); // The NTP header is the color that surrounds the current active // thumbnail on the NTP, and acts as the border of the "Recent // Links" box. It would be awesome if they were separated so we // could use GetBorderColor() for the border around the "Recent // Links" section, but matching the frame color is more important. colors_[ThemeProperties::COLOR_NTP_HEADER] = colors_[ThemeProperties::COLOR_FRAME]; #else std::string header_selector = GtkVersionCheck(3, 10) ? "#headerbar.header-bar.titlebar" : "GtkMenuBar#menubar"; SkColor frame_color = GetBgColor(header_selector); SkColor frame_color_inactive = GetBgColor(header_selector + ":backdrop"); colors_[ThemeProperties::COLOR_FRAME] = frame_color; colors_[ThemeProperties::COLOR_FRAME_INACTIVE] = frame_color_inactive; colors_[ThemeProperties::COLOR_FRAME_INCOGNITO] = color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito); colors_[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] = color_utils::HSLShift(frame_color_inactive, kDefaultTintFrameIncognito); SkColor tab_color = GetBgColor(""); SkColor tab_text_color = GetFgColor("GtkLabel"); colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] = tab_text_color; colors_[ThemeProperties::COLOR_TAB_TEXT] = tab_text_color; colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = tab_text_color; colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] = color_utils::BlendTowardOppositeLuma(tab_text_color, 50); SkColor location_bar_border = GetBorderColor("GtkEntry#entry"); if (SkColorGetA(location_bar_border)) colors_[ThemeProperties::COLOR_LOCATION_BAR_BORDER] = location_bar_border; inactive_selection_bg_color_ = GetSelectionBgColor( GtkVersionCheck(3, 20) ? "GtkTextView#textview.view:backdrop " "#text:backdrop #selection:backdrop" : "GtkTextView.view:selected:backdrop"); inactive_selection_fg_color_ = GetFgColor(GtkVersionCheck(3, 20) ? "GtkTextView#textview.view:backdrop " "#text:backdrop #selection:backdrop" : "GtkTextView.view:selected:backdrop"); SkColor tab_border = GetBorderColor("GtkButton#button"); colors_[ThemeProperties::COLOR_DETACHED_BOOKMARK_BAR_BACKGROUND] = tab_color; colors_[ThemeProperties::COLOR_BOOKMARK_BAR_INSTRUCTIONS_TEXT] = tab_text_color; // Separates the toolbar from the bookmark bar or butter bars. colors_[ThemeProperties::COLOR_TOOLBAR_BOTTOM_SEPARATOR] = tab_border; // Separates entries in the downloads bar. colors_[ThemeProperties::COLOR_TOOLBAR_VERTICAL_SEPARATOR] = tab_border; // These colors represent the border drawn around tabs and between // the tabstrip and toolbar. SkColor toolbar_top_separator = GetToolbarTopSeparatorColor( GetBorderColor(header_selector + " GtkButton#button"), frame_color, tab_border, tab_color); SkColor toolbar_top_separator_inactive = GetToolbarTopSeparatorColor( GetBorderColor(header_selector + ":backdrop GtkButton#button"), frame_color_inactive, tab_border, tab_color); // Unlike with toolbars, we always want a border around tabs, so let // ThemeService choose the border color if the theme doesn't provide one. if (SkColorGetA(toolbar_top_separator) && SkColorGetA(toolbar_top_separator_inactive)) { colors_[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR] = toolbar_top_separator; colors_[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR_INACTIVE] = toolbar_top_separator_inactive; } colors_[ThemeProperties::COLOR_NTP_BACKGROUND] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultBackground); colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultColor); colors_[ThemeProperties::COLOR_NTP_HEADER] = GetBorderColor("GtkButton#button"); #endif colors_[ThemeProperties::COLOR_TOOLBAR] = tab_color; colors_[ThemeProperties::COLOR_CONTROL_BACKGROUND] = tab_color; colors_[ThemeProperties::COLOR_NTP_LINK] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused); // Generate the colors that we pass to WebKit. SetScrollbarColors(); focus_ring_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_FocusedBorderColor); // Some GTK themes only define the text selection colors on the GtkEntry // class, so we need to use that for getting selection colors. active_selection_bg_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused); active_selection_fg_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldSelectionColor); colors_[ThemeProperties::COLOR_TAB_THROBBER_SPINNING] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_ThrobberSpinningColor); colors_[ThemeProperties::COLOR_TAB_THROBBER_WAITING] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_ThrobberWaitingColor); } void GtkUi::UpdateCursorTheme() { GtkSettings* settings = gtk_settings_get_default(); gchar* theme = nullptr; gint size = 0; g_object_get(settings, "gtk-cursor-theme-name", &theme, "gtk-cursor-theme-size", &size, nullptr); if (theme) XcursorSetTheme(gfx::GetXDisplay(), theme); if (size) XcursorSetDefaultSize(gfx::GetXDisplay(), size); g_free(theme); } void GtkUi::UpdateDefaultFont() { gfx::SetFontRenderParamsDeviceScaleFactor(device_scale_factor_); GtkWidget* fake_label = gtk_label_new(nullptr); g_object_ref_sink(fake_label); // Remove the floating reference. PangoContext* pc = gtk_widget_get_pango_context(fake_label); const PangoFontDescription* desc = pango_context_get_font_description(pc); // Use gfx::FontRenderParams to select a family and determine the rendering // settings. gfx::FontRenderParamsQuery query; query.families = base::SplitString(pango_font_description_get_family(desc), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (pango_font_description_get_size_is_absolute(desc)) { // If the size is absolute, it's specified in Pango units. There are // PANGO_SCALE Pango units in a device unit (pixel). const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE; default_font_size_pixels_ = size_pixels; query.pixel_size = size_pixels; } else { // Non-absolute sizes are in points (again scaled by PANGO_SIZE). // Round the value when converting to pixels to match GTK's logic. const double size_points = pango_font_description_get_size(desc) / static_cast<double>(PANGO_SCALE); default_font_size_pixels_ = static_cast<int>(kDefaultDPI / 72.0 * size_points + 0.5); query.point_size = static_cast<int>(size_points); } query.style = gfx::Font::NORMAL; query.weight = static_cast<gfx::Font::Weight>(pango_font_description_get_weight(desc)); // TODO(davemoore): What about PANGO_STYLE_OBLIQUE? if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC) query.style |= gfx::Font::ITALIC; default_font_render_params_ = gfx::GetFontRenderParams(query, &default_font_family_); default_font_style_ = query.style; gtk_widget_destroy(fake_label); g_object_unref(fake_label); } bool GtkUi::GetChromeStyleColor(const char* style_property, SkColor* ret_color) const { #if GTK_MAJOR_VERSION == 2 GdkColor* style_color = nullptr; gtk_widget_style_get(fake_window_, style_property, &style_color, nullptr); if (style_color) { *ret_color = GdkColorToSkColor(*style_color); gdk_color_free(style_color); return true; } #endif return false; } void GtkUi::ResetStyle() { LoadGtkValues(); native_theme_->NotifyObservers(); } float GtkUi::GetRawDeviceScaleFactor() { if (display::Display::HasForceDeviceScaleFactor()) return display::Display::GetForcedDeviceScaleFactor(); #if GTK_MAJOR_VERSION == 2 GtkSettings* gtk_settings = gtk_settings_get_default(); gint gtk_dpi = -1; g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, nullptr); const float scale_factor = gtk_dpi / (1024 * kDefaultDPI); #else GdkScreen* screen = gdk_screen_get_default(); gint scale = gtk_widget_get_scale_factor(fake_window_); DCHECK_GT(scale, 0); gdouble resolution = gdk_screen_get_resolution(screen); const float scale_factor = resolution <= 0 ? scale : resolution * scale / kDefaultDPI; #endif // Blacklist scaling factors <120% (crbug.com/484400) and round // to 1 decimal to prevent rendering problems (crbug.com/485183). return scale_factor < 1.2f ? 1.0f : roundf(scale_factor * 10) / 10; } void GtkUi::UpdateDeviceScaleFactor() { float old_device_scale_factor = device_scale_factor_; device_scale_factor_ = GetRawDeviceScaleFactor(); if (device_scale_factor_ != old_device_scale_factor) { for (views::DeviceScaleFactorObserver& observer : device_scale_factor_observer_list_) { observer.OnDeviceScaleFactorChanged(); } } UpdateDefaultFont(); } float GtkUi::GetDeviceScaleFactor() const { return device_scale_factor_; } } // namespace libgtkui views::LinuxUI* BuildGtkUi() { return new libgtkui::GtkUi; }
[ "heatherfarrar.ima@gmail.com" ]
heatherfarrar.ima@gmail.com
cfcdaf92ae1a9e6512a390c6755aed5288ccb417
2ca36f1406d6e6acad6e4f3663d1a1da4fe1ba25
/main/chase_value.h
60b4b1d38c7975b218a78574d9d02e49925e8410
[]
no_license
je-pu-pu/hand
ce24eacdfaa551a85ff2e2ad7e98b82b62d29541
bdbc33d5e4912972e0af8ab3cb529be06c9cfb88
refs/heads/master
2020-03-11T11:30:12.162397
2018-05-06T15:48:30
2018-05-06T15:48:30
129,971,200
1
0
null
null
null
null
UTF-8
C++
false
false
1,123
h
#ifndef COMMON_CHASE_VALUE_H #define COMMON_CHASE_VALUE_H #include "math.h" namespace common { template< typename Type > class chase_value { private: Type value_; Type target_value_; Type speed_; public: chase_value( Type value, Type target_value, Type speed ) : value_( value ) , target_value_( target_value ) , speed_( speed ) { } void chase() { value_ = math::chase( value_, target_value_, speed_ ); } void chase( Type speed ) { value_ = math::chase( value_, target_value_, speed ); } void fit_to_target() { value_ = target_value_; } void fit( Type v ) { value_ = v; target_value_ = v; } Type& value() { return value_; } Type value() const { return value_; } Type& target_value() { return target_value_; } Type target_value() const { return target_value_; } Type& speed() { return speed_; } Type speed() const { return speed_; } // Type operator Type () { return value_; } // Type operator Type () const { return value_; } }; // class chase_value } // namespace common #endif // COMMON_SERIALIZE_H
[ "je@je-pu-pu.jp" ]
je@je-pu-pu.jp
769f486f9eaea63e238ccf9611d4d47453dd6995
44b2b74338fd359e6535b216319799a1af2ec83c
/communect/searchuser.cpp
2ecafed1eb302d7b447f980bd778bd8a4fbf6939
[]
no_license
nozberkaryaindonesia/public
b0cb38f125012d6e931d46266d480729d422705e
528104029b7f8ebe5734ae6cc4374b5b84d6ef62
refs/heads/master
2022-06-05T16:02:33.100468
2014-04-07T06:27:34
2014-04-07T06:27:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
220
cpp
/*#include "searchuser.h" #include "ui_searchuser.h" searchuser::searchuser(QWidget *parent) : QDialog(parent), ui(new Ui::searchuser) { ui->setupUi(this); } searchuser::~searchuser() { delete ui; } */
[ "festinsalazarsison@gmail.com" ]
festinsalazarsison@gmail.com
3f0b05fa48c45733ac1251a4a7b2c9c5011829ff
470f1ea0c29e3c2b3e039dd390ff308e2a3d64b6
/homework/points2.cpp
92057a46218063fb5f148fb77bbbc7201dec0e77
[]
no_license
HOSHICHEN7267/1092CP2
655f81efd9281eb522d1c33f4168c855593a3b8c
c8cae852279269949141ba16ac714656ed5c24ac
refs/heads/master
2023-06-07T18:54:29.435412
2021-06-22T06:22:42
2021-06-22T06:22:42
344,451,013
0
0
null
null
null
null
UTF-8
C++
false
false
887
cpp
#include <iostream> #include <algorithm> #define SIZE 10000 using namespace std; int main(){ int num = 0; int ans = 0; float slope[SIZE] = {}; int points[SIZE][2] = {}; cin >> num; for(int i = 0 ; i < num ; ++i){ cin >> points[i][0] >> points[i][1]; } for(int i = 0 ; i < num ; ++i){ int cnt = 0; int sum = 1; for(int j = i + 1 ; j < num ; ++j){ if(i != j){ slope[cnt++] = (float)(points[i][1] - points[j][1]) / (float)(points[i][0] - points[j][0]); } } sort(slope, slope + cnt); for(int j = 0 ; j < cnt - 1 ; ++j){ if(slope[j] == slope[j+1]){ ++sum; } else{ ans = max(ans, sum); sum = 1; } } } cout << ans + 1 << '\n'; return 0; }
[ "antonychen5ds2@gmail.com" ]
antonychen5ds2@gmail.com
8f56f1db67726fe16f815bb7dcd50cad43c33e15
db6d5226ad3d8d213e06d59d3998a4ce2e9030bd
/src/addrman.cpp
b27f403849e3d5445adfbe9c30285bc66f89d3b7
[ "MIT" ]
permissive
Schilling99/SchillingCoin
9536c00d1bd8eef55482a398f3b5f12429938cb2
c9d7c4f70341e7ab552131e7e4a018197bc8558a
refs/heads/master
2022-12-26T14:58:40.917535
2020-10-08T12:33:38
2020-10-08T12:33:38
302,329,522
1
2
null
null
null
null
UTF-8
C++
false
false
16,094
cpp
// Copyright (c) 2012 Pieter Wuille // Copyright (c) 2012-2014 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Copyright (c) 2018-2020 The SchillingCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addrman.h" #include "hash.h" #include "serialize.h" #include "streams.h" int CAddrInfo::GetTriedBucket(const uint256& nKey) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_TRIED_BUCKET_COUNT; } int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const { std::vector<unsigned char> vchSourceGroupKey = src.GetGroup(); uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash(); uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash(); return hash2 % ADDRMAN_NEW_BUCKET_COUNT; } int CAddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int nBucket) const { uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash(); return hash1 % ADDRMAN_BUCKET_SIZE; } bool CAddrInfo::IsTerrible(int64_t nNow) const { if (nLastTry && nLastTry >= nNow - 60) // never remove things tried in the last minute return false; if (nTime > nNow + 10 * 60) // came in a flying DeLorean return true; if (nTime == 0 || nNow - nTime > ADDRMAN_HORIZON_DAYS * 24 * 60 * 60) // not seen in recent history return true; if (nLastSuccess == 0 && nAttempts >= ADDRMAN_RETRIES) // tried N times and never a success return true; if (nNow - nLastSuccess > ADDRMAN_MIN_FAIL_DAYS * 24 * 60 * 60 && nAttempts >= ADDRMAN_MAX_FAILURES) // N successive failures in the last week return true; return false; } double CAddrInfo::GetChance(int64_t nNow) const { double fChance = 1.0; int64_t nSinceLastSeen = nNow - nTime; int64_t nSinceLastTry = nNow - nLastTry; if (nSinceLastSeen < 0) nSinceLastSeen = 0; if (nSinceLastTry < 0) nSinceLastTry = 0; // deprioritize very recent attempts away if (nSinceLastTry < 60 * 10) fChance *= 0.01; // deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages. fChance *= pow(0.66, std::min(nAttempts, 8)); return fChance; } CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId) { std::map<CNetAddr, int>::iterator it = mapAddr.find(addr); if (it == mapAddr.end()) return NULL; if (pnId) *pnId = (*it).second; std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second); if (it2 != mapInfo.end()) return &(*it2).second; return NULL; } CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId) { int nId = nIdCount++; mapInfo[nId] = CAddrInfo(addr, addrSource); mapAddr[addr] = nId; mapInfo[nId].nRandomPos = vRandom.size(); vRandom.push_back(nId); if (pnId) *pnId = nId; return &mapInfo[nId]; } void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2) { if (nRndPos1 == nRndPos2) return; assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size()); int nId1 = vRandom[nRndPos1]; int nId2 = vRandom[nRndPos2]; assert(mapInfo.count(nId1) == 1); assert(mapInfo.count(nId2) == 1); mapInfo[nId1].nRandomPos = nRndPos2; mapInfo[nId2].nRandomPos = nRndPos1; vRandom[nRndPos1] = nId2; vRandom[nRndPos2] = nId1; } void CAddrMan::Delete(int nId) { assert(mapInfo.count(nId) != 0); CAddrInfo& info = mapInfo[nId]; assert(!info.fInTried); assert(info.nRefCount == 0); SwapRandom(info.nRandomPos, vRandom.size() - 1); vRandom.pop_back(); mapAddr.erase(info); mapInfo.erase(nId); nNew--; } void CAddrMan::ClearNew(int nUBucket, int nUBucketPos) { // if there is an entry in the specified bucket, delete it. if (vvNew[nUBucket][nUBucketPos] != -1) { int nIdDelete = vvNew[nUBucket][nUBucketPos]; CAddrInfo& infoDelete = mapInfo[nIdDelete]; assert(infoDelete.nRefCount > 0); infoDelete.nRefCount--; vvNew[nUBucket][nUBucketPos] = -1; if (infoDelete.nRefCount == 0) { Delete(nIdDelete); } } } void CAddrMan::MakeTried(CAddrInfo& info, int nId) { // remove the entry from all new buckets for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) { int pos = info.GetBucketPosition(nKey, true, bucket); if (vvNew[bucket][pos] == nId) { vvNew[bucket][pos] = -1; info.nRefCount--; } } nNew--; assert(info.nRefCount == 0); // which tried bucket to move the entry to int nKBucket = info.GetTriedBucket(nKey); int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket); // first make space to add it (the existing tried entry there is moved to new, deleting whatever is there). if (vvTried[nKBucket][nKBucketPos] != -1) { // find an item to evict int nIdEvict = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nIdEvict) == 1); CAddrInfo& infoOld = mapInfo[nIdEvict]; // Remove the to-be-evicted item from the tried set. infoOld.fInTried = false; vvTried[nKBucket][nKBucketPos] = -1; nTried--; // find which new bucket it belongs to int nUBucket = infoOld.GetNewBucket(nKey); int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket); ClearNew(nUBucket, nUBucketPos); assert(vvNew[nUBucket][nUBucketPos] == -1); // Enter it into the new set again. infoOld.nRefCount = 1; vvNew[nUBucket][nUBucketPos] = nIdEvict; nNew++; } assert(vvTried[nKBucket][nKBucketPos] == -1); vvTried[nKBucket][nKBucketPos] = nId; nTried++; info.fInTried = true; } void CAddrMan::Good_(const CService& addr, int64_t nTime) { int nId; nLastGood = nTime; CAddrInfo* pinfo = Find(addr, &nId); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastSuccess = nTime; info.nLastTry = nTime; info.nAttempts = 0; // nTime is not updated here, to avoid leaking information about // currently-connected peers. // if it is already in the tried set, don't do anything else if (info.fInTried) return; // find a bucket it is in now int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucket = -1; for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT; int nBpos = info.GetBucketPosition(nKey, true, nB); if (vvNew[nB][nBpos] == nId) { nUBucket = nB; break; } } // if no bucket is found, something bad happened; // TODO: maybe re-add the node, but for now, just bail out if (nUBucket == -1) return; LogPrint("addrman", "Moving %s to tried\n", addr.ToString()); // move nId to the tried tables MakeTried(info, nId); } bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty) { if (!addr.IsRoutable()) return false; bool fNew = false; int nId; CAddrInfo* pinfo = Find(addr, &nId); if (pinfo) { // periodically update nTime bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60); int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60); if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty)) pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty); // add services pinfo->nServices |= addr.nServices; // do not update if no new information is present if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime)) return false; // do not update if the entry was already in the "tried" table if (pinfo->fInTried) return false; // do not update if the max reference count is reached if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it int nFactor = 1; for (int n = 0; n < pinfo->nRefCount; n++) nFactor *= 2; if (nFactor > 1 && (RandomInt(nFactor) != 0)) return false; } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty); nNew++; fNew = true; } int nUBucket = pinfo->GetNewBucket(nKey, source); int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket); if (vvNew[nUBucket][nUBucketPos] != nId) { bool fInsert = vvNew[nUBucket][nUBucketPos] == -1; if (!fInsert) { CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]]; if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) { // Overwrite the existing new table entry. fInsert = true; } } if (fInsert) { ClearNew(nUBucket, nUBucketPos); pinfo->nRefCount++; vvNew[nUBucket][nUBucketPos] = nId; } else { if (pinfo->nRefCount == 0) { Delete(nId); } } } return fNew; } void CAddrMan::Attempt_(const CService& addr, bool fCountFailure, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info info.nLastTry = nTime; if (fCountFailure && info.nLastCountAttempt < nLastGood) { info.nLastCountAttempt = nTime; info.nAttempts++; } } CAddrInfo CAddrMan::Select_(bool newOnly) { if (size() == 0) return CAddrInfo(); if (newOnly && nNew == 0) return CAddrInfo(); // Use a 50% chance for choosing between tried and new table entries. if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) { // use a tried node double fChanceFactor = 1.0; while (1) { int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT); int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvTried[nKBucket][nKBucketPos] == -1) { nKBucket = (nKBucket + insecure_rand.randbits(ADDRMAN_TRIED_BUCKET_COUNT_LOG2)) % ADDRMAN_TRIED_BUCKET_COUNT; nKBucketPos = (nKBucketPos + insecure_rand.randbits(ADDRMAN_BUCKET_SIZE_LOG2)) % ADDRMAN_BUCKET_SIZE; } int nId = vvTried[nKBucket][nKBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } else { // use a new node double fChanceFactor = 1.0; while (1) { int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT); int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE); while (vvNew[nUBucket][nUBucketPos] == -1) { nUBucket = (nUBucket + insecure_rand.randbits(ADDRMAN_NEW_BUCKET_COUNT_LOG2)) % ADDRMAN_NEW_BUCKET_COUNT; nUBucketPos = (nUBucketPos + insecure_rand.randbits(ADDRMAN_BUCKET_SIZE_LOG2)) % ADDRMAN_BUCKET_SIZE; } int nId = vvNew[nUBucket][nUBucketPos]; assert(mapInfo.count(nId) == 1); CAddrInfo& info = mapInfo[nId]; if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30)) return info; fChanceFactor *= 1.2; } } } #ifdef DEBUG_ADDRMAN int CAddrMan::Check_() { std::set<int> setTried; std::map<int, int> mapNew; if (vRandom.size() != nTried + nNew) return -7; for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++) { int n = (*it).first; CAddrInfo& info = (*it).second; if (info.fInTried) { if (!info.nLastSuccess) return -1; if (info.nRefCount) return -2; setTried.insert(n); } else { if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3; if (!info.nRefCount) return -4; mapNew[n] = info.nRefCount; } if (mapAddr[info] != n) return -5; if (info.nRandomPos < 0 || info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n) return -14; if (info.nLastTry < 0) return -6; if (info.nLastSuccess < 0) return -8; } if (setTried.size() != nTried) return -9; if (mapNew.size() != nNew) return -10; for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvTried[n][i] != -1) { if (!setTried.count(vvTried[n][i])) return -11; if (mapInfo[vvTried[n][i]].GetTriedBucket(nKey) != n) return -17; if (mapInfo[vvTried[n][i]].GetBucketPosition(nKey, false, n) != i) return -18; setTried.erase(vvTried[n][i]); } } } for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) { for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) { if (vvNew[n][i] != -1) { if (!mapNew.count(vvNew[n][i])) return -12; if (mapInfo[vvNew[n][i]].GetBucketPosition(nKey, true, n) != i) return -19; if (--mapNew[vvNew[n][i]] == 0) mapNew.erase(vvNew[n][i]); } } } if (setTried.size()) return -13; if (mapNew.size()) return -15; if (nKey.IsNull()) return -16; return 0; } #endif void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr) { unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100; if (nNodes > ADDRMAN_GETADDR_MAX) nNodes = ADDRMAN_GETADDR_MAX; // gather a list of random nodes, skipping those of low quality for (unsigned int n = 0; n < vRandom.size(); n++) { if (vAddr.size() >= nNodes) break; int nRndPos = RandomInt(vRandom.size() - n) + n; SwapRandom(n, nRndPos); assert(mapInfo.count(vRandom[n]) == 1); const CAddrInfo& ai = mapInfo[vRandom[n]]; if (!ai.IsTerrible()) vAddr.push_back(ai); } } void CAddrMan::Connected_(const CService& addr, int64_t nTime) { CAddrInfo* pinfo = Find(addr); // if not found, bail out if (!pinfo) return; CAddrInfo& info = *pinfo; // check whether we are talking about the exact same CService (including same port) if (info != addr) return; // update info int64_t nUpdateInterval = 20 * 60; if (nTime - info.nTime > nUpdateInterval) info.nTime = nTime; } int CAddrMan::RandomInt(int nMax){ return GetRandInt(nMax); }
[ "59433840+Schilling99@users.noreply.github.com" ]
59433840+Schilling99@users.noreply.github.com
daa77994fbd83ce04b9661a8432d08975bd70341
62d6c28df01ace2ef06c32bd1dc3da4c2c0a210f
/Simple_tic_tac_toe/main.cpp
1b26c6dcc3d9a3c32f8c85bb197317d51f0ff67c
[]
no_license
ostell/console_games
c83bb7c9ec7425888592325e668a60facf1b5b30
ce9a68b04084d9bdd484bd32cecb14b3e103023a
refs/heads/master
2020-03-08T09:42:59.142410
2018-04-10T20:43:12
2018-04-10T20:43:12
128,053,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,078
cpp
/* TIC-TAC-TOE ----------- | o | x | o | ----------- | o | x | o | ----------- | x | o | o | ----------- */ #include <iostream> #include <string> #include <windows.h> #include "TTToe.h" int main(){ int coordX = 0, coordY = 0; char temp; TToe toe; WinFuncs win; //Game setup std::cout << "WELCOME TO TIC-TAC-TOE!" << std::endl << std::endl; std::cout << "Player 1 will play with sumbol?" << std::endl; std::cin >> temp; toe.setSumbol(1, temp); std::cout << "Player 2 will play with sumbol?" << std::endl; std::cin >> temp; toe.setSumbol(2, temp); win.ClearScreen(); toe.print_board(); while (toe.getWinner()){ toe.validate_input(coordX, coordY, "Player 1"); toe.setBoard(coordX, coordY, 1); win.ClearScreen(); toe.print_board(); toe.win_check(coordX, coordY, 1); std::cout << std::endl; if (toe.getWinner()){ toe.validate_input(coordX, coordY, "Player 2"); toe.setBoard(coordX, coordY, 2); win.ClearScreen(); toe.print_board(); toe.win_check(coordX, coordY, 2); std::cout << std::endl; } } std::cin.get(); return 0; }
[ "noreply@github.com" ]
ostell.noreply@github.com
3e3f20f3a22598e0dd694d6fdc5fa0408a2c0552
f2ae99a0fa0e73188f68e0b6d9d6e0c30a24367d
/기초알고리즘/2283_boj(동전1).cpp
05d59ec23688faf139e06a20bf8e15687ebe9c91
[]
no_license
kiseop91/Algorithm
69181d57acfe7a3e7e4696eb215c693b53ef5bec
4a62e85cce7db04c17c936bae2e885e8c237bc66
refs/heads/master
2020-04-10T03:13:17.389509
2019-07-18T08:36:21
2019-07-18T08:36:21
160,764,342
2
0
null
null
null
null
UTF-8
C++
false
false
350
cpp
#include <cstdio> int main() { int n, k; int coins[101]; int d[10001] = { 0 }; scanf("%d %d", &n, &k); for (int i = 1; i <= n; i++) { scanf("%d", &coins[i]); } d[0] = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= k; j++) { if (j >= coins[i]) { d[j] += d[j - coins[i]]; } } } printf("%d\n", d[k]); return 0; }
[ "kiseop91@naver.com" ]
kiseop91@naver.com
455514f11af827e6fc36ff4b1e28c6611fd9521c
a3b3b096fc709a4519a8fc143ad864f936e72d06
/examples/sqlite3_webquery/sqlite3_webquery.ino
7180e291061be26964724400f4227da4214601e3
[ "Apache-2.0" ]
permissive
minimum-necessary-change/esp_arduino_sqlite3_lib
baaf9712d6a6904abb61abf08c692f50d614226d
2b94d624fdc43fe49e868a2d0932c88d914b9553
refs/heads/master
2020-04-25T10:37:35.241016
2019-06-24T08:11:08
2019-06-24T08:11:08
172,715,844
0
0
Apache-2.0
2019-06-24T08:11:10
2019-02-26T13:22:43
C
UTF-8
C++
false
false
8,523
ino
/* This example shows how to retrieve data from Sqlite3 databases from SD Card through the Web Server and display in the form of HTML page. It also demonstrates query filtering by parameter passing and chunked encoding. Before running please copy following files to SD Card: examples/sqlite3_small_db/data/babyname.db This database contains around 30000 baby names and corresponding data. Also need to increase stack size in cores/esp8266/cont.h to atleast 6144 (from 4096) Please see https://github.com/siara-cc/esp_arduino_sqlite3_lib/ for more inforemation. Copyright (c) 2018, Siara Logics (cc) */ /* * Copyright (c) 2015, Majenko Technologies * 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 Majenko Technologies nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <sqlite3.h> #include <vfs.h> #include <SPI.h> const char *ssid = "Nokia1"; const char *password = "nokiafour"; ESP8266WebServer server ( 80 ); const int led = 13; void handleRoot() { digitalWrite ( led, 1 ); String temp; int sec = millis() / 1000; int min = sec / 60; int hr = min / 60; temp = "<html><head>\ <title>ESP8266 Demo</title>\ <style>\ body { font-family: Arial, Helvetica, Sans-Serif; font-size: large; Color: #000088; }\ </style>\ </head>\ <body>\ <h1>Hello from ESP8266!</h1>\ <h2>Query gendered names database</h2>\ <form name='params' method='GET' action='query_db'>\ Enter from: <input type=text style='font-size: large' value='Bob' name='from'/> \ <br>to: <input type=text style='font-size: large' value='Bobby' name='to'/> \ <br><br><input type=submit style='font-size: large' value='Query database'/>\ </form>\ </body>\ </html>"; server.send ( 200, "text/html", temp.c_str() ); digitalWrite ( led, 0 ); } void handleNotFound() { digitalWrite ( led, 1 ); String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += ( server.method() == HTTP_GET ) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for ( uint8_t i = 0; i < server.args(); i++ ) { message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n"; } server.send ( 404, "text/plain", message ); digitalWrite ( led, 0 ); } sqlite3 *db1; int rc; sqlite3_stmt *res; int rec_count = 0; const char *tail; int openDb(const char *filename, sqlite3 **db) { int rc = sqlite3_open(filename, db); if (rc) { Serial.printf("Can't open database: %s\n", sqlite3_errmsg(*db)); return rc; } else { Serial.printf("Opened database successfully\n"); } return rc; } void setup ( void ) { pinMode ( led, OUTPUT ); digitalWrite ( led, 0 ); Serial.begin ( 74880 ); WiFi.mode ( WIFI_STA ); WiFi.begin ( ssid, password ); Serial.println ( "" ); // Wait for connection while ( WiFi.status() != WL_CONNECTED ) { delay ( 500 ); Serial.print ( "." ); } Serial.println ( "" ); Serial.print ( "Connected to " ); Serial.println ( ssid ); Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() ); if ( MDNS.begin ( "esp8266" ) ) { Serial.println ( "MDNS responder started" ); } SPI.begin(); vfs_mount("/SD0", SS); sqlite3_initialize(); // Open database if (openDb("/SD0/babyname.db", &db1)) return; server.on ( "/", handleRoot ); server.on ( "/query_db", []() { String sql = "Select count(*) from gendered_names where name between '"; sql += server.arg("from"); sql += "' and '"; sql += server.arg("to"); sql += "'"; rc = sqlite3_prepare_v2(db1, sql.c_str(), 1000, &res, &tail); if (rc != SQLITE_OK) { String resp = "Failed to fetch data: "; resp += sqlite3_errmsg(db1); resp += ".<br><br><input type=button onclick='location.href=\"/\"' value='back'/>"; server.send ( 200, "text/html", resp.c_str()); Serial.println(resp.c_str()); return; } while (sqlite3_step(res) == SQLITE_ROW) { rec_count = sqlite3_column_int(res, 0); if (rec_count > 5000) { String resp = "Too many records: "; resp += rec_count; resp += ". Please select different range"; resp += ".<br><br><input type=button onclick='location.href=\"/\"' value='back'/>"; server.send ( 200, "text/html", resp.c_str()); Serial.println(resp.c_str()); sqlite3_finalize(res); return; } } sqlite3_finalize(res); sql = "Select year, state, name, total_babies, primary_sex, primary_sex_ratio, per_100k_in_state from gendered_names where name between '"; sql += server.arg("from"); sql += "' and '"; sql += server.arg("to"); sql += "'"; rc = sqlite3_prepare_v2(db1, sql.c_str(), 1000, &res, &tail); if (rc != SQLITE_OK) { String resp = "Failed to fetch data: "; resp += sqlite3_errmsg(db1); resp += "<br><br><a href='/'>back</a>"; server.send ( 200, "text/html", resp.c_str()); Serial.println(resp.c_str()); return; } rec_count = 0; server.setContentLength(CONTENT_LENGTH_UNKNOWN); String resp = "<html><head><title>ESP8266 Database query through web server</title>\ <style>\ body { font-family: Arial, Helvetica, Sans-Serif; font-size: large; Color: #000088; }\ </style><head><body><h1>ESP8266 Database query through web server</h1><h3>"; resp += sql; resp += "</h3><table cellspacing='1' cellpadding='1' border='1'><tr><td>Year</td><td>State</td><td>Name</td><td>Total babies</td><td>Primary Sex</td><td>Ratio</td><td>Per 100k</td></tr>"; server.send ( 200, "text/html", resp.c_str()); while (sqlite3_step(res) == SQLITE_ROW) { resp = "<tr><td>"; resp += sqlite3_column_int(res, 0); resp += "</td><td>"; resp += (const char *) sqlite3_column_text(res, 1); resp += "</td><td>"; resp += (const char *) sqlite3_column_text(res, 2); resp += "</td><td>"; resp += sqlite3_column_int(res, 3); resp += "</td><td>"; resp += (const char *) sqlite3_column_text(res, 4); resp += "</td><td>"; resp += sqlite3_column_double(res, 5); resp += "</td><td>"; resp += sqlite3_column_double(res, 6); resp += "</td></tr>"; server.sendContent(resp); rec_count++; } resp = "</table><br>Number of records: "; resp += rec_count; resp += ".<br><br><input type=button onclick='location.href=\"/\"' value='back'/>"; server.sendContent(resp); sqlite3_finalize(res); } ); server.onNotFound ( handleNotFound ); server.begin(); Serial.println ( "HTTP server started" ); } void loop ( void ) { server.handleClient(); }
[ "arun@siara.cc" ]
arun@siara.cc
a49d62dc597ce3adc898ffcdd354b5273b356e84
b77b470762df293be67877b484bb53b9d87b346a
/game/editor/EditModeSceneImpl.h
27efa2967507ce9874804a364d0d14bfd3cdb297
[ "BSD-3-Clause" ]
permissive
Sheph/af3d
9b8b8ea41f4e439623116d70d14ce5f1ee1fae25
4697fbc5f9a5cfb5d54b06738de9dc44b9f7755f
refs/heads/master
2023-08-28T16:41:43.989585
2021-09-11T19:09:45
2021-09-11T19:09:45
238,231,399
1
1
null
null
null
null
UTF-8
C++
false
false
2,086
h
/* * Copyright (c) 2020, Stanislav Vorobiov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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 _EDITOR_EDITMODE_SCENE_IMPL_H_ #define _EDITOR_EDITMODE_SCENE_IMPL_H_ #include "editor/EditModeScene.h" #include "editor/EditModeImpl.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4250) #endif namespace af3d { namespace editor { class EditModeSceneImpl : public EditModeImpl, public EditModeScene { public: explicit EditModeSceneImpl(Workspace* workspace); ~EditModeSceneImpl() = default; Item rayCast(const Frustum& frustum, const Ray& ray) const override; bool isValid(const Item& item) const override; bool isAlive(const Item& item) const override; }; } } #ifdef _MSC_VER #pragma warning(pop) #endif #endif
[ "sheffmail@mail.ru" ]
sheffmail@mail.ru
96d2a3d2f6c921b8d477df7390e7338e9a5deda9
106023d31ce8cd8db977b8f624a2c3fa1a2e0b25
/src/rpc/mining.cpp
ff1d9afb999f63020345909a45f9a1c082e06b1b
[ "MIT" ]
permissive
aissty/rockcoin
06345dc0d8b9056740692601300261a605345e71
75e15231d3b8cbf7532741f26f6f0e5a13c223e7
refs/heads/master
2021-01-25T09:53:59.781189
2018-03-04T19:25:28
2018-03-04T19:25:28
123,329,520
0
0
null
null
null
null
UTF-8
C++
false
false
42,932
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "amount.h" #include "chain.h" #include "chainparams.h" #include "consensus/consensus.h" #include "consensus/params.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "validation.h" #include "miner.h" #include "net.h" #include "pow.h" #include "rpc/server.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "validationinterface.h" #include <memory> #include <stdint.h> #include <boost/assign/list_of.hpp> #include <boost/shared_ptr.hpp> #include <univalue.h> using namespace std; /** * Return average network hashes per second based on the last 'lookup' blocks, * or from the last difficulty change if 'lookup' is nonpositive. * If 'height' is nonnegative, compute the estimate at the time when a given block was found. */ UniValue GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = chainActive.Tip(); if (height >= 0 && height < chainActive.Height()) pb = chainActive[height]; if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64_t minTime = pb0->GetBlockTime(); int64_t maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64_t time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64_t timeDiff = maxTime - minTime; return workDiff.getdouble() / timeDiff; } UniValue getnetworkhashps(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 2) throw runtime_error( "getnetworkhashps ( nblocks height )\n" "\nReturns the estimated network hashes per second based on the last n blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found.\n" "\nArguments:\n" "1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n" "2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n" "\nResult:\n" "x (numeric) Hashes per second estimated\n" "\nExamples:\n" + HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", "") ); LOCK(cs_main); return GetNetworkHashPS(request.params.size() > 0 ? request.params[0].get_int() : 120, request.params.size() > 1 ? request.params[1].get_int() : -1); } UniValue generateBlocks(boost::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript) { static const int nInnerLoopCount = 0x10000; int nHeightStart = 0; int nHeightEnd = 0; int nHeight = 0; { // Don't keep cs_main locked LOCK(cs_main); nHeightStart = chainActive.Height(); nHeight = nHeightStart; nHeightEnd = nHeightStart+nGenerate; } unsigned int nExtraNonce = 0; UniValue blockHashes(UniValue::VARR); while (nHeight < nHeightEnd) { std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript)); if (!pblocktemplate.get()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); CBlock *pblock = &pblocktemplate->block; { LOCK(cs_main); IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce); } while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetPoWHash(), pblock->nBits, Params().GetConsensus())) { ++pblock->nNonce; --nMaxTries; } if (nMaxTries == 0) { break; } if (pblock->nNonce == nInnerLoopCount) { continue; } std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock); if (!ProcessNewBlock(Params(), shared_pblock, true, NULL)) throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted"); ++nHeight; blockHashes.push_back(pblock->GetHash().GetHex()); //mark script as important because it was used at least for one coinbase output if the script came from the wallet if (keepScript) { coinbaseScript->KeepScript(); } } return blockHashes; } UniValue generate(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "generate nblocks ( maxtries )\n" "\nMine up to nblocks blocks immediately (before the RPC call returns)\n" "\nArguments:\n" "1. nblocks (numeric, required) How many blocks are generated immediately.\n" "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n" "\nResult:\n" "[ blockhashes ] (array) hashes of blocks generated\n" "\nExamples:\n" "\nGenerate 11 blocks\n" + HelpExampleCli("generate", "11") ); int nGenerate = request.params[0].get_int(); uint64_t nMaxTries = 1000000; if (request.params.size() > 1) { nMaxTries = request.params[1].get_int(); } boost::shared_ptr<CReserveScript> coinbaseScript; GetMainSignals().ScriptForMining(coinbaseScript); // If the keypool is exhausted, no script is returned at all. Catch this. if (!coinbaseScript) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); //throw an error if no script was provided if (coinbaseScript->reserveScript.empty()) throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)"); return generateBlocks(coinbaseScript, nGenerate, nMaxTries, true); } UniValue generatetoaddress(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw runtime_error( "generatetoaddress nblocks address (maxtries)\n" "\nMine blocks immediately to a specified address (before the RPC call returns)\n" "\nArguments:\n" "1. nblocks (numeric, required) How many blocks are generated immediately.\n" "2. address (string, required) The address to send the newly generated rockcoin to.\n" "3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n" "\nResult:\n" "[ blockhashes ] (array) hashes of blocks generated\n" "\nExamples:\n" "\nGenerate 11 blocks to myaddress\n" + HelpExampleCli("generatetoaddress", "11 \"myaddress\"") ); int nGenerate = request.params[0].get_int(); uint64_t nMaxTries = 1000000; if (request.params.size() > 2) { nMaxTries = request.params[2].get_int(); } CBitcoinAddress address(request.params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address"); boost::shared_ptr<CReserveScript> coinbaseScript(new CReserveScript()); coinbaseScript->reserveScript = GetScriptForDestination(address.Get()); return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false); } UniValue getmininginfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getmininginfo\n" "\nReturns a json object containing mining-related information." "\nResult:\n" "{\n" " \"blocks\": nnn, (numeric) The current block\n" " \"currentblocksize\": nnn, (numeric) The last block size\n" " \"currentblockweight\": nnn, (numeric) The last block weight\n" " \"currentblocktx\": nnn, (numeric) The last block transaction\n" " \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n" " \"errors\": \"...\" (string) Current errors\n" " \"networkhashps\": nnn, (numeric) The network hashes per second\n" " \"pooledtx\": n (numeric) The size of the mempool\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight)); obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("networkhashps", getnetworkhashps(request))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("chain", Params().NetworkIDString())); return obj; } // NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts UniValue prioritisetransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 3) throw runtime_error( "prioritisetransaction <txid> <priority delta> <fee delta>\n" "Accepts the transaction into mined blocks at a higher (or lower) priority\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id.\n" "2. priority_delta (numeric, required) The priority to add or subtract.\n" " The transaction selection algorithm considers the tx as it would have a higher priority.\n" " (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n" "3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n" " The fee is not actually paid, only the algorithm for selecting transactions into a block\n" " considers the transaction as it would have paid a higher (or lower) fee.\n" "\nResult:\n" "true (boolean) Returns true\n" "\nExamples:\n" + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000") ); LOCK(cs_main); uint256 hash = ParseHashStr(request.params[0].get_str(), "txid"); CAmount nAmount = request.params[2].get_int64(); mempool.PrioritiseTransaction(hash, request.params[0].get_str(), request.params[1].get_real(), nAmount); return true; } // NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller static UniValue BIP22ValidationResult(const CValidationState& state) { if (state.IsValid()) return NullUniValue; std::string strRejectReason = state.GetRejectReason(); if (state.IsError()) throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason); if (state.IsInvalid()) { if (strRejectReason.empty()) return "rejected"; return strRejectReason; } // Should be impossible return "valid?"; } std::string gbt_vb_name(const Consensus::DeploymentPos pos) { const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; std::string s = vbinfo.name; if (!vbinfo.gbt_force) { s.insert(s.begin(), '!'); } return s; } UniValue getblocktemplate(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "getblocktemplate ( TemplateRequest )\n" "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n" "It returns data needed to construct a block to work on.\n" "For full specification, see BIPs 22, 23, 9, and 145:\n" " https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n" " https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n" " https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n" " https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n" "\nArguments:\n" "1. template_request (json object, optional) A json object in the following spec\n" " {\n" " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n" " \"capabilities\":[ (array, optional) A list of strings\n" " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n" " ,...\n" " ],\n" " \"rules\":[ (array, optional) A list of strings\n" " \"support\" (string) client side supported softfork deployment\n" " ,...\n" " ]\n" " }\n" "\n" "\nResult:\n" "{\n" " \"version\" : n, (numeric) The preferred block version\n" " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n" " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n" " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n" " ,...\n" " },\n" " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n" " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n" " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n" " {\n" " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n" " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n" " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n" " \"depends\" : [ (array) array of numbers \n" " n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n" " ,...\n" " ],\n" " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n" " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n" " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n" " \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n" " }\n" " ,...\n" " ],\n" " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n" " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n" " },\n" " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n" " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n" " \"target\" : \"xxxx\", (string) The hash target\n" " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mutable\" : [ (array of string) list of ways the block template may be changed \n" " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n" " ,...\n" " ],\n" " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n" " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n" " \"sizelimit\" : n, (numeric) limit of block size\n" " \"weightlimit\" : n, (numeric) limit of block weight\n" " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n" " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n" " \"height\" : n (numeric) The height of the next block\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblocktemplate", "") + HelpExampleRpc("getblocktemplate", "") ); LOCK(cs_main); std::string strMode = "template"; UniValue lpval = NullUniValue; std::set<std::string> setClientRules; int64_t nMaxVersionPreVB = -1; if (request.params.size() > 0) { const UniValue& oparam = request.params[0].get_obj(); const UniValue& modeval = find_value(oparam, "mode"); if (modeval.isStr()) strMode = modeval.get_str(); else if (modeval.isNull()) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); lpval = find_value(oparam, "longpollid"); if (strMode == "proposal") { const UniValue& dataval = find_value(oparam, "data"); if (!dataval.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal"); CBlock block; if (!DecodeHexBlk(block, dataval.get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetHash(); BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex *pindex = mi->second; if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) return "duplicate"; if (pindex->nStatus & BLOCK_FAILED_MASK) return "duplicate-invalid"; return "duplicate-inconclusive"; } CBlockIndex* const pindexPrev = chainActive.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; CValidationState state; TestBlockValidity(state, Params(), block, pindexPrev, false, true); return BIP22ValidationResult(state); } const UniValue& aClientRules = find_value(oparam, "rules"); if (aClientRules.isArray()) { for (unsigned int i = 0; i < aClientRules.size(); ++i) { const UniValue& v = aClientRules[i]; setClientRules.insert(v.get_str()); } } else { // NOTE: It is important that this NOT be read if versionbits is supported const UniValue& uvMaxVersion = find_value(oparam, "maxversion"); if (uvMaxVersion.isNum()) { nMaxVersionPreVB = uvMaxVersion.get_int64(); } } } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "RockCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "RockCoin is downloading blocks..."); static unsigned int nTransactionsUpdatedLast; if (!lpval.isNull()) { // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions uint256 hashWatchedChain; boost::system_time checktxtime; unsigned int nTransactionsUpdatedLastLP; if (lpval.isStr()) { // Format: <hashBestChain><nTransactionsUpdatedLast> std::string lpstr = lpval.get_str(); hashWatchedChain.SetHex(lpstr.substr(0, 64)); nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64)); } else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier hashWatchedChain = chainActive.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } // Release the wallet and main lock while waiting LEAVE_CRITICAL_SECTION(cs_main); { checktxtime = boost::get_system_time() + boost::posix_time::minutes(1); boost::unique_lock<boost::mutex> lock(csBestBlock); while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) { if (!cvBlockChange.timed_wait(lock, checktxtime)) { // Timeout: Check transactions for update if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) break; checktxtime += boost::posix_time::seconds(10); } } } ENTER_CRITICAL_SECTION(cs_main); if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down"); // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners? } const struct BIP9DeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT]; // If the caller is indicating segwit support, then allow CreateNewBlock() // to select witness transactions, after segwit activates (otherwise // don't). bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end(); // Update block static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr<CBlockTemplate> pblocktemplate; // Cache whether the last invocation was with segwit support, to avoid returning // a segwit-block to a non-segwit caller. static bool fLastTemplateSupportsSegwit = true; if (pindexPrev != chainActive.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) || fLastTemplateSupportsSegwit != fSupportsSegwit) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = nullptr; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrevNew = chainActive.Tip(); nStart = GetTime(); fLastTemplateSupportsSegwit = fSupportsSegwit; // Create new block CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience const Consensus::Params& consensusParams = Params().GetConsensus(); // Update nTime UpdateTime(pblock, consensusParams, pindexPrev); pblock->nNonce = 0; // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache)); UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal"); UniValue transactions(UniValue::VARR); map<uint256, int64_t> setTxIndex; int i = 0; for (const auto& it : pblock->vtx) { const CTransaction& tx = *it; uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; UniValue entry(UniValue::VOBJ); entry.push_back(Pair("data", EncodeHexTx(tx))); entry.push_back(Pair("txid", txHash.GetHex())); entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex())); UniValue deps(UniValue::VARR); BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template]; if (fPreSegWit) { assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0); nTxSigOps /= WITNESS_SCALE_FACTOR; } entry.push_back(Pair("sigops", nTxSigOps)); entry.push_back(Pair("weight", GetTransactionWeight(tx))); transactions.push_back(entry); } UniValue aux(UniValue::VOBJ); aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); UniValue aMutable(UniValue::VARR); aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); UniValue result(UniValue::VOBJ); result.push_back(Pair("capabilities", aCaps)); UniValue aRules(UniValue::VARR); UniValue vbavailable(UniValue::VOBJ); for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) { Consensus::DeploymentPos pos = Consensus::DeploymentPos(j); ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache); switch (state) { case THRESHOLD_DEFINED: case THRESHOLD_FAILED: // Not exposed to GBT at all break; case THRESHOLD_LOCKED_IN: // Ensure bit is set in block version pblock->nVersion |= VersionBitsMask(consensusParams, pos); // FALL THROUGH to get vbavailable set... case THRESHOLD_STARTED: { const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit)); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { if (!vbinfo.gbt_force) { // If the client doesn't support this, don't indicate it in the [default] version pblock->nVersion &= ~VersionBitsMask(consensusParams, pos); } } break; } case THRESHOLD_ACTIVE: { // Add to rules only const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; aRules.push_back(gbt_vb_name(pos)); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { // Not supported by the client; make sure it's safe to proceed if (!vbinfo.gbt_force) { // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name)); } } break; } } } result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("rules", aRules)); result.push_back(Pair("vbavailable", vbavailable)); result.push_back(Pair("vbrequired", int(0))); if (nMaxVersionPreVB >= 2) { // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated aMutable.push_back("version/force"); } result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue)); result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast))); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST; if (fPreSegWit) { assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0); nSigOpLimit /= WITNESS_SCALE_FACTOR; } result.push_back(Pair("sigoplimit", nSigOpLimit)); if (fPreSegWit) { result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_BASE_SIZE)); } else { result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SERIALIZED_SIZE)); result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT)); } result.push_back(Pair("curtime", pblock->GetBlockTime())); result.push_back(Pair("bits", strprintf("%08x", pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) { result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end()))); } return result; } class submitblock_StateCatcher : public CValidationInterface { public: uint256 hash; bool found; CValidationState state; submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {} protected: virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) { if (block.GetHash() != hash) return; found = true; state = stateIn; } }; UniValue submitblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n" "\nAttempts to submit new block to network.\n" "The 'jsonparametersobject' parameter is currently ignored.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n" "\nArguments\n" "1. \"hexdata\" (string, required) the hex-encoded block data to submit\n" "2. \"parameters\" (string, optional) object of optional parameters\n" " {\n" " \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n" " }\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\"") ); std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>(); CBlock& block = *blockptr; if (!DecodeHexBlk(block, request.params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase"); } uint256 hash = block.GetHash(); bool fBlockPresent = false; { LOCK(cs_main); BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex *pindex = mi->second; if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) return "duplicate"; if (pindex->nStatus & BLOCK_FAILED_MASK) return "duplicate-invalid"; // Otherwise, we might only have the header - process the block before returning fBlockPresent = true; } } { LOCK(cs_main); BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi != mapBlockIndex.end()) { UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus()); } } submitblock_StateCatcher sc(block.GetHash()); RegisterValidationInterface(&sc); bool fAccepted = ProcessNewBlock(Params(), blockptr, true, NULL); UnregisterValidationInterface(&sc); if (fBlockPresent) { if (fAccepted && !sc.found) return "duplicate-inconclusive"; return "duplicate"; } if (!sc.found) return "inconclusive"; return BIP22ValidationResult(sc.state); } UniValue estimatefee(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "estimatefee nblocks\n" "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n" "confirmation within nblocks blocks. Uses virtual transaction size of transaction\n" "as defined in BIP 141 (witness data is discounted).\n" "\nArguments:\n" "1. nblocks (numeric, required)\n" "\nResult:\n" "n (numeric) estimated fee-per-kilobyte\n" "\n" "A negative value is returned if not enough transactions and blocks\n" "have been observed to make an estimate.\n" "-1 is always returned for nblocks == 1 as it is impossible to calculate\n" "a fee that is high enough to get reliably included in the next block.\n" "\nExample:\n" + HelpExampleCli("estimatefee", "6") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM)); int nBlocks = request.params[0].get_int(); if (nBlocks < 1) nBlocks = 1; CFeeRate feeRate = mempool.estimateFee(nBlocks); if (feeRate == CFeeRate(0)) return -1.0; return ValueFromAmount(feeRate.GetFeePerK()); } UniValue estimatepriority(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "estimatepriority nblocks\n" "\nDEPRECATED. Estimates the approximate priority a zero-fee transaction needs to begin\n" "confirmation within nblocks blocks.\n" "\nArguments:\n" "1. nblocks (numeric, required)\n" "\nResult:\n" "n (numeric) estimated priority\n" "\n" "A negative value is returned if not enough transactions and blocks\n" "have been observed to make an estimate.\n" "\nExample:\n" + HelpExampleCli("estimatepriority", "6") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM)); int nBlocks = request.params[0].get_int(); if (nBlocks < 1) nBlocks = 1; return mempool.estimatePriority(nBlocks); } UniValue estimatesmartfee(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "estimatesmartfee nblocks\n" "\nWARNING: This interface is unstable and may disappear or change!\n" "\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n" "confirmation within nblocks blocks if possible and return the number of blocks\n" "for which the estimate is valid. Uses virtual transaction size as defined\n" "in BIP 141 (witness data is discounted).\n" "\nArguments:\n" "1. nblocks (numeric)\n" "\nResult:\n" "{\n" " \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in RKC)\n" " \"blocks\" : n (numeric) block number where estimate was found\n" "}\n" "\n" "A negative value is returned if not enough transactions and blocks\n" "have been observed to make an estimate for any number of blocks.\n" "However it will not return a value below the mempool reject fee.\n" "\nExample:\n" + HelpExampleCli("estimatesmartfee", "6") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM)); int nBlocks = request.params[0].get_int(); UniValue result(UniValue::VOBJ); int answerFound; CFeeRate feeRate = mempool.estimateSmartFee(nBlocks, &answerFound); result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK()))); result.push_back(Pair("blocks", answerFound)); return result; } UniValue estimatesmartpriority(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "estimatesmartpriority nblocks\n" "\nDEPRECATED. WARNING: This interface is unstable and may disappear or change!\n" "\nEstimates the approximate priority a zero-fee transaction needs to begin\n" "confirmation within nblocks blocks if possible and return the number of blocks\n" "for which the estimate is valid.\n" "\nArguments:\n" "1. nblocks (numeric, required)\n" "\nResult:\n" "{\n" " \"priority\" : x.x, (numeric) estimated priority\n" " \"blocks\" : n (numeric) block number where estimate was found\n" "}\n" "\n" "A negative value is returned if not enough transactions and blocks\n" "have been observed to make an estimate for any number of blocks.\n" "However if the mempool reject fee is set it will return 1e9 * MAX_MONEY.\n" "\nExample:\n" + HelpExampleCli("estimatesmartpriority", "6") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM)); int nBlocks = request.params[0].get_int(); UniValue result(UniValue::VOBJ); int answerFound; double priority = mempool.estimateSmartPriority(nBlocks, &answerFound); result.push_back(Pair("priority", priority)); result.push_back(Pair("blocks", answerFound)); return result; } static const CRPCCommand commands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- { "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} }, { "mining", "getmininginfo", &getmininginfo, true, {} }, { "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","priority_delta","fee_delta"} }, { "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} }, { "mining", "submitblock", &submitblock, true, {"hexdata","parameters"} }, { "generating", "generate", &generate, true, {"nblocks","maxtries"} }, { "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} }, { "util", "estimatefee", &estimatefee, true, {"nblocks"} }, { "util", "estimatepriority", &estimatepriority, true, {"nblocks"} }, { "util", "estimatesmartfee", &estimatesmartfee, true, {"nblocks"} }, { "util", "estimatesmartpriority", &estimatesmartpriority, true, {"nblocks"} }, }; void RegisterMiningRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
[ "aissty@qq.com" ]
aissty@qq.com
d68d5dc0b28f35dd3d671c078c41659f6288d908
3e80a79b455d2c7ab6e5e39d97ec813ff1e8512f
/EditorTextoSln/EditorCPP2015/stdafx.cpp
f592706449921a1cc4ea812ef5a16e620804850e
[ "MIT" ]
permissive
CampioniMan/EditorCPP
6656691d69888944e316de0423e8c228330c2649
41f237a42af8ac5bc89027424c2dd8d8d8536e6f
refs/heads/master
2021-01-18T18:10:26.158644
2016-11-18T20:36:32
2016-11-18T20:36:32
69,965,394
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
// stdafx.cpp : source file that includes just the standard includes // EditorCPP2015.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "campioni.daniel@gmail.com" ]
campioni.daniel@gmail.com
9458a17564ceb99412ab938caf4f18fe654636ef
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/xdktools/Producer/StyleDesigner/TabPatternPattern.cpp
e032a8bb3ada599c58ae1105cfff41338c332049
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,271
cpp
// TabPatternPattern.cpp : implementation file // #include "stdafx.h" #include "StyleDesignerDLL.h" #include "Style.h" #include "Pattern.h" #include "PatternLengthDlg.h" #include "TimeSignatureDlg.h" #include "RhythmDlg.h" #include "TabPatternPattern.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern property page CTabPatternPattern::CTabPatternPattern( CPatternPropPageManager* pPatternPropPageManager ) : CPropertyPage(CTabPatternPattern::IDD) { //{{AFX_DATA_INIT(CTabPatternPattern) //}}AFX_DATA_INIT ASSERT( pPatternPropPageManager != NULL ); m_pPattern = NULL; m_pPageManager = pPatternPropPageManager; m_fNeedToDetach = FALSE; } CTabPatternPattern::~CTabPatternPattern() { // Work around 27331 m_pPattern = NULL; } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::RefreshTab void CTabPatternPattern::RefreshTab( IDMUSProdPropPageObject* pIPropPageObject ) { PPGPattern ppgPattern; PPGPattern* pPPGPattern = &ppgPattern; if( pIPropPageObject && ( SUCCEEDED ( pIPropPageObject->GetData((void **)&pPPGPattern ) ) ) ) { m_pPattern = ppgPattern.pPattern; } else { m_pPattern = NULL; } UpdateControls(); } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::EnableControls void CTabPatternPattern::EnableControls( BOOL fEnable ) { m_editName.EnableWindow( fEnable ); m_btnLength.EnableWindow( fEnable ); m_editGrooveBottom.EnableWindow( fEnable ); m_spinGrooveBottom.EnableWindow( fEnable ); m_editGrooveTop.EnableWindow( fEnable ); m_spinGrooveTop.EnableWindow( fEnable ); m_editDestBottom.EnableWindow( fEnable ); m_spinDestBottom.EnableWindow( fEnable ); m_editDestTop.EnableWindow( fEnable ); m_spinDestTop.EnableWindow( fEnable ); m_btnIntro.EnableWindow( fEnable ); m_btnFill.EnableWindow( fEnable ); m_btnBreak.EnableWindow( fEnable ); m_btnEnd.EnableWindow( fEnable ); m_btnCustom.EnableWindow( fEnable ); m_editCustomId.EnableWindow( fEnable ); m_spinCustomId.EnableWindow( fEnable ); m_btnTimeSignature.EnableWindow( fEnable ); m_btnCustomDlg.EnableWindow( fEnable ); } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::UpdateControls void CTabPatternPattern::UpdateControls() { // Make sure controls have been created if( ::IsWindow(m_editName.m_hWnd) == FALSE ) { return; } // Update controls m_editName.LimitText( DMUS_MAX_NAME ); m_editGrooveBottom.LimitText( 3 ); m_editGrooveTop.LimitText( 3 ); m_editDestBottom.LimitText( 3 ); m_editDestTop.LimitText( 3 ); m_editCustomId.LimitText( 3 ); if( m_pPattern ) { EnableControls( TRUE ); // Set name m_editName.SetWindowText( m_pPattern->m_strName ); // Set length CString strLength; strLength.Format( "%d", m_pPattern->m_wNbrMeasures ); m_btnLength.SetWindowText( strLength ); // Set Bottom Groove m_spinGrooveBottom.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinGrooveBottom.SetPos( m_pPattern->m_bGrooveBottom ); // Set Top Groove m_spinGrooveTop.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinGrooveTop.SetPos( m_pPattern->m_bGrooveTop ); // Set Destination Bottom Groove m_spinDestBottom.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinDestBottom.SetPos( m_pPattern->m_bDestGrooveBottom ); // Set Destination Top Groove m_spinDestTop.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinDestTop.SetPos( m_pPattern->m_bDestGrooveTop ); // Set Embellishments m_btnIntro.SetCheck( (m_pPattern->m_wEmbellishment & EMB_INTRO) ? TRUE : FALSE ); m_btnFill.SetCheck( (m_pPattern->m_wEmbellishment & EMB_FILL) ? TRUE : FALSE ); m_btnBreak.SetCheck( (m_pPattern->m_wEmbellishment & EMB_BREAK) ? TRUE : FALSE ); m_btnEnd.SetCheck( (m_pPattern->m_wEmbellishment & EMB_END) ? TRUE : FALSE ); // Set User-defined Embellishment BOOL fCustomEmbellishment = FALSE; if( HIBYTE(m_pPattern->m_wEmbellishment) >= MIN_EMB_CUSTOM_ID && HIBYTE(m_pPattern->m_wEmbellishment) <= MAX_EMB_CUSTOM_ID ) { fCustomEmbellishment = TRUE; ASSERT( LOBYTE(m_pPattern->m_wEmbellishment) == 0 ); } m_btnCustom.SetCheck( fCustomEmbellishment ); m_spinCustomId.SetRange( MIN_EMB_CUSTOM_ID, MAX_EMB_CUSTOM_ID ); if( fCustomEmbellishment ) { m_editCustomId.EnableWindow( TRUE ); m_spinCustomId.EnableWindow( TRUE ); m_spinCustomId.SetPos( HIBYTE(m_pPattern->m_wEmbellishment) ); } else { m_spinCustomId.SetPos( m_pPattern->m_nLastCustomId ); m_editCustomId.EnableWindow( FALSE ); m_spinCustomId.EnableWindow( FALSE ); } // Draw rhythm map m_btnRhythmMap.Invalidate(); // Update bitmap on time signature button SetTimeSignatureBitmap(); } else { m_editName.SetWindowText( _T("") ); m_btnLength.SetWindowText( _T("") ); m_spinGrooveBottom.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinGrooveBottom.SetPos( MIN_GROOVE ); m_spinGrooveTop.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinGrooveTop.SetPos( MAX_GROOVE ); m_spinDestBottom.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinDestBottom.SetPos( MIN_GROOVE ); m_spinDestTop.SetRange( MIN_GROOVE, MAX_GROOVE ); m_spinDestTop.SetPos( MAX_GROOVE ); m_btnIntro.SetCheck( 0 ); m_btnFill.SetCheck( 0 ); m_btnBreak.SetCheck( 0 ); m_btnEnd.SetCheck( 0 ); m_btnCustom.SetCheck( 0 ); m_spinCustomId.SetRange( MIN_EMB_CUSTOM_ID, MAX_EMB_CUSTOM_ID ); m_spinCustomId.SetPos( MIN_EMB_CUSTOM_ID ); m_btnRhythmMap.Invalidate(); EnableControls( FALSE ); } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::SetTimeSignatureBitmap void CTabPatternPattern::SetTimeSignatureBitmap( void ) { if( !::IsWindow( m_btnTimeSignature.m_hWnd ) ) { return; } HBITMAP hNewBits = NULL; ASSERT( m_pPattern != NULL ); RECT rect; m_btnTimeSignature.GetClientRect( &rect ); // Create a DC for the new bitmap // a DC for the 'Grids Per Beat' bitmap // a Bitmap for the new bits CDC cdcDest; CDC cdcGridsPerBeat; CBitmap bmpNewBits; CBitmap bmpGridsPerBeat; CDC* pDC = m_btnTimeSignature.GetDC(); if( pDC ) { if( cdcDest.CreateCompatibleDC( pDC ) == FALSE || cdcGridsPerBeat.CreateCompatibleDC( pDC ) == FALSE || bmpNewBits.CreateCompatibleBitmap( pDC, rect.right, rect.bottom ) == FALSE ) { m_btnTimeSignature.ReleaseDC( pDC ); return; } m_btnTimeSignature.ReleaseDC( pDC ); } // Create the new bitmap CBitmap* pbmpOldMem = cdcDest.SelectObject( &bmpNewBits ); // Fill Rect with button color cdcDest.SetBkColor( ::GetSysColor(COLOR_BTNFACE) ); cdcDest.ExtTextOut( 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); // Write text CString strTimeSignature; CFont font; CFont* pfontOld = NULL; if( font.CreateFont( 10, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "MS Sans Serif" ) ) { pfontOld = cdcDest.SelectObject( &font ); } strTimeSignature.Format( "%d/%d", m_pPattern->m_TimeSignature.m_bBeatsPerMeasure, m_pPattern->m_TimeSignature.m_bBeat ); rect.left += 6; cdcDest.SetTextColor( COLOR_BTNTEXT ); cdcDest.DrawText( strTimeSignature, -1, &rect, (DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_NOPREFIX) ); rect.left -= 6; if( pfontOld ) { cdcDest.SelectObject( pfontOld ); font.DeleteObject(); } // Set x coord for 'Grids Per Beat' image CSize sizeText = cdcDest.GetTextExtent( strTimeSignature ); int nX = max( 48, (sizeText.cx + 8) ); // Draw "splitter" { CPen pen1; CPen pen2; CPen* ppenOld; int nPlace = nX - 6; int nModeOld = cdcDest.SetROP2( R2_COPYPEN ); // Highlight if( pen1.CreatePen( PS_SOLID, 1, ::GetSysColor(COLOR_BTNSHADOW) ) ) { ppenOld = cdcDest.SelectObject( &pen1 ); cdcDest.MoveTo( nPlace, (rect.top + 3) ); cdcDest.LineTo( nPlace, (rect.bottom - 3) ); cdcDest.SelectObject( ppenOld ); } // Shadow if( pen2.CreatePen( PS_SOLID, 1, ::GetSysColor(COLOR_BTNHIGHLIGHT) ) ) { ppenOld = cdcDest.SelectObject( &pen2 ); cdcDest.MoveTo( ++nPlace, (rect.top + 3) ); cdcDest.LineTo( nPlace, (rect.bottom - 3) ); cdcDest.SelectObject( ppenOld ); } if( nModeOld ) { cdcDest.SetROP2( nModeOld ); } } // Add 'Grids Per Beat' bitmap { int nResourceID = m_pPattern->m_TimeSignature.m_wGridsPerBeat - 1; if( m_pPattern->m_TimeSignature.m_bBeat != 4 ) // 4 = quarter note gets the beat { nResourceID += MAX_GRIDS_PER_BEAT; } ASSERT( (nResourceID >= 0) && (nResourceID <= MAX_GRIDS_PER_BEAT_ENTRIES) ); if( bmpGridsPerBeat.LoadBitmap( g_nGridsPerBeatBitmaps[nResourceID] ) ) { BITMAP bm; bmpGridsPerBeat.GetBitmap( &bm ); int nY = ((rect.bottom - rect.top) - bm.bmHeight) >> 1; CBitmap* pbmpOld = cdcGridsPerBeat.SelectObject( &bmpGridsPerBeat ); { CDC cdcMono; CBitmap bmpMono; if( cdcMono.CreateCompatibleDC( &cdcDest ) && bmpMono.CreateBitmap( bm.bmWidth, bm.bmHeight, 1, 1, NULL ) ) { CBitmap* pbmpOldMono = cdcMono.SelectObject( &bmpMono ); cdcGridsPerBeat.SetBkColor( RGB(255,255,255) ); cdcDest.SetBkColor( RGB(255,255,255) ); cdcMono.BitBlt( 0, 0, bm.bmWidth, bm.bmHeight, &cdcGridsPerBeat, 0, 0, SRCCOPY); cdcDest.BitBlt( nX, nY, bm.bmWidth, bm.bmHeight, &cdcGridsPerBeat, 0, 0, SRCINVERT ) ; cdcDest.BitBlt( nX, nY, bm.bmWidth, bm.bmHeight, &cdcMono, 0, 0, SRCAND ) ; cdcDest.BitBlt( nX, nY, bm.bmWidth, bm.bmHeight, &cdcGridsPerBeat, 0, 0, SRCINVERT ) ; cdcMono.SelectObject( pbmpOldMono ) ; } } cdcGridsPerBeat.SelectObject( pbmpOld ); } } cdcDest.SelectObject( pbmpOldMem ); // Set the new bitmap hNewBits = (HBITMAP)bmpNewBits.Detach(); if( hNewBits ) { HBITMAP hBitmapOld = m_btnTimeSignature.SetBitmap( hNewBits ); if( hBitmapOld ) { ::DeleteObject( hBitmapOld ); } } } void CTabPatternPattern::DoDataExchange(CDataExchange* pDX) { AFX_MANAGE_STATE(_afxModuleAddrThis); CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTabPatternPattern) DDX_Control(pDX, IDC_EMB_CUSTOM, m_btnCustom); DDX_Control(pDX, IDC_CUSTOM_ID, m_editCustomId); DDX_Control(pDX, IDC_CUSTOM_ID_SPIN, m_spinCustomId); DDX_Control(pDX, IDC_DEST_TOP_SPIN, m_spinDestTop); DDX_Control(pDX, IDC_DEST_BOTTOM_SPIN, m_spinDestBottom); DDX_Control(pDX, IDC_DEST_TOP, m_editDestTop); DDX_Control(pDX, IDC_DEST_BOTTOM, m_editDestBottom); DDX_Control(pDX, IDC_TIME_SIGNATURE, m_btnTimeSignature); DDX_Control(pDX, IDC_RHYTHM_MAP, m_btnRhythmMap); DDX_Control(pDX, IDC_CUSTOM_DLG, m_btnCustomDlg); DDX_Control(pDX, IDC_EMB_INTRO, m_btnIntro); DDX_Control(pDX, IDC_EMB_FILL, m_btnFill); DDX_Control(pDX, IDC_EMB_END, m_btnEnd); DDX_Control(pDX, IDC_EMB_BREAK, m_btnBreak); DDX_Control(pDX, IDC_GROOVE_TOP_SPIN, m_spinGrooveTop); DDX_Control(pDX, IDC_GROOVE_TOP, m_editGrooveTop); DDX_Control(pDX, IDC_GROOVE_BOTTOM_SPIN, m_spinGrooveBottom); DDX_Control(pDX, IDC_GROOVE_BOTTOM, m_editGrooveBottom); DDX_Control(pDX, IDC_NAME, m_editName); DDX_Control(pDX, IDC_LENGTH, m_btnLength); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTabPatternPattern, CPropertyPage) //{{AFX_MSG_MAP(CTabPatternPattern) ON_WM_CREATE() ON_WM_DESTROY() ON_EN_KILLFOCUS(IDC_NAME, OnKillFocusName) ON_BN_CLICKED(IDC_LENGTH, OnLength) ON_EN_KILLFOCUS(IDC_GROOVE_BOTTOM, OnKillFocusGrooveBottom) ON_NOTIFY(UDN_DELTAPOS, IDC_GROOVE_BOTTOM_SPIN, OnDeltaPosGrooveBottomSpin) ON_EN_KILLFOCUS(IDC_GROOVE_TOP, OnKillFocusGrooveTop) ON_NOTIFY(UDN_DELTAPOS, IDC_GROOVE_TOP_SPIN, OnDeltaPosGrooveTopSpin) ON_BN_CLICKED(IDC_EMB_INTRO, OnEmbIntro) ON_BN_CLICKED(IDC_EMB_FILL, OnEmbFill) ON_BN_CLICKED(IDC_EMB_BREAK, OnEmbBreak) ON_BN_CLICKED(IDC_EMB_END, OnEmbEnd) ON_BN_CLICKED(IDC_CUSTOM_DLG, OnCustomDlg) ON_WM_DRAWITEM() ON_BN_CLICKED(IDC_TIME_SIGNATURE, OnTimeSignature) ON_EN_KILLFOCUS(IDC_DEST_BOTTOM, OnKillFocusDestBottom) ON_NOTIFY(UDN_DELTAPOS, IDC_DEST_BOTTOM_SPIN, OnDeltaPosDestBottomSpin) ON_EN_KILLFOCUS(IDC_DEST_TOP, OnKillFocusDestTop) ON_NOTIFY(UDN_DELTAPOS, IDC_DEST_TOP_SPIN, OnDeltaPosDestTopSpin) ON_BN_CLICKED(IDC_EMB_CUSTOM, OnEmbCustom) ON_EN_KILLFOCUS(IDC_CUSTOM_ID, OnKillFocusCustomId) ON_NOTIFY(UDN_DELTAPOS, IDC_CUSTOM_ID_SPIN, OnDeltaPosCustomIdSpin) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern message handlers ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnSetActive BOOL CTabPatternPattern::OnSetActive() { AFX_MANAGE_STATE(_afxModuleAddrThis); UpdateControls(); return CPropertyPage::OnSetActive(); } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnCreate int CTabPatternPattern::OnCreate(LPCREATESTRUCT lpCreateStruct) { AFX_MANAGE_STATE(_afxModuleAddrThis); // Attach the window to the property page structure. // This has been done once already in the main application // since the main application owns the property sheet. // It needs to be done here so that the window handle can if( !FromHandlePermanent( m_hWnd ) ) { HWND hWnd = m_hWnd; m_hWnd = NULL; Attach( hWnd ); m_fNeedToDetach = TRUE; } if( CPropertyPage::OnCreate(lpCreateStruct) == -1 ) { return -1; } return 0; } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDestroy void CTabPatternPattern::OnDestroy() { AFX_MANAGE_STATE(_afxModuleAddrThis); // Delete the time signature button's bitmap HBITMAP hBitmap = m_btnTimeSignature.GetBitmap(); if( hBitmap ) { ::DeleteObject( hBitmap ); } // Detach the window from the property page structure. // This will be done again by the main application since // it owns the property sheet. It needs o be done here // so that the window handle can be removed from the // DLLs handle map. if( m_fNeedToDetach && m_hWnd ) { HWND hWnd = m_hWnd; Detach(); m_hWnd = hWnd; } CPropertyPage::OnDestroy(); } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnKillFocusName void CTabPatternPattern::OnKillFocusName() { AFX_MANAGE_STATE(_afxModuleAddrThis); ASSERT( theApp.m_pStyleComponent != NULL ); ASSERT( theApp.m_pStyleComponent->m_pIFramework != NULL ); if( m_pPattern ) { CString strName; m_editName.GetWindowText( strName ); // Strip leading and trailing spaces strName.TrimRight(); strName.TrimLeft(); if( strName.IsEmpty() ) { m_editName.SetWindowText( m_pPattern->m_strName ); } else { if( strName.Compare( m_pPattern->m_strName ) != 0 ) { BSTR bstrName = strName.AllocSysString(); m_pPattern->SetNodeName( bstrName ); theApp.m_pStyleComponent->m_pIFramework->RefreshNode( m_pPattern ); } } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnLength void CTabPatternPattern::OnLength() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CPatternLengthDlg plDlg( m_pPattern ); if( plDlg.DoModal() == IDOK ) { CString strLength; if( ::IsWindow( m_btnLength.m_hWnd ) ) { strLength.Format( "%d", m_pPattern->m_wNbrMeasures ); m_btnLength.SetWindowText( strLength ); } // Redraw rhythm map if( ::IsWindow( m_btnRhythmMap.m_hWnd ) ) { m_btnRhythmMap.Invalidate(); m_btnRhythmMap.UpdateWindow(); } } if( ::IsWindow( m_btnLength.m_hWnd ) ) { m_btnLength.SetFocus(); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnKillFocusGrooveBottom void CTabPatternPattern::OnKillFocusGrooveBottom() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CString strNewGrooveBottom; m_editGrooveBottom.GetWindowText( strNewGrooveBottom ); // Strip leading and trailing spaces strNewGrooveBottom.TrimRight(); strNewGrooveBottom.TrimLeft(); if( strNewGrooveBottom.IsEmpty() ) { m_spinGrooveBottom.SetPos( m_pPattern->m_bGrooveBottom ); } else { int nNewGrooveBottom = _ttoi( strNewGrooveBottom ); int nNewGrooveTop = m_pPattern->m_bGrooveTop; if( nNewGrooveBottom < MIN_GROOVE) { nNewGrooveBottom = MIN_GROOVE; } if( nNewGrooveBottom > MAX_GROOVE) { nNewGrooveBottom = MAX_GROOVE; } m_spinGrooveBottom.SetPos( nNewGrooveBottom ); if( nNewGrooveBottom > nNewGrooveTop ) { nNewGrooveTop = nNewGrooveBottom; m_spinGrooveTop.SetPos( nNewGrooveTop ); } m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDeltaPosGrooveBottomSpin void CTabPatternPattern::OnDeltaPosGrooveBottomSpin( NMHDR* pNMHDR, LRESULT* pResult ) { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; int nGrooveBottom = m_spinGrooveBottom.GetPos(); if( HIWORD(nGrooveBottom) == 0 ) { int nNewGrooveBottom = LOWORD(nGrooveBottom) + pNMUpDown->iDelta; int nNewGrooveTop = m_pPattern->m_bGrooveTop; if( nNewGrooveBottom < MIN_GROOVE) { nNewGrooveBottom = MIN_GROOVE; } if( nNewGrooveBottom > MAX_GROOVE) { nNewGrooveBottom = MAX_GROOVE; } m_spinGrooveBottom.SetPos( nNewGrooveBottom ); if( nNewGrooveBottom > nNewGrooveTop ) { nNewGrooveTop = nNewGrooveBottom; m_spinGrooveTop.SetPos( nNewGrooveTop ); } m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop ); } } *pResult = 1; } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnKillFocusGrooveTop void CTabPatternPattern::OnKillFocusGrooveTop() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CString strNewGrooveTop; m_editGrooveTop.GetWindowText( strNewGrooveTop ); // Strip leading and trailing spaces strNewGrooveTop.TrimRight(); strNewGrooveTop.TrimLeft(); if( strNewGrooveTop.IsEmpty() ) { m_spinGrooveTop.SetPos( m_pPattern->m_bGrooveTop ); } else { int nNewGrooveTop = _ttoi( strNewGrooveTop ); int nNewGrooveBottom = m_pPattern->m_bGrooveBottom; if( nNewGrooveTop < MIN_GROOVE) { nNewGrooveTop = MIN_GROOVE; } if( nNewGrooveTop > MAX_GROOVE) { nNewGrooveTop = MAX_GROOVE; } m_spinGrooveTop.SetPos( nNewGrooveTop ); if( nNewGrooveTop < nNewGrooveBottom ) { nNewGrooveBottom = nNewGrooveTop; m_spinGrooveBottom.SetPos( nNewGrooveBottom ); } m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDeltaPosGrooveTopSpin void CTabPatternPattern::OnDeltaPosGrooveTopSpin( NMHDR* pNMHDR, LRESULT* pResult ) { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; int nGrooveTop = m_spinGrooveTop.GetPos(); if( HIWORD(nGrooveTop) == 0 ) { int nNewGrooveTop = LOWORD(nGrooveTop) + pNMUpDown->iDelta; int nNewGrooveBottom = m_pPattern->m_bGrooveBottom; if( nNewGrooveTop < MIN_GROOVE) { nNewGrooveTop = MIN_GROOVE; } if( nNewGrooveTop > MAX_GROOVE) { nNewGrooveTop = MAX_GROOVE; } m_spinGrooveTop.SetPos( nNewGrooveTop ); if( nNewGrooveTop < nNewGrooveBottom ) { nNewGrooveBottom = nNewGrooveTop; m_spinGrooveBottom.SetPos( nNewGrooveBottom ); } m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop ); } } *pResult = 1; } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnEmbIntro void CTabPatternPattern::OnEmbIntro() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { if( m_btnIntro.GetCheck() ) { m_pPattern->SetEmbellishment( EMB_INTRO, 0, 0 ); } else { m_pPattern->SetEmbellishment( 0, EMB_INTRO, 0 ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnEmbFill void CTabPatternPattern::OnEmbFill() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { if( m_btnFill.GetCheck() ) { m_pPattern->SetEmbellishment( EMB_FILL, 0, 0 ); } else { m_pPattern->SetEmbellishment( 0, EMB_FILL, 0 ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnEmbBreak void CTabPatternPattern::OnEmbBreak() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { if( m_btnBreak.GetCheck() ) { m_pPattern->SetEmbellishment( EMB_BREAK, 0, 0 ); } else { m_pPattern->SetEmbellishment( 0, EMB_BREAK, 0 ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnEmbEnd void CTabPatternPattern::OnEmbEnd() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { if( m_btnEnd.GetCheck() ) { m_pPattern->SetEmbellishment( EMB_END, 0, 0 ); } else { m_pPattern->SetEmbellishment( 0, EMB_END, 0 ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnCustomDlg void CTabPatternPattern::OnCustomDlg() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { // Display rhythmDlg CRhythmDlg rhythmDlg; rhythmDlg.m_TimeSignature = m_pPattern->m_TimeSignature; rhythmDlg.m_wNbrMeasures = m_pPattern->m_wNbrMeasures; rhythmDlg.m_pRhythmMap = new DWORD[m_pPattern->m_wNbrMeasures]; if( rhythmDlg.m_pRhythmMap ) { for( int i = 0 ; i < m_pPattern->m_wNbrMeasures ; ++i ) { rhythmDlg.m_pRhythmMap[i] = m_pPattern->m_pRhythmMap[i]; } if( rhythmDlg.DoModal() == IDOK ) { // Update rhythm map m_pPattern->SetRhythmMap( rhythmDlg.m_pRhythmMap ); // Redraw rhythm map if( ::IsWindow( m_btnRhythmMap.m_hWnd ) ) { m_btnRhythmMap.Invalidate(); m_btnRhythmMap.UpdateWindow(); } } } if( ::IsWindow( m_btnCustomDlg.m_hWnd ) ) { m_btnCustomDlg.SetFocus(); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDrawItem void CTabPatternPattern::OnDrawItem( int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct ) { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern == NULL ) { CPropertyPage::OnDrawItem( nIDCtl, lpDrawItemStruct ); return; } switch( nIDCtl ) { case IDC_RHYTHM_MAP: { if( lpDrawItemStruct->itemID == -1 ) { return; } CDC* pDC = CDC::FromHandle( lpDrawItemStruct->hDC ); if( pDC == NULL ) { return; } if( lpDrawItemStruct->itemAction & ODA_DRAWENTIRE || lpDrawItemStruct->itemAction & ODA_SELECT ) { int i, j; int nMaxRight = lpDrawItemStruct->rcItem.right - 4; CRect rect( lpDrawItemStruct->rcItem ); rect.right = rect.left; rect.InflateRect( 0, -3 ); int nTickHeight = (rect.Height() >> 1) - 1; for( i = 0 ; i < m_pPattern->m_wNbrMeasures ; i++ ) { for( j = 0 ; j < 32 ; j++ ) { if( j >= m_pPattern->m_TimeSignature.m_bBeatsPerMeasure ) { break; } rect.left = rect.right + 2; rect.right = rect.left + 1; if( rect.left >= nMaxRight ) { break; } if( m_pPattern->m_pRhythmMap[i] & (1 << j) ) { pDC->FillSolidRect( &rect, RGB(0,0,0) ); } else { rect.InflateRect( 0, -nTickHeight ); pDC->FillSolidRect( &rect, RGB(0,0,0) ); rect.InflateRect( 0, nTickHeight ); } } rect.left += 3; rect.right += 3; if( rect.left >= nMaxRight ) { break; } } rect.InflateRect( 0, 3 ); } return; } } CPropertyPage::OnDrawItem( nIDCtl, lpDrawItemStruct ); } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnTimeSignature void CTabPatternPattern::OnTimeSignature() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CTimeSignatureDlg tsDlg; tsDlg.m_TimeSignature = m_pPattern->m_TimeSignature; tsDlg.m_nContext = IDS_PATTERN_TEXT; if( tsDlg.DoModal() == IDOK ) { // Update time signature AfxMessageBox( "Not yet implemented." ); // AMC?? m_pPattern->SetTimeSignature( tsDlg.m_TimeSignature, FALSE ); // Update bitmap on time signature button SetTimeSignatureBitmap(); } if( ::IsWindow( m_btnTimeSignature.m_hWnd ) ) { m_btnTimeSignature.SetFocus(); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnKillFocusDestBottom void CTabPatternPattern::OnKillFocusDestBottom() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CString strNewDestBottom; m_editDestBottom.GetWindowText( strNewDestBottom ); // Strip leading and trailing spaces strNewDestBottom.TrimRight(); strNewDestBottom.TrimLeft(); if( strNewDestBottom.IsEmpty() ) { m_spinDestBottom.SetPos( m_pPattern->m_bDestGrooveBottom ); } else { int nNewDestBottom = _ttoi( strNewDestBottom ); int nNewDestTop = m_pPattern->m_bDestGrooveTop; if( nNewDestBottom < MIN_GROOVE) { nNewDestBottom = MIN_GROOVE; } if( nNewDestBottom > MAX_GROOVE) { nNewDestBottom = MAX_GROOVE; } m_spinDestBottom.SetPos( nNewDestBottom ); if( nNewDestBottom > nNewDestTop ) { nNewDestTop = nNewDestBottom; m_spinDestTop.SetPos( nNewDestTop ); } m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDeltaPosDestBottomSpin void CTabPatternPattern::OnDeltaPosDestBottomSpin( NMHDR* pNMHDR, LRESULT* pResult ) { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; int nDestBottom = m_spinDestBottom.GetPos(); int nNewDestTop = m_pPattern->m_bDestGrooveTop; if( HIWORD(nDestBottom) == 0 ) { int nNewDestBottom = LOWORD(nDestBottom) + pNMUpDown->iDelta; if( nNewDestBottom < MIN_GROOVE) { nNewDestBottom = MIN_GROOVE; } if( nNewDestBottom > MAX_GROOVE) { nNewDestBottom = MAX_GROOVE; } m_spinDestBottom.SetPos( nNewDestBottom ); if( nNewDestBottom > nNewDestTop ) { nNewDestTop = nNewDestBottom; m_spinDestTop.SetPos( nNewDestTop ); } m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop ); } } *pResult = 1; } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnKillFocusDestTop void CTabPatternPattern::OnKillFocusDestTop() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CString strNewDestTop; m_editDestTop.GetWindowText( strNewDestTop ); // Strip leading and trailing spaces strNewDestTop.TrimRight(); strNewDestTop.TrimLeft(); if( strNewDestTop.IsEmpty() ) { m_spinDestTop.SetPos( m_pPattern->m_bDestGrooveTop ); } else { int nNewDestTop = _ttoi( strNewDestTop ); int nNewDestBottom = m_pPattern->m_bDestGrooveBottom; if( nNewDestTop < MIN_GROOVE) { nNewDestTop = MIN_GROOVE; } if( nNewDestTop > MAX_GROOVE) { nNewDestTop = MAX_GROOVE; } m_spinDestTop.SetPos( nNewDestTop ); if( nNewDestTop < nNewDestBottom ) { nNewDestBottom = nNewDestTop; m_spinDestBottom.SetPos( nNewDestBottom ); } m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDeltaPosDestTopSpin void CTabPatternPattern::OnDeltaPosDestTopSpin( NMHDR* pNMHDR, LRESULT* pResult ) { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; int nDestTop = m_spinDestTop.GetPos(); if( HIWORD(nDestTop) == 0 ) { int nNewDestTop = LOWORD(nDestTop) + pNMUpDown->iDelta; int nNewDestBottom = m_pPattern->m_bDestGrooveBottom; if( nNewDestTop < MIN_GROOVE) { nNewDestTop = MIN_GROOVE; } if( nNewDestTop > MAX_GROOVE) { nNewDestTop = MAX_GROOVE; } m_spinDestTop.SetPos( nNewDestTop ); if( nNewDestTop < nNewDestBottom ) { nNewDestBottom = nNewDestTop; m_spinDestBottom.SetPos( nNewDestBottom ); } m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop ); } } *pResult = 1; } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnEmbCustom void CTabPatternPattern::OnEmbCustom() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { if( m_btnCustom.GetCheck() ) { m_pPattern->SetEmbellishment( 0, EMB_ALL, m_pPattern->m_nLastCustomId ); } else { m_pPattern->SetEmbellishment( 0, EMB_ALL, 0 ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnKillFocusCustomId void CTabPatternPattern::OnKillFocusCustomId() { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { CString strNewCustomId; m_editCustomId.GetWindowText( strNewCustomId ); // Strip leading and trailing spaces strNewCustomId.TrimRight(); strNewCustomId.TrimLeft(); if( strNewCustomId.IsEmpty() ) { ASSERT( HIBYTE(m_pPattern->m_wEmbellishment) >= MIN_EMB_CUSTOM_ID && HIBYTE(m_pPattern->m_wEmbellishment) <= MAX_EMB_CUSTOM_ID ); m_spinCustomId.SetPos( HIBYTE(m_pPattern->m_wEmbellishment) ); } else { int nNewCustomId = _ttoi( strNewCustomId ); if( nNewCustomId < MIN_EMB_CUSTOM_ID) { nNewCustomId = MIN_EMB_CUSTOM_ID; } if( nNewCustomId > MAX_EMB_CUSTOM_ID) { nNewCustomId = MAX_EMB_CUSTOM_ID; } m_spinCustomId.SetPos( nNewCustomId ); m_pPattern->SetEmbellishment( 0, EMB_ALL, (BYTE)nNewCustomId ); } } } ///////////////////////////////////////////////////////////////////////////// // CTabPatternPattern::OnDeltaPosCustomIdSpin void CTabPatternPattern::OnDeltaPosCustomIdSpin( NMHDR* pNMHDR, LRESULT* pResult ) { AFX_MANAGE_STATE(_afxModuleAddrThis); if( m_pPattern ) { NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR; int nCustomId = m_spinCustomId.GetPos(); if( HIWORD(nCustomId) == 0 ) { int nNewCustomId = LOWORD(nCustomId) + pNMUpDown->iDelta; if( nNewCustomId < MIN_EMB_CUSTOM_ID) { nNewCustomId = MIN_EMB_CUSTOM_ID; } if( nNewCustomId > MAX_EMB_CUSTOM_ID) { nNewCustomId = MAX_EMB_CUSTOM_ID; } m_spinCustomId.SetPos( nNewCustomId ); m_pPattern->SetEmbellishment( 0, EMB_ALL, (BYTE)nNewCustomId ); } } *pResult = 1; }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
7b742403a29b8b88c41698af9d7532552888f0fd
880b21dd63bd95f69978ac7fc18be59f691c8935
/src/wallet/rpcnames.cpp
67c3839101e31f9417ead0cd79a4ec9ec2b23a4d
[ "MIT" ]
permissive
sovr610/xaya
c88f60bb72138180d2df6c630a52c44ccc37f8a6
a1ba991b476eaa49397e2d054be3241db3727831
refs/heads/master
2022-10-01T17:45:38.814386
2020-06-05T11:53:03
2020-06-08T13:55:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,394
cpp
// Copyright (c) 2014-2020 Daniel Kraft // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <base58.h> #include <coins.h> #include <consensus/validation.h> #include <init.h> #include <interfaces/chain.h> #include <key_io.h> #include <names/common.h> #include <names/encoding.h> #include <names/main.h> #include <names/mempool.h> #include <node/context.h> #include <net.h> #include <primitives/transaction.h> #include <random.h> #include <rpc/blockchain.h> #include <rpc/names.h> #include <rpc/server.h> #include <rpc/util.h> #include <script/names.h> #include <script/standard.h> #include <txmempool.h> #include <util/fees.h> #include <util/moneystr.h> #include <util/system.h> #include <util/translation.h> #include <validation.h> #include <wallet/coincontrol.h> #include <wallet/rpcwallet.h> #include <wallet/wallet.h> #include <univalue.h> #include <algorithm> #include <memory> /* ************************************************************************** */ namespace { /** * A simple helper class that handles determination of the address to which * name outputs should be sent. It handles the CReserveKey reservation * as well as parsing the explicit options given by the user (if any). */ class DestinationAddressHelper { private: /** Reference to the wallet that should be used. */ CWallet& wallet; /** * The reserve key that was used if no override is given. When finalising * (after the sending succeeded), this key needs to be marked as Keep(). */ std::unique_ptr<ReserveDestination> rdest; /** Set if a valid override destination was added. */ std::unique_ptr<CTxDestination> overrideDest; public: explicit DestinationAddressHelper (CWallet& w) : wallet(w) {} /** * Processes the given options object to see if it contains an override * destination. If it does, remembers it. */ void setOptions (const UniValue& opt); /** * Returns the script that should be used as destination. */ CScript getScript (); /** * Marks the key as used if one has been reserved. This should be called * when sending succeeded. */ void finalise (); }; void DestinationAddressHelper::setOptions (const UniValue& opt) { RPCTypeCheckObj (opt, { {"destAddress", UniValueType (UniValue::VSTR)}, }, true, false); if (!opt.exists ("destAddress")) return; CTxDestination dest = DecodeDestination (opt["destAddress"].get_str ()); if (!IsValidDestination (dest)) throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "invalid address"); overrideDest.reset (new CTxDestination (std::move (dest))); } CScript DestinationAddressHelper::getScript () { if (overrideDest != nullptr) return GetScriptForDestination (*overrideDest); rdest.reset (new ReserveDestination (&wallet, wallet.m_default_address_type)); CTxDestination dest; if (!rdest->GetReservedDestination (dest, false)) throw JSONRPCError (RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out," " please call keypoolrefill first"); return GetScriptForDestination (dest); } void DestinationAddressHelper::finalise () { if (rdest != nullptr) rdest->KeepDestination (); } /** * Sends a name output to the given name script. This is the "final" step that * is common between name_new, name_firstupdate and name_update. This method * also implements the "sendCoins" option, if included. */ CTransactionRef SendNameOutput (const JSONRPCRequest& request, CWallet& wallet, const CScript& nameOutScript, const CTxIn* nameInput, const UniValue& opt) { RPCTypeCheckObj (opt, { {"sendCoins", UniValueType (UniValue::VOBJ)}, {"burn", UniValueType (UniValue::VOBJ)}, }, true, false); auto& node = EnsureNodeContext (request.context); if (wallet.GetBroadcastTransactions () && !node.connman) throw JSONRPCError (RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing" " or disabled"); std::vector<CRecipient> vecSend; vecSend.push_back ({nameOutScript, NAME_LOCKED_AMOUNT, false}); if (opt.exists ("sendCoins")) for (const std::string& addr : opt["sendCoins"].getKeys ()) { const CTxDestination dest = DecodeDestination (addr); if (!IsValidDestination (dest)) throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "Invalid address: " + addr); const CAmount nAmount = AmountFromValue (opt["sendCoins"][addr]); if (nAmount <= 0) throw JSONRPCError (RPC_TYPE_ERROR, "Invalid amount for send"); vecSend.push_back ({GetScriptForDestination (dest), nAmount, false}); } if (opt.exists ("burn")) for (const std::string& data : opt["burn"].getKeys ()) { /* MAX_OP_RETURN_RELAY contains three extra bytes, for the opcodes it includes. */ const auto bytes = ToByteVector (data); if (bytes.size () > MAX_OP_RETURN_RELAY - 3) throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "Burn data is too long: " + data); const CAmount nAmount = AmountFromValue (opt["burn"][data]); if (nAmount <= 0) throw JSONRPCError (RPC_TYPE_ERROR, "Invalid amount for burn"); const CScript scr = CScript () << OP_RETURN << bytes; vecSend.push_back ({scr, nAmount, false}); } /* Shuffle the recipient list for privacy. */ std::shuffle (vecSend.begin (), vecSend.end (), FastRandomContext ()); /* Check balance against total amount sent. If we have a name input, we have to take its value into account. */ const CAmount curBalance = wallet.GetBalance ().m_mine_trusted; CAmount totalSpend = 0; for (const auto& recv : vecSend) totalSpend += recv.nAmount; CAmount lockedValue = 0; bilingual_str error; if (nameInput != nullptr) { const CWalletTx* dummyWalletTx; if (!wallet.FindValueInNameInput (*nameInput, lockedValue, dummyWalletTx, error)) throw JSONRPCError(RPC_WALLET_ERROR, error.original); } if (totalSpend > curBalance + lockedValue) throw JSONRPCError (RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); /* Create and send the transaction. This code is based on the corresponding part of SendMoneyToScript and should stay in sync. */ CCoinControl coinControl; CAmount nFeeRequired; int nChangePosRet = -1; CTransactionRef tx; if (!wallet.CreateTransaction (vecSend, nameInput, tx, nFeeRequired, nChangePosRet, error, coinControl)) { if (totalSpend + nFeeRequired > curBalance) error = strprintf (Untranslated ( "Error: This transaction requires a transaction" " fee of at least %s"), FormatMoney (nFeeRequired)); throw JSONRPCError (RPC_WALLET_ERROR, error.original); } wallet.CommitTransaction (tx, {}, {}); return tx; } } // anonymous namespace /* ************************************************************************** */ UniValue name_list (const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request); CWallet* const pwallet = wallet.get (); if (!EnsureWalletIsAvailable (pwallet, request.fHelp)) return NullUniValue; NameOptionsHelp optHelp; optHelp .withNameEncoding () .withValueEncoding (); RPCHelpMan ("name_list", "\nShows the status of all names in the wallet.\n", { {"name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Only include this name"}, optHelp.buildRpcArg (), }, RPCResult {RPCResult::Type::ARR, "", "", { NameInfoHelp () .withHeight () .finish () } }, RPCExamples { HelpExampleCli ("name_list", "") + HelpExampleCli ("name_list", "\"myname\"") + HelpExampleRpc ("name_list", "") } ).Check (request); RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ}, true); UniValue options(UniValue::VOBJ); if (request.params.size () >= 2) options = request.params[1].get_obj (); valtype nameFilter; if (request.params.size () >= 1 && !request.params[0].isNull ()) nameFilter = DecodeNameFromRPCOrThrow (request.params[0], options); std::map<valtype, int> mapHeights; std::map<valtype, UniValue> mapObjects; /* Make sure the results are valid at least up to the most recent block the user could have gotten from another RPC command prior to now. */ pwallet->BlockUntilSyncedToCurrentChain (); { LOCK2 (pwallet->cs_wallet, cs_main); const int tipHeight = ::ChainActive ().Height (); for (const auto& item : pwallet->mapWallet) { const CWalletTx& tx = item.second; CNameScript nameOp; int nOut = -1; for (unsigned i = 0; i < tx.tx->vout.size (); ++i) { const CNameScript cur(tx.tx->vout[i].scriptPubKey); if (cur.isNameOp ()) { if (nOut != -1) LogPrintf ("ERROR: wallet contains tx with multiple" " name outputs"); else { nameOp = cur; nOut = i; } } } if (nOut == -1 || !nameOp.isAnyUpdate ()) continue; const valtype& name = nameOp.getOpName (); if (!nameFilter.empty () && nameFilter != name) continue; const int depth = tx.GetDepthInMainChain (); if (depth <= 0) continue; const int height = tipHeight - depth + 1; const auto mit = mapHeights.find (name); if (mit != mapHeights.end () && mit->second > height) continue; UniValue obj = getNameInfo (options, name, nameOp.getOpValue (), COutPoint (tx.GetHash (), nOut), nameOp.getAddress ()); addOwnershipInfo (nameOp.getAddress (), pwallet, obj); addHeightInfo (height, obj); mapHeights[name] = height; mapObjects[name] = obj; } } UniValue res(UniValue::VARR); for (const auto& item : mapObjects) res.push_back (item.second); return res; } /* ************************************************************************** */ UniValue name_register (const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request); CWallet* const pwallet = wallet.get (); if (!EnsureWalletIsAvailable (pwallet, request.fHelp)) return NullUniValue; NameOptionsHelp optHelp; optHelp .withNameEncoding () .withValueEncoding () .withWriteOptions (); RPCHelpMan ("name_register", "\nRegisters a new name." + HELP_REQUIRING_PASSPHRASE, { {"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to register"}, {"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"}, optHelp.buildRpcArg (), }, RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"}, RPCExamples { HelpExampleCli ("name_register", "\"myname\", \"new-value\"") + HelpExampleRpc ("name_register", "\"myname\", \"new-value\"") } ).Check (request); RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VSTR, UniValue::VOBJ}); UniValue options(UniValue::VOBJ); if (request.params.size () >= 3) options = request.params[2].get_obj (); const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options); TxValidationState state; if (!IsNameValid (name, state)) throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ()); const valtype value = DecodeValueFromRPCOrThrow (request.params[1], options); if (!IsValueValid (value, state)) throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ()); /* Reject updates to a name for which the mempool already has a pending registration. This is not a hard rule enforced by network rules, but it is necessary with the current mempool implementation. */ { LOCK (mempool.cs); if (mempool.registersName (name)) throw JSONRPCError (RPC_TRANSACTION_ERROR, "there is already a pending registration" " for this name"); } { LOCK (cs_main); CNameData data; if (::ChainstateActive ().CoinsTip ().GetName (name, data)) throw JSONRPCError (RPC_TRANSACTION_ERROR, "this name exists already"); } /* Make sure the results are valid at least up to the most recent block the user could have gotten from another RPC command prior to now. */ pwallet->BlockUntilSyncedToCurrentChain (); LOCK (pwallet->cs_wallet); EnsureWalletIsUnlocked (pwallet); DestinationAddressHelper destHelper(*pwallet); destHelper.setOptions (options); const CScript nameScript = CNameScript::buildNameRegister (destHelper.getScript (), name, value); CTransactionRef tx = SendNameOutput (request, *pwallet, nameScript, nullptr, options); destHelper.finalise (); return tx->GetHash ().GetHex (); } /* ************************************************************************** */ UniValue name_update (const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request); CWallet* const pwallet = wallet.get (); if (!EnsureWalletIsAvailable (pwallet, request.fHelp)) return NullUniValue; NameOptionsHelp optHelp; optHelp .withNameEncoding () .withValueEncoding () .withWriteOptions (); RPCHelpMan ("name_update", "\nUpdates a name and possibly transfers it." + HELP_REQUIRING_PASSPHRASE, { {"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to update"}, {"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"}, optHelp.buildRpcArg (), }, RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"}, RPCExamples { HelpExampleCli ("name_update", "\"myname\", \"new-value\"") + HelpExampleRpc ("name_update", "\"myname\", \"new-value\"") } ).Check (request); RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VSTR, UniValue::VOBJ}); UniValue options(UniValue::VOBJ); if (request.params.size () >= 3) options = request.params[2].get_obj (); const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options); TxValidationState state; if (!IsNameValid (name, state)) throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ()); const valtype value = DecodeValueFromRPCOrThrow (request.params[1], options); if (!IsValueValid (value, state)) throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ()); /* For finding the name output to spend, we first check if there are pending operations on the name in the mempool. If there are, then we build upon the last one to get a valid chain. If there are none, then we look up the last outpoint from the name database instead. */ const unsigned chainLimit = gArgs.GetArg ("-limitnamechains", DEFAULT_NAME_CHAIN_LIMIT); COutPoint outp; { LOCK (mempool.cs); const unsigned pendingOps = mempool.pendingNameChainLength (name); if (pendingOps >= chainLimit) throw JSONRPCError (RPC_TRANSACTION_ERROR, "there are already too many pending operations" " on this name"); if (pendingOps > 0) outp = mempool.lastNameOutput (name); } if (outp.IsNull ()) { LOCK (cs_main); CNameData oldData; const auto& coinsTip = ::ChainstateActive ().CoinsTip (); if (!coinsTip.GetName (name, oldData)) throw JSONRPCError (RPC_TRANSACTION_ERROR, "this name can not be updated"); outp = oldData.getUpdateOutpoint (); } assert (!outp.IsNull ()); const CTxIn txIn(outp); /* Make sure the results are valid at least up to the most recent block the user could have gotten from another RPC command prior to now. */ pwallet->BlockUntilSyncedToCurrentChain (); LOCK (pwallet->cs_wallet); EnsureWalletIsUnlocked (pwallet); DestinationAddressHelper destHelper(*pwallet); destHelper.setOptions (options); const CScript nameScript = CNameScript::buildNameUpdate (destHelper.getScript (), name, value); CTransactionRef tx = SendNameOutput (request, *pwallet, nameScript, &txIn, options); destHelper.finalise (); return tx->GetHash ().GetHex (); } /* ************************************************************************** */ UniValue sendtoname (const JSONRPCRequest& request) { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request); CWallet* const pwallet = wallet.get (); if (!EnsureWalletIsAvailable (pwallet, request.fHelp)) return NullUniValue; RPCHelpMan{"sendtoname", "\nSend an amount to the owner of a name.\n" "\nIt is an error if the name is expired." + HELP_REQUIRING_PASSPHRASE, { {"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to send to."}, {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"}, {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment used to store what the transaction is for.\n" " This is not part of the transaction, just kept in your wallet."}, {"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment to store the name of the person or organization\n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet."}, {"subtractfeefromamount", RPCArg::Type::BOOL, /* default */ "false", "The fee will be deducted from the amount being sent.\n" " The recipient will receive less coins than you enter in the amount field."}, {"replaceable", RPCArg::Type::BOOL, /* default */ "fallback to wallet's default", "Allow this transaction to be replaced by a transaction with higher fees via BIP 125"}, {"conf_target", RPCArg::Type::NUM, /* default */ "fallback to wallet's default", "Confirmation target (in blocks)"}, {"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET", "The fee estimate mode, must be one of:\n" " \"UNSET\"\n" " \"ECONOMICAL\"\n" " \"CONSERVATIVE\""}, }, RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"}, RPCExamples{ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1") + HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"\" \"\" true") + HelpExampleRpc ("sendtoname", "\"id/foobar\", 0.1, \"donation\", \"seans outpost\"") }, }.Check (request); RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VNUM, UniValue::VSTR, UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL, UniValue::VNUM, UniValue::VSTR}); if (::ChainstateActive ().IsInitialBlockDownload ()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Xaya is downloading blocks..."); /* Make sure the results are valid at least up to the most recent block the user could have gotten from another RPC command prior to now. */ pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); /* sendtoname does not support an options argument (e.g. to override the configured name/value encodings). That would just add to the already long list of rarely used arguments. Also, this function is inofficially deprecated anyway, see https://github.com/namecoin/namecoin-core/issues/12. */ const UniValue NO_OPTIONS(UniValue::VOBJ); const valtype name = DecodeNameFromRPCOrThrow (request.params[0], NO_OPTIONS); CNameData data; if (!::ChainstateActive ().CoinsTip ().GetName (name, data)) { std::ostringstream msg; msg << "name not found: " << EncodeNameForMessage (name); throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, msg.str ()); } /* The code below is strongly based on sendtoaddress. Make sure to keep it in sync. */ // Amount CAmount nAmount = AmountFromValue(request.params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments mapValue_t mapValue; if (request.params.size() > 2 && !request.params[2].isNull() && !request.params[2].get_str().empty()) mapValue["comment"] = request.params[2].get_str(); if (request.params.size() > 3 && !request.params[3].isNull() && !request.params[3].get_str().empty()) mapValue["to"] = request.params[3].get_str(); bool fSubtractFeeFromAmount = false; if (!request.params[4].isNull()) fSubtractFeeFromAmount = request.params[4].get_bool(); CCoinControl coin_control; if (!request.params[5].isNull()) { coin_control.m_signal_bip125_rbf = request.params[5].get_bool(); } if (!request.params[6].isNull()) { coin_control.m_confirm_target = ParseConfirmTarget(request.params[6], pwallet->chain().estimateMaxBlocks()); } if (!request.params[7].isNull()) { if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter"); } } EnsureWalletIsUnlocked(pwallet); CTransactionRef tx = SendMoneyToScript (pwallet, data.getAddress (), nullptr, nAmount, fSubtractFeeFromAmount, coin_control, std::move(mapValue)); return tx->GetHash ().GetHex (); }
[ "d@domob.eu" ]
d@domob.eu
b189572e70472c26b01c47daea76cd9caab28501
6beb9371bf20461c218a534ea9aabf73727456c0
/WS06/in-lab/Car.cpp
826805572ee822c3bfe272d4f466e3698c5ef00a
[]
no_license
minhqto/oopsiestreefourfive
aef9398a45eabfc62b8a8bf8ff8d5c2d21e44ea5
cb8a5a745dfd50477316337d99522bf54ae07dfe
refs/heads/master
2022-03-15T01:14:25.639532
2020-01-02T04:30:42
2020-01-02T04:30:42
208,258,444
0
0
null
null
null
null
UTF-8
C++
false
false
1,917
cpp
// Name: Minh To // Seneca Student ID: 125526186 // Seneca email: qto@myseneca.ca // Date of completion: 31 Oct 19 // // I confirm that the content of this file is created by me, // with the exception of the parts provided to me by my professor. #include "Car.h" namespace sdds { Car::Car() { maker = ""; carCondition = ""; top_speed = 0; } Car::Car(std::istream& src) { std::string tempCar; std::getline(src, tempCar); //need to erase spaces while(tempCar.find(' ') != std::string::npos){ // size_t indexer = tempCar.find(' '); tempCar.erase(tempCar.find(' '), 1); } eraseStr(tempCar); maker = tempCar.substr(0, tempCar.find_first_of(',')); eraseStr(tempCar); carCondition = tempCar.substr(0, tempCar.find_first_of(',')); if(carCondition == "n"){ carCondition = "new"; } else if(carCondition == "b"){ carCondition = "broken"; } eraseStr(tempCar); top_speed = std::stoi(tempCar); } std::string Car::condition() const { return carCondition; } double Car::topSpeed() const { return top_speed; } void Car::display(std::ostream& out) const { out << "|"; out.width(11); out << this->maker; out << " | "; out.width(6); out.setf(std::ios::left); out << this->carCondition; out.unsetf(std::ios::left); out << " | "; out.width(6); out.setf(std::ios::fixed); out.precision(2); out << this->top_speed << " |"; out.unsetf(std::ios::fixed); out << std::endl; } void eraseStr(std::string& src) { size_t comma = src.find_first_of(','); src.erase(0, comma + 1); } }
[ "minhqto3@gmail.com" ]
minhqto3@gmail.com
9af94c742012d2c814f28c61c6fc3989cad7e2ed
c4026d5ff8cdb876ddb9111df22ce0e4ad3058b2
/codigosC++/testEpp/testEpp/testEpp.cpp
2a590c14fdd309941ce2aaaf52af096577ad0d7b
[]
no_license
NoelGaspar/WacBoard
c8335c2807c16a1d31216b6be83d69f78b23f088
810938cb2543a3f551d024d1c6680947ad6d0f5f
refs/heads/master
2020-04-13T13:18:38.772225
2019-01-03T03:28:56
2019-01-03T03:28:56
163,226,293
0
1
null
null
null
null
ISO-8859-3
C++
false
false
11,339
cpp
// testEpp.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> #include <stdlib.h> #include <string.h> #include <time.h> #include "dpcdecl.h" #include "depp.h" #include "dmgr.h" #include "dpcutil.h" #include "dpcdefs.h" using namespace std; static HIF hif = hifInvalid; static HANDLE han = hifInvalid; static ERC erc=0; static int val=0; //static char dato=0x00; static int test(){ //tratamos de inicializar la comunicacion con el puerto EPP BYTE data[16]; BYTE data2[16]; int i =0; BYTE count=0x00; memset(data2,0x00,16); for(i=0;i<16;i++){ count=count+1; data[i]=count; } fprintf(stderr,"Iniciando\n"); if(!DpcInit(&erc)) { printf("No fue posible iniciar...\n"); puts("presione una tecla para cerrar"); getchar(); return 0; } //una vez inicializado tratamos de abrir la comuniacion. fprintf(stderr,"Iniciado\nAbriendo\n"); if(!DpcOpenData(&han, "Nexys2",&erc,NULL)) { // Change to Basys2 for the other board. printf("DpcOpenData failed (revise si la tarjeta esta conectada)\n"); DpcTerm(); puts("presione una tecla para cerrar"); getchar(); return 0; } // ya abierta la comunicación tratamos de enviar un dato al primer registro fprintf(stderr,"enviando dato de prueba\n"); if(!DpcPutReg(han,0x00, 0x01, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); getchar(); return 0; } puts("presione una tecla para cerrar"); getchar(); fprintf(stderr,"enviando dato de prueba\n"); if(!DpcPutReg(han, 0x10, 0x02, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); char c=getchar(); return 0; } puts("presione una tecla para cerrar"); getchar(); //DpcPutReg(HANDLE hif, BYTE bAddr, BYTE bData, ERC* perc, TRID *ptrid) fprintf(stderr,"enviando dato de prueba\n"); if(!DpcPutReg(han, 0x20, 0x04, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); char c=getchar(); return 0; } //// TRATAMOS DE ENVIAR UN BLOQUE DE 40 BYTES //fprintf(stderr,"enviado 16 datos"); //if(!DpcPutRegRepeat(han,0x30, data,16,&erc, NULL)){ // printf("DpcPutRegRepeat failed.\n"); // puts("presione una tecla para cerrar"); // char c=getchar(); //} // // TRATAMOS DE LEER UN BLOQUE DE 40 BYTES //fprintf(stderr,"leyendo datos. \n"); //if(!DpcGetRegRepeat(han,0x30,data2,16,&erc, NULL)){ // printf("DpcGetRegRepeat failed.\n"); // puts("presione una tecla para cerrar"); // char c=getchar(); //} // //for(int i=0;i<16;i++){ //printf( "datos obtenidos:%x \n",data2[i]); //} fprintf(stderr,"dato enviado exitosamente. Cerrando\n"); if( han != hifInvalid ) { DpcCloseData(han,&erc); DpcTerm(); puts("presione una tecla para cerrar"); char c=getchar(); return 0; } return 1; } static int sendAdc(BYTE *datos){ if(!DpcPutReg(han,0x00, 0x59, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } if(!DpcPutReg(han,0x10, 0xff, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } if(!DpcPutReg(han,0x20, 0x55, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } Sleep(20); fprintf(stderr,"leyendo datos. \n"); if(!DpcGetRegRepeat(han,0x30,datos,20,&erc, NULL)){ printf("DpcGetRegRepeat failed.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } return 0; } /* Esta funcion envia comandos de forma completa. el formato es 1 addr: 0x00 dato: ctrl 2 addr: 0x10 dato: confL 3 addr: 0x20 dato: confH */ static int sendComnd(BYTE ctrl, BYTE confH,BYTE confL){ if(!DpcPutReg(han,0x00, ctrl, &erc, NULL)){ printf("DpcPutReg failed sending control word.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } if(!DpcPutReg(han,0x10, confL, &erc, NULL)){ printf("DpcPutReg failed sending config Low word.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } if(!DpcPutReg(han,0x20, confH, &erc, NULL)){ printf("DpcPutReg failed sending config HIGH word.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } return 0; } /* Esta funcion envia una nueva memoria al bloque secuenciador. Para esto debe enviar 32*2 datos de 8 bits. La memoria en tontal cuenta con 32 addr de 16 bits. Para esto en el archivo "text_seq.tex" debe haberse cargado los 64 BYTE a enviar escritos en formato hexadecimal La funcion carga los 64 BYTE en el buffer data[64] y posteriormente se envian con la funcion DpcPutRegRepeat, a la dirección 0x40. */ static int sendSeq(){ BYTE data[68]; memset(data,0x00,68); int i =0; FILE *pFilSeq; pFilSeq=fopen("tex_output.txt","r"); rewind(pFilSeq); for(i=0;i<64;i++) {fscanf(pFilSeq,"%x",&data[i]);} fclose(pFilSeq); for( i=0; i<64;i++){ //Mostramos en consola los datos enviados. fprintf (stderr, "datos a enviar: %d : %x \n",i,data[i]);} if(!DpcPutRegRepeat(han,0x40, data, 64, &erc, NULL)){ printf("DpcPutRegRepeat failed.\n"); puts("presione una tecla para cerrar"); getchar(); return 1; } printf("Datos enviados.\n"); getchar(); return 0; } /* Esta funcion convierte de un numero int en ascii a su representación hexadecimal */ static BYTE charintohex(char in1,char in2){ BYTE out=0x00; BYTE temp1=0x00; BYTE temp2=0x00; if(in1=='1'){ temp1=0x01;} if(in1=='2'){ temp1=0x02;} if(in1=='3'){ temp1=0x03;} if(in1=='4'){ temp1=0x04;} if(in1=='5'){ temp1=0x05;} if(in1=='6'){ temp1=0x06;} if(in1=='7'){ temp1=0x07;} if(in1=='8'){ temp1=0x08;} if(in1=='9'){ temp1=0x09;} if(in1=='a'){ temp1=0x0a;} if(in1=='b'){ temp1=0x0b;} if(in1=='c'){ temp1=0x0c;} if(in1=='d'){ temp1=0x0d;} if(in1=='e'){ temp1=0x0e;} if(in1=='f'){ temp1=0x0f;} if(in2=='1'){ temp2=0x10;} if(in2=='2'){ temp2=0x20;} if(in2=='3'){ temp2=0x30;} if(in2=='4'){ temp2=0x40;} if(in2=='5'){ temp2=0x50;} if(in2=='6'){ temp2=0x60;} if(in2=='7'){ temp2=0x70;} if(in2=='8'){ temp2=0x80;} if(in2=='9'){ temp2=0x90;} if(in2=='a'){ temp2=0xa0;} if(in2=='b'){ temp2=0xb0;} if(in2=='c'){ temp2=0xc0;} if(in2=='d'){ temp2=0xd0;} if(in2=='e'){ temp2=0xe0;} if(in2=='f'){ temp2=0xf0;} return out=temp2|temp1; } /* Esta funcion convierte un numeros de 12 bits en formato complemento de dos a un entero con signo. El formato de las entradas son 11 10 9 8 7 6 5 4 3 2 1 0 |----msb----| |-------lsb-----| asi si nuestro numero a convertir es 0xf43 debemos usar complementoDos2int(0x0f, 0x34); el serultado será =-204. */ static int complementoDos2int(BYTE msb, BYTE lsb){ BYTE carry=0x00; int d=0; if((msb&0x08)==0x08){ lsb=lsb^0xff; msb=msb^0x0f; if(lsb==0xff){carry=0x01;} else{carry=0x00;} lsb=lsb+0x01; msb=msb+carry; msb=msb&0x0f; d=(-1)* (int)(msb << 8 | lsb); } else{ d=(int)( msb << 8 | lsb); } return d; } int main(int cszArg, char * rgszArg[]) { //definimos funciones locales char c='p'; //recibir datos char n='p'; //recibir datos BYTE ctrl=0x00; //palabra de control a enviar BYTE confH=0x00; //palabra de configuracion primeros 8 bits BYTE confL=0x00; //palabra de configuracion ultimos 8 bits //BYTE dato=0x00; //variable de dato BYTE max=0x07; int val=0; int i=0; int d[1000]; ////creamos una variable FILE para registrar los datos obtenidos ////y un vector de 30 datos de 8 bits a enviar. FILE * pFile; pFile = fopen ("prueba.txt","w"); BYTE datos[2000]; memset(datos,0xff,2000); //Iniciar la comunicación fprintf(stderr,"Iniciando\n"); if(!DpcInit(&erc)) { printf("No fue posible iniciar...\n"); puts("presione una tecla para cerrar"); getchar(); return 0; } //Una vez inicializado tratamos de abrir la comuniacion. fprintf(stderr,"Abriendo conexion...\n"); if(!DpcOpenData(&han, "Nexys2",&erc,NULL)) { // Change to Basys2 for the other board. printf("DpcOpenData failed (revise si la tarjeta esta conectada)\n"); DpcTerm(); puts("presione una tecla para cerrar"); getchar(); return 0; } fprintf(stderr,"enviando dato de prueba\n"); //Este dato es para resetear el puntero de direcciones en la memoria de la BRAM if(!DpcPutReg(han,0x3f, 0xff, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); getchar(); } //-------------------------------------- // Enviar un comando //-------------------------------------- while(c!='x'){ printf("Ingrese un comando:\n"); n=getchar(); c=getchar(); getchar(); if(n=='x'){break;} ctrl=charintohex(c,n); printf("Ingrese un confH:\n"); n=getchar(); c=getchar(); getchar(); if(n=='x'){break;} confH=charintohex(c,n); printf("Ingrese un confL:\n"); n=getchar(); c=getchar(); getchar(); if(n=='x'){break;} confL=charintohex(c,n); if(ctrl==0x44) {val=sendSeq(); printf("Enviando una nueva secuencia\n");} else {val= sendComnd(ctrl,confH,confL); printf("Enviando comando\n");} if(c=='x'){ printf("Saliendo del programa\n"); } if(val!=0){ printf("problema detectado\n"); break;} } //-------------------------------------- //-------------------------------------- fprintf(stderr,"enviando dato de prueba\n"); //Este dato es para resetear el puntero de direcciones en la memoria de la BRAM if(!DpcPutReg(han,0x3f, 0xff, &erc, NULL)){ printf("DpcPutReg failed.\n"); puts("presione una tecla para cerrar"); getchar(); } fprintf(stderr,"leyendo datos. \n"); //Leemos de forma continua los 30 direcciones a partir de la direccion 3. y los almacenamos en el vector datos. if(!DpcGetRegRepeat(han,0x30,datos,2000,&erc, NULL)){ printf("DpcGetRegRepeat failed.\n"); puts("presione una tecla para cerrar"); getchar(); } fprintf(stderr,"calculando datos\n"); BYTE carry=0x00; for(i=0;i<1000;i++){ d[i]=complementoDos2int(datos[2*i+1],datos[2*i]); } for( i=0; i<30;i++){ //Mostramos en consola los datos enviados. fprintf (stderr, "datos obtenidos: %d : %d \n",i,d[i]);} fprintf(stderr,"escribiendo datos\n"); for( i=0; i<1000;i++){ //Mostramos en consola los datos enviados. fprintf (pFile,"%d\n",d[i]);} ////-------------------------------------------------------------------------- ////Este bloque es para probar el dac, hace un barrido de todos los valores //puts("listos para empezar, presione una tecla para continuar"); //getchar(); //confH=0xe0; //ctrl=0x01; //for(int j=0;j<15;j++){ //for(int i=0;i<25;i++){ // confL=confL+0x0a; // val=(j*25)+i; // //printf("dato%i:%x %x\n",val,confH,confL); // sendComnd(ctrl,confH,confL); //} //confH=confH+0x01; //} ////---------------------------------------------------------------------------- printf("Cerrando. presione cualquier tecla para continuar\n"); //cerramos las comunicaciones. getchar(); if( han != hifInvalid ) { DpcCloseData(han,&erc); DpcTerm(); } DpcCloseData(han,&erc); //terminamos la comunicación DpcTerm(); fclose (pFile); return 0; }
[ "waaraya@uc.cl" ]
waaraya@uc.cl
c72ab318a1314d7a1d024e8dc7aaa0ca85bdac53
98e40260cddd889669396c8328805268346684e7
/src/mineField.h
c4e6d9275062ba6eac3db4b5f2756858bc5c04ca
[]
no_license
FightingSu/mine_sweeper
4e7f891bba9cdbe70deaf559df3a11f1ea3fa623
cc7a538b8870dbdf1bcba0f2a32c5de038c149ec
refs/heads/main
2023-04-02T12:22:33.118838
2021-04-07T07:36:07
2021-04-07T07:36:07
308,811,309
1
0
null
null
null
null
UTF-8
C++
false
false
1,405
h
#ifndef _MINE_FIELD_H_ #define _MINE_FIELD_H_ #include "blockWidget.h" #include <cstdlib> #include <ctime> #include <QWidget> #include <QVector> #include <QMessageBox> #include <QMouseEvent> #include <QDebug> class mineField : public QWidget { Q_OBJECT public: mineField(QWidget* parent = nullptr, int _width = 9, int _height = 9, int _mineNum = 10); void getSettingSquare(int _square[3][3], int center, int _xNum); int getXNum(); int getYNum(); int getMineNum(); void mouseReleaseEvent(QMouseEvent* event); void resotre(); void showMines(); // reimplement function QSize sizeHint() const; public Q_SLOTS: void getExplode(); void getFlag(int _xPos, int _yPos, bool _flag); void getEmptyBlock(int _xPos, int _yPos); Q_SIGNALS: // true alive // false dead void gameOver(bool _lifeStatus); private: // 为什么使用 QVector<blockWidget*> 而不是 blockWidget*? // 因为 这里需要申请多个 blockWidget, 每个 blockWidget 的父对象都是 mineField // 当释放第一个 blockWidget 的时候, mineField 会将 blockWidget 当作 blockWidget* 释放 // 但是实际上它是一个 blockWidget* [] // 相当于 delete [] 用成了 delete QVector<blockWidget*> ptrVector; QVector<int> randomRes; QVector<int> flagBlocks; int xNum; int yNum; int mineNum; QVector<int> randomMines(int mineNumber, int _xNum, int _yNum); }; #endif // _MINE_FIELD_H_
[ "ww951127.ok@hotmail.com" ]
ww951127.ok@hotmail.com
909913756b968f2ee38ca4cc7c276341484f1427
768bda36062ffa1a5c6357b28cb8367f9b2be1ed
/AbleClass/AsyncLoaderHelper.cpp
5e29c2ba9f5a99a7e11362fbe11aa99ba91bffd2
[]
no_license
djia99/creadIWB
446f9c77c5e97c3774a8fd3efdf9a66e82a64f1c
6fd0b41f42b29df61dac7952249db8715de076b1
refs/heads/master
2020-04-16T22:52:46.243102
2019-01-16T07:07:53
2019-01-16T07:07:53
165,988,118
0
0
null
null
null
null
UTF-8
C++
false
false
6,459
cpp
//=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED 'AS IS' WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== #include "StdAfx.h" #include "AsyncLoaderHelper.h" #include "AsyncLoader\CriticalSectionLocker.h" using namespace AsyncLoaderSpace; // // Constructor // AsyncLoaderHelper::AsyncLoaderHelper() : m_criticalSection(nullptr), m_pageItemCount(0), m_pageStart(0), m_nextPagePercentage(0), m_previousPagePercentage(0), m_smallerSizePercentage(0) // smaller size = more items in the window by %20... { } // // Destructor // AsyncLoaderHelper::~AsyncLoaderHelper() { bool active = true; do { HRESULT hr = m_asyncLoader->IsWorkingThreadActive(&active); if (FAILED(hr)) { active = false; } else { if (active) { m_asyncLoader->EndWorkerThread(); ::Sleep(100); } } } while (active); } // // Initialize // HRESULT AsyncLoaderHelper::Initialize() { HRESULT hr = SharedObject<AsyncLoader>::Create(&m_asyncLoader); if (SUCCEEDED(hr)) { hr = m_asyncLoader->GetCriticalSection(&m_criticalSection); } if (SUCCEEDED(hr)) { hr = m_asyncLoader->GetItemsList(&m_asyncLoaderItemList); } if (SUCCEEDED(hr)) { hr = m_asyncLoader->GetItemLayoutManager(&m_asyncLoaderLayoutManager); } if (SUCCEEDED(hr)) { // Configure layout manager... //m_asyncLoaderLayoutManager->SetCurrentPageItemCount(static_cast<int>(m_pageItemCount)); m_asyncLoaderLayoutManager->SetCurrentPage(static_cast<int>(m_pageStart)); // Configure the memory manager... hr = m_asyncLoader->GetMemoryManager(&m_asyncLoaderMemoryManager); } if (SUCCEEDED(hr)) { // Connect the converter... hr = SharedObject<MemorySizeConverter>::Create(&m_memorySizeConverter); } if (SUCCEEDED(hr)) { hr = m_asyncLoaderMemoryManager->SetMemorySizeConverter(m_memorySizeConverter); } if (SUCCEEDED(hr)) { // Configure the memory manager... m_asyncLoaderMemoryManager->SetMemoryCap(500000000); //m_asyncLoaderMemoryManager->SetMemoryCap(10); } return hr; } // // Start background loading // HRESULT AsyncLoaderHelper::StartBackgroundLoading() { return m_asyncLoader->StartWorkerThread(); } // // Pause background loading // HRESULT AsyncLoaderHelper::PauseBackgroundLoading() { CriticalSectionLocker l(m_criticalSection); return m_asyncLoader->PauseWorkerThread(); } // // Resume background loading // HRESULT AsyncLoaderHelper::ResumeBackgroundLoading() { CriticalSectionLocker l(m_criticalSection); return m_asyncLoader->ResumeWorkerThread(); } // // Shutdown // HRESULT AsyncLoaderHelper::Shutdown() { CriticalSectionLocker l(m_criticalSection); HRESULT hr = m_asyncLoader->EndWorkerThread(); if (SUCCEEDED(hr)) { hr = m_asyncLoader->Shutdown(); } return hr; } // // Get the associated AsyncLoader // HRESULT AsyncLoaderHelper::GetAsyncLoader(IAsyncLoader** asyncLoader) { CriticalSectionLocker l(m_criticalSection); *asyncLoader = nullptr; return AssignToOutputPointer(asyncLoader, m_asyncLoader); } // // SetPageItemCount // HRESULT AsyncLoaderHelper::SetPageItemCount(unsigned int count) { CriticalSectionLocker l(m_criticalSection); return m_asyncLoaderLayoutManager->SetCurrentPageItemCount(count); } // // SetCurrentPagePivot // HRESULT AsyncLoaderHelper::SetCurrentPagePivot(unsigned int pivot) { CriticalSectionLocker l(m_criticalSection); m_pageStart = static_cast<float>(pivot); return m_asyncLoaderLayoutManager->SetCurrentPage(static_cast<int>(m_pageStart)); } // // Scroll by the specified amount // HRESULT AsyncLoaderHelper::Scroll(int scrollBy) { CriticalSectionLocker l(m_criticalSection); m_pageStart += scrollBy; return m_asyncLoaderLayoutManager->SetCurrentPage((int)m_pageStart); } // // Zoom // HRESULT AsyncLoaderHelper::Zoom(float factor) { CriticalSectionLocker l(m_criticalSection); m_pageItemCount = m_pageItemCount * factor; return m_asyncLoaderLayoutManager->SetCurrentPageItemCount(static_cast<unsigned int>(m_pageItemCount)); } // // Connect to the specified client // HRESULT AsyncLoaderHelper::ConnectClient(CWnd* client) { return m_asyncLoaderMemoryManager->RegisterClientWnd(client); } // // ConnectItem // HRESULT AsyncLoaderHelper::ConnectItem(IUnknown* newItem, int location) { ComPtr<IAsyncLoaderItem> asyncLoaderItem; HRESULT hr = newItem->QueryInterface(IID_PPV_ARGS(&asyncLoaderItem)); if (SUCCEEDED(hr)) { hr = asyncLoaderItem->SetMemoryManager(m_asyncLoaderMemoryManager); } if (SUCCEEDED(hr)) { hr = asyncLoaderItem->SetLocation(location); } if (SUCCEEDED(hr)) { hr = asyncLoaderItem->SetCriticalSection(m_criticalSection); } if (SUCCEEDED(hr)) { hr = m_asyncLoaderItemList->Add(asyncLoaderItem); } return hr; } // // Clear items // HRESULT AsyncLoaderHelper::ClearItems() { return m_asyncLoaderItemList->Clear(); } HRESULT AsyncLoaderHelper::StartFullImageLoad(LoadSize type, unsigned int index) { CriticalSectionLocker l(m_criticalSection); return m_asyncLoaderLayoutManager->SetFullImageLoad(type, index); } HRESULT AsyncLoaderHelper::SetLoadType(LOADTYPE loadType) { return m_asyncLoader->SetLoadType(loadType); } BOOL AsyncLoaderHelper::CheckListLoadDone() { return m_asyncLoader->IsListLoadDone(); }
[ "noreply@github.com" ]
djia99.noreply@github.com
ffaa53a6d966d9872692c9fc4b814cc96d412bb0
0b34dc130e8296d3d61eedf37452be5de41af1c2
/OpenGl/OpenGL超级宝典完整源码(第五版)/OpenGL超级宝典完整源码(第五版)/Src/Chapter07/TextureArrays/TextureArrays.cpp
6175095d59282c7ccfb534788f26f04a7c793668
[]
no_license
BIbiLion/LS_Wqiakun2017Test
67a77c07a33ea4d5f308492580a403774de99b30
2955f20d8ac63acd8ace2a553f2e062e9ac26e92
refs/heads/master
2021-01-20T14:19:28.468757
2017-09-15T08:04:55
2017-09-15T08:04:55
90,591,454
2
3
null
null
null
null
UTF-8
C++
false
false
9,071
cpp
// TextureArrays.cpp // OpenGL SuperBible // Demonstrates Passing a TextureArray to a shader // Program by Richard S. Wright Jr. #include <GLTools.h> // OpenGL toolkit #include <GLFrustum.h> #include <Stopwatch.h> #ifdef __APPLE__ #include <glut/glut.h> #else #define FREEGLUT_STATIC #include <GL/glut.h> #endif GLShaderManager shaderManager; GLFrustum viewFrustum; GLBatch smallStarBatch; GLBatch mediumStarBatch; GLBatch largeStarBatch; GLBatch mountainRangeBatch; GLBatch moonBatch; GLuint starTexture; GLuint starFieldShader; // The point sprite shader GLint locMVP; // The location of the ModelViewProjection matrix uniform GLint locStarTexture; // The location of the texture uniform GLuint moonTexture; GLuint moonShader; GLint locMoonMVP; GLint locMoonTexture; GLint locMoonTime; GLint locTimeStamp; // The location of the time stamp // Array of small stars #define SMALL_STARS 100 #define MEDIUM_STARS 40 #define LARGE_STARS 15 #define SCREEN_X 800 #define SCREEN_Y 600 // Load a TGA as a 2D Texture. Completely initialize the state bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode) { GLbyte *pBits; int nWidth, nHeight, nComponents; GLenum eFormat; // Read the texture bits pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat); if(pBits == NULL) return false; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBits); free(pBits); if(minFilter == GL_LINEAR_MIPMAP_LINEAR || minFilter == GL_LINEAR_MIPMAP_NEAREST || minFilter == GL_NEAREST_MIPMAP_LINEAR || minFilter == GL_NEAREST_MIPMAP_NEAREST) glGenerateMipmap(GL_TEXTURE_2D); return true; } /////////////////////////////////////////////////// // Called to draw scene void RenderScene(void) { static CStopWatch timer; // Clear the window glClear(GL_COLOR_BUFFER_BIT); // Everything is white GLfloat vWhite [] = { 1.0f, 1.0f, 1.0f, 1.0f }; glBindTexture(GL_TEXTURE_2D, starTexture); glUseProgram(starFieldShader); glUniformMatrix4fv(locMVP, 1, GL_FALSE, viewFrustum.GetProjectionMatrix()); glUniform1i(locStarTexture, 0); // Draw small stars glPointSize(4.0f); smallStarBatch.Draw(); // Draw medium sized stars glPointSize(8.0f); mediumStarBatch.Draw(); // Draw largest stars glPointSize(12.0f); largeStarBatch.Draw(); // Draw distant horizon shaderManager.UseStockShader(GLT_SHADER_FLAT, viewFrustum.GetProjectionMatrix(), vWhite); glLineWidth(3.5); mountainRangeBatch.Draw(); // Draw the "moon" glBindTexture(GL_TEXTURE_2D_ARRAY, moonTexture); glUseProgram(moonShader); glUniformMatrix4fv(locMoonMVP, 1, GL_FALSE, viewFrustum.GetProjectionMatrix()); glUniform1i(locMoonTexture, 0); // fTime goes from 0.0 to 28.0 and recycles float fTime = timer.GetElapsedSeconds(); fTime = fmod(fTime, 28.0f); glUniform1f(locTimeStamp, fTime); moonBatch.Draw(); // Swap buffers glutSwapBuffers(); glutPostRedisplay(); } // This function does any needed initialization on the rendering // context. void SetupRC() { M3DVector3f vVerts[SMALL_STARS]; // SMALL_STARS is the largest batch we are going to need int i; shaderManager.InitializeStockShaders(); // Populate star list smallStarBatch.Begin(GL_POINTS, SMALL_STARS); for(i = 0; i < SMALL_STARS; i++) { vVerts[i][0] = (GLfloat)(rand() % SCREEN_X); vVerts[i][1] = (GLfloat)(rand() % (SCREEN_Y - 100)) + 100.0f; vVerts[i][2] = 0.0f; } smallStarBatch.CopyVertexData3f(vVerts); smallStarBatch.End(); // Populate star list mediumStarBatch.Begin(GL_POINTS, MEDIUM_STARS); for(i = 0; i < MEDIUM_STARS; i++) { vVerts[i][0] = (GLfloat)(rand() % SCREEN_X); vVerts[i][1] = (GLfloat)(rand() % (SCREEN_Y - 100)) + 100.0f; vVerts[i][2] = 0.0f; } mediumStarBatch.CopyVertexData3f(vVerts); mediumStarBatch.End(); // Populate star list largeStarBatch.Begin(GL_POINTS, LARGE_STARS); for(i = 0; i < LARGE_STARS; i++) { vVerts[i][0] = (GLfloat)(rand() % SCREEN_X); vVerts[i][1] = (GLfloat)(rand() % (SCREEN_Y - 100)) + 100.0f; vVerts[i][2] = 0.0f; } largeStarBatch.CopyVertexData3f(vVerts); largeStarBatch.End(); M3DVector3f vMountains[12] = { 0.0f, 25.0f, 0.0f, 50.0f, 100.0f, 0.0f, 100.0f, 25.0f, 0.0f, 225.0f, 125.0f, 0.0f, 300.0f, 50.0f, 0.0f, 375.0f, 100.0f, 0.0f, 460.0f, 25.0f, 0.0f, 525.0f, 100.0f, 0.0f, 600.0f, 20.0f, 0.0f, 675.0f, 70.0f, 0.0f, 750.0f, 25.0f, 0.0f, 800.0f, 90.0f, 0.0f }; mountainRangeBatch.Begin(GL_LINE_STRIP, 12); mountainRangeBatch.CopyVertexData3f(vMountains); mountainRangeBatch.End(); // The Moon GLfloat x = 700.0f; // Location and radius of moon GLfloat y = 500.0f; GLfloat r = 50.0f; GLfloat angle = 0.0f; // Another looping variable moonBatch.Begin(GL_TRIANGLE_FAN, 4, 1); moonBatch.MultiTexCoord2f(0, 0.0f, 0.0f); moonBatch.Vertex3f(x - r, y - r, 0.0f); moonBatch.MultiTexCoord2f(0, 1.0f, 0.0f); moonBatch.Vertex3f(x + r, y - r, 0.0f); moonBatch.MultiTexCoord2f(0, 1.0f, 1.0f); moonBatch.Vertex3f(x + r, y + r, 0.0f); moonBatch.MultiTexCoord2f(0, 0.0f, 1.0f); moonBatch.Vertex3f(x - r, y + r, 0.0f); moonBatch.End(); // Black background glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); // Turn on line antialiasing, and give hint to do the best // job possible. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_LINE_SMOOTH); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); starFieldShader = gltLoadShaderPairWithAttributes("StarField.vp", "StarField.fp", 1, GLT_ATTRIBUTE_VERTEX, "vVertex"); locMVP = glGetUniformLocation(starFieldShader, "mvpMatrix"); locStarTexture = glGetUniformLocation(starFieldShader, "starImage"); moonShader = gltLoadShaderPairWithAttributes("MoonShader.vp", "MoonShader.fp", 2, GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_TEXTURE0, "vTexCoords"); locMoonMVP = glGetUniformLocation(moonShader, "mvpMatrix"); locMoonTexture = glGetUniformLocation(moonShader, "moonImage"); locMoonTime = glGetUniformLocation(moonShader, "fTime"); glGenTextures(1, &starTexture); glBindTexture(GL_TEXTURE_2D, starTexture); LoadTGATexture("Star.tga", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE); glGenTextures(1, &moonTexture); glBindTexture(GL_TEXTURE_2D_ARRAY, moonTexture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 64, 64, 30, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); for(int i = 0; i < 29; i++) { char cFile[32]; sprintf(cFile, "moon%02d.tga", i); GLbyte *pBits; int nWidth, nHeight, nComponents; GLenum eFormat; // Read the texture bits pBits = gltReadTGABits(cFile, &nWidth, &nHeight, &nComponents, &eFormat); glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, nWidth, nHeight, 1, GL_BGRA, GL_UNSIGNED_BYTE, pBits); free(pBits); } } void ChangeSize(int w, int h) { // Prevent a divide by zero if(h == 0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); // Establish clipping volume (left, right, bottom, top, near, far) viewFrustum.SetOrthographic(0.0f, SCREEN_X, 0.0f, SCREEN_Y, -1.0f, 1.0f); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 600); glutCreateWindow("Texture Arrays"); glutReshapeFunc(ChangeSize); glutDisplayFunc(RenderScene); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } SetupRC(); glutMainLoop(); return 0; }
[ "wqiankun89@163.com" ]
wqiankun89@163.com
47c52f62c32dabd6b2804693f66fdfdd707b6fc7
c6881dbb2cb0aea8ac39c809aa5d339c9e15ac09
/Blockchain/nameclaim.cpp
37a2ae949f27d126a29dd3d7b55cc86da074e52c
[]
no_license
HungMingWu/blockchain-demo
d62afbe6caf41f07b7896f312fd9a2a7e27280c7
ebe6e079606fe2fe7bf03783d66300df7a94d5be
refs/heads/master
2020-03-21T22:33:38.664567
2018-10-01T10:12:40
2018-10-01T10:12:40
139,134,108
0
0
null
null
null
null
UTF-8
C++
false
false
5,046
cpp
#include "nameclaim.h" #include "hash.h" #include "util.h" #include "Log.h" #include <string> using namespace std; std::vector<unsigned char> uint32_t_to_vch(uint32_t n) { std::vector<unsigned char> vchN; vchN.resize(4); vchN[0] = n >> 24; vchN[1] = n >> 16; vchN[2] = n >> 8; vchN[3] = n; return vchN; } uint32_t vch_to_uint32_t(std::vector<unsigned char>& vchN) { uint32_t n; if (vchN.size() != 4) { LOG_INFO("%s() : a vector<unsigned char> with size other than 4 has been given", __func__); return 0; } n = vchN[0] << 24 | vchN[1] << 16 | vchN[2] << 8 | vchN[3]; return n; } CScript ClaimNameScript(std::string name, std::string value) { std::vector<unsigned char> vchName(name.begin(), name.end()); std::vector<unsigned char> vchValue(value.begin(), value.end()); return CScript() << OP_CLAIM_NAME << vchName << vchValue << OP_2DROP << OP_DROP << OP_TRUE; } CScript SupportClaimScript(std::string name, uint160 claimId) { std::vector<unsigned char> vchName(name.begin(), name.end()); std::vector<unsigned char> vchClaimId(claimId.begin(),claimId.end()); return CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId << OP_2DROP << OP_DROP << OP_TRUE; } CScript UpdateClaimScript(std::string name, uint160 claimId, std::string value) { std::vector<unsigned char> vchName(name.begin(), name.end()); std::vector<unsigned char> vchClaimId(claimId.begin(),claimId.end()); std::vector<unsigned char> vchValue(value.begin(), value.end()); return CScript() << OP_UPDATE_CLAIM << vchName << vchClaimId << vchValue << OP_2DROP << OP_2DROP << OP_TRUE; } bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams) { CScript::const_iterator pc = scriptIn.begin(); return DecodeClaimScript(scriptIn, op, vvchParams, pc); } bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, CScript::const_iterator& pc) { opcodetype opcode; if (!scriptIn.GetOp(pc, opcode)) { return false; } if (opcode != OP_CLAIM_NAME && opcode != OP_SUPPORT_CLAIM && opcode != OP_UPDATE_CLAIM) { return false; } op = opcode; std::vector<unsigned char> vchParam1; std::vector<unsigned char> vchParam2; std::vector<unsigned char> vchParam3; // Valid formats: // OP_CLAIM_NAME vchName vchValue OP_2DROP OP_DROP pubkeyscript // OP_UPDATE_CLAIM vchName vchClaimId vchValue OP_2DROP OP_2DROP pubkeyscript // OP_SUPPORT_CLAIM vchName vchClaimId OP_2DROP OP_DROP pubkeyscript // All others are invalid. if (!scriptIn.GetOp(pc, opcode, vchParam1) || opcode < 0 || opcode > OP_PUSHDATA4) { return false; } if (!scriptIn.GetOp(pc, opcode, vchParam2) || opcode < 0 || opcode > OP_PUSHDATA4) { return false; } if (op == OP_UPDATE_CLAIM || op == OP_SUPPORT_CLAIM) { if (vchParam2.size() != 160/8) { return false; } } if (op == OP_UPDATE_CLAIM) { if (!scriptIn.GetOp(pc, opcode, vchParam3) || opcode < 0 || opcode > OP_PUSHDATA4) { return false; } } if (!scriptIn.GetOp(pc, opcode) || opcode != OP_2DROP) { return false; } if (!scriptIn.GetOp(pc, opcode)) { return false; } if ((op == OP_CLAIM_NAME || op == OP_SUPPORT_CLAIM) && opcode != OP_DROP) { return false; } else if ((op == OP_UPDATE_CLAIM) && opcode != OP_2DROP) { return false; } vvchParams.push_back(vchParam1); vvchParams.push_back(vchParam2); if (op == OP_UPDATE_CLAIM) { vvchParams.push_back(vchParam3); } return true; } uint160 ClaimIdHash(const uint256& txhash, uint32_t nOut) { std::vector<unsigned char> claimToHash(txhash.begin(), txhash.end()); std::vector<unsigned char> vchnOut = uint32_t_to_vch(nOut); claimToHash.insert(claimToHash.end(), vchnOut.begin(), vchnOut.end()); return Hash160(claimToHash); } CScript StripClaimScriptPrefix(const CScript& scriptIn) { int op; return StripClaimScriptPrefix(scriptIn, op); } CScript StripClaimScriptPrefix(const CScript& scriptIn, int& op) { std::vector<std::vector<unsigned char> > vvchParams; CScript::const_iterator pc = scriptIn.begin(); if (!DecodeClaimScript(scriptIn, op, vvchParams, pc)) { return scriptIn; } return CScript(pc, scriptIn.end()); } size_t ClaimScriptSize(const CScript& scriptIn) { CScript strippedScript = StripClaimScriptPrefix(scriptIn); return scriptIn.size() - strippedScript.size(); } size_t ClaimNameSize(const CScript& scriptIn) { std::vector<std::vector<unsigned char> > vvchParams; CScript::const_iterator pc = scriptIn.begin(); int op; if (!DecodeClaimScript(scriptIn, op, vvchParams, pc)) { return 0; } else { return vvchParams[0].size(); } }
[ "u9089000@gmail.com" ]
u9089000@gmail.com
5b0b66aed7ff6b3f5191221a850fbc4d11ee6035
5474747cb6ec8f0fe72b4d6320ff51e04e35946e
/training/Source.cpp
be3ef3091d6f42d6cbb8bbc798b94071b279d9f6
[]
no_license
SergeyShopik/Cpp_Warehouse_Managament
50dd84bfe1621f7e5001304afa50a3517693c0a3
bf9d15c55e00854df9283b2a57aca3c2676dcc11
refs/heads/master
2023-01-27T22:56:58.547499
2020-12-11T19:36:42
2020-12-11T19:36:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,938
cpp
#include<iostream> #include<cctype> #include<cstring> #include<cstdlib> const int SIZE = 100; //warehouse managament struct inv_type { char item[40]; double cost, retail; int on_hand, lead_time; } invtry[SIZE]; void init_list(); int menu(); void input(int); void enter(); void update(); void display(); void find(); void showFound(int); int main() { int n = 0; //warehouse managament char choice; init_list(); for ( ; ; ) { choice = menu(); switch (choice) { case 'e': enter(); break; case 'd': display(); break; case 'u': update(); break; case 'f': find(); break; case 's': showFound(n); break; case 'q': return 0; } } system("pause"); return 0; } void init_list() { for (int i = 0; i < SIZE; i++) *invtry[i].item = '\0'; } int menu() { char ch; std::cout << '\n'; do { std::cout << "(E)nter\n"; std::cout << "(D)isplay\n"; std::cout << "(U)pdate\n"; std::cout << "(F)ind\n"; std::cout << "(S)how\n"; std::cout << "(Q)uit\n\n"; std::cout << "Choose comand: "; std::cin >> ch; } while (!strchr("edufsq", tolower(ch))); return tolower(ch); } void input(int i) { std::cout << "Good: "; std::cin >> invtry[i].item; std::cout << "Cost: "; std::cin >> invtry[i].cost; std::cout << "Price: "; std::cin >> invtry[i].retail; std::cout << "Stock: "; std::cin >> invtry[i].on_hand; std::cout << "Lead time: "; std::cin >> invtry[i].lead_time; } void enter() { int i; for (i = 0; i < SIZE; i++) if (!*invtry[i].item) break; if (i == SIZE) { std::cout << "List is full.\n"; return; } input(i); } void update() { int i; char name[80]; std::cout << "Enter good's name: "; std::cin >> name; for (i = 0; i < SIZE; i++) if (!strcmp(name, invtry[i].item)) break; if (i == SIZE) { std::wcout << "Good is not found.\n"; return; } std::cout << "Enter new info.\n"; input(i); } void display() { int i; for (i = 0; i < SIZE; i++) { if (*invtry[i].item) { std::cout << invtry[i].item << '\n'; std::cout << "Cost: $" << invtry[i].cost; std::cout << "\nPrice: $"; std::cout << invtry[i].retail; std::cout << "\nStock: " << invtry[i].on_hand; std::cout << "\nLead time remaining: "; std::cout << invtry[i].lead_time << " days\n\n"; } } } void find() { int i; char name[80]; std::cout << "Enter good's name: "; std::cin >> name; for (i = 0; i < SIZE; i++) if (!strcmp(name, invtry[i].item)) break; if (i == SIZE) { std::cout << "Good is not found.\n"; return; } std::cout << "Enter new info.\n"; showFound(i); } void showFound(int i) { for (i = 0; i < SIZE; i++) { if (*invtry[i].item) { std::cout << invtry[i].item << '\n'; std::cout << "Cost: $" << invtry[i].cost; std::cout << "\nPrice: $"; std::cout << invtry[i].retail; std::cout << "\nStock: " << invtry[i].on_hand; std::cout << "\nLead time remaining: "; std::cout << invtry[i].lead_time << " days\n\n"; } } }
[ "sergey.shopik101@gmail.com" ]
sergey.shopik101@gmail.com
f64df2b94f4b1b2a86840084189f9565e180cabf
c81133690291377794e35afc4dcf2763a4b2a12d
/src/proxy_lib.cpp
ce9cdf8f24376dfec86d1575f544a692d7a4f822
[]
no_license
T-Maxxx/iw3linker_vs
3666c4646b4ca4e0c8065c1a902350eab4ae97ce
4fa22fa00bcd4601bf5641199cc336571879a7ef
refs/heads/master
2021-01-24T04:43:45.438553
2020-06-12T13:24:36
2020-06-12T13:26:43
122,948,449
1
3
null
null
null
null
UTF-8
C++
false
false
2,304
cpp
#include "proxy_lib.hpp" #include <cstdio> template<class FP> FP GetLibFunction(HMODULE hLib_, const char* FunctionName_) { return reinterpret_cast<FP>(GetProcAddress(hLib_, FunctionName_)); } CProxyLib::CProxyLib() { char path[MAX_PATH] = { '\0' }; char sysPath[MAX_PATH - 13] = { '\0' }; GetSystemDirectoryA(sysPath, sizeof(sysPath)); sprintf_s(path, "%s\\d3dx9_34.dll", sysPath); m_hOriginalLib = LoadLibrary(path); } CProxyLib::~CProxyLib() { if (m_hOriginalLib) FreeLibrary(m_hOriginalLib); } CProxyLib& CProxyLib::Instance() { static CProxyLib proxyLib; return proxyLib; } bool CProxyLib::IsReady() const { return m_hOriginalLib != NULL; } HRESULT CProxyLib::D3DXGetShaderOutputSemantics(const DWORD* pFunction, void* pSemantics, UINT* pCount) { using D3DXGetShaderOutputSemantics_t = HRESULT(WINAPI*)(const DWORD*, void*, UINT*); static D3DXGetShaderOutputSemantics_t fn = nullptr; if (!fn) fn = GetLibFunction<D3DXGetShaderOutputSemantics_t>(m_hOriginalLib, "D3DXGetShaderOutputSemantics"); return fn ? fn(pFunction, pSemantics, pCount) : -1; } HRESULT CProxyLib::D3DXCreateBuffer(DWORD NumBytes, DWORD ppBuffer) { using D3DXCreateBuffer_t = HRESULT(WINAPI*)(DWORD, DWORD); static D3DXCreateBuffer_t fn = nullptr; if (!fn) fn = GetLibFunction<D3DXCreateBuffer_t>(m_hOriginalLib, "D3DXCreateBuffer"); return fn ? fn(NumBytes, ppBuffer) : -1; } HRESULT CProxyLib::D3DXGetShaderInputSemantics(const DWORD* pFunction, void* pSemantics, UINT* pCount) { using D3DXGetShaderInputSemantics_t = HRESULT(WINAPI*)(const DWORD*, void*, UINT*); static D3DXGetShaderInputSemantics_t fn = nullptr; if (!fn) fn = GetLibFunction<D3DXGetShaderInputSemantics_t>(m_hOriginalLib, "D3DXGetShaderInputSemantics"); return fn ? fn(pFunction, pSemantics, pCount) : -1; } HRESULT CProxyLib::D3DXGetShaderConstantTable(const DWORD* pFunction, void* ppConstantTable) { using FPD3DXGetShaderConstantTable_t = HRESULT(WINAPI*)(const DWORD*, void*); static FPD3DXGetShaderConstantTable_t fn = nullptr; if (!fn) fn = GetLibFunction<FPD3DXGetShaderConstantTable_t>(m_hOriginalLib, "D3DXGetShaderConstantTable"); return fn ? fn(pFunction, ppConstantTable) : -1; }
[ "tmax.tver.95@gmail.com" ]
tmax.tver.95@gmail.com
f2e0a2924468f1e593445878edd0e3318c7fb77e
5752ccaf99fc23ad5d22e8aa2e7d38b0e06c1ad4
/test/timer.hpp
23331a6cbd8b5b6fc5c351f2ca9cb8327a384871
[]
no_license
EoghanMcGinty/xcelerit_test
1c43db44db5773f8e7acee625b72a8fe1fbc4316
98ec76850c615e523497fd45a12436670f89d0cc
refs/heads/master
2020-08-09T02:15:46.373115
2019-10-09T17:07:13
2019-10-09T17:07:13
213,975,512
0
0
null
null
null
null
UTF-8
C++
false
false
622
hpp
#include <iostream> #include <chrono> class Timer { public: Timer() { startTime = std::chrono::high_resolution_clock::now(); } long int stop() { auto endTime = std::chrono::high_resolution_clock::now(); auto start = std::chrono::time_point_cast<std::chrono::microseconds>(startTime).time_since_epoch().count(); auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTime).time_since_epoch().count(); auto duration = end - start; return duration; } private: std::chrono::time_point<std::chrono::high_resolution_clock> startTime; };
[ "eoghanm19@gmail.com" ]
eoghanm19@gmail.com
c66afabc1ff3c9d43a80f7f7ed592e835939795e
b3679befe0405fbb04b3b8e331055e1d04704819
/src/cl_sphere.cpp
f09b8ecdadef40277f3980997ffa4947346dbca9
[ "MIT" ]
permissive
gmmoreira/ruby-ffi-opencl
f3d5c1ffe249d437439ab3195bcff48805873d24
48363889d01428a1d9df78690db7b437974a545c
refs/heads/master
2021-01-11T08:24:45.982661
2016-11-03T01:28:57
2016-11-03T01:28:57
72,287,687
1
0
null
null
null
null
UTF-8
C++
false
false
1,028
cpp
#include "cl_sphere.h" #include "cl_platform.hpp" #include "cl_device.hpp" #include <cstring> using std::string; using std::vector; using std::strcpy; const char * string_to_char(string data) { auto c_data = (char *) malloc(sizeof(char) * (data.size() + 1)); strcpy(c_data, data.c_str()); return c_data; } cl_uint get_platforms_size() { return getPlatformsSize(); } cl_platform_id get_platform(cl_uint position) { auto platforms = getPlatforms(); return platforms[position].id; } const char * get_platform_name(cl_platform_id platform_id) { auto platform = getPlatform(platform_id); return string_to_char(platform.name); } cl_uint get_devices_size(cl_platform_id platform_id) { return getDevicesSize(platform_id); } cl_device_id get_device(cl_platform_id platform_id, cl_uint position) { auto devices = getDevices(platform_id); return devices[position].id; } const char * get_device_name(cl_device_id device_id) { auto device = getDevice(device_id); return string_to_char(device.name); }
[ "guilhermerx7@gmail.com" ]
guilhermerx7@gmail.com
8177a20561454d860f25fe4dce77c068f6bd7237
2d36ac7285664ce798edb27bafa00e0dbc0f25fb
/LSL/liblsl/external/lslboost/date_time/gregorian/greg_month.hpp
e9d3aa485fa1de590c08a9c2d97cf9384e4dc7b5
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
nagarjunvinukonda/Brain-Computer-Interface-for-Bionic-Arm
af1a6241df167e747a7d9426e497f95dda632fda
839cb0dc798d2bf274d3df7c4db0fef62af3770d
refs/heads/master
2023-02-13T12:02:36.692225
2021-01-14T08:32:35
2021-01-14T08:32:35
297,540,583
2
0
null
null
null
null
UTF-8
C++
false
false
3,508
hpp
#ifndef GREG_MONTH_HPP___ #define GREG_MONTH_HPP___ /* Copyright (c) 2002,2003 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.lslboost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $ */ #include "lslboost/date_time/constrained_value.hpp" #include "lslboost/date_time/date_defs.hpp" #include "lslboost/shared_ptr.hpp" #include "lslboost/date_time/compiler_config.hpp" #include <stdexcept> #include <string> #include <map> #include <algorithm> #include <cctype> namespace lslboost { namespace gregorian { typedef date_time::months_of_year months_of_year; //bring enum values into the namespace using date_time::Jan; using date_time::Feb; using date_time::Mar; using date_time::Apr; using date_time::May; using date_time::Jun; using date_time::Jul; using date_time::Aug; using date_time::Sep; using date_time::Oct; using date_time::Nov; using date_time::Dec; using date_time::NotAMonth; using date_time::NumMonths; //! Exception thrown if a greg_month is constructed with a value out of range struct bad_month : public std::out_of_range { bad_month() : std::out_of_range(std::string("Month number is out of range 1..12")) {} }; //! Build a policy class for the greg_month_rep typedef CV::simple_exception_policy<unsigned short, 1, 12, bad_month> greg_month_policies; //! A constrained range that implements the gregorian_month rules typedef CV::constrained_value<greg_month_policies> greg_month_rep; //! Wrapper class to represent months in gregorian based calendar class BOOST_DATE_TIME_DECL greg_month : public greg_month_rep { public: typedef date_time::months_of_year month_enum; typedef std::map<std::string, unsigned short> month_map_type; typedef lslboost::shared_ptr<month_map_type> month_map_ptr_type; //! Construct a month from the months_of_year enumeration greg_month(month_enum theMonth) : greg_month_rep(static_cast<greg_month_rep::value_type>(theMonth)) {} //! Construct from a short value greg_month(unsigned short theMonth) : greg_month_rep(theMonth) {} //! Convert the value back to a short operator unsigned short() const {return value_;} //! Returns month as number from 1 to 12 unsigned short as_number() const {return value_;} month_enum as_enum() const {return static_cast<month_enum>(value_);} const char* as_short_string() const; const char* as_long_string() const; #ifndef BOOST_NO_STD_WSTRING const wchar_t* as_short_wstring() const; const wchar_t* as_long_wstring() const; #endif // BOOST_NO_STD_WSTRING //! Shared pointer to a map of Month strings (Names & Abbrev) & numbers static month_map_ptr_type get_month_map_ptr(); /* parameterized as_*_string functions are intended to be called * from a template function: "... as_short_string(charT c='\0');" */ const char* as_short_string(char) const { return as_short_string(); } const char* as_long_string(char) const { return as_long_string(); } #ifndef BOOST_NO_STD_WSTRING const wchar_t* as_short_string(wchar_t) const { return as_short_wstring(); } const wchar_t* as_long_string(wchar_t) const { return as_long_wstring(); } #endif // BOOST_NO_STD_WSTRING }; } } //namespace gregorian #endif
[ "vinukondanagarjun4@gmail.com" ]
vinukondanagarjun4@gmail.com
599f75157c869fe3b57f71026b184769113dbb23
cc21344f152ec8f2f9b27fc666af32d6aefbb24c
/binary-string.cpp
659168db5018c1ee75548c75f80eee337f333433
[]
no_license
narwal1996/GeeksforGeeks
447aa4d8a940fc28002917aac840ee1d0dc9413b
0226c5ac6ac58d00cf2a56c28e649f73641472d9
refs/heads/master
2020-04-12T05:41:00.558652
2016-11-15T14:16:13
2016-11-15T14:16:13
65,081,905
0
0
null
null
null
null
UTF-8
C++
false
false
341
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; string s; cin >> s; long long int nones = 0; for(int i=0; i<n; i++) if(s[i]=='1') nones++; if(n<2 || nones<2) cout << 0 << endl; else cout << (nones*(nones-1))/2 << endl; } return 0; }
[ "noreply@github.com" ]
narwal1996.noreply@github.com
ff966d913d5427f17ec9fd7e32dd7d537cdf1ff7
6e57bdc0a6cd18f9f546559875256c4570256c45
/external/pdfium/core/fpdfapi/render/cpdf_imagecacheentry.h
2bede23e628d28b72affbe8c617dbaaf2c083a51
[ "BSD-3-Clause" ]
permissive
dongdong331/test
969d6e945f7f21a5819cd1d5f536d12c552e825c
2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e
refs/heads/master
2023-03-07T06:56:55.210503
2020-12-07T04:15:33
2020-12-07T04:15:33
134,398,935
2
1
null
2022-11-21T07:53:41
2018-05-22T10:26:42
null
UTF-8
C++
false
false
1,984
h
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef CORE_FPDFAPI_RENDER_CPDF_IMAGECACHEENTRY_H_ #define CORE_FPDFAPI_RENDER_CPDF_IMAGECACHEENTRY_H_ #include <memory> #include "core/fxcrt/fx_system.h" #include "core/fxcrt/retain_ptr.h" #include "core/fxcrt/unowned_ptr.h" class CFX_DIBSource; class CFX_DIBitmap; class CPDF_Dictionary; class CPDF_Document; class CPDF_Image; class CPDF_RenderStatus; class IFX_PauseIndicator; class CPDF_ImageCacheEntry { public: CPDF_ImageCacheEntry(CPDF_Document* pDoc, const RetainPtr<CPDF_Image>& pImage); ~CPDF_ImageCacheEntry(); void Reset(const RetainPtr<CFX_DIBitmap>& pBitmap); uint32_t EstimateSize() const { return m_dwCacheSize; } uint32_t GetTimeCount() const { return m_dwTimeCount; } CPDF_Image* GetImage() const { return m_pImage.Get(); } int StartGetCachedBitmap(CPDF_Dictionary* pFormResources, CPDF_Dictionary* pPageResources, bool bStdCS, uint32_t GroupFamily, bool bLoadMask, CPDF_RenderStatus* pRenderStatus); int Continue(IFX_PauseIndicator* pPause, CPDF_RenderStatus* pRenderStatus); RetainPtr<CFX_DIBSource> DetachBitmap(); RetainPtr<CFX_DIBSource> DetachMask(); int m_dwTimeCount; uint32_t m_MatteColor; private: void ContinueGetCachedBitmap(CPDF_RenderStatus* pRenderStatus); void CalcSize(); UnownedPtr<CPDF_Document> const m_pDocument; RetainPtr<CPDF_Image> const m_pImage; RetainPtr<CFX_DIBSource> m_pCurBitmap; RetainPtr<CFX_DIBSource> m_pCurMask; RetainPtr<CFX_DIBSource> m_pCachedBitmap; RetainPtr<CFX_DIBSource> m_pCachedMask; uint32_t m_dwCacheSize; }; #endif // CORE_FPDFAPI_RENDER_CPDF_IMAGECACHEENTRY_H_
[ "dongdong331@163.com" ]
dongdong331@163.com
b06e60cd44f26f9a6f7f3f53d7e0ff07cac00255
07d308c27b77bf452a3df302b8da3906ec6ef23d
/include/dali/core/mm/pool_resource.h
276afa5fd3f38e48d07b1abd36ea3bdfc66cc89e
[ "Apache-2.0" ]
permissive
Lovegood-1/DALI
aa678a57030a083308f1d72fe1296a4eb9f5e812
0c62fc3b6d56003f326457d5387c803518094a37
refs/heads/master
2023-04-03T06:37:09.113994
2021-03-30T14:44:24
2021-03-30T14:44:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,055
h
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef DALI_CORE_MM_POOL_RESOURCE_H_ #define DALI_CORE_MM_POOL_RESOURCE_H_ #include <mutex> #include "dali/core/mm/memory_resource.h" #include "dali/core/mm/detail/free_list.h" #include "dali/core/small_vector.h" namespace dali { namespace mm { struct pool_options { /** * @brief Maximum block size * * Growth stops at this point; larger blocks are allocated only when allocate is called with * a larger memory requirements. */ size_t max_block_size = static_cast<size_t>(-1); // no limit /// Minimum size of blocks requested from upstream size_t min_block_size = (1 << 12); /// The factor by which the allocation size grows until it reaches max_block_size float growth_factor = 2; /** * @brief Whether to try to allocate smaller blocks from upstream if default upcoming * block is unavailable. */ bool try_smaller_on_failure = true; size_t upstream_alignment = 256; }; constexpr pool_options default_host_pool_opts() noexcept { return { (1 << 28), (1 << 12), 2.0f, true }; } constexpr pool_options default_device_pool_opts() noexcept { return { (static_cast<size_t>(1) << 32), (1 << 20), 2.0f, false }; } template <memory_kind kind, typename Context, class FreeList, class LockType> class pool_resource_base : public memory_resource<kind, Context> { public: explicit pool_resource_base(memory_resource<kind, Context> *upstream = nullptr, const pool_options opt = {}) : upstream_(upstream), options_(opt) { next_block_size_ = opt.min_block_size; } pool_resource_base(const pool_resource_base &) = delete; pool_resource_base(pool_resource_base &&) = delete; ~pool_resource_base() { free_all(); } void free_all() { for (auto &block : blocks_) { upstream_->deallocate(block.ptr, block.bytes, block.alignment); } blocks_.clear(); free_list_.clear(); } protected: void *do_allocate(size_t bytes, size_t alignment) override { if (!bytes) return nullptr; { lock_guard guard(lock_); void *ptr = free_list_.get(bytes, alignment); if (ptr) return ptr; } alignment = std::max(alignment, options_.upstream_alignment); size_t blk_size = bytes; void *new_block = get_upstream_block(blk_size, bytes, alignment); assert(new_block); try { lock_guard guard(lock_); blocks_.push_back({ new_block, blk_size, alignment }); if (blk_size == bytes) { // we've allocated a block exactly of the required size - there's little // chance that it will be merged with anything in the pool, so we'll return it as-is return new_block; } else { // we've allocated an oversized block - put the remainder in the free list lock_guard guard(lock_); free_list_.put(static_cast<char *>(new_block) + bytes, blk_size - bytes); return new_block; } } catch (...) { upstream_->deallocate(new_block, blk_size, alignment); throw; } } void do_deallocate(void *ptr, size_t bytes, size_t alignment) override { lock_guard guard(lock_); free_list_.put(ptr, bytes); } void *get_upstream_block(size_t &blk_size, size_t min_bytes, size_t alignment) { blk_size = next_block_size(min_bytes); for (;;) { try { return upstream_->allocate(blk_size, alignment); } catch (const std::bad_alloc &) { if (blk_size == min_bytes || !options_.try_smaller_on_failure) throw; blk_size = std::max(min_bytes, blk_size >> 1); } } } virtual Context do_get_context() const noexcept { return upstream_->get_context(); } size_t next_block_size(size_t upcoming_allocation_size) { size_t actual_block_size = std::max(upcoming_allocation_size, next_block_size_); next_block_size_ = std::min<size_t>(actual_block_size * options_.growth_factor, options_.max_block_size); return actual_block_size; } memory_resource<kind, Context> *upstream_; FreeList free_list_; LockType lock_; pool_options options_; size_t next_block_size_ = 0; struct UpstreamBlock { void *ptr; size_t bytes, alignment; }; SmallVector<UpstreamBlock, 16> blocks_; using lock_guard = std::lock_guard<LockType>; using unique_lock = std::unique_lock<LockType>; }; } // namespace mm } // namespace dali #endif // DALI_CORE_MM_POOL_RESOURCE_H_
[ "noreply@github.com" ]
Lovegood-1.noreply@github.com
3ebeedf97df49842ffcfcfedb7331250015f06c8
07a72a30913757756484c60402007ad39154b2f4
/Spider/Worker.cpp
8d00a3dde2098813a7445d44b10b6d05d789e695
[]
no_license
SammyEnigma/ImageSpider
d767275feea58f5d0a8b40f7cbb49ec70d02f341
6bf4e9d8085ec080d9f9bc06fb083a23153bb827
refs/heads/master
2021-07-20T03:26:27.602635
2016-02-20T03:43:56
2016-02-20T03:43:56
223,331,944
0
0
null
2020-08-01T12:57:47
2019-11-22T05:43:19
null
UTF-8
C++
false
false
1,681
cpp
#include "Worker.h" Worker::Worker(QObject *parent) : QObject(parent) { //http://sexy.faceks.com/ //http://www.2xiezhen.com/meinvxiezhen/ startUrl = QUrl("http://sexy.faceks.com/"); // startUrl = QUrl("http://www.2xiezhen.com/meinvxiezhen/"); QString referer = "http://" + startUrl.host(); DataQueue::data()->appendUrl(startUrl); network = new QNetworkAccessManager(this); spider = new Spider; parser = new Parser; QStringList nextPagePatterns; nextPagePatterns << "<a\\s+class=[\"']next[\"'].*href=[\"']([^>]*page=\\d+.*)[\"']>" << "<a\\s+href=['\"]([^['\"]+.html)['\"]>></a>" << "<a\\s+href=['\"]([^['\"]+.html)['\"]>下一页</a>" << "<a\\s+href=['\"]([^['\"]+.html)['\"]>Next</a>"; //http://sexy.faceks.com parser->setUrlRegexpPattern("<div\\s+class=['\"]pic['\"].*href=['\"]([^['\"]+)['\"].*>"); parser->setImageRegexpPattern("bigimgsrc=[\"']([^'\"]+)['\"]"); parser->setNextPageRegexpPatterns(nextPagePatterns); //http://www.2xiezhen.com/siwameinv // parser->setUrlRegexpPattern("<li>\\s*<a.*href=['\"]([^['\"]+.html)['\"].*/></a>"); // parser->setImageRegexpPattern("<a\\s+class=['\"]showpic['\"].*href=.*src=['\"]([^['\"]+.jpg)['\"]\\s*/>"); parser->setRefererUrl(referer); spider->setNetwokManager(network); spider->setParser(parser); // download images downloader = new Downloader; downloader->setNetwokManager(network); downloader->setRefererUrl(referer.toLocal8Bit()); } Worker::~Worker() { delete parser; delete spider; delete network; } void Worker::start() { spider->start(); }
[ "yuri.young@newdebug.com" ]
yuri.young@newdebug.com
ec27883f3a712e4cc23567b6e8b2d992fd684b8f
becc5bffc7a29491a09780c57e89f5ab8d688299
/Code/src/simcube/simcube_projection-galactic/fits_simimg.cpp
b7e4539fc627ed9602457940fff8480abc09e5dc
[ "Apache-2.0" ]
permissive
VisIVOLab/ViaLacteaVisualAnalytics
6186d282f553e63984bac9f6086ca326d3ac8503
fbd5da6dc28c1f32632a7622193c03a98263903b
refs/heads/master
2023-08-21T19:46:05.667116
2023-06-01T14:30:43
2023-06-01T14:30:43
269,041,293
1
0
Apache-2.0
2023-09-11T08:39:46
2020-06-03T09:09:00
C++
UTF-8
C++
false
false
3,503
cpp
#include "fits_simimg.hpp" #include <fitsio.h> #include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <string> using namespace std; string get_errstatus(int status) { char err_text[32]; // CFITSIO doc: max 30 char error text fits_get_errstatus(status, err_text); return string { err_text }; } fits_simimg::fits_simimg(string fits_filename) : fptr { nullptr } { int status = 0; if (fits_open_image(&fptr, fits_filename.c_str(), READWRITE, &status)) { throw std::runtime_error(get_errstatus(status) + " : " + fits_filename); } // FIXME assert that ctype is parsec -> only then cdelt/dist is valid int nfound = 0; if (fits_read_keys_dbl(fptr, "CDELT", 1, 2, cdelt_vals, &nfound, &status) || (nfound != 2)) { throw std::invalid_argument(string("Error: reading CDELT 1 2 : ") + get_errstatus(status)); } } void fits_simimg::update_card(string keyname, string keyvalue) { int status = 0; char card[FLEN_CARD], oldcard[FLEN_CARD], newcard[FLEN_CARD]; char oldvalue[FLEN_VALUE], comment[FLEN_COMMENT]; int keytype; if (fits_read_card(fptr, keyname.c_str(), card, &status)) { throw invalid_argument(string("Keys to update must exist but read card ") + string(card) + " yields error : " + get_errstatus(status)); } strcpy(oldcard, card); /* check if this is a protected keyword that must not be changed */ if (*card && fits_get_keyclass(card) == TYP_STRUC_KEY) { throw invalid_argument(string("Protected keyword cannot be modified: ") + string(card)); } else { /* get the comment string */ if (*card) fits_parse_value(card, oldvalue, comment, &status); /* construct template for new keyword */ strcpy(newcard, keyname.c_str()); /* copy keyword name */ strcat(newcard, " = "); /* '=' value delimiter */ strcat(newcard, keyvalue.c_str()); /* new value */ if (*comment) { strcat(newcard, " / "); /* comment delimiter */ strcat(newcard, comment); /* append the comment */ } /* reformat the keyword string to conform to FITS rules */ fits_parse_template(newcard, card, &keytype, &status); if (string(card) == string(oldcard)) { throw invalid_argument(string("Card has already the expected value: ") + string(card)); } /* overwrite the keyword with the new value */ fits_update_card(fptr, keyname.c_str(), card, &status); } if (status) throw runtime_error(string("update_card failed: ") + get_errstatus(status)); } void fits_simimg::update_header(const double cdelt_deg[2], const double crval_deg[2]) { map<string, string> keys_const_value { { "CTYPE1", "GLON-CAR" }, { "CTYPE2", "GLAT-CAR" }, { "CUNIT1", "deg" }, { "CUNIT2", "deg" }, }; for (map<string, string>::iterator it = keys_const_value.begin(); it != keys_const_value.end(); ++it) update_card(it->first, it->second); map<string, string> keys_calc_value { { "CRVAL1", to_string(crval_deg[0]) }, { "CRVAL2", to_string(crval_deg[1]) }, { "CDELT1", to_string(cdelt_deg[0]) }, { "CDELT2", to_string(cdelt_deg[1]) }, }; for (map<string, string>::iterator it = keys_calc_value.begin(); it != keys_calc_value.end(); ++it) update_card(it->first, it->second); }
[ "giuseppe.tudisco@inaf.it" ]
giuseppe.tudisco@inaf.it
e6038e7dcca49ac7daaa4389f6ba0be8e791b711
f7ff42ef0bb9b9b1223bd7851e31070044a977b2
/temp/find_address.cpp
426f38b9902ce64ff7cfcbee084a9ece6a40c1c0
[]
no_license
yvesmartindestaillades/RRL_pouch_motors_control
42250c9672c6cf0a678e2535897f58b453a9fa95
42b32829e8dc36356c31acb6a1a79056a3cf7bba
refs/heads/master
2023-04-02T17:31:28.724360
2021-04-17T18:09:58
2021-04-17T18:09:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
cpp
/**************************************************************************/ /*! @file read_simple_angle.ino @author SOSAndroid (E. Ha.) @license BSD (see license.txt) read a simple angle from AS5048B over I2C bus @section HISTORY v1.0 - First release */ /**************************************************************************/ #include <ams_as5048b.h> //unit consts #define U_RAW 1 #define U_TRN 2 #define U_DEG 3 #define U_RAD 4 #define U_GRAD 5 #define U_MOA 6 #define U_SOA 7 #define U_MILNATO 8 #define U_MILSE 9 #define U_MILRU 10 AMS_AS5048B mysensor; void setup() { //Start serial Serial.begin(9600); while (!Serial) ; //wait until Serial ready //consider the current position as zero //mysensor.setZeroReg(); for(int i=0x30;i<0xFF;i++){ AMS_AS5048B mysensor(i); mysensor.begin(); uint8_t adress = mysensor.addressRegR(); if (adress != 255){ Serial.println( "\n ----------------------- \n \n Adress "+ String(i)+" : "+String(adress) + "\n -----------"); delay(2000); } delay(5); } } void loop() { //print to serial the raw angle and degree angle every 2 seconds //print 2 times the exact same angle - only one measurement Serial.println("Programme fini"); delay(3000); }
[ "yves.mrtn98@gmail.com" ]
yves.mrtn98@gmail.com
f7a68585d3ca11e6ff92fe2ea4c38c8c7e0e395d
02099155d15b3d65330abc7276b13c8deff68e94
/B/B. Petya and Countryside/main.cpp
e2e84479e9c7db2144ca35e695e0c611be158735
[]
no_license
xUser5000/competitive-programming
d7c760fa6db58956e472dd80e24def0358bbb5a8
90337c982dd3663a69f2d19021e692f1edb1b3a5
refs/heads/master
2023-06-26T21:56:02.452867
2021-07-23T22:39:49
2021-07-23T22:39:49
288,557,139
1
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include <iostream> using namespace std; int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) cin >> arr[i]; int ans = 1; for (int i = 0; i < n; i++) { int d = 1; for (int j = i + 1; j < n; j++) { if (arr[j] <= arr[j - 1]) d++; else break; } for (int j = i - 1; j >= 0; j--) { if (arr[j] <= arr[j + 1]) d++; else break; } ans = max(ans, d); } cout << ans; return 0; }
[ "abdallahar1974@gmail.com" ]
abdallahar1974@gmail.com
37d9f26142043f7e9671c4145c998b08f8aac179
8687a237b885bb7a116410491e48c35d444745b5
/c++/primer_plus_s_pratt/ch_12/pe_2/include/string2.h
befd489d13e2ea2f9251f323c4a68d73227cb3c6
[ "MIT" ]
permissive
dinimar/Projects
150b3d95247c738ca9a5ce6b2ec1ed9cee30b415
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
refs/heads/master
2021-06-11T20:34:29.081266
2021-05-15T19:22:36
2021-05-15T19:22:36
183,491,754
0
0
MIT
2019-04-25T18:47:39
2019-04-25T18:47:39
null
UTF-8
C++
false
false
1,404
h
// // Created by Dinir Imameev on 11/21/19. // Github: @dinimar // #ifndef STRING2_H_ #define STRING2_H_ #include <iostream> using std::ostream; using std::istream; class String { private: char * str; // pointer to string int len; // length of string static int num_strings; // number of objects static const int CINLIM = 80; // cin input limit public: // constructors and other methods String(const char * s); // constructor String(); // default constructor String(const String &); // copy constructor ~String(); // destructor int length () const { return len; } int has(const char &); void stringLow(); void stringUp(); // overloaded operator methods String & operator=(const String &); String & operator=(const char *); String operator+(const String &) const; String operator+(const char *) const; char & operator[](int i); const char & operator[](int i) const; // overloaded operator friends friend String operator+(char * s, const String &st); friend bool operator<(const String &st, const String &st2); friend bool operator>(const String &st1, const String &st2); friend bool operator==(const String &st, const String &st2); friend ostream & operator<<(ostream & os, const String & st); friend istream & operator>>(istream & is, String & st); // static function static int HowMany(); }; #endif
[ "dinir.imameev@gmail.com" ]
dinir.imameev@gmail.com
4026209bb982fc198cd3f1eda31ea3f3fb757153
5ae308aaa7bb2e60b1ddff28fcaf39567da1b6ae
/LCP/lcp_074_search_a_2D_matrix.cpp
7c4af2d1f617bfa0f15ed800596c4be892f02961
[]
no_license
jiahonglin/LCP
55cde187f98b8a013544f95aea6087df92516fc3
1805972511193dd91103ced834bdd35302481e98
refs/heads/master
2023-08-17T06:59:00.287333
2023-08-16T15:34:14
2023-08-16T15:34:14
189,690,649
2
0
null
null
null
null
UTF-8
C++
false
false
1,468
cpp
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); int n = matrix[0].size(); bool bFind = false; if(m == 1){ for(int j=0;j<n;j++){ if(matrix[0][j] == target){ bFind=true; break; } } return bFind; } if(n == 1){ for(int i=0;i<m;i++){ if(matrix[i][0] == target){ bFind=true; break; } } return bFind; } for(int i=0;i<m;i++){ if(matrix[i][0] <= target && target <= matrix[i][n-1]){ for(int j=0;j<n;j++){ if(matrix[i][j] == target){ bFind=true; break; } } return bFind; } } return bFind; } /* bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); int n = matrix[0].size(); int i=0; for(;i<m;i++){ if(matrix[i][0] <= target && matrix[i][n-1] >= target) break; if(i == m-1) return false; } for(int j=0;j<n;j++){ if(matrix[i][j] == target) return true; } return false; } */ };
[ "jiahonglin17@gmail.com" ]
jiahonglin17@gmail.com
9f86d9166140fef0455357fd0d9e6b87fa56e3fa
6c57b1f26dabd8bb24a41471ced5e0d1ac30735b
/BB/include/BB/Serial/SerialMessage.h
3bcaedf8cff29c8c0a4520c42fcbfebaaeaa4140
[]
no_license
hadzim/bb
555bb50465fbd604c56c755cdee2cce796118322
a6f43a9780753242e5e9f2af804c5233af4a920e
refs/heads/master
2021-01-21T04:54:53.835407
2016-06-06T06:31:55
2016-06-06T06:31:55
17,916,029
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
h
/* * SerialMessage.h * * Created on: 18.5.2014 * Author: JV */ #ifndef SERIALMESSAGE_H_ #define SERIALMESSAGE_H_ #include <vector> #include <string> #include "BB/Sensor/SensorData.h" namespace BB { /* * byte sequence * 0 - start byte * 1 - NodeID * 2 - NodeStatus * 3 - NodeType * 4 - MessageLength * 5 - n Message */ class SerialMessage { public: typedef int NodeID; typedef unsigned char Length; enum NodeStatus { NodeOk = 'O', NodeError = 'E' }; enum NodeType { NodeTemperature = 'T', NodeMotion = 'M' }; enum DataType { DataDouble = 'D' }; NodeID nodeID; NodeStatus nodeStatus; NodeType nodeType; DataType dataType; Length length; std::string message; SerialMessage(std::vector <unsigned char> & bytes); virtual ~SerialMessage(); SensorData createSensorData(); private: }; } /* namespace BB */ std::ostream & operator<<(std::ostream & stream, const BB::SerialMessage::NodeType & s); std::ostream & operator<<(std::ostream & stream, const BB::SerialMessage::NodeStatus & s); std::ostream & operator<<(std::ostream & stream, const BB::SerialMessage & s); #endif /* SERIALMESSAGE_H_ */
[ "jan.vana@tbs-biometrics.com" ]
jan.vana@tbs-biometrics.com
d16d901662b1158fd7289b98503415a1efa58400
59819ec8eb426ec0cdf4d187c41961b9a35cfe09
/questions_on_functions/dec_to_binary.cpp
6c2c866ef10d08dee7ffd66701d848eba5913f1a
[]
no_license
deep1358/CPP-Programs
46d0a84e2d1790983641303921fec82733cffbd5
f5eb80f0fca195ef40300ea5c13adb896d6ee978
refs/heads/master
2023-08-18T11:08:17.678754
2021-08-26T12:26:26
2021-08-26T12:26:26
373,787,578
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <bits/stdc++.h> using namespace std; void dec_to_bin(int n) { int ans = 0; int c = 0; while (n > 0) { int temp = n % 2; ans += pow(10, c) * temp; c++; n /= 2; } cout << ans; } int main() { int n; cin >> n; dec_to_bin(n); return 0; }
[ "deepshah1358@gmail.com" ]
deepshah1358@gmail.com
f8c0f50ebc607cae607e6f1a3040fd48d3d59752
374444870cff54414655655ebfb994717e2907b2
/SemGapI/Week5/1SumOfDigits.cpp
fd030c1a51f3a0582bce931a14092395d7a69fad
[ "BSD-3-Clause" ]
permissive
AnkitApurv/MCA
7d7d35a0c45bfa1337de4f3e55f5bf810fb62c06
e6240fc326a282369e0ca173da28944cf516fbbe
refs/heads/master
2023-03-22T05:56:09.187082
2020-03-23T18:35:32
2020-03-23T18:35:32
166,032,236
1
0
BSD-3-Clause
2021-03-20T03:19:42
2019-01-16T11:54:18
ASP
UTF-8
C++
false
false
807
cpp
/* @name 1SumOfDigits.cpp @desc to find the sum of the digits of a number using recursion. @author Ankit Apurv 180970042 @date 04/01/2019 */ #include <iostream> using namespace std; /* @desc computes sum of digits recursively @args num : integer, number whose digits are to be added sum : integer, variable to store and return the result @return integer, sum of digits of the given number */ int rSum(int num, int sum) { if(num > 0) { if(num >= 10) { int i = num % 10; num -= i; num /= 10; sum += i; } else { sum += num; num = 0; } return rSum(num, sum); } else { return sum; } } /* @desc main @args void @return exit code */ int main(void) { int n, s = 0; cout << "Number : "; cin >> n; cout << "\nSum : " << rSum(n, s) << "\n"; return 0; }
[ "k.ankit.capricon@gmail.com" ]
k.ankit.capricon@gmail.com
6f024c9ba4a90cc8ccdbaa344501abb857db7eeb
5626349a40a2a0a73cee8d88264ad791fc25791a
/src/aft/aftma/aftma_blockallocator.h
fcbca3b00c68a51f56cce34f7fde6314ca7075ce
[]
no_license
lyell/aegis
ae8600c2b334ad1db3c4005a74a43b4099966701
61952676c1d6eb0823e5ff8a7097cc29bb6308f7
refs/heads/master
2020-12-24T08:55:11.755560
2018-01-06T13:09:01
2018-01-06T13:09:01
26,701,231
1
0
null
null
null
null
UTF-8
C++
false
false
650
h
#ifndef INCLUDED_AEGIS_AFTMA_BLOCKALLOCATOR_H #define INCLUDED_AEGIS_AFTMA_BLOCKALLOCATOR_H #include <aftma_allocator.h> #include <map> namespace aftma { class BlockAllocator : public aftma::Allocator { public: BlockAllocator(); virtual ~BlockAllocator(); virtual void* allocate(size_t size); virtual void deallocate(void* ptr); private: struct Pool { void* startPool; void* endPool; size_t size; uint32_t* freeListBitmap; size_t bitmapLength; }; typedef std::map<size_t, Pool*> PoolMap; PoolMap m_poolMap; }; } // namespace #endif // INCLUDED
[ "lyell@sophicstudios.com" ]
lyell@sophicstudios.com
16fd3dca7b1347f279d052bbd52cc9c5165c1c83
3a25498190f3d30b67220df5ae52988802d70070
/engine/core/RMObject.hpp
14c4982c006fdf840817253967534025d0b0cb2a
[ "MIT" ]
permissive
vitali-kurlovich/RMPropeller
c80108ddeab9e8df74da87a33fbafc65490b266c
6b914957000dc5bd35319828b7e2608ceb2c92ca
refs/heads/master
2020-04-03T22:43:01.203168
2017-03-13T22:20:52
2017-03-13T22:20:52
56,176,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,188
hpp
// // Created by Vitali Kurlovich on 8/24/16. // #ifndef RMPROPELLER_RMOBJECT_HPP #define RMPROPELLER_RMOBJECT_HPP #include "../common/RMType.hpp" namespace rmengine { class RMObject { private: int32 _refCount{1}; //uint32 _uid{0}; public: inline friend void rmRetain(RMObject** object) noexcept { (*object)->_refCount++; } inline friend void rmRetain(RMObject* object) noexcept { object->_refCount++; } inline friend void rmRelease(RMObject** object) { if ((*object)->_refCount != 1) { (*object)->_refCount--; } else { delete (*object); (*object) = nullptr; } } inline friend void rmRelease(RMObject* object) { if ((object)->_refCount != 1) { (object)->_refCount--; } else { delete (object); } } constexpr friend uint32 rmRetainCount(const RMObject* object) noexcept { return object->_refCount; } }; } #endif //RMPROPELLER_RMOBJECT_HPP
[ "vitalikurlovich@gmail.com" ]
vitalikurlovich@gmail.com
2f9185fb2113e3cb2cc1f8807c3431ba78cdc16b
79c9ab2cf119c106c3c42353e766750bbcf497fa
/hdu/4734.cpp
8730185795f41d64d3c5922d5607ea371078d687
[]
no_license
cen5bin/Algorithm-Problem
12e17dd300f69fd8121ea3f5be2f1d1a61cb3485
00099428c1b4199f3a6dc286c43e91acf94c58b0
refs/heads/master
2021-01-17T13:35:00.819979
2016-11-30T03:05:49
2016-11-30T03:05:49
22,202,801
1
1
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
#include <cstdio> #include <cstring> int dp[12][5000]; int digit[12]; int A, B; void init() { memset(dp, -1, sizeof(dp)); } int dfs(int pos, int pre, bool limit) { if (pos == -1) return pre >= 0 ? 1 : 0; if (pre < 0) return 0; if (!limit && dp[pos][pre] != -1) return dp[pos][pre]; int end = limit ? digit[pos] : 9; int ret = 0; for (int i = 0; i <= end; ++i) ret += dfs(pos-1, pre - (1<<pos) * i, limit && i == end); if (!limit) dp[pos][pre] = ret; return ret; } int solve(int n) { int fa = 0; int tmp = 1; while (A) { fa += A % 10 * tmp; A /= 10; tmp <<= 1; } A = fa; //printf("%d\n", A); memset(digit, 0, sizeof(digit)); int len = 0; while (n) { digit[len++] = n % 10; n /= 10; } return dfs(len-1, A, 1); } int main() { init(); int T; scanf("%d", &T); while (T--) { scanf("%d%d", &A, &B); static int cas = 1; printf("Case #%d: %d\n", cas++, solve(B)); } return 0; }
[ "cen5bin@163.com" ]
cen5bin@163.com
6e2e761ddfaa55fc2965adae2eed28dc41d70279
900e651d100f8130d93cf7378feba2df3447f8b9
/C++Version/Dog.h
a60a563a7f2b49d7ec37da701c889297313d3d98
[]
no_license
xy008areshsu/Design-Pattern-Project
85d1abba1994f1cbe5e82358bb071129dabb2dac
63f24fd38268190fcb8abd2300db4f89aa2b6efa
refs/heads/master
2020-04-14T22:27:14.217343
2015-04-05T04:21:45
2015-04-05T04:21:45
29,419,467
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
#ifndef DOG_H #define DOG_H #include "Animal.h" #include <string> #include <iostream> class Dog : public Animal { public: Dog(const std::string name, double height, int weight, const std::string& dog_stuff): Animal{name, height, weight}, _dog_stuff {dog_stuff} {} // Dog(const Dog& rhs): // Animal {rhs.get_name(), rhs.get_height(), rhs.get_weight()}, _dog_stuff {rhs.get_stuff()} // {} void dig_hole() const{ std::cout << "Dug a hole" << std::endl; } void set_stuff(const std::string& dog_stuff) { _dog_stuff = dog_stuff; } std::string get_stuff() const {return _dog_stuff;} private: std::string _dog_stuff; }; #endif
[ "xy008areshsu@gmail" ]
xy008areshsu@gmail
90e1470327c9dc3ac6a9c63201c27dec02315802
c62e654417f64705fc54aca4759b54c73ac756f1
/sources/codeforces/practice/579/A.cpp
f8e19f08aee3b51e3eef87ad1fecdd9d23eebeb7
[]
no_license
miguelmartin75/cp-problems
9c56b14e61808650c5ad103ec1024223cfbfc26b
fbafdf7c4e70c18f003e54d4f657980e6e2948e3
refs/heads/master
2021-08-17T21:46:31.237678
2021-04-03T17:59:08
2021-04-03T17:59:08
80,083,158
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
#include <iostream> using namespace std; int main() { int x; cin >> x; int result = 0; while(x > 0) { if(x & 1) { ++result; } x >>= 1; } cout << result << endl; }
[ "miguel@miguel-martin.com" ]
miguel@miguel-martin.com
d630af31d6c2b8819e010eb4bb880813c3be631e
33f0b5041dd2dd40200d03ecbca65131a13cf15b
/mnum_bissection/mnum_bissection/mnum_bissection.cpp
904067feb4feaba5cf57598582b0d16020b032de
[]
no_license
ricardoleitee/MNUM
a51a34edf2ef88e7b13b626801917b4e03f22fe7
f55da6abfa53ab424f2ae5322fca886076ee3051
refs/heads/master
2021-01-23T07:20:34.020532
2014-11-16T19:57:38
2014-11-16T19:57:38
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,937
cpp
#include <iostream> #include <iomanip> #include <time.h> #include <cmath> using namespace std; //Problema da pag. 128, falling parachutist problem //Resolvido via método da bissecção float fx(float x){ //return 667.38/x * (1-exp(-0.146843*x))-40; return x*x*x*x + 2*x*x*x - x - 1; } float xu(float xl){ do { float fxl = fx(xl); float fxu = fx(xl+1); if (fxl*fxu<0) return xl; else xl++; } while (true); } float bissection(float xl, float xu){ return (xl+xu)/2; } /*A função stop contém o critério de paragem definido no livro, utilizando a função |Ea| = | (xroot(new) - xroot(old)) / xroot(new) | * 100% no entanto, nas aulas foi utilizado o método dif(x) = | f(xroot(old)) - f(xroot(new)) | < 1e-7 cujo resultado da aproximação não é tão próximo do valor real da raiz como o da primeira função, podendo até ser definido um erro aproximado (Ea) de 0, obtendo uma aproximação correcta da raiz a n casas decimais */ float stop(float xrn, float xro){ return abs((xrn-xro)/xrn)*100; } int main(){ float xl=0,xup=0,xr=0,xro=0; xl = 0; xup = 1; cout << "xl = " << xl << endl; unsigned int i=0; do { cout << "Iteration: " << i << endl; i++; xr = bissection(xl,xup); cout << "|Ea| = " << setprecision(4) << fixed << stop(xr,xro) << endl; float et = abs(((0.86674-xr)/0.86674)*100); cout << "Et = " << setprecision(4) << fixed << et << endl; if (stop(xr,xro)==0) break; xro = xr; cout << "xl = " << setprecision(4) << fixed << xl << endl; cout << "xu = " << setprecision(4) << fixed << xup << endl; cout << "xr = " << setprecision(4) << fixed << xr << endl; cout << "----- End Iteration -----" << endl; if (fx(xl)*fx(xr)<0) xup = xr; if (fx(xl)*fx(xr)>0) xl = xr; } while (/*abs(fx(xl)-fx(xr))<1e-7*/ true); cout << "Root: " << setprecision(4) << fixed << xr <<endl; int t = clock(); cout << "Time Elapsed: " << t; cin.get(); cin.ignore(); return 0; }
[ "ricardo.leitee12@gmail.com" ]
ricardo.leitee12@gmail.com
2aa695d0d8af69e8c7c2d4affa8b6e4d756c7cac
7cd1e7ea85736a930416909e6b9e82a7d5f3c346
/New Project-20161129/Newfile.cpp
0f7ad56d9861b11099a859de20e0395bf20689a3
[]
no_license
vkharlamov/codingground
6be34cf70633381880f4469d34743022e9babd9f
3bf0fc2f536e63d4af64818a3d9a9d1e053c8bab
refs/heads/master
2020-06-16T16:14:46.922486
2016-11-29T13:41:37
2016-11-29T13:41:37
75,085,082
0
0
null
null
null
null
UTF-8
C++
false
false
4,507
cpp
/* 24.12.2008 last modification: 26.06.2013 Copyright (c) 2008-2013 by Siegfried Koepf This file is distributed under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. For information on usage and redistribution and for a disclaimer of all warranties, see the file COPYING in this distribution. testing gen_comb_norep_lex_init() and gen_comb_norep_lex_next() compile gcc -o comb_norep_lex_example comb_norep_lex_example.c comb_norep_lex.c */ #include "string.h" #include "stdio.h" #include <algorithm> #include <vector> #include <stack> #include <stdlib.h> using namespace std; //include "_generate.h" /* Combinatorial generation functions public interfaces */ #ifndef _GENERATE_H #define _GENERATE_H //return values of generation functions #define GEN_NEXT 0 //ok, print and continue #define GEN_TERM 1 //ok, terminate #define GEN_EMPTY 2 //ok, print EMPTY SET and continue #define GEN_ERROR 3 //an error occured, print an error message and terminate //combinatorial generation functions int gen_comb_norep_init(unsigned char *vector, const unsigned char n, const unsigned char k); int gen_comb_norep_next(unsigned char *vector, const unsigned char n, const unsigned char k); int gen_comb_rep_init(unsigned char *vector, const unsigned char n, const unsigned char k); int gen_comb_rep_next(unsigned char *vector, const unsigned char n, const unsigned char k); int gen_perm_rep_init(const unsigned char n); int gen_perm_rep_next(unsigned char *vector, const unsigned char n); int gen_vari_rep_init(unsigned char *vector, const unsigned char m, const unsigned char n); int gen_vari_rep_next(unsigned char *vector, const unsigned char m, const unsigned char n); int gen_neck_init(unsigned char *vector, const unsigned char m, const unsigned char n); int gen_neck_next(unsigned char *vector, const unsigned char m, const unsigned char n); int gen_part_init(unsigned char *vector, const unsigned char n, unsigned char *k); int gen_part_next(unsigned char *vector, unsigned char *k); int gen_k_part_init(unsigned char *vector, const unsigned char n, const unsigned char k); int gen_k_part_next(unsigned char *vector, const unsigned char k); int gen_k_comp_init(unsigned char *vector, const unsigned char n, const unsigned char k); int gen_k_comp_next(unsigned char *vector, const unsigned char k); #endif int gen_comb_norep_lex_init(unsigned char *vector, const unsigned char n, const unsigned char k) { int j; //index //test for special cases if(k > n) return(GEN_ERROR); if(k == 0) return(GEN_EMPTY); //initialize: vector[0, ..., k - 1] are 0, ..., k - 1 for(j = 0; j < k; j++) vector[j] = j; return(GEN_NEXT); } int gen_comb_norep_lex_next(unsigned char *vector, const unsigned char n, const unsigned char k) { int j; //index //easy case, increase rightmost element if(vector[k - 1] < n - 1) { vector[k - 1]++; return(GEN_NEXT); } //find rightmost element to increase for(j = k - 2; j >= 0; j--) if(vector[j] < n - k + j) break; //terminate if vector[0] == n - k if(j < 0) return(GEN_TERM); //increase vector[j]++; //set right-hand elements while(j < k - 1) { vector[j + 1] = vector[j] + 1; j++; } return(GEN_NEXT); } int main(void) { unsigned char n = 5; //length of alphabet unsigned char k = 3; //length of figures unsigned char *vector = NULL; //where the current figure is stored int gen_result; //return value of generation functions unsigned int set_counter; //counting generated sequences int x; //iterator //alloc memory for vector vector = (unsigned char *)malloc(sizeof(unsigned char) * k); if(vector == NULL) { fprintf(stderr, "error: insufficient memory\n"); exit(EXIT_FAILURE); } set_counter = 0; printf("comb_norep_lex(%u, %u)\n", n, k); //initialize gen_result = gen_comb_norep_lex_init(vector, n, k); if(gen_result == GEN_ERROR) { fprintf(stderr, "error: couldn't initialize\n"); return(EXIT_FAILURE); } if(gen_result == GEN_EMPTY) { set_counter++; printf("{} (%u)\n", set_counter); } //generate all successors while(gen_result == GEN_NEXT) { set_counter++; for(x = 0; x < k; x++) printf("%u ", vector[x]); printf("(%u)\n", set_counter); gen_result = gen_comb_norep_lex_next(vector, n, k); } return(EXIT_SUCCESS); }
[ "vladimir.sevastopol@gmail.com" ]
vladimir.sevastopol@gmail.com
5610347a6ee2c70fe86c230d65cb8408f66d69eb
fea08e89058a927d341447a28bf716ef05db4038
/libraries/FastShiftOut/FastShiftOut.h
5fbc70e5f9250fc00678bd093a6a9ff3e9e7da55
[ "MIT" ]
permissive
hendog993/Arduino
774e48deab0fb3e417613a2d3b9953043c68a8e3
0ebb451644154fbe63b42c32f933a9ba2a476283
refs/heads/master
2022-11-11T02:49:39.998758
2022-11-07T14:28:23
2022-11-07T14:28:23
169,162,653
0
0
MIT
2019-02-04T22:54:56
2019-02-04T22:54:56
null
UTF-8
C++
false
false
1,062
h
#pragma once // // FILE: FastShiftOut.h // AUTHOR: Rob Tillaart // VERSION: 0.3.0 // PURPOSE: shiftOut class that implements the Print interface // DATE: 2013-08-22 // URL: https://github.com/RobTillaart/FastShiftOut #include "Arduino.h" #include "Print.h" #define FASTSHIFTOUT_LIB_VERSION (F("0.3.0")) class FastShiftOut : public Print { public: // bitOrder = { LSBFIRST, MSBFIRST }; FastShiftOut(uint8_t dataOut, uint8_t clockPin, uint8_t bitOrder = LSBFIRST); size_t write(uint8_t data); uint8_t lastWritten(void); bool setBitOrder(uint8_t bitOrder); uint8_t getBitOrder(void); // overrule bitOrder (most optimized). size_t writeLSBFIRST(uint8_t data); size_t writeMSBFIRST(uint8_t data); private: uint8_t _bitOrder; int _value; #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_MEGAAVR) volatile uint8_t *_dataOutRegister; uint8_t _dataOutBit; volatile uint8_t *_clockRegister; uint8_t _clockBit; #else uint8_t _dataPinOut; uint8_t _clockPin; #endif }; // -- END OF FILE --
[ "rob.tillaart@gmail.com" ]
rob.tillaart@gmail.com
50dc01c100021b654cf3506164a280f801190fbe
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/third_party/WebKit/Source/core/dom/DOMMatrixReadOnly.cpp
a3cc1da8182c721b93b902f67c7778c802ccabcd
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
11,607
cpp
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/dom/DOMMatrixReadOnly.h" #include "bindings/core/v8/V8ObjectBuilder.h" #include "core/dom/DOMMatrix.h" #include "core/dom/DOMMatrixInit.h" #include "core/dom/DOMPoint.h" #include "core/dom/DOMPointInit.h" namespace blink { namespace { void setDictionaryMembers(DOMMatrixInit& other) { if (!other.hasM11()) other.setM11(other.hasA() ? other.a() : 1); if (!other.hasM12()) other.setM12(other.hasB() ? other.b() : 0); if (!other.hasM21()) other.setM21(other.hasC() ? other.c() : 0); if (!other.hasM22()) other.setM22(other.hasD() ? other.d() : 1); if (!other.hasM41()) other.setM41(other.hasE() ? other.e() : 0); if (!other.hasM42()) other.setM42(other.hasF() ? other.f() : 0); } String getErrorMessage(const char* a, const char* b) { return String::format("The '%s' property should equal the '%s' property.", a, b); } } // namespace bool DOMMatrixReadOnly::validateAndFixup(DOMMatrixInit& other, ExceptionState& exceptionState) { if (other.hasA() && other.hasM11() && other.a() != other.m11()) { exceptionState.throwTypeError(getErrorMessage("a", "m11")); return false; } if (other.hasB() && other.hasM12() && other.b() != other.m12()) { exceptionState.throwTypeError(getErrorMessage("b", "m12")); return false; } if (other.hasC() && other.hasM21() && other.c() != other.m21()) { exceptionState.throwTypeError(getErrorMessage("c", "m21")); return false; } if (other.hasD() && other.hasM22() && other.d() != other.m22()) { exceptionState.throwTypeError(getErrorMessage("d", "m22")); return false; } if (other.hasE() && other.hasM41() && other.e() != other.m41()) { exceptionState.throwTypeError(getErrorMessage("e", "m41")); return false; } if (other.hasF() && other.hasM42() && other.f() != other.m42()) { exceptionState.throwTypeError(getErrorMessage("f", "m42")); return false; } if (other.hasIs2D() && other.is2D() && (other.m31() || other.m32() || other.m13() || other.m23() || other.m43() || other.m14() || other.m24() || other.m34() || other.m33() != 1 || other.m44() != 1)) { exceptionState.throwTypeError( "The is2D member is set to true but the input matrix is 3d matrix."); return false; } setDictionaryMembers(other); if (!other.hasIs2D()) { bool is2D = !(other.m31() || other.m32() || other.m13() || other.m23() || other.m43() || other.m14() || other.m24() || other.m34() || other.m33() != 1 || other.m44() != 1); other.setIs2D(is2D); } return true; } DOMMatrixReadOnly* DOMMatrixReadOnly::create(ExceptionState& exceptionState) { return new DOMMatrixReadOnly(TransformationMatrix()); } DOMMatrixReadOnly* DOMMatrixReadOnly::create(Vector<double> sequence, ExceptionState& exceptionState) { if (sequence.size() != 6 && sequence.size() != 16) { exceptionState.throwTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements " "for a 3D matrix."); return nullptr; } return new DOMMatrixReadOnly(sequence, sequence.size()); } DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat32Array( DOMFloat32Array* float32Array, ExceptionState& exceptionState) { if (float32Array->length() != 6 && float32Array->length() != 16) { exceptionState.throwTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements a " "for 3D matrix."); return nullptr; } return new DOMMatrixReadOnly(float32Array->data(), float32Array->length()); } DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat64Array( DOMFloat64Array* float64Array, ExceptionState& exceptionState) { if (float64Array->length() != 6 && float64Array->length() != 16) { exceptionState.throwTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements " "for a 3D matrix."); return nullptr; } return new DOMMatrixReadOnly(float64Array->data(), float64Array->length()); } DOMMatrixReadOnly* DOMMatrixReadOnly::fromMatrix( DOMMatrixInit& other, ExceptionState& exceptionState) { if (!validateAndFixup(other, exceptionState)) { DCHECK(exceptionState.hadException()); return nullptr; } if (other.is2D()) { double args[] = {other.m11(), other.m12(), other.m21(), other.m22(), other.m41(), other.m42()}; return new DOMMatrixReadOnly(args, 6); } double args[] = {other.m11(), other.m12(), other.m13(), other.m14(), other.m21(), other.m22(), other.m23(), other.m24(), other.m31(), other.m32(), other.m33(), other.m34(), other.m41(), other.m42(), other.m43(), other.m44()}; return new DOMMatrixReadOnly(args, 16); } DOMMatrixReadOnly::~DOMMatrixReadOnly() {} bool DOMMatrixReadOnly::is2D() const { return m_is2D; } bool DOMMatrixReadOnly::isIdentity() const { return m_matrix->isIdentity(); } DOMMatrix* DOMMatrixReadOnly::multiply(DOMMatrixInit& other, ExceptionState& exceptionState) { return DOMMatrix::create(this)->multiplySelf(other, exceptionState); } DOMMatrix* DOMMatrixReadOnly::translate(double tx, double ty, double tz) { return DOMMatrix::create(this)->translateSelf(tx, ty, tz); } DOMMatrix* DOMMatrixReadOnly::scale(double sx) { return scale(sx, sx); } DOMMatrix* DOMMatrixReadOnly::scale(double sx, double sy, double sz, double ox, double oy, double oz) { return DOMMatrix::create(this)->scaleSelf(sx, sy, sz, ox, oy, oz); } DOMMatrix* DOMMatrixReadOnly::scale3d(double scale, double ox, double oy, double oz) { return DOMMatrix::create(this)->scale3dSelf(scale, ox, oy, oz); } DOMMatrix* DOMMatrixReadOnly::rotate(double rotX) { return DOMMatrix::create(this)->rotateSelf(rotX); } DOMMatrix* DOMMatrixReadOnly::rotate(double rotX, double rotY) { return DOMMatrix::create(this)->rotateSelf(rotX, rotY); } DOMMatrix* DOMMatrixReadOnly::rotate(double rotX, double rotY, double rotZ) { return DOMMatrix::create(this)->rotateSelf(rotX, rotY, rotZ); } DOMMatrix* DOMMatrixReadOnly::rotateFromVector(double x, double y) { return DOMMatrix::create(this)->rotateFromVectorSelf(x, y); } DOMMatrix* DOMMatrixReadOnly::rotateAxisAngle(double x, double y, double z, double angle) { return DOMMatrix::create(this)->rotateAxisAngleSelf(x, y, z, angle); } DOMMatrix* DOMMatrixReadOnly::skewX(double sx) { return DOMMatrix::create(this)->skewXSelf(sx); } DOMMatrix* DOMMatrixReadOnly::skewY(double sy) { return DOMMatrix::create(this)->skewYSelf(sy); } DOMMatrix* DOMMatrixReadOnly::flipX() { DOMMatrix* flipX = DOMMatrix::create(this); flipX->setM11(-this->m11()); flipX->setM12(-this->m12()); flipX->setM13(-this->m13()); flipX->setM14(-this->m14()); return flipX; } DOMMatrix* DOMMatrixReadOnly::flipY() { DOMMatrix* flipY = DOMMatrix::create(this); flipY->setM21(-this->m21()); flipY->setM22(-this->m22()); flipY->setM23(-this->m23()); flipY->setM24(-this->m24()); return flipY; } DOMMatrix* DOMMatrixReadOnly::inverse() { return DOMMatrix::create(this)->invertSelf(); } DOMPoint* DOMMatrixReadOnly::transformPoint(const DOMPointInit& point) { if (is2D() && point.z() == 0 && point.w() == 1) { double x = point.x() * m11() + point.y() * m12() + m41(); double y = point.x() * m12() + point.y() * m22() + m42(); return DOMPoint::create(x, y, 0, 1); } double x = point.x() * m11() + point.y() * m21() + point.z() * m31() + point.w() * m41(); double y = point.x() * m12() + point.y() * m22() + point.z() * m32() + point.w() * m42(); double z = point.x() * m13() + point.y() * m23() + point.z() * m33() + point.w() * m43(); double w = point.x() * m14() + point.y() * m24() + point.z() * m34() + point.w() * m44(); return DOMPoint::create(x, y, z, w); } DOMMatrixReadOnly::DOMMatrixReadOnly(const TransformationMatrix& matrix, bool is2D) { m_matrix = TransformationMatrix::create(matrix); m_is2D = is2D; } DOMFloat32Array* DOMMatrixReadOnly::toFloat32Array() const { float array[] = { static_cast<float>(m_matrix->m11()), static_cast<float>(m_matrix->m12()), static_cast<float>(m_matrix->m13()), static_cast<float>(m_matrix->m14()), static_cast<float>(m_matrix->m21()), static_cast<float>(m_matrix->m22()), static_cast<float>(m_matrix->m23()), static_cast<float>(m_matrix->m24()), static_cast<float>(m_matrix->m31()), static_cast<float>(m_matrix->m32()), static_cast<float>(m_matrix->m33()), static_cast<float>(m_matrix->m34()), static_cast<float>(m_matrix->m41()), static_cast<float>(m_matrix->m42()), static_cast<float>(m_matrix->m43()), static_cast<float>(m_matrix->m44())}; return DOMFloat32Array::create(array, 16); } DOMFloat64Array* DOMMatrixReadOnly::toFloat64Array() const { double array[] = { m_matrix->m11(), m_matrix->m12(), m_matrix->m13(), m_matrix->m14(), m_matrix->m21(), m_matrix->m22(), m_matrix->m23(), m_matrix->m24(), m_matrix->m31(), m_matrix->m32(), m_matrix->m33(), m_matrix->m34(), m_matrix->m41(), m_matrix->m42(), m_matrix->m43(), m_matrix->m44()}; return DOMFloat64Array::create(array, 16); } const String DOMMatrixReadOnly::toString() const { std::stringstream stream; if (is2D()) { stream << "matrix(" << a() << ", " << b() << ", " << c() << ", " << d() << ", " << e() << ", " << f(); } else { stream << "matrix3d(" << m11() << ", " << m12() << ", " << m13() << ", " << m14() << ", " << m21() << ", " << m22() << ", " << m23() << ", " << m24() << ", " << m31() << ", " << m32() << ", " << m33() << ", " << m34() << ", " << m41() << ", " << m42() << ", " << m43() << ", " << m44(); } stream << ")"; return String(stream.str().c_str()); } ScriptValue DOMMatrixReadOnly::toJSONForBinding( ScriptState* scriptState) const { V8ObjectBuilder result(scriptState); result.addNumber("a", a()); result.addNumber("b", b()); result.addNumber("c", c()); result.addNumber("d", d()); result.addNumber("e", e()); result.addNumber("f", f()); result.addNumber("m11", m11()); result.addNumber("m12", m12()); result.addNumber("m13", m13()); result.addNumber("m14", m14()); result.addNumber("m21", m21()); result.addNumber("m22", m22()); result.addNumber("m23", m23()); result.addNumber("m24", m24()); result.addNumber("m31", m31()); result.addNumber("m32", m32()); result.addNumber("m33", m33()); result.addNumber("m34", m34()); result.addNumber("m41", m41()); result.addNumber("m42", m42()); result.addNumber("m43", m43()); result.addNumber("m44", m44()); result.addBoolean("is2D", is2D()); result.addBoolean("isIdentity", isIdentity()); return result.scriptValue(); } } // namespace blink
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
22931e0fc056883f0c7038dff3b528ed09f27abf
de6a5f131933fd8bcc49d02f351ddc0ffcf2c279
/StealthGameTest/Source/FPSGame/Public/FPSAIGuard.h
d215153d29fb6634ffa941427a9dfd0659aeadce
[]
no_license
GabrieleAncona/StealthGameTest
79402784e419957b7aa68e696656378453df621e
0b2bd1ddb4e82eb7b6d6f75f333455b518919b49
refs/heads/master
2023-08-28T06:21:02.990406
2021-10-21T01:05:02
2021-10-21T01:05:02
408,923,939
1
0
null
null
null
null
UTF-8
C++
false
false
1,837
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "FPSAIGuard.generated.h" class UPawnSensingComponent; UENUM(BlueprintType) enum class EAIState : uint8 { Idle, Suspicious, Alerted }; UCLASS() class FPSGAME_API AFPSAIGuard : public ACharacter { GENERATED_BODY() public: // Sets default values for this character's properties AFPSAIGuard(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; UPROPERTY(VisibleAnywhere, Category = "Components") UPawnSensingComponent* PawnSensingComp; UFUNCTION() void OnPawnSeen(APawn* SeenPawn); UFUNCTION() void OnNoiseHeard(APawn* NoiseInstigator, const FVector& Location, float Volume); FRotator OriginalRotation; UFUNCTION() void ResetOrientation(); FTimerHandle TimerHandle_ResetOrientation; UPROPERTY(ReplicatedUsing=OnRep_GuardState) EAIState GuardState; UFUNCTION() void OnRep_GuardState(); void SetGuardState(EAIState NewState); UFUNCTION(BlueprintImplementableEvent, Category = "AI") void OnStateChanged(EAIState NewState); public: // Called every frame virtual void Tick(float DeltaTime) override; protected: // CHALLENGE CODE /* Let the guard go on patrol */ UPROPERTY(EditInstanceOnly, Category = "AI") bool bPatrol; /* First of two patrol points to patrol between */ UPROPERTY(EditInstanceOnly, Category = "AI", meta = (EditCondition="bPatrol")) AActor* FirstPatrolPoint; /* Second of two patrol points to patrol between */ UPROPERTY(EditInstanceOnly, Category = "AI", meta = (EditCondition = "bPatrol")) AActor* SecondPatrolPoint; // The current point the actor is either moving to or standing at AActor* CurrentPatrolPoint; void MoveToNextPatrolPoint(); };
[ "gabry.ancona@gmail.com" ]
gabry.ancona@gmail.com
34c5cf2f39e610a6e1b4253910b816df0ff3609d
b970b54403e209e4bff058430c9ee9e8f5c0d8ba
/src/test/sighash_tests.cpp
48ed97368997b71d3c1ca69330d4743c7d161bbb
[ "MIT" ]
permissive
onexnet/onexcore
4f6324bb8e2e7422a3128282deba1a8bb02e1db8
86fbcd6d0e24832b175c7bba3134896843cd8d49
refs/heads/master
2021-09-05T01:55:13.385261
2018-01-23T16:11:35
2018-01-23T16:11:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,353
cpp
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "consensus/validation.h" #include "data/sighash.json.h" #include "hash.h" #include "main.h" // For CheckTransaction #include "random.h" #include "script/interpreter.h" #include "script/script.h" #include "serialize.h" #include "streams.h" #include "test/test_onex.h" #include "util.h" #include "utilstrencodings.h" #include "version.h" #include <iostream> #include <boost/test/unit_test.hpp> #include <univalue.h> extern UniValue read_json(const std::string& jsondata); // Old script.cpp SignatureHash function uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); if (nIn >= txTo.vin.size()) { printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn); return one; } CMutableTransaction txTmp(txTo); // In case concatenating two scripts ends up with two codeseparators, // or an extra one at the end, this prevents all those possible incompatibilities. scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR)); // Blank out other inputs' signatures for (unsigned int i = 0; i < txTmp.vin.size(); i++) txTmp.vin[i].scriptSig = CScript(); txTmp.vin[nIn].scriptSig = scriptCode; // Blank out some of the outputs if ((nHashType & 0x1f) == SIGHASH_NONE) { // Wildcard payee txTmp.vout.clear(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } else if ((nHashType & 0x1f) == SIGHASH_SINGLE) { // Only lock-in the txout payee at same index as txin unsigned int nOut = nIn; if (nOut >= txTmp.vout.size()) { printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut); return one; } txTmp.vout.resize(nOut+1); for (unsigned int i = 0; i < nOut; i++) txTmp.vout[i].SetNull(); // Let the others update at will for (unsigned int i = 0; i < txTmp.vin.size(); i++) if (i != nIn) txTmp.vin[i].nSequence = 0; } // Blank out other inputs completely, not recommended for open transactions if (nHashType & SIGHASH_ANYONECANPAY) { txTmp.vin[0] = txTmp.vin[nIn]; txTmp.vin.resize(1); } // Serialize and hash CHashWriter ss(SER_GETHASH, 0); ss << txTmp << nHashType; return ss.GetHash(); } void static RandomScript(CScript &script) { static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; script = CScript(); int ops = (insecure_rand() % 10); for (int i=0; i<ops; i++) script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))]; } void static RandomTransaction(CMutableTransaction &tx, bool fSingle) { tx.nVersion = insecure_rand(); tx.vin.clear(); tx.vout.clear(); tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0; int ins = (insecure_rand() % 4) + 1; int outs = fSingle ? ins : (insecure_rand() % 4) + 1; for (int in = 0; in < ins; in++) { tx.vin.push_back(CTxIn()); CTxIn &txin = tx.vin.back(); txin.prevout.hash = GetRandHash(); txin.prevout.n = insecure_rand() % 4; RandomScript(txin.scriptSig); txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1; } for (int out = 0; out < outs; out++) { tx.vout.push_back(CTxOut()); CTxOut &txout = tx.vout.back(); txout.nValue = insecure_rand() % 100000000; RandomScript(txout.scriptPubKey); } } BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(sighash_test) { seed_insecure_rand(false); #if defined(PRINT_SIGHASH_JSON) std::cout << "[\n"; std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n"; #endif int nRandomTests = 50000; #if defined(PRINT_SIGHASH_JSON) nRandomTests = 500; #endif for (int i=0; i<nRandomTests; i++) { int nHashType = insecure_rand(); CMutableTransaction txTo; RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE); CScript scriptCode; RandomScript(scriptCode); int nIn = insecure_rand() % txTo.vin.size(); uint256 sh, sho; sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType); sh = SignatureHash(scriptCode, txTo, nIn, nHashType); #if defined(PRINT_SIGHASH_JSON) CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << txTo; std::cout << "\t[\"" ; std::cout << HexStr(ss.begin(), ss.end()) << "\", \""; std::cout << HexStr(scriptCode) << "\", "; std::cout << nIn << ", "; std::cout << nHashType << ", \""; std::cout << sho.GetHex() << "\"]"; if (i+1 != nRandomTests) { std::cout << ","; } std::cout << "\n"; #endif BOOST_CHECK(sh == sho); } #if defined(PRINT_SIGHASH_JSON) std::cout << "]\n"; #endif } // Goal: check that SignatureHash generates correct hash BOOST_AUTO_TEST_CASE(sighash_from_data) { UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash))); for (unsigned int idx = 0; idx < tests.size(); idx++) { UniValue test = tests[idx]; std::string strTest = test.write(); if (test.size() < 1) // Allow for extra stuff (useful for comments) { BOOST_ERROR("Bad test: " << strTest); continue; } if (test.size() == 1) continue; // comment std::string raw_tx, raw_script, sigHashHex; int nIn, nHashType; uint256 sh; CTransaction tx; CScript scriptCode = CScript(); try { // deserialize test data raw_tx = test[0].get_str(); raw_script = test[1].get_str(); nIn = test[2].get_int(); nHashType = test[3].get_int(); sigHashHex = test[4].get_str(); uint256 sh; CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION); stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest); BOOST_CHECK(state.IsValid()); std::vector<unsigned char> raw = ParseHex(raw_script); scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); } catch (...) { BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest); continue; } sh = SignatureHash(scriptCode, tx, nIn, nHashType); BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); } } BOOST_AUTO_TEST_SUITE_END()
[ "reactnet@gmail.com" ]
reactnet@gmail.com
043331e5f5764b54fdd6f194cfab2e7687922686
21d6b37c5c55b5f8f712b8455224854bdeafd3b2
/twib/ResultError.hpp
9c767a59474d8c8d2c409822549601bdaa94f5af
[]
no_license
npdmfixup/twili
95418f93c49286750760ab7eccb00cba762eafde
8a3694116e269422e2534fd9683be7cb4bca155f
refs/heads/master
2020-03-30T05:20:43.886771
2018-09-24T01:05:21
2018-09-24T01:05:21
150,793,531
0
0
null
2018-09-28T20:54:02
2018-09-28T20:54:01
null
UTF-8
C++
false
false
335
hpp
#pragma once #include<stdexcept> #include<string> namespace twili { namespace twib { class ResultError : public std::runtime_error { public: ResultError(uint32_t result); virtual const char *what() const noexcept override; const uint32_t code; private: std::string description; }; } // namespace twib } // namespace twili
[ "xenotoad@xenotoad.net" ]
xenotoad@xenotoad.net
276d4cd38bcf9be231037cfdacf49b7e620eb531
e7a3f7458a31f28c578207fafd5f26b014809458
/src/detail/camera/gstcameraimpl.cpp
26f73bba9be1366d6159fc7309ff623b378d086b
[ "Apache-2.0" ]
permissive
joshua-henderson/egt
50ca128625935b3c99be5d32c6d0a32f9f1f60ac
1b7fbdc4f440fd31ea31c5e65ead7ab66f54a40d
refs/heads/master
2020-08-27T14:24:17.237133
2020-05-27T01:13:10
2020-05-27T01:13:37
217,404,295
0
0
Apache-2.0
2019-10-24T22:13:47
2019-10-24T22:13:46
null
UTF-8
C++
false
false
17,873
cpp
/* * Copyright (C) 2018 Microchip Technology Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "detail/camera/gstcameraimpl.h" #include "detail/video/gstmeta.h" #include "egt/app.h" #ifdef HAVE_LIBPLANES #include "egt/detail/screen/kmsoverlay.h" #include "egt/detail/screen/kmsscreen.h" #endif #include "egt/types.h" #include "egt/video.h" #include <exception> #include <gst/gst.h> #include <spdlog/fmt/ostr.h> #include <spdlog/spdlog.h> namespace egt { inline namespace v1 { namespace detail { CameraImpl::CameraImpl(CameraWindow& interface, const Rect& rect, // NOLINTNEXTLINE(modernize-pass-by-value) const std::string& device) : m_interface(interface), m_devnode(device), m_rect(rect) { GError* err = nullptr; if (!gst_init_check(nullptr, nullptr, &err)) { std::ostringstream ss; ss << "failed to initialize gstreamer: "; if (err && err->message) { ss << err->message; g_error_free(err); } else { ss << "unknown error"; } throw std::runtime_error(ss.str()); } /** * check for cache file by finding a playback plugin. * if gst_registry_find_plugin returns NULL, then no * cache file present and assume GSTREAMER1_PLUGIN_REGISTRY * is disabled in gstreamer package. */ if (!gst_registry_find_plugin(gst_registry_get(), "playback")) { SPDLOG_DEBUG("manually loading gstreamer plugins"); auto plugins = { "/usr/lib/gstreamer-1.0/libgstcoreelements.so", "/usr/lib/gstreamer-1.0/libgsttypefindfunctions.so", "/usr/lib/gstreamer-1.0/libgstplayback.so", "/usr/lib/gstreamer-1.0/libgstapp.so", "/usr/lib/gstreamer-1.0/libgstvideo4linux2.so", "/usr/lib/gstreamer-1.0/libgstvideoscale.so", "/usr/lib/gstreamer-1.0/libgstvideoconvert.so", "/usr/lib/gstreamer-1.0/libgstlibav.so", "/usr/lib/gstreamer-1.0/libgstvideoparsersbad.so", }; for (auto& plugin : plugins) { GError* error = nullptr; gst_plugin_load_file(plugin, &error); if (error) { if (error->message) spdlog::error("load plugin error: {}", error->message); g_error_free(error); } } } m_gmain_loop = g_main_loop_new(nullptr, FALSE); m_gmain_thread = std::thread(g_main_loop_run, m_gmain_loop); } gboolean CameraImpl::bus_callback(GstBus* bus, GstMessage* message, gpointer data) { ignoreparam(bus); auto impl = static_cast<CameraImpl*>(data); SPDLOG_TRACE("gst message: {}", GST_MESSAGE_TYPE_NAME(message)); switch (GST_MESSAGE_TYPE(message)) { case GST_MESSAGE_ERROR: { GstErrorHandle error; GstStringHandle debug; gst_message_parse(gst_message_parse_error, message, error, debug); if (error) { SPDLOG_DEBUG("gst error: {} {}", error->message, debug ? debug.get() : ""); if (Application::check_instance()) { asio::post(Application::instance().event().io(), [impl, error = std::move(error)]() { impl->m_interface.on_error.invoke(error->message); }); } } break; } case GST_MESSAGE_WARNING: { GstErrorHandle error; GstStringHandle debug; gst_message_parse(gst_message_parse_warning, message, error, debug); if (error) { SPDLOG_DEBUG("gst warning: {} {}", error->message, debug ? debug.get() : ""); } break; } case GST_MESSAGE_INFO: { GstErrorHandle error; GstStringHandle debug; gst_message_parse(gst_message_parse_info, message, error, debug); if (error) { SPDLOG_DEBUG("gst info: {} {}", error->message, debug ? debug.get() : ""); } break; } case GST_MESSAGE_DEVICE_ADDED: { GstDevice* device; gst_message_parse_device_added(message, &device); std::string devnode; GstStructure* props = gst_device_get_properties(device); if (props) { SPDLOG_DEBUG("device properties: {}", gst_structure_to_string(props)); devnode = gst_structure_get_string(props, "device.path"); gst_structure_free(props); } if (Application::check_instance()) { asio::post(Application::instance().event().io(), [impl, devnode]() { impl->m_interface.on_connect.invoke(devnode); }); } break; } case GST_MESSAGE_DEVICE_REMOVED: { GstDevice* device; gst_message_parse_device_removed(message, &device); std::string devnode; GstStructure* props = gst_device_get_properties(device); if (props) { SPDLOG_DEBUG("device properties: {}", gst_structure_to_string(props)); devnode = gst_structure_get_string(props, "device.path"); gst_structure_free(props); } asio::post(Application::instance().event().io(), [impl, devnode]() { /** * invoke disconnect only if current device is * disconnected. */ if (devnode == impl->m_devnode) impl->m_interface.on_disconnect.invoke(devnode); }); break; } default: break; } /* we want to be notified again if there is a message on the bus, so * returning true (false means we want to stop watching for messages * on the bus and our callback should not be called again) */ return true; } /* * Its a Basic window: copying buffer to cairo surface. */ void CameraImpl::draw(Painter& painter, const Rect& rect) { ignoreparam(rect); if (m_camerasample) { GstCaps* caps = gst_sample_get_caps(m_camerasample); GstStructure* capsStruct = gst_caps_get_structure(caps, 0); int width = 0; int height = 0; gst_structure_get_int(capsStruct, "width", &width); gst_structure_get_int(capsStruct, "height", &height); SPDLOG_TRACE("videowidth = {} videoheight = {}", width, height); gst_sample_ref(m_camerasample); GstBuffer* buffer = gst_sample_get_buffer(m_camerasample); GstMapInfo map; if (gst_buffer_map(buffer, &map, GST_MAP_READ)) { const auto box = m_interface.content_area(); const auto surface = unique_cairo_surface_t( cairo_image_surface_create_for_data(map.data, CAIRO_FORMAT_RGB16_565, width, height, cairo_format_stride_for_width(CAIRO_FORMAT_RGB16_565, width))); if (cairo_surface_status(surface.get()) == CAIRO_STATUS_SUCCESS) { auto cr = painter.context().get(); if (width != box.width() || height != box.height()) { double scalex = static_cast<double>(box.width()) / width; double scaley = static_cast<double>(box.height()) / height; cairo_scale(cr, scalex, scaley); } cairo_set_source_surface(cr, surface.get(), box.x(), box.y()); cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); cairo_paint(cr); } gst_buffer_unmap(buffer, &map); } gst_sample_unref(m_camerasample); } } GstFlowReturn CameraImpl::on_new_buffer(GstElement* elt, gpointer data) { auto impl = static_cast<CameraImpl*>(data); GstSample* sample; g_signal_emit_by_name(elt, "pull-sample", &sample); if (sample) { #ifdef HAVE_LIBPLANES // TODO: this is not thread safe accessing impl here if (impl->m_interface.plane_window()) { GstBuffer* buffer = gst_sample_get_buffer(sample); if (buffer) { GstMapInfo map; if (gst_buffer_map(buffer, &map, GST_MAP_READ)) { auto screen = reinterpret_cast<detail::KMSOverlay*>(impl->m_interface.screen()); assert(screen); if (screen) { memcpy(screen->raw(), map.data, map.size); screen->schedule_flip(); gst_buffer_unmap(buffer, &map); } } } gst_sample_unref(sample); } else #endif { if (Application::check_instance()) { asio::post(Application::instance().event().io(), [impl, sample]() { if (impl->m_camerasample) gst_sample_unref(impl->m_camerasample); impl->m_camerasample = sample; impl->m_interface.damage(); }); } } return GST_FLOW_OK; } return GST_FLOW_ERROR; } void CameraImpl::get_camera_device_caps() { std::tuple<std::string, std::string, std::string, std::vector<std::tuple<int, int>>> caps = detail::get_camera_device_caps(m_devnode, &bus_callback, this); m_devnode = std::get<0>(caps); m_caps_name = std::get<1>(caps); m_caps_format = std::get<2>(caps); m_resolutions = std::get<3>(caps); } bool CameraImpl::start() { std::string pipe; get_camera_device_caps(); auto box = m_interface.content_area(); SPDLOG_DEBUG("box = {}", box); /* * if user constructs a default constructor, then size of * the camerawindow is zero for BasicWindow and 32x32 for * plane window. due to which pipeline initialization fails * incase of BasicWindow. as a fix resize the camerawindow * to 32x32. */ if ((box.width() < 32) && (box.height() < 32)) { m_interface.resize(Size(32, 32)); m_rect.size(Size(32, 32)); box = m_interface.content_area(); } /* * Here we try to match camera resolution with camerawindow size * and add scaling to pipeline if size does not match. * note: adding scaling to may effects performance and this way * now users can set any size for camera window. */ auto w = box.width(); auto h = box.height(); if (!m_resolutions.empty()) { auto index = std::distance(m_resolutions.begin(), std::lower_bound(m_resolutions.begin(), m_resolutions.end(), std::make_tuple(box.width(), box.height()))); w = std::get<0>(m_resolutions.at(index)); h = std::get<1>(m_resolutions.at(index)); SPDLOG_DEBUG("closest match of camerawindow : {} is {} ", box.size(), Size(w, h)); } std::string vscale; if ((w != box.width()) || (h != box.height())) { vscale = fmt::format(" videoscale ! video/x-raw,width={},height={} !", box.width(), box.height()); SPDLOG_DEBUG("scaling video: {} to {} ", Size(w, h), box.size()); } const auto format = detail::gstreamer_format(m_interface.format()); SPDLOG_DEBUG("format: {} ", format); static constexpr auto appsink_pipe = "v4l2src device={} ! videoconvert ! video/x-raw,width={},height={},format={} ! {} " \ "appsink name=appsink async=false enable-last-sample=false sync=true"; pipe = fmt::format(appsink_pipe, m_devnode, w, h, format, vscale); SPDLOG_DEBUG(pipe); /* Make sure we don't leave orphan references */ stop(); GError* error = nullptr; m_pipeline = gst_parse_launch(pipe.c_str(), &error); if (!m_pipeline) { m_interface.on_error.invoke(fmt::format("failed to create pipeline: {}", error->message)); return false; } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) m_appsink = gst_bin_get_by_name(GST_BIN(m_pipeline), "appsink"); if (!m_appsink) { m_interface.on_error.invoke("failed to get app sink element"); return false; } // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) g_object_set(G_OBJECT(m_appsink), "emit-signals", TRUE, "sync", TRUE, nullptr); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) g_signal_connect(m_appsink, "new-sample", G_CALLBACK(on_new_buffer), this); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) GstBus* bus = gst_pipeline_get_bus(GST_PIPELINE(m_pipeline)); gst_bus_add_watch(bus, &bus_callback, this); gst_object_unref(bus); int ret = gst_element_set_state(m_pipeline, GST_STATE_PLAYING); if (ret == GST_STATE_CHANGE_FAILURE) { m_interface.on_error.invoke("failed to set pipeline to play state"); stop(); return false; } return true; } void CameraImpl::scale(float scalex, float scaley) { m_interface.resize(Size(m_rect.width() * scalex, m_rect.height() * scaley)); } void CameraImpl::stop() { if (m_pipeline) { GstStateChangeReturn ret = gst_element_set_state(m_pipeline, GST_STATE_NULL); if (GST_STATE_CHANGE_FAILURE == ret) { spdlog::error("set pipeline to NULL state failed"); } g_object_unref(m_pipeline); m_pipeline = nullptr; } } CameraImpl::~CameraImpl() { if (m_gmain_loop) { /* * check loop is running to avoid race condition when stop is called too early */ if (g_main_loop_is_running(m_gmain_loop)) { //stop loop and wait g_main_loop_quit(m_gmain_loop); } m_gmain_thread.join(); g_main_loop_unref(m_gmain_loop); } } std::tuple<std::string, std::string, std::string, std::vector<std::tuple<int, int>>> get_camera_device_caps(const std::string& dev_name, BusCallback bus_callback, void* instance) { std::string devnode; GstDeviceMonitor* monitor = gst_device_monitor_new(); GstBus* bus = gst_device_monitor_get_bus(monitor); gst_bus_add_watch(bus, bus_callback, instance); gst_object_unref(bus); GstCaps* caps = gst_caps_new_empty_simple("video/x-raw"); gst_device_monitor_add_filter(monitor, "Video/Source", caps); gst_caps_unref(caps); std::string caps_name; std::string caps_format; std::vector<std::tuple<int, int>> resolutions; if (gst_device_monitor_start(monitor)) { GList* devlist = gst_device_monitor_get_devices(monitor); for (GList* i = g_list_first(devlist); i; i = g_list_next(i)) { auto device = static_cast<GstDevice*>(i->data); if (device == nullptr) continue; // Probe all device properties and store them internally: GstStringHandle display_name{gst_device_get_display_name(device)}; SPDLOG_DEBUG("name : {}", display_name.get()); GstStringHandle dev_string{gst_device_get_device_class(device)}; SPDLOG_DEBUG("class : {}", dev_string.get()); GstCaps* caps = gst_device_get_caps(device); if (caps) { resolutions.clear(); int size = gst_caps_get_size(caps); SPDLOG_DEBUG("caps : "); for (int j = 0; j < size; ++j) { GstStructure* s = gst_caps_get_structure(caps, j); std::string name = std::string(gst_structure_get_name(s)); if (name == "video/x-raw") { int width = 0; int height = 0; caps_name = name; gst_structure_get_int(s, "width", &width); gst_structure_get_int(s, "height", &height); caps_format = std::string(gst_structure_get_string(s, "format")); resolutions.emplace_back(std::make_tuple(width, height)); SPDLOG_DEBUG("{}, format=(string){}, width=(int){}, " "height=(int){}", caps_name, caps_format, width, height); } } if (!resolutions.empty()) { // sort by camera width std::sort(resolutions.begin(), resolutions.end(), []( std::tuple<int, int>& t1, std::tuple<int, int>& t2) { return std::get<0>(t1) < std::get<0>(t2); }); } gst_caps_unref(caps); } GstStructure* props = gst_device_get_properties(device); if (props) { SPDLOG_DEBUG("device properties: {}", gst_structure_to_string(props)); devnode = std::string(gst_structure_get_string(props, "device.path")); gst_structure_free(props); if (devnode == dev_name) break; } } g_list_free(devlist); } SPDLOG_DEBUG("camera device node : {}", devnode); return std::make_tuple(devnode, caps_name, caps_format, resolutions); } } } }
[ "joshua.henderson@microchip.com" ]
joshua.henderson@microchip.com
e00f401b29f6ff458390090a86d9b53f192c9088
3762e1e9dcc74653eefc35010768a32fd2ab00d5
/execs/partition_pointcloud_levels/src/process/export_data.h
7347a642de08f69a9f9985ab5b92ebd3aed1cb96
[]
no_license
HollisJoe/geometry-1
6d5d8ba69b006b2d0bb5b9128b94fdcbd4af3b82
1e1f3c3b0aec35e80313d9d1124a77f1e439f53e
refs/heads/master
2021-06-14T16:38:37.744499
2017-02-02T14:20:26
2017-02-02T14:20:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,749
h
#ifndef EXPORT_DATA_H #define EXPORT_DATA_H /* export_data.h: * * This file contains functions * used to export the level partitioning * data, including partitioning the point * cloud and exporting the level values */ #include <vector> #include "../io/config.h" #include "../structs/point.h" #include "../structs/histogram.h" using namespace std; /* export_data: * * Will export the given data to the specified files, * which includes partitioning scans into xyz files * by floor, which requires the input scans files to * be read. * * arguments: * * floor_heights - The list of floors and their heights * ceil_heights - The list of ceilings and their heights, * must be the same length as floor_heights * floor_hist - The floors histogram * ceil_hist - The ceilings histogram * conf - The configuration file * * return value: * * Returns zero on success, non-zero on failure. */ int export_data(vector<double>& floor_heights, vector<double>& ceil_heights, histogram_t& floor_hist, histogram_t& ceil_hist, config_t& conf); /********************** Helper Functions ****************************/ /* export_matlab_script: * * Will attempt to export a matlab script that contains all * relevant information about the level partitioning computed. * * arguments: * * floor_heights - The list of floors and their heights * ceil_heights - The list of ceilings and their heights, * must be the same length as floor_heights * floor_hist - The floors histogram * ceil_hist - The ceilings histogram * conf - The configuration file * * return value: * * Returns zero on success, non-zero on failure. */ int export_matlab_script(vector<double>& floor_heights, vector<double>& ceil_heights, histogram_t& floor_hist, histogram_t& ceil_hist, config_t& conf); /* partition_scans: * * Will read in the scans, and rewrite the points to the specified * output locations, partitioning the points based on which level * they are in. * * arguments: * * floor_heights - The list of floors and their heights * ceil_heights - The list of ceilings and their heights, * must be the same length as floor_heights * conf - The configuration file * * return value: * * Returns zero on success, non-zero on failure. */ int partition_scans(vector<double>& floor_heights, vector<double>& ceil_heights, config_t& conf); /* level_of_point: * * Will specify the level index for the given point. * * arguments: * * p - The point to analyze * floor_heights, ceil_heights - The level heights to use * * return value: * * Returns the level of the point p. */ int level_of_point(point_t& p, vector<double>& floor_heights, vector<double>& ceil_heights); #endif
[ "elturner@eecs.berkeley.edu" ]
elturner@eecs.berkeley.edu
6d029f53d82e2a52ace2d7572d636300e13cd885
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/chrome/browser/chromeos/customization/customization_wallpaper_downloader_browsertest.cc
63becc1c65a0737c6394bf5fddea20790d12db9c
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
11,596
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <vector> #include "ash/common/wallpaper/wallpaper_controller.h" #include "ash/common/wm_shell.h" #include "base/command_line.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/time/time.h" #include "chrome/browser/chromeos/customization/customization_document.h" #include "chrome/browser/chromeos/customization/customization_wallpaper_downloader.h" #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager.h" #include "chrome/browser/chromeos/login/users/wallpaper/wallpaper_manager_test_utils.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chromeos/chromeos_switches.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_fetcher_impl.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace { const char kOEMWallpaperURL[] = "http://somedomain.com/image.png"; const char kServicesManifest[] = "{" " \"version\": \"1.0\"," " \"default_wallpaper\": \"http://somedomain.com/image.png\",\n" " \"default_apps\": [\n" " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n" " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" " ],\n" " \"localized_content\": {\n" " \"en-US\": {\n" " \"default_apps_folder_name\": \"EN-US OEM Name\"\n" " },\n" " \"en\": {\n" " \"default_apps_folder_name\": \"EN OEM Name\"\n" " },\n" " \"default\": {\n" " \"default_apps_folder_name\": \"Default OEM Name\"\n" " }\n" " }\n" "}"; // Expected minimal wallpaper download retry interval in milliseconds. const int kDownloadRetryIntervalMS = 100; class TestWallpaperObserver : public WallpaperManager::Observer { public: explicit TestWallpaperObserver(WallpaperManager* wallpaper_manager) : finished_(false), wallpaper_manager_(wallpaper_manager) { DCHECK(wallpaper_manager_); wallpaper_manager_->AddObserver(this); } ~TestWallpaperObserver() override { wallpaper_manager_->RemoveObserver(this); } void OnWallpaperAnimationFinished(const AccountId&) override { finished_ = true; base::MessageLoop::current()->QuitWhenIdle(); } void WaitForWallpaperAnimationFinished() { while (!finished_) base::RunLoop().Run(); } private: bool finished_; WallpaperManager* wallpaper_manager_; DISALLOW_COPY_AND_ASSIGN(TestWallpaperObserver); }; } // namespace // This is helper class for net::FakeURLFetcherFactory. class TestWallpaperImageURLFetcherCallback { public: TestWallpaperImageURLFetcherCallback( const GURL& url, const size_t require_retries, const std::vector<unsigned char>& jpeg_data_raw) : url_(url), require_retries_(require_retries), factory_(nullptr) { jpeg_data_.resize(jpeg_data_raw.size()); std::copy(jpeg_data_raw.begin(), jpeg_data_raw.end(), jpeg_data_.begin()); } std::unique_ptr<net::FakeURLFetcher> CreateURLFetcher( const GURL& url, net::URLFetcherDelegate* delegate, const std::string& response_data, net::HttpStatusCode response_code, net::URLRequestStatus::Status status) { chromeos::ServicesCustomizationDocument* customization = chromeos::ServicesCustomizationDocument::GetInstance(); customization->wallpaper_downloader_for_testing() ->set_retry_delay_for_testing( base::TimeDelta::FromMilliseconds(kDownloadRetryIntervalMS)); attempts_.push_back(base::TimeTicks::Now()); if (attempts_.size() > 1) { const int retry = num_attempts() - 1; const base::TimeDelta current_delay = customization->wallpaper_downloader_for_testing() ->retry_current_delay_for_testing(); const double base_interval = base::TimeDelta::FromMilliseconds( kDownloadRetryIntervalMS).InSecondsF(); EXPECT_GE(current_delay, base::TimeDelta::FromSecondsD(base_interval * retry * retry)) << "Retry too fast. Actual interval " << current_delay.InSecondsF() << " seconds, but expected at least " << base_interval << " * (retry=" << retry << " * retry)= " << base_interval * retry * retry << " seconds."; } if (attempts_.size() > require_retries_) { response_code = net::HTTP_OK; status = net::URLRequestStatus::SUCCESS; factory_->SetFakeResponse(url, response_data, response_code, status); } std::unique_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher( url, delegate, response_data, response_code, status)); scoped_refptr<net::HttpResponseHeaders> download_headers = new net::HttpResponseHeaders(std::string()); download_headers->AddHeader("Content-Type: image/jpeg"); fetcher->set_response_headers(download_headers); return fetcher; } void Initialize(net::FakeURLFetcherFactory* factory) { factory_ = factory; factory_->SetFakeResponse(url_, jpeg_data_, net::HTTP_INTERNAL_SERVER_ERROR, net::URLRequestStatus::FAILED); } size_t num_attempts() const { return attempts_.size(); } private: const GURL url_; // Respond with OK on required retry attempt. const size_t require_retries_; net::FakeURLFetcherFactory* factory_; std::vector<base::TimeTicks> attempts_; std::string jpeg_data_; DISALLOW_COPY_AND_ASSIGN(TestWallpaperImageURLFetcherCallback); }; // This implements fake remote source for wallpaper image. // JPEG image is created here and served to CustomizationWallpaperDownloader // via net::FakeURLFetcher. class WallpaperImageFetcherFactory { public: WallpaperImageFetcherFactory(const GURL& url, int width, int height, SkColor color, const size_t require_retries) { // ASSERT_TRUE() cannot be directly used in constructor. Initialize(url, width, height, color, require_retries); } ~WallpaperImageFetcherFactory() { fetcher_factory_.reset(); net::URLFetcherImpl::set_factory(fallback_fetcher_factory_.get()); fallback_fetcher_factory_.reset(); } size_t num_attempts() const { return url_callback_->num_attempts(); } private: void Initialize(const GURL& url, int width, int height, SkColor color, const size_t require_retries) { std::vector<unsigned char> oem_wallpaper_; ASSERT_TRUE(wallpaper_manager_test_utils::CreateJPEGImage( width, height, color, &oem_wallpaper_)); url_callback_.reset(new TestWallpaperImageURLFetcherCallback( url, require_retries, oem_wallpaper_)); fallback_fetcher_factory_.reset(new net::TestURLFetcherFactory); net::URLFetcherImpl::set_factory(nullptr); fetcher_factory_.reset(new net::FakeURLFetcherFactory( fallback_fetcher_factory_.get(), base::Bind(&TestWallpaperImageURLFetcherCallback::CreateURLFetcher, base::Unretained(url_callback_.get())))); url_callback_->Initialize(fetcher_factory_.get()); } std::unique_ptr<TestWallpaperImageURLFetcherCallback> url_callback_; // Use a test factory as a fallback so we don't have to deal with other // requests. std::unique_ptr<net::TestURLFetcherFactory> fallback_fetcher_factory_; std::unique_ptr<net::FakeURLFetcherFactory> fetcher_factory_; DISALLOW_COPY_AND_ASSIGN(WallpaperImageFetcherFactory); }; class CustomizationWallpaperDownloaderBrowserTest : public InProcessBrowserTest { public: CustomizationWallpaperDownloaderBrowserTest() {} ~CustomizationWallpaperDownloaderBrowserTest() override {} void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(chromeos::switches::kLoginManager); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user"); } protected: void CreateCmdlineWallpapers() { cmdline_wallpaper_dir_.reset(new base::ScopedTempDir); ASSERT_TRUE(cmdline_wallpaper_dir_->CreateUniqueTempDir()); wallpaper_manager_test_utils::CreateCmdlineWallpapers( *cmdline_wallpaper_dir_, &wallpaper_manager_command_line_); } std::unique_ptr<base::CommandLine> wallpaper_manager_command_line_; // Directory created by CreateCmdlineWallpapersAndSetFlags() to store default // wallpaper images. std::unique_ptr<base::ScopedTempDir> cmdline_wallpaper_dir_; private: DISALLOW_COPY_AND_ASSIGN(CustomizationWallpaperDownloaderBrowserTest); }; IN_PROC_BROWSER_TEST_F(CustomizationWallpaperDownloaderBrowserTest, OEMWallpaperIsPresent) { CreateCmdlineWallpapers(); WallpaperManager::Get()->SetDefaultWallpaperNow(EmptyAccountId()); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); EXPECT_TRUE(wallpaper_manager_test_utils::ImageIsNearColor( ash::WmShell::Get()->wallpaper_controller()->GetWallpaper(), wallpaper_manager_test_utils::kSmallDefaultWallpaperColor)); WallpaperImageFetcherFactory url_factory( GURL(kOEMWallpaperURL), wallpaper_manager_test_utils::kWallpaperSize, wallpaper_manager_test_utils::kWallpaperSize, wallpaper_manager_test_utils::kCustomWallpaperColor, 0 /* require_retries */); TestWallpaperObserver observer(WallpaperManager::Get()); chromeos::ServicesCustomizationDocument* customization = chromeos::ServicesCustomizationDocument::GetInstance(); EXPECT_TRUE( customization->LoadManifestFromString(std::string(kServicesManifest))); observer.WaitForWallpaperAnimationFinished(); EXPECT_TRUE(wallpaper_manager_test_utils::ImageIsNearColor( ash::WmShell::Get()->wallpaper_controller()->GetWallpaper(), wallpaper_manager_test_utils::kCustomWallpaperColor)); EXPECT_EQ(1U, url_factory.num_attempts()); } IN_PROC_BROWSER_TEST_F(CustomizationWallpaperDownloaderBrowserTest, OEMWallpaperRetryFetch) { CreateCmdlineWallpapers(); WallpaperManager::Get()->SetDefaultWallpaperNow(EmptyAccountId()); wallpaper_manager_test_utils::WaitAsyncWallpaperLoadFinished(); EXPECT_TRUE(wallpaper_manager_test_utils::ImageIsNearColor( ash::WmShell::Get()->wallpaper_controller()->GetWallpaper(), wallpaper_manager_test_utils::kSmallDefaultWallpaperColor)); WallpaperImageFetcherFactory url_factory( GURL(kOEMWallpaperURL), wallpaper_manager_test_utils::kWallpaperSize, wallpaper_manager_test_utils::kWallpaperSize, wallpaper_manager_test_utils::kCustomWallpaperColor, 1 /* require_retries */); TestWallpaperObserver observer(WallpaperManager::Get()); chromeos::ServicesCustomizationDocument* customization = chromeos::ServicesCustomizationDocument::GetInstance(); EXPECT_TRUE( customization->LoadManifestFromString(std::string(kServicesManifest))); observer.WaitForWallpaperAnimationFinished(); EXPECT_TRUE(wallpaper_manager_test_utils::ImageIsNearColor( ash::WmShell::Get()->wallpaper_controller()->GetWallpaper(), wallpaper_manager_test_utils::kCustomWallpaperColor)); EXPECT_EQ(2U, url_factory.num_attempts()); } } // namespace chromeos
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
f43c14f22fe2e1c8ddb79aeedc375204914c5ada
c489a7536d9ab501a817173731ce3c23ec055274
/28-Lec21/EditDistance.cpp
6fffc0913a9c6ad65ec076abef30677add66552a
[]
no_license
netbits/MIT-6.006-Introduction-to-Algorithms
ac5e721dec31b67b709a370b5adc4515de160647
d24026c426d2c5cbb00103ad1139ec65ee136134
refs/heads/main
2023-07-13T13:55:34.071992
2021-08-14T14:09:05
2021-08-14T14:09:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,207
cpp
#include <iostream> #include <string> #include <vector> #include <list> #include <algorithm> using namespace std; // using recursion class Solution_Recursion { public: int minDistance(string word1, string word2) { return minDistance(word1,word2,0,0); } int minDistance(string word1, string word2,int i,int j){ if(i==word1.size()||j==word2.size()) return word1.size()+word2.size()-i-j; if(word1[i]==word2[j]) return minDistance(word1,word2,i+1,j+1); int insert_cost = 1+minDistance(word1,word2,i,j+1); int delete_cost = 1+minDistance(word1,word2,i+1,j); int replace_cost = 1+minDistance(word1,word2,i+1,j+1); return min(insert_cost,min(delete_cost,replace_cost)); } }; // bottom-up 2-d array class Solution_Iteration { public: int minDistance(string word1, string word2) { int len1 = word1.size(),len2 = word2.size(); if(len1*len2==0) return len1+len2; // initialisation int dp[len1+1][len2+1]; // todo : replace 2-d array with last 2 rows or columns for(int i = 0;i<=len1;i++) { dp[i][len2] = len1-i; } for(int j = 0; j<=len2;j++) { dp[len1][j] = len2-j; } // bottom->up & right->left for(int i = len1-1; i>=0; i--) { for(int j = len2-1; j>=0; j--) { if(word1[i]==word2[j]) dp[i][j] = dp[i+1][j+1]; else dp[i][j] = 1 + min(dp[i][j+1],min(dp[i+1][j+1],dp[i+1][j])); } } return dp[0][0]; } }; // only keep last 2 rows class Solution_Itration_Better { public: int minDistance(string word1, string word2) { int len1 = word1.size(),len2 = word2.size(); if(len1*len2==0) return len1+len2; // initialisation // only need to keep last 2 rows (or last 2 columns) vector<int> current_row(len2+1),last_row(len2+1); for(int j = 0; j<=len2;j++) { last_row[j] = len2-j; } // bottom->up & right->left int i = len1-1; int j = len2-1; for( i = len1-1; i>=0; i--) { current_row[len2] = len1-i; for(j = len2-1; j>=0; j--) { if(word1[i]==word2[j]) current_row[j] = last_row[j+1]; else current_row[j] = 1+min(current_row[j+1],min(last_row[j],last_row[j+1])); } last_row = current_row; } return current_row[0]; } }; int main() { string s1("hieroglyphology"); string s2("michaelangelo"); string s3("dinitrophenylhydrazine"); string s4("acetylphenylhydrazine"); Solution_Recursion solution_r; Solution_Iteration solution_i; Solution_Itration_Better solution_ib; // cout<< solution_r.minDistance(s1,s2)<<endl; // 46 seconds! // cout<< solution_i.minDistance(s1,s2)<<endl; // 0.873 seconds! cout<< solution_ib.minDistance(s1,s2)<<endl; // 0.873 seconds! // cout<< solution_i.minDistance(s2,s3)<<endl; // cout<< solution_i.minDistance(s3,s4)<<endl; }
[ "valentinmu@outlook.com" ]
valentinmu@outlook.com
c3c8ccf28d77065447e2d3587095ebeaec8e7032
94db0bd95a58fabfd47517ed7d7d819a542693cd
/client/ClientRes/IOSAPI/Classes/Native/mscorlib_System_Collections_Generic_Dictionary_2_T1638887798.h
7babf58bdbc0ef9de48a0b885c44c0d203fbefe7
[]
no_license
Avatarchik/card
9fc6efa058085bd25f2b8831267816aa12b24350
d18dbc9c7da5cf32c963458ac13731ecfbf252fa
refs/heads/master
2020-06-07T07:01:00.444233
2017-12-11T10:52:17
2017-12-11T10:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,019
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // Spine.BoundingBoxAttachment struct BoundingBoxAttachment_t1898929740; // UnityEngine.PolygonCollider2D struct PolygonCollider2D_t3220183178; // System.IAsyncResult struct IAsyncResult_t1999651008; // System.AsyncCallback struct AsyncCallback_t163412349; // System.Object struct Il2CppObject; #include "mscorlib_System_MulticastDelegate3201952435.h" #include "mscorlib_System_Collections_DictionaryEntry3048875398.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<Spine.BoundingBoxAttachment,UnityEngine.PolygonCollider2D,System.Collections.DictionaryEntry> struct Transform_1_t1638887798 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "1" ]
1
97f75e5fad3eaeed8a7d2c32466a09eddaf625e1
3059e62977233086c566b668cd9821986eb44dad
/3dmath/math3d.cpp
96ef8b09d8c2a3ebd13a6efaa33d33af606a44e4
[]
no_license
xandrock/xandrock-common-library
f3c015d181d210617ebfca0175cf417bc9f4bec2
192e5e2e13a903748fa6ac699a588751efaff5e3
refs/heads/master
2021-01-01T16:12:32.175249
2015-01-21T03:33:38
2015-01-21T03:33:38
32,298,042
0
0
null
null
null
null
UTF-8
C++
false
false
36,966
cpp
// Math3d.c // Implementation of non-inlined functions in the Math3D Library // Richard S. Wright Jr. // These are pretty portable #include <math.h> #include "math3d.h" float ReciprocalSqrt( float x ) { long i; float y, r; y = x * 0.5f; i = *(long *)( &x ); i = 0x5f3759df - ( i >> 1 ); r = *(float *)( &i ); r = r * ( 1.5f - r * r * y ); return r; } void m3dMatToQuat( float q[4], const M3DMatrix44f m) { if ( m[0] + m[1*4+1] + m[2*4+2] > 0.0f ) { float t = + m[0] + m[1*4+1] + m[2*4+2] + 1.0f; float s = ReciprocalSqrt( t ) * 0.5f; q[3] = s * t; q[2] = ( m[1*4+0] - m[0*4+1] ) * s; q[1] = ( m[0*4+2] - m[2*4+0] ) * s; q[0] = ( m[2*4+1] - m[1*4+2] ) * s; }else if( m[0*4+0] > m[1*4+1] && m[0*4+0] > m[2*4+2] ) { float t = + m[0+0*4] - m[1+1*4] - m[2+2*4] + 1.0f; float s = ReciprocalSqrt( t ) * 0.5f; q[0] = s * t; q[1] = ( m[1*4+0] + m[0*4+1] ) * s; q[2] = ( m[0*4+2] + m[2*4+0] ) * s; q[3] = ( m[2*4+1] - m[1*4+2] ) * s; }else if( m[1*4+1] > m[2*4+2] ) { float t = - m[0*4+0] + m[1*4+1] - m[2*4+2] + 1.0f; float s = ReciprocalSqrt( t ) * 0.5f; q[1] = s * t; q[0] = ( m[1*4+0] + m[0*4+1] ) * s; q[3] = ( m[0*4+2] - m[2*4+0] ) * s; q[2] = ( m[2*4+1] + m[1*4+2] ) * s; } else { float t = - m[0*4+0] - m[1*4+1] + m[2*4+2] + 1.0f; float s = ReciprocalSqrt( t ) * 0.5f; q[2] = s * t; q[3] = ( m[1*4+0] - m[0*4+1] ) * s; q[0] = ( m[0*4+2] + m[2*4+0] ) * s; q[1] = ( m[2*4+1] + m[1*4+2] ) * s; } } void m3dRotationMatrix44(M3DMatrix44f m, M3DVector3f angles) { float angle; float sr, sp, sy, cr, cp, cy; angle = angles[2]; sy = sin(angle); cy = cos(angle); angle = angles[1]; sp = sin(angle); cp = cos(angle); angle = angles[0]; sr = sin(angle); cr = cos(angle); // matrix = (Z * Y) * X m[0] = cp*cy; m[4] = cp*sy; m[8] = -sp; m[12] = 0.0f; m[1] = sr*sp*cy+cr*-sy; m[5] = sr*sp*sy+cr*cy; m[9] = sr*cp; m[13] = 0.0f; m[2] = (cr*sp*cy+-sr*-sy); m[6] = (cr*sp*sy+-sr*cy); m[10] = cr*cp; m[14] = 0.0f; m[3] = 0.0; m[7] = 0.0; m[11] = 0.0; m[15] = 1.0f; } void m3dRotationMatrix44(M3DMatrix44d m, M3DVector3d angles) { float angle; float sr, sp, sy, cr, cp, cy; angle = angles[2]; sy = sin(angle); cy = cos(angle); angle = angles[1]; sp = sin(angle); cp = cos(angle); angle = angles[0]; sr = sin(angle); cr = cos(angle); // matrix = (Z * Y) * X m[0] = cp*cy; m[4] = cp*sy; m[8] = -sp; m[12] = 0.0f; m[1] = sr*sp*cy+cr*-sy; m[5] = sr*sp*sy+cr*cy; m[9] = sr*cp; m[13] = 0.0f; m[2] = (cr*sp*cy+-sr*-sy); m[6] = (cr*sp*sy+-sr*cy); m[10] = cr*cp; m[14] = 0.0f; m[3] = 0.0; m[7] = 0.0; m[11] = 0.0; m[15] = 1.0f; } void m3dQuaternionMatrix( const float quaternion[4], M3DMatrix44f matrix ) { matrix[0] = 1.0f - 2.0f * quaternion[1] * quaternion[1] - 2.0f * quaternion[2] * quaternion[2]; matrix[4] = 2.0f * quaternion[0] * quaternion[1] + 2.0f * quaternion[3] * quaternion[2]; matrix[8] = 2.0f * quaternion[0] * quaternion[2] - 2.0f * quaternion[3] * quaternion[1]; matrix[1] = 2.0f * quaternion[0] * quaternion[1] - 2.0f * quaternion[3] * quaternion[2]; matrix[5] = 1.0f - 2.0f * quaternion[0] * quaternion[0] - 2.0f * quaternion[2] * quaternion[2]; matrix[9] = 2.0f * quaternion[1] * quaternion[2] + 2.0f * quaternion[3] * quaternion[0]; matrix[2] = 2.0f * quaternion[0] * quaternion[2] + 2.0f * quaternion[3] * quaternion[1]; matrix[6] = 2.0f * quaternion[1] * quaternion[2] - 2.0f * quaternion[3] * quaternion[0]; matrix[10] = 1.0f - 2.0f * quaternion[0] * quaternion[0] - 2.0f * quaternion[1] * quaternion[1]; } //////////////////////////////////////////////////////////// // LoadIdentity // For 3x3 and 4x4 float and double matricies. // 3x3 float void m3dLoadIdentity33(M3DMatrix33f m) { // Don't be fooled, this is still column major static M3DMatrix33f identity = { 1.0f, 0.0f, 0.0f , 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; memcpy(m, identity, sizeof(M3DMatrix33f)); } // 3x3 double void m3dLoadIdentity33(M3DMatrix33d m) { // Don't be fooled, this is still column major static M3DMatrix33d identity = { 1.0, 0.0, 0.0 , 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; memcpy(m, identity, sizeof(M3DMatrix33d)); } // 4x4 float void m3dLoadIdentity44(M3DMatrix44f m) { // Don't be fooled, this is still column major static M3DMatrix44f identity = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; memcpy(m, identity, sizeof(M3DMatrix44f)); } // 4x4 double void m3dLoadIdentity44(M3DMatrix44d m) { static M3DMatrix44d identity = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; memcpy(m, identity, sizeof(M3DMatrix44d)); } //////////////////////////////////////////////////////////////////////// // Return the square of the distance between two points // Should these be inlined...? float m3dGetDistanceSquared(const M3DVector3f u, const M3DVector3f v) { float x = u[0] - v[0]; x = x*x; float y = u[1] - v[1]; y = y*y; float z = u[2] - v[2]; z = z*z; return (x + y + z); } // Ditto above, but for doubles double m3dGetDistanceSquared(const M3DVector3d u, const M3DVector3d v) { double x = u[0] - v[0]; x = x*x; double y = u[1] - v[1]; y = y*y; double z = u[2] - v[2]; z = z*z; return (x + y + z); } #define A(row,col) a[(col<<2)+row] #define B(row,col) b[(col<<2)+row] #define P(row,col) product[(col<<2)+row] /////////////////////////////////////////////////////////////////////////////// // Multiply two 4x4 matricies void m3dMatrixMultiply44(M3DMatrix44f product, const M3DMatrix44f a, const M3DMatrix44f b ) { for (int i = 0; i < 4; i++) { float ai0=A(i,0), ai1=A(i,1), ai2=A(i,2), ai3=A(i,3); P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0); P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1); P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2); P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3); } } // Ditto above, but for doubles void m3dMatrixMultiply44(M3DMatrix44d product, const M3DMatrix44d a, const M3DMatrix44d b ) { for (int i = 0; i < 4; i++) { double ai0=A(i,0), ai1=A(i,1), ai2=A(i,2), ai3=A(i,3); P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0); P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1); P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2); P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3); } } #undef A #undef B #undef P #define A33(row,col) a[(col*3)+row] #define B33(row,col) b[(col*3)+row] #define P33(row,col) product[(col*3)+row] /////////////////////////////////////////////////////////////////////////////// // Multiply two 3x3 matricies void m3dMatrixMultiply33(M3DMatrix33f product, const M3DMatrix33f a, const M3DMatrix33f b ) { for (int i = 0; i < 3; i++) { float ai0=A33(i,0), ai1=A33(i,1), ai2=A33(i,2); P33(i,0) = ai0 * B33(0,0) + ai1 * B33(1,0) + ai2 * B33(2,0); P33(i,1) = ai0 * B33(0,1) + ai1 * B33(1,1) + ai2 * B33(2,1); P33(i,2) = ai0 * B33(0,2) + ai1 * B33(1,2) + ai2 * B33(2,2); } } // Ditto above, but for doubles void m3dMatrixMultiply33(M3DMatrix33d product, const M3DMatrix33d a, const M3DMatrix33d b ) { for (int i = 0; i < 3; i++) { double ai0=A33(i,0), ai1=A33(i,1), ai2=A33(i,2); P33(i,0) = ai0 * B33(0,0) + ai1 * B33(1,0) + ai2 * B33(2,0); P33(i,1) = ai0 * B33(0,1) + ai1 * B33(1,1) + ai2 * B33(2,1); P33(i,2) = ai0 * B33(0,2) + ai1 * B33(1,2) + ai2 * B33(2,2); } } #undef A33 #undef B33 #undef P33 #define M33(row,col) m[col*3+row] /////////////////////////////////////////////////////////////////////////////// // Creates a 3x3 rotation matrix, takes radians NOT degrees void m3dRotationMatrix33(M3DMatrix33f m, float angle, float x, float y, float z) { float mag, s, c; float xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c; s = float(sin(angle)); c = float(cos(angle)); mag = float(sqrt( x*x + y*y + z*z )); // Identity matrix if (mag == 0.0f) { m3dLoadIdentity33(m); return; } // Rotation matrix is normalized x /= mag; y /= mag; z /= mag; xx = x * x; yy = y * y; zz = z * z; xy = x * y; yz = y * z; zx = z * x; xs = x * s; ys = y * s; zs = z * s; one_c = 1.0f - c; M33(0,0) = (one_c * xx) + c; M33(0,1) = (one_c * xy) - zs; M33(0,2) = (one_c * zx) + ys; M33(1,0) = (one_c * xy) + zs; M33(1,1) = (one_c * yy) + c; M33(1,2) = (one_c * yz) - xs; M33(2,0) = (one_c * zx) - ys; M33(2,1) = (one_c * yz) + xs; M33(2,2) = (one_c * zz) + c; } #undef M33 /////////////////////////////////////////////////////////////////////////////// // Creates a 4x4 rotation matrix, takes radians NOT degrees void m3dRotationMatrix44(M3DMatrix44f m, float angle, float x, float y, float z) { float mag, s, c; float xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c; s = float(sin(angle)); c = float(cos(angle)); mag = float(sqrt( x*x + y*y + z*z )); // Identity matrix if (mag == 0.0f) { m3dLoadIdentity44(m); return; } // Rotation matrix is normalized x /= mag; y /= mag; z /= mag; #define M(row,col) m[col*4+row] xx = x * x; yy = y * y; zz = z * z; xy = x * y; yz = y * z; zx = z * x; xs = x * s; ys = y * s; zs = z * s; one_c = 1.0f - c; M(0,0) = (one_c * xx) + c; M(0,1) = (one_c * xy) - zs; M(0,2) = (one_c * zx) + ys; M(0,3) = 0.0f; M(1,0) = (one_c * xy) + zs; M(1,1) = (one_c * yy) + c; M(1,2) = (one_c * yz) - xs; M(1,3) = 0.0f; M(2,0) = (one_c * zx) - ys; M(2,1) = (one_c * yz) + xs; M(2,2) = (one_c * zz) + c; M(2,3) = 0.0f; M(3,0) = 0.0f; M(3,1) = 0.0f; M(3,2) = 0.0f; M(3,3) = 1.0f; #undef M } /////////////////////////////////////////////////////////////////////////////// // Ditto above, but for doubles void m3dRotationMatrix33(M3DMatrix33d m, double angle, double x, double y, double z) { double mag, s, c; double xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c; s = sin(angle); c = cos(angle); mag = sqrt( x*x + y*y + z*z ); // Identity matrix if (mag == 0.0) { m3dLoadIdentity33(m); return; } // Rotation matrix is normalized x /= mag; y /= mag; z /= mag; #define M(row,col) m[col*3+row] xx = x * x; yy = y * y; zz = z * z; xy = x * y; yz = y * z; zx = z * x; xs = x * s; ys = y * s; zs = z * s; one_c = 1.0 - c; M(0,0) = (one_c * xx) + c; M(0,1) = (one_c * xy) - zs; M(0,2) = (one_c * zx) + ys; M(1,0) = (one_c * xy) + zs; M(1,1) = (one_c * yy) + c; M(1,2) = (one_c * yz) - xs; M(2,0) = (one_c * zx) - ys; M(2,1) = (one_c * yz) + xs; M(2,2) = (one_c * zz) + c; #undef M } /////////////////////////////////////////////////////////////////////////////// // Creates a 4x4 rotation matrix, takes radians NOT degrees void m3dRotationMatrix44(M3DMatrix44d m, double angle, double x, double y, double z) { double mag, s, c; double xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c; s = sin(angle); c = cos(angle); mag = sqrt( x*x + y*y + z*z ); // Identity matrix if (mag == 0.0) { m3dLoadIdentity44(m); return; } // Rotation matrix is normalized x /= mag; y /= mag; z /= mag; #define M(row,col) m[col*4+row] xx = x * x; yy = y * y; zz = z * z; xy = x * y; yz = y * z; zx = z * x; xs = x * s; ys = y * s; zs = z * s; one_c = 1.0f - c; M(0,0) = (one_c * xx) + c; M(0,1) = (one_c * xy) - zs; M(0,2) = (one_c * zx) + ys; M(0,3) = 0.0; M(1,0) = (one_c * xy) + zs; M(1,1) = (one_c * yy) + c; M(1,2) = (one_c * yz) - xs; M(1,3) = 0.0; M(2,0) = (one_c * zx) - ys; M(2,1) = (one_c * yz) + xs; M(2,2) = (one_c * zz) + c; M(2,3) = 0.0; M(3,0) = 0.0; M(3,1) = 0.0; M(3,2) = 0.0; M(3,3) = 1.0; #undef M } // Lifted from Mesa /* * Compute inverse of 4x4 transformation matrix. * Code contributed by Jacques Leroy jle@star.be * Return GL_TRUE for success, GL_FALSE for failure (singular matrix) */ bool m3dInvertMatrix44(M3DMatrix44f dst, const M3DMatrix44f src ) { #define SWAP_ROWS(a, b) { float *_tmp = a; (a)=(b); (b)=_tmp; } #define MAT(m,r,c) (m)[(c)*4+(r)] float wtmp[4][8]; float m0, m1, m2, m3, s; float *r0, *r1, *r2, *r3; r0 = wtmp[0], r1 = wtmp[1], r2 = wtmp[2], r3 = wtmp[3]; r0[0] = MAT(src,0,0), r0[1] = MAT(src,0,1), r0[2] = MAT(src,0,2), r0[3] = MAT(src,0,3), r0[4] = 1.0, r0[5] = r0[6] = r0[7] = 0.0, r1[0] = MAT(src,1,0), r1[1] = MAT(src,1,1), r1[2] = MAT(src,1,2), r1[3] = MAT(src,1,3), r1[5] = 1.0, r1[4] = r1[6] = r1[7] = 0.0, r2[0] = MAT(src,2,0), r2[1] = MAT(src,2,1), r2[2] = MAT(src,2,2), r2[3] = MAT(src,2,3), r2[6] = 1.0, r2[4] = r2[5] = r2[7] = 0.0, r3[0] = MAT(src,3,0), r3[1] = MAT(src,3,1), r3[2] = MAT(src,3,2), r3[3] = MAT(src,3,3), r3[7] = 1.0, r3[4] = r3[5] = r3[6] = 0.0; /* choose pivot - or die */ if (fabs(r3[0])>fabs(r2[0])) SWAP_ROWS(r3, r2); if (fabs(r2[0])>fabs(r1[0])) SWAP_ROWS(r2, r1); if (fabs(r1[0])>fabs(r0[0])) SWAP_ROWS(r1, r0); if (0.0 == r0[0]) return false; /* eliminate first variable */ m1 = r1[0]/r0[0]; m2 = r2[0]/r0[0]; m3 = r3[0]/r0[0]; s = r0[1]; r1[1] -= m1 * s; r2[1] -= m2 * s; r3[1] -= m3 * s; s = r0[2]; r1[2] -= m1 * s; r2[2] -= m2 * s; r3[2] -= m3 * s; s = r0[3]; r1[3] -= m1 * s; r2[3] -= m2 * s; r3[3] -= m3 * s; s = r0[4]; if (s != 0.0) { r1[4] -= m1 * s; r2[4] -= m2 * s; r3[4] -= m3 * s; } s = r0[5]; if (s != 0.0) { r1[5] -= m1 * s; r2[5] -= m2 * s; r3[5] -= m3 * s; } s = r0[6]; if (s != 0.0) { r1[6] -= m1 * s; r2[6] -= m2 * s; r3[6] -= m3 * s; } s = r0[7]; if (s != 0.0) { r1[7] -= m1 * s; r2[7] -= m2 * s; r3[7] -= m3 * s; } /* choose pivot - or die */ if (fabs(r3[1])>fabs(r2[1])) SWAP_ROWS(r3, r2); if (fabs(r2[1])>fabs(r1[1])) SWAP_ROWS(r2, r1); if (0.0 == r1[1]) return false; /* eliminate second variable */ m2 = r2[1]/r1[1]; m3 = r3[1]/r1[1]; r2[2] -= m2 * r1[2]; r3[2] -= m3 * r1[2]; r2[3] -= m2 * r1[3]; r3[3] -= m3 * r1[3]; s = r1[4]; if (0.0 != s) { r2[4] -= m2 * s; r3[4] -= m3 * s; } s = r1[5]; if (0.0 != s) { r2[5] -= m2 * s; r3[5] -= m3 * s; } s = r1[6]; if (0.0 != s) { r2[6] -= m2 * s; r3[6] -= m3 * s; } s = r1[7]; if (0.0 != s) { r2[7] -= m2 * s; r3[7] -= m3 * s; } /* choose pivot - or die */ if (fabs(r3[2])>fabs(r2[2])) SWAP_ROWS(r3, r2); if (0.0 == r2[2]) return false; /* eliminate third variable */ m3 = r3[2]/r2[2]; r3[3] -= m3 * r2[3], r3[4] -= m3 * r2[4], r3[5] -= m3 * r2[5], r3[6] -= m3 * r2[6], r3[7] -= m3 * r2[7]; /* last check */ if (0.0 == r3[3]) return false; s = 1.0f/r3[3]; /* now back substitute row 3 */ r3[4] *= s; r3[5] *= s; r3[6] *= s; r3[7] *= s; m2 = r2[3]; /* now back substitute row 2 */ s = 1.0f/r2[2]; r2[4] = s * (r2[4] - r3[4] * m2), r2[5] = s * (r2[5] - r3[5] * m2), r2[6] = s * (r2[6] - r3[6] * m2), r2[7] = s * (r2[7] - r3[7] * m2); m1 = r1[3]; r1[4] -= r3[4] * m1, r1[5] -= r3[5] * m1, r1[6] -= r3[6] * m1, r1[7] -= r3[7] * m1; m0 = r0[3]; r0[4] -= r3[4] * m0, r0[5] -= r3[5] * m0, r0[6] -= r3[6] * m0, r0[7] -= r3[7] * m0; m1 = r1[2]; /* now back substitute row 1 */ s = 1.0f/r1[1]; r1[4] = s * (r1[4] - r2[4] * m1), r1[5] = s * (r1[5] - r2[5] * m1), r1[6] = s * (r1[6] - r2[6] * m1), r1[7] = s * (r1[7] - r2[7] * m1); m0 = r0[2]; r0[4] -= r2[4] * m0, r0[5] -= r2[5] * m0, r0[6] -= r2[6] * m0, r0[7] -= r2[7] * m0; m0 = r0[1]; /* now back substitute row 0 */ s = 1.0f/r0[0]; r0[4] = s * (r0[4] - r1[4] * m0), r0[5] = s * (r0[5] - r1[5] * m0), r0[6] = s * (r0[6] - r1[6] * m0), r0[7] = s * (r0[7] - r1[7] * m0); MAT(dst,0,0) = r0[4]; MAT(dst,0,1) = r0[5], MAT(dst,0,2) = r0[6]; MAT(dst,0,3) = r0[7], MAT(dst,1,0) = r1[4]; MAT(dst,1,1) = r1[5], MAT(dst,1,2) = r1[6]; MAT(dst,1,3) = r1[7], MAT(dst,2,0) = r2[4]; MAT(dst,2,1) = r2[5], MAT(dst,2,2) = r2[6]; MAT(dst,2,3) = r2[7], MAT(dst,3,0) = r3[4]; MAT(dst,3,1) = r3[5], MAT(dst,3,2) = r3[6]; MAT(dst,3,3) = r3[7]; return true; #undef MAT #undef SWAP_ROWS } // Ditto above, but for doubles bool m3dInvertMatrix44(M3DMatrix44d dst, const M3DMatrix44d src) { #define SWAP_ROWS(a, b) { double *_tmp = a; (a)=(b); (b)=_tmp; } #define MAT(m,r,c) (m)[(c)*4+(r)] double wtmp[4][8]; double m0, m1, m2, m3, s; double *r0, *r1, *r2, *r3; r0 = wtmp[0], r1 = wtmp[1], r2 = wtmp[2], r3 = wtmp[3]; r0[0] = MAT(src,0,0), r0[1] = MAT(src,0,1), r0[2] = MAT(src,0,2), r0[3] = MAT(src,0,3), r0[4] = 1.0, r0[5] = r0[6] = r0[7] = 0.0, r1[0] = MAT(src,1,0), r1[1] = MAT(src,1,1), r1[2] = MAT(src,1,2), r1[3] = MAT(src,1,3), r1[5] = 1.0, r1[4] = r1[6] = r1[7] = 0.0, r2[0] = MAT(src,2,0), r2[1] = MAT(src,2,1), r2[2] = MAT(src,2,2), r2[3] = MAT(src,2,3), r2[6] = 1.0, r2[4] = r2[5] = r2[7] = 0.0, r3[0] = MAT(src,3,0), r3[1] = MAT(src,3,1), r3[2] = MAT(src,3,2), r3[3] = MAT(src,3,3), r3[7] = 1.0, r3[4] = r3[5] = r3[6] = 0.0; // choose pivot - or die if (fabs(r3[0])>fabs(r2[0])) SWAP_ROWS(r3, r2); if (fabs(r2[0])>fabs(r1[0])) SWAP_ROWS(r2, r1); if (fabs(r1[0])>fabs(r0[0])) SWAP_ROWS(r1, r0); if (0.0 == r0[0]) return false; // eliminate first variable m1 = r1[0]/r0[0]; m2 = r2[0]/r0[0]; m3 = r3[0]/r0[0]; s = r0[1]; r1[1] -= m1 * s; r2[1] -= m2 * s; r3[1] -= m3 * s; s = r0[2]; r1[2] -= m1 * s; r2[2] -= m2 * s; r3[2] -= m3 * s; s = r0[3]; r1[3] -= m1 * s; r2[3] -= m2 * s; r3[3] -= m3 * s; s = r0[4]; if (s != 0.0) { r1[4] -= m1 * s; r2[4] -= m2 * s; r3[4] -= m3 * s; } s = r0[5]; if (s != 0.0) { r1[5] -= m1 * s; r2[5] -= m2 * s; r3[5] -= m3 * s; } s = r0[6]; if (s != 0.0) { r1[6] -= m1 * s; r2[6] -= m2 * s; r3[6] -= m3 * s; } s = r0[7]; if (s != 0.0) { r1[7] -= m1 * s; r2[7] -= m2 * s; r3[7] -= m3 * s; } // choose pivot - or die if (fabs(r3[1])>fabs(r2[1])) SWAP_ROWS(r3, r2); if (fabs(r2[1])>fabs(r1[1])) SWAP_ROWS(r2, r1); if (0.0 == r1[1]) return false; // eliminate second variable m2 = r2[1]/r1[1]; m3 = r3[1]/r1[1]; r2[2] -= m2 * r1[2]; r3[2] -= m3 * r1[2]; r2[3] -= m2 * r1[3]; r3[3] -= m3 * r1[3]; s = r1[4]; if (0.0 != s) { r2[4] -= m2 * s; r3[4] -= m3 * s; } s = r1[5]; if (0.0 != s) { r2[5] -= m2 * s; r3[5] -= m3 * s; } s = r1[6]; if (0.0 != s) { r2[6] -= m2 * s; r3[6] -= m3 * s; } s = r1[7]; if (0.0 != s) { r2[7] -= m2 * s; r3[7] -= m3 * s; } // choose pivot - or die if (fabs(r3[2])>fabs(r2[2])) SWAP_ROWS(r3, r2); if (0.0 == r2[2]) return false; // eliminate third variable m3 = r3[2]/r2[2]; r3[3] -= m3 * r2[3], r3[4] -= m3 * r2[4], r3[5] -= m3 * r2[5], r3[6] -= m3 * r2[6], r3[7] -= m3 * r2[7]; // last check if (0.0 == r3[3]) return false; s = 1.0f/r3[3]; // now back substitute row 3 r3[4] *= s; r3[5] *= s; r3[6] *= s; r3[7] *= s; m2 = r2[3]; // now back substitute row 2 s = 1.0f/r2[2]; r2[4] = s * (r2[4] - r3[4] * m2), r2[5] = s * (r2[5] - r3[5] * m2), r2[6] = s * (r2[6] - r3[6] * m2), r2[7] = s * (r2[7] - r3[7] * m2); m1 = r1[3]; r1[4] -= r3[4] * m1, r1[5] -= r3[5] * m1, r1[6] -= r3[6] * m1, r1[7] -= r3[7] * m1; m0 = r0[3]; r0[4] -= r3[4] * m0, r0[5] -= r3[5] * m0, r0[6] -= r3[6] * m0, r0[7] -= r3[7] * m0; m1 = r1[2]; // now back substitute row 1 s = 1.0f/r1[1]; r1[4] = s * (r1[4] - r2[4] * m1), r1[5] = s * (r1[5] - r2[5] * m1), r1[6] = s * (r1[6] - r2[6] * m1), r1[7] = s * (r1[7] - r2[7] * m1); m0 = r0[2]; r0[4] -= r2[4] * m0, r0[5] -= r2[5] * m0, r0[6] -= r2[6] * m0, r0[7] -= r2[7] * m0; m0 = r0[1]; // now back substitute row 0 s = 1.0f/r0[0]; r0[4] = s * (r0[4] - r1[4] * m0), r0[5] = s * (r0[5] - r1[5] * m0), r0[6] = s * (r0[6] - r1[6] * m0), r0[7] = s * (r0[7] - r1[7] * m0); MAT(dst,0,0) = r0[4]; MAT(dst,0,1) = r0[5], MAT(dst,0,2) = r0[6]; MAT(dst,0,3) = r0[7], MAT(dst,1,0) = r1[4]; MAT(dst,1,1) = r1[5], MAT(dst,1,2) = r1[6]; MAT(dst,1,3) = r1[7], MAT(dst,2,0) = r2[4]; MAT(dst,2,1) = r2[5], MAT(dst,2,2) = r2[6]; MAT(dst,2,3) = r2[7], MAT(dst,3,0) = r3[4]; MAT(dst,3,1) = r3[5], MAT(dst,3,2) = r3[6]; MAT(dst,3,3) = r3[7]; return true; #undef MAT #undef SWAP_ROWS return true; } /////////////////////////////////////////////////////////////////////////////////////// // Get Window coordinates, discard Z... void m3dProjectXY(const M3DMatrix44f mModelView, const M3DMatrix44f mProjection, const int iViewPort[4], const M3DVector3f vPointIn, M3DVector2f vPointOut) { M3DVector4f vBack, vForth; memcpy(vBack, vPointIn, sizeof(float)*3); vBack[3] = 1.0f; m3dTransformVector4(vForth, vBack, mModelView); m3dTransformVector4(vBack, vForth, mProjection); if(!m3dCloseEnough(vBack[3], 0.0f, 0.000001f)) { float div = 1.0f / vBack[3]; vBack[0] *= div; vBack[1] *= div; } vPointOut[0] = vBack[0] * 0.5f + 0.5f; vPointOut[1] = vBack[1] * 0.5f + 0.5f; /* Map x,y to viewport */ vPointOut[0] = (vPointOut[0] * iViewPort[2]) + iViewPort[0]; vPointOut[1] = (vPointOut[1] * iViewPort[3]) + iViewPort[1]; } /////////////////////////////////////////////////////////////////////////////////////// // Get window coordinates, we also want Z.... void m3dProjectXYZ(M3DVector3f vPointOut, const M3DMatrix44f mModelView, const M3DMatrix44f mProjection, const int iViewPort[4], const M3DVector3f vPointIn) { M3DVector4f vBack, vForth; memcpy(vBack, vPointIn, sizeof(float)*3); vBack[3] = 1.0f; m3dTransformVector4(vForth, vBack, mModelView); m3dTransformVector4(vBack, vForth, mProjection); if(!m3dCloseEnough(vBack[3], 0.0f, 0.000001f)) { float div = 1.0f / vBack[3]; vBack[0] *= div; vBack[1] *= div; vBack[2] *= div; } vPointOut[0] = vBack[0] * 0.5f + 0.5f; vPointOut[1] = vBack[1] * 0.5f + 0.5f; vPointOut[2] = vBack[2] * 0.5f + 0.5f; /* Map x,y to viewport */ vPointOut[0] = (vPointOut[0] * iViewPort[2]) + iViewPort[0]; vPointOut[1] = (vPointOut[1] * iViewPort[3]) + iViewPort[1]; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Misc. Utilities /////////////////////////////////////////////////////////////////////////////// // Calculates the normal of a triangle specified by the three points // p1, p2, and p3. Each pointer points to an array of three floats. The // triangle is assumed to be wound counter clockwise. void m3dFindNormal(M3DVector3f result, const M3DVector3f point1, const M3DVector3f point2, const M3DVector3f point3) { M3DVector3f v1,v2; // Temporary vectors // Calculate two vectors from the three points. Assumes counter clockwise // winding! v1[0] = point1[0] - point2[0]; v1[1] = point1[1] - point2[1]; v1[2] = point1[2] - point2[2]; v2[0] = point2[0] - point3[0]; v2[1] = point2[1] - point3[1]; v2[2] = point2[2] - point3[2]; // Take the cross product of the two vectors to get // the normal vector. m3dCrossProduct(result, v1, v2); } // Ditto above, but for doubles void m3dFindNormal(M3DVector3d result, const M3DVector3d point1, const M3DVector3d point2, const M3DVector3d point3) { M3DVector3d v1,v2; // Temporary vectors // Calculate two vectors from the three points. Assumes counter clockwise // winding! v1[0] = point1[0] - point2[0]; v1[1] = point1[1] - point2[1]; v1[2] = point1[2] - point2[2]; v2[0] = point2[0] - point3[0]; v2[1] = point2[1] - point3[1]; v2[2] = point2[2] - point3[2]; // Take the cross product of the two vectors to get // the normal vector. m3dCrossProduct(result, v1, v2); } ///////////////////////////////////////////////////////////////////////////////////////// // Calculate the plane equation of the plane that the three specified points lay in. The // points are given in clockwise winding order, with normal pointing out of clockwise face // planeEq contains the A,B,C, and D of the plane equation coefficients void m3dGetPlaneEquation(M3DVector4f planeEq, const M3DVector3f p1, const M3DVector3f p2, const M3DVector3f p3) { // Get two vectors... do the cross product M3DVector3f v1, v2; // V1 = p3 - p1 v1[0] = p3[0] - p1[0]; v1[1] = p3[1] - p1[1]; v1[2] = p3[2] - p1[2]; // V2 = P2 - p1 v2[0] = p2[0] - p1[0]; v2[1] = p2[1] - p1[1]; v2[2] = p2[2] - p1[2]; // Unit normal to plane - Not sure which is the best way here m3dCrossProduct(planeEq, v1, v2); m3dNormalizeVector(planeEq); // Back substitute to get D planeEq[3] = -(planeEq[0] * p3[0] + planeEq[1] * p3[1] + planeEq[2] * p3[2]); } // Ditto above, but for doubles void m3dGetPlaneEquation(M3DVector4d planeEq, const M3DVector3d p1, const M3DVector3d p2, const M3DVector3d p3) { // Get two vectors... do the cross product M3DVector3d v1, v2; // V1 = p3 - p1 v1[0] = p3[0] - p1[0]; v1[1] = p3[1] - p1[1]; v1[2] = p3[2] - p1[2]; // V2 = P2 - p1 v2[0] = p2[0] - p1[0]; v2[1] = p2[1] - p1[1]; v2[2] = p2[2] - p1[2]; // Unit normal to plane - Not sure which is the best way here m3dCrossProduct(planeEq, v1, v2); m3dNormalizeVector(planeEq); // Back substitute to get D planeEq[3] = -(planeEq[0] * p3[0] + planeEq[1] * p3[1] + planeEq[2] * p3[2]); } ////////////////////////////////////////////////////////////////////////////////////////////////// // This function does a three dimensional Catmull-Rom curve interpolation. Pass four points, and a // floating point number between 0.0 and 1.0. The curve is interpolated between the middle two points. // Coded by RSW // http://www.mvps.org/directx/articles/catmull/ void m3dCatmullRom3(M3DVector3f vOut, M3DVector3f vP0, M3DVector3f vP1, M3DVector3f vP2, M3DVector3f vP3, float t) { // Unrolled loop to speed things up a little bit... float t2 = t * t; float t3 = t2 * t; // X vOut[0] = 0.5f * ( ( 2.0f * vP1[0]) + (-vP0[0] + vP2[0]) * t + (2.0f * vP0[0] - 5.0f *vP1[0] + 4.0f * vP2[0] - vP3[0]) * t2 + (-vP0[0] + 3.0f*vP1[0] - 3.0f *vP2[0] + vP3[0]) * t3); // Y vOut[1] = 0.5f * ( ( 2.0f * vP1[1]) + (-vP0[1] + vP2[1]) * t + (2.0f * vP0[1] - 5.0f *vP1[1] + 4.0f * vP2[1] - vP3[1]) * t2 + (-vP0[1] + 3.0f*vP1[1] - 3.0f *vP2[1] + vP3[1]) * t3); // Z vOut[2] = 0.5f * ( ( 2.0f * vP1[2]) + (-vP0[2] + vP2[2]) * t + (2.0f * vP0[2] - 5.0f *vP1[2] + 4.0f * vP2[2] - vP3[2]) * t2 + (-vP0[2] + 3.0f*vP1[2] - 3.0f *vP2[2] + vP3[2]) * t3); } ////////////////////////////////////////////////////////////////////////////////////////////////// // This function does a three dimensional Catmull-Rom curve interpolation. Pass four points, and a // floating point number between 0.0 and 1.0. The curve is interpolated between the middle two points. // Coded by RSW // http://www.mvps.org/directx/articles/catmull/ void m3dCatmullRom3(M3DVector3d vOut, M3DVector3d vP0, M3DVector3d vP1, M3DVector3d vP2, M3DVector3d vP3, double t) { // Unrolled loop to speed things up a little bit... double t2 = t * t; double t3 = t2 * t; // X vOut[0] = 0.5 * ( ( 2.0 * vP1[0]) + (-vP0[0] + vP2[0]) * t + (2.0 * vP0[0] - 5.0 *vP1[0] + 4.0 * vP2[0] - vP3[0]) * t2 + (-vP0[0] + 3.0*vP1[0] - 3.0 *vP2[0] + vP3[0]) * t3); // Y vOut[1] = 0.5 * ( ( 2.0 * vP1[1]) + (-vP0[1] + vP2[1]) * t + (2.0 * vP0[1] - 5.0 *vP1[1] + 4.0 * vP2[1] - vP3[1]) * t2 + (-vP0[1] + 3*vP1[1] - 3.0 *vP2[1] + vP3[1]) * t3); // Z vOut[2] = 0.5 * ( ( 2.0 * vP1[2]) + (-vP0[2] + vP2[2]) * t + (2.0 * vP0[2] - 5.0 *vP1[2] + 4.0 * vP2[2] - vP3[2]) * t2 + (-vP0[2] + 3.0*vP1[2] - 3.0 *vP2[2] + vP3[2]) * t3); } /////////////////////////////////////////////////////////////////////////////// // Determine if the ray (starting at point) intersects the sphere centered at // sphereCenter with radius sphereRadius // Return value is < 0 if the ray does not intersect // Return value is 0.0 if ray is tangent // Positive value is distance to the intersection point // Algorithm from "3D Math Primer for Graphics and Game Development" double m3dRaySphereTest(const M3DVector3d point, const M3DVector3d ray, const M3DVector3d sphereCenter, double sphereRadius) { //m3dNormalizeVector(ray); // Make sure ray is unit length M3DVector3d rayToCenter; // Ray to center of sphere rayToCenter[0] = sphereCenter[0] - point[0]; rayToCenter[1] = sphereCenter[1] - point[1]; rayToCenter[2] = sphereCenter[2] - point[2]; // Project rayToCenter on ray to test double a = m3dDotProduct(rayToCenter, ray); // Distance to center of sphere double distance2 = m3dDotProduct(rayToCenter, rayToCenter); // Or length double dRet = (sphereRadius * sphereRadius) - distance2 + (a*a); if(dRet > 0.0) // Return distance to intersection dRet = a - sqrt(dRet); return dRet; } /////////////////////////////////////////////////////////////////////////////// // Determine if the ray (starting at point) intersects the sphere centered at // ditto above, but uses floating point math float m3dRaySphereTest(const M3DVector3f point, const M3DVector3f ray, const M3DVector3f sphereCenter, float sphereRadius) { //m3dNormalizeVectorf(ray); // Make sure ray is unit length M3DVector3f rayToCenter; // Ray to center of sphere rayToCenter[0] = sphereCenter[0] - point[0]; rayToCenter[1] = sphereCenter[1] - point[1]; rayToCenter[2] = sphereCenter[2] - point[2]; // Project rayToCenter on ray to test float a = m3dDotProduct(rayToCenter, ray); // Distance to center of sphere float distance2 = m3dDotProduct(rayToCenter, rayToCenter); // Or length float dRet = (sphereRadius * sphereRadius) - distance2 + (a*a); if(dRet > 0.0) // Return distance to intersection dRet = a - sqrtf(dRet); return dRet; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Calculate the tangent basis for a triangle on the surface of a model // This vector is needed for most normal mapping shaders void m3dCalculateTangentBasis(const M3DVector3f vTriangle[3], const M3DVector2f vTexCoords[3], const M3DVector3f N, M3DVector3f vTangent) { M3DVector3f dv2v1, dv3v1; float dc2c1t, dc2c1b, dc3c1t, dc3c1b; float M; m3dSubtractVectors3(dv2v1, vTriangle[1], vTriangle[0]); m3dSubtractVectors3(dv3v1, vTriangle[2], vTriangle[0]); dc2c1t = vTexCoords[1][0] - vTexCoords[0][0]; dc2c1b = vTexCoords[1][1] - vTexCoords[0][1]; dc3c1t = vTexCoords[2][0] - vTexCoords[0][0]; dc3c1b = vTexCoords[2][1] - vTexCoords[0][1]; M = (dc2c1t * dc3c1b) - (dc3c1t * dc2c1b); M = 1.0f / M; m3dScaleVector3(dv2v1, dc3c1b); m3dScaleVector3(dv3v1, dc2c1b); m3dSubtractVectors3(vTangent, dv2v1, dv3v1); m3dScaleVector3(vTangent, M); // This potentially changes the direction of the vector m3dNormalizeVector(vTangent); M3DVector3f B; m3dCrossProduct(B, N, vTangent); m3dCrossProduct(vTangent, B, N); m3dNormalizeVector(vTangent); } //////////////////////////////////////////////////////////////////////////// // Smoothly step between 0 and 1 between edge1 and edge 2 double m3dSmoothStep(double edge1, double edge2, double x) { double t; t = (x - edge1) / (edge2 - edge1); if(t > 1.0) t = 1.0; if(t < 0.0) t = 0.0f; return t * t * ( 3.0 - 2.0 * t); } //////////////////////////////////////////////////////////////////////////// // Smoothly step between 0 and 1 between edge1 and edge 2 float m3dSmoothStep(float edge1, float edge2, float x) { float t; t = (x - edge1) / (edge2 - edge1); if(t > 1.0f) t = 1.0f; if(t < 0.0) t = 0.0f; return t * t * ( 3.0f - 2.0f * t); } /////////////////////////////////////////////////////////////////////////// // Creae a projection to "squish" an object into the plane. // Use m3dGetPlaneEquationf(planeEq, point1, point2, point3); // to get a plane equation. void m3dMakePlanarShadowMatrix(M3DMatrix44f proj, const M3DVector4f planeEq, const M3DVector3f vLightPos) { // These just make the code below easier to read. They will be // removed by the optimizer. float a = planeEq[0]; float b = planeEq[1]; float c = planeEq[2]; float d = planeEq[3]; float dx = -vLightPos[0]; float dy = -vLightPos[1]; float dz = -vLightPos[2]; // Now build the projection matrix proj[0] = b * dy + c * dz; proj[1] = -a * dy; proj[2] = -a * dz; proj[3] = 0.0; proj[4] = -b * dx; proj[5] = a * dx + c * dz; proj[6] = -b * dz; proj[7] = 0.0; proj[8] = -c * dx; proj[9] = -c * dy; proj[10] = a * dx + b * dy; proj[11] = 0.0; proj[12] = -d * dx; proj[13] = -d * dy; proj[14] = -d * dz; proj[15] = a * dx + b * dy + c * dz; // Shadow matrix ready } /////////////////////////////////////////////////////////////////////////// // Creae a projection to "squish" an object into the plane. // Use m3dGetPlaneEquationd(planeEq, point1, point2, point3); // to get a plane equation. void m3dMakePlanarShadowMatrix(M3DMatrix44d proj, const M3DVector4d planeEq, const M3DVector3f vLightPos) { // These just make the code below easier to read. They will be // removed by the optimizer. double a = planeEq[0]; double b = planeEq[1]; double c = planeEq[2]; double d = planeEq[3]; double dx = -vLightPos[0]; double dy = -vLightPos[1]; double dz = -vLightPos[2]; // Now build the projection matrix proj[0] = b * dy + c * dz; proj[1] = -a * dy; proj[2] = -a * dz; proj[3] = 0.0; proj[4] = -b * dx; proj[5] = a * dx + c * dz; proj[6] = -b * dz; proj[7] = 0.0; proj[8] = -c * dx; proj[9] = -c * dy; proj[10] = a * dx + b * dy; proj[11] = 0.0; proj[12] = -d * dx; proj[13] = -d * dy; proj[14] = -d * dz; proj[15] = a * dx + b * dy + c * dz; // Shadow matrix ready } ///////////////////////////////////////////////////////////////////////////// // I want to know the point on a ray, closest to another given point in space. // As a bonus, return the distance squared of the two points. // In: vRayOrigin is the origin of the ray. // In: vUnitRayDir is the unit vector of the ray // In: vPointInSpace is the point in space // Out: vPointOnRay is the poing on the ray closest to vPointInSpace // Return: The square of the distance to the ray double m3dClosestPointOnRay(M3DVector3d vPointOnRay, const M3DVector3d vRayOrigin, const M3DVector3d vUnitRayDir, const M3DVector3d vPointInSpace) { M3DVector3d v; m3dSubtractVectors3(v, vPointInSpace, vRayOrigin); double t = m3dDotProduct(vUnitRayDir, v); // This is the point on the ray vPointOnRay[0] = vRayOrigin[0] + (t * vUnitRayDir[0]); vPointOnRay[1] = vRayOrigin[1] + (t * vUnitRayDir[1]); vPointOnRay[2] = vRayOrigin[2] + (t * vUnitRayDir[2]); return m3dGetDistanceSquared(vPointOnRay, vPointInSpace); } // ditto above... but with floats float m3dClosestPointOnRay(M3DVector3f vPointOnRay, const M3DVector3f vRayOrigin, const M3DVector3f vUnitRayDir, const M3DVector3f vPointInSpace) { M3DVector3f v; m3dSubtractVectors3(v, vPointInSpace, vRayOrigin); float t = m3dDotProduct(vUnitRayDir, v); // This is the point on the ray vPointOnRay[0] = vRayOrigin[0] + (t * vUnitRayDir[0]); vPointOnRay[1] = vRayOrigin[1] + (t * vUnitRayDir[1]); vPointOnRay[2] = vRayOrigin[2] + (t * vUnitRayDir[2]); return m3dGetDistanceSquared(vPointOnRay, vPointInSpace); }
[ "drindking@gmail.com@0f1f08ab-4ab0-9d7d-a974-823501e1538f" ]
drindking@gmail.com@0f1f08ab-4ab0-9d7d-a974-823501e1538f
2f7e24c165d1e8a72feaefcd23ae68fb88189787
389f92dc3a47bed51466cb1106b8e12852b9f79c
/ isoftstone/src/hmi/edcc/resource.h
c0bb3aae284258e90c1931f04a518933af4c2b9d
[]
no_license
radtek/isoftstone
4dc99ea83c26c802e1eded1ce23aa7ebdce29a86
e1abede2913885a6374dfe9d1ab54aa85ed8e61f
refs/heads/master
2021-01-06T20:46:17.654521
2013-08-24T01:49:57
2013-08-24T01:49:57
41,403,225
3
4
null
null
null
null
GB18030
C++
false
false
1,555
h
#ifndef RESOURCE_H #define RESOURCE_H #include <string> #include <vector> #include <map> #include <QVector> #include <QVariant> #include <QMutex> #include <QMutexLocker> /* 用于保存内存数据 对于界面数据的显示,有两种策略: 其一:接收线程根据规约处理完报文数据后直接Post给主界面,这样可以节省内存操作,但是此操作不易保存历史数据。 其二:接收线程根据规约处理完报文数据后放到内存保存,由主界面定时器主动去获取数据并显示,此处不需要另外线程。 另外,历史线程也会定时去获取内存数据并保存到文件中,并且根据时间进行各类统计。 还有一个线程负责处理上位机实时数据请求,并且将数据打包发给上位机。 */ struct SMeasureInfo { SMeasureInfo() { resourceID = 0; type = -1; } quint64 resourceID; float upper; float lower; QString name; int type; QVariant value; }; class CResource { public : static CResource* instance(); void init(); SMeasureInfo getInfo(quint64 id); QVariant getValue(quint64 id); QMap<quint64,QVariant> getValues(const QList<quint64>& vecIDs); void setValue(quint64 id ,const QVariant& value); QMap<quint64,SMeasureInfo> getValues(); QList<quint64> getResourceIDs(); void clear(); private: CResource(){}; private: QMap<quint64,SMeasureInfo> m_MeaInfoMap; QMutex m_Mutex; static CResource* s_Resource; }; #endif
[ "liuruigong@gmail.com" ]
liuruigong@gmail.com
361f1c9dab7700fdc399a4846a72f80fdc9a1f3b
988f74fd1f5e04811c19137a239e9c2fecdae6be
/segmentation/GridMap.h
93a32afee56ece50d68ae485dffb2718d4c8d1b8
[]
no_license
aemarkov/lidar-road-segmentation
fadf9d1c915341bf3ddad07dc1a7593582dd818e
6643ebe7eb0cd54d84d00c4c8515b561ae031583
refs/heads/master
2023-09-01T07:09:58.583045
2020-08-03T08:55:43
2020-08-03T08:55:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,805
h
// // Created by garrus on 13.12.18. // #ifndef ROAD_SEGMENTATION_GRIDMAP_H #define ROAD_SEGMENTATION_GRIDMAP_H #include <vector> #include <pcl/common/common_headers.h> #include <GridCoord.h> #include <Grid.h> enum Obstacle { UNKNOW = 0, FREE, OBSTACLE }; /** * \brief 2D Occupancy Grid with some additional information * * - Store 2D occupancy grid * - Store original point cloud * - Store 2D grid coordinate of each point in point cloud * (e.g. for visualization purposes) * - Store size, cell size, min/max of bounding box * * @tparam TPoint pcl::PointCloud template argument */ template <class TPoint> class GridMap { public: /** * \brief Initialize the empty grid map of given PointCloud * * Calculate the required grid size based on cell size and point cloud size. * Do not perform placing points into the cells. * * @param cloud * @param cell_size */ GridMap(const typename pcl::PointCloud<TPoint>::ConstPtr& cloud, float cell_size, TPoint min, TPoint max) : CELL_SIZE(cell_size), _min(min), _max(max), _rows((size_t)ceil((max.x - min.x) / cell_size)), _cols((size_t)ceil((max.y - min.y) / cell_size)), _cloud(cloud), _point_cells(cloud->points.size()), _obstacles(_rows, _cols) { } GridMap(GridMap&& grid) : CELL_SIZE(grid.CELL_SIZE), _rows(grid._rows), _cols(grid._cols), _min(grid._min), _max(grid._max), _cloud(grid._cloud), _point_cells(std::move(grid._point_cells)), _obstacles(std::move(grid._obstacles)) { } ~GridMap() { } Grid<Obstacle>& obstacles() { return _obstacles; } const Grid<Obstacle>& obstacles() const { return _obstacles; } TPoint& cloud_at(size_t index) { return _cloud->at(index); } const TPoint& cloud_at(size_t index) const { return _cloud->at(index); } typename pcl::PointCloud<TPoint>::Ptr cloud(){ return _cloud; } size_t cloud_size() const {return _cloud->points.size(); } GridCoord& point_cell(size_t index) { return _point_cells[index]; } GridCoord point_cell(size_t index) const { return _point_cells[index]; } const TPoint& min() const { return _min; } const TPoint& max() const { return _max; } size_t rows() const { return _rows; } size_t cols() const { return _cols; } GridCoord size() const { return GridCoord(_rows, _cols); } float cell_size() const { return CELL_SIZE; } private: const float CELL_SIZE; const TPoint _min, _max; const size_t _rows, _cols; typename pcl::PointCloud<TPoint>::ConstPtr _cloud; std::vector<GridCoord> _point_cells; // coord of cell for each point Grid<Obstacle> _obstacles; }; #endif //ROAD_SEGMENTATION_GRIDMAP_H
[ "markovalex95@gmail.com" ]
markovalex95@gmail.com
0f7800e97a9c6320a7ca1146acb63132880a4650
b90e5696800d2b8a944cdf9f61fac0bda0019aca
/src/devices/atmega32/aspects/debug.cpp
3c72c1c72a7cac7ade4936b8d29642501c08eb3b
[]
no_license
goc9000/megas2
7031024fc8c190c09f787f3e1679b80025f59453
2cdc4ed193732322f1d79aa7c742c07a7e3057c5
refs/heads/master
2021-12-25T13:55:34.947943
2013-05-21T00:11:15
2013-05-21T00:11:15
4,712,374
0
0
null
null
null
null
UTF-8
C++
false
false
3,792
cpp
#include <inttypes.h> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctype.h> #include <algorithm> #include <fcntl.h> #include <unistd.h> #include "utils/bit_macros.h" #include "utils/fail.h" #include "devices/atmega32/atmega32.h" #include "devices/atmega32/defs.h" using namespace std; void Atmega32::_dumpRegisters() { char const *SREG_REP = "ithsvnzc"; char sreg_rep[9]; printf("--- Registers ---\n"); for (int i=0; i<IO_BASE; i++) { printf("%c%02d", i ? ' ' : 'r', i); } printf("\n"); for (int i=0; i<IO_BASE; i++) { printf(" %02x", this->core.ram[i]); } printf("\n"); uint8_t sreg = this->core.ram[REG_SREG]; for (int i=0; i<8; i++) sreg_rep[i] = bit_is_set(sreg, 7-i) ? toupper(SREG_REP[i]) : SREG_REP[i]; sreg_rep[8] = 0; printf("X=%04x Y=%04x Z=%04x SP=%04x SREG=%02x (%s)\n", this->_get16BitReg(REG16_X), this->_get16BitReg(REG16_Y), this->_get16BitReg(REG16_Z), this->_get16BitReg(REG16_SP), sreg, sreg_rep); printf("Last fetch @PC=%04x (in bytes: %04x)\n", this->core.last_inst_pc, 2*this->core.last_inst_pc); } void Atmega32::_dumpSram() { const int BYTES_PER_BLOCK = 32; int size = RAM_SIZE - SRAM_BASE; int blocks = (size + BYTES_PER_BLOCK-1) / BYTES_PER_BLOCK; printf("--- SRAM contents ---\n"); printf(" "); for (int i = 0; i < BYTES_PER_BLOCK; i++) printf("%c%02x", i ? ' ' : '+', i); printf("\n"); for (int i = 0; i < blocks; i++) { int addr = i * BYTES_PER_BLOCK; printf("%04x:", addr); int count = min(size - addr, BYTES_PER_BLOCK); for (int j = 0; j < count; j++) printf(" %02x", this->core.ram[SRAM_BASE + addr + j]); for (int j = BYTES_PER_BLOCK; j < count; j++) printf(" "); printf(" | "); for (int j = 0; j < count; j++) { uint8_t byte = this->core.ram[SRAM_BASE + addr + j]; printf("%c", ((byte >= 32) && (byte <= 126)) ? byte : '.'); } printf("\n"); } } void Atmega32::_dumpPortRead(const char *header, uint8_t port, int8_t bit, uint8_t &value) { char buffer[1024]; int len = 0; len += sprintf(buffer + len, "%04x: ", this->core.last_inst_pc * 2); if (header) { len += sprintf(buffer + len, "%s: ", header); } len += sprintf(buffer + len, "READ from %s", PORT_NAMES[port]); if (bit != -1) { len += sprintf(buffer + len, ":%d", bit); } len += sprintf(buffer + len, " = "); if (bit == -1) { len += sprintf(buffer + len, "%02x", value); } else { len += sprintf(buffer + len, "%d (full: %02x)", bit_is_set(value, bit), value); } buffer[len] = 0; printf("%s\n", buffer); } void Atmega32::_dumpPortWrite(const char *header, uint8_t port, int8_t bit, uint8_t value, uint8_t prev_val, uint8_t cleared) { char buffer[1024]; int len = 0; len += sprintf(buffer + len, "%04x: ", this->core.last_inst_pc * 2); if (header) { len += sprintf(buffer + len, "%s: ", header); } len += sprintf(buffer + len, "WRITE to %s", PORT_NAMES[port]); if (bit != -1) { len += sprintf(buffer + len, ":%d", bit); } len += sprintf(buffer + len, " : "); if (bit == -1) { len += sprintf(buffer + len, "%02x->%02x", prev_val, value); } else { len += sprintf(buffer + len, "%d->%d (full: %02x->%02x)", bit_is_set(prev_val, bit), bit_is_set(value, bit), prev_val, value); } if (cleared) { len += sprintf(buffer + len, " cleared:%02x", cleared); } buffer[len] = 0; printf("%s\n", buffer); }
[ "goc9000@gmail.com" ]
goc9000@gmail.com
70011f1ff16ef3aca267296a94a6d92ff5c1cc63
9ba354f2dfb6755864560e258d1a6e9970641b0c
/TCore/dllmain.cpp
0d81e05b5d05895ebe6fee5da03d9540ef39f02c
[ "MIT" ]
permissive
thirty30/Muffin
b808d75b1b5bb78dc463c64ab159d889cc873e79
06db87761be740408457728a40d95cdc8ec05108
refs/heads/master
2020-08-04T02:02:34.009543
2020-04-14T19:56:58
2020-04-14T19:56:58
211,962,180
5
0
null
null
null
null
UTF-8
C++
false
false
269
cpp
#include "stdafx.h" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
[ "402050805@qq.com" ]
402050805@qq.com
d441aaf2267674dffec805960f9c1098e60cccbf
79619f59853e6b5ccebf1e79784bb8c19bb964e5
/C++/neststructure.cpp
814427cf7760426595c1b113778be47a3949ed7f
[]
no_license
Muzummil/Software-Development-Work
a738efcbede29d0edca0fcf63eabc70ce7151a32
d11f2b4eeb1bc5121ca9db1628c0bd805ef609ac
refs/heads/master
2020-12-14T11:54:49.508737
2020-01-23T20:08:52
2020-01-23T20:08:52
234,732,158
0
1
null
null
null
null
UTF-8
C++
false
false
614
cpp
#include <iostream> #include <conio.h> #include <string.h> using namespace std; struct time{ short second,minut; string h; }; struct date{ int day; int month,year; time x; }; int main() { date d1; d1.x.h=="muzummil"; cout<<"name 1 is"<<d1.x.h; cout<<"enter your name";cin>>d1.x.h; cout<<"name 2 is"<<d1.x.h; cout<<"enter second"; cin>>d1.x.second; cout<<"enter day"; cin>>d1.day; cout<<"enter minut"; cin>>d1.x.minut; cout<<"enter year";cin>>d1.year; cout<<d1.x.second<<endl; cout<<"year is"<<d1.year; cout<<"minut is"<<d1.x.minut; cout<<d1.day; getch(); }
[ "noreply@github.com" ]
Muzummil.noreply@github.com
1659c0fadf15126da87ada072e243a2b77292272
15c3c9dfcb69a534c5c392c2983b0158aa809dd7
/InputManager.cpp
db864be61311d3e4f06973f6fc7e56b43af98cf3
[]
no_license
adrianhartanto0/AE2CPP
5389b257514515de74ab430b0025beb329b0c2bc
e45398bffff287a8d334bb6fd79124093ffef548
refs/heads/master
2021-01-10T14:52:23.603115
2016-05-09T06:16:21
2016-05-09T06:16:21
54,475,510
0
0
null
null
null
null
UTF-8
C++
false
false
832
cpp
// // InputManager.cpp // Space // // Created by Ericko Hartanto on 4/29/16. // Copyright © 2016 adrian. All rights reserved. // #include "InputManager.h" InputManager::InputManager(){ this->mouseX = 0; this->mouseY = 0; this->key = nullptr; } void InputManager::setMouseX(int val){ this->mouseX = val; } void InputManager::setMouseY(int val){ this->mouseY = val; } void InputManager::setKey(const char *k){ this->key = k; } int InputManager::getMouseX(){ return this->mouseX; } int InputManager::getMouseY(){ return this->mouseY; } const char * InputManager::getKey(){ return this->key; } void InputManager::clearKey(){ this->key = nullptr; } void InputManager::setClickedMouse(bool val){ this->clicked = val; } bool InputManager::getClick(){ return this->clicked; }
[ "erickohartanto@Erickos-MacBook-Pro.local" ]
erickohartanto@Erickos-MacBook-Pro.local
fe047f98933efe6113ed62a8707a2c5303ddbb00
535e44e24d60879d5d654aada6d48f1d932a1e9f
/desiredimpl/01-basic-scenario/timer_proxy.cpp
24a8016cb2ef5e162b8bb7ef75ef025c6dc2bd6c
[]
no_license
glucktv/dboost
6ff4c93d3e509c52b0a4eb44319f2f0b3ddae6c4
d1a0eb1b4ec1c2af2ad2b29ffa23157f845b39ab
refs/heads/master
2016-09-06T11:15:00.377118
2015-03-27T05:07:29
2015-03-27T05:07:29
17,452,491
1
0
null
null
null
null
UTF-8
C++
false
false
2,081
cpp
#include <timer_proxy.h> #include <dbus/dbus.h> #include <exception.h> #include <iostream> #include <serializer.h> namespace dboost_test { const char* timer_proxy::s_ifc_name = "org.dboost.timer"; const int TIMEOUT_MS = 5000; timer_proxy::timer_proxy(dboost::dbus_ptr<DBusConnection> conn, const std::string& bus_name, const std::string& obj_name) : m_connection(conn), m_bus_name(bus_name), m_obj_name(obj_name) { } // here arguments are called a0 .. aN to avoid naming clashes, result is called r long timer_proxy::add_timer(const long a0) { // create caller (name, arguments) dboost::dbus_ptr<DBusMessage> msg(DBOOST_CHECK(dbus_message_new_method_call(m_bus_name.c_str(), m_obj_name.c_str(), s_ifc_name, "add_timer"))); dboost::oserializer os(msg.get()); os & a0; // call synchronously dboost::error err; dboost::dbus_ptr<DBusMessage> reply(dbus_connection_send_with_reply_and_block(m_connection.get(), msg.get(), TIMEOUT_MS, &err)); // check if there was an error DBOOST_CHECK_WITH_ERR(reply, err); if (dbus_message_get_type(reply.get()) == DBUS_MESSAGE_TYPE_ERROR) { throw dboost::exception(dbus_message_get_error_name(reply.get())); } // unpack output parameters dboost::iserializer is(reply.get()); long r; is & r; return r; } void timer_proxy::remove_timer(const long a0) { // create caller (name, arguments) dboost::dbus_ptr<DBusMessage> msg(DBOOST_CHECK(dbus_message_new_method_call(m_bus_name.c_str(), m_obj_name.c_str(), s_ifc_name, "remove_timer"))); dboost::oserializer os(msg.get()); os & a0; // call synchronously dboost::error err; dboost::dbus_ptr<DBusMessage> reply(dbus_connection_send_with_reply_and_block(m_connection.get(), msg.get(), TIMEOUT_MS, &err)); // check if there was an error DBOOST_CHECK_WITH_ERR(reply, err); if (dbus_message_get_type(reply.get()) == DBUS_MESSAGE_TYPE_ERROR) { throw dboost::exception(dbus_message_get_error_name(reply.get())); } } } // namespace dboost
[ "yu_stas@hotbox.ru" ]
yu_stas@hotbox.ru
9f0f0ffbb5f2fe641876d5c5bc9c7d3cc579a0b4
cccd77053ce93010420e72a9cb98bbcde3441c76
/level1/p08_hanoi/hanoi.cpp
6ede4ad6341c2b921ff86a3bf73f1ef44d2ceee7
[ "MIT" ]
permissive
liaohui-2002/c2020
e02d8e8fc6534ec6217c26465d70413de5e600a5
be2d1437260c0c9f096d9580afd72452087b1f2a
refs/heads/master
2022-04-09T21:23:25.988797
2020-03-24T14:24:11
2020-03-24T14:24:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define For(x,a,b) for(x=a;x<=b;x++) int i,i1,i2; void hanoi(int n,char a,char b,char c); int main(void) { int n; printf("Please input the number of the disk:\n"); scanf("%d",&n); hanoi(n,'a','b','c'); return 0; } void hanoi(int n,char a,char b,char c) { if(n==1)printf("%c --> %c\n",a,b); else{ hanoi(n-1,a,c,b); printf("%c --> %c\n",a,b); hanoi(n-1,c,b,a); } }
[ "15091591733@126.com" ]
15091591733@126.com
8c39665e4e03fa38f1c72c4d27e5785937deda25
ac75560a56c0698ff098251f8d4bc5bf2a0dc3db
/examples/FlashErase/FlashErase.ino
16af96fa62f5790da6b83d37865d79e04dc31ee7
[ "MIT" ]
permissive
Hansen0314/Seeed_Arduino_SFUD
e0fdc58f356dfea9a4a0b7c5b0a39ca439b12d4a
d2a3a1776b3f54a71452051daa7ff97d811dc4bd
refs/heads/master
2022-07-17T13:33:27.460560
2020-05-13T08:14:41
2020-05-13T08:14:41
259,585,337
1
0
MIT
2020-04-28T09:03:35
2020-04-28T09:03:34
null
UTF-8
C++
false
false
896
ino
#include <sfud.h> #define SFUD_DEMO_TEST_BUFFER_SIZE 1024 static uint8_t sfud_demo_test_buf[SFUD_DEMO_TEST_BUFFER_SIZE]; static void sfud_demo(uint32_t addr, size_t size, uint8_t *data); #define SERIAL Serial #ifdef ARDUINO_ARCH_SAMD #undef SERIAL Serial #define SERIAL SerialUSB #endif void setup() { SERIAL.begin(115200); while(!SERIAL) {}; while(!(sfud_init() == SFUD_SUCCESS)); /* erase test */ const sfud_flash *flash = sfud_get_device_table() + 0; uint32_t addr = 0; size_t size = sizeof(sfud_demo_test_buf); uint8_t result = sfud_erase(flash, addr, size); if (result == SFUD_SUCCESS) { printf("Erase the %s flash data finish. Start from 0x%08X, size is %ld.\r\n", flash->name, addr, size); } else { printf("Erase the %s flash data failed.\r\n", flash->name); } } void loop() { }
[ "595355940@qq.com" ]
595355940@qq.com
8511193ee147fa83e17a9c52dfb659a87628737f
9aee810d0d9d72d3dca7920447872216a3af49fe
/AtCoder/ABC/100-199/ABC141/abc141_e.cpp
d73963e78363014bf6c03049ad80c8c4b69ffbca
[]
no_license
pulcherriman/Programming_Contest
37d014a414d473607a11c2edcb25764040edd686
715308628fc19843b8231526ad95dbe0064597a8
refs/heads/master
2023-08-04T00:36:36.540090
2023-07-30T18:31:32
2023-07-30T18:31:32
163,375,122
3
0
null
2023-01-24T11:02:11
2018-12-28T06:33:16
C++
UTF-8
C++
false
false
4,531
cpp
#include <bits/stdc++.h> #if defined(ONLINE_JUDGE) || defined(_DEBUG) #include <atcoder/all> using namespace atcoder; #endif using namespace std; using ll=long long; using ull=unsigned long long; using vb=vector<bool>; using vvb=vector<vb>; using vd=vector<double>; using vvd=vector<vd>; using vi=vector<int>; using vvi=vector<vi>; using vl=vector<ll>; using vvl=vector<vl>; using pll=pair<ll,ll>; using tll=tuple<ll,ll>; using tlll=tuple<ll,ll,ll>; using vs=vector<string>; #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define rep(i,n) range(i,0,n) #define rrep(i,n) rrange(i,0,n) #define range(i,a,n) for(ll i=((ll)a);i<((ll)n);++i) #define rrange(i,a,n) for(ll i=((ll)n-1);i>=((ll)a);--i) #define repsq(i,n) for(ll i=0;i*i<=n;++i) #define LINF ((ll)1ll<<60) #define INF ((int)1<<30) #define EPS (1e-9) #define MOD (1000000007ll) #define fcout(a) cout<<setprecision(a)<<fixed #define PI (3.1415926535897932384) int dx[]={1,0,-1,0,1,-1,-1,1},dy[]={0,1,0,-1,1,1,-1,-1}; template<class T>bool chmax(T&a,T b){if(a<b){a=b; return true;}return false;} template<class T>bool chmin(T&a,T b){if(a>b){a=b; return true;}return false;} template<class S>S sum(vector<S>&a){return accumulate(all(a),S());} template<class S>S max(vector<S>&a){return *max_element(all(a));} template<class S>S min(vector<S>&a){return *min_element(all(a));} //output template<class T>struct hasItr{ template<class U>static constexpr true_type check(class U::iterator*); template<class U>static constexpr false_type check(...); static constexpr bool v=decltype(check<T>(nullptr))::value; }; template<>struct hasItr<string>{static constexpr bool v=false;}; template<class T>void puta(T&t,false_type,ostream&os,char el){os<<t;} template<class T>void puta(T&t,true_type,ostream&os,char el){ constexpr bool h=hasItr<typename T::value_type>::v; bool F=true,I; for(auto&i:t){ if(!F)os<<' '; puta(i,bool_constant<h>(),os,el); F=I=h; } if(!I)os<<el; } template<class T>void puta(const T&t, ostream&os=cout, char el='\n'){ puta(t,bool_constant<hasItr<T>::v>(),os,el); if(!hasItr<T>::v)os<<el; } template<class H,class...T>void puta(const H&h,const T&...t){cout<<h<<' ';puta(t...);} template<size_t i,class...T>void puta(tuple<T...>const&t, ostream&os){ if constexpr(i==sizeof...(T)-1)puta(get<i>(t),os); else{os<<get<i>(t)<<' ';puta<i+1>(t,os);} } template<class...T>void puta(tuple<T...>const&t, ostream&os=cout){puta<0>(t,os);} template<class T>void dump(const T&t){puta(t,cerr);} template<class H,class...T>void dump(const H&h,const T&...t){cerr<<h<<' ';dump(t...);} template<class...T>void dump(tuple<T...>const&t){puta(t,cerr);} template<class S,class T>constexpr ostream&operator<<(ostream&os,pair<S,T>p){ os<<'['<<p.first<<", "; if constexpr(hasItr<T>::v)puta(p.second,bool_constant<true>(),os,']'); else os<<p.second<<']'; return os; }; template<class...T>constexpr ostream&operator<<(ostream&os,tuple<T...>t){ puta(t,os); return os; } void YN(bool b){puta(b?"YES":"NO");} void Yn(bool b){puta(b?"Yes":"No");} #ifndef _DEBUG #define dump(...) #endif //input template<class S>auto&operator>>(istream&is,vector<S>&t){for(S&a:t)cin>>a;return is;} // #define geta(t,n,...) t n;cin>>n;geta(t,__VA_ARGS__) // #define vec(t,a,h,...) vector<t>a(h);rep(i,n)a[i]=t(__VA_ARGS__);rep(i,n)cin>>a[i] template<typename...S>void geta_(S&...s){((cin>>s),...);} #define geta(t,...) t __VA_ARGS__;geta_(__VA_ARGS__) class RollingHash{ using u64=uint_fast64_t; using i128=__int128_t; public: string str; RollingHash(const string&str):str(str){ h.resize(str.size()+1,0); p.resize(str.size()+1,1); rep(i,str.size()){ p[i+1]=mul(p[i],base); h[i+1]=mul(h[i],base)+xorshift(str[i]+1); if(h[i+1]>=mod)h[i+1]-=mod; } } u64 get()const{return h.back();} u64 get(int l,int r)const{u64 v=mod+h[r]-mul(h[l],p[r-l]);return v<mod?v:v-mod;} private: vector<u64> h,p; static constexpr u64 mod=(1ull<<61)-1; static constexpr u64 base=36000*__TIME__[0]+3600*__TIME__[1]+600*__TIME__[3]+60*__TIME__[4]+10*__TIME__[6]+__TIME__[7]; static constexpr u64 mul(i128 a,i128 b){i128 t=a*b;t=(t>>61)+(t&mod);return t<mod?t:t-mod;} static constexpr int xorshift(int x){x^=x<<13;x^=x>>17;return x^=x<<5;} }; int main(){ cin.tie(0); ios::sync_with_stdio(false); geta(ll, n); geta(string,s); ll ans=0; RollingHash hash(s); rep(i,s.size()){ range(j,i,s.size()){ while(i + ans < j and j + ans < n) { if(hash.get(i, i + ans + 1) != hash.get(j, j + ans + 1)) break; ans++; } } } puta(ans); return 0; }
[ "tsukasawa_agu@yahoo.co.jp" ]
tsukasawa_agu@yahoo.co.jp
27940e4b21f3ca69109feb6deab118700e13be7f
c3f781286ebf1832ee4809678c1eda1f4755442a
/HashTable.h
ff86645c5c13575177a06e6a1a486060ab08bb99
[]
no_license
shunjizhan/Social-Network
faffe94cbcbf9c1c654dde6d34e17167a7e56c6e
725c95bf653aa8b6247d3d29a68e8212fd010bfc
refs/heads/master
2021-06-15T17:45:33.569851
2017-03-29T01:44:56
2017-03-29T01:44:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
493
h
#include <vector> #include "Node.h" using namespace std; class HashTable { public: const static int TABLE_SIZE = 211; HashTable(); void insert(string name, int index, vector<string> friends); int search(string name); // find index in the hash table int hash(string name); void addFriend(string friend1, string friend2); void printAll(); int getUserIndex(string name); void printUser(vector<string> info); Node* getNode(int index); private: Node** table; };
[ "shunjizhan@umail.ucsb.edu" ]
shunjizhan@umail.ucsb.edu
601f6e2cc0c87784ac59e95234b74e0fc76ea5db
6097e7cd1cd311ef13bd166d6323bbb749385291
/CCI/cci/cci/URLify.cpp
11f1f8243ba212248f3c9d7e20f07abf3c7b7836
[]
no_license
ysripath/CPP
a9a33f6d89c759b68def91df084915cf78f525fd
009bb94561b267c87b5ab5b38fbddcd1670a42a5
refs/heads/master
2020-03-26T09:57:47.602806
2019-04-07T01:33:01
2019-04-07T01:33:01
144,774,285
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
#include <bits/stdc++.h> using namespace std; void util(string& str) { int l = str.length(); l--; int i = l; while (i >= 0) { if (str[i] == ' ') i--; else break; } while (i >= 0) { if (str[i] != ' ') { str[l--] = str[i--]; continue; } else { str[l--] = '0'; str[l--] = '2'; str[l--] = '%'; i--; continue; } } } int main() { //ios::sync_with_stdio(false); //cin.tie(NULL); cout << "Enter string \n"; string str = ""; char c; while (cin.get(c)) { if (c == '\n') break; str += c; } util(str); cout << str << "\n"; return 0; }
[ "yuvarajsripathi91@gmail.com" ]
yuvarajsripathi91@gmail.com
4598f3ac3e28b6a6c9258d192f14ce928b2e5695
83bab97601870553188e19700027457c8b0aaa34
/include/myslam/camera.h
7bbb23df5a0ca27fad1e0600c568efb8a992fcd3
[]
no_license
yxtwl94/Slam_demo
d31149df72a2db95c79dd7146e368e98e220226e
10b39352c8237b4d91d63c36b0a45af904b22822
refs/heads/master
2020-05-27T00:36:10.989504
2019-05-24T13:32:58
2019-05-24T13:32:58
183,479,015
0
0
null
null
null
null
UTF-8
C++
false
false
918
h
#ifndef CAMERA_H #define CAMERA_H #include "myslam/common_include.h" namespace myslam{ using namespace std; class Camera{ public: typedef shared_ptr<Camera> Ptr; float fx_, fy_, cx_, cy_,depth_scale_; Camera(); Camera( float fx ,float fy,float cx,float cy,float depth_scale=0): fx_(fx),fy_(fy),cx_(cx),cy_(cy),depth_scale_(depth_scale) {}; Vector3d world2camera( const Vector3d& p_w, const SE3& T_c_w ); Vector3d camera2world( const Vector3d& p_c, const SE3& T_c_w ); Vector2d camera2pixel( const Vector3d& p_c ); Vector3d pixel2camera( const Vector2d& p_p, double depth=1 ); Vector3d pixel2world ( const Vector2d& p_p, const SE3& T_c_w, double depth=1 ); Vector2d world2pixel ( const Vector3d& p_w, const SE3& T_c_w ); }; } #endif
[ "yxtwl95@hotmail.com" ]
yxtwl95@hotmail.com
6f2e51dc609330ecf74fae09a979054e42312be4
232fa6f856936c984e218371d53a0c5f63ac8ddc
/rbf/rbfm.h
18e9a17d152390559c6f00be33d726e2ce3746d8
[]
no_license
xianpeim/CompSci222-database-implementation
6528ae408459c1c754d7ed7e6bc982b8b783004a
c983264a607081213c167b981c32e054c8f8eb9d
refs/heads/master
2020-11-28T16:13:18.964400
2019-12-24T08:56:18
2019-12-24T08:56:18
229,864,628
1
0
null
null
null
null
UTF-8
C++
false
false
21,134
h
#ifndef _rbfm_h_ #define _rbfm_h_ #include <string.h> #include <vector> #include <cmath> #include "pfm.h" #define epsilon 0.00005 // for float comparison #define DEBUG 0 // 1 show all debug msg. 0 dont show. #define DEBUGUNIT 0 // 1 show all unit debug msg. 0 dont show. #define DEBUGFREE 0 // 1 show all unit free msg. 0 dont show. //# TODO: add func call to handle memory leak. free func already defined. // Record ID typedef struct { unsigned pageNum; // page number unsigned slotNum; // slot number in the page } RID; // Attribute typedef enum { TypeInt = 0, TypeReal, TypeVarChar } AttrType; typedef unsigned AttrLength; struct Attribute { std::string name; // attribute name AttrType type; // attribute type AttrLength length; // attribute length }; // Comparison Operator (NOT needed for part 1 of the project) typedef enum { EQ_OP = 0, // = LT_OP, // < LE_OP, // <= GT_OP, // > GE_OP, // >= NE_OP, // != NO_OP // no condition } CompOp; class Field{ public: Field(){ } ~Field(){ } Attribute attr; union { int int_val; float real_val; char* varchar_val; }; }; class IntField: public Field{ public: IntField():Field(){} ~IntField(){} }; class RealField: public Field{ public: RealField():Field(){} ~RealField(){} }; class VarcharField: public Field{ public: VarcharField():Field(){} ~VarcharField(){} }; struct RecordInfo { int offset; int length; }; class Record{ public: Record(){ total_size = 0; } Record(const std::vector<Attribute> &recordDescriptor, const void* data){ if(DEBUG) std::cout << "record constructor 1"<< std::endl; field_size = 0; total_size = 0; attrs = recordDescriptor; null_size = ceil((double) recordDescriptor.size() / CHAR_BIT); null_val = (unsigned char*) malloc(sizeof(null_size)); buffer = NULL; memcpy(null_val, data,null_size); if(null_size == 0 or null_val == NULL){ std::cerr << "Null value cannot be read." << std::endl; } int offset = null_size; for(int i=0; i<recordDescriptor.size(); i++){ int null_count_in_bit = i%8; int null_count_in_byte = i/8; if(!(null_val[null_count_in_byte] & (unsigned)1 << (unsigned)(7-null_count_in_bit))){ // check if corresponding bit is 1. switch (recordDescriptor[i].type){ case TypeInt:{ IntField int_field; int_field.attr = recordDescriptor[i]; memcpy(&int_field.int_val, (char*)data+offset, recordDescriptor[i].length); fields.push_back(int_field); field_size += recordDescriptor[i].length; offset += recordDescriptor[i].length; break; } case TypeReal:{ RealField real_field; real_field.attr = recordDescriptor[i]; memcpy(&real_field.real_val, (char*)data+offset, recordDescriptor[i].length); fields.push_back(real_field); field_size += recordDescriptor[i].length; offset += recordDescriptor[i].length; break; } case TypeVarChar:{ int length; memcpy(&length, (char*)data+offset, sizeof(int)); offset += sizeof(int); VarcharField varchar_field; varchar_field.attr = recordDescriptor[i]; varchar_field.attr.length = length; varchar_field.varchar_val = (char*)malloc(length); memcpy(varchar_field.varchar_val, (char*)data+offset, length); fields.push_back(varchar_field); field_size += length + sizeof(int); offset += length; break; } default:{ std::cerr << "Date type wrong. it should be int/real/varchar" << std::endl; } } } else{ field_size += recordDescriptor[i].length; } } total_size = null_size + field_size; } Record(const std::vector<Attribute> &recordDescriptor, char* in_buffer, RecordInfo ri){ if(DEBUG) std::cout << "record constructor 2"<< std::endl; if(DEBUG) std::cout << ri.length<< std::endl; if(DEBUG) std::cout << ri.offset<< std::endl; field_size = 0; total_size = 0; attrs = recordDescriptor; buffer = (char*) malloc(ri.length); memcpy(buffer, in_buffer+ri.offset, ri.length); null_size = ceil((double) recordDescriptor.size() / CHAR_BIT); null_val = (unsigned char*) malloc(sizeof(null_size)); memcpy(null_val, buffer, null_size); if(null_size == 0 or null_val == NULL){ std::cerr << "Null value cannot be read." << std::endl; } int offset = null_size; for(int i=0; i<recordDescriptor.size(); i++){ int null_count_in_bit = i%8; int null_count_in_byte = i/8; if(!(null_val[null_count_in_byte] & (unsigned)1 << (unsigned)(7-null_count_in_bit))){ // check if corresponding bit is 1. switch (recordDescriptor[i].type){ case TypeInt:{ //if(DEBUG) std::cout << "record constructor 2 bp0"<< std::endl; IntField int_field; int_field.attr = recordDescriptor[i]; memcpy(&int_field.int_val, (char*)buffer+offset, recordDescriptor[i].length); fields.push_back(int_field); field_size += recordDescriptor[i].length; offset += recordDescriptor[i].length; break; } case TypeReal:{ //if(DEBUG) std::cout << "record constructor 2 bp1"<< std::endl; RealField real_field; real_field.attr = recordDescriptor[i]; memcpy(&real_field.real_val, (char*)buffer+offset, recordDescriptor[i].length); fields.push_back(real_field); field_size += recordDescriptor[i].length; offset += recordDescriptor[i].length; break; } case TypeVarChar:{ int length; memcpy(&length, (char*)buffer+offset, sizeof(int)); //if(DEBUG) std::cout << "record constructor 2 bp4"<< std::endl; offset += sizeof(int); VarcharField varchar_field; varchar_field.attr = recordDescriptor[i]; varchar_field.attr.length = length; varchar_field.varchar_val = (char*)malloc(length); //if(DEBUG) std::cout << "record constructor 2 bp4.5: " << length << std::endl; memcpy(varchar_field.varchar_val, (char*)buffer+offset, length); //if(DEBUG) std::cout << "record constructor 2 bp5"<< std::endl; fields.push_back(varchar_field); field_size += length + sizeof(int); offset += length; break; } default:{ std::cerr << "Date type wrong. it should be int/real/varchar" << std::endl; } } } else{ field_size += recordDescriptor[i].length; offset += recordDescriptor[i].length; } } total_size = null_size+ field_size; if(DEBUG) std::cout << "record constructor 2 bp2"<< std::endl; } ~Record(){} std::vector<Attribute> attrs; std::vector<Field> fields; RID rid; int null_size; unsigned char* null_val; int total_size; int field_size; char* buffer; RC updateBuffer(); RC getData(void* data_out); RC getSpecificData(void *data_out, const std::vector<std::string> &attributeNames); int getActualByteForNullsIndicator(int fieldCount) { return ceil((double) fieldCount / CHAR_BIT); } RC freeMalloc(){ if(buffer!=NULL){ free(buffer); buffer = NULL; if(DEBUGFREE) std::cout << " record buffer freed"<< std::endl; } if(null_val!=NULL){ free(null_val); null_val = NULL; if(DEBUGFREE) std::cout << " record null val freed"<< std::endl; } for(int i=0; i<fields.size(); i++){ if(fields[i].attr.type == TypeVarChar and fields[i].varchar_val!=NULL){ free(fields[i].varchar_val); fields[i].varchar_val = NULL; } } if(DEBUGFREE) std::cout << " record fields freed"<< std::endl; return 0; } }; struct PageIndexInfo{ int offset; int free_byte; }; class PageIndex{ public: PageIndex(){ if(DEBUG) std::cout << "pageindex constructor 1"<< std::endl; num = 0; next = -1; buffer = (char*)malloc(PAGE_SIZE); } PageIndex(char* to_buffer){ if(DEBUG) std::cout << "pageindex constructor 2"<< std::endl; buffer = (char*) malloc(PAGE_SIZE); memcpy(buffer, to_buffer, PAGE_SIZE); memcpy(&num, buffer, sizeof(int)); memcpy(&next, buffer+ sizeof(int), sizeof(int)); int offset = 2* sizeof(int); for(int i = 0; i < num; i++){ PageIndexInfo pii; memcpy(&pii, buffer+offset, sizeof(PageIndexInfo)); infos.push_back(pii); offset += sizeof(PageIndexInfo); } } ~PageIndex(){} int num; int next; std::vector<PageIndexInfo> infos; char* buffer; RC updateBuffer(); RC freeMalloc(){ if(buffer!=NULL){ if(DEBUGFREE) std::cout << " page index buffer freed" << std::endl; free(buffer); buffer = NULL; } return 0; } }; class Page{ public: Page(){ if(DEBUG) std::cout << "page constructor 1"<< std::endl; buffer = (char*)malloc(PAGE_SIZE); } Page(char* buffer_in, const std::vector<Attribute> &recordDescriptor){ if(DEBUG) std::cout << "page constructor 2"<< std::endl; buffer = (char*)malloc(PAGE_SIZE); memcpy(buffer, buffer_in, PAGE_SIZE); memcpy(&free_offset, buffer+PAGE_SIZE- sizeof(int), sizeof(int)); memcpy(&num_record, buffer+PAGE_SIZE- 2*sizeof(int), sizeof(int)); if(DEBUG) std::cout << "num of record: "<< num_record << std::endl; int offset = PAGE_SIZE - 2*sizeof(int); for(int i=0; i<num_record; i++){ RecordInfo ri; offset -= sizeof(RecordInfo); memcpy(&ri, buffer+offset, sizeof(RecordInfo)); infos.push_back(ri); if(ri.offset <= -1){ Record record; records.push_back(record); continue; } Record record(recordDescriptor, buffer, ri); records.push_back(record); /*record.buffer = NULL; record.null_val = NULL; record.fields.clear();*/ } } ~Page(){} char* buffer; std::vector<Record> records; std::vector<RecordInfo> infos; int free_offset; int num_record; RC updateBuffer(); RC freeMalloc(){ if(buffer!=NULL){ if(DEBUGFREE) std::cout << " page buffer freed" << std::endl; free(buffer); buffer = NULL; } for(int i=0; i< records.size(); i++){ if(infos[i].offset <= -1) continue; records[i].freeMalloc(); } if(DEBUGFREE) std::cout << " page records freed" << std::endl; return 0; } }; /******************************************************************** * The scan iterator is NOT required to be implemented for Project 1 * ********************************************************************/ # define RBFM_EOF (-1) // end of a scan operator // RBFM_ScanIterator is an iterator to go through records // The way to use it is like the following: // RBFM_ScanIterator rbfmScanIterator; // rbfm.open(..., rbfmScanIterator); // while (rbfmScanIterator(rid, data) != RBFM_EOF) { // process the data; // } // rbfmScanIterator.close(); class RBFM_ScanIterator { public: RBFM_ScanIterator(){ cur_index = 0; } ~RBFM_ScanIterator() = default;; // Never keep the results in the memory. When getNextRecord() is called, // a satisfying record needs to be fetched from the file. // "data" follows the same format as RecordBasedFileManager::insertRecord(). RC getNextRecord(RID &rid, void *data) { //if(DEBUG) std::cout << "rids size: "<< rids.size() << std::endl; if(cur_index == rids.size()) return RBFM_EOF; rid.slotNum = rids[cur_index].slotNum; rid.pageNum = rids[cur_index].pageNum; if(DEBUG) std::cout<<"getting next record"<< std::endl; if(DEBUG) std::cout<<"rid scanned: " << rid.pageNum << " " << rid.slotNum << std::endl; char* buffer = (char*)malloc(PAGE_SIZE); fileHandle.readPage(rid.pageNum, buffer); Page page(buffer, recordDescriptor); //if(DEBUG) std::cout << "page infos size: " << page.infos.size() << std::endl; RecordInfo ri; memcpy(&ri, &page.infos[rid.slotNum], sizeof(RecordInfo)); if(ri.offset == -1) return -1; if(ri.offset < -1){ RID rid_point_to; rid_point_to.pageNum = ri.offset + 10000000; rid_point_to.slotNum = ri.length; return getNextRecord(rid_point_to, data); } Record record(recordDescriptor, buffer, ri); if(attrs_need.size() == 0){ record.getData(data); free(buffer); buffer = NULL; page.freeMalloc(); record.freeMalloc(); cur_index += 1; return 0; } else{ record.getSpecificData(data, attrs_need); free(buffer); buffer = NULL; page.freeMalloc(); record.freeMalloc(); cur_index += 1; return 0; } }; RC setFileHandle(FileHandle &fileHandle){ this->fileHandle = fileHandle; return 0; } RC setRecordDescriptor(const std::vector<Attribute> recordDescriptor){ this->recordDescriptor = recordDescriptor; return 0; } RC clear(){ cur_index = 0; rids.clear(); attrs_need.clear(); recordDescriptor.clear(); return 0; } RC setAttrsNeed(const std::vector<std::string> &attributeNames){ attrs_need = attributeNames; return 0; } RC close() { clear(); return 0; }; std::vector<RID> rids; int cur_index; FileHandle fileHandle; std::vector<Attribute> recordDescriptor; std::vector<std::string> attrs_need; }; class RecordBasedFileManager { public: static RecordBasedFileManager &instance(); // Access to the _rbf_manager instance RC createFile(const std::string &fileName); // Create a new record-based file RC destroyFile(const std::string &fileName); // Destroy a record-based file RC openFile(const std::string &fileName, FileHandle &fileHandle); // Open a record-based file RC closeFile(FileHandle &fileHandle); // Close a record-based file // Format of the data passed into the function is the following: // [n byte-null-indicators for y fields] [actual value for the first field] [actual value for the second field] ... // 1) For y fields, there is n-byte-null-indicators in the beginning of each record. // The value n can be calculated as: ceil(y / 8). (e.g., 5 fields => ceil(5 / 8) = 1. 12 fields => ceil(12 / 8) = 2.) // Each bit represents whether each field value is null or not. // If k-th bit from the left is set to 1, k-th field value is null. We do not include anything in the actual data part. // If k-th bit from the left is set to 0, k-th field contains non-null values. // If there are more than 8 fields, then you need to find the corresponding byte first, // then find a corresponding bit inside that byte. // 2) Actual data is a concatenation of values of the attributes. // 3) For Int and Real: use 4 bytes to store the value; // For Varchar: use 4 bytes to store the length of characters, then store the actual characters. // !!! The same format is used for updateRecord(), the returned data of readRecord(), and readAttribute(). // For example, refer to the Q8 of Project 1 wiki page. // Insert a record into a file RC insertRecord(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const void *data, RID &rid); // Read a record identified by the given rid. RC readRecord(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const RID &rid, void *data); // Print the record that is passed to this utility method. // This method will be mainly used for debugging/testing. // The format is as follows: // field1-name: field1-value field2-name: field2-value ... \n // (e.g., age: 24 height: 6.1 salary: 9000 // age: NULL height: 7.5 salary: 7500) RC printRecord(const std::vector<Attribute> &recordDescriptor, const void *data); /***************************************************************************************************** * IMPORTANT, PLEASE READ: All methods below this comment (other than the constructor and destructor) * * are NOT required to be implemented for Project 1 * *****************************************************************************************************/ // Delete a record identified by the given rid. RC deleteRecord(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const RID &rid); // Assume the RID does not change after an update RC updateRecord(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const void *data, const RID &rid); // Read an attribute given its name and the rid. RC readAttribute(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const RID &rid, const std::string &attributeName, void *data); // Scan returns an iterator to allow the caller to go through the results one by one. RC scan(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const std::string &conditionAttribute, const CompOp compOp, // comparision type such as "<" and "=" const void *value, // used in the comparison const std::vector<std::string> &attributeNames, // a list of projected attributes RBFM_ScanIterator &rbfm_ScanIterator); RC insertInNewPage(FileHandle& fileHandle, Record& record, PageIndex& pi, RID& rid, int& num_page); RC addNewPageIndex(FileHandle& fileHandle, int &num_page); RC findAvailPage(FileHandle& fileHandle, PageIndex& pi, Record& record, int& avail_page_num); RC insertToExistingPage(FileHandle& fileHandle, const std::vector<Attribute> &recordDescriptor, int avail_page_num, Record& record, PageIndex& pi, int found_pageIndex_index , RID& rid); RC updatePageIndex(FileHandle &fileHandle, RID& rid, int data_length); RC deleteRecordWithPage(FileHandle &fileHandle, const std::vector<Attribute> &recordDescriptor, const RID &rid, Page &page); public: int num_of_pageIndex; int cur_pageIndex; protected: RecordBasedFileManager(); // Prevent construction ~RecordBasedFileManager(); // Prevent unwanted destruction RecordBasedFileManager(const RecordBasedFileManager &); // Prevent construction by copying RecordBasedFileManager &operator=(const RecordBasedFileManager &); // Prevent assignment private: static RecordBasedFileManager *_rbf_manager; static PagedFileManager& _pf_manager; }; #endif
[ "noreply@github.com" ]
xianpeim.noreply@github.com
151f7625adf5a148b23df572275d53dee59f434e
6e09bfc1f306d1ea8aff2464ab001d45dd4a996b
/ElectionCopy2/DistrictResult.cpp
fe824a867c50511796c340a4d006f9de695b2219
[]
no_license
avivmor2103/ElectionSystemProject
ac95815e406af45a04c65a6d02ac2e9588b544de
7dd8b25a6f4869dcfe73ac4dae297a6fb424b102
refs/heads/master
2023-04-04T21:02:15.438448
2021-04-20T17:54:40
2021-04-20T17:54:40
356,373,503
0
0
null
null
null
null
UTF-8
C++
false
false
3,606
cpp
#include "DistrictResult.h" DistrictResult::DistrictResult() { this->lSize = 0; this->phSize = 1; try { result = new DistrictVotes[phSize]; } catch (std::bad_alloc& ex) { cout << ex.what() << endl; exit(1); } } DistrictResult::~DistrictResult() { delete[] result; } DistrictResult::DistrictResult(const DistrictResult& res) { this->lSize = res.lSize; this->phSize = res.phSize; this->result = res.result; } int DistrictResult::getNumOfVotes(int partyId) const { return result[partyId].numberOfVoters; } int DistrictResult::getLSize() const { return this->lSize; } void DistrictResult::addParty(const Party* party) { if (lSize == phSize) { phSize *= 2; DistrictVotes* temp = nullptr; try { temp = new DistrictVotes[phSize]; } catch (std::bad_alloc& ex) { cout << ex.what() << endl; exit(1); } memcpy(temp, result, lSize * sizeof(DistrictVotes)); delete[]result; result = temp; } result[lSize].party = party; lSize++; } void DistrictResult::saveResults(ofstream& file)const { int partyid; for (int i = 0; i < lSize; i++) { partyid = result[i].party->getPartyID(); file.write(rcastcc(&partyid), sizeof(int)); file.write(rcastcc(&(result[i].numberOfVoters)), sizeof(int)); file.write(rcastcc(&(result[i].numOfReps)), sizeof(int)); if (!file.good()) throw "problem occurred while loading data from the file"; } } void DistrictResult::loadDistricResults(ifstream& file, const PartyArr& partyList) { int size; file.read(rcastc(&size), sizeof(int)); if (!file.good()) throw "problem occurred while loading data from the file"; delete[]result; try { result = new DistrictVotes[size]; } catch (std::bad_alloc& ex) { cout << ex.what() << endl; exit(1); } DistrictVotes* newDisVotes = nullptr; for (int i = 0; i < size; i++) { try { newDisVotes = new DistrictVotes(file, partyList); } catch (bad_alloc& ex) { cout << "Error:" << ex.what() << endl; exit(1); } if (!file.good()) throw "problem occurred while loading data from the file"; result[i].party = newDisVotes->party; result[i].numberOfVoters = newDisVotes->numberOfVoters; result[i].numOfReps = newDisVotes->numOfReps; newDisVotes = nullptr; } lSize = size; phSize = size; delete newDisVotes; } DistrictResult::DistrictVotes::DistrictVotes(ifstream& file, const PartyArr& partyList) { int paryId, numOfVotes, numOfReps; file.read(rcastc(&paryId), sizeof(int)); file.read(rcastc(&numOfVotes), sizeof(int)); file.read(rcastc(&numOfReps), sizeof(int)); if (!file.good()) { throw "problem occurred while loading data from the file"; } this->party = &partyList.getParty(paryId); this->numberOfVoters = numOfVotes; this->numOfReps = numOfReps; } const DistrictResult& DistrictResult::operator=(const DistrictResult& origin) { this->lSize = origin.lSize; this->phSize = origin.phSize; delete[]result; result = new DistrictVotes[phSize]; for (int i = 0; i < lSize; i++) { result[i].numberOfVoters = origin.result[i].numberOfVoters; result[i].numOfReps = origin.result[i].numOfReps; result[i].party = origin.result[i].party; } return *this; }
[ "avivmore88@gmail.com" ]
avivmore88@gmail.com
4d8de2ce86702aab7ff29e81ad448c332b3ef220
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-ec2/source/model/DescribeReservedInstancesRequest.cpp
11ce500c9ddbdff07c4535f8d551756c09402b70
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
2,259
cpp
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/ec2/model/DescribeReservedInstancesRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::EC2::Model; using namespace Aws::Utils; DescribeReservedInstancesRequest::DescribeReservedInstancesRequest() : m_dryRun(false), m_dryRunHasBeenSet(false), m_reservedInstancesIdsHasBeenSet(false), m_filtersHasBeenSet(false), m_offeringType(OfferingTypeValues::NOT_SET), m_offeringTypeHasBeenSet(false), m_offeringClass(OfferingClassType::NOT_SET), m_offeringClassHasBeenSet(false) { } Aws::String DescribeReservedInstancesRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=DescribeReservedInstances&"; if(m_dryRunHasBeenSet) { ss << "DryRun=" << std::boolalpha << m_dryRun << "&"; } if(m_reservedInstancesIdsHasBeenSet) { unsigned reservedInstancesIdsCount = 1; for(auto& item : m_reservedInstancesIds) { ss << "ReservedInstancesId." << reservedInstancesIdsCount << "=" << StringUtils::URLEncode(item.c_str()) << "&"; reservedInstancesIdsCount++; } } if(m_filtersHasBeenSet) { unsigned filtersCount = 1; for(auto& item : m_filters) { item.OutputToStream(ss, "Filter.", filtersCount, ""); filtersCount++; } } if(m_offeringTypeHasBeenSet) { ss << "OfferingType=" << OfferingTypeValuesMapper::GetNameForOfferingTypeValues(m_offeringType) << "&"; } if(m_offeringClassHasBeenSet) { ss << "OfferingClass=" << OfferingClassTypeMapper::GetNameForOfferingClassType(m_offeringClass) << "&"; } ss << "Version=2016-11-15"; return ss.str(); }
[ "henso@amazon.com" ]
henso@amazon.com