blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f23b6708ea920c343143f4aee984746e8c3d1f13
2095af306a0eb2e10c78aa6047f85a7dcdc7c47d
/include/Util/UIInlineObject.h
08afb620a8368502f5770ef1be99646eea0cc974
[ "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-scintilla" ]
permissive
grimtraveller/LongUI
ff4e5f565a44c266a8aede6925b75de711e5ea41
d4fed468217312cb77e99b7f1ead45bdab9223b6
refs/heads/master
2020-12-11T03:25:13.373234
2016-03-12T12:13:36
2016-03-12T12:13:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,875
h
#pragma once /** * Copyright (c) 2014-2016 dustpg mailto:dustpg@gmail.com * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // longui namespace namespace LongUI { // LongUI Inline Object class CUIInlineObject : public Helper::ComBase< Helper::QiList<IDWriteInlineObject>, std::atomic<ULONG>> { public: // inline obj type enum InlineType : uint32_t { // CUIInlineMeta Type_Meta = 0, // CUIRubyCharacter Type_Ruby, // Unknown }; // type: InlineType const type; // ctor CUIInlineObject(InlineType _type) noexcept: type(_type) {} // dtor virtual ~CUIInlineObject() noexcept {} }; // Meta inlineobject ver. class CUIInlineMeta final : public CUIInlineObject { using Super = CUIInlineObject; public: // UIInlineMeta CUIInlineMeta(): Super(CUIInlineObject::Type_Meta){} // ~UIInlineMeta virtual ~CUIInlineMeta() {} public: // meta to render Meta meta; }; // Ruby Character class CUIRubyCharacter final : public CUIInlineObject { // super class using Super = CUIInlineObject; public: // ctor's context struct CtorContext { // basic format IDWriteTextFormat* basic_format; // ruby format IDWriteTextFormat* ruby_format; // basic text const wchar_t* basic_text; // ruby text const wchar_t* ruby_text; // basic text length size_t basic_text_length; // ruby text length size_t ruby_text_length; }; // ctor CUIRubyCharacter(const CtorContext&) noexcept; // ~dtor virtual ~CUIRubyCharacter() noexcept; public: // impl for IDWriteInlineObject HRESULT STDMETHODCALLTYPE Draw(void*, IDWriteTextRenderer*, FLOAT, FLOAT, BOOL, BOOL, IUnknown*) noexcept override; // draw this HRESULT STDMETHODCALLTYPE GetMetrics(DWRITE_INLINE_OBJECT_METRICS*) noexcept override; // draw this HRESULT STDMETHODCALLTYPE GetOverhangMetrics(DWRITE_OVERHANG_METRICS*) noexcept override; // draw this HRESULT STDMETHODCALLTYPE GetBreakConditions(DWRITE_BREAK_CONDITION*, DWRITE_BREAK_CONDITION*) noexcept override; private: // base chars layout IDWriteTextLayout* m_pBaseLayout = nullptr; // ruby chars IDWriteTextLayout* m_pRubyLayout = nullptr; // inline metrics DWRITE_INLINE_OBJECT_METRICS m_inlineMetrics; // overhand metrics DWRITE_OVERHANG_METRICS m_overhandMetrics; }; }
[ "dustpg@gmail.com" ]
dustpg@gmail.com
cb7892ec5053cfc498afcf77200d3d23ce3b0276
ffd2ca527b49d447def2702e45f8243897544702
/src/crayg/src/image/ColorConversion.cpp
8c8cda19c76668b60a20b95a1e2d5acfcdb94623
[]
no_license
Latios96/crayg
17b730f745b9367cc15b55b8f1dbd095a29c86c9
57b206d755fb3cafd3dd7a04caa7382cd85f25f8
refs/heads/master
2023-08-17T10:26:10.310064
2023-08-07T16:23:21
2023-08-07T16:23:21
144,862,288
2
1
null
2023-01-26T11:43:21
2018-08-15T14:17:47
Mathematica
UTF-8
C++
false
false
586
cpp
#include "ColorConversion.h" #include "imageiterators/pixels/ImageIterators.h" namespace crayg { bool ColorConversion::channelNeedsLinearToSRgbConversion(const std::string &channelName) { return channelName == "rgb"; } void ColorConversion::linearToSRGB(const PixelBuffer &source, PixelBuffer &target) { for (auto pixel : ImageIterators::lineByLine(source)) { target.setValue(pixel, linearToSRGB(source.getValue(pixel))); } } Color ColorConversion::linearToSRGB(const Color &color) { static const float gamma = 1.0f / 2.2f; return color.pow(gamma); } }
[ "jan.honsbrok@gmail.com" ]
jan.honsbrok@gmail.com
10ead22d00b1896783b2d99d9527e8421b95b4f9
dd081ecec68d0447af647d7f4a3a839dcbba9bea
/src/windows/DeviceINQ.cc
07aa6730fde820e4c30280482f79ed895748e286
[ "MIT", "BSD-2-Clause", "BSD-2-Clause-Views", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dutiene/bluetooth-serial-port
61b5de7bb8b1c8e5e3e6b892adca139db1b4df10
c07dedadbfb94138aeb79cfdb5109e6aa7f43393
refs/heads/master
2021-01-20T08:16:29.187123
2015-10-05T12:46:38
2015-10-05T12:46:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,096
cc
#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include <string> #include <stdlib.h> #include <winsock2.h> #include <ws2bth.h> #include <memory> #include <bluetoothapis.h> #include "../BluetoothException.h" #include "../DeviceINQ.h" #include "BluetoothHelpers.h" #ifdef UNICODE #define tscanf swscanf #else #define tscanf sscanf #endif using namespace std; struct free_delete { void operator()(void* x) { free(x); } }; time_t ConvertTime(SYSTEMTIME *t) { tm x; x.tm_sec = t->wSecond; x.tm_min = t->wMinute; x.tm_hour = t->wHour; x.tm_mday = t->wDay; x.tm_mon = t->wMonth; x.tm_year = t->wYear - 1900; x.tm_isdst = 0; return mktime(&x); } DeviceINQ *DeviceINQ::Create() { auto inquire = new DeviceINQ(); if (!inquire->initialized) { delete inquire; throw BluetoothException("Unable to initialize socket library"); } return inquire; } DeviceINQ::DeviceINQ() { initialized = BluetoothHelpers::Initialize(); } DeviceINQ::~DeviceINQ() { if (initialized) BluetoothHelpers::Finalize(); } vector<device> DeviceINQ::Inquire() { // Construct windows socket bluetooth variables DWORD flags = LUP_CONTAINERS | LUP_FLUSHCACHE | LUP_RETURN_NAME | LUP_RETURN_ADDR; DWORD querySetSize = sizeof(WSAQUERYSET); unique_ptr<WSAQUERYSET, free_delete> querySet((WSAQUERYSET*)malloc(querySetSize)); if (querySet == nullptr) throw BluetoothException("Out of memory: Unable to allocate memory resource for inquiry"); ZeroMemory(querySet.get(), querySetSize); querySet->dwSize = querySetSize; querySet->dwNameSpace = NS_BTH; // Initiate client device inquiry HANDLE lookupServiceHandle; int lookupServiceError = WSALookupServiceBegin(querySet.get(), flags, &lookupServiceHandle); vector<device> devices; int errorCode = WSAGetLastError(); if (lookupServiceError == SOCKET_ERROR) { if (errorCode == WSASERVICE_NOT_FOUND) return devices; else throw BluetoothException(BluetoothHelpers::GetWSAErrorMessage(errorCode)); } // Iterate over each found bluetooth service bool inquiryComplete = false; while (!inquiryComplete) { // For each bluetooth service retrieve its corresponding details lookupServiceError = WSALookupServiceNext(lookupServiceHandle, flags, &querySetSize, querySet.get()); if (lookupServiceError != SOCKET_ERROR) { TCHAR address[40] = { 0 }; char name[248] = { 0 }; DWORD addressLength = _countof(address); SOCKADDR_BTH *bluetoothSocketAddress = (SOCKADDR_BTH *)querySet->lpcsaBuffer->RemoteAddr.lpSockaddr; BTH_ADDR bluetoothAddress = bluetoothSocketAddress->btAddr; // Emit the corresponding event if we were able to retrieve the address int addressToStringError = WSAAddressToString( querySet->lpcsaBuffer->RemoteAddr.lpSockaddr, sizeof(SOCKADDR_BTH), nullptr, address, &addressLength); if (addressToStringError != SOCKET_ERROR) { // Strip any leading and trailing parentheses is encountered TCHAR strippedAddress[19] = { 0 }; auto sscanfResult = tscanf(address, TEXT("(%18[^)])"), strippedAddress); TCHAR *addr = sscanfResult == 1 ? strippedAddress : address; auto addressString = BluetoothHelpers::ToString(addr); int b, c, d, e, f, g; tscanf(addr, TEXT("%2x:%2x:%2x:%2x:%2x:%2x"), &b, &c, &d, &e, &f, &g); BLUETOOTH_ADDRESS a = { 0 }; a.rgBytes[5] = b; a.rgBytes[4] = c; a.rgBytes[3] = d; a.rgBytes[2] = e; a.rgBytes[1] = f; a.rgBytes[0] = g; BLUETOOTH_DEVICE_INFO deviceInfo; deviceInfo.dwSize = sizeof(BLUETOOTH_DEVICE_INFO); deviceInfo.Address = a; deviceInfo.ulClassofDevice = 0; deviceInfo.fConnected = false; deviceInfo.fRemembered = false; deviceInfo.fAuthenticated = false; auto result = BluetoothGetDeviceInfo(NULL, &deviceInfo); device dev; dev.address = addressString; if (querySet->lpszServiceInstanceName == NULL || lstrlen(querySet->lpszServiceInstanceName) == 0) { size_t convertedChars; wcstombs_s(&convertedChars, name, sizeof(name), deviceInfo.szName, _TRUNCATE); dev.name = std::string(name); } else { dev.name = BluetoothHelpers::ToString(querySet->lpszServiceInstanceName); } if (result == ERROR_SUCCESS) { ULONG cod = deviceInfo.ulClassofDevice; dev.connected = deviceInfo.fConnected ? true : false; dev.remembered = deviceInfo.fRemembered ? true : false; dev.authenticated = deviceInfo.fAuthenticated ? true : false; dev.lastSeen = ConvertTime(&deviceInfo.stLastSeen); dev.lastUsed = ConvertTime(&deviceInfo.stLastUsed); dev.deviceClass = (DeviceClass)(cod & 0x1ffc); dev.majorDeviceClass = (DeviceClass)(cod & DC_Uncategorized); dev.serviceClass = (ServiceClass)(cod >> 13); } else { dev.connected = false; dev.remembered = false; dev.authenticated = false; dev.lastSeen = 0; dev.lastUsed = 0; dev.deviceClass = DC_Miscellaneous; dev.majorDeviceClass = DC_Miscellaneous; dev.serviceClass = SC_None; } devices.push_back(dev); } } else { int lookupServiceErrorNumber = WSAGetLastError(); if (lookupServiceErrorNumber == WSAEFAULT) { querySet.reset((WSAQUERYSET*)malloc(querySetSize)); if (querySet == nullptr) { WSALookupServiceEnd(lookupServiceHandle); throw BluetoothException("Out of memory: Unable to allocate memory resource for inquiry"); } } else if (lookupServiceErrorNumber == WSA_E_NO_MORE) { // No more services where found inquiryComplete = true; } else { // Unhandled error inquiryComplete = true; } } } WSALookupServiceEnd(lookupServiceHandle); return devices; } int DeviceINQ::SdpSearch(string address) { // Construct windows socket bluetooth variables DWORD flags = LUP_FLUSHCACHE | LUP_RETURN_ADDR; DWORD querySetSize = sizeof(WSAQUERYSET); unique_ptr<WSAQUERYSET, free_delete> querySet((WSAQUERYSET*)malloc(querySetSize)); if (querySet == nullptr) throw BluetoothException("Out of memory: Unable to allocate memory resource for sdp search"); TCHAR addressBuffer[40]; if (address.length() >= 40) throw BluetoothException("Address length is invalid"); for (size_t i = 0; i < address.length(); i++) addressBuffer[i] = (TCHAR)address[i]; ZeroMemory(querySet.get(), querySetSize); querySet->dwSize = querySetSize; querySet->dwNameSpace = NS_BTH; querySet->lpServiceClassId = (LPGUID)&SerialPortServiceClass_UUID; querySet->dwNumberOfCsAddrs = 0; querySet->lpszContext = addressBuffer; // Initiate client device inquiry HANDLE lookupServiceHandle; int lookupServiceError = WSALookupServiceBegin(querySet.get(), flags, &lookupServiceHandle); int channelID = -1; if (lookupServiceError == SOCKET_ERROR) throw BluetoothException(BluetoothHelpers::GetWSAErrorMessage(WSAGetLastError())); // Iterate over each found bluetooth service bool inquiryComplete = false; while (!inquiryComplete) { // For each bluetooth service retrieve its corresponding details lookupServiceError = WSALookupServiceNext(lookupServiceHandle, flags, &querySetSize, querySet.get()); if (lookupServiceError != SOCKET_ERROR) { char address[19] = { 0 }; SOCKADDR_BTH* bluetoothSocketAddress = (SOCKADDR_BTH*)querySet->lpcsaBuffer->RemoteAddr.lpSockaddr; channelID = bluetoothSocketAddress->port; inquiryComplete = true; } else { int lookupServiceErrorNumber = WSAGetLastError(); if (lookupServiceErrorNumber == WSAEFAULT) { querySet.reset((WSAQUERYSET*)malloc(querySetSize)); if (querySet == nullptr) { WSALookupServiceEnd(lookupServiceHandle); throw BluetoothException("Out of memory: Unable to allocate memory resource for sdp search"); } } else if (lookupServiceErrorNumber == WSA_E_NO_MORE) { // No more services where found inquiryComplete = true; } else { // Unhandled error inquiryComplete = true; } } } WSALookupServiceEnd(lookupServiceHandle); return channelID; }
[ "agamnentzar@gmail.com" ]
agamnentzar@gmail.com
38956a11f7c9459cf2e2c5928398c495e48bcd62
2cb24ca130a70c38eaa92a09f5df05af69690268
/forumNet/TaskManager.cpp
a41af5f390c9d049824f1f8c200880f4c9dfd311
[]
no_license
mianwu515/forumNet
b6e6004559bf9d8e9804d6e24eeb5d91e558cd3f
0341a068354c6581640c36c8dda04b2470b27c72
refs/heads/master
2022-01-27T13:53:17.598277
2017-12-04T09:17:59
2017-12-04T09:17:59
null
0
0
null
null
null
null
GB18030
C++
false
false
1,953
cpp
#include "TaskManager.h" using namespace std; TaskManager::~TaskManager() { } void TaskManager::CreateTask(string httpBody) { //cout << "in the function: 'TaskManager::CreateTask' " << endl; string key, value; map<string, string> requestForm; size_t pos_and = 0, pos_equal = 0, prev = 0, next = 0; string key_array[5] = { "type", "id", "accessToken", "resourceId", "resourceType"}; /*"""type""=""HomePageRequest"" ""id""= ""accessToken"" ""resourceId"" = ""NoID"" “resourceType”=""NoTYPE""" */ for (int i = 0; i < 5; ++i) { key = key_array[i]; prev = httpBody.find(key, 0); pos_equal = httpBody.find("=", prev); if ((pos_and = httpBody.find("&", prev)) != string::npos) { value = httpBody.substr(pos_equal + 1, pos_and - pos_equal - 1); } else { value = httpBody.substr(pos_equal + 1); } cout << "value"<< value << endl; requestForm.insert(pair<string, string>(key, value)); } Task task; task.taskType = requestForm["type"]; task.userID = requestForm["id"]; task.accessToken = requestForm["accessToken"]; task.resourceId = requestForm["resourceId"]; task.resourceType = requestForm["resourceType"]; _taskQueue.push(task); } /*任务调度,选择任务,交给执行器*/ void TaskManager::TaskScheduling() { //cout << "in the function: 'TaskManager::TaskScheduling' " << endl; Task task = _taskQueue.front(); _taskQueue.pop(); //认证中心 AuthenticationServer authenticationServer; if (authenticationServer.CheckUser(task)) { TaskExcutor taskExcutor; string responseData = taskExcutor.Run(task); _scheduleResult.push(responseData); } else { //重新登陆 string responseData = "post info error,try again"; _scheduleResult.push(responseData); } } string TaskManager::GetScheduleResult() { //cout << "in the function: 'TaskManager::GetScheduleResult' " << endl; string scheduleResult = _scheduleResult.front(); _scheduleResult.pop(); return scheduleResult; }
[ "shhchen@outlook.com" ]
shhchen@outlook.com
e21aa69438fde6396391d61e0c70b04774cf8dbb
f97ce0a588e023675eaa980f2f105f0a9c25ce18
/UVa/v116/11636.cpp
be60db154b5772945d0fe75d4d807ad70b40b797
[]
no_license
anindya028/Programming-Contest-Problems
a5c49653d990391a6e2003f2ec9d951222cabbe2
7038b6267432189de72539ef5ad046d38e730ee8
refs/heads/master
2023-03-17T06:27:38.339049
2021-02-23T22:58:06
2021-02-23T22:58:06
277,399,320
0
0
null
null
null
null
UTF-8
C++
false
false
181
cpp
#include<stdio.h> #include<math.h> int main() { int n,cs=0; while(scanf("%d",&n)==1 && n>0) printf("Case %d: %.0lf\n",++cs,ceil(log((double)n)/log(2.0))); return 0; }
[ "anindya@Anindyas-MacBook-Pro.local" ]
anindya@Anindyas-MacBook-Pro.local
94dde5d47afee2ebb075a51d355e83f271582d8a
28cec552b85e7d8ee9b0a06f99a875fbc2ac4092
/GameLib/Graph/Render/GraphicsScene/LayersOwner.h
6be4a1a7bc0c3e7389c6a10839551a647e1278f8
[]
no_license
GromCaptain/snake-game-prototype
74535f215dc007b0e6d14cb096d954429b9cb6f5
f79efd8da8401d5c9760f6e93cd8d4f430947458
refs/heads/master
2021-01-10T17:41:22.676891
2017-02-19T19:16:47
2017-02-19T19:16:47
44,188,154
1
0
null
null
null
null
UTF-8
C++
false
false
425
h
#ifndef LAYERS_OWNER_H #define LAYERS_OWNER_H #include <memory> #include <vector> class Rectangle; namespace Graphics { class Actor; template<typename Layer> class LayersOwner { public: virtual ~LayersOwner() = default; virtual std::vector<Layer> layersOrder() const = 0; virtual std::vector<std::shared_ptr<Actor>> actorsInArea(Layer sourceLayer, const Rectangle& area) const = 0; }; } #endif // LAYERS_OWNER_H
[ "andrej.vedernikov@gmail.com" ]
andrej.vedernikov@gmail.com
bab4df10ef917669a295dce4cd7baca0eaa801ca
6fcdbb23b52acbd3c1f32c55308801f1067a6ac6
/ProgramForClient/RhinoClientCode/Extend/project/BetLobbyLoL/GameLobby.h
97cdeeee593531a302c05059de63f6fe285c70d3
[ "Apache-2.0" ]
permissive
jyqiu1216/Rino
e507b70a2796cb356cd7ce90578981802ee5008c
eb8c110e7a551ee9bd736792a957a544c5ffdeb5
refs/heads/master
2020-04-13T21:41:26.474356
2017-05-19T07:39:42
2017-05-19T07:39:42
86,565,153
3
2
null
null
null
null
GB18030
C++
false
false
1,010
h
#pragma once #ifndef GAMELOBBY_H #define GAMELOBBY_H //游戏状态 typedef enum _State { //未知 unknown, //进入选角色 inselect, //从选角色返回 breakslect } State; class CGameLobby { private: //HOOK地址 DWORD m_HookAddress; //HOOK处原始机器码 byte m_HookOpCode[7]; protected: //发送数据到平台 static void SendGameData(State pState, int inMode = 0); //搜索是否是人机模式 static bool FindMode(int inStart, int inEnd, char* pchData, const char* pchTemp); public: //hook跳转地址 static DWORD m_JmpGameLobby; public: CGameLobby(); ~CGameLobby(); //过滤游戏Flash发包 static void __stdcall FilterGameLobby(char* pchBuffer, int inLen); //HOOK Flash发包 void HookGameLobby(); //UnHook Flash发包 void UnHookGameLobby(); }; #endif
[ "qiujy" ]
qiujy
5f24ad35df8245acb9bf7cf7e9c3810acc621776
a84ca341f0de14be3f4df8e3061457765fa9aa9b
/Source/SpaceKitBullet/BulletCollision/CollisionDispatch/btGhostObject.h
dce36e6e87b55d0f93e90d7df0b96b5d03a3a49f
[]
no_license
Evols/SpaceKit
9effcd0314fd07ad1ac2dd9a1c8c709cf5f3c635
1b618c1fc258a27544e83cb5ed5794b7a5271e83
refs/heads/master
2023-05-28T11:00:36.092567
2021-06-17T19:09:40
2021-06-17T19:09:40
339,409,834
15
4
null
2023-05-25T20:45:11
2021-02-16T13:37:25
C++
UTF-8
C++
false
false
5,679
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_GHOST_OBJECT_H #define BT_GHOST_OBJECT_H #include "btCollisionObject.h" #include "SpaceKitBullet/BulletCollision/BroadphaseCollision/btOverlappingPairCallback.h" #include "SpaceKitBullet/LinearMath/btAlignedAllocator.h" #include "SpaceKitBullet/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" #include "btCollisionWorld.h" class btConvexShape; class btDispatcher; ///The btGhostObject can keep track of all objects that are overlapping ///By default, this overlap is based on the AABB ///This is useful for creating a character controller, collision sensors/triggers, explosions etc. ///We plan on adding rayTest and other queries for the btGhostObject ATTRIBUTE_ALIGNED16(class) btGhostObject : public btCollisionObject { protected: btAlignedObjectArray<btCollisionObject*> m_overlappingObjects; public: btGhostObject(); virtual ~btGhostObject(); void convexSweepTest(const class btConvexShape* castShape, const btTransform& convexFromWorld, const btTransform& convexToWorld, btCollisionWorld::ConvexResultCallback& resultCallback, btScalar allowedCcdPenetration = 0.0_fl) const; void rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, btCollisionWorld::RayResultCallback& resultCallback) const; ///this method is mainly for expert/internal use only. virtual void addOverlappingObjectInternal(btBroadphaseProxy * otherProxy, btBroadphaseProxy* thisProxy = 0); ///this method is mainly for expert/internal use only. virtual void removeOverlappingObjectInternal(btBroadphaseProxy * otherProxy, btDispatcher * dispatcher, btBroadphaseProxy* thisProxy = 0); int getNumOverlappingObjects() const { return m_overlappingObjects.size(); } btCollisionObject* getOverlappingObject(int index) { return m_overlappingObjects[index]; } const btCollisionObject* getOverlappingObject(int index) const { return m_overlappingObjects[index]; } btAlignedObjectArray<btCollisionObject*>& getOverlappingPairs() { return m_overlappingObjects; } const btAlignedObjectArray<btCollisionObject*> getOverlappingPairs() const { return m_overlappingObjects; } // // internal cast // static const btGhostObject* upcast(const btCollisionObject* colObj) { if (colObj->getInternalType() == CO_GHOST_OBJECT) return (const btGhostObject*)colObj; return 0; } static btGhostObject* upcast(btCollisionObject * colObj) { if (colObj->getInternalType() == CO_GHOST_OBJECT) return (btGhostObject*)colObj; return 0; } }; class btPairCachingGhostObject : public btGhostObject { btHashedOverlappingPairCache* m_hashPairCache; public: btPairCachingGhostObject(); virtual ~btPairCachingGhostObject(); ///this method is mainly for expert/internal use only. virtual void addOverlappingObjectInternal(btBroadphaseProxy* otherProxy, btBroadphaseProxy* thisProxy = 0); virtual void removeOverlappingObjectInternal(btBroadphaseProxy* otherProxy, btDispatcher* dispatcher, btBroadphaseProxy* thisProxy = 0); btHashedOverlappingPairCache* getOverlappingPairCache() { return m_hashPairCache; } }; ///The btGhostPairCallback interfaces and forwards adding and removal of overlapping pairs from the btBroadphaseInterface to btGhostObject. class btGhostPairCallback : public btOverlappingPairCallback { public: btGhostPairCallback() { } virtual ~btGhostPairCallback() { } virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) { btCollisionObject* colObj0 = (btCollisionObject*)proxy0->m_clientObject; btCollisionObject* colObj1 = (btCollisionObject*)proxy1->m_clientObject; btGhostObject* ghost0 = btGhostObject::upcast(colObj0); btGhostObject* ghost1 = btGhostObject::upcast(colObj1); if (ghost0) ghost0->addOverlappingObjectInternal(proxy1, proxy0); if (ghost1) ghost1->addOverlappingObjectInternal(proxy0, proxy1); return 0; } virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, btDispatcher* dispatcher) { btCollisionObject* colObj0 = (btCollisionObject*)proxy0->m_clientObject; btCollisionObject* colObj1 = (btCollisionObject*)proxy1->m_clientObject; btGhostObject* ghost0 = btGhostObject::upcast(colObj0); btGhostObject* ghost1 = btGhostObject::upcast(colObj1); if (ghost0) ghost0->removeOverlappingObjectInternal(proxy1, dispatcher, proxy0); if (ghost1) ghost1->removeOverlappingObjectInternal(proxy0, dispatcher, proxy1); return 0; } virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/, btDispatcher* /*dispatcher*/) { btAssert(0); //need to keep track of all ghost objects and call them here //m_hashPairCache->removeOverlappingPairsContainingProxy(proxy0,dispatcher); } }; #endif
[ "hutteau.b@gmail.com" ]
hutteau.b@gmail.com
658384dff8f69fe010d6beca842b3939e5779d55
287dc1683f7e19a5239c2b8addbc8531809f9177
/boboleetcode/Play-Leetcode-master/1002-Find-Common-Characters/cpp-1002/main3.cpp
386ba6baed156e5d5a4cf0d59287f8e8b19e7bde
[ "Apache-2.0" ]
permissive
yaominzh/CodeLrn2019
ea192cf18981816c6adafe43d85e2462d4bc6e5d
adc727d92904c5c5d445a2621813dfa99474206d
refs/heads/master
2023-01-06T14:11:45.281011
2020-10-28T07:16:32
2020-10-28T07:16:32
164,027,453
2
0
Apache-2.0
2023-01-06T00:39:06
2019-01-03T22:02:24
C++
UTF-8
C++
false
false
1,348
cpp
/// Source : https://leetcode.com/problems/find-common-characters/ /// Author : liuyubobobo /// Time : 2019-03-03 #include <iostream> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; /// Using HashMap to get the intersection of every two strings /// Time Complexity: O(n * ave_len_of_strings) /// Space Complexity: O(26) class Solution { public: vector<string> commonChars(vector<string>& A) { vector<unordered_map<char, int>> freqs(A.size()); for(int i = 0; i < A.size(); i ++) for(char c: A[i]) freqs[i][c] ++; unordered_map<char, int> res = freqs[0]; for(int i = 1; i < freqs.size(); i ++) res = intersection(res, freqs[i]); vector<string> ret; for(const pair<char, int>& p: res) for(int i = 0; i < p.second; i ++) ret.push_back(string(1, p.first)); return ret; } private: unordered_map<char, int> intersection(unordered_map<char, int>& freq1, unordered_map<char, int>& freq2){ unordered_map<char, int> res; for(const pair<char, int>& p: freq1) if(freq2.count(p.first)) res[p.first] = min(p.second, freq2[p.first]); return res; } }; int main() { return 0; }
[ "mcuallen@gmail.com" ]
mcuallen@gmail.com
cd195002c8d40413572200bb3e30ea0eb81f900a
ea4d7d2722beb08865dda667e4c8969664398e8a
/example2.cpp
e44bda41c4100cfa3bba5701f5cd089bed60413c
[ "MIT" ]
permissive
aherrmann/unpacking_tuples_examples
8d7c4c9dab1b687d4f107b1e02123c3cc8090ebb
f71cf25ab68429d69090438398508c746865fed5
refs/heads/master
2016-08-12T07:35:33.618962
2016-02-27T10:44:01
2016-02-28T16:37:06
52,731,924
12
0
null
null
null
null
UTF-8
C++
false
false
2,203
cpp
/* * Tuple Examples * Copyright (c) 2016 Andreas Herrmann * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <cassert> #include <functional> #include <tuple> #include <utility> using std::get; using std::index_sequence; using std::integral_constant; using std::make_index_sequence; using std::make_tuple; using std::plus; using std::size_t; using std::tuple_size; template <class F, size_t... Is> constexpr auto index_apply_impl(F f, index_sequence<Is...>) { return f(integral_constant<size_t, Is> {}...); } template <size_t N, class F> constexpr auto index_apply(F f) { return index_apply_impl(f, make_index_sequence<N>{}); } template <size_t N, class Tuple> constexpr auto take_front(Tuple t) { return index_apply<N>([&](auto... Is) { return make_tuple(get<Is>(t)...); }); } template <class Tuple, class F> constexpr auto apply(Tuple t, F f) { return index_apply<tuple_size<Tuple>{}>( [&](auto... Is) { return f(get<Is>(t)...); }); } int main() { assert(take_front<2>(make_tuple(1, 2, 3, 4)) == make_tuple(1, 2)); assert(apply(make_tuple(1, 2), plus<>{}) == 3); }
[ "andreash87@gmx.ch" ]
andreash87@gmx.ch
4ff6f9a40d21ea93a5768af911087adb539fbad3
76605262ecac1026f0d983b04c6d8e03c0913f0a
/src/test.cpp
7d4d1b9ca8e5c4195cf12832bcee2f2e230e813c
[]
no_license
caijunhao/beethoven
179cbee2db446651e6c049864ccd1b465be52acc
e3b048ad5f3c50071cd592b72f33b9908b15f611
refs/heads/main
2023-01-09T13:19:08.817540
2020-11-10T12:22:00
2020-11-10T12:22:00
311,356,223
0
0
null
null
null
null
UTF-8
C++
false
false
4,951
cpp
// This code is copied from learning opengl tutorial. // Link: https://learnopengl.com/code_viewer_gh.php?code=src/1.getting_started/3.3.shaders_class/shaders_class.cpp #include <glad/glad.h> #include <GLFW/glfw3.h> #include <test.h> #include <iostream> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader program // ------------------------------------ Shader ourShader("../shader/test.vs", "../shader/test.fs"); // you can name your shader files however you like // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { // positions // colors 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // bottom left 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // top }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. // glBindVertexArray(0); // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // render the triangle ourShader.use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); }
[ "caijh28@mail3.sysu.edu.cn" ]
caijh28@mail3.sysu.edu.cn
548accff049702158ec99945724a2e8174287902
b4032b8b9b5b5b0728e51f3ae5c964b637949487
/project_v3/src/sd.h
354e7169fc70332f369949769db15fba27d70f7b
[]
no_license
niklasbuhl/Particle-Photon-Aqubiq-Sensor
e079d9623246a6e29e705148b794f1cadaa2075e
7df682b78b8254384ae7bfb2806bf35463f4f03c
refs/heads/master
2021-06-19T02:24:23.646270
2017-06-23T16:31:23
2017-06-23T16:31:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,627
h
#ifndef SD_H #define SD_H #include "application.h" #include "FatFs.h" #include "rgb.h" #include "data.h" class SD { public: SD(); // SD Module Control int setup(int SD_CS, int redPin, int greenPin, int bluePin, int button); // Setup the module int update(); // Mainly user interface. (RGB and button) // SD Card Control int attach(); // Attempt to attach the SD card int eject(); // Attempt to eject attached SD card int forceeject(); // Force eject // Data Manipulation String getData(unsigned int id); // Get a piece of data int writeData(Data data); // Write a new piece of data // Status String getSDModuleStatus(); // Get the module status String getSDCardStatus(); // Get the SD card status String getSessionStatus(); // Get the session status String getIDStatus(); // Get the ID status String getDataStatus(); // Get the data status String getTimestamp(); // Get the timestamp // Cloud int SDCloudInput(String command); // Published cloud commands private: // I/O RGBled rgb; // Button btn; // void control(&btn); // Module String message, moduleMessage; int write(); // Test for write access (not working). int writesuccess(); int writefail(); int work(); // Test for working. int worksuccess(); // Success. int workfail(); // Fail. int working, writing; // Time int time[6]; // year, month, day, hour, minute, second. String timestamp, prettyTimestamp, masterTimestamp, startTimestamp; // YYYYMMDDHHMMSS, YMMDDHH - Short time stamp String updateTime(); // Update time, return true if new data file is created, else false. String getPrettyTimestamp(String ts); // Error and trouble shooting int error(FRESULT result, String *output); FRESULT SDresult, FILEresult; String checkFilename(String filename); int troubleShootSD(); // SD int checkSD(); FatFsSD FatSD; int sdAttached, SD_CS; String sdMessage; // Session Log int checkSessionFile(); int openSessionFile(); int closeSessionFile(); int writeSession(String log); FIL sessionFile; int sessionOpen, sessionStarted; String session, sessionMessage, sessionFilename; // Data ID int writeID(unsigned int id, String datafile); int loadIDFile(); // Loads the saved ID file into memory FIL IDFile; int idOpen; String idMessage, idFilename; unsigned int latestID; unsigned int dataIDs[256]; // Beginning ID String dataFilenames[256]; // Data name (could be reduced to char [8]? int IDcount = 0; // Data File FIL dataFile; String dataMessage, dataFilename; }; #endif /* end of include guard: SD_H */
[ "nibuh@dtu.dk" ]
nibuh@dtu.dk
c67125548b6c316f4507c99d33d3361fc27a993d
aadbfbf8a460a42a211d891a03b27a63f5125fef
/src/wallet.cpp
797cce891ec67c509889466fc523358b453a8f0f
[ "MIT" ]
permissive
CherryYang05/gkccash_core
aa914fab3bb739f9d82e0348e4667f352ed1e406
2ec968c273d6d60eeeaceefa78e9a1903bd308d5
refs/heads/master
2022-04-20T00:41:04.829545
2020-04-20T14:27:17
2020-04-20T14:27:17
257,483,509
1
0
MIT
2020-04-21T04:52:17
2020-04-21T04:52:17
null
UTF-8
C++
false
false
220,079
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "accumulators.h" #include "base58.h" #include "checkpoints.h" #include "coincontrol.h" #include "kernel.h" #include "masternode-budget.h" #include "net.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/sign.h" #include "spork.h" #include "swifttx.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "denomination_functions.h" #include "libzerocoin/Denominations.h" #include <assert.h> #include <boost/algorithm/string/replace.hpp> #include <boost/thread.hpp> #include <boost/filesystem/operations.hpp> #include "miner.h" #ifdef DPOS #include "entrustment.h" #endif #include "scriptex.h" using namespace std; /** * Settings */ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE; unsigned int nTxConfirmTarget = 1; bool bSpendZeroConfChange = true; bool bZeroBalanceAddressToken = DEFAULT_ZERO_BALANCE_ADDRESS_TOKEN; bool bdisableSystemnotifications = false; // Those bubbles can be annoying and slow down the UI when you get lots of trx bool fSendFreeTransactions = false; bool fPayAtLeastCustomFee = true; /** * Fees smaller than this (in duffs) are considered zero fee (for transaction creation) * We are ~100 times smaller then bitcoin now (2015-06-23), set minTxFee 10 times higher * so it's still 10 times lower comparing to bitcoin. * Override with -mintxfee */ CFeeRate CWallet::minTxFee = CFeeRate(10000); int64_t nStartupTime = GetAdjustedTime(); /** @defgroup mapWallet * * @{ */ struct CompareValueOnly { bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; struct CompareStakeCoin : public std::unary_function<std::pair<const CWalletTx*, unsigned int>,bool> { bool operator ()(const std::pair<const CWalletTx*, unsigned int>& p1,const std::pair<const CWalletTx*, unsigned int>& p2) const { const CWalletTx *tx1 = p1.first, *tx2 = p2.first; int n1 = p1.second, n2 = p2.second; CAmount value1 = tx1->vout[n1].nValue, value2 = tx2->vout[n2].nValue; if(value1 != value2) return value1 > value2; else if(tx1->nTimeSmart != tx2->nTimeSmart) return tx1->nTimeSmart < tx2->nTimeSmart; else if(n1 != n2) return n1 > n2; else ; return tx1->GetHash() > tx2->GetHash(); } }; std::string COutput::ToString() const { return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); } void CWallet::SetNull() { nWalletVersion = FEATURE_BASE; nWalletMaxVersion = FEATURE_BASE; fFileBacked = false; nMasterKeyMaxID = 0; pwalletdbEncryption = NULL; nOrderPosNext = 0; nNextResend = 0; nLastResend = 0; nTimeFirstKey = 0; fWalletUnlockAnonymizeOnly = false; fBackupMints = false; // Stake Settings nHashDrift = 45; nStakeSplitThreshold = 2000; nHashInterval = 22; nStakeSetUpdateTime = 300; // 5 minutes //MultiSend vMultiSend.clear(); fMultiSendStake = false; fMultiSendMasternodeReward = false; fMultiSendNotify = false; strMultiSendChangeAddress = ""; nLastMultiSendHeight = 0; vDisabledAddresses.clear(); //Auto Combine Dust fCombineDust = false; nAutoCombineThreshold = 0; #ifdef DPOS SetCoreMode(); #endif } const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const { LOCK(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); if (it == mapWallet.end()) return NULL; return &(it->second); } CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); assert(secret.VerifyPubKey(pubkey)); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); if (HaveWatchOnly(script)) RemoveWatchOnly(script); if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey& vchPubKey, const vector<unsigned char>& vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::AddWatchOnly(const CScript& dest) { if (!CCryptoKeyStore::AddWatchOnly(dest)) return false; nTimeFirstKey = 1; // No birthday information for watch-only keys. NotifyWatchonlyChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteWatchOnly(dest); } bool CWallet::RemoveWatchOnly(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveWatchOnly(dest)) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) return false; return true; } bool CWallet::LoadWatchOnly(const CScript& dest) { return CCryptoKeyStore::AddWatchOnly(dest); } bool CWallet::AddMultiSig(const CScript& dest) { if (!CCryptoKeyStore::AddMultiSig(dest)) return false; nTimeFirstKey = 1; // No birthday information NotifyMultiSigChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteMultiSig(dest); } bool CWallet::RemoveMultiSig(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveMultiSig(dest)) return false; if (!HaveMultiSig()) NotifyMultiSigChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseMultiSig(dest)) return false; return true; } bool CWallet::LoadMultiSig(const CScript& dest) { return CCryptoKeyStore::AddMultiSig(dest); } bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { SecureString strWalletPassphraseFinal; if (!IsLocked()) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } strWalletPassphraseFinal = strWalletPassphrase; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase; { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } set<uint256> CWallet::GetConflicts(const uint256& txid) const { set<uint256> result; AssertLockHeld(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); if (it == mapWallet.end()) return result; const CWalletTx& wtx = it->second; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; BOOST_FOREACH (const CTxIn& txin, wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1 || wtx.IsZerocoinSpend()) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) result.insert(it->second); } return result; } void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). // So: find smallest nOrderPos: int nMinOrderPos = std::numeric_limits<int>::max(); const CWalletTx* copyFrom = NULL; for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; int n = mapWallet[hash].nOrderPos; if (n < nMinOrderPos) { nMinOrderPos = n; copyFrom = &mapWallet[hash]; } } // Now copy data from copyFrom to rest: for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; CWalletTx* copyTo = &mapWallet[hash]; if (copyFrom == copyTo) continue; copyTo->mapValue = copyFrom->mapValue; copyTo->vOrderForm = copyFrom->vOrderForm; // fTimeReceivedIsTxTime not copied on purpose // nTimeReceived not copied on purpose copyTo->nTimeSmart = copyFrom->nTimeSmart; copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; // nOrderPos not copied on purpose // cached members not copied on purpose } } /** * Outpoint is spent if any non-conflicted transaction * spends it: */ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); pair<TxSpends::const_iterator, TxSpends::const_iterator> range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) return true; // Spent } return false; } void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { //LogPrintf("CWallet::AddToSpends|outpoint=%s,wtxid=%s\n",outpoint.ToString(),wtxid.ToString()); mapTxSpends.insert(make_pair(outpoint, wtxid)); pair<TxSpends::iterator, TxSpends::iterator> range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } void CWallet::AddToSpends(const uint256& wtxid) { assert(mapWallet.count(wtxid)); CWalletTx& thisTx = mapWallet[wtxid]; if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; BOOST_FOREACH (const CTxIn& txin, thisTx.vin) AddToSpends(txin.prevout, wtxid); } bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; // Find possible candidates std::vector<COutput> vPossibleCoins; AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_10000); if (vPossibleCoins.empty()) { LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n"); return false; } if (strTxHash.empty()) // No output specified, select the first one return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet); // Find specific vin uint256 txHash = uint256S(strTxHash); int nOutputIndex; try { nOutputIndex = std::stoi(strOutputIndex.c_str()); } catch (const std::exception& e) { LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what()); return false; } BOOST_FOREACH (COutput& out, vPossibleCoins) if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it! return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet); LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n"); return false; } bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; CScript pubScript; txinRet = CTxIn(out.tx->GetHash(), out.i); pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); CBitcoinAddress address2(address1); CKeyID keyID; if (!address2.GetKeyID(keyID)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n"); return false; } if (!GetKey(keyID, keyRet)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n"); return false; } pubKeyRet = keyRet.GetPubKey(); return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { assert(!pwalletdbEncryption); pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) { delete pwalletdbEncryption; pwalletdbEncryption = NULL; return false; } pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) { pwalletdbEncryption->TxnAbort(); delete pwalletdbEncryption; } // We now probably have half of our keys encrypted in memory, and half not... // die and let the user reload their unencrypted wallet. assert(false); } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) { delete pwalletdbEncryption; // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload their unencrypted wallet. assert(false); } delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB* pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH (CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddAdvertiseTx(const CWalletTx& wtxIn, bool fFromLoadWallet) { LogPrint("wallet","CWallet::AddAdvertiseTx | wtxIn=%s\n",wtxIn.GetHash().ToString()); return AddAdTx(mapAdvertise,wtxIn,fFromLoadWallet); } bool CWallet::AddSysmessageTx(const CWalletTx& wtxIn, bool fFromLoadWallet) { LogPrint("wallet","CWallet::AddSysmessageTx | wtxIn=%s\n",wtxIn.GetHash().ToString()); return AddAdTx(mapSysMessage,wtxIn,fFromLoadWallet); } bool CWallet::AddAdFilterTx(const CWalletTx& wtxIn, bool fFromLoadWallet) { LogPrint("wallet","CWallet::AddAdFilterTx | wtxIn=%s\n",wtxIn.GetHash().ToString()); return AddAdTx(mapFilterAd,wtxIn,fFromLoadWallet); } bool CWallet::AddAdTx(std::map<uint256, CWalletTx>& mapTx, const CWalletTx& wtxIn, bool fFromLoadWallet) { LogPrint("wallet","CWallet::AddAdTx | wtxIn=%s, fFromLoadWallet=%d\n",wtxIn.GetHash().ToString(),fFromLoadWallet); uint256 hash = wtxIn.GetHash(); if (fFromLoadWallet) { mapTx[hash] = wtxIn; mapTx[hash].BindWallet(this); } else { LOCK(cs_wallet); pair<map<uint256, CWalletTx>::iterator, bool> ret = mapTx.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; bool fUpdated = false; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; } if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } } // Write to disk LogPrint("wallet","CWallet::AddAdTx | wtxIn=%s, fInsertedNew=%d, fUpdated=%d\n",wtxIn.GetHash().ToString(),fInsertedNew,fUpdated); if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; } return true; } bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) { uint256 hash = wtxIn.GetHash(); LogPrint("wallet","CWallet::AddToWallet | wtxIn.hash=%s, fFromLoadWallet=%d\n",hash.GetHex(),fFromLoadWallet); if(wtxIn.IsAdvertise()) AddAdvertiseTx(wtxIn,fFromLoadWallet); else if(wtxIn.IsSysMessage()) AddSysmessageTx(wtxIn,fFromLoadWallet); else if(wtxIn.IsFilterAd()) AddAdFilterTx(wtxIn,fFromLoadWallet); if (fFromLoadWallet) { mapWallet[hash] = wtxIn; mapWallet[hash].BindWallet(this); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { int64_t latestNow = wtx.nTimeReceived; int64_t latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx* const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry* const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } AddToSpends(hash); } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } #ifdef DPOS if(wtx.blockHeight != wtxIn.blockHeight) { wtx.blockHeight = wtxIn.blockHeight; fUpdated = true; } #endif } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // Break debit/credit balance caches: wtx.MarkDirty(); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if (!strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } #ifdef DPOS if(wtxIn.IsEntrust()) { for(int i=0; i<wtxIn.vout.size(); i++) { const CTxOut& txout = wtxIn.vout[i]; if(txout.IsEntrusted()) { COutPoint outpoint(wtxIn.GetHash(),i); LockCoin(outpoint); } } } else if(wtxIn.IsDeprive()) { for(int i=0; i<wtxIn.vin.size(); i++) { const CTxIn& txin = wtxIn.vin[i]; COutPoint outpoint(txin.prevout); UnlockCoin(outpoint); } } else if(wtxIn.IsCreateAgent()) { for(int i=0;i<wtxIn.vout.size();++i) { const CTxOut& txout = wtxIn.vout[i]; if(txout.IsCreateAgentType()) { COutPoint outpoint(wtxIn.GetHash(),i); LockCoin(outpoint); } } } else if(wtxIn.IsResignAgent()) { for(int i=0; i<wtxIn.vin.size(); i++) { const CTxIn& txin = wtxIn.vin[i]; COutPoint outpoint(txin.prevout); UnlockCoin(outpoint); } } else { // do nothing for normal transaction. } #endif return true; } /** * Add a transaction to the wallet, or update it. * pblock is optional, but should be provided if the transaction is known to be in a block. * If fUpdate is true, existing transactions will be updated. */ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { AssertLockHeld(cs_wallet); if(tx.IsAdvertise() || tx.IsSysMessage() || tx.IsFilterAd()) { CWalletTx wtx(this, tx); if (pblock) wtx.SetMerkleBranch(*pblock); AddToWallet(wtx); } bool fExisted = mapWallet.count(tx.GetHash()) != 0; if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this, tx); // Get merkle branch if transaction was found in a block if (pblock) { #ifdef DPOS if(mode==Mode::APP) { assert(pblock->height != invalidBlockHeight); wtx.blockHeight = pblock->height; } #endif wtx.SetMerkleBranch(*pblock); } IsMine_Each(tx); return AddToWallet(wtx); } } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) { LOCK2(cs_main, cs_wallet); if (!AddToWalletIfInvolvingMe(tx, pblock, true)) return; // Not one of ours // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (!tx.IsZerocoinSpend() && mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } } void CWallet::EraseFromWallet(const uint256& hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } isminetype CWallet::IsMine(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsMine(prev.vout[txin.prevout.n]); } } return ISMINE_NO; } bool CWallet::IsMyZerocoinSpend(const CBigNum& bnSerial) const { return CWalletDB(strWalletFile).ReadZerocoinSpendSerialEntry(bnSerial); } CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n]) & filter) return prev.vout[txin.prevout.n].nValue; } } return 0; } // Recursively determine the rounds of a given input (How deep is the Obfuscation chain for a given input) int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const { static std::map<uint256, CMutableTransaction> mDenomWtxes; if (rounds >= 16) return 15; // 16 rounds max uint256 hash = in.prevout.hash; unsigned int nout = in.prevout.n; const CWalletTx* wtx = GetWalletTx(hash); if (wtx != NULL) { std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash); // not known yet, let's add it if (mdwi == mDenomWtxes.end()) { LogPrint("obfuscation", "GetInputObfuscationRounds INSERTING %s\n", hash.ToString()); mDenomWtxes[hash] = CMutableTransaction(*wtx); } // found and it's not an initial value, just return it else if (mDenomWtxes[hash].vout[nout].nRounds != -10) { return mDenomWtxes[hash].vout[nout].nRounds; } // bounds check if (nout >= wtx->vout.size()) { // should never actually hit this LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4); return -4; } if (pwalletMain->IsCollateralAmount(wtx->vout[nout].nValue)) { mDenomWtxes[hash].vout[nout].nRounds = -3; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } //make sure the final output is non-denominate if (/*rounds == 0 && */ !IsDenominatedAmount(wtx->vout[nout].nValue)) //NOT DENOM { mDenomWtxes[hash].vout[nout].nRounds = -2; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } bool fAllDenoms = true; BOOST_FOREACH (CTxOut out, wtx->vout) { fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue); } // this one is denominated but there is another non-denominated output found in the same tx if (!fAllDenoms) { mDenomWtxes[hash].vout[nout].nRounds = 0; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } int nShortest = -10; // an initial value, should be no way to get this by calculations bool fDenomFound = false; // only denoms here so let's look up BOOST_FOREACH (CTxIn in2, wtx->vin) { if (IsMine(in2)) { int n = GetRealInputObfuscationRounds(in2, rounds + 1); // denom found, find the shortest chain or initially assign nShortest with the first found value if (n >= 0 && (n < nShortest || nShortest == -10)) { nShortest = n; fDenomFound = true; } } } mDenomWtxes[hash].vout[nout].nRounds = fDenomFound ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed : 0; // too bad, we are the fist one in that chain LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } return rounds - 1; } // respect current settings int CWallet::GetInputObfuscationRounds(CTxIn in) const { LOCK(cs_wallet); int realObfuscationRounds = GetRealInputObfuscationRounds(in, 0); return realObfuscationRounds > nZeromintPercentage ? nZeromintPercentage : realObfuscationRounds; } bool CWallet::IsDenominated(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); } } return false; } bool CWallet::IsDenominated(const CTransaction& tx) const { /* Return false if ANY inputs are non-denom */ bool ret = true; BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (!IsDenominated(txin)) { ret = false; } } return ret; } bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const { BOOST_FOREACH (CAmount d, obfuScationDenominations) if (nInputAmount == d) return true; return false; } bool CWallet::IsChange(const CTxOut& txout) const { // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a script that is ours, but is not in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (::IsMine(*this, txout.scriptPubKey)) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) return true; LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int64_t CWalletTx::GetComputedTxTime() const { LOCK(cs_main); int64_t nTime = GetTxTime(); if (IsZerocoinSpend() || IsZerocoinMint()) { if (IsInMainChain()) return mapBlockIndex.at(hashBlock)->GetBlockTime(); else return nTimeReceived; } return nTime; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: CAmount nDebit = GetDebit(filter); if (nDebit > 0) // debit>0 means we signed/sent this transaction { CAmount nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. for (unsigned int i = 0; i < vout.size(); ++i) { const CTxOut& txout = vout[i]; isminetype fIsMine = pwallet->IsMine(txout); // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; } else if (!(fIsMine & filter) && !IsZerocoinSpend()) continue; // In either case, we need to get the destination address CTxDestination address; if (txout.scriptPubKey.IsZerocoinMint()) { address = CNoDestination(); } else if (!ExtractDestination(txout.scriptPubKey, address)) { if (!IsCoinStake() && !IsCoinBase()) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); } address = CNoDestination(); } COutputEntry output = {address, txout.nValue, (int)i}; // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(output); // If we are receiving the output, add it as a "received" entry if (fIsMine & filter) listReceived.push_back(output); } } void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { BOOST_FOREACH (const COutputEntry& s, listSent) nSent += s.amount; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH (const COutputEntry& r, listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) nReceived += r.amount; } else if (strAccount.empty()) { nReceived += r.amount; } } } } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } /** * Scan the block chain (starting in pindexStart) for transactions * from or to us. If fUpdate is true, found transactions that already * exist in the wallet will be updated. */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; int64_t nNow = GetTime(); CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) pindex = chainActive.Next(pindex); ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; ReadBlockFromDisk(block, pindex); #ifdef DPOS assert(pindex->nHeight != invalidBlockHeight); block.height = pindex->nHeight; #endif BOOST_FOREACH (CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } return ret; } void CWallet::ReacceptWalletTransactions() { LOCK2(cs_main, cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); int nDepth = wtx.GetDepthInMainChain(); if (!wtx.IsCoinBase() && !wtx.IsCoinStake() && nDepth < 0) { // Try to add to memory pool LOCK(mempool.cs); wtx.AcceptToMemoryPool(false); } } } void CWalletTx::Init(const CWallet* pwalletIn) { pwallet = pwalletIn; mapValue.clear(); vOrderForm.clear(); fTimeReceivedIsTxTime = false; nTimeReceived = 0; nTimeSmart = 0; fFromMe = false; strFromAccount.clear(); fDebitCached = false; fCreditCached = false; fImmatureCreditCached = false; fAvailableCreditCached = false; fAnonymizableCreditCached = false; fAnonymizedCreditCached = false; fDenomUnconfCreditCached = false; fDenomConfCreditCached = false; fWatchDebitCached = false; fWatchCreditCached = false; fImmatureWatchCreditCached = false; fAvailableWatchCreditCached = false; fChangeCached = false; nDebitCached = 0; nCreditCached = 0; nImmatureCreditCached = 0; nAvailableCreditCached = 0; nAnonymizableCreditCached = 0; nAnonymizedCreditCached = 0; nDenomUnconfCreditCached = 0; nDenomConfCreditCached = 0; nWatchDebitCached = 0; nWatchCreditCached = 0; nAvailableWatchCreditCached = 0; nImmatureWatchCreditCached = 0; nChangeCached = 0; nOrderPos = -1; #ifdef DPOS blockHeight = invalidBlockHeight; #endif } bool CWalletTx::InMempool() const { LOCK(mempool.cs); if (mempool.exists(GetHash())) { return true; } return false; } bool CWalletTx::IsTrusted() const { // Quick answer in most cases if (!IsFinalTx(*this)) return false; int nDepth = GetDepthInMainChain(); if (nDepth >= 1) return true; if (nDepth < 0) return false; if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit return false; // Trusted if all inputs are from us and are in the mempool: BOOST_FOREACH (const CTxIn& txin, vin) { // Transactions not sent by us: not trusted const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash); if (parent == NULL) return false; const CTxOut& parentOut = parent->vout[txin.prevout.n]; if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE) return false; } return true; } void CWalletTx::RelayWalletTransaction(std::string strCommand) { LOCK(cs_main); if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); LogPrintf("Relaying wtx %s\n", hash.ToString()); if (strCommand == "ix") { mapTxLockReq.insert(make_pair(hash, (CTransaction) * this)); CreateNewLock(((CTransaction) * this)); RelayTransactionLockReq((CTransaction) * this, true); } else { RelayTransaction((CTransaction) * this); } } } } set<uint256> CWalletTx::GetConflicts() const { set<uint256> result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); result.erase(myHash); } return result; } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. if (GetTime() < nNextResend) return; bool fFirst = (nNextResend == 0); nNextResend = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time if (nTimeBestReceived < nLastResend) return; nLastResend = GetTime(); // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } /** @} */ // end of mapWallet /** @defgroup Actions * * @{ */ CAmount CWallet::GetBalance() const { //LogPrintf("CWallet::GetBalance|mapWallet.size=%lld\n",mapWallet.size()); CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; bool trusted = pcoin->IsTrusted(); //LogPrintf("CWallet::GetBalance|pcoin=%s,pcoin->IsTrusted()=%d\n",pcoin->GetHash().ToString(),trusted); if (trusted) { CAmount credit = pcoin->GetAvailableCredit(); //LogPrintf("CWallet::GetBalance|credit=%lld\n",credit); nTotal += credit; } } } return nTotal; } CAmount CWallet::GetMasternodeLockedBalance() const { LOCK2(cs_main, cs_wallet); CAmount nTotal = 0; for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin && pcoin->IsTrusted()) nTotal += pcoin->GetMasternodeLockedCredit(); } return nTotal; } CAmount CWallet::GetZerocoinBalance(bool fMatureOnly) const { CAmount nTotal = 0; //! zerocoin specific fields std::map<libzerocoin::CoinDenomination, unsigned int> myZerocoinSupply; for (auto& denom : libzerocoin::zerocoinDenomList) { myZerocoinSupply.insert(make_pair(denom, 0)); } { LOCK2(cs_main, cs_wallet); // Get Unused coins list<CZerocoinMint> listPubCoin = CWalletDB(strWalletFile).ListMintedCoins(true, fMatureOnly, true); LogPrint("zero","CWallet::GetZerocoinBalance | info | listPubCoin.size=%u\n",listPubCoin.size()); for (auto& mint : listPubCoin) { libzerocoin::CoinDenomination denom = mint.GetDenomination(); nTotal += libzerocoin::ZerocoinDenominationToAmount(denom); myZerocoinSupply.at(denom)++; } } for (auto& denom : libzerocoin::zerocoinDenomList) { LogPrint("zero","%s My coins for denomination %d pubcoin %s\n", __func__,denom, myZerocoinSupply.at(denom)); } LogPrint("zero","Total value of coins %d\n",nTotal); if (nTotal < 0 ) nTotal = 0; // Sanity never hurts return nTotal; } CAmount CWallet::GetImmatureZerocoinBalance() const { return GetZerocoinBalance(false) - GetZerocoinBalance(true); } CAmount CWallet::GetUnconfirmedZerocoinBalance() const { CAmount nUnconfirmed = 0; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true); std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapUnconfirmed.insert(make_pair(denom, 0)); } { LOCK2(cs_main, cs_wallet); for (auto& mint : listMints){ if (!mint.GetHeight() || mint.GetHeight() > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) { libzerocoin::CoinDenomination denom = mint.GetDenomination(); nUnconfirmed += libzerocoin::ZerocoinDenominationToAmount(denom); mapUnconfirmed.at(denom)++; } } } for (auto& denom : libzerocoin::zerocoinDenomList) { LogPrint("zero","%s My unconfirmed coins for denomination %d pubcoin %s\n", __func__,denom, mapUnconfirmed.at(denom)); } LogPrint("zero","Total value of unconfirmed coins %ld\n", nUnconfirmed); if (nUnconfirmed < 0 ) nUnconfirmed = 0; // Sanity never hurts return nUnconfirmed; } CAmount CWallet::GetUnlockedCoins() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) nTotal += pcoin->GetUnlockedCredit(); } } return nTotal; } CAmount CWallet::GetLockedCoins() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) nTotal += pcoin->GetLockedCredit(); } } return nTotal; } // Get a Map pairing the Denominations with the amount of Zerocoin for each Denomination std::map<libzerocoin::CoinDenomination, CAmount> CWallet::GetMyZerocoinDistribution() const { std::map<libzerocoin::CoinDenomination, CAmount> spread; for (const auto& denom : libzerocoin::zerocoinDenomList) spread.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0)); { LOCK2(cs_main, cs_wallet); list<CZerocoinMint> listPubCoin = CWalletDB(strWalletFile).ListMintedCoins(true, true, true); for (auto& mint : listPubCoin) spread.at(mint.GetDenomination())++; } return spread; } CAmount CWallet::GetAnonymizableBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizedCredit(); } } return nTotal; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only double CWallet::GetAverageAnonymizedRounds() const { if (fLiteMode) return 0; double fTotal = 0; double fCount = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; int rounds = GetInputObfuscationRounds(vin); fTotal += (float)rounds; fCount += 1; } } } if (fCount == 0) return 0; return fTotal / fCount; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only CAmount CWallet::GetNormalizedAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; if (pcoin->GetDepthInMainChain() < 0) continue; int rounds = GetInputObfuscationRounds(vin); nTotal += pcoin->vout[i].nValue * rounds / nZeromintPercentage; } } } return nTotal; } CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetDenominatedCredit(unconfirmed); } } return nTotal; } CAmount CWallet::GetUnconfirmedBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetImmatureBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetImmatureWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } } return nTotal; } /** * populate vCoins with vector of available COutputs. */ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseIX) const { #ifdef DPOS bool forDepriveTx = (coinControl && coinControl->txType==CTransaction::Type::DEPRIVE); #endif vCoins.clear(); { LOCK2(cs_main, cs_wallet); //LogPrint("miner","CWallet::AvailableCoins | fOnlyConfirmed=%d, coinControl=%p, fIncludeZeroValue=%d, nCoinType=%d, fUseIX=%d, mapWallet.size=%u, forDepriveTx=%d\n",fOnlyConfirmed, coinControl, fIncludeZeroValue, nCoinType, fUseIX,mapWallet.size(),forDepriveTx); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const uint256& txid = it->first; const CWalletTx* tx = &(*it).second; if (!CheckFinalTx(*tx)){ //LogPrint("miner","CWallet::AvailableCoins | CheckFinalTx() false, txid=%s\n",txid.ToString()); continue; } #ifdef DPOS if(forDepriveTx) { //为‘取消委托’交易选择VIN时,过滤掉不相关AGENT的委托交易 assert(tx); assert(coinControl); if(tx->GetAgentId() != coinControl->agentid){ //LogPrint("miner","CWallet::AvailableCoins | tx->GetAgentId()=%s, coinControl->agentid=%s, txid=%s\n",tx->GetAgentId().ToString(),coinControl->agentid.ToString(),txid.ToString()); continue; } } #endif if (fOnlyConfirmed && !tx->IsTrusted()){ //LogPrint("miner","CWallet::AvailableCoins | tx->IsTrusted() false, txid=%s\n",txid.ToString()); continue; } if ((tx->IsCoinBase() || tx->IsCoinStake()) && tx->GetBlocksToMaturity() > 0){ //LogPrint("miner","CWallet::AvailableCoins | tx->GetBlocksToMaturity()=%d, txid=%s\n",tx->GetBlocksToMaturity(),txid.ToString()); continue; } int nDepth = tx->GetDepthInMainChain(false); // do not use IX for inputs that have less then 6 blockchain confirmations if (fUseIX && nDepth < 6){ //LogPrint("miner","CWallet::AvailableCoins | nDepth=%d, txid=%s\n",nDepth,txid.ToString()); continue; } // We should not consider coins which aren't at least in our mempool // It's possible for these to be conflicted via ancestors which we may never be able to detect if (nDepth == 0 && !tx->InMempool()){ //LogPrint("miner","CWallet::AvailableCoins | tx->InMempool() false, txid=%s\n",txid.ToString()); continue; } for (unsigned int n = 0; n < tx->vout.size(); n++) { const CTxOut& txout = tx->vout[n]; const CAmount nValue = txout.nValue; bool found = false; if (nCoinType == ONLY_DENOMINATED) { found = IsDenominatedAmount(nValue); } else if (nCoinType == ONLY_NOT10000IFMN) { found = !(fMasterNode && nValue == MASTERNODE_COIN_AMOUNT * COIN); } else if (nCoinType == ONLY_NONDENOMINATED_NOT10000IFMN) { if (IsCollateralAmount(nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(nValue); if (found && fMasterNode) found = nValue != MASTERNODE_COIN_AMOUNT * COIN; // do not use Hot MN funds } else if (nCoinType == ONLY_10000) { found = nValue == MASTERNODE_COIN_AMOUNT * COIN; } else { found = true; } if (!found){ //LogPrint("miner","CWallet::AvailableCoins | vout not found, %s:%d\n",txid.ToString(),n); continue; } if (nCoinType == STAKABLE_COINS) { if (txout.IsZerocoinMint()){ //LogPrint("miner","CWallet::AvailableCoins | vout is zerocoinmint, %s:%d\n",txid.ToString(),n); continue; } } isminetype mine = IsMine(txout); if (IsSpent(txid, n)){ //LogPrint("miner","CWallet::AvailableCoins | vout spent, %s:%d\n",txid.ToString(),n); continue; } if (mine == ISMINE_NO){ //LogPrint("miner","CWallet::AvailableCoins | vout isn't mine, %s:%d\n",txid.ToString(),n); continue; } if (mine == ISMINE_WATCH_ONLY){ //LogPrint("miner","CWallet::AvailableCoins | vout is watch only, %s:%d\n",txid.ToString(),n); continue; } #ifdef DPOS if (!forDepriveTx) { //委托的vout是被锁定的,但可以用于‘取消委托’交易的vin。 //所以,仅当为普通交易选择vin时,才做IsLockedCoin检查。 if(IsLockedCoin(txid, n) && nCoinType != ONLY_10000){ //LogPrint("miner","CWallet::AvailableCoins | DPOS mode | vout is locked, %s:%d\n",txid.ToString(),n); continue; } } #else if (IsLockedCoin(txid, n) && nCoinType != ONLY_10000){ //LogPrint("miner","CWallet::AvailableCoins | vout is locked, %s:%d\n",txid.ToString(),n); continue; } #endif if (nValue <= 0 && !fIncludeZeroValue){ //LogPrint("miner","CWallet::AvailableCoins | nValue=%lld, %s:%d\n",nValue,txid.ToString(),n); continue; } if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(txid, n)){ //LogPrint("miner","CWallet::AvailableCoins | vout is controled, %s:%d\n",txid.ToString(),n); continue; } #ifdef DPOS if(forDepriveTx) { //没有委托的out 或 在锁定期间的out 不能作为 ‘取消委托’交易的vin if((!txout.IsEntrusted() || tx->IsInDepriveLockingTime(chainActive.Height()))){ //LogPrint("miner","CWallet::AvailableCoins | txout.IsEntrusted()=%d, chainActive.Height()=%d, %s:%d\n",txout.IsEntrusted(),chainActive.Height(),txid.ToString(),n); continue; } } else { //已委托的out 不能作为 普通交易或委托交易的vin if(txout.IsEntrusted()){ //LogPrint("miner","CWallet::AvailableCoins | txout.IsEntrusted() true, %s:%d\n",txid.ToString(),n); continue; } } if(txout.IsCreateAgentType()){ //LogPrint("miner","CWallet::AvailableCoins | txout.IsCreateAgentType() true, %s:%d\n",txid.ToString(),n); continue; } #endif bool fIsSpendable = false; if ((mine & ISMINE_SPENDABLE) != ISMINE_NO) fIsSpendable = true; if ((mine & ISMINE_MULTISIG) != ISMINE_NO) fIsSpendable = true; vCoins.emplace_back(COutput(tx, n, nDepth, fIsSpendable)); } } } } map<CBitcoinAddress, vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue) { vector<COutput> vCoins; AvailableCoins(vCoins, fConfirmed); map<CBitcoinAddress, vector<COutput> > mapCoins; BOOST_FOREACH (COutput out, vCoins) { if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue) continue; CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address)].push_back(out); } return mapCoins; } static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand() & 1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // TODO: find appropriate place for this sort function // move denoms down bool less_then_denom(const COutput& out1, const COutput& out2) { const CWalletTx* pcoin1 = out1.tx; const CWalletTx* pcoin2 = out2.tx; bool found1 = false; bool found2 = false; BOOST_FOREACH (CAmount d, obfuScationDenominations) // loop through predefined denoms { if (pcoin1->vout[out1.i].nValue == d) found1 = true; if (pcoin2->vout[out2.i].nValue == d) found2 = true; } return (!found1 && found2); } bool CWallet::SelectStakeCoins(std::set<std::pair<const CWalletTx*, unsigned int>>& setCoins, CAmount nTargetAmount) const { //LogPrint("miner","CWallet::SelectStakeCoins | pos | nTargetAmount=%lld\n",nTargetAmount); LOCK(cs_main); vector<COutput> vCoins; std::set<pair<const CWalletTx*, unsigned int>, CompareStakeCoin > setStakeCandidate; AvailableCoins(vCoins, true, NULL, false, STAKABLE_COINS); LogPrint("miner","CWallet::SelectStakeCoins | pos | vCoins.size=%lld\n",vCoins.size()); CAmount nAmountSelected = 0; int debugCount[4] = {0}; for (const COutput& out : vCoins) { const CWalletTx* tx = out.tx; const uint256 txid = tx->GetHash(); const CTxOut& txout = tx->vout[out.i]; const CAmount nValue = txout.nValue; //make sure not to outrun target amount if (nAmountSelected + nValue > nTargetAmount){ //LogPrint("miner","CWallet::SelectStakeCoins | nAmountSelected=%lld, nValue=%lld, nTargetAmount=%lld\n", nAmountSelected, nValue, nTargetAmount); continue; } if (tx->IsZerocoinSpend() && !tx->IsInMainChain()){ //LogPrint("miner","CWallet::SelectStakeCoins | tx is zerocoin spent and is not in the main chain. txid=%s\n",txid.ToString()); continue; } if (!tx->hashBlock){ //LogPrint("miner","CWallet::SelectStakeCoins | blockhash of tx invalid. txid=%s\n",txid.ToString()); continue; } //check for min age CBlockIndex* utxoBlock = mapBlockIndex.at(tx->hashBlock); if (GetAdjustedTime() - utxoBlock->GetBlockTime() < nStakeMinAge){ //LogPrint("miner","CWallet::SelectStakeCoins | min age not match. GetAdjustedTime()=%lld, utxoBlock->GetBlockTime()=%lld, nStakeMinAge=%u, txid=%s\n",GetAdjustedTime(), utxoBlock->GetBlockTime(), nStakeMinAge,txid.ToString()); continue; } //check that it is matured if (out.nDepth < (tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10)){ //LogPrint("miner","CWallet::SelectStakeCoins | maturity not match. out.nDepth=%d, tx->IsCoinStake()=%d, Params().COINBASE_MATURITY()=%d, txid=%s\n",out.nDepth, tx->IsCoinStake(), Params().COINBASE_MATURITY(),txid.ToString()); continue; } //add to our stake set //setCoins.insert(make_pair(out.tx, out.i)); setStakeCandidate.insert(make_pair(out.tx, out.i)); nAmountSelected += out.tx->vout[out.i].nValue; } //LogPrint("miner","CWallet::SelectStakeCoins | setStakeCandidate.size=%d\n",setStakeCandidate.size()); BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCandidate) { setCoins.insert(make_pair(pcoin.first, pcoin.second)); if (setCoins.size() >= 1000){ break; } } LogPrint("miner","CWallet::SelectStakeCoins | setCoins.size=%d\n",setCoins.size()); return true; } bool CWallet::MintableCoins() { LOCK(cs_main); CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("MintableCoins() : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; vector<COutput> vCoins; AvailableCoins(vCoins, true); for (const COutput& out : vCoins) { int64_t nTxTime = out.tx->GetTxTime(); if (out.tx->IsZerocoinSpend()) { if (!out.tx->IsInMainChain()) continue; nTxTime = mapBlockIndex.at(out.tx->hashBlock)->GetBlockTime(); } if (GetAdjustedTime() - nTxTime > nStakeMinAge) return true; } return false; } int CWallet::GetStakableCoinsNum() const { LOCK(cs_main); vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, false, STAKABLE_COINS); int count = 0; for (const COutput& out : vCoins) { const CWalletTx* tx = out.tx; if (tx->IsZerocoinSpend() && !tx->IsInMainChain()) continue; if (!tx->hashBlock) continue; CBlockIndex* utxoBlock = mapBlockIndex.at(tx->hashBlock); if (GetAdjustedTime() - utxoBlock->GetBlockTime() < nStakeMinAge) continue; if (out.nDepth < (tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10)) continue; count++; } return count; } bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<CAmount, pair<const CWalletTx*, unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<CAmount>::max(); coinLowestLarger.second.first = NULL; vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue; CAmount nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; BOOST_FOREACH (const COutput& output, vCoins) { if (!output.fSpendable) continue; const CWalletTx* pcoin = output.tx; // if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth); if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) continue; int i = output.i; CAmount n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run pair<CAmount, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue { if (tryDenom == 0) // we didn't look at denom yet, let's do it continue; else // we looked at everything possible and didn't find anything, no luck return false; } setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // nTotalLower > nTargetValue break; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; CAmount nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { string s = "CWallet::SelectCoinsMinConf best subset: "; for (unsigned int i = 0; i < vValue.size(); i++) { if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; s += FormatMoney(vValue[i].first) + " "; } } LogPrintf("%s - total %s\n", s, FormatMoney(nBest)); } return true; } bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { //LogPrintf("DPOS CWallet::SelectCoins | nTargetValue=%s,coin_type=%d\n",FormatMoney(nTargetValue),static_cast<int>(coin_type)); // Note: this function should never be used for "always free" tx types like dstx vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX); //#ifdef DPOS //LogPrintf("DPOS CWallet::SelectCoins | AvailableCoins, vCoins.size=%d\n",vCoins.size()); //for(COutput& out : vCoins) // LogPrintf("DPOS CWallet::SelectCoins | AvailableCoins, tx=%s, vout=%d\n",out.tx->GetHash().ToString(),out.i); //#endif if(coinControl && coinControl->nMinUtxoValue > 0){ BOOST_FOREACH (const COutput& out, vCoins) { if (!out.fSpendable) continue; CAmount nValue = out.tx->vout[out.i].nValue; if(nValue < coinControl->nMinUtxoValue) continue; nValueRet += nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); if (nValueRet >= nTargetValue) return true; } return (nValueRet >= nTargetValue); } // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH (const COutput& out, vCoins) { if (!out.fSpendable) continue; if (coin_type == ONLY_DENOMINATED) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nZeromintPercentage) continue; } else if (coinControl->IsSelected(out.tx->GetHash(), out.i)) { nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); if (nValueRet >= nTargetValue) return true; } } BOOST_FOREACH (const COutput& out, vCoins) { if (!out.fSpendable) continue; if (coin_type == ONLY_DENOMINATED) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nZeromintPercentage) continue; } else if (!coinControl->IsSelected(out.tx->GetHash(), out.i)) { nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); if (nValueRet >= nTargetValue) return true; } } return (nValueRet >= nTargetValue); } //if we're doing only denominated, we need to round up to the nearest .1 GKC if (coin_type == ONLY_DENOMINATED) { // Make outputs by looping through denominations, from large to small BOOST_FOREACH (CAmount v, obfuScationDenominations) { BOOST_FOREACH (const COutput& out, vCoins) { if (out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1 * COIN) + 100 //round the amount up to .1 GKC over ) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nZeromintPercentage) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } } } return (nValueRet >= nTargetValue); } return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet))); } struct CompareByPriority { bool operator()(const COutput& t1, const COutput& t2) const { return t1.Priority() > t2.Priority(); } }; bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vCoinsRet, std::vector<COutput>& vCoinsRet2, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) { vCoinsRet.clear(); nValueRet = 0; vCoinsRet2.clear(); vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, ONLY_DENOMINATED); std::random_shuffle(vCoins.rbegin(), vCoins.rend()); //keep track of each denomination that we have bool fFound10000 = false; bool fFound1000 = false; bool fFound100 = false; bool fFound10 = false; bool fFound1 = false; bool fFoundDot1 = false; //Check to see if any of the denomination are off, in that case mark them as fulfilled if (!(nDenom & (1 << 0))) fFound10000 = true; if (!(nDenom & (1 << 1))) fFound1000 = true; if (!(nDenom & (1 << 2))) fFound100 = true; if (!(nDenom & (1 << 3))) fFound10 = true; if (!(nDenom & (1 << 4))) fFound1 = true; if (!(nDenom & (1 << 5))) fFoundDot1 = true; BOOST_FOREACH (const COutput& out, vCoins) { // masternode-like input should not be selected by AvailableCoins now anyway //if(out.tx->vout[out.i].nValue == 10000*COIN) continue; if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { bool fAccepted = false; // Function returns as follows: // // bit 0 - 10000 GKC+1 ( bit on if present ) // bit 1 - 1000 GKC+1 // bit 2 - 100 GKC+1 // bit 3 - 10 GKC+1 // bit 4 - 1 GKC+1 // bit 5 - .1 GKC+1 CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; if (fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1) { //if fulfilled //we can return this for submission if (nValueRet >= nValueMin) { //random reduce the max amount we'll submit for anonymity nValueMax -= (rand() % (nValueMax / 5)); //on average use 50% of the inputs or less int r = (rand() % (int)vCoins.size()); if ((int)vCoinsRet.size() > r) return true; } //Denomination criterion has been met, we can take any matching denominations if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) { fAccepted = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; } } else { //Criterion has not been satisfied, we will only take 1 of each until it is. if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; fFound10000 = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) { fAccepted = true; fFound1000 = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; fFound100 = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; fFound10 = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; fFound1 = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; fFoundDot1 = true; } } if (!fAccepted) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; vCoinsRet.push_back(vin); vCoinsRet2.push_back(out); } } return (nValueRet >= nValueMin && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); } bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) const { CCoinControl* coinControl = NULL; setCoinsRet.clear(); nValueRet = 0; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, nObfuscationRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT10000IFMN : ONLY_DENOMINATED); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; //order the array so largest nondenom are first, then denominations, then very small inputs. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); BOOST_FOREACH (const COutput& out, vCoins) { //do not allow inputs less than 1 CENT if (out.tx->vout[out.i].nValue < CENT) continue; //do not allow collaterals to be selected if (IsCollateralAmount(out.tx->vout[out.i].nValue)) continue; if (fMasterNode && out.tx->vout[out.i].nValue == MASTERNODE_COIN_AMOUNT * COIN) continue; //masternode input if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); } } // if it's more than min, we're good to return if (nValueRet >= nValueMin) return true; return false; } bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet) const { vector<COutput> vCoins; //LogPrintf(" selecting coins for collateral\n"); AvailableCoins(vCoins); //LogPrintf("found coins %d\n", (int)vCoins.size()); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; BOOST_FOREACH (const COutput& out, vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if (IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); return true; } } return false; } int CWallet::CountInputsWithAmount(CAmount nInputAmount) { CAmount nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(false); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { COutput out = COutput(pcoin, i, nDepth, true); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); if (out.tx->vout[out.i].nValue != nInputAmount) continue; if (!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; if (IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; nTotal++; } } } } return nTotal; } bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const { vector<COutput> vCoins; AvailableCoins(vCoins, fOnlyConfirmed); int nFound = 0; BOOST_FOREACH (const COutput& out, vCoins) if (IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 0; } bool CWallet::IsCollateralAmount(CAmount nInputAmount) const { return nInputAmount != 0 && nInputAmount % OBFUSCATION_COLLATERAL == 0 && nInputAmount < OBFUSCATION_COLLATERAL * 5 && nInputAmount > OBFUSCATION_COLLATERAL; } bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason) { /* To doublespend a collateral transaction, it will require a fee higher than this. So there's still a significant cost. */ CAmount nFeeRet = 1 * COIN; txCollateral.vin.clear(); txCollateral.vout.clear(); CReserveKey reservekey(this); CAmount nValueIn2 = 0; std::vector<CTxIn> vCoinsCollateral; if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) { strReason = "Error: Obfuscation requires a collateral transaction and could not locate an acceptable input!"; return false; } // make our change address CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); BOOST_FOREACH (CTxIn v, vCoinsCollateral) txCollateral.vin.push_back(v); if (nValueIn2 - OBFUSCATION_COLLATERAL - nFeeRet > 0) { //pay collateral charge in fees CTxOut vout3 = CTxOut(nValueIn2 - OBFUSCATION_COLLATERAL, scriptChange); txCollateral.vout.push_back(vout3); } int vinNumber = 0; BOOST_FOREACH (CTxIn v, txCollateral.vin) { if (!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { BOOST_FOREACH (CTxIn v, vCoinsCollateral) UnlockCoin(v.prevout); strReason = "CObfuscationPool::Sign - Unable to sign collateral transaction! \n"; return false; } vinNumber++; } return true; } bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, bool useIX) { CWalletTx wtx; if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) { tx = (CTransaction)wtx; return true; } return false; } bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX) { // make our change address CReserveKey reservekey(pwalletMain); CScript scriptChange; scriptChange << OP_RETURN << ToByteVector(hash); CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX)); CCoinControl* coinControl = NULL; bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0); if (!success) { LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail); return false; } return true; } bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<CAmount>& vecAmounts) { BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); } } else { LogPrintf("ConvertList -- Couldn't find transaction\n"); } } return true; } bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay, CAmount nGasFee, bool hasSender) { #ifdef DPOS //存储通过wtxNew传进来的参数 CTransaction::Type txType = wtxNew.GetType(); uint256 agentid = wtxNew.GetAgentId(); #endif if (useIX && nFeePay < CENT) nFeePay = CENT; CAmount nValue = 0; COutPoint senderInput; if(hasSender && coinControl->HasSelected()){ std::vector<COutPoint> vSenderInputs; coinControl->ListSelected(vSenderInputs); senderInput=vSenderInputs[0]; } BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { if (nValue < 0 || s.second < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(this); CMutableTransaction txNew; #ifdef DPOS txNew.type = txType; txNew.agentid = agentid; #endif { LOCK2(cs_main, cs_wallet); { nFeeRet = 0; if (nFeePay > 0) nFeeRet = nFeePay; while (true) { txNew.vin.clear(); txNew.vout.clear(); wtxNew.fFromMe = true; CAmount nTotalValue = nValue + nFeeRet + nGasFee; double dPriority = 0; // vouts to the payees if (coinControl && !coinControl->fSplitBlock) { BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { CTxOut txout(s.second, s.first); #ifdef DPOS if(txType==CTransaction::Type::ENTRUST) txout.SetType(CTxOut::Type::ENTRUST); else if(txType==CTransaction::Type::CREATE_AGENT && s.second > 0) txout.SetType(CTxOut::Type::CREATE_AGENT); #endif if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } txNew.vout.push_back(txout); } } else //UTXO Splitter Transaction { int nSplitBlock; if (coinControl) nSplitBlock = coinControl->nSplitBlock; else nSplitBlock = 1; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { for (int i = 0; i < nSplitBlock; i++) { CTxOut txout; if (i == nSplitBlock - 1) { uint64_t nRemainder = s.second % nSplitBlock; txout = CTxOut((s.second / nSplitBlock) + nRemainder, s.first); } else { txout = CTxOut(s.second / nSplitBlock, s.first); } #ifdef DPOS if(txType==CTransaction::Type::ENTRUST) txout.SetType(CTxOut::Type::ENTRUST); else if(txType==CTransaction::Type::CREATE_AGENT && s.second > 0) txout.SetType(CTxOut::Type::CREATE_AGENT); #endif txNew.vout.push_back(txout); } } } // Choose coins to use set<pair<const CWalletTx*, unsigned int> > setCoins; std::vector<pair<const CWalletTx*, unsigned int>> vCoins; CAmount nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) { if (coin_type == ALL_COINS) { strFailReason = _("Insufficient funds."); } else if (coin_type == ONLY_NOT10000IFMN) { strFailReason = _("Unable to locate enough funds for this transaction that are not equal 10000 GKC."); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN) { strFailReason = _("Unable to locate enough Obfuscation non-denominated funds for this transaction that are not equal 10000 GKC."); } else { strFailReason = _("Unable to locate enough Obfuscation denominated funds for this transaction."); strFailReason += " " + _("Obfuscation uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); } if (useIX) { strFailReason += " " + _("SwiftX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again."); } return false; } if(setCoins.size() > MAX_STANDARD_VIN_COUNT){ strFailReason = _("Too many inputs."); return false; } BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); if (age != 0) age += 1; dPriority += (double)nCredit * age; } CAmount nChange = nValueIn - nValue - nFeeRet - nGasFee; //over pay for denominated transactions if (coin_type == ONLY_DENOMINATED) { nFeeRet += nChange; nChange = 0; wtxNew.mapValue["DS"] = "1"; } if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-gkc-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); #ifdef DPOS // 取消委托时,找零部分继续委托 if(txType==CTransaction::Type::DEPRIVE) newTxOut.SetType(CTxOut::Type::ENTRUST); #endif // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(::minRelayTxFee)) { nFeeRet += nChange; nChange = 0; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1); txNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); vCoins.clear(); std::copy(setCoins.begin(), setCoins.end(), std::back_inserter(vCoins)); if(hasSender && coinControl->HasSelected()){ for (std::vector<pair<const CWalletTx*, unsigned int>>::size_type i = 0 ; i != vCoins.size(); i++){ COutPoint outPoint = COutPoint(vCoins[i].first->GetHash(), vCoins[i].second); if(outPoint==senderInput){ if(i==0)break; iter_swap(vCoins.begin(),vCoins.begin()+i); break; } } } // Fill vin BOOST_FOREACH (const auto & coin, vCoins){ txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); } // Sign int nIn = 0; BOOST_FOREACH (const auto & coin, vCoins) if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Embed the constructed transaction data in wtxNew. *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); #ifdef DPOS assert(wtxNew.GetType()==txType); assert(wtxNew.GetAgentId()==agentid); #endif // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Can we complete this as a free transaction? if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) { // Not enough fee: enough priority? double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget); // Not enough mempool history to estimate: use hard-coded AllowFree. if (dPriorityNeeded <= 0 && AllowFree(dPriority)) break; // Small enough, and priority high enough, to send for free if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded) break; } CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strFailReason = _("Transaction too large for fee policy"); return false; } if (nFeeRet >= nFeeNeeded) // Done, enough fee included break; // Include more fee and try again. nFeeRet = nFeeNeeded; continue; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay, CAmount nGasFee, bool hasSender) { vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); if(wtxNew.mapValue.count("comment") > 0) { advertisement::TxComment comment; comment.content = wtxNew.mapValue["comment"]; CScript commentScript; if(!comment.EncodeTo(commentScript)) { LogPrint("wallet","CWallet::CreateTransaction | encode comment script failed\n"); return false; } vecSend.push_back(make_pair(commentScript, 0)); } return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay, nGasFee, hasSender); } #ifdef DPOS bool CWallet::CreateDepriveTransaction(const CWalletTx& entrustTx, CWalletTx& wtxNew, CReserveKey& reservekey, BlockHeight chainHeight, std::string& strError) { assert(entrustTx.IsEntrust()); wtxNew.SetDeprive(); wtxNew.SetAgentId(entrustTx.agentid); int voutIndex = -1; CTxOut entrustTxOut; if(!entrustTx.GetEntrustOut(entrustTxOut,voutIndex)) { strError = "!entrustTx.GetEntrustOut(entrustTxOut)"; return false; } if(entrustTx.IsInDepriveLockingTime(chainHeight)) { strError = "entrustTx.IsInDepriveLockingTime()"; return false; } return CreateCancelTx(entrustTx, entrustTxOut, voutIndex, wtxNew, strError); } bool CWallet::CreateResignAgentTx(CWalletTx& wtxNew, CReserveKey& reservekey, std::string& strError) { wtxNew.SetResignAgent(); wtxNew.SetAgentId(Entrustment::GetInstance().GetMyAgentID()); const Agent* agent = Entrustment::GetInstance().GetAgent(chainActive.Height(),wtxNew.agentid); if(!agent) { strError = "agent not found."; return false; } if(agent->Amount() > 0) { strError = "agent->Amount() > 0"; return false; } const CWalletTx* createAgentTx = GetWalletTx(wtxNew.agentid); if(!createAgentTx) { strError = "input tx(wtxNew.agentid) not found."; return false; } if(!createAgentTx->IsCreateAgent()) { strError = "!createAgentTx->IsCreateAgent()"; return false; } CTxOut createAgentOut; int createAgentOutIndex = 0; if(!createAgentTx->GetCreateAgentOut(createAgentOut,createAgentOutIndex)) { strError = "!createAgentTx->GetCreateAgentOut(createAgentOut,createAgentOutIndex)"; return false; } return CreateCancelTx(*createAgentTx,createAgentOut,createAgentOutIndex,wtxNew,strError); } bool CWallet::CreateCancelTx(const CWalletTx& inTx, const CTxOut& inTxOut, int txOutIndex, CWalletTx& wtxNew, std::string& strError) { wtxNew.BindWallet(this); wtxNew.fTimeReceivedIsTxTime = true; wtxNew.fFromMe = true; if (!CheckFinalTx(inTx)) { strError = "!CheckFinalTx(inTx)"; return false; } if (IsSpent(inTx.GetHash(), txOutIndex)) { strError = "IsSpent(inTx.GetHash(), txOutIndex)"; return false; } std::vector<CBitcoinAddress> addresses = inTxOut.GetScriptAddresses(); if(addresses.empty()) { strError = "addresses.empty()"; return false; } CBitcoinAddress myaddress = addresses[0]; CScript myScript = GetScriptForDestination(myaddress.Get()); LOCK2(cs_main, cs_wallet); CAmount nFee = 0; while (true) { if(inTxOut.nValue < nFee) { strError = ", inTxOut.nValue < nFee"; return false; } CMutableTransaction txNew; txNew.type = wtxNew.type; txNew.agentid = wtxNew.agentid; txNew.vin.push_back(CTxIn(inTx.GetHash(),txOutIndex)); txNew.vout.push_back(CTxOut(inTxOut.nValue - nFee, myScript)); if (!SignSignature(*this, inTx, txNew, 0)) { strError = "Signing transaction failed"; return false; } // Embed the constructed transaction data in wtxNew. *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strError = "Transaction too large"; return false; } int age = inTx.GetDepthInMainChain(); if (age != 0) age += 1; double dPriority = (double)inTxOut.nValue * age; dPriority = wtxNew.ComputePriority(dPriority, nBytes); CAmount nFeeNeeded = std::max(nFee, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strError = "Transaction too large for fee policy"; return false; } if (nFee >= nFeeNeeded) break; nFee = nFeeNeeded; continue; } return true; } #endif // ppcoin: create coin stake transaction bool CWallet::CreateCoinStake(const CKeyStore& keystore, CBlock* pblock, int64_t nSearchInterval, CMutableTransaction& txNew, unsigned int& nTxNewTime) { // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences //int64_t nCombineThreshold = 0; BlockHeight historyHeight = chainActive.Height(); BlockHeight newBlockHeight = historyHeight + 1; txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Add contract state. if (pblock->nVersion >= SMART_CONTRACT_VERSION) { uint256 utxoRoot; uint256 stateRoot; GetState(stateRoot, utxoRoot); LogPrintf("POS stateRoot: %s, utxoRoot: %s\n", stateRoot.GetHex().c_str(), utxoRoot.GetHex().c_str()); CScript vmstate = CScript() << ParseHex(stateRoot.GetHex().c_str()) << ParseHex(utxoRoot.GetHex().c_str()) << OP_VM_STATE; txNew.vout.push_back(CTxOut(0, vmstate)); } // Choose coins to use CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) { LogPrintf("%s:%d:%s|invalid reserve balance amount|nReserveBalance=%lld\n",nReserveBalance); return error("CreateCoinStake : invalid reserve balance amount"); } if (nBalance > 0 && nBalance <= nReserveBalance) { LogPrintf("%s:%d:%s | nBalance=%lld, nReserveBalance=%lld\n",__FILE__,__LINE__,__func__,nBalance,nReserveBalance); return false; } // presstab HyperStake - Initialize as static and don't update the set on every run of CreateCoinStake() in order to lighten resource use static std::set<pair<const CWalletTx*, unsigned int> > setStakeCoins; static int nLastStakeSetUpdate = 0; if (GetTime() - nLastStakeSetUpdate > nStakeSetUpdateTime) { setStakeCoins.clear(); if (!SelectStakeCoins(setStakeCoins, nBalance - nReserveBalance)) { LogPrintf("%s:%d:%s|SelectStakeCoins failed|nBalance=%lld, nReserveBalance=%lld\n",nBalance,nReserveBalance); return false; } nLastStakeSetUpdate = GetTime(); } if (setStakeCoins.empty()) { LogPrintf("%s:%d:%s | setStakeCoins is empty\n",__FILE__,__LINE__,__func__); return false; } //LogPrint("miner","CWallet::CreateCoinStake | setStakeCoins.size=%u\n",setStakeCoins.size()); vector<const CWalletTx*> vwtxPrev; CAmount nCredit = 0; CScript scriptPubKey; CScript scriptPubKeyOut; //prevent staking a time that won't be accepted if (GetAdjustedTime() <= chainActive.Tip()->nTime) MilliSleep(10000); BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) { // Make sure the wallet is unlocked and shutdown hasn't been requested if (IsLocked() || ShutdownRequested()){ LogPrint("miner","CWallet::CreateCoinStake | return from loop setStakeCoins | IsLocked()=%d, ShutdownRequested()=%d \n",IsLocked(),ShutdownRequested()); return false; } //make sure that enough time has elapsed between CBlockIndex* pindex = NULL; BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock); if (it != mapBlockIndex.end()) pindex = it->second; else { if (fDebug) LogPrintf("CreateCoinStake() failed to find block index \n"); continue; } // Read block header CBlockHeader block = pindex->GetBlockHeader(); bool fKernelFound = false; uint256 hashProofOfStake = 0; COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); nTxNewTime = GetAdjustedTime(); //iterates each utxo inside of CheckStakeKernelHash() #ifdef DPOS txNew.agentid = Entrustment::GetInstance().GetMyAgentID(); if (CheckStakeKernelHash(pblock->nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true, chainActive.Height(), txNew.agentid)) #else if (CheckStakeKernelHash(pblock->nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true)) #endif { //Double check that this will pass time requirements if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast()) { LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n"); continue; } // Found a kernel if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; scriptPubKeyOut.clear(); scriptPubKey = pcoin.first->vout[pcoin.second].scriptPubKey; if(newBlockHeight >= Entrustment::GetInstance().forkHeightForLockMinerRewardReceiver) scriptPubKey = dpos::GetCreatorPubKeyOf(txNew.agentid); if (!Solver(scriptPubKey, whichType, vSolutions)) { LogPrintf("CreateCoinStake : failed to parse kernel\n"); break; } if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { LogPrint("miner","CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { //convert to pay to public key type CKeyID keyID; keyID = CKeyID(uint160(vSolutions[0])); CKey key; if (!keystore.GetKey(keyID, key)) { LogPrint("miner","CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKeyOut = scriptPubKey; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); if(newBlockHeight >= Entrustment::GetInstance().forkHeightForSpecifyMinerRewardReceiver){ scriptPubKey = newBlockAddress.IsValid() ? GetScriptForDestination(newBlockAddress.Get()) : dpos::GetCreatorPubKeyOf(txNew.agentid); txNew.vout.push_back(CTxOut(0, scriptPubKey)); } else { //presstab HyperStake - calculate the total size of our new output including the stake reward so that we can use it to decide whether to split the stake outputs uint64_t nTotalSize = pcoin.first->vout[pcoin.second].nValue + crp::GetBlockValue(newBlockHeight).miner; //presstab HyperStake - if MultiSend is set to send in coinstake we will add our outputs here (values asigned further down) if (nTotalSize / 2 > nStakeSplitThreshold * COIN) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake } LogPrint("miner","CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } if (fKernelFound) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) { LogPrint("miner","CWallet::CreateCoinStake | nCredit zero | nCredit=%lld,nBalance=%lld, nReserveBalance=%lld, nHashDrift=%d\n",nCredit,nBalance,nReserveBalance,nHashDrift); return false; } FillPosBlockPayee(newBlockHeight,BLOCK_VERSION(pblock->nVersion),nCredit,txNew.vout); // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5) return error("CreateCoinStake : exceeded coinstake size limit"); // Sign int nIn = 0; BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Successfully generated coinstake nLastStakeSetUpdate = 0; //this will trigger stake set to repopulate next round return true; } /** * Call after CreateTransaction unless you want to abort */ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand) { { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Notify that old coins are spent if (!wtxNew.IsZerocoinSpend()) { set<uint256> updated_hahes; BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) { // notify only once if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue; CWalletTx& coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); updated_hahes.insert(txin.prevout.hash); } } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(strCommand); } return true; } CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool) { // payTxFee is user-set "I want to pay this much" CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes); // user selected total at least (default=true) if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK()) nFeeNeeded = payTxFee.GetFeePerK(); // User didn't set: use -txconfirmtarget to estimate... if (nFeeNeeded == 0) nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes); // ... unless we don't have enough mempool data, in which case fall // back to a hard-coded fee if (nFeeNeeded == 0) nFeeNeeded = minTxFee.GetFee(nTxBytes); // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes)) nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes); // But always obey the maximum if (nFeeNeeded > maxTxFee) nFeeNeeded = maxTxFee; return nFeeNeeded; } CAmount CWallet::GetTotalValue(std::vector<CTxIn> vCoins) { CAmount nTotalValue = 0; CWalletTx wtx; BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { nTotalValue += wtx.vout[i.prevout.n].nValue; } } else { LogPrintf("GetTotalValue -- Couldn't find transaction\n"); } } return nTotalValue; } string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) { if (IsLocked()) return _("Error: Wallet locked, unable to create transaction!"); if (obfuScationPool.GetState() != POOL_STATUS_ERROR && obfuScationPool.GetState() != POOL_STATUS_SUCCESS) if (obfuScationPool.GetEntriesCount() > 0) return _("Error: You already have pending entries in the Obfuscation pool"); // ** find the coins we'll use std::vector<CTxIn> vCoins; std::vector<CTxIn> vCoinsResult; std::vector<COutput> vCoins2; CAmount nValueIn = 0; CReserveKey reservekey(this); /* Select the coins we'll use if minRounds >= 0 it means only denominated inputs are going in and coming out */ if (minRounds >= 0) { if (!SelectCoinsByDenominations(obfuScationPool.sessionDenom, 0.1 * COIN, OBFUSCATION_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) return _("Error: Can't select current denominated inputs"); } LogPrintf("PrepareObfuscationDenominate - preparing obfuscation denominate . Got: %d \n", nValueIn); { LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) LockCoin(v.prevout); } CAmount nValueLeft = nValueIn; std::vector<CTxOut> vOut; /* TODO: Front load with needed denominations (e.g. .1, 1 ) */ // Make outputs by looping through denominations: try to add every needed denomination, repeat up to 5-10 times. // This way we can be pretty sure that it should have at least one of each needed denomination. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while (nStep < nStepsMax) { BOOST_FOREACH (CAmount v, obfuScationDenominations) { // only use the ones that are approved bool fAccepted = false; if ((obfuScationPool.sessionDenom & (1 << 0)) && v == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 1)) && v == ((1000 * COIN) + 1000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 2)) && v == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 3)) && v == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 4)) && v == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 5)) && v == ((.1 * COIN) + 100)) { fAccepted = true; } if (!fAccepted) continue; // try to add it if (nValueLeft - v >= 0) { // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vCoins.begin(); std::vector<COutput>::iterator it2 = vCoins2.begin(); while (it2 != vCoins2.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == v) { // add new input in resulting vector vCoinsResult.push_back(*it); // remove corresponting items from initial vectors vCoins.erase(it); vCoins2.erase(it2); CScript scriptChange; CPubKey vchPubKey; // use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); // add new output CTxOut o(v, scriptChange); vOut.push_back(o); // subtract denomination amount nValueLeft -= v; break; } ++it; ++it2; } } } nStep++; if (nValueLeft == 0) break; } { // unlock unused coins LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) UnlockCoin(v.prevout); } if (obfuScationPool.GetDenominations(vOut) != obfuScationPool.sessionDenom) { // unlock used coins on failure LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoinsResult) UnlockCoin(v.prevout); return "Error: can't make current denominated outputs"; } // randomize the output order std::random_shuffle(vOut.begin(), vOut.end()); // We also do not care about full amount as long as we have right denominations, just pass what we found obfuScationPool.SendObfuscationDenominate(vCoinsResult, vOut, nValueIn - nValueLeft); return ""; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); uiInterface.LoadWallet(this); return DB_LOAD_OK; } DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) { if (!fFileBacked) return DB_LOAD_OK; DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx); if (nZapWalletTxRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // that requires a new key. } } if (nZapWalletTxRet != DB_LOAD_OK) return nZapWalletTxRet; return DB_LOAD_OK; } #include "qml/qt_native/bip39.h" bool CWallet::deriveWithChain(const char *key64, const std::string &lastUsedAddress,const std::string &seeds, int chainType ) { uint8_t I[64] = {0}; uint8_t secret[32] = {0}; uint8_t chainCode[32] = {0}; uint8_t s[32] = {0}; uint8_t c[32] = {0}; BIP39HMAC(I, BIP39SHA512, 64, BIP32_SEED_KEY, strlen(BIP32_SEED_KEY), key64, 64); memcpy(secret, I, 32); memcpy(chainCode, I + 32 , 32); CKDpriv(secret, chainCode, 0 | BIP32_HARD); // path m/0H CKDpriv(secret, chainCode, chainType); // path m/0H/chain size_t i = 0; bool found = false; for (; i < 100000; i++) { //Can not let them try too much! memcpy(s, secret,32); memcpy(c, chainCode,32); CKDpriv(s, c, i); // index'th key in chain CKey key; key.Set((const unsigned char *)s,(const unsigned char *)(s+32),true); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress; vchAddress = pubkey.GetID(); CBitcoinAddress address; address.Set(vchAddress); if(lastUsedAddress == address.ToString()) { found = true; i++; break; } } if(!found) return false; memcpy(s, secret,32); memcpy(c, chainCode,32); CKDpriv(s, c, i); // index'th key in chain CKey key; key.Set((const unsigned char *)s,(const unsigned char *)(s+32),true); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress; vchAddress = pubkey.GetID(); CBitcoinAddress address; address.Set(vchAddress); CTxDestination dest = address.Get(); //------------- { MarkDirty(); SetAddressBook(dest, "BIP39", "receive",seeds,chainType); // Don't throw error in case a key is already there if (HaveKey(vchAddress)) { return false; } mapKeyMetadata[vchAddress].nCreateTime = 1; if (!AddKeyPubKey(key, pubkey)) return false; // whenever a key is imported, we need to scan the whole chain nTimeFirstKey = 1; // 0 would be considered 'no value' } return true; } void CWallet::deriveBIP39(const CKeyID &keyID) { CBitcoinAddress address; CTxDestination dest; char key64[64] = {0}; address.Set(keyID); dest = address.Get(); if(mapAddressBook[dest].seeds.empty()) return; hex2byte(key64,mapAddressBook[dest].seeds.c_str()); deriveWithChain(key64,address.ToString(),mapAddressBook[dest].seeds,mapAddressBook[dest].chainType); } bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose, const string &seeds, int chainType) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address].name = strName; if (!strPurpose.empty()) /* update purpose only if requested */ mapAddressBook[address].purpose = strPurpose; if(!seeds.empty()) { mapAddressBook[address].seeds = seeds; mapAddressBook[address].chainType = chainType; } // LogPrintf("seeds1:%s\n",mapAddressBook[address].seeds); } //LogPrintf("seeds.empty():%d\n",seeds.empty()); if(seeds.empty()) NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW)); else NotifyAddressBookChanged(this, address, strName, ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW)); if (!fFileBacked) return false; if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose)) return false; if(!CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName)) return false; if(!CWalletDB(strWalletFile).WriteSeeds(CBitcoinAddress(address).ToString(), seeds)) return false; if(!CWalletDB(strWalletFile).WriteChainType(CBitcoinAddress(address).ToString(), chainType)) return false; return true; } bool CWallet::DelAddressBook(const CTxDestination& address) { std::string seeds = mapAddressBook[address].seeds; { LOCK(cs_wallet); // mapAddressBook if (fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = CBitcoinAddress(address).ToString(); BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } mapAddressBook.erase(address); } if(seeds.empty()) NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); else NotifyAddressBookChanged(this, address, "", ISMINE_NO, "", CT_DELETED);//TODO: Is this right, or should it be ISMINE_SPENDABLE? if (!fFileBacked) return false; CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString()); if(! CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString())) return false; if(!CWalletDB(strWalletFile).EraseSeeds(CBitcoinAddress(address).ToString())) return false; if(!CWalletDB(strWalletFile).EraseChainType(CBitcoinAddress(address).ToString())) return false; return true; } bool CWallet::SetDefaultKey(const CPubKey& vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } /** * Mark old keypool keys as used, * and generate all new keys */ bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH (int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i + 1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int kpSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (kpSize > 0) nTargetSize = kpSize; else nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); double dProgress = 100.f * nEnd / (nTargetSize + 1); std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress); uiInterface.InitMessage(strMsg); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if (setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() { map<CTxDestination, CAmount> balances; { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set<set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set<set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH (CTxIn txin, pcoin->vin) { CTxDestination address; if (!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH (CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if (!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set<set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses map<CTxDestination, set<CTxDestination>*> setmap; // map addresses to the unique group containing it BOOST_FOREACH (set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set<set<CTxDestination>*> hits; map<CTxDestination, set<CTxDestination>*>::iterator it; BOOST_FOREACH (CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH (set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH (CTxDestination element, *merged) setmap[element] = merged; } set<set<CTxDestination> > ret; BOOST_FOREACH (set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const { LOCK(cs_wallet); set<CTxDestination> result; BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) result.insert(address); } return result; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH (const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } bool CWallet::UpdatedTransaction(const uint256& hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { NotifyTransactionChanged(this, hashTx, CT_UPDATED); return true; } } return false; } void CWallet::LockCoin(COutPoint& output) { // LogPrintf("DPOS CWallet::LockCoin | output=%s\n",output.ToString()); AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } /** @} */ // end of Actions class CAffectedKeysVisitor : public boost::static_visitor<void> { private: const CKeyStore& keystore; std::vector<CKeyID>& vKeys; public: CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {} void Process(const CScript& script) { txnouttype type; std::vector<CTxDestination> vDest; int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { BOOST_FOREACH (const CTxDestination& dest, vDest) boost::apply_visitor(*this, dest); } } void operator()(const CKeyID& keyId) { if (keystore.HaveKey(keyId)) vKeys.push_back(keyId); } void operator()(const CScriptID& scriptId) { CScript script; if (keystore.GetCScript(scriptId, script)) Process(script); } void operator()(const CNoDestination& none) {} }; void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH (const CKeyID& keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx& wtx = (*it).second; BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH (const CTxOut& txout, wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); BOOST_FOREACH (const CKeyID& keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off } bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { if (boost::get<CNoDestination>(&dest)) return false; mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value); } bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key) { if (!mapAddressBook[dest].destdata.erase(key)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key); } bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); return true; } bool CWallet::GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const { std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest); if (i != mapAddressBook.end()) { CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key); if (j != i->second.destdata.end()) { if (value) *value = j->second; return true; } } return false; } // CWallet::AutoZeromint() gets called with each new incoming block void CWallet::AutoZeromint() { // Don't bother Autominting if Zerocoin Protocol isn't active if (GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) return; // Wait until blockchain + masternodes are fully synced and wallet is unlocked. if (!masternodeSync.IsSynced() || IsLocked()){ // Re-adjust startup time in case syncing needs a long time. nStartupTime = GetAdjustedTime(); return; } // After sync wait even more to reduce load when wallet was just started int64_t nWaitTime = GetAdjustedTime() - nStartupTime; if (nWaitTime < AUTOMINT_DELAY){ LogPrint("zero", "CWallet::AutoZeromint(): time since sync-completion or last Automint (%ld sec) < default waiting time (%ld sec). Waiting again...\n", nWaitTime, AUTOMINT_DELAY); return; } CAmount nZerocoinBalance = GetZerocoinBalance(false); //false includes both pending and mature zerocoins. Need total balance for this so nothing is overminted. CAmount nBalance = GetUnlockedCoins(); // We only consider unlocked coins, this also excludes masternode-vins // from being accidentally minted CAmount nMintAmount = 0; CAmount nToMintAmount = 0; // zGKC are integers > 0, so we can't mint 10% of 9 GKC if (nBalance < 10){ LogPrint("zero", "CWallet::AutoZeromint(): available balance (%ld) too small for minting zGKC\n", nBalance); return; } // Percentage of zGKC we already have double dPercentage = 100 * (double)nZerocoinBalance / (double)(nZerocoinBalance + nBalance); // Check if minting is actually needed if(dPercentage >= nZeromintPercentage){ LogPrint("zero", "CWallet::AutoZeromint() @block %ld: percentage of existing zGKC (%lf%%) already >= configured percentage (%d%%). No minting needed...\n", chainActive.Tip()->nHeight, dPercentage, nZeromintPercentage); return; } // zGKC amount needed for the target percentage nToMintAmount = ((nZerocoinBalance + nBalance) * nZeromintPercentage / 100); // zGKC amount missing from target (must be minted) nToMintAmount = (nToMintAmount - nZerocoinBalance) / COIN; // Use the biggest denomination smaller than the needed zGKC We'll only mint exact denomination to make minting faster. // Exception: for big amounts use 6666 (6666 = 1*5000 + 1*1000 + 1*500 + 1*100 + 1*50 + 1*10 + 1*5 + 1) to create all // possible denominations to avoid having 5000 denominations only. // If a preferred denomination is used (means nPreferredDenom != 0) do nothing until we have enough GKC to mint this denomination if (nPreferredDenom > 0){ if (nToMintAmount >= nPreferredDenom) nToMintAmount = nPreferredDenom; // Enough coins => mint preferred denomination else nToMintAmount = 0; // Not enough coins => do nothing and wait for more coins } if (nToMintAmount >= ZQ_6666){ nMintAmount = ZQ_6666; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND){ nMintAmount = libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED){ nMintAmount = libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIFTY){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIFTY; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_TEN){ nMintAmount = libzerocoin::CoinDenomination::ZQ_TEN; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIVE){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIVE; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_ONE){ nMintAmount = libzerocoin::CoinDenomination::ZQ_ONE; } else { nMintAmount = 0; } if (nMintAmount > 0){ CWalletTx wtx; vector<CZerocoinMint> vMints; string strError = pwalletMain->MintZerocoin(nMintAmount*COIN, wtx, vMints); // Return if something went wrong during minting if (strError != ""){ LogPrintf("CWallet::AutoZeromint(): auto minting failed with error: %s\n", strError); return; } nZerocoinBalance = GetZerocoinBalance(false); nBalance = GetUnlockedCoins(); dPercentage = 100 * (double)nZerocoinBalance / (double)(nZerocoinBalance + nBalance); LogPrintf("CWallet::AutoZeromint() @ block %ld: successfully minted %ld zGKC. Current percentage of zGKC: %lf%%\n", chainActive.Tip()->nHeight, nMintAmount, dPercentage); // Re-adjust startup time to delay next Automint for 5 minutes nStartupTime = GetAdjustedTime(); } else { LogPrintf("CWallet::AutoZeromint(): Nothing minted because either not enough funds available or the requested denomination size (%d) is not yet reached.\n", nPreferredDenom); } } void CWallet::AutoCombineDust() { LOCK2(cs_main, cs_wallet); if (IsInitialBlockDownload() || IsLocked()) { return; } map<CBitcoinAddress, vector<COutput> > mapCoinsByAddress = AvailableCoinsByAddress(true, 0); //coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address for (map<CBitcoinAddress, vector<COutput> >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) { vector<COutput> vCoins, vRewardCoins; vCoins = it->second; //find masternode rewards that need to be combined CCoinControl* coinControl = new CCoinControl(); CAmount nTotalRewardsValue = 0; BOOST_FOREACH (const COutput& out, vCoins) { //no coins should get this far if they dont have proper maturity, this is double checking if (out.tx->IsCoinStake() && out.tx->GetDepthInMainChain() < COINBASE_MATURITY + 1) continue; if (out.Value() > nAutoCombineThreshold * COIN) continue; COutPoint outpt(out.tx->GetHash(), out.i); coinControl->Select(outpt); vRewardCoins.push_back(out); nTotalRewardsValue += out.Value(); } //if no inputs found then return if (!coinControl->HasSelected()) continue; //we cannot combine one coin with itself if (vRewardCoins.size() <= 1) continue; vector<pair<CScript, CAmount> > vecSend; CScript scriptPubKey = GetScriptForDestination(it->first.Get()); vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue)); // Create the transaction and commit it to the network CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch string strErr; CAmount nFeeRet = 0; //get the fee amount CWalletTx wtxdummy; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0)); vecSend[0].second = nTotalRewardsValue - nFeeRet - 500; if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0))) { LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr); continue; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("AutoCombineDust transaction commit failed\n"); continue; } LogPrintf("AutoCombineDust sent transaction\n"); delete coinControl; } } bool CWallet::MultiSend() { LOCK2(cs_main, cs_wallet); if (IsInitialBlockDownload() || IsLocked()) { return false; } if (chainActive.Tip()->nHeight <= nLastMultiSendHeight) { LogPrintf("Multisend: lastmultisendheight is higher than current best height\n"); return false; } std::vector<COutput> vCoins; AvailableCoins(vCoins); int stakeSent = 0; int mnSent = 0; BOOST_FOREACH (const COutput& out, vCoins) { //need output with precise confirm count - this is how we identify which is the output to send if (out.tx->GetDepthInMainChain() != COINBASE_MATURITY + 1) continue; COutPoint outpoint(out.tx->GetHash(), out.i); bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx); bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both if (!(sendMSOnStake || sendMSonMNReward)) continue; CTxDestination destMyAddress; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) { LogPrintf("Multisend: failed to extract destination\n"); continue; } //Disabled Addresses won't send MultiSend transactions if (vDisabledAddresses.size() > 0) { for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) { if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) { LogPrintf("Multisend: disabled address preventing multisend\n"); return false; } } } // create new coin control, populate it with the selected utxo, create sending vector CCoinControl* cControl = new CCoinControl(); COutPoint outpt(out.tx->GetHash(), out.i); cControl->Select(outpt); cControl->destChange = destMyAddress; CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch CAmount nFeeRet = 0; vector<pair<CScript, CAmount> > vecSend; // loop through multisend vector and add amounts and addresses to the sending vector const isminefilter filter = ISMINE_SPENDABLE; CAmount nAmount = 0; for (unsigned int i = 0; i < vMultiSend.size(); i++) { // MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100; CBitcoinAddress strAddSend(vMultiSend[i].first); CScript scriptPubKey; scriptPubKey = GetScriptForDestination(strAddSend.Get()); vecSend.push_back(make_pair(scriptPubKey, nAmount)); } //get the fee amount CWalletTx wtxdummy; string strErr; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0)); CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second; if (nLastSendAmount < nFeeRet + 500) { LogPrintf("%s: fee of %d is too large to insert into last output\n", __func__, nFeeRet + 500); return false; } vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500; // Create the transaction and commit it to the network if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0))) { LogPrintf("MultiSend createtransaction failed\n"); return false; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("MultiSend transaction commit failed\n"); return false; } else fMultiSendNotify = true; delete cControl; //write nLastMultiSendHeight to DB CWalletDB walletdb(strWalletFile); nLastMultiSendHeight = chainActive.Tip()->nHeight; if (!walletdb.WriteMSettings(fMultiSendStake, fMultiSendMasternodeReward, nLastMultiSendHeight)) LogPrintf("Failed to write MultiSend setting to DB\n"); LogPrintf("MultiSend successfully sent\n"); if (sendMSOnStake) stakeSent++; else mnSent++; //stop iterating if we are done if (mnSent > 0 && stakeSent > 0) return true; if (stakeSent > 0 && !fMultiSendMasternodeReward) return true; if (mnSent > 0 && !fMultiSendStake) return true; } return true; } CKeyPool::CKeyPool() { nTime = GetTime(); } CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn) { nTime = GetTime(); vchPubKey = vchPubKeyIn; } CWalletKey::CWalletKey(int64_t nExpires) { nTimeCreated = (nExpires ? GetTime() : 0); nTimeExpires = nExpires; } int CMerkleTx::SetMerkleBranch(const CBlock& block) { AssertLockHeld(cs_main); CBlock blockTmp; // Update the tx's hashBlock hashBlock = block.GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++) if (block.vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)block.vtx.size()) { vMerkleBranch.clear(); nIndex = -1; LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = block.GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; const CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); //LogPrintf("CMerkleTx::GetDepthInMainChain|hash=%s,nResult=%d,mempool.exists()=%d,enableIX=%d\n",GetHash().ToString(),nResult,mempool.exists(GetHash()),enableIX); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool if (enableIX) { if (nResult < 6) { int signatures = GetTransactionLockSignatures(); if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) { return nSwiftTXDepth + nResult; } } } return nResult; } int CMerkleTx::GetDepthInMainChain(bool enableIX) const { const CBlockIndex* pindexRet; return GetDepthInMainChain(pindexRet, enableIX); } int CMerkleTx::GetBlocksToMaturity() const { LOCK(cs_main); if (!(IsCoinBase() || IsCoinStake())) return 0; return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees) { CValidationState state; bool fAccepted = ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees); if (!fAccepted) LogPrintf("%s : %s\n", __func__, state.GetRejectReason()); return fAccepted; } int CMerkleTx::GetTransactionLockSignatures() const { if (fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2; if (!IsSporkActive(SPORK_2_SWIFTTX)) return -3; if (!fEnableSwiftTX) return -1; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return (*i).second.CountSignatures(); } return -1; } bool CMerkleTx::IsTransactionLockTimedOut() const { if (!fEnableSwiftTX) return 0; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return GetTime() > (*i).second.nTimeout; } return false; } #ifdef DPOS bool CWalletTx::IsInDepriveLockingTime(BlockHeight chainHeight) const { int lockHeight = Entrustment::GetInstance().GetLockHeightForDeprive(); if(lockHeight <= 0) return false; //不设取消委托锁定高度 int thisHeight = blockHeight; return chainHeight - thisHeight < lockHeight; } int CWalletTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const { if(pwallet->mode == CWallet::Mode::APP) { //LogPrintf("CWalletTx::GetDepthInMainChainINTERNAL|this=%p,hash=%s,pwallet->GetChainHeight()=%d,blockHeight=%d\n",this,GetHash().ToString(),pwallet->GetChainHeight(),blockHeight); if(blockHeight < 0) { return 0; } return pwallet->GetChainHeight() - blockHeight + 1; } return CMerkleTx::GetDepthInMainChainINTERNAL(pindexRet); } CAmount CWalletTx::GetTotalInputValue() const { CAmount total = 0; CTxOut input; if(pwallet) { for (const CTxIn txin : vin) { if(pwallet->SearchTxOut(txin.prevout,input)) total += input.nValue; } } return total; } CAmount CWalletTx::GetTotalOutputValue() const { return GetValueOut(); } CAmount CWalletTx::GetFee() const { return (GetTotalInputValue() - GetTotalOutputValue()); } #endif // Given a set of inputs, find the public key that contributes the most coins to the input set CScript GetLargestContributor(set<pair<const CWalletTx*, unsigned int> >& setCoins) { map<CScript, CAmount> mapScriptsOut; for (const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) { CTxOut out = coin.first->vout[coin.second]; mapScriptsOut[out.scriptPubKey] += out.nValue; } CScript scriptLargest; CAmount nLargestContributor = 0; for (auto it : mapScriptsOut) { if (it.second > nLargestContributor) { scriptLargest = it.first; nLargestContributor = it.second; } } return scriptLargest; } bool CWallet::CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, vector<CZerocoinMint>& vMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, const bool isZCSpendChange) { if (IsLocked()) { strFailReason = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("SpendZerocoin() : %s", strFailReason.c_str()); return false; } //add multiple mints that will fit the amount requested as closely as possible CAmount nMintingValue = 0; CAmount nValueRemaining = 0; while (true) { //mint a coin with the closest denomination to what is being requested nFeeRet = max(static_cast<int>(txNew.vout.size()), 1) * Params().Zerocoin_MintFee(); nValueRemaining = nValue - nMintingValue - (isZCSpendChange ? nFeeRet : 0); // if this is change of a zerocoinspend, then we can't mint all change, at least something must be given as a fee if (isZCSpendChange && nValueRemaining <= 1 * COIN) break; libzerocoin::CoinDenomination denomination = libzerocoin::AmountToClosestDenomination(nValueRemaining, nValueRemaining); if (denomination == libzerocoin::ZQ_ERROR) break; CAmount nValueNewMint = libzerocoin::ZerocoinDenominationToAmount(denomination); nMintingValue += nValueNewMint; // mint a new coin (create Pedersen Commitment) and extract PublicCoin that is shareable from it libzerocoin::PrivateCoin newCoin(Params().Zerocoin_Params(), denomination); libzerocoin::PublicCoin pubCoin = newCoin.getPublicCoin(); // Validate if(!pubCoin.validate()) { strFailReason = _("failed to validate zerocoin"); return false; } CScript scriptSerializedCoin = CScript() << OP_ZEROCOINMINT << pubCoin.getValue().getvch().size() << pubCoin.getValue().getvch(); CTxOut outMint(nValueNewMint, scriptSerializedCoin); txNew.vout.push_back(outMint); //store as CZerocoinMint for later use CZerocoinMint mint(denomination, pubCoin.getValue(), newCoin.getRandomness(), newCoin.getSerialNumber(), false); vMints.push_back(mint); } // calculate fee CAmount nFee = Params().Zerocoin_MintFee() * txNew.vout.size(); // no ability to select more coins if this is a ZCSpend change mint CAmount nTotalValue = (isZCSpendChange ? nValue : (nValue + nFee)); // check for a zerocoinspend that mints the change CAmount nValueIn = 0; set<pair<const CWalletTx*, unsigned int> > setCoins; if (isZCSpendChange) { nValueIn = nValue; } else { // select UTXO's to use if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl)) { strFailReason = _("Insufficient or insufficient confirmed funds, you might need to wait a few minutes and try again."); return false; } // Fill vin for (const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); } //any change that is less than 0.0100000 will be ignored and given as an extra fee //also assume that a zerocoinspend that is minting the change will not have any change that goes to Tsr CAmount nChange = nValueIn - nTotalValue; // Fee already accounted for in nTotalValue if (nChange > 1 * CENT && !isZCSpendChange) { // Fill a vout to ourself using the largest contributing address CScript scriptChange = GetLargestContributor(setCoins); //add to the transaction CTxOut outChange(nChange, scriptChange); txNew.vout.push_back(outChange); } else { if (reservekey) reservekey->ReturnKey(); } // Sign if these are gkc outputs - NOTE that zTsr outputs are signed later in SoK if (!isZCSpendChange) { int nIn = 0; for (const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) { if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } } } return true; } bool CWallet::MintToTxIn(CZerocoinMint zerocoinSelected, int nSecurityLevel, const uint256& hashTxOut, CTxIn& newTxIn, CZerocoinSpendReceipt& receipt) { // Default error status if not changed below receipt.SetStatus(_("Transaction Mint Started"), ZGKC_TXMINT_GENERAL); libzerocoin::CoinDenomination denomination = zerocoinSelected.GetDenomination(); // 2. Get pubcoin from the private coin libzerocoin::PublicCoin pubCoinSelected(Params().Zerocoin_Params(), zerocoinSelected.GetValue(), denomination); LogPrintf("%s : pubCoinSelected:\n denom=%d\n value%s\n", __func__, denomination, pubCoinSelected.getValue().GetHex()); if (!pubCoinSelected.validate()) { receipt.SetStatus(_("The selected mint coin is an invalid coin"), ZGKC_INVALID_COIN); return false; } // 3. Compute Accumulator and Witness libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(), pubCoinSelected.getDenomination()); libzerocoin::AccumulatorWitness witness(Params().Zerocoin_Params(), accumulator, pubCoinSelected); string strFailReason = ""; int nMintsAdded = 0; if (!GenerateAccumulatorWitness(pubCoinSelected, accumulator, witness, nSecurityLevel, nMintsAdded, strFailReason)) { receipt.SetStatus(_("Try to spend with a higher security level to include more coins"), ZGKC_FAILED_ACCUMULATOR_INITIALIZATION); LogPrintf("%s : %s \n", __func__, receipt.GetStatusMessage()); return false; } // Construct the CoinSpend object. This acts like a signature on the transaction. libzerocoin::PrivateCoin privateCoin(Params().Zerocoin_Params(), denomination); privateCoin.setPublicCoin(pubCoinSelected); privateCoin.setRandomness(zerocoinSelected.GetRandomness()); privateCoin.setSerialNumber(zerocoinSelected.GetSerialNumber()); uint32_t nChecksum = GetChecksum(accumulator.getValue()); try { libzerocoin::CoinSpend spend(Params().Zerocoin_Params(), privateCoin, accumulator, nChecksum, witness, hashTxOut); if (!spend.Verify(accumulator)) { receipt.SetStatus(_("The new spend coin transaction did not verify"), ZGKC_INVALID_WITNESS); return false; } // Deserialize the CoinSpend intro a fresh object CDataStream serializedCoinSpend(SER_NETWORK, PROTOCOL_VERSION); serializedCoinSpend << spend; std::vector<unsigned char> data(serializedCoinSpend.begin(), serializedCoinSpend.end()); //Add the coin spend into a GKC transaction newTxIn.scriptSig = CScript() << OP_ZEROCOINSPEND << data.size(); newTxIn.scriptSig.insert(newTxIn.scriptSig.end(), data.begin(), data.end()); newTxIn.prevout.SetNull(); //use nSequence as a shorthand lookup of denomination //NOTE that this should never be used in place of checking the value in the final blockchain acceptance/verification //of the transaction newTxIn.nSequence = denomination; CDataStream serializedCoinSpendChecking(SER_NETWORK, PROTOCOL_VERSION); try { serializedCoinSpendChecking << spend; } catch (...) { receipt.SetStatus(_("Failed to deserialize"), ZGKC_BAD_SERIALIZATION); return false; } libzerocoin::CoinSpend newSpendChecking(Params().Zerocoin_Params(), serializedCoinSpendChecking); if (!newSpendChecking.Verify(accumulator)) { receipt.SetStatus(_("The transaction did not verify"), ZGKC_BAD_SERIALIZATION); return false; } std::list<CBigNum> listCoinSpendSerial = CWalletDB(strWalletFile).ListSpentCoinsSerial(); for (const CBigNum& item : listCoinSpendSerial) { if (spend.getCoinSerialNumber() == item) { //Tried to spend an already spent zTsr zerocoinSelected.SetUsed(true); if (!CWalletDB(strWalletFile).WriteZerocoinMint(zerocoinSelected)) LogPrintf("%s failed to write zerocoinmint\n", __func__); pwalletMain->NotifyZerocoinChanged(pwalletMain, zerocoinSelected.GetValue().GetHex(), "Used", CT_UPDATED); receipt.SetStatus(_("The coin spend has been used"), ZGKC_SPENT_USED_ZGKC); return false; } } uint32_t nAccumulatorChecksum = GetChecksum(accumulator.getValue()); CZerocoinSpend zcSpend(spend.getCoinSerialNumber(), 0, zerocoinSelected.GetValue(), zerocoinSelected.GetDenomination(), nAccumulatorChecksum); zcSpend.SetMintCount(nMintsAdded); receipt.AddSpend(zcSpend); } catch (const std::exception&) { receipt.SetStatus(_("CoinSpend: Accumulator witness does not verify"), ZGKC_INVALID_WITNESS); return false; } receipt.SetStatus(_("Spend Valid"), ZGKC_SPEND_OKAY); // Everything okay return true; } bool CWallet::CreateZerocoinSpendTransaction(CAmount nValue, int nSecurityLevel, CWalletTx& wtxNew, CReserveKey& reserveKey, CZerocoinSpendReceipt& receipt, vector<CZerocoinMint>& vSelectedMints, vector<CZerocoinMint>& vNewMints, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* address) { // Check available funds int nStatus = ZGKC_TRX_FUNDS_PROBLEMS; if (nValue > GetZerocoinBalance(true)) { receipt.SetStatus(_("You don't have enough Zerocoins in your wallet"), nStatus); return false; } if (nValue < 1) { receipt.SetStatus(_("Value is below the the smallest available denomination (= 1) of zTsr"), nStatus); return false; } // Create transaction nStatus = ZGKC_TRX_CREATE; // If not already given pre-selected mints, then select mints from the wallet CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints; CAmount nValueSelected = 0; int nCoinsReturned = 0; // Number of coins returned in change from function below (for debug) int nNeededSpends = 0; // Number of spends which would be needed if selection failed const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zGKC transaction if (vSelectedMints.empty()) { listMints = walletdb.ListMintedCoins(true, true, true); // need to find mints to spend if(listMints.empty()) { receipt.SetStatus(_("Failed to find Zerocoins in in wallet.dat"), nStatus); return false; } // If the input value is not an int, then we want the selection algorithm to round up to the next highest int double dValue = static_cast<double>(nValue) / static_cast<double>(COIN); bool fWholeNumber = floor(dValue) == dValue; CAmount nValueToSelect = nValue; if(!fWholeNumber) nValueToSelect = static_cast<CAmount>(ceil(dValue) * COIN); // Select the zTsr mints to use in this spend std::map<libzerocoin::CoinDenomination, CAmount> DenomMap = GetMyZerocoinDistribution(); vSelectedMints = SelectMintsFromList(nValueToSelect, nValueSelected, nMaxSpends, fMinimizeChange, nCoinsReturned, listMints, DenomMap, nNeededSpends); } else { for (const CZerocoinMint mint : vSelectedMints) nValueSelected += ZerocoinDenominationToAmount(mint.GetDenomination()); } listSpends(vSelectedMints); int nArchived = 0; for (CZerocoinMint mint : vSelectedMints) { // see if this serial has already been spent if (IsSerialKnown(mint.GetSerialNumber())) { receipt.SetStatus(_("Trying to spend an already spent serial #, try again."), nStatus); mint.SetUsed(true); walletdb.WriteZerocoinMint(mint); return false; } //check that this mint made it into the blockchain CTransaction txMint; uint256 hashBlock; bool fArchive = false; if (!GetTransaction(mint.GetTxHash(), txMint, hashBlock)) { receipt.SetStatus(_("Unable to find transaction containing mint"), nStatus); fArchive = true; } else if (mapBlockIndex.count(hashBlock) < 1) { receipt.SetStatus(_("Mint did not make it into blockchain"), nStatus); fArchive = true; } // archive this mint as an orphan if (fArchive) { walletdb.ArchiveMintOrphan(mint); nArchived++; } } if (nArchived) return false; if (vSelectedMints.empty()) { if(nNeededSpends > 0){ // Too much spends needed, so abuse nStatus to report back the number of needed spends receipt.SetStatus(_("Too many spends needed"), nStatus, nNeededSpends); } else { receipt.SetStatus(_("Failed to select a zerocoin"), nStatus); } return false; } if ((static_cast<int>(vSelectedMints.size()) > Params().Zerocoin_MaxSpendsPerTransaction())) { receipt.SetStatus(_("Failed to find coin set amongst held coins with less than maxNumber of Spends"), nStatus); return false; } // Create change if needed nStatus = ZGKC_TRX_CHANGE; CMutableTransaction txNew; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); { txNew.vin.clear(); txNew.vout.clear(); //if there is an address to send to then use it, if not generate a new address to send to CScript scriptZerocoinSpend; CScript scriptChange; CAmount nChange = nValueSelected - nValue; if (nChange && !address) { receipt.SetStatus(_("Need address because change is not exact"), nStatus); return false; } if (address) { scriptZerocoinSpend = GetScriptForDestination(address->Get()); if (nChange) { // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reserveKey.GetReservedKey(vchPubKey)); // should never fail scriptChange = GetScriptForDestination(vchPubKey.GetID()); } } else { // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reserveKey.GetReservedKey(vchPubKey)); // should never fail scriptZerocoinSpend = GetScriptForDestination(vchPubKey.GetID()); } //add change output if we are spending too much (only applies to spending multiple at once) if (nChange) { //mint change as zerocoins if (fMintChange) { CAmount nFeeRet = 0; string strFailReason = ""; if (!CreateZerocoinMintTransaction(nChange, txNew, vNewMints, &reserveKey, nFeeRet, strFailReason, NULL, true)) { receipt.SetStatus(_("Failed to create mint"), nStatus); return false; } } else { CTxOut txOutChange(nValueSelected - nValue, scriptChange); txNew.vout.push_back(txOutChange); } } //add output to gkc address to the transaction (the actual primary spend taking place) CTxOut txOutZerocoinSpend(nValue, scriptZerocoinSpend); txNew.vout.push_back(txOutZerocoinSpend); //hash with only the output info in it to be used in Signature of Knowledge uint256 hashTxOut = txNew.GetHash(); //add all of the mints to the transaction as inputs for (CZerocoinMint mint : vSelectedMints) { CTxIn newTxIn; if (!MintToTxIn(mint, nSecurityLevel, hashTxOut, newTxIn, receipt)) { return false; } txNew.vin.push_back(newTxIn); } // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_ZEROCOIN_TX_SIZE) { receipt.SetStatus(_("In rare cases, a spend with 7 coins exceeds our maximum allowable transaction size, please retry spend using 6 or less coins"), ZGKC_TX_TOO_LARGE); return false; } //now that all inputs have been added, add full tx hash to zerocoinspend records and write to db uint256 txHash = txNew.GetHash(); for (CZerocoinSpend spend : receipt.GetSpends()) { spend.SetTxHash(txHash); if (!CWalletDB(strWalletFile).WriteZerocoinSpendSerialEntry(spend)) { receipt.SetStatus(_("Failed to write coin serial number into wallet"), nStatus); } } //turn the finalized transaction into a wallet transaction wtxNew = CWalletTx(this, txNew); wtxNew.fFromMe = true; wtxNew.fTimeReceivedIsTxTime = true; wtxNew.nTimeReceived = GetAdjustedTime(); } } receipt.SetStatus(_("Transaction Created"), ZGKC_SPEND_OKAY); // Everything okay return true; } string CWallet::ResetMintZerocoin(bool fExtendedSearch) { long updates = 0; long deletions = 0; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(false, false, true); vector<CZerocoinMint> vMintsToFind{ std::make_move_iterator(std::begin(listMints)), std::make_move_iterator(std::end(listMints)) }; vector<CZerocoinMint> vMintsMissing; vector<CZerocoinMint> vMintsToUpdate; // search all of our available data for these mints FindMints(vMintsToFind, vMintsToUpdate, vMintsMissing, fExtendedSearch); // Update the meta data of mints that were marked for updating for (CZerocoinMint mint : vMintsToUpdate) { updates++; walletdb.WriteZerocoinMint(mint); } // Delete any mints that were unable to be located on the blockchain for (CZerocoinMint mint : vMintsMissing) { deletions++; walletdb.ArchiveMintOrphan(mint); } string strResult = _("ResetMintZerocoin finished: ") + to_string(updates) + _(" mints updated, ") + to_string(deletions) + _(" mints deleted\n"); return strResult; } string CWallet::ResetSpentZerocoin() { long removed = 0; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(false, false, false); list<CZerocoinSpend> listSpends = walletdb.ListSpentCoins(); list<CZerocoinSpend> listUnconfirmedSpends; for (CZerocoinSpend spend : listSpends) { CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(spend.GetTxHash(), tx, hashBlock)) { listUnconfirmedSpends.push_back(spend); continue; } //no confirmations if (hashBlock == 0) listUnconfirmedSpends.push_back(spend); } for (CZerocoinSpend spend : listUnconfirmedSpends) { for (CZerocoinMint mint : listMints) { if (mint.GetSerialNumber() == spend.GetSerial()) { removed++; mint.SetUsed(false); RemoveSerialFromDB(spend.GetSerial()); walletdb.WriteZerocoinMint(mint); walletdb.EraseZerocoinSpendSerialEntry(spend.GetSerial()); continue; } } } string strResult = _("ResetSpentZerocoin finished: ") + to_string(removed) + _(" unconfirmed transactions removed\n"); return strResult; } void CWallet::ReconsiderZerocoins(std::list<CZerocoinMint>& listMintsRestored) { CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListArchivedZerocoins(); if (listMints.empty()) return; for (CZerocoinMint mint : listMints) { if (IsSerialKnown(mint.GetSerialNumber())) continue; uint256 txHash; if (!GetZerocoinMint(mint.GetValue(), txHash)) continue; uint256 hashBlock = 0; CTransaction tx; if (!GetTransaction(txHash, tx, hashBlock)) continue; mint.SetTxHash(txHash); mint.SetHeight(mapBlockIndex.at(hashBlock)->nHeight); if (!walletdb.UnarchiveZerocoin(mint)) { LogPrintf("%s : failed to unarchive mint %s\n", __func__, mint.GetValue().GetHex()); } listMintsRestored.emplace_back(mint); } } void CWallet::ZTsrBackupWallet() { filesystem::path backupDir = GetDataDir() / "backups"; filesystem::path backupPath; string strNewBackupName; for (int i = 0; i < 10; i++) { strNewBackupName = strprintf("wallet-autoztsrbackup-%d.dat", i); backupPath = backupDir / strNewBackupName; if (filesystem::exists(backupPath)) { //Keep up to 10 backups if (i <= 8) { //If the next file backup exists and is newer, then iterate filesystem::path nextBackupPath = backupDir / strprintf("wallet-autoztsrbackup-%d.dat", i + 1); if (filesystem::exists(nextBackupPath)) { time_t timeThis = filesystem::last_write_time(backupPath); time_t timeNext = filesystem::last_write_time(nextBackupPath); if (timeThis > timeNext) { //The next backup is created before this backup was //The next backup is the correct path to use backupPath = nextBackupPath; break; } } //Iterate to the next filename/number continue; } //reset to 0 because name with 9 already used strNewBackupName = strprintf("wallet-autoztsrbackup-%d.dat", 0); backupPath = backupDir / strNewBackupName; break; } //This filename is fresh, break here and backup break; } BackupWallet(*this, backupPath.string()); } string CWallet::MintZerocoin(CAmount nValue, CWalletTx& wtxNew, vector<CZerocoinMint>& vMints, const CCoinControl* coinControl) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + Params().Zerocoin_MintFee() > GetBalance()) return _("Insufficient funds"); CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("MintZerocoin() : %s", strError.c_str()); return strError; } string strError; CMutableTransaction txNew; if (!CreateZerocoinMintTransaction(nValue, txNew, vMints, &reservekey, nFeeRequired, strError, coinControl)) { if (nValue + nFeeRequired > GetBalance()) return strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired).c_str()); return strError; } wtxNew = CWalletTx(this, txNew); wtxNew.fFromMe = true; wtxNew.fTimeReceivedIsTxTime = true; // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_ZEROCOIN_TX_SIZE) { return _("Error: The transaction is larger than the maximum allowed transaction size!"); } //commit the transaction to the network if (!CommitTransaction(wtxNew, reservekey)) { return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); } else { //update mints with full transaction hash and then database them CWalletDB walletdb(pwalletMain->strWalletFile); for (CZerocoinMint mint : vMints) { mint.SetTxHash(wtxNew.GetHash()); walletdb.WriteZerocoinMint(mint); pwalletMain->NotifyZerocoinChanged(pwalletMain, mint.GetValue().GetHex(), "Used", CT_UPDATED); } } //Create a backup of the wallet if (fBackupMints) ZTsrBackupWallet(); return ""; } bool CWallet::SpendZerocoin(CAmount nAmount, int nSecurityLevel, CWalletTx& wtxNew, CZerocoinSpendReceipt& receipt, vector<CZerocoinMint>& vMintsSelected, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* addressTo) { // Default: assume something goes wrong. Depending on the problem this gets more specific below int nStatus = ZGKC_SPEND_ERROR; if (IsLocked()) { receipt.SetStatus("Error: Wallet locked, unable to create transaction!", ZGKC_WALLET_LOCKED); return false; } CReserveKey reserveKey(this); vector<CZerocoinMint> vNewMints; if (!CreateZerocoinSpendTransaction(nAmount, nSecurityLevel, wtxNew, reserveKey, receipt, vMintsSelected, vNewMints, fMintChange, fMinimizeChange, addressTo)) { return false; } if (fMintChange && fBackupMints) ZTsrBackupWallet(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!CommitTransaction(wtxNew, reserveKey)) { LogPrintf("%s: failed to commit\n", __func__); nStatus = ZGKC_COMMIT_FAILED; //reset all mints for (CZerocoinMint mint : vMintsSelected) { mint.SetUsed(false); // having error, so set to false, to be able to use again walletdb.WriteZerocoinMint(mint); pwalletMain->NotifyZerocoinChanged(pwalletMain, mint.GetValue().GetHex(), "New", CT_UPDATED); } //erase spends for (CZerocoinSpend spend : receipt.GetSpends()) { if (!walletdb.EraseZerocoinSpendSerialEntry(spend.GetSerial())) { receipt.SetStatus("Error: It cannot delete coin serial number in wallet", ZGKC_ERASE_SPENDS_FAILED); } //Remove from public zerocoinDB RemoveSerialFromDB(spend.GetSerial()); } // erase new mints for (auto& mint : vNewMints) { if (!walletdb.EraseZerocoinMint(mint)) { receipt.SetStatus("Error: Unable to cannot delete zerocoin mint in wallet", ZGKC_ERASE_NEW_MINTS_FAILED); } } receipt.SetStatus("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.", nStatus); return false; } for (CZerocoinMint mint : vMintsSelected) { mint.SetUsed(true); if (!walletdb.WriteZerocoinMint(mint)) { receipt.SetStatus("Failed to write mint to db", nStatus); return false; } CZerocoinMint mintCheck; if (!walletdb.ReadZerocoinMint(mint.GetValue(), mintCheck)) { receipt.SetStatus("failed to read mintcheck", nStatus); return false; } if (!mintCheck.IsUsed()) { receipt.SetStatus("Error, the mint did not get marked as used", nStatus); return false; } } // write new Mints to db for (CZerocoinMint mint : vNewMints) { mint.SetTxHash(wtxNew.GetHash()); walletdb.WriteZerocoinMint(mint); } receipt.SetStatus("Spend Successful", ZGKC_SPEND_OKAY); // When we reach this point spending zGKC was successful return true; } uint256 CTokenInfo::GetHash() const { return SerializeHash(*this, SER_GETHASH, 0); } uint256 CTokenTx::GetHash() const { return SerializeHash(*this, SER_GETHASH, 0); } bool CWallet::LoadToken(const CTokenInfo &token) { uint256 hash = token.GetHash(); mapToken[hash] = token; return true; } bool CWallet::LoadTokenTx(const CTokenTx &tokenTx) { uint256 hash = tokenTx.GetHash(); mapTokenTx[hash] = tokenTx; return true; } bool CWallet::AddTokenEntry(const CTokenInfo &token, bool fFlushOnClose) { LOCK2(cs_main, cs_wallet); //CWalletDB walletdb(*dbw, "r+", fFlushOnClose); CWalletDB walletdb(pwalletMain->strWalletFile); uint256 hash = token.GetHash(); bool fInsertedNew = true; std::map<uint256, CTokenInfo>::iterator it = mapToken.find(hash); if(it!=mapToken.end()) { fInsertedNew = false; } // Write to disk CTokenInfo wtoken = token; if(!fInsertedNew) { wtoken.nCreateTime = GetAdjustedTime(); } else { wtoken.nCreateTime = it->second.nCreateTime; } if (!walletdb.WriteToken(wtoken)) return false; mapToken[hash] = wtoken; NotifyTokenChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // Refresh token tx if(fInsertedNew) { for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++) { uint256 tokenTxHash = it->second.GetHash(); NotifyTokenTransactionChanged(this, tokenTxHash, CT_UPDATED); } } LogPrintf("AddTokenEntry %s\n", wtoken.GetHash().ToString()); return true; } bool CWallet::AddTokenTxEntry(const CTokenTx &tokenTx, bool fFlushOnClose) { LOCK2(cs_main, cs_wallet); //CWalletDB walletdb(*dbw, "r+", fFlushOnClose); CWalletDB walletdb(pwalletMain->strWalletFile); uint256 hash = tokenTx.GetHash(); bool fInsertedNew = true; std::map<uint256, CTokenTx>::iterator it = mapTokenTx.find(hash); if(it!=mapTokenTx.end()) { fInsertedNew = false; } // Write to disk CTokenTx wtokenTx = tokenTx; if(!fInsertedNew) { wtokenTx.strLabel = it->second.strLabel; } const CBlockIndex *pIndex = chainActive[wtokenTx.blockNumber]; wtokenTx.nCreateTime = pIndex ? pIndex->GetBlockTime() : GetAdjustedTime(); if (!walletdb.WriteTokenTx(wtokenTx)) return false; mapTokenTx[hash] = wtokenTx; NotifyTokenTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); LogPrintf("AddTokenTxEntry %s\n", wtokenTx.GetHash().ToString()); return true; } bool CWallet::GetTokenTxDetails(const CTokenTx &wtx, uint256 &credit, uint256 &debit, std::string &tokenSymbol, uint8_t &decimals) const { LOCK2(cs_main, cs_wallet); bool ret = false; for(auto it = mapToken.begin(); it != mapToken.end(); it++) { CTokenInfo info = it->second; if(wtx.strContractAddress == info.strContractAddress) { if(wtx.strSenderAddress == info.strSenderAddress) { debit = wtx.nValue; tokenSymbol = info.strTokenSymbol; decimals = info.nDecimals; ret = true; } if(wtx.strReceiverAddress == info.strSenderAddress) { credit = wtx.nValue; tokenSymbol = info.strTokenSymbol; decimals = info.nDecimals; ret = true; } } } return ret; } bool CWallet::IsTokenTxMine(const CTokenTx &wtx) const { LOCK2(cs_main, cs_wallet); bool ret = false; for(auto it = mapToken.begin(); it != mapToken.end(); it++) { CTokenInfo info = it->second; if(wtx.strContractAddress == info.strContractAddress) { if(wtx.strSenderAddress == info.strSenderAddress || wtx.strReceiverAddress == info.strSenderAddress) { ret = true; } } } return ret; } bool CWallet::RemoveTokenEntry(const uint256 &tokenHash, bool fFlushOnClose) { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(pwalletMain->strWalletFile); // CWalletDB walletdb(*dbw, "r+", fFlushOnClose); bool fFound = false; std::map<uint256, CTokenInfo>::iterator it = mapToken.find(tokenHash); if(it!=mapToken.end()) { fFound = true; } if(fFound) { // Remove from disk if (!walletdb.EraseToken(tokenHash)) return false; mapToken.erase(it); NotifyTokenChanged(this, tokenHash, CT_DELETED); // Refresh token tx for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++) { uint256 tokenTxHash = it->second.GetHash(); NotifyTokenTransactionChanged(this, tokenTxHash, CT_UPDATED); } } LogPrintf("RemoveTokenEntry %s\n", tokenHash.ToString()); return true; } bool CWallet::CleanTokenTxEntries(bool fFlushOnClose) { LOCK2(cs_main, cs_wallet); // Open db CWalletDB walletdb(pwalletMain->strWalletFile); // CWalletDB walletdb(*dbw, "r+", fFlushOnClose); // Get all token transaction hashes std::vector<uint256> tokenTxHashes; for(auto it = mapTokenTx.begin(); it != mapTokenTx.end(); it++) { tokenTxHashes.push_back(it->first); } // Remove existing entries for(size_t i = 0; i < tokenTxHashes.size(); i++) { // Get the I entry uint256 hashTxI = tokenTxHashes[i]; auto itTxI = mapTokenTx.find(hashTxI); if(itTxI == mapTokenTx.end()) continue; CTokenTx tokenTxI = itTxI->second; for(size_t j = 0; j < tokenTxHashes.size(); j++) { // Skip the same entry if(i == j) continue; // Get the J entry uint256 hashTxJ = tokenTxHashes[j]; auto itTxJ = mapTokenTx.find(hashTxJ); if(itTxJ == mapTokenTx.end()) continue; CTokenTx tokenTxJ = itTxJ->second; // Compare I and J entries if(tokenTxI.strContractAddress != tokenTxJ.strContractAddress) continue; if(tokenTxI.strSenderAddress != tokenTxJ.strSenderAddress) continue; if(tokenTxI.strReceiverAddress != tokenTxJ.strReceiverAddress) continue; if(tokenTxI.blockHash != tokenTxJ.blockHash) continue; if(tokenTxI.blockNumber != tokenTxJ.blockNumber) continue; if(tokenTxI.transactionHash != tokenTxJ.transactionHash) continue; // Delete the lower entry from disk size_t nLower = uintTou256(tokenTxI.nValue) < uintTou256(tokenTxJ.nValue) ? i : j; auto itTx = nLower == i ? itTxI : itTxJ; uint256 hashTx = nLower == i ? hashTxI : hashTxJ; if (!walletdb.EraseTokenTx(hashTx)) return false; mapTokenTx.erase(itTx); NotifyTokenTransactionChanged(this, hashTx, CT_DELETED); break; } } return true; } #ifdef DPOS void CWallet::GetDepriveTxOut(std::vector<COutPoint>& depriveTxOut) const { assert(depriveTxOut.empty()); // assert: mapWallet中的VOUT都是属于本钱包的 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { uint256 txhash = it->first; const CWalletTx& tx = it->second; if(!tx.IsDeprive()) continue; for (size_t i = 0; i < tx.vout.size(); i++) { if(tx.vout[i].IsEntrusted()) continue; depriveTxOut.push_back(COutPoint(txhash,i)); } } } std::vector<const CWalletTx*> CWallet::GetCreateAgentTx() const { std::vector<const CWalletTx*> txVec; for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx& tx = it->second; if(!tx.IsCreateAgent()) continue; CTxOut txout; int voutIndex = 0; if(!tx.GetCreateAgentOut(txout,voutIndex)) continue; if(IsSpent(tx.GetHash(), voutIndex)) continue; txVec.push_back(&tx); } return txVec; } void CWallet::SetAppMode() { mode = Mode::APP; } void CWallet::SetCoreMode() { mode = Mode::CORE; } BlockHeight CWallet::GetChainHeight() const { return chainActive.Height(); } bool CWallet::SearchTxOut(const COutPoint& outpoint, CTxOut& txout) const { for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { if(it->first == outpoint.hash) { for(int n = 0; n < it->second.vout.size(); n++) { if(n == outpoint.n) { txout = it->second.vout[n]; return true; } } } } return false; } #endif bool CWallet::SetContractBook(const std::string &strAddress, const std::string &strName, const std::string &strAbi) { bool fUpdated = false; { LOCK(cs_wallet); // mapContractBook auto mi = mapContractBook.find(strAddress); fUpdated = mi != mapContractBook.end(); mapContractBook[strAddress].name = strName; mapContractBook[strAddress].abi = strAbi; } NotifyContractBookChanged(this, strAddress, strName, strAbi, (fUpdated ? CT_UPDATED : CT_NEW) ); CWalletDB walletdb(pwalletMain->strWalletFile); // CWalletDB walletdb(*dbw, "r+", true); bool ret = walletdb.WriteContractData(strAddress, "name", strName); ret &= walletdb.WriteContractData(strAddress, "abi", strAbi); return ret; } bool CWallet::DelContractBook(const std::string &strAddress) { { LOCK(cs_wallet); // mapContractBook mapContractBook.erase(strAddress); } NotifyContractBookChanged(this, strAddress, "", "", CT_DELETED); CWalletDB walletdb(pwalletMain->strWalletFile); //CWalletDB walletdb(*dbw, "r+", true); bool ret = walletdb.EraseContractData(strAddress, "name"); ret &= walletdb.EraseContractData(strAddress, "abi"); return ret; } bool CWallet::LoadContractData(const std::string &address, const std::string &key, const std::string &value) { bool ret = true; if(key == "name") { mapContractBook[address].name = value; } else if(key == "abi") { mapContractBook[address].abi = value; } else { ret = false; } return ret; } CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const { if (pwallet == 0) return 0; // Must wait until coinbase is safely deep enough in the chain before valuing it if (IsCoinBase() && GetBlocksToMaturity() > 0) return 0; if (fUseCache && fAvailableCreditCached) return nAvailableCreditCached; CAmount nCredit = 0; uint256 hashTx = GetHash(); for (unsigned int i = 0; i < vout.size(); i++) { bool spent = pwallet->IsSpent(hashTx, i); //LogPrintf("CWalletTx::GetAvailableCredit|output=%s:%d,spent=%d\n",hashTx.ToString(),i,spent); if (!spent) { const CTxOut& txout = vout[i]; #ifdef DPOS if(txout.IsEntrusted() || txout.IsCreateAgentType()) continue; #endif nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE); if (!MoneyRange(nCredit)) throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range"); } } nAvailableCreditCached = nCredit; fAvailableCreditCached = true; return nCredit; } CAmount CWalletTx::GetUnlockedCredit() const { if (pwallet == 0) return 0; // Must wait until coinbase is safely deep enough in the chain before valuing it if (IsCoinBase() && GetBlocksToMaturity() > 0) return 0; CAmount nCredit = 0; uint256 hashTx = GetHash(); for (unsigned int i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (pwallet->IsSpent(hashTx, i) || pwallet->IsLockedCoin(hashTx, i)) continue; if (fMasterNode && vout[i].nValue == 10000 * COIN) continue; // do not count MN-like outputs #ifdef DPOS if(txout.IsEntrusted()) // 委托输出不可用 continue; #endif nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE); if (!MoneyRange(nCredit)) throw std::runtime_error("CWalletTx::GetUnlockedCredit() : value out of range"); } return nCredit; } CAmount CWalletTx::GetMasternodeLockedCredit() const { if (pwallet == 0) return 0; // Must wait until coinbase is safely deep enough in the chain before valuing it if (IsCoinBase() && GetBlocksToMaturity() > 0) return 0; CAmount nCredit = 0; uint256 hashTx = GetHash(); for (unsigned int i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; // Skip spent coins if (pwallet->IsSpent(hashTx, i)) continue; // Add locked coins if (pwallet->IsLockedCoin(hashTx, i) && vout[i].nValue == 10000 * COIN) { nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE); } // Add masternode collaterals which are handled likc locked coins else if (fMasterNode && vout[i].nValue == 10000 * COIN) { nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE); } if (!MoneyRange(nCredit)) throw std::runtime_error("CWalletTx::GetMasternodeLockedCredit() : value out of range"); } return nCredit; }
[ "gkcproject@hotmail.com" ]
gkcproject@hotmail.com
d2449a090a0a6b3f827652017a757ec9ca83022c
4abe6baa6ecc1e2d47c43555aca329b7ff6d99de
/Source/Teme/Flappy Bird/Tema1.cpp
de47adc985a936990516165551068e332303a6a4
[]
no_license
craciunoiuc/computer-graphics
3ce179ef2490a9a3823239e151ae22eb93763c6f
0b04aca12b33bfcda7bbf7f5dc1b74319bbc18c1
refs/heads/master
2021-01-04T14:40:54.469649
2020-02-14T20:40:18
2020-02-14T20:40:18
240,594,562
1
0
null
null
null
null
UTF-8
C++
false
false
10,597
cpp
#include "Tema1.h" #include <vector> #include <string> #include <iostream> #include "../../../Visual Studio/Objects.h" #include "../../../Visual Studio/Transform.h" using namespace std; Tema1::Tema1() { } Tema1::~Tema1() { } static int cameraX = 0, cameraY = 0, cameraZ = 1; static int inaltime = 0.0f, latime = 0.0f; void Tema1::Init() { renderCameraTarget = false; //camera = new Tema::Camera(); glm::ivec2 resolution = window->GetResolution(); //camera->Set(glm::vec3(0, 0, 1), glm::vec3(0, 0, 0), glm::vec3(0, 0, 0)); // TODO TO CHANGE camera = GetSceneCamera(); camera->SetOrthographic(0, (float)resolution.x, 0, (float)resolution.y, 0, 40); camera->SetPosition(glm::vec3(cameraX, cameraY, cameraZ)); camera->SetRotation(glm::vec3(0, 0, 0)); camera->Update(); // //projectionMatrix = glm::ortho(0.0f, (float)resolution.x, 0.0f, (float)resolution.y, 0.01f, 40.0f); //camera->TranslateUpword(100); GetCameraInput()->SetActive(false); float length = 30; glm::vec3 centerSquare = glm::vec3(-length / 2, -length / 2, 0); glm::vec3 centerTriangle = glm::vec3(-length / 2, -length / 3, 0); glm::vec3 centerRectangle = glm::vec3(0, 0, 0); // initialize tx and ty (the translation steps) translateX = 0; translateY = 0; for (int i = 0; i < 50; ++i) { randomGap.push_back(rand() % 100); } Mesh* square = Objects::CreateSquare("square", centerSquare, length, glm::vec3(0, 0, 0), true); AddMeshToList(square); Mesh* rectangle = Objects::CreateRectangle("rectang", centerRectangle, length * 3, glm::vec3(0, 0, 1), true); AddMeshToList(rectangle); Mesh* triangle = Objects::CreateTriangle("triangle", centerTriangle, length, glm::vec3(0, 0, 0), true); AddMeshToList(triangle); } void Tema1::FrameStart() { // clears the color buffer (using the previously set color) and depth buffer glClearColor(1, 1, 1, 1); // Setat culoare fundal glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::ivec2 resolution = window->GetResolution(); // sets the screen area where to draw glViewport(0, 0, resolution.x, resolution.y); } void Tema1::Update(float deltaTimeSeconds) { //glm::ivec2 resolution = window->GetResolution(); //projectionMatrix = glm::ortho(0.0f + latime, (float)resolution.x - latime, 0.0f + inaltime, (float)resolution.y - inaltime, 0.0f, 40.0f); const int startX = 150, startY = 350; if (gameStarted && !gameFinished) { translateX += (100 + velocity) * deltaTimeSeconds; if (toJump > 1) { translateY += 70 * deltaTimeSeconds; if (rotateAngle < 0.90) { rotateAngle += 1.55 * deltaTimeSeconds; } //rotateAngle += 1.2 * deltaTimeSeconds; toJump--; } else { translateY -= 60 * deltaTimeSeconds; if (rotateAngle > -0.90) { rotateAngle -= 1.05 * deltaTimeSeconds; } } if (rotateAngle < 0.7) { jumpKey = true; } } std::vector <std::pair<std::pair<int, int>, std::pair<int, int>>> birdCoords; // Corp modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(0, translateY); modelMatrix *= Transform::Translate(-30, 0); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(30, 0); RenderMesh2D(meshes["square"], shaders["VertexColor"], modelMatrix); birdCoords.push_back({ {startX, startY + translateY}, {30, 30} }); modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(25, 0); modelMatrix *= Transform::Translate(0, translateY); modelMatrix *= Transform::Translate(-55, 0); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(55, 0); RenderMesh2D(meshes["square"], shaders["VertexColor"], modelMatrix); birdCoords.push_back({ {startX + 25, startY + translateY}, {30, 30} }); // Picioare modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(0, translateY - 10); modelMatrix *= Transform::Translate(-30, 10); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(30, -10); RenderMesh2D(meshes["square"], shaders["VertexColor"], modelMatrix); birdCoords.push_back({ {startX, startY + translateY - 10}, {30, 30} }); modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(25, 0); modelMatrix *= Transform::Translate(0, translateY - 10); modelMatrix *= Transform::Translate(-55, 10); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(55, -10); RenderMesh2D(meshes["square"], shaders["VertexColor"], modelMatrix); birdCoords.push_back({ {startX, startY + translateY - 10}, {30, 30} }); //Aripi modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(0 + 20, translateY + 10); modelMatrix *= Transform::Rotate(0.1); modelMatrix *= Transform::Translate(-50, -10); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(50, 10); RenderMesh2D(meshes["triangle"], shaders["VertexColor"], modelMatrix); //birdCoords.push_back({ startX + 20, startY + translateY + 10}); modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(0 + 1, translateY + 10); modelMatrix *= Transform::Rotate(0.1); modelMatrix *= Transform::Translate(-31, -10); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(31, 10); RenderMesh2D(meshes["triangle"], shaders["VertexColor"], modelMatrix); //birdCoords.push_back({ startX + 1, startY + 10 + translateY}); //Cioc modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(0 + 41, translateY - 9); modelMatrix *= Transform::Translate(-71, 9); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(71, -9); RenderMesh2D(meshes["triangle"], shaders["VertexColor"], modelMatrix); //birdCoords.push_back({ { startX + 41, startY + translateY - 9}, { 30, 30 } }); //Coada modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(startX, startY); modelMatrix *= Transform::Translate(0 - 10, translateY - 5); modelMatrix *= Transform::Translate(-20, 5); modelMatrix *= Transform::Rotate(rotateAngle); modelMatrix *= Transform::Translate(20, -5); RenderMesh2D(meshes["triangle"], shaders["VertexColor"], modelMatrix); //birdCoords.push_back({ startX - 10, startY + translateY - 5}); std::vector<std::pair<std::pair<int, int>, std::pair<int, int>>> objectCoords; // Desenare mediu const int offsetX = 1100; const int offsetY = -450; bool newElem = true; // Pereche int nrOfCreatedBarriers = 0; for (uint32_t barrier = ((nrOfCreatedBarriers - 6) > 0)? (nrOfCreatedBarriers - 6) * 200 : 0; barrier + startX + offsetX - translateX < 1280; ++nrOfCreatedBarriers, barrier += 200) { if (barrier + startX + offsetX - translateX > -90) { modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(barrier + startX + offsetX, startY + 70 + randomGap.at(nrOfCreatedBarriers % 50)); modelMatrix *= Transform::Scale(1.0, 2.3); modelMatrix *= Transform::Translate(-translateX, 0); RenderMesh2D(meshes["rectang"], shaders["VertexColor"], modelMatrix); modelMatrix = glm::mat3(1); modelMatrix *= Transform::Translate(barrier + startX + offsetX, startY + offsetY + randomGap.at(nrOfCreatedBarriers % 50)); modelMatrix *= Transform::Scale(1.0, 2.0); modelMatrix *= Transform::Translate(-translateX, 0); RenderMesh2D(meshes["rectang"], shaders["VertexColor"], modelMatrix); objectCoords.push_back({ {barrier + startX + offsetX - translateX, (startY + 60 + randomGap.at(nrOfCreatedBarriers % 50))}, {90, 180 * 2.3} }); objectCoords.push_back({ {barrier + startX + offsetX - translateX, startY + offsetY + randomGap.at(nrOfCreatedBarriers % 50)}, {90, 360} }); } } // Verificare coliziune for (auto& barrier : objectCoords) { for (auto& birdPart : birdCoords) { if (!gameFinished && Objects::ObjectsOverlap(birdPart, barrier) && Objects::ObjectsOverlap(birdPart, barrier)) { gameFinished = true; std::cout << "Score:" << nrOfCreatedBarriers - 6 << std::endl; break; } } } } void Tema1::FrameEnd() { DrawCoordinatSystem(camera->GetViewMatrix(), projectionMatrix); } void Tema1::OnInputUpdate(float deltaTime, int mods) { float cameraSpeed = 2.0f; if (jumpKey && window->KeyHold(GLFW_KEY_SPACE)) { gameStarted = true; jumping = true; toJump = 20; jumpKey = false; } /*if (window->MouseHold(GLFW_MOUSE_BUTTON_RIGHT)) { float cameraSpeed = 2.0f; if (window->KeyHold(GLFW_KEY_W)) { // TODO : translate the camera forward camera->TranslateForward(deltaTime * cameraSpeed); } if (window->KeyHold(GLFW_KEY_A)) { // TODO : translate the camera to the left camera->TranslateRight(-deltaTime * cameraSpeed); } if (window->KeyHold(GLFW_KEY_S)) { // TODO : translate the camera backwards camera->TranslateForward(-deltaTime * cameraSpeed); } if (window->KeyHold(GLFW_KEY_D)) { // TODO : translate the camera to the right camera->TranslateRight(deltaTime * cameraSpeed); } if (window->KeyHold(GLFW_KEY_Q)) { // TODO : translate the camera down camera->TranslateUpward(deltaTime * cameraSpeed); } if (window->KeyHold(GLFW_KEY_E)) { // TODO : translate the camera up camera->TranslateUpward(-deltaTime * cameraSpeed); } }*/ if (window->KeyHold(GLFW_KEY_3)) { inaltime += 0.5f; } if (window->KeyHold(GLFW_KEY_4)) { inaltime -= 0.5f; } if (window->KeyHold(GLFW_KEY_5)) { latime += 0.5f; } if (window->KeyHold(GLFW_KEY_6)) { latime -= 0.5f; } } void Tema1::OnKeyPress(int key, int mods) { if (key == GLFW_KEY_E) { velocity += 200; } if (key == GLFW_KEY_Q) { velocity -= 200; } if (key == GLFW_KEY_R) { gameFinished = false; } } void Tema1::OnKeyRelease(int key, int mods) { // add key release event } void Tema1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) { // add mouse move event } void Tema1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) { // add mouse button press event } void Tema1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) { // add mouse button release event } void Tema1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) { } void Tema1::OnWindowResize(int width, int height) { } // De Facut // 1. Camera 2d // 2. Curatat Cod // 4. Readme // 7. Modificat translate sa nu faca overflow - face la 10mil
[ "craciunoiu.cezar@yahoo.com" ]
craciunoiu.cezar@yahoo.com
f25a515d29a7e6dd4f440c9db26234f788fe5dae
ac48dc874f5550d03648c28b1eda5720202eb55c
/prebuilt_HY11/target/product/msm8953_32/obj/include/mare/mare/internal/task/task_shared_ptr.hh
95853eaa47eb3083c5b32c782e338aa3a8c950d7
[]
no_license
difr/msm8937-8953_qcom_vendor
464e478cae4a89de34ac79f4d615e5141c40cbcb
6cafff53eca7f0c28fa9c470b5211423cf47fd40
refs/heads/master
2020-03-20T09:58:48.935110
2018-05-27T04:13:22
2018-05-27T04:13:22
137,355,108
0
1
null
null
null
null
UTF-8
C++
false
false
450
hh
// --~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~-- // Copyright 2013-2015 Qualcomm Technologies, Inc. // All rights reserved. // Confidential and Proprietary – Qualcomm Technologies, Inc. // --~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~----~--~--~--~-- #pragma once #include <mare/internal/util/mareptrs.hh> namespace mare { namespace internal { class task; using task_shared_ptr = mare_shared_ptr<task>; }; };
[ "adithya.r02@outlook.com" ]
adithya.r02@outlook.com
3441f3129bea67cfa8de366dc702094a9ab3808d
5507ff1d3a3abdb1085156cfcf7bf377290946a7
/SimpleComServer/SmartControl.cpp
7503d5496489e842d8a68943422e40206c08907e
[]
no_license
cattommy/SimpleComServer
8cd33177c85c4d83936c2300e8b97ddf033fb170
c92867b685afc54a824237da780f7c0c131227a7
refs/heads/master
2021-04-15T14:46:48.315024
2016-06-30T14:39:11
2016-06-30T14:39:11
62,316,660
0
0
null
null
null
null
UTF-8
C++
false
false
228
cpp
// SmartControl.cpp : Implementation of CSmartControl #include "stdafx.h" #include "SmartControl.h" // CSmartControl STDMETHODIMP CSmartControl::call(BSTR c) { // TODO: Add your implementation code here return S_OK; }
[ "tt3.14@mail.ru" ]
tt3.14@mail.ru
06fe9ef747d80192190773084785d312a59e3aaa
f94aa5bd4d8814b57ae6713c1f69fa1e11bc6526
/TribesAscendSDK/HeaderDump/TribesGame__TrArmorMod.h
a2bed42921fcde14c33099cfbade5a75d9aac870
[]
no_license
pixel5/TASDK
71980b727b86034771ea91c67f6c02116f47c245
0dc5e4524efed291fe7d8cf936fa64e0e37e4e82
refs/heads/master
2020-05-23T15:12:55.162796
2013-07-13T00:27:32
2013-07-13T00:27:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
863
h
#pragma once #define ADD_VAR( x, y, z ) ( ##x ) var_##y() \ { \ static ScriptProperty *script_property = ( ScriptProperty* )( ScriptObject::Find( #x " TribesGame.TrArmorMod." #y ) ); \ return ( ##x( this, script_property->offset, z ) ); \ } #define ADD_STRUCT( x, y, z ) ( ##x ) var_##y() \ { \ static ScriptProperty *script_property = ( ScriptProperty* )( ScriptObject::Find( "StructProperty TribesGame.TrArmorMod." #y ) ); \ return ( ##x( this, script_property->offset, z ) ); \ } #define ADD_OBJECT( x, y ) ( class x* ) var_##y() \ { \ static ScriptProperty *script_property = ( ScriptProperty* )( ScriptObject::Find( "ObjectProperty TribesGame.TrArmorMod." #y ) ); \ return *( x** )( this + script_property->offset ); \ } namespace UnrealScript { class TrArmorMod : public TrDevice { public: }; } #undef ADD_VAR #undef ADD_STRUCT #undef ADD_OBJECT
[ "altimormc@gmail.com" ]
altimormc@gmail.com
fe0bd7e321e5f39abade559d6b90c1a1c80ba605
11a49a8fdc1d1ed3418932d607b4ec70e35b2888
/ProgrammeC++/tabelle2/main.cpp
3150f09cf939802c4275615ef8fb88e656bd1ca4
[]
no_license
FelixTheC/computer-science-studies-ILS
e6b67255300dd4a462223441991eea5ba245d496
f86352047fd03ea0bec2a1498770a411f649f0da
refs/heads/master
2020-12-30T11:59:50.334063
2017-05-16T19:55:37
2017-05-16T19:55:38
91,482,777
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
#include <iostream> using namespace std; string verknuepf (bool, bool); { int tabelle [5][5][5]; } int main() { cout << string verknuepf() << endl; return 0; }
[ "felixeisenmenger@gmx.net" ]
felixeisenmenger@gmx.net
0cc04c0f1e2a014768afd671f23fb253d6d81ca7
2e9764404e3341bfdb410ddaaf8d9fe0fae3097a
/inc/BMP_Header.h
dc8d8878ade4ddaa6086a6c8157ceb7b8e38f706
[]
no_license
akhileshpandey1989/BiMP
a94b4cfec406b980c92610bb669f05c0ca98bc37
adcc815320029c0255a3d5418a9620f987dea2ec
refs/heads/master
2016-09-10T13:48:12.465860
2013-09-25T19:43:22
2013-09-25T19:43:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
337
h
class BMP_Header { char header[14]; int file_size; int pixel_array_offset; public: BMP_Header(); BMP_Header(const char* inp_file); int get_file_size(); void set_file_size(int fs); int get_pixel_array_offset(); void set_pixel_array_offset(int pao); void copy_BMP_Header(char *destination); void display_BMP_Header(); };
[ "akhileshpandey1989@gmail.com" ]
akhileshpandey1989@gmail.com
e5cda8eb71217a07634e7050a068968002047c0f
5c277595fb142a41746853ef9a68d365bb5e468f
/phantasma/Cryptography/SHA.h
090fe873299abb28f054dc4685b2d90e21a29107
[ "MIT" ]
permissive
GOATi/blindbag_audit
8dbe631c671e1bbd5d7aca88d25e1175e4370fdf
93fa603620804cbc16af5b8f535e49c32d8f131d
refs/heads/master
2021-01-02T14:30:31.251400
2020-12-03T11:18:20
2020-12-03T11:18:20
239,662,847
1
0
null
null
null
null
UTF-8
C++
false
false
669
h
#pragma once #ifndef PHANTASMA_SHA256 #error "You must supply a SHA256 implementation" #endif namespace phantasma { #define PHANTASMA_SHA256_LENGTH 32 void SHA256( Byte* output, int outputSize, const Byte* input, int inputSize ) { if(!output || !input || outputSize != PHANTASMA_SHA256_LENGTH || inputSize < 0 ) { PHANTASMA_EXCEPTION("Invalid arguments"); return; } PHANTASMA_SHA256(output, outputSize, input, inputSize); } ByteArray SHA256( const ByteArray& input ) { ByteArray result; result.resize(PHANTASMA_SHA256_LENGTH); SHA256(&result.front(), PHANTASMA_SHA256_LENGTH, input.empty() ? 0 : &input.front(), (int)input.size()); return result; } }
[ "brooke.hodgman@gmail.com" ]
brooke.hodgman@gmail.com
c19471c2c6d95befce47fdda7281882910b7356b
58958463ae51c6af762ade55e53154cdd57e9b71
/OpenSauce/Halo2/Halo2_Xbox/TagGroups/TagGroups.hpp
8da525f076acb776f0058e242ce7fd1f3b76cb3e
[]
no_license
yumiris/OpenSauce
af270d723d15bffdfb38f44dbebd90969c432c2b
d200c970c918921d40e9fb376ec685c77797c8b7
refs/heads/master
2022-10-10T17:18:20.363252
2022-08-11T20:31:30
2022-08-11T20:31:30
188,238,131
14
3
null
2020-07-14T08:48:26
2019-05-23T13:19:31
C++
UTF-8
C++
false
false
216
hpp
/* Yelo: Open Sauce SDK Halo 2 (Xbox) Edition See license\OpenSauce\Halo2_Xbox for specific license information */ #pragma once #include <blamlib/Halo2/tag_files/tag_groups.hpp> namespace Yelo { };
[ "kornman00@gmail.com" ]
kornman00@gmail.com
9f6ceda453c12ce5535244e1c79578103d8ec07f
4003fcac8331a732f210f5908e8734a653c38111
/pythonlib/main.cpp
99dad62c5e24e6f6700fcb51c207681adcf9b76b
[ "MIT" ]
permissive
rhythmus-emulator/rparser
0de6faf10edee7fca4f8bcfa5324b4599219c3d3
d2efba4c36e5f74fda3da4b90f7e9119f1f62861
refs/heads/master
2021-11-26T00:00:35.627460
2021-11-06T06:08:53
2021-11-06T06:08:53
67,385,425
1
0
null
null
null
null
UTF-8
C++
false
false
8,820
cpp
#include "pybind11/pybind11.h" #include "Song.h" #include "ChartUtil.h" namespace py = pybind11; using namespace rparser; template <typename A, typename T, typename NT> py::class_<T> pyclass_track(A &m, const char* name) { return py::class_<T>(m, name) .def("get", &T::get) .def("clear", &T::clear) .def("size", &T::size) .def("front", [](T &t) { return t.front(); }) .def("back", [](T &t) { return t.back(); }) .def("is_empty", &T::is_empty) .def("AddNoteElement", &T::AddNoteElement) .def("RemoveNoteElement", &T::RemoveNoteElement) .def("RemoveObjectByBeat", &T::RemoveObjectByBeat) .def("RemoveObjectByPos", &T::RemoveObjectByPos) .def("ClearAll", &T::ClearAll) .def("ClearRange", &T::ClearRange) .def("MoveAll", &T::MoveAll) .def("MoveRange", &T::MoveRange) .def("InsertBlank", &T::InsertBlank) .def("IsHoldNoteAt", &T::IsHoldNoteAt) .def("IsRangeEmpty", [](T &t, double m_start, double m_end) { return t.IsRangeEmpty(m_start, m_end); }) ; } template <typename A, typename T, typename NT> py::class_<T> pyclass_track_datatype(A &m, const char* name) { return py::class_<T>(m, name) .def("clear", &T::clear) .def("size", &T::size) .def("front", [](T &t) { return t.front(); }) .def("back", [](T &t) { return t.back(); }) .def("is_empty", &T::is_empty) .def("AddNoteElement", &T::AddNoteElement) .def("RemoveNoteElement", &T::RemoveNoteElement) .def("RemoveObjectByBeat", &T::RemoveObjectByBeat) .def("RemoveObjectByPos", &T::RemoveObjectByPos) .def("ClearAll", &T::ClearAll) .def("ClearRange", &T::ClearRange) .def("MoveAll", &T::MoveAll) .def("MoveRange", &T::MoveRange) .def("InsertBlank", &T::InsertBlank) .def("IsHoldNoteAt", &T::IsHoldNoteAt) .def("IsRangeEmpty", [](T &t, double m_start, double m_end) { return t.IsRangeEmpty(m_start, m_end); }) .def("toString", &T::toString) .def("GetAllTrackIterator", [](T& nd) { return nd.GetAllTrackIterator(); }) .def("GetRowIterator", [](T& nd) { return nd.GetRowIterator(); }) .def("get_track", [](const T& d, size_t i) { return d.get_track(i); }) .def("__getitem__", [](const T& d, size_t i) { return d.get_track(i); }); } template <typename A, typename T> py::class_<T> pyclass_objtype(A &m, const char* name) { // TODO: get_value, set_value, get_point, set_point return py::class_<T>(m, name) .def(py::init<>()) .def("time", &T::time_msec) .def("beat", &T::beat) .def("measure", &T::measure) .def("set_time", &T::set_time_msec) .def("set_beat", &T::set_beat) .def("set_measure", &T::set_measure) .def("toString", &T::toString); } PYBIND11_MODULE(rparser_py, m) { py::class_<Song>(m, "Song") .def(py::init<>()) .def("Open", [](Song& s, const std::string& fn) { return s.Open(fn); }) .def("Close", [](Song &s) { s.Close(); }) .def("Close", &Song::Close) .def("GetChartCount", &Song::GetChartCount) .def("GetPath", &Song::GetPath) .def("GetChart", (Chart* (Song::*)(size_t)) &Song::GetChart) .def("GetChart", (Chart* (Song::*)(const std::string&)) &Song::GetChart) .def("NewChart", &Song::NewChart) .def("DeleteChart", &Song::DeleteChart) ; py::class_<Chart>(m, "Chart") .def(py::init<>()) .def("GetMetaData", (MetaData& (Chart::*)()) &Chart::GetMetaData) .def("GetBgmData", (TrackData& (Chart::*)()) &Chart::GetBgmData) .def("GetNoteData", (TrackData& (Chart::*)()) &Chart::GetNoteData) .def("GetCommandData", (TrackData& (Chart::*)()) &Chart::GetCommandData) .def("GetTimingData", (TrackData& (Chart::*)()) &Chart::GetTimingData) .def("GetTimingSegmentData", (TimingSegmentData& (Chart::*)()) &Chart::GetTimingSegmentData) .def("GetNoteCount", &Chart::GetScoreableNoteCount) .def("GetLastObjectTime", &Chart::GetSongLastObjectTime) .def("HasLongNote", &Chart::HasLongnote) .def("GetPlayLaneCount", &Chart::GetPlayLaneCount) .def("IsEmpty", &Chart::IsEmpty) .def("GetHash", &Chart::GetHash) .def("GetFilename", &Chart::GetFilename) .def("Update", &Chart::Update) ; py::class_<MetaData>(m, "MetaData") .def("SetUtf8Encoding", &MetaData::SetUtf8Encoding) .def("GetAttribute", (int (MetaData::*)(const std::string&) const) &MetaData::GetAttribute) .def("GetAttribute", (double (MetaData::*)(const std::string&) const) &MetaData::GetAttribute) //.def("GetAttribute", (std::string(MetaData::*)(const std::string&) const) &MetaData::GetAttribute) .def("SetAttribute", (void (MetaData::*)(const std::string&, int)) &MetaData::SetAttribute) .def("SetAttribute", (void (MetaData::*)(const std::string&, const std::string&)) &MetaData::SetAttribute) .def("SetAttribute", (void (MetaData::*)(const std::string&, double)) &MetaData::SetAttribute) .def("SetMetaFromAttribute", &MetaData::SetMetaFromAttribute) .def_readwrite("title", &MetaData::title) .def_readwrite("artist", &MetaData::artist) .def_readwrite("subtitle", &MetaData::subtitle) .def_readwrite("subartist", &MetaData::subartist) .def_readwrite("genre", &MetaData::genre) .def_readwrite("charttype", &MetaData::charttype) .def_readwrite("chartmaker", &MetaData::chartmaker) .def_readwrite("player_count", &MetaData::player_count) .def_readwrite("player_side", &MetaData::player_side) .def_readwrite("difficulty", &MetaData::difficulty) .def_readwrite("level", &MetaData::level) .def_readwrite("bpm", &MetaData::bpm) .def_readwrite("total", &MetaData::gauge_total) .def_readwrite("LNType", &MetaData::bms_longnote_type) .def_readwrite("LNOBJ", &MetaData::bms_longnote_object) .def_readwrite("script", &MetaData::script) .def("GetSoundChannel", (SoundMetaData* (MetaData::*)()) &MetaData::GetSoundChannel) .def("GetBGAChannel", (BgaMetaData* (MetaData::*)()) &MetaData::GetBGAChannel) .def("GetBPMChannel", (BmsBpmMetaData* (MetaData::*)()) &MetaData::GetBPMChannel) .def("GetSTOPChannel", (BmsStopMetaData* (MetaData::*)()) &MetaData::GetSTOPChannel) .def("toString", &MetaData::toString) ; py::class_<TimingSegmentData>(m, "TimingSegmentData") .def("GetTimeFromBeat", &TimingSegmentData::GetTimeFromBeat) .def("GetBeatFromTime", &TimingSegmentData::GetBeatFromTime) .def("GetBeatFromMeasure", &TimingSegmentData::GetBeatFromMeasure) .def("GetMeasureFromBeat", &TimingSegmentData::GetMeasureFromBeat) .def("GetMeasureFromTime", &TimingSegmentData::GetMeasureFromTime) .def("GetMaxBpm", &TimingSegmentData::GetMaxBpm) .def("GetMinBpm", &TimingSegmentData::GetMinBpm) .def("HasBpmChange", &TimingSegmentData::HasBpmChange) .def("HasStop", &TimingSegmentData::HasStop) .def("HasWarp", &TimingSegmentData::HasWarp) .def("clear", &TimingSegmentData::clear) .def("toString", &TimingSegmentData::toString) ; pyclass_track_datatype<decltype(m), TrackData, NoteElement>(m, "TrackData"); pyclass_track<decltype(m), Track, NoteElement>(m, "Track"); pyclass_objtype<decltype(m), NoteElement>(m, "NotePos"); py::class_<TrackData::all_track_iterator>(m, "AllTrackIterator") .def("get", &TrackData::all_track_iterator::get) .def("next", &TrackData::all_track_iterator::next) .def("get_track", &TrackData::all_track_iterator::get_track) .def("is_end", &TrackData::all_track_iterator::is_end); py::class_<TrackData::row_iterator>(m, "RowIterator") .def("get", [](const TrackData::row_iterator &riter, size_t i) { return riter[i]; }) .def("get_measure", &TrackData::row_iterator::get_measure) .def("next", &TrackData::row_iterator::next) .def("is_end", &TrackData::row_iterator::is_end); #if 0 pyclass_objtype<decltype(m), Note>(m, "Note") .def("chainsize", &Note::chainsize) .def("IsLongnote", [](Note& n) { return n.chainsize() > 1; }) .def("get_player", &Note::get_player) .def("set_player", &Note::set_player) ; #endif // ChartUtil functions m.def("ExportToHTML", ExportToHTML); py::class_<effector::EffectorParam>(m, "EffectorParam"); m.def("SetLanefor7Key", effector::SetLanefor7Key); m.def("SetLanefor9Key", effector::SetLanefor9Key); m.def("SetLaneforBMS1P", effector::SetLaneforBMS1P); m.def("SetLaneforBMS2P", effector::SetLaneforBMS2P); m.def("SetLaneforBMSDP1P", effector::SetLaneforBMSDP1P); m.def("SetLaneforBMSDP2P", effector::SetLaneforBMSDP2P); m.def("GenerateRandomColumn", effector::GenerateRandomColumn); m.def("Random", effector::Random); m.def("SRandom", effector::SRandom); m.def("HRandom", effector::HRandom); m.def("RRandom", effector::RRandom); m.def("Mirror", effector::Mirror); m.def("AllSC", effector::AllSC); m.def("Flip", effector::Flip); // TODO: add definition for adding note with smart pointer }
[ "kgdgwn98@gmail.com" ]
kgdgwn98@gmail.com
b6a84750dc581cb542c173c50e3ce554eb4524f3
94848e00d5d800b06a4581f978fd48901c69b1f7
/libembryo/src/FixedMonitor.cpp
c9d165cd3f817c0799b8877868cba75f10b75d34
[]
no_license
Janulka/embryo
8ed3bc9f1b92c199860b50ee3ffc95b6ecd15a1d
51f87706716df0568f913775a3ab731b21590bbd
refs/heads/master
2020-04-23T21:01:11.896121
2014-10-31T05:57:40
2014-10-31T05:58:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
cpp
/* * libembryo * Copyright (C) 2008 by Alexandre Devert * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2004 Sam Hocevar * 14 rue de Plaisance, 75014 Paris, France * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. */ #include "Embryo.h" #include "FixedMonitor.h" using namespace embryo; // --- FixedMonitor ----------------------------------------------------------- FixedMonitor::FixedMonitor(size_t inNbSteps) : mNbSteps(inNbSteps) { } FixedMonitor::~FixedMonitor() { } void FixedMonitor::init(const Embryo& inEmbryo) { mNbStepsConsumed = 0; } bool FixedMonitor::hasNext(bool ibColor) { return mNbStepsConsumed < mNbSteps; } void FixedMonitor::next(const Embryo& inEmbryo) { mNbStepsConsumed += 1; } // --- FixedMonitorFactory ---------------------------------------------------- FixedMonitorFactory::FixedMonitorFactory(const ObjectFactoryDealer& inDealer) : ObjectFactory("fixed.monitor", inDealer) { } FixedMonitorFactory::~FixedMonitorFactory() { } Object::Handle FixedMonitorFactory::produce(MapTree::Handle inMapTree) const { size_t lNbSteps; inMapTree->get("max.nb.steps", lNbSteps); return new FixedMonitor(lNbSteps); }
[ "jbaran@newfieldwireless.com" ]
jbaran@newfieldwireless.com
e20f7ad4c7f9b4b18a19195c5b7fdbaf3918a676
493a4c99ba7d2122bcca2a495b87bf190ece5750
/martixsearchassign.cpp
7d36ece56ce4b4519adbc30153db2332ddb0a8de
[]
no_license
md-qubais/Data_Structures_Algorithms_and_Competitive_Programming
9b8d38c05522568bbf4cffa95dc5390a3aaae1cb
d7157c27720fa28ead3d4562e423ad719aabd87b
refs/heads/main
2023-04-02T12:36:34.482803
2021-04-05T08:31:14
2021-04-05T08:31:14
354,769,143
1
0
null
null
null
null
UTF-8
C++
false
false
733
cpp
#include<bits/stdc++.h> using namespace std; int matrixsearch(int **arr,int rows,int cols,int key){ int i=0,j=cols-1; while(i<rows&&i>=0&&j<cols&&j>=0){ if(arr[i][j]==key){ return 1; } else if(arr[i][j]>key){ j--; }else{ i++; } } return 0; } int main(){ #ifndef qubais_judge freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int rows; int cols; cin>>rows>>cols; int **arr=new int*[rows]; for(int i=0;i<rows;i++){ arr[i]=new int[cols]; } for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ cin>>arr[i][j]; } } int key; cin>>key; cout<<matrixsearch(arr,rows,cols,key)<<endl; return 0; }
[ "shareefhussain733@gmail.com" ]
shareefhussain733@gmail.com
3efbc3312670a24ea4701f5c216f5ff8eb28bc1b
680440f5e59eb2157c1ecb41fd891880ac47c459
/LUOGU/P3390/mtrx.cpp
0f789aba78b1cbd0e1142613c0d7f32395621f72
[]
no_license
Skywt2003/codes
a705dc3a4f5f79d47450179fc597bd92639f3d93
0e09198dc84e3f6907a11b117a068f5e0f55ca68
refs/heads/master
2020-03-29T09:29:54.014364
2019-11-15T12:39:47
2019-11-15T12:39:47
149,760,952
6
0
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
#include<cstdio> #include<cstring> #include<iostream> using namespace std; const int maxn=105,tt=1000000007;; int n; long long m; inline int read(){ int ret=0,f=1;char ch=getchar(); while (ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();} while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar(); return ret*f; } struct Matrix{ int a[maxn][maxn]; void ReadMatrix(){ memset(a,0,sizeof(a)); for (int i=0;i<n;i++) for (int j=0;j<n;j++) a[i][j]=read(); } void Init(){ memset(a,0,sizeof(a)); for (int i=0;i<n;i++) a[i][i]=1; } void Clear(){ memset(a,0,sizeof(a)); } Matrix operator *(Matrix b){ Matrix c; c.Clear(); for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) c.a[i][j]=((long long)c.a[i][j]+(long long)a[i][k]*b.a[k][j])%tt; return c; } Matrix operator ^(long long b){ Matrix ret; ret.Init(); Matrix w; w.Clear(); for (int i=0;i<n;i++) for (int j=0;j<n;j++) w.a[i][j]=a[i][j]; while (b){ if (b%2) ret=ret*w; b=b/2;w=w*w; } return ret; } void Write(){ for (int i=0;i<n;i++){ for (int j=0;j<n;j++) printf("%d ",a[i][j]); printf("\n"); } } }; int main(){ n=read();scanf("%lld",&m); Matrix a; a.ReadMatrix(); // printf("Read part finished.\n"); a=a^m; a.Write(); return 0; }
[ "skywt2003@gmail.com" ]
skywt2003@gmail.com
fc314b24896a8973320aeb0dfd840e7e23da9329
48b8b208571a43270b5181523c2d88fb7c12958d
/1.0.0/libraries/lr1110/examples/application/hci/Command/command_update_almanac.h
82f3abd15b1c68210ccbd3a1f7620dec9120dfc7
[]
no_license
VietNg2702/Repository
da05feaae15820ede99ec6c1861d272149955e29
4e5f82d4dbc9bbfa88b237eaad433d8d6bc128e0
refs/heads/main
2023-06-03T21:18:23.114675
2021-06-22T03:41:28
2021-06-22T03:41:28
370,280,793
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
h
/** * @file command_update_almanac.h * * @brief Definitions of the HCI command to update almanac class. * * Revised BSD License * Copyright Semtech Corporation 2020. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Semtech corporation 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 SEMTECH CORPORATION 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 __COMMAND_UPDATE_ALMANAC_H__ #define __COMMAND_UPDATE_ALMANAC_H__ #include "command_base.h" #include "../hci.h" #define COMMAND_UPDATE_ALMANAC_BUFFER_SIZE ( 20 ) class CommandUpdateAlmanac : public CommandBase { public: CommandUpdateAlmanac( DeviceInterface* device, Hci& hci ); virtual ~CommandUpdateAlmanac( ); virtual uint16_t GetComCode( ); virtual bool ConfigureFromPayload( const uint8_t* buffer, const uint16_t buffer_size ); virtual bool Job( ); private: uint8_t almanac_buffer[COMMAND_UPDATE_ALMANAC_BUFFER_SIZE]; }; #endif // __COMMAND_UPDATE_ALMANAC_H__
[ "ndviet.bkhcm@gmail.com" ]
ndviet.bkhcm@gmail.com
ad73e33820e5e489a3bfc3cba57e42a41e1d66cd
897f6f13f054e726319e634c4253b62ecb7e9408
/clever_raytracer_name/vect.cpp
ac81635db485fb6b56ca9129c292ac993360eb72
[]
no_license
data-exp-lab/cis_viz
2051d693566686003eabfbbc4176112a722d538e
49385af0730be4aae98a823c1ee07f9431c35970
refs/heads/master
2021-07-06T12:31:06.284916
2019-02-15T20:40:35
2019-02-15T20:40:35
110,877,211
1
0
null
null
null
null
UTF-8
C++
false
false
149
cpp
/*#include "vect.hpp" using namespace std; float mix(const float &a, const float &b, const float &mix) { return (b * mix + a * (1 - mix)); }*/
[ "heinmnn2@illinois.edu" ]
heinmnn2@illinois.edu
fbf2df366a097c6875e04642add6d5916925be5c
fd2f49d88a7892df95d65908da1347c487bf82a6
/src/zaf/control/text_validator.cpp
42cad46064d8aa7a29a61f9887850002421ac8cd
[]
no_license
lineCode/zaf
001811678b81964f071e5e3f23e1bd246eab6e80
3fdda80e5dcc9208d7500a01318602db0c3eedc3
refs/heads/master
2023-04-05T11:54:52.521921
2021-04-26T17:39:10
2021-04-26T17:39:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
365
cpp
#include <zaf/control/text_validator.h> #include <cwctype> namespace zaf { TextValidator GetNumberTextValidator() { return [](const TextBox& text_box, const std::wstring& new_text) { for (auto each_char : new_text) { if (! std::iswdigit(each_char)) { return false; } } return true; }; } }
[ "zplutor@qq.com" ]
zplutor@qq.com
89730c6cd2d06dcd0d696bec701278e86eaafb27
b2217569c8f0c23c9f43e8d48911bb03e1d255a8
/Hello World/main.cpp
d29673751ee798f1d06db49ea3f904d33f130bdd
[]
no_license
Deathray75/Start
7180da77835cfa325d4587c9ac7c7cbbfb5f6eac
0cd10c6055430a20718dd61ae9e986f4247b930a
refs/heads/master
2020-05-25T09:32:05.163240
2011-07-13T19:05:05
2011-07-13T19:05:05
2,025,587
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
#include <iostream> int main() { using namespace std; cout << "Hello World" << endl; return 0; }
[ "Deathray75@hotmail.co.uk" ]
Deathray75@hotmail.co.uk
b6b7cb653ec9488e8603287b8222252fb683dd1c
f8083f1ac05ecb07b93c58af98eaf78e8eab9367
/others/Tenka1_Programmer_Contest/2015/qual_B/A.cpp
625797e63b9f0771fa3a0028576a7ba4c9ad4127
[]
no_license
itohdak/AtCoder
4f42ccc7b2b7f71d0d51069bd86503ee0f4b3dbf
9ee89bac3ced919b94096ffd7b644d3716569762
refs/heads/master
2021-06-24T14:42:54.529474
2020-10-16T18:41:27
2020-10-16T18:41:27
134,136,836
2
1
null
2020-02-07T12:45:10
2018-05-20T09:26:13
C++
UTF-8
C++
false
false
646
cpp
#include <bits/stdc++.h> // #include "/home/itohdak/AtCoder/000/print.hpp" using namespace std; #define ll long long #define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++) #define rep(i,n) REP(i,0,n) #define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--) #define rrep(i,n) RREP(i,n-1,0) #define REPL(i,m,n) for(ll i=(ll)(m); i<(ll)(n); i++) #define repl(i,n) REPL(i,0,n) #define all(v) v.begin(), v.end() const int inf = 1e9+7; const ll longinf = 1LL<<60; const ll mod = 1e9+7; int main() { vector<ll> A(20); A[0] = 100; A[1] = 100; A[2] = 200; REP(i, 3, 20) A[i] = A[i-1] + A[i-2] + A[i-3]; cout << A[19] << endl; return 0; }
[ "itohdak@gmail.com" ]
itohdak@gmail.com
1781d255a09d7454c79877bc0e6324c96038c856
85d38f94327099f43cdcf90240fd6b0d8241c6ef
/TravelingFrankenstein.cpp
a532d65eda1a29b370fdbac23916759e6e7b504c
[]
no_license
JamCamAbreu/TravelingSalesmanProblemImplementations
79cecb3b7caf471d3c14042b97a72c7b538411da
2d02a602af494f5eaf4fbf67c596f359a6fd504b
refs/heads/master
2021-08-20T03:03:43.860479
2017-11-28T02:57:59
2017-11-28T02:57:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,533
cpp
/* Alex Hoffer: Traveling Frankenstein Solution. A solution to the Traveling Salesman Problem wherein a first path is generated using the Simulated Annealing algorithm, a subsequent path is found using the 2-Opt algorithm, and a third optimized path is found using the 2.5-Opt algorithm. Called the Traveling Frankenstein due to the stitching together of multiple TSP solutions to find a great optimal path in a reasonable amount of time. */ #include <cstdio> #include <vector> #include <algorithm> #include <stdio.h> #include <string.h> #include <ctime> #include <cmath> #include <time.h> #include <stdlib.h> #include <iomanip> #include <sstream> #include <iostream> #include <fstream> using namespace std; typedef vector<int> possibleSolution; ifstream inputFile; ofstream outputFile; string outputFileName; string testOutputName; class cityInformation { public: vector< pair<double,double> > cityCoords; vector< vector<double> > cost; vector <int> cityNumbers; vector <int> xCoordinates; vector <int> yCoordinates; int** adjacencyMatrix; int N; char s[30]; cityInformation() { string line; if (!inputFile) { cout << "Error opening file." << endl; exit(1); } // Load line by line. while (getline(inputFile, line)) { int counter = 0; // Parse the string. stringstream stream(line); while (1) { int tmp; stream >> tmp; if (stream) { if (counter == 0) cityNumbers.push_back(tmp); else if (counter == 1) xCoordinates.push_back(tmp); else if (counter == 2) yCoordinates.push_back(tmp); } else if (!stream) // No more string to parse, break the infinite loop. { break; } counter++; } } N = cityNumbers.size(); // index from 1 cityCoords.push_back(make_pair(0,0)); vector< double> T; cost.push_back(T); for(int i=0;i<N;i++) { double x,y; cityCoords.push_back(make_pair(xCoordinates.at(i), yCoordinates.at(i))); } constructAdjacencyMatrix(); for(int i=0;i<N;i++) { vector<double> V(N+1); for(int j = 1;j<N;j++) { V[j] = adjacencyMatrix[i][j]; } cost.push_back(V); } } int computeDistance(int idx1, int idx2) { int x1 = xCoordinates.at(idx1); int x2 = xCoordinates.at(idx2); int y1 = yCoordinates.at(idx1); int y2 = yCoordinates.at(idx2); float firstClause = x1 - x2; firstClause = pow(firstClause, 2); float secondClause = y1 - y2; secondClause = pow(secondClause, 2); float sumOfClauses = firstClause + secondClause; float distance = sqrt(sumOfClauses); distance = round(distance); return distance; } void constructAdjacencyMatrix() { int max = cityNumbers.size(); adjacencyMatrix = new int*[max]; for (int i = 0; i < cityNumbers.size(); i++) { adjacencyMatrix[i] = new int[max]; for (int j = 0; j < cityNumbers.size(); j++) { adjacencyMatrix[i][j] = computeDistance(i, j); } } } static int myrandom (int i) { return rand()%i; } possibleSolution genRand(possibleSolution C) { int l,a,b,temp; l = C.size(); a = rand()%l; b = rand()%l; temp = C[a]; C[a] = C[b]; C[b] = temp; return C; } double evaluate(possibleSolution C) { return tourCost(C); } double tourCost(possibleSolution C) { int l = C.size(); double tourCost = 0.0; l = l-1; for (int i=0;i <l; i++) { tourCost += cost[C[i]][C[i+1]]; } tourCost += cost[C[l]][C[0]]; return tourCost; } }; class TravelingFrankenstein { public: possibleSolution best; long int minTour; cityInformation data; TravelingFrankenstein() { minTour = 0.0; } double randProb() { double p = (rand() / (RAND_MAX + 1.0)); return p; } void SimulatedAnnealing() { vector <int> V(data.N); for (int i=0;i < data.N;i++) V[i] = i+1; possibleSolution c = data.genRand(V); best = c; minTour = data.tourCost(c); for(int i=0;i<1000;i++) { random_shuffle(c.begin(),c.end()); double tCost = data.tourCost(c); if(tCost < minTour) { minTour = tCost; best = c; } } c = best; double p,expP,deltaE; // Run at this initial temperature for test cases 1 through 5 and all example cases. //double Temp = 1000000000; // 9 0s // Run at this initial temperature for test case 6. // double Temp = 1000000; // 6 0s double Temp = 950000; // Run at this for test cases 1 thru 5, all example cases. // int numberOfIterations = 100000; // Run at this for test case 6. // int numberOfIterations = 50000; int numberOfIterations = 6000; for (double T = Temp; T > 0.01; T*=0.5) { for (int i = 0; i < numberOfIterations; i++) { possibleSolution n = data.genRand(c); deltaE = eval(c) - eval(n); deltaE /= T; p = 1 / (1+exp(-1*deltaE)); expP = randProb(); if(expP < p) { c = n; double tCost = data.tourCost(c); if(tCost < minTour ) { best = c; minTour = tCost; } } } } // Given our current best path, let's make it better. twoOpt(); //calculatePathDistance(); } /* Given an initial optimal candidate solution from the Simulated Annealing algorithm, optimize further using the 2-Opt algorithm. * The idea here is to look through the best path we have currently and if an edge crosses over another edge, we swap the nodes such that the edges are now straight. This reduces the total distance our Frankenstein travels. */ void twoOpt() { bool changed; do { changed = false; // For each node within bounds, check what nodes it's connected to. If we can reconnect such that there's no crossing over, we reduce distance, so swap the edges. for (int i = 0; i < best.size() - 4; i++) { for (int j = i + 3; j < best.size() - 4; j++) { int distance1 = data.computeDistance(best.at(i) -1, best.at(i + 1) -1); int distance2 = data.computeDistance(best.at(j-1) -1, best.at(j)-1); int distance3 = data.computeDistance(best.at(i)-1, best.at(j-1)-1); int distance4 = data.computeDistance(best.at(i+1)-1, best.at(j)-1); // When we travel from node i to node i + 1, and then node j - 1 to node j, we're crossing over in the graph and thereby increasing our total distance. This is because the distance from node i to node j - 1 and then node i + 1 to node j is actually shorter, and yet it still maintains the constraint of reaching each node. Swap the nodes out to optimize the distance. if ((distance1 + distance2) > (distance3 + distance4)) { reverse(best.begin() + i + 1, best.begin() + j); changed = true; } } } } while (changed); //twoHalfOpt(); calculatePathDistance(); } // We've applied Two-Opt to our best path, now let's subject our path to a third optimizing algorithm. This time, we broaden our horizons from Two-Opt by not simply considering two sets of adjacent edges, but instead three edges where two are adjacent to each other and 1 is not. void twoHalfOpt() { bool changed; do { changed = false; for (int i = 0; i < best.size() - 4; i++) { for (int j = i + 3; j < best.size() - 4; j++) { int option1current = (data.computeDistance(best.at(i) - 1, best.at(i+1) - 1)) + (data.computeDistance(best.at(i+1)-1, best.at(i+2)-1)) + (data.computeDistance(best.at(j-1)-1, best.at(j)-1)); int option1Check = (data.computeDistance(best.at(i)-1, best.at(i+2)-1)) + (data.computeDistance(best.at(j-1) -1, best.at(i+1)-1)) + (data.computeDistance(best.at(i+1) -1, best.at(j)-1)); if (option1Check < option1current) { int temp = best.at(i+1); for (int m = i + 2; m < j; m++) best.at(m-1) = best.at(m); best.at(j-1) = temp; changed = true; } int option2current = (data.computeDistance(best.at(i)-1, best.at(i+1)-1)) + (data.computeDistance(best.at(j-2)-1, best.at(j-1)-1)) + (data.computeDistance(best.at(j-1)-1, best.at(j)-1)); int option2Check = (data.computeDistance(best.at(i)-1, best.at(j-1)-1)) + (data.computeDistance(best.at(j-1)-1, best.at(i+1)-1)) + (data.computeDistance(best.at(j-2)-1, best.at(j)-1)); if (option2Check < option2current) { int temp = best.at(j-1); for (int m = j -2; m > i; m--) best.at(m+1) = best.at(m); best.at(i+1) = temp; changed = true; } } } } while (changed); calculatePathDistance(); } void calculatePathDistance() { int result = 0; for (int i = 0; i < best.size() - 1; i++) result += data.computeDistance(best.at(i)-1, best.at(i + 1)-1); result += data.computeDistance(best.at(best.size() -1)-1, best.at(0)-1); minTour = result; outputToFile(); } void outputToFile() { outputFile.open(outputFileName.c_str()); outputFile << minTour << "\n"; for (int i = 0; i < best.size(); i++) outputFile << best.at(i)-1 << "\n"; outputFile.close(); } double eval(possibleSolution C) { return data.evaluate(C); } }; int main(int argc, char* argv[]) { ofstream testOutput; clock_t t; t = clock(); srand(time(NULL)); inputFile.open(argv[1]); string firstPart(argv[1]); outputFileName = firstPart + ".tour"; TravelingFrankenstein Shelley; Shelley.SimulatedAnnealing(); testOutputName = firstPart + ".time"; testOutput.open(testOutputName.c_str()); t = clock() - t; float convtime = ((float)t)/(CLOCKS_PER_SEC); testOutput << convtime; testOutput.close(); return 0; }
[ "hoffera@oregonstate.edu" ]
hoffera@oregonstate.edu
41e8bde25dfcad24fd09c57017ef1483318715d1
89c7bead0bfb7b3b4d3d53450cc69bc4db47b7c2
/Engine/Code/Engine/Core/Tools/Clock.hpp
1067e63562e2f24e4db07d54de446954d171c05e
[]
no_license
itsdrell/SoftwareDevelopment
73fb218ae002a4dc3cd9bbed8f50ccc1a2d8a2f4
546b0d59e21f25a9b951ca0adc38783c1305f7ab
refs/heads/master
2020-03-19T00:43:23.348211
2019-05-08T17:21:37
2019-05-08T17:21:37
135,498,540
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
hpp
#pragma once #include "Engine/Core/General/EngineCommon.hpp" //------------------------------------------------------------------------ //------------------------------------------------------------------------ struct time_unit_t { time_unit_t() { memset(this,0,sizeof(time_unit_t)); //gag } uint64_t hpc; double hpcSeconds; // high precision seconds uint ms; float seconds; // convenience float seconds }; //------------------------------------------------------------------------ //------------------------------------------------------------------------ class Clock { public: Clock( Clock *parent = nullptr ); ~Clock(); // make sure to cleanup the heirachy // resets the clock - everything should be zeros out // and the reference hpc variables set // to the current hpc. void Reset(); // used on a root clock // calculates elapsed time since last call // and calls advance. void BeginFrame(); // advance the clock by the given hpc void Advance( uint64_t elapsed ); // adds a clock as a child to this clock void AddChild( Clock *child ); // returns time since this clock // using the current hpc, and our start hpc // to get the most up-to-date time. double GetCurrentTime() const; uint GetTotalFrameCount() { return m_frameCount; } // manipulation void SetPaused( bool paused ); void TogglePaused() {m_paused = !m_paused;} void SetScale( float scale ); void IncreaseScale(float scaleToAdd = .5f); void DescreaseScale(float scaleToSubtract = .5f); void StepForwardAFrame(float deltaToMove = .03f); // add whatever other convenience methods you may want; // ... public: // I don't use "m_" here as // the intended usage is to be able to go // clock->total.seconds -or- clock->frame.seconds; // these are only updated at begin_frame. time_unit_t frame; time_unit_t total; // for game clock so i can just say g_theGameClock.deltaTime like unity float deltaTime; float totalTime; bool m_debugMode; private: // local data we need to track for the clock to work; uint64_t m_startHpc; // hpc when the clock was last reset (made) uint64_t m_lastFrameHpc; // hpc during last begin_frame call double m_timeScale; uint m_frameCount; // if you're interested in number of frames your game has processes bool m_paused; // For the hierarchy Clock *m_parent; std::vector<Clock*> m_children; }; //------------------------------------------------------------------------ // C Funtions //------------------------------------------------------------------------ // could calso be static Clock* Clock::GetMaster(); Clock* GetMasterClock(); // convenience - calls begin frame on the master clock void ClockSystemBeginFrame(); // I now move this here - as this now refers to the master clock // who is keeping track of the starting reference point. double GetTheCurrentTime(); // I usually also add convenience functions so I'm not constantly fetching the master clock, like float GetDeltaTime(); //float GetFrameStartTime(); float GetFPS(); uint GetTimeInMilliseconds(); // Declaring all main clocks here extern Clock* g_theMasterClock; extern Clock* g_theGameClock;
[ "ztbracken@gmail.com" ]
ztbracken@gmail.com
8c216d0727678ba0d697f879fc673f63852e409e
2c148e207664a55a5809a3436cbbd23b447bf7fb
/src/content/public/renderer/content_renderer_client.h
e62a17b09f8e4283b7a28f8fcdef2b7db9ea3341
[ "BSD-3-Clause" ]
permissive
nuzumglobal/Elastos.Trinity.Alpha.Android
2bae061d281ba764d544990f2e1b2419b8e1e6b2
4c6dad6b1f24d43cadb162fb1dbec4798a8c05f3
refs/heads/master
2020-05-21T17:30:46.563321
2018-09-03T05:16:16
2018-09-03T05:16:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,318
h
// 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. #ifndef CONTENT_PUBLIC_RENDERER_CONTENT_RENDERER_CLIENT_H_ #define CONTENT_PUBLIC_RENDERER_CONTENT_RENDERER_CLIENT_H_ #include <stddef.h> #include <map> #include <memory> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "base/task_scheduler/task_scheduler.h" #include "build/build_config.h" #include "content/public/common/content_client.h" #include "content/public/renderer/url_loader_throttle_provider.h" #include "content/public/renderer/websocket_handshake_throttle_provider.h" #include "media/base/decode_capabilities.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h" #include "third_party/blink/public/platform/web_content_settings_client.h" #include "third_party/blink/public/web/web_navigation_policy.h" #include "third_party/blink/public/web/web_navigation_type.h" #include "ui/base/page_transition_types.h" #include "v8/include/v8.h" class GURL; class SkBitmap; namespace base { class FilePath; class SingleThreadTaskRunner; } namespace blink { class WebAudioDevice; class WebAudioLatencyHint; class WebClipboard; class WebFrame; class WebLocalFrame; class WebMIDIAccessor; class WebMIDIAccessorClient; class WebPlugin; class WebPrescientNetworking; class WebSpeechSynthesizer; class WebSpeechSynthesizerClient; class WebThemeEngine; class WebURL; class WebURLRequest; class WebURLResponse; struct WebPluginParams; struct WebURLError; } // namespace blink namespace media { class KeySystemProperties; } namespace content { class BrowserPluginDelegate; class MediaStreamRendererFactory; class RenderFrame; class RenderView; struct WebPluginInfo; // Embedder API for participating in renderer logic. class CONTENT_EXPORT ContentRendererClient { public: virtual ~ContentRendererClient() {} // Notifies us that the RenderThread has been created. virtual void RenderThreadStarted() {} // Notifies that a new RenderFrame has been created. virtual void RenderFrameCreated(RenderFrame* render_frame) {} // Notifies that a new RenderView has been created. virtual void RenderViewCreated(RenderView* render_view) {} // Returns the bitmap to show when a plugin crashed, or NULL for none. virtual SkBitmap* GetSadPluginBitmap(); // Returns the bitmap to show when a <webview> guest has crashed, or NULL for // none. virtual SkBitmap* GetSadWebViewBitmap(); // Allows the embedder to override creating a plugin. If it returns true, then // |plugin| will contain the created plugin, although it could be NULL. If it // returns false, the content layer will create the plugin. virtual bool OverrideCreatePlugin( RenderFrame* render_frame, const blink::WebPluginParams& params, blink::WebPlugin** plugin); // Creates a replacement plugin that is shown when the plugin at |file_path| // couldn't be loaded. This allows the embedder to show a custom placeholder. // This may return nullptr. However, if it does return a WebPlugin, it must // never fail to initialize. virtual blink::WebPlugin* CreatePluginReplacement( RenderFrame* render_frame, const base::FilePath& plugin_path); // Creates a delegate for browser plugin. virtual BrowserPluginDelegate* CreateBrowserPluginDelegate( RenderFrame* render_frame, const WebPluginInfo& info, const std::string& mime_type, const GURL& original_url); // Returns true if the embedder has an error page to show for the given http // status code. virtual bool HasErrorPage(int http_status_code); // Returns true if the embedder prefers not to show an error page for a failed // navigation to |url| in |render_frame|. virtual bool ShouldSuppressErrorPage(RenderFrame* render_frame, const GURL& url); // Returns false for new tab page activities, which should be filtered out in // UseCounter; returns true otherwise. virtual bool ShouldTrackUseCounter(const GURL& url); // Returns the information to display when a navigation error occurs. // If |error_html| is not null then it may be set to a HTML page // containing the details of the error and maybe links to more info. // If |error_description| is not null it may be set to contain a brief // message describing the error that has occurred. // Either of the out parameters may be not written to in certain cases // (lack of information on the error code) so the caller should take care to // initialize the string values with safe defaults before the call. virtual void PrepareErrorPage(content::RenderFrame* render_frame, const blink::WebURLRequest& failed_request, const blink::WebURLError& error, std::string* error_html, base::string16* error_description) {} virtual void PrepareErrorPageForHttpStatusError( content::RenderFrame* render_frame, const blink::WebURLRequest& failed_request, const GURL& unreachable_url, int http_status, std::string* error_html, base::string16* error_description) {} // Returns as |error_description| a brief description of the error that // ocurred. The out parameter may be not written to in certain cases (lack of // information on the error code) virtual void GetErrorDescription(const blink::WebURLRequest& failed_request, const blink::WebURLError& error, base::string16* error_description) {} // Allows the embedder to control when media resources are loaded. Embedders // can run |closure| immediately if they don't wish to defer media resource // loading. If |has_played_media_before| is true, the render frame has // previously started media playback (i.e. played audio and video). virtual void DeferMediaLoad(RenderFrame* render_frame, bool has_played_media_before, const base::Closure& closure); // Allows the embedder to override creating a WebMIDIAccessor. If it // returns NULL the content layer will create the MIDI accessor. virtual std::unique_ptr<blink::WebMIDIAccessor> OverrideCreateMIDIAccessor( blink::WebMIDIAccessorClient* client); // Allows the embedder to override creating a WebAudioDevice. If it // returns NULL the content layer will create the audio device. virtual std::unique_ptr<blink::WebAudioDevice> OverrideCreateAudioDevice( const blink::WebAudioLatencyHint& latency_hint); // Allows the embedder to override the blink::WebClipboard used. If it // returns NULL the content layer will handle clipboard interactions. virtual blink::WebClipboard* OverrideWebClipboard(); // Allows the embedder to override the WebThemeEngine used. If it returns NULL // the content layer will provide an engine. virtual blink::WebThemeEngine* OverrideThemeEngine(); // Allows the embedder to provide a WebSocketHandshakeThrottle. If it returns // NULL then none will be used. // TODO(nhiroki): Remove this once the off-main-thread WebSocket is enabled by // default (https://crbug.com/825740). virtual std::unique_ptr<blink::WebSocketHandshakeThrottle> CreateWebSocketHandshakeThrottle(); // Allows the embedder to provide a WebSocketHandshakeThrottleProvider. If it // returns NULL then none will be used. virtual std::unique_ptr<WebSocketHandshakeThrottleProvider> CreateWebSocketHandshakeThrottleProvider(); // Allows the embedder to override the WebSpeechSynthesizer used. // If it returns NULL the content layer will provide an engine. virtual std::unique_ptr<blink::WebSpeechSynthesizer> OverrideSpeechSynthesizer(blink::WebSpeechSynthesizerClient* client); // Called on the main-thread immediately after the io thread is // created. virtual void PostIOThreadCreated( base::SingleThreadTaskRunner* io_thread_task_runner); // Called on the main-thread immediately after the compositor thread is // created. virtual void PostCompositorThreadCreated( base::SingleThreadTaskRunner* compositor_thread_task_runner); // Returns true if the renderer process should schedule the idle handler when // all widgets are hidden. virtual bool RunIdleHandlerWhenWidgetsHidden(); // Returns true if the renderer process should allow task suspension // after the process has been backgrounded. Defaults to false. virtual bool AllowFreezingWhenProcessBackgrounded(); // Returns true if a popup window should be allowed. virtual bool AllowPopup(); #if defined(OS_ANDROID) // TODO(sgurun) This callback is deprecated and will be removed as soon // as android webview completes implementation of a resource throttle based // shouldoverrideurl implementation. See crbug.com/325351 // // Returns true if the navigation was handled by the embedder and should be // ignored by WebKit. This method is used by CEF and android_webview. virtual bool HandleNavigation(RenderFrame* render_frame, bool is_content_initiated, bool render_view_was_created_by_renderer, blink::WebFrame* frame, const blink::WebURLRequest& request, blink::WebNavigationType type, blink::WebNavigationPolicy default_policy, bool is_redirect); // Indicates if the Android MediaPlayer should be used instead of Chrome's // built in media player for the given |url|. Defaults to false. virtual bool ShouldUseMediaPlayerForURL(const GURL& url); #endif // Returns true if we should fork a new process for the given navigation. // If |send_referrer| is set to false (which is the default), no referrer // header will be send for the navigation. Otherwise, the referrer header is // set according to the frame's referrer policy. virtual bool ShouldFork(blink::WebLocalFrame* frame, const GURL& url, const std::string& http_method, bool is_initial_navigation, bool is_server_redirect, bool* send_referrer); // Notifies the embedder that the given frame is requesting the resource at // |url|. If the function returns a valid |new_url|, the request must be // updated to use it. The |attach_same_site_cookies| output parameter // determines whether SameSite cookies should be attached to the request. // TODO(nasko): When moved over to Network Service, find a way to perform // this check on the browser side, so untrusted renderer processes cannot // influence whether SameSite cookies are attached. virtual void WillSendRequest(blink::WebLocalFrame* frame, ui::PageTransition transition_type, const blink::WebURL& url, const url::Origin* initiator_origin, GURL* new_url, bool* attach_same_site_cookies); // Returns true if the request is associated with a document that is in // ""prefetch only" mode, and will not be rendered. virtual bool IsPrefetchOnly(RenderFrame* render_frame, const blink::WebURLRequest& request); // See blink::Platform. virtual unsigned long long VisitedLinkHash(const char* canonical_url, size_t length); virtual bool IsLinkVisited(unsigned long long link_hash); virtual blink::WebPrescientNetworking* GetPrescientNetworking(); virtual bool ShouldOverridePageVisibilityState( const RenderFrame* render_frame, blink::mojom::PageVisibilityState* override_state); // Returns true if the given Pepper plugin is external (requiring special // startup steps). virtual bool IsExternalPepperPlugin(const std::string& module_name); // Returns true if the given Pepper plugin should process content from // different origins in different PPAPI processes. This is generally a // worthwhile precaution when the plugin provides an active scripting // language. virtual bool IsOriginIsolatedPepperPlugin(const base::FilePath& plugin_path); // Returns true if the page at |url| can use Pepper MediaStream APIs. virtual bool AllowPepperMediaStreamAPI(const GURL& url); // Allows an embedder to provide a MediaStreamRendererFactory. virtual std::unique_ptr<MediaStreamRendererFactory> CreateMediaStreamRendererFactory(); // Allows embedder to register the key system(s) it supports by populating // |key_systems|. virtual void AddSupportedKeySystems( std::vector<std::unique_ptr<media::KeySystemProperties>>* key_systems); // Signal that embedder has changed key systems. // TODO(chcunningham): Refactor this to a proper change "observer" API that is // less fragile (don't assume AddSupportedKeySystems has just one caller). virtual bool IsKeySystemsUpdateNeeded(); // Allows embedder to describe customized audio capabilities. virtual bool IsSupportedAudioConfig(const media::AudioConfig& config); // Allows embedder to describe customized video capabilities. virtual bool IsSupportedVideoConfig(const media::VideoConfig& config); // Return true if the bitstream format |codec| is supported by the audio sink. virtual bool IsSupportedBitstreamAudioCodec(media::AudioCodec codec); // Returns true if we should report a detailed message (including a stack // trace) for console [logs|errors|exceptions]. |source| is the WebKit- // reported source for the error; this can point to a page or a script, // and can be external or internal. virtual bool ShouldReportDetailedMessageForSource( const base::string16& source) const; // Creates a permission client for in-renderer worker. virtual std::unique_ptr<blink::WebContentSettingsClient> CreateWorkerContentSettingsClient(RenderFrame* render_frame); // Returns true if the page at |url| can use Pepper CameraDevice APIs. virtual bool IsPluginAllowedToUseCameraDeviceAPI(const GURL& url); // Returns true if the page at |url| can use Pepper Compositor APIs. virtual bool IsPluginAllowedToUseCompositorAPI(const GURL& url); // Returns true if dev channel APIs are available for plugins. virtual bool IsPluginAllowedToUseDevChannelAPIs(); // Records a sample string to a Rappor privacy-preserving metric. // See: https://www.chromium.org/developers/design-documents/rappor virtual void RecordRappor(const std::string& metric, const std::string& sample) {} // Records a domain and registry of a url to a Rappor privacy-preserving // metric. See: https://www.chromium.org/developers/design-documents/rappor virtual void RecordRapporURL(const std::string& metric, const GURL& url) {} // Gives the embedder a chance to add properties to the context menu. // Currently only called when the context menu is for an image. virtual void AddImageContextMenuProperties( const blink::WebURLResponse& response, bool is_image_in_context_a_placeholder_image, std::map<std::string, std::string>* properties) {} // Notifies that a document element has been inserted in the frame's document. // This may be called multiple times for the same document. This method may // invalidate the frame. virtual void RunScriptsAtDocumentStart(RenderFrame* render_frame) {} // Notifies that the DOM is ready in the frame's document. // This method may invalidate the frame. virtual void RunScriptsAtDocumentEnd(RenderFrame* render_frame) {} // Notifies that the window.onload event is about to fire. // This method may invalidate the frame. virtual void RunScriptsAtDocumentIdle(RenderFrame* render_frame) {} // Allows subclasses to enable some runtime features before Blink has // started. virtual void SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() {} // Notifies that a service worker context has been created. This function // is called from the worker thread. virtual void DidInitializeServiceWorkerContextOnWorkerThread( v8::Local<v8::Context> context, int64_t service_worker_version_id, const GURL& service_worker_scope, const GURL& script_url) {} // Notifies that a service worker context will be destroyed. This function // is called from the worker thread. virtual void WillDestroyServiceWorkerContextOnWorkerThread( v8::Local<v8::Context> context, int64_t service_worker_version_id, const GURL& service_worker_scope, const GURL& script_url) {} // Whether this renderer should enforce preferences related to the WebRTC // routing logic, i.e. allowing multiple routes and non-proxied UDP. virtual bool ShouldEnforceWebRTCRoutingPreferences(); // Notifies that a worker context has been created. This function is called // from the worker thread. virtual void DidInitializeWorkerContextOnWorkerThread( v8::Local<v8::Context> context) {} // Overwrites the given URL to use an HTML5 embed if possible. // An empty URL is returned if the URL is not overriden. virtual GURL OverrideFlashEmbedWithHTML(const GURL& url); // Provides parameters for initializing the global task scheduler. Default // params are used if this returns nullptr. virtual std::unique_ptr<base::TaskScheduler::InitParams> GetTaskSchedulerInitParams(); // Whether the renderer allows idle media players to be automatically // suspended after a period of inactivity. virtual bool AllowIdleMediaSuspend(); // Called when a resource at |url| is loaded using an otherwise-valid legacy // Symantec certificate that will be distrusted in future. Allows the embedder // to override the message that is added to the console to inform developers // that their certificate will be distrusted in future. If the method returns // true, then |*console_message| will be printed to the console; otherwise a // generic mesage will be used. virtual bool OverrideLegacySymantecCertConsoleMessage( const GURL& url, std::string* console_messsage); // Asks the embedder to bind |service_request| to its renderer-side service // implementation. virtual void CreateRendererService( service_manager::mojom::ServiceRequest service_request) {} virtual std::unique_ptr<URLLoaderThrottleProvider> CreateURLLoaderThrottleProvider(URLLoaderThrottleProviderType provider_type); // Called when Blink cannot find a frame with the given name in the frame's // browsing instance. This gives the embedder a chance to return a frame // from outside of the browsing instance. virtual blink::WebFrame* FindFrame(blink::WebLocalFrame* relative_to_frame, const std::string& name); }; } // namespace content #endif // CONTENT_PUBLIC_RENDERER_CONTENT_RENDERER_CLIENT_H_
[ "jiawang.yu@spreadtrum.com" ]
jiawang.yu@spreadtrum.com
3e0dfcd4f560e26ada04e8541df46627072bd347
c7becf103bb17122e1e9546e73f2b3d1a58eb5fa
/leitura_digital/leitura_digital.ino
78d9a0d25a1067d4f79e8e9704986945f51ab6ce
[]
no_license
alexandretok/digital-systems-class
83e8fb321f85f779c9951ea0360da6cc2094ab30
54b9d71f87172fddb626358b1b8b9b87b8b2441c
refs/heads/master
2021-03-27T10:08:05.477859
2017-03-29T20:01:16
2017-03-29T20:01:16
85,029,341
0
0
null
null
null
null
UTF-8
C++
false
false
211
ino
// Ler a entrada digital D2 e ligar um led em D3 // Ler a porta analogica 0 e int main(void){ DDRD = 1<<3; // Configura D2 como entrada e D3 como saida while(1){ PORTD = (PIND & 1<<2) << 1; } }
[ "alexandretok@gmail.com" ]
alexandretok@gmail.com
e9852dcabd0812acf13365a3d12bffa3a0ec6176
86daf7f3f7dcf7e698c1b128a93126c45a5d47e1
/src/core/sTimer.cpp
ba34427da20214a2868548b6314d85e9c5ca6517
[]
no_license
BentleyBlanks/smallptCuda
e67db6e8b0d2bf233ed91650f08a662e4659aadd
98caadd16b3be8a6dabe5aa19e863c973a59c43d
refs/heads/master
2020-03-11T08:46:56.085407
2018-04-22T14:22:05
2018-04-22T14:22:05
129,892,480
9
7
null
null
null
null
UTF-8
C++
false
false
3,822
cpp
#include <core/sTimer.h> //#include <Common/t3Test.h> // --!参考于http://nadeausoftware.com/articles/2012/04/c_c_tip_how_measure_elapsed_real_time_benchmarking #if defined(_WIN32) #include <Windows.h> #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) #include <unistd.h> /* POSIX flags */ #include <time.h> /* clock_gettime(), time() */ #include <sys/time.h> /* gethrtime(), gettimeofday() */ #if defined(__MACH__) && defined(__APPLE__) #include <mach/mach.h> #include <mach/mach_time.h> #endif #else #error "Unable to define getRealTime( ) for an unknown OS." #endif /** * Returns the real time, in seconds, or -1.0 if an error occurred. * * Time is measured since an arbitrary and OS-dependent start time. * The returned real time is only useful for computing an elapsed time * between two calls to this function. */ double t3GetRealTime( ) { #if defined(_WIN32) FILETIME tm; ULONGLONG t; #if defined(NTDDI_WIN8) && NTDDI_VERSION >= NTDDI_WIN8 /* Windows 8, Windows Server 2012 and later. ---------------- */ GetSystemTimeAsFileTime(&tm); //GetSystemTimePreciseAsFileTime( &tm ); #else /* Windows 2000 and later. ---------------------------------- */ GetSystemTimeAsFileTime( &tm ); #endif t = ((ULONGLONG)tm.dwHighDateTime << 32) | (ULONGLONG)tm.dwLowDateTime; return (double)t / 10000000.0; #elif (defined(__hpux) || defined(hpux)) || ((defined(__sun__) || defined(__sun) || defined(sun)) && (defined(__SVR4) || defined(__svr4__))) /* HP-UX, Solaris. ------------------------------------------ */ return (double)gethrtime( ) / 1000000000.0; #elif defined(__MACH__) && defined(__APPLE__) /* OSX. ----------------------------------------------------- */ static double timeConvert = 0.0; if ( timeConvert == 0.0 ) { mach_timebase_info_data_t timeBase; (void)mach_timebase_info( &timeBase ); timeConvert = (double)timeBase.numer / (double)timeBase.denom / 1000000000.0; } return (double)mach_absolute_time( ) * timeConvert; #elif defined(_POSIX_VERSION) /* POSIX. --------------------------------------------------- */ #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) { struct timespec ts; #if defined(CLOCK_MONOTONIC_PRECISE) /* BSD. --------------------------------------------- */ const clockid_t id = CLOCK_MONOTONIC_PRECISE; #elif defined(CLOCK_MONOTONIC_RAW) /* Linux. ------------------------------------------- */ const clockid_t id = CLOCK_MONOTONIC_RAW; #elif defined(CLOCK_HIGHRES) /* Solaris. ----------------------------------------- */ const clockid_t id = CLOCK_HIGHRES; #elif defined(CLOCK_MONOTONIC) /* AIX, BSD, Linux, POSIX, Solaris. ----------------- */ const clockid_t id = CLOCK_MONOTONIC; #elif defined(CLOCK_REALTIME) /* AIX, BSD, HP-UX, Linux, POSIX. ------------------- */ const clockid_t id = CLOCK_REALTIME; #else const clockid_t id = (clockid_t)-1; /* Unknown. */ #endif /* CLOCK_* */ if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 ) return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0; /* Fall thru. */ } #endif /* _POSIX_TIMERS */ /* AIX, BSD, Cygwin, HP-UX, Linux, OSX, POSIX, Solaris. ----- */ struct timeval tm; gettimeofday( &tm, NULL ); return (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0; #else return -1.0; /* Failed. */ #endif } // 开始计时 double sTimer::start() { startTime = t3GetRealTime(); return startTime; } // 结束计时 double sTimer::end() { endTime = t3GetRealTime(); return endTime; } double sTimer::difference() { return endTime - startTime; }
[ "bentleyjobs@gmail.com" ]
bentleyjobs@gmail.com
0234f8f2052774373b666715516d08a7083fd65d
3258b5d8867e625dcd8e5e83bcad8c2c4e0db151
/Dynamic Programming/max_length_substring.cpp
e4ffccfd931c84e4f56b1355ac61d27a41b4d718
[]
no_license
pranshu2610/Algorithms-2
b8333d18f8ed97ff22e88c83f5bffcc9b813b121
459fb3fde84c4bd57d1247ad4e3bdc72be6ae055
refs/heads/master
2020-07-27T08:36:50.304574
2020-05-30T08:05:07
2020-05-30T08:05:07
209,032,317
0
1
null
2019-09-17T11:10:05
2019-09-17T11:10:04
null
UTF-8
C++
false
false
999
cpp
//Length of the longest substring without repeating characters #include<bits/stdc++.h> using namespace std; int longestUniqueSubsttr(string str) { int start = 0; int end = 0; int n = str.size(); int visited[27]; for(int i = 1 ; i <= n; i++) { visited[i] = -1; } int max_length = 0; int cur_length = 0; for(int i = 0; i < n; i++) { if(visited[(int)(str[i] - 'A' + 1)] != -1) { max_length = max(max_length, cur_length); start = visited[(int)(str[i] - 'A' + 1)] + 1; cur_length = end - start + 1; for(int i = 0; i < start; i++) visited[(int)(str[i] - 'A' + 1)] = -1; } else { visited[(int)(str[i] - 'A' + 1)] = i; cur_length++; end++; } } return (max_length); } int main() { freopen("in.in", "r", stdin); freopen("out.out", "w", stdout); char str[] = "GEEKSFORGEEKS"; cout<<"The length of the longest non-repeating " "character substring is "<< longestUniqueSubsttr(str); return 0; }
[ "sonakshisaxena1@gmail.com" ]
sonakshisaxena1@gmail.com
cbf5cee26255dff80dcd65ac01bcfaceb937e61a
615f66a65bb857c6a963d78dbe163c07413c9a1f
/src/test/cpp/src/ExpectedInPlaceGenMatRowIndsGenDouble.cpp
25f8e9babadd1731503c4b8fecc0f6878e5fc8c0
[ "MIT" ]
permissive
flamecloud/ArmadilloJava
3c6d6fd38e834d7548ac2c2318e53202acd1312a
061121e22708111a8df3a2da92f6278c3a581e26
refs/heads/master
2021-01-21T09:23:27.915003
2015-01-06T14:30:51
2015-01-06T14:30:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,361
cpp
/******************************************************************************* * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * Developers: * Sebastian Niemann - Lead developer * Daniel Kiechle - Unit testing ******************************************************************************/ #include <Expected.hpp> using armadilloJava::Expected; #include <iostream> using std::cout; using std::endl; #include <utility> using std::pair; #include <armadillo> using arma::Mat; using arma::Col; using arma::uword; #include <InputClass.hpp> using armadilloJava::InputClass; #include <Input.hpp> using armadilloJava::Input; namespace armadilloJava { class ExpectedInPlaceGenMatRowIndsGenDouble : public Expected { public: ExpectedInPlaceGenMatRowIndsGenDouble() { cout << "Compute ExpectedInPlaceGenMatRowIndsGenDouble(): " << endl; vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({ InputClass::GenMat, InputClass::RowInds, InputClass::GenDouble }); for (vector<pair<string, void*>> input : inputs) { _fileSuffix = ""; int n = 0; for (pair<string, void*> value : input) { switch (n) { case 0: _fileSuffix += value.first; _genMat = *static_cast<Mat<double>*>(value.second); break; case 1: _fileSuffix += "," + value.first; _rowInds = *static_cast<Col<uword>*>(value.second); break; case 2: _fileSuffix += "," + value.first; _genDouble = *static_cast<double*>(value.second); break; } ++n; } cout << "Using input: " << _fileSuffix << endl; _copyOfGenMat = _genMat; _copyOfRowInds = _rowInds; _copyOfGenDouble = _genDouble; expectedRowsPlus(); _genMat = _copyOfGenMat; _rowInds = _copyOfRowInds; _genDouble = _copyOfGenDouble; expectedRowsMinus(); _genMat = _copyOfGenMat; _rowInds = _copyOfRowInds; _genDouble = _copyOfGenDouble; expectedRowsTimes(); _genMat = _copyOfGenMat; _rowInds = _copyOfRowInds; _genDouble = _copyOfGenDouble; expectedRowsDivide(); } cout << "done." << endl; } protected: Mat<double> _genMat; Mat<double> _copyOfGenMat; Col<uword> _rowInds; Col<uword> _copyOfRowInds; double _genDouble; double _copyOfGenDouble; void expectedRowsPlus() { for(int i = 0; i < _rowInds.n_elem; i++) { if(_rowInds.at(i) >= _genMat.n_rows) { return; } } cout << "- Compute expectedRowsPlus() ... "; _genMat.rows(_rowInds) += _genDouble; save<double>("Mat.rowsPlus", _genMat); cout << "done." << endl; } void expectedRowsMinus() { for(int i = 0; i < _rowInds.n_elem; i++) { if(_rowInds.at(i) >= _genMat.n_rows) { return; } } cout << "- Compute expectedRowsMinus() ... "; _genMat.rows(_rowInds) -= _genDouble; save<double>("Mat.rowsMinus", _genMat); cout << "done." << endl; } void expectedRowsTimes() { for(int i = 0; i < _rowInds.n_elem; i++) { if(_rowInds.at(i) >= _genMat.n_rows) { return; } } cout << "- Compute expectedRowsTimes() ... "; _genMat.rows(_rowInds) *= _genDouble; save<double>("Mat.rowsTimes", _genMat); cout << "done." << endl; } void expectedRowsDivide() { for(int i = 0; i < _rowInds.n_elem; i++) { if(_rowInds.at(i) >= _genMat.n_rows) { return; } } cout << "- Compute expectedRowsDivide() ... "; _genMat.rows(_rowInds) /= _genDouble; save<double>("Mat.rowsDivide", _genMat); cout << "done." << endl; } }; }
[ "niemann@sra.uni-hannover.de" ]
niemann@sra.uni-hannover.de
d2d14dcbf818b0c511e022f965cd059cd5514536
7ea5365a0424c50be888cfba52c54fab1779b879
/Old/대건/iseq_27.cpp
0eee309852e4b281adebb8a7139c3cf973500148
[]
no_license
judemin/AlgorithmSolutions
a3e26fb7685f7357fad7fe05743f975fe2fde406
cef19d14ab7bf9ca70aa73f87d49834f2ee24f31
refs/heads/master
2023-06-29T05:22:00.109993
2021-08-04T07:07:25
2021-08-04T07:07:25
259,854,361
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
#include<iostream> using namespace std; int main(void){ freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int a,b,i,tmp; cin >> a >> b; for(i = a;i <= b;i++){ tmp = i%10; if(tmp == 3 || tmp == 6 || tmp == 9) cout << i << endl; } return 0; }
[ "judemin2087@naver.com" ]
judemin2087@naver.com
6b5426d141ce5f5789237293ca3912858298e9e3
b4e238cb8ae9ee439f3bf2052de24ddcde4276b5
/2019级/[标程]Div2 基本输入输出练习/A+B cin cout/C.cpp
fa46f58fc644ac22d4bb4c11c1d7539019faa43c
[]
no_license
nbutacm/NBUTACM
b91206a9d91dfce8fd6ab13e197db4a61b0d5637
5a764d89c5052e1a86dfb7f67516a42950482b58
refs/heads/master
2022-01-27T00:01:41.790721
2022-01-17T08:25:12
2022-01-17T08:25:12
174,715,583
20
5
null
null
null
null
UTF-8
C++
false
false
158
cpp
#include<iostream> using namespace std; int main(){ int a,b; while(cin >> a >> b ){ if(a == 0 && b == 0 ) break; cout << a+b << endl; } return 0; }
[ "52810302+cornyum@users.noreply.github.com" ]
52810302+cornyum@users.noreply.github.com
be9c1191b47271dea3fe2d88f8b7d553f6b62ce1
12c82ceba45d5508cff2e4f152563435873f2b8b
/best_time_to_buy_sell_stock_iv.cpp
9837f9dc8549426f1da2a719abb78ed4e451fac1
[]
no_license
Web-Dev-Collaborative/leetcode-solutions
45d50ff92f4c96cf59d5407a8a2bed7405383430
b46d09c665d4a89322a32916ebc76c15565616bf
refs/heads/master
2023-04-03T17:22:53.180100
2021-03-29T21:15:55
2021-03-29T21:15:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
class Solution { public: int greedy(vector<int>& prices) { int profit = 0; for (int i = 1; i < prices.size(); i++) { profit += (prices[i] > prices[i - 1]) ? (prices[i] - prices[i - 1]) : 0; } return profit; } int maxProfit(int k, vector<int>& prices) { int n = prices.size(); if(n < 2 || k < 1) return 0; if(k > n/2){ return greedy(prices); } vector<int> buy(k, INT_MIN); vector<int> sell(k, 0); for(auto p : prices){ buy[0] = max(buy[0], -p); sell[0] = max(sell[0], buy[0] + p); for(int j=1; j<k; j++){ buy[j] = max(buy[j], (sell[j-1] - p)); sell[j] = max(sell[j], (buy[j] + p)); } } return sell.back(); } };
[ "chiragshah9696@gmail.com" ]
chiragshah9696@gmail.com
c2077f770c29154e18844078f39480596dec1c51
15fbd3e6ae793d8a339e3786c5914c8ae34c1744
/player.cpp
4b2247b5dd0ee17562154fce33fed895f37a9ad1
[]
no_license
Haskis/ProjektPJC
bf79dcfd035d08e2356da587c9590b910da30a52
9210b690ecd627579826b23b9ef3886ac905e802
refs/heads/master
2021-01-19T14:10:21.429499
2014-06-13T06:22:14
2014-06-13T06:22:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
908
cpp
#include "player.h" Player::Player(AbstractCar * car, std::string name) { this->car = car; this->name = name; keyUp = 0; keyDown = 0; keyRight = 0; keyLeft = 0; } Player::~Player(){ delete car; } std::string Player::getName(){ return name; } void Player::defineKeys(int keyUp, int keyDown, int keyRight, int keyLeft){ this->keyUp = keyUp; this->keyDown = keyDown; this->keyRight = keyRight; this->keyLeft = keyLeft; } void Player::keyChanged(int key, bool status){ if(key == 0) return; if(key == keyUp) { car->updateMovingDirection(NULL,AbstractCar::Forward,status); } else if (key == keyDown){ car->updateMovingDirection(NULL,AbstractCar::Backward,status); } else if (key == keyRight){ car->updateMovingDirection(NULL,AbstractCar::Right,status); } else if (key == keyLeft){ car->updateMovingDirection(NULL,AbstractCar::Left,status); } }
[ "haskis@haskis.(none)" ]
haskis@haskis.(none)
7b14ea94e9858d253342726c66391d5c39fb88fd
b2158c566326e0ff07e7573e4e4d7c635d829144
/job_stream/message.cpp
3a02dc91295c5171789aa7eab587235fd6b4c424
[ "MIT" ]
permissive
gregorgebhardt/job_stream
59cd4d7f8422d29bc56e878d8fb3a4933c91aee8
63db58cb754b51e4da08106c130fd54b1a397159
refs/heads/master
2021-05-02T16:02:38.811619
2018-08-16T18:14:45
2018-08-16T18:14:45
120,666,194
0
0
null
2018-02-07T20:13:49
2018-02-07T20:13:49
null
UTF-8
C++
false
false
2,487
cpp
#include "message.h" #include "pythonType.h" #include "serialization.h" #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <sys/time.h> namespace job_stream { namespace message { uint64_t Location::getCurrentTimeMs() { timeval ts; gettimeofday(&ts, 0); return (uint64_t)(ts.tv_sec * 1000 + ts.tv_usec / 1000); } WorkRecord::WorkRecord(const std::string& serialized) { serialization::decode(serialized, *this); //We were received, so... this->source.tsReceived = Location::getCurrentTimeMs(); } WorkRecord::WorkRecord(const std::vector<std::string>& target, const std::string& work) : reduceTag(0), reduceHomeRank(0), work(work) { this->source.hostname = boost::asio::ip::host_name(); this->source.target = target; this->source.tsSent = Location::getCurrentTimeMs(); } WorkRecord::WorkRecord(const std::vector<std::string>& target, void* work) : reduceTag(0), reduceHomeRank(0) { this->source.hostname = boost::asio::ip::host_name(); this->source.target = target; this->source.tsSent = Location::getCurrentTimeMs(); //work will be set in derived constructor } void WorkRecord::chainFrom(const WorkRecord& wr) { this->route.insert(this->route.end(), wr.route.begin(), wr.route.end()); this->route.push_back(wr.source); this->reduceHomeRank = wr.reduceHomeRank; this->reduceTag = wr.reduceTag; } template<typename T> std::string getAsString(const std::string& payload) { std::unique_ptr<T> decoded; serialization::decode(payload, decoded); return boost::lexical_cast<std::string>(*decoded); } std::string WorkRecord::getWorkAsString() const { #define TRY_TYPE(T) \ try { \ return getAsString<T>(this->work); \ } \ catch (const std::exception& e) { \ /* Do nothing, conversion failed */ \ } TRY_TYPE(std::string); TRY_TYPE(job_stream::python::SerializedPython); TRY_TYPE(uint64_t); TRY_TYPE(int64_t); TRY_TYPE(unsigned int); TRY_TYPE(int); TRY_TYPE(unsigned short); TRY_TYPE(short); TRY_TYPE(unsigned char); TRY_TYPE(char); TRY_TYPE(float); TRY_TYPE(double); //While we can't print this type of output, rather than raising an //exception, print out the type std::ostringstream ss; ss << "<object of type "; ss << serialization::getDecodedType(this->work); ss << ">"; return ss.str(); #undef TRY_TYPE } } //message } //job_stream
[ "woodswalben@gmail.com" ]
woodswalben@gmail.com
215163badb4b5b68f000bd1ccb991b81426a4fe2
19a012b6a66374235771a8c2baee19560e98f8d7
/UVa/v118/trains_fast_io.cpp
acce5a4a08066a0df3f02812e0c0f7e685581efe
[]
no_license
juancate/CompetitivePrograming
735e992fd6ac9c264059604fb7a2f2dfce74d330
8cea3695fd0dec7122c94ab45b4517cb13232fb3
refs/heads/master
2021-01-25T10:06:47.576470
2018-12-19T01:11:41
2018-12-19T01:11:41
14,966,965
0
0
null
null
null
null
UTF-8
C++
false
false
3,824
cpp
#include <iostream> #include <algorithm> #include <queue> #include <cstring> #include <cstdio> #include <cstdlib> #include <utility> #include <cmath> #include <unistd.h> class INPUT { static const int BUFSIZE = 1<<16; static char buffer[]; char *bufpos; char *bufend; void grabBuffer(); public: INPUT() { grabBuffer(); } bool eof() { return bufend==buffer; } char nextChar() { return *bufpos; } inline char readChar(); inline void skipWS(); inline unsigned readUnsigned(); inline int readInt(); inline double readDouble(); }; char INPUT::buffer[INPUT::BUFSIZE]; void INPUT::grabBuffer() { bufpos = buffer; bufend = buffer + read(0, buffer, BUFSIZE); } char INPUT::readChar() { char res = *bufpos++; if(bufpos==bufend) grabBuffer(); return res; } inline bool myisspace(char c) { return c<=' '; } void INPUT::skipWS() { while(!eof() && myisspace(nextChar())) readChar(); } unsigned INPUT::readUnsigned() { skipWS(); unsigned res = 0; while(!eof() && isdigit(nextChar())) { res = 10u * res + (readChar()-'0'); } return res; } int INPUT::readInt() { skipWS(); bool neg = false; if(!eof() && nextChar()=='-') { neg=true; readChar(); } int res = static_cast<int>(readUnsigned()); if(neg) res = -res; return res; } double INPUT::readDouble() { skipWS(); double res = 0.0; int sign = 1; if(nextChar() == '-') { sign = -1; readChar(); } while(!eof() && isdigit(nextChar())) { res *= 10; res += (readChar() - '0'); } if(nextChar() == '.') { readChar(); double m = 1; while(!eof() && isdigit(nextChar())) { m /= 10; res += (readChar() - '0') * m; } } return res * sign; } using namespace std; const int MAXN = 111; int n; int GA[MAXN][MAXN], GB[MAXN][MAXN]; double d[MAXN]; INPUT in; #define mp make_pair int dijkstra(int source, int sink, double a) { for(int i = 0; i < n; i++) d[i] = 1e50; d[source] = 0; priority_queue< pair<double, int>, vector< pair<double, int> >, greater< pair<double, int> > > Q; Q.push( mp(0.0, source) ); while(!Q.empty()) { int v = Q.top().second; double cost = Q.top().first; Q.pop(); if(cost > d[v]) continue; if(v == sink) return floor(cost); for(int u = 0; u < n; u++) { if(GA[v][u] == -1 && GB[v][u] == -1) continue; double diff; if(GA[v][u] != -1 && GB[v][u] != -1) { diff = a * GA[v][u] + (1. - a) * GB[v][u]; } else { diff = max(GA[u][v], GB[v][u]); } if(diff + cost < d[u]) { d[u] = diff + cost; Q.push(mp(diff + cost, u)); } } } return -1; } int main() { int ma, mb, k; while(true) { n = in.readInt(), ma = in.readInt(), mb = in.readInt(), k = in.readInt(); if(n == -1 && ma == -1 && mb == -1 && k == -1) break; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) GA[i][j] = GB[i][j] = -1; for(int i = 0; i < ma; i++) { int a, b, c; a = in.readInt(), b = in.readInt(), c = in.readInt(); GA[a][b] = GA[b][a] = c; } for(int i = 0; i < mb; i++) { int a, b, c; a = in.readInt(), b = in.readInt(), c = in.readInt(); GB[a][b] = GB[b][a] = c; } for(int i = 0; i < k; i++) { double a = in.readDouble(); printf("%d\n", dijkstra(0, n-1, a)); } } }
[ "jcamargo@gmail.com" ]
jcamargo@gmail.com
f0bba36e5aebea0568a77769fb31106e4dcc9e2e
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/third_party/blink/renderer/core/events/message_event_init.h
d893788677e2031f9b93037c2ab6c71aab1f7789
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
2,670
h
// 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. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef MessageEventInit_h #define MessageEventInit_h #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/events/event_init.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { class EventTarget; class MessagePort; class CORE_EXPORT MessageEventInit : public EventInit { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); public: MessageEventInit(); virtual ~MessageEventInit(); MessageEventInit(const MessageEventInit&); MessageEventInit& operator=(const MessageEventInit&); bool hasData() const { return !(data_.IsEmpty() || data_.IsUndefined()); } ScriptValue data() const { return data_; } void setData(ScriptValue); bool hasLastEventId() const { return !last_event_id_.IsNull(); } const String& lastEventId() const { return last_event_id_; } inline void setLastEventId(const String&); bool hasOrigin() const { return !origin_.IsNull(); } const String& origin() const { return origin_; } inline void setOrigin(const String&); bool hasPorts() const { return has_ports_; } const HeapVector<Member<MessagePort>>& ports() const { DCHECK(has_ports_); return ports_; } void setPorts(const HeapVector<Member<MessagePort>>&); bool hasSource() const { return source_; } EventTarget* source() const { return source_; } inline void setSource(EventTarget*); inline void setSourceToNull(); v8::Local<v8::Value> ToV8Impl(v8::Local<v8::Object>, v8::Isolate*) const override; void Trace(blink::Visitor*) override; private: bool has_ports_ = false; ScriptValue data_; String last_event_id_; String origin_; HeapVector<Member<MessagePort>> ports_; Member<EventTarget> source_; friend class V8MessageEventInit; }; void MessageEventInit::setLastEventId(const String& value) { last_event_id_ = value; } void MessageEventInit::setOrigin(const String& value) { origin_ = value; } void MessageEventInit::setSource(EventTarget* value) { source_ = value; } void MessageEventInit::setSourceToNull() { source_ = Member<EventTarget>(); } } // namespace blink #endif // MessageEventInit_h
[ "aoeiuv020@gmail.com" ]
aoeiuv020@gmail.com
aa9bebcf9b4eadc9143329429af5a57916ce4727
9af61d59bdbf0ba71f09941219bdd3bff968162a
/Lab6/Lab6/Log.h
7f50dbe85780067a609295c1174832ae350ccbd9
[ "Apache-2.0" ]
permissive
AshBringer47/KPI_OOP
ffdfe3c464a1f052ef1813bffcc8b0badeac253e
ea7676ebecafd2ae9f7b2bf38c0ab54c2b88e0ea
refs/heads/master
2023-08-21T05:59:34.129387
2021-10-30T13:55:04
2021-10-30T13:55:04
241,584,516
1
1
Apache-2.0
2021-10-30T13:55:05
2020-02-19T09:42:53
C#
UTF-8
C++
false
false
247
h
#pragma once #include <string> #include <fstream> #include <ctime> #include <chrono> using namespace std; class Log { private: char* _exception; // exception. public: void LogException(const char*, string); // method to log an exception. };
[ "shiron.kaz@gmail.com" ]
shiron.kaz@gmail.com
fadbac84a3aa9b21a8671b5ff86bf8fad23e2b40
282f47d0c09da26489516ddef19b46b396cc2068
/number-of-1-bits/number-of-1-bits.cpp
a5457f0d8441ba8badef57a2f539185e0763ae67
[]
no_license
concurs-program/LeetCode
600ede88a3b04b8cb0e5160796f92db248891f1a
8537dba79427bef446d561778d1e9b3370c9e029
refs/heads/main
2023-05-31T08:24:48.332861
2021-06-20T06:43:56
2021-06-20T06:43:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
class Solution { public: int hammingWeight(uint32_t n) { int count=0; while(n!=0) { count++; n&=(n-1); } return count; } };
[ "68791455+Gaurisha21@users.noreply.github.com" ]
68791455+Gaurisha21@users.noreply.github.com
8dd326b880b5a7fb478f7d179bec673aa776d10b
7b36000e13eadf66533dc5cc9f0e414ba063e218
/fibonnaci2.cpp
f828f6003409d48e6eb3f3c1a349826d3c441616
[]
no_license
fabiomsrs/Atividade-Estrutura-de-Dados
76348253cd1c8883fc8a7fb791830631d2aae44c
423736792f0e20088e6a32a55a6341803581dc95
refs/heads/master
2021-06-15T17:29:59.300666
2017-04-11T03:00:28
2017-04-11T03:00:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
#include <stdio.h> #include <conio.h> int main(){ int n1 = 0,n2 = 1,termo,cont; printf("Funcao fibonnaci termo numero - "); scanf("%d",&termo); for(cont = 0;cont < termo;cont++){ n2 += n1; n1 = n2 - n1; printf("\n%d",n2); } getch(); return 0; }
[ "fabiomsrs@gmail.com" ]
fabiomsrs@gmail.com
1eef130fa4343b18c6eca43e8b213e092d1efd83
1e5543a43ff87285b493eea61aad4635099e4034
/src/rpcmasternode-budget.cpp
be961a497630be544e115f33567cc90e554bbaa4
[ "MIT" ]
permissive
comunidaddcoins/Criptopeso
b51773452b9177de183b681abe24294fd3f1ddd7
f04d8fc1eed9c4fce277c0fa5f98559786c786a9
refs/heads/master
2020-07-05T10:55:13.584401
2019-08-17T00:12:42
2019-08-17T00:12:42
202,630,258
3
0
null
null
null
null
UTF-8
C++
false
false
45,493
cpp
// Copyright (c) 2014-2015 The Dash Developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "db.h" #include "init.h" #include "main.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "masternode-helpers.h" #include "rpcserver.h" #include "utilmoneystr.h" #include <univalue.h> #include <fstream> using namespace std; void budgetToJSON(CBudgetProposal* pbudgetProposal, UniValue& bObj) { CTxDestination address1; ExtractDestination(pbudgetProposal->GetPayee(), address1); CBitcoinAddress address2(address1); bObj.push_back(Pair("Name", pbudgetProposal->GetName())); bObj.push_back(Pair("URL", pbudgetProposal->GetURL())); bObj.push_back(Pair("Hash", pbudgetProposal->GetHash().ToString())); bObj.push_back(Pair("FeeHash", pbudgetProposal->nFeeTXHash.ToString())); bObj.push_back(Pair("BlockStart", (int64_t)pbudgetProposal->GetBlockStart())); bObj.push_back(Pair("BlockEnd", (int64_t)pbudgetProposal->GetBlockEnd())); bObj.push_back(Pair("TotalPaymentCount", (int64_t)pbudgetProposal->GetTotalPaymentCount())); bObj.push_back(Pair("RemainingPaymentCount", (int64_t)pbudgetProposal->GetRemainingPaymentCount())); bObj.push_back(Pair("PaymentAddress", address2.ToString())); bObj.push_back(Pair("Ratio", pbudgetProposal->GetRatio())); bObj.push_back(Pair("Yeas", (int64_t)pbudgetProposal->GetYeas())); bObj.push_back(Pair("Nays", (int64_t)pbudgetProposal->GetNays())); bObj.push_back(Pair("Abstains", (int64_t)pbudgetProposal->GetAbstains())); bObj.push_back(Pair("TotalPayment", ValueFromAmount(pbudgetProposal->GetAmount() * pbudgetProposal->GetTotalPaymentCount()))); bObj.push_back(Pair("MonthlyPayment", ValueFromAmount(pbudgetProposal->GetAmount()))); bObj.push_back(Pair("IsEstablished", pbudgetProposal->IsEstablished())); std::string strError = ""; bObj.push_back(Pair("IsValid", pbudgetProposal->IsValid(strError))); bObj.push_back(Pair("IsValidReason", strError.c_str())); bObj.push_back(Pair("fValid", pbudgetProposal->fValid)); } // This command is retained for backwards compatibility, but is deprecated. // Future removal of this command is planned to keep things clean. UniValue mnbudget(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "vote-alias" && strCommand != "vote-many" && strCommand != "prepare" && strCommand != "submit" && strCommand != "vote" && strCommand != "getvotes" && strCommand != "getinfo" && strCommand != "show" && strCommand != "projection" && strCommand != "check" && strCommand != "nextblock")) throw runtime_error( "mnbudget \"command\"... ( \"passphrase\" )\n" "\nVote or show current budgets\n" "This command is deprecated, please see individual command documentation for future reference\n\n" "\nAvailable commands:\n" " prepare - Prepare proposal for network by signing and creating tx\n" " submit - Submit proposal for network\n" " vote-many - Vote on a Criptopeso initiative\n" " vote-alias - Vote on a Criptopeso initiative\n" " vote - Vote on a Criptopeso initiative/budget\n" " getvotes - Show current masternode budgets\n" " getinfo - Show current masternode budgets\n" " show - Show all budgets\n" " projection - Show the projection of which proposals will be paid the next cycle\n" " check - Scan proposals and remove invalid\n" " nextblock - Get next superblock for budget system\n"); if (strCommand == "nextblock") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getnextsuperblock(newParams, fHelp); } if (strCommand == "prepare") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return preparebudget(newParams, fHelp); } if (strCommand == "submit") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return submitbudget(newParams, fHelp); } if (strCommand == "vote" || strCommand == "vote-many" || strCommand == "vote-alias") { if (strCommand == "vote-alias") throw runtime_error( "vote-alias is not supported with this command\n" "Please use mnbudgetvote instead.\n" ); return mnbudgetvote(params, fHelp); } if (strCommand == "projection") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getbudgetprojection(newParams, fHelp); } if (strCommand == "show" || strCommand == "getinfo") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getbudgetinfo(newParams, fHelp); } if (strCommand == "getvotes") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getbudgetvotes(newParams, fHelp); } if (strCommand == "check") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return checkbudgets(newParams, fHelp); } return NullUniValue; } UniValue preparebudget(const UniValue& params, bool fHelp) { int nBlockMin = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 6) throw runtime_error( "preparebudget \"proposal-name\" \"url\" payment-count block-start \"peso-address\" monthly-payment\n" "\nPrepare proposal for network by signing and creating tx\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n" "2. \"url\": (string, required) URL of proposal details (64 character limit)\n" "3. payment-count: (numeric, required) Total number of monthly payments\n" "4. block-start: (numeric, required) Starting super block height\n" "5. \"peso-address\": (string, required) PESO address to send payments to\n" "6. monthly-payment: (numeric, required) Monthly payment amount\n" "\nResult:\n" "\"xxxx\" (string) proposal fee hash (if successful) or error message (if failed)\n" "\nExamples:\n" + HelpExampleCli("preparebudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500") + HelpExampleRpc("preparebudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500")); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) throw runtime_error("Invalid proposal name, limit of 20 characters."); std::string strURL = SanitizeString(params[1].get_str()); if (strURL.size() > 64) throw runtime_error("Invalid url, limit of 64 characters."); int nPaymentCount = params[2].get_int(); if (nPaymentCount < 1) throw runtime_error("Invalid payment count, must be more than zero."); // Start must be in the next budget cycle if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockStart = params[3].get_int(); if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); } int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() * nPaymentCount; // End must be AFTER current cycle if (nBlockStart < nBlockMin) throw runtime_error("Invalid block start, must be more than current height."); if (nBlockEnd < pindexPrev->nHeight) throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); CBitcoinAddress address(params[4].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PESO address"); // Parse PESO address CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(params[5]); //************************************************************************* // create transaction 15 minutes into the future, to allow for confirmation time CBudgetProposalBroadcast budgetProposalBroadcast(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, 0); std::string strError = ""; if (!budgetProposalBroadcast.IsValid(strError, false)) throw runtime_error("Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError); bool useIX = false; //true; // if (params.size() > 7) { // if(params[7].get_str() != "false" && params[7].get_str() != "true") // return "Invalid use_ix, must be true or false"; // useIX = params[7].get_str() == "true" ? true : false; // } CWalletTx wtx; if (!pwalletMain->GetBudgetSystemCollateralTX(wtx, budgetProposalBroadcast.GetHash(), useIX)) { throw runtime_error("Error making collateral transaction for proposal. Please check your wallet balance."); } // make our change address CReserveKey reservekey(pwalletMain); //send the tx to the network pwalletMain->CommitTransaction(wtx, reservekey, useIX ? "ix" : "tx"); return wtx.GetHash().ToString(); } UniValue submitbudget(const UniValue& params, bool fHelp) { int nBlockMin = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 7) throw runtime_error( "submitbudget \"proposal-name\" \"url\" payment-count block-start \"peso-address\" monthly-payment \"fee-tx\"\n" "\nSubmit proposal to the network\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n" "2. \"url\": (string, required) URL of proposal details (64 character limit)\n" "3. payment-count: (numeric, required) Total number of monthly payments\n" "4. block-start: (numeric, required) Starting super block height\n" "5. \"peso-address\": (string, required) PESO address to send payments to\n" "6. monthly-payment: (numeric, required) Monthly payment amount\n" "7. \"fee-tx\": (string, required) Transaction hash from preparebudget command\n" "\nResult:\n" "\"xxxx\" (string) proposal hash (if successful) or error message (if failed)\n" "\nExamples:\n" + HelpExampleCli("submitbudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500") + HelpExampleRpc("submitbudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500")); // Check these inputs the same way we check the vote commands: // ********************************************************** std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) throw runtime_error("Invalid proposal name, limit of 20 characters."); std::string strURL = SanitizeString(params[1].get_str()); if (strURL.size() > 64) throw runtime_error("Invalid url, limit of 64 characters."); int nPaymentCount = params[2].get_int(); if (nPaymentCount < 1) throw runtime_error("Invalid payment count, must be more than zero."); // Start must be in the next budget cycle if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockStart = params[3].get_int(); if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); } int nBlockEnd = nBlockStart + (GetBudgetPaymentCycleBlocks() * nPaymentCount); // End must be AFTER current cycle if (nBlockStart < nBlockMin) throw runtime_error("Invalid block start, must be more than current height."); if (nBlockEnd < pindexPrev->nHeight) throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); CBitcoinAddress address(params[4].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PESO address"); // Parse PESO address CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(params[5]); uint256 hash = ParseHashV(params[6], "parameter 1"); //create the proposal incase we're the first to make it CBudgetProposalBroadcast budgetProposalBroadcast(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, hash); std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(hash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { throw runtime_error("Proposal FeeTX is not valid - " + hash.ToString() + " - " + strError); } if (!masternodeSync.IsBlockchainSynced()) { throw runtime_error("Must wait for client to sync with masternode network. Try again in a minute or so."); } // if(!budgetProposalBroadcast.IsValid(strError)){ // return "Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError; // } budget.mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); budgetProposalBroadcast.Relay(); if(budget.AddProposal(budgetProposalBroadcast)) { return budgetProposalBroadcast.GetHash().ToString(); } throw runtime_error("Invalid proposal, see debug.log for details."); } UniValue mnbudgetvote(const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) { strCommand = params[0].get_str(); // Backwards compatibility with legacy `mnbudget` command if (strCommand == "vote") strCommand = "local"; if (strCommand == "vote-many") strCommand = "many"; if (strCommand == "vote-alias") strCommand = "alias"; } if (fHelp || (params.size() == 3 && (strCommand != "local" && strCommand != "many")) || (params.size() == 4 && strCommand != "alias") || params.size() > 4 || params.size() < 3) throw runtime_error( "mnbudgetvote \"local|many|alias\" \"votehash\" \"yes|no\" ( \"alias\" )\n" "\nVote on a budget proposal\n" "\nArguments:\n" "1. \"mode\" (string, required) The voting mode. 'local' for voting directly from a masternode, 'many' for voting with a MN controller and casting the same vote for each MN, 'alias' for voting with a MN controller and casting a vote for a single MN\n" "2. \"votehash\" (string, required) The vote hash for the proposal\n" "3. \"votecast\" (string, required) Your vote. 'yes' to vote for the proposal, 'no' to vote against\n" "4. \"alias\" (string, required for 'alias' mode) The MN alias to cast a vote for.\n" "\nResult:\n" "{\n" " \"overall\": \"xxxx\", (string) The overall status message for the vote cast\n" " \"detail\": [\n" " {\n" " \"node\": \"xxxx\", (string) 'local' or the MN alias\n" " \"result\": \"xxxx\", (string) Either 'Success' or 'Failed'\n" " \"error\": \"xxxx\", (string) Error message, if vote failed\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("mnbudgetvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"") + HelpExampleRpc("mnbudgetvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"")); uint256 hash = ParseHashV(params[1], "parameter 1"); std::string strVote = params[2].get_str(); if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'"; int nVote = VOTE_ABSTAIN; if (strVote == "yes") nVote = VOTE_YES; if (strVote == "no") nVote = VOTE_NO; int success = 0; int failed = 0; UniValue resultsObj(UniValue::VARR); if (strCommand == "local") { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; UniValue statusObj(UniValue::VOBJ); while (true) { if (!masternodeSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); break; } CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == NULL) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to find masternode in list : " + activeMasternode.vin.ToString())); resultsObj.push_back(statusObj); break; } CBudgetVote vote(activeMasternode.vin, hash, nVote); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); break; } std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { success++; budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Error voting : " + strError)); } resultsObj.push_back(statusObj); break; } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "many") { BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if (!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if (pmn == NULL) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Can't find masternode by pubkey")); resultsObj.push_back(statusObj); continue; } CBudgetVote vote(pmn->vin, hash, nVote); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); continue; } std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", strError.c_str())); } resultsObj.push_back(statusObj); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "alias") { std::string strAlias = params[3].get_str(); std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { if( strAlias != mne.getAlias()) continue; std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if(!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)){ failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if(pmn == NULL) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Can't find masternode by pubkey")); resultsObj.push_back(statusObj); continue; } CBudgetVote vote(pmn->vin, hash, nVote); if(!vote.Sign(keyMasternode, pubKeyMasternode)){ failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); continue; } std::string strError = ""; if(budget.UpdateProposal(vote, NULL, strError)) { budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", strError.c_str())); } resultsObj.push_back(statusObj); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } return NullUniValue; } UniValue getbudgetvotes(const UniValue& params, bool fHelp) { if (params.size() != 1) throw runtime_error( "getbudgetvotes \"proposal-name\"\n" "\nPrint vote information for a budget proposal\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Name of the proposal\n" "\nResult:\n" "[\n" " {\n" " \"mnId\": \"xxxx\", (string) Hash of the masternode's collateral transaction\n" " \"nHash\": \"xxxx\", (string) Hash of the vote\n" " \"Vote\": \"YES|NO\", (string) Vote cast ('YES' or 'NO')\n" " \"nTime\": xxxx, (numeric) Time in seconds since epoch the vote was cast\n" " \"fValid\": true|false, (boolean) 'true' if the vote is valid, 'false' otherwise\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getbudgetvotes", "\"test-proposal\"") + HelpExampleRpc("getbudgetvotes", "\"test-proposal\"")); std::string strProposalName = SanitizeString(params[0].get_str()); UniValue ret(UniValue::VARR); CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName); if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name"); std::map<uint256, CBudgetVote>::iterator it = pbudgetProposal->mapVotes.begin(); while (it != pbudgetProposal->mapVotes.end()) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("mnId", (*it).second.vin.prevout.hash.ToString())); bObj.push_back(Pair("nHash", (*it).first.ToString().c_str())); bObj.push_back(Pair("Vote", (*it).second.GetVoteString())); bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime)); bObj.push_back(Pair("fValid", (*it).second.fValid)); ret.push_back(bObj); it++; } return ret; } UniValue getnextsuperblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getnextsuperblock\n" "\nPrint the next super block height\n" "\nResult:\n" "n (numeric) Block height of the next super block\n" "\nExamples:\n" + HelpExampleCli("getnextsuperblock", "") + HelpExampleRpc("getnextsuperblock", "")); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return "unknown"; int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); return nNext; } UniValue getbudgetprojection(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbudgetprojection\n" "\nShow the projection of which proposals will be paid the next cycle\n" "\nResult:\n" "[\n" " {\n" " \"Name\": \"xxxx\", (string) Proposal Name\n" " \"URL\": \"xxxx\", (string) Proposal URL\n" " \"Hash\": \"xxxx\", (string) Proposal vote hash\n" " \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n" " \"BlockStart\": n, (numeric) Proposal starting block\n" " \"BlockEnd\": n, (numeric) Proposal ending block\n" " \"TotalPaymentCount\": n, (numeric) Number of payments\n" " \"RemainingPaymentCount\": n, (numeric) Number of remaining payments\n" " \"PaymentAddress\": \"xxxx\", (string) PESO address of payment\n" " \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n" " \"Yeas\": n, (numeric) Number of yea votes\n" " \"Nays\": n, (numeric) Number of nay votes\n" " \"Abstains\": n, (numeric) Number of abstains\n" " \"TotalPayment\": xxx.xxx, (numeric) Total payment amount\n" " \"MonthlyPayment\": xxx.xxx, (numeric) Monthly payment amount\n" " \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n" " \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"IsValidReason\": \"xxxx\", (string) Error message, if any\n" " \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"Alloted\": xxx.xxx, (numeric) Amount alloted in current period\n" " \"TotalBudgetAlloted\": xxx.xxx (numeric) Total alloted\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getbudgetprojection", "") + HelpExampleRpc("getbudgetprojection", "")); UniValue ret(UniValue::VARR); UniValue resultObj(UniValue::VOBJ); CAmount nTotalAllotted = 0; std::vector<CBudgetProposal*> winningProps = budget.GetBudget(); BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) { nTotalAllotted += pbudgetProposal->GetAllotted(); CTxDestination address1; ExtractDestination(pbudgetProposal->GetPayee(), address1); CBitcoinAddress address2(address1); UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); bObj.push_back(Pair("Alloted", ValueFromAmount(pbudgetProposal->GetAllotted()))); bObj.push_back(Pair("TotalBudgetAlloted", ValueFromAmount(nTotalAllotted))); ret.push_back(bObj); } return ret; } UniValue getbudgetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getbudgetinfo ( \"proposal\" )\n" "\nShow current masternode budgets\n" "\nArguments:\n" "1. \"proposal\" (string, optional) Proposal name\n" "\nResult:\n" "[\n" " {\n" " \"Name\": \"xxxx\", (string) Proposal Name\n" " \"URL\": \"xxxx\", (string) Proposal URL\n" " \"Hash\": \"xxxx\", (string) Proposal vote hash\n" " \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n" " \"BlockStart\": n, (numeric) Proposal starting block\n" " \"BlockEnd\": n, (numeric) Proposal ending block\n" " \"TotalPaymentCount\": n, (numeric) Number of payments\n" " \"RemainingPaymentCount\": n, (numeric) Number of remaining payments\n" " \"PaymentAddress\": \"xxxx\", (string) PESO address of payment\n" " \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n" " \"Yeas\": n, (numeric) Number of yea votes\n" " \"Nays\": n, (numeric) Number of nay votes\n" " \"Abstains\": n, (numeric) Number of abstains\n" " \"TotalPayment\": xxx.xxx, (numeric) Total payment amount\n" " \"MonthlyPayment\": xxx.xxx, (numeric) Monthly payment amount\n" " \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n" " \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"IsValidReason\": \"xxxx\", (string) Error message, if any\n" " \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getbudgetprojection", "") + HelpExampleRpc("getbudgetprojection", "")); UniValue ret(UniValue::VARR); std::string strShow = "valid"; if (params.size() == 1) { std::string strProposalName = SanitizeString(params[0].get_str()); CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName); if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name"); UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); ret.push_back(bObj); return ret; } std::vector<CBudgetProposal*> winningProps = budget.GetAllProposals(); BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) { if (strShow == "valid" && !pbudgetProposal->fValid) continue; UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); ret.push_back(bObj); } return ret; } UniValue mnbudgetrawvote(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 6) throw runtime_error( "mnbudgetrawvote \"masternode-tx-hash\" masternode-tx-index \"proposal-hash\" yes|no time \"vote-sig\"\n" "\nCompile and relay a proposal vote with provided external signature instead of signing vote internally\n" "\nArguments:\n" "1. \"masternode-tx-hash\" (string, required) Transaction hash for the masternode\n" "2. masternode-tx-index (numeric, required) Output index for the masternode\n" "3. \"proposal-hash\" (string, required) Proposal vote hash\n" "4. yes|no (boolean, required) Vote to cast\n" "5. time (numeric, required) Time since epoch in seconds\n" "6. \"vote-sig\" (string, required) External signature\n" "\nResult:\n" "\"status\" (string) Vote status or error message\n" "\nExamples:\n" + HelpExampleCli("mnbudgetrawvote", "") + HelpExampleRpc("mnbudgetrawvote", "")); uint256 hashMnTx = ParseHashV(params[0], "mn tx hash"); int nMnTxIndex = params[1].get_int(); CTxIn vin = CTxIn(hashMnTx, nMnTxIndex); uint256 hashProposal = ParseHashV(params[2], "Proposal hash"); std::string strVote = params[3].get_str(); if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'"; int nVote = VOTE_ABSTAIN; if (strVote == "yes") nVote = VOTE_YES; if (strVote == "no") nVote = VOTE_NO; int64_t nTime = params[4].get_int64(); std::string strSig = params[5].get_str(); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSig.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { return "Failure to find masternode in list : " + vin.ToString(); } CBudgetVote vote(vin, hashProposal, nVote); vote.nTime = nTime; vote.vchSig = vchSig; if (!vote.SignatureValid(true)) { return "Failure to verify signature."; } std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); return "Voted successfully"; } else { return "Error voting : " + strError; } } UniValue mnfinalbudget(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "suggest" && strCommand != "vote-many" && strCommand != "vote" && strCommand != "show" && strCommand != "getvotes")) throw runtime_error( "mnfinalbudget \"command\"... ( \"passphrase\" )\n" "Vote or show current budgets\n" "\nAvailable commands:\n" " vote-many - Vote on a finalized budget\n" " vote - Vote on a finalized budget\n" " show - Show existing finalized budgets\n" " getvotes - Get vote information for each finalized budget\n"); if (strCommand == "vote-many") { if (params.size() != 2) throw runtime_error("Correct usage is 'mnfinalbudget vote-many BUDGET_HASH'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); int success = 0; int failed = 0; UniValue resultsObj(UniValue::VOBJ); BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if (!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(Pair(mne.getAlias(), statusObj)); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if (pmn == NULL) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Can't find masternode by pubkey")); resultsObj.push_back(Pair(mne.getAlias(), statusObj)); continue; } CFinalizedBudgetVote vote(pmn->vin, hash); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Failure to sign.")); resultsObj.push_back(Pair(mne.getAlias(), statusObj)); continue; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("result", "success")); } else { failed++; statusObj.push_back(Pair("result", strError.c_str())); } resultsObj.push_back(Pair(mne.getAlias(), statusObj)); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "vote") { if (params.size() != 2) throw runtime_error("Correct usage is 'mnfinalbudget vote BUDGET_HASH'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if (!masternodeSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) return "Error upon calling SetKey"; CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == NULL) { return "Failure to find masternode in list : " + activeMasternode.vin.ToString(); } CFinalizedBudgetVote vote(activeMasternode.vin, hash); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { return "Failure to sign."; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); return "success"; } else { return "Error voting : " + strError; } } if (strCommand == "show") { UniValue resultObj(UniValue::VOBJ); std::vector<CFinalizedBudget*> winningFbs = budget.GetFinalizedBudgets(); BOOST_FOREACH (CFinalizedBudget* finalizedBudget, winningFbs) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("FeeTX", finalizedBudget->nFeeTXHash.ToString())); bObj.push_back(Pair("Hash", finalizedBudget->GetHash().ToString())); bObj.push_back(Pair("BlockStart", (int64_t)finalizedBudget->GetBlockStart())); bObj.push_back(Pair("BlockEnd", (int64_t)finalizedBudget->GetBlockEnd())); bObj.push_back(Pair("Proposals", finalizedBudget->GetProposals())); bObj.push_back(Pair("VoteCount", (int64_t)finalizedBudget->GetVoteCount())); bObj.push_back(Pair("Status", finalizedBudget->GetStatus())); std::string strError = ""; bObj.push_back(Pair("IsValid", finalizedBudget->IsValid(strError))); bObj.push_back(Pair("IsValidReason", strError.c_str())); resultObj.push_back(Pair(finalizedBudget->GetName(), bObj)); } return resultObj; } if (strCommand == "getvotes") { if (params.size() != 2) throw runtime_error("Correct usage is 'mnbudget getvotes budget-hash'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); UniValue obj(UniValue::VOBJ); CFinalizedBudget* pfinalBudget = budget.FindFinalizedBudget(hash); if (pfinalBudget == NULL) return "Unknown budget hash"; std::map<uint256, CFinalizedBudgetVote>::iterator it = pfinalBudget->mapVotes.begin(); while (it != pfinalBudget->mapVotes.end()) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("nHash", (*it).first.ToString().c_str())); bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime)); bObj.push_back(Pair("fValid", (*it).second.fValid)); obj.push_back(Pair((*it).second.vin.prevout.ToStringShort(), bObj)); it++; } return obj; } return NullUniValue; } UniValue checkbudgets(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "checkbudgets\n" "\nInitiates a buddget check cycle manually\n" "\nExamples:\n" + HelpExampleCli("checkbudgets", "") + HelpExampleRpc("checkbudgets", "")); budget.CheckAndRemove(); return NullUniValue; }
[ "falcon@gmail.com" ]
falcon@gmail.com
1bde2fda60f53467681f4e595745ad71861dd43a
b640537dc5445b91969e0835e9fbbc17541e97fa
/HY3A/doc/上位机软件/QQuickView/View/QtDockTitleBar.cpp
cd5d65c77015bff02d3c548996457ad833db1878
[]
no_license
ucasdong/HTCZ
3e7ea972948a515c5013323d2559cd35c82827a1
f3db6391dccae161d4ffd705061703b61b2ab9a3
refs/heads/master
2021-07-09T08:44:33.921298
2021-04-09T12:25:38
2021-04-09T12:25:38
239,684,145
0
1
null
null
null
null
UTF-8
C++
false
false
1,858
cpp
#include "QtDockTitleBar.h" #include <QPropertyAnimation> #include <QGraphicsOpacityEffect> QtDockTitleBar::QtDockTitleBar(QWidget *parent) : QWidget(parent) { ui.setupUi(this); ui.widget->setProperty("nav", "top"); QDockWidget *dw = qobject_cast<QDockWidget*>(parentWidget()); ui.titleLabel->setText(dw->windowTitle()); initConnect(); ui.label->setAutoFillBackground(true); QGraphicsOpacityEffect *pButtonOpacity = new QGraphicsOpacityEffect(this); pButtonOpacity->setOpacity(1); ui.label->setGraphicsEffect(pButtonOpacity); QPropertyAnimation *pOpacityAnimation1 = new QPropertyAnimation(pButtonOpacity, "opacity"); pOpacityAnimation1->setDuration(1000); pOpacityAnimation1->setStartValue(1); pOpacityAnimation1->setEndValue(0); pOpacityAnimation1->setLoopCount(-1); pOpacityAnimation1->start(QAbstractAnimation::KeepWhenStopped); //m_pTitleMovie = new QMovie(":/image/View/image/Rolling-1s-64px.gif"); //m_pTitleMovie->resized(this->size()); //ui.label->setMovie(m_pTitleMovie); //ui.label->setScaledContents(true); //m_pTitleMovie->start(); } QtDockTitleBar::~QtDockTitleBar() { } void QtDockTitleBar::initConnect() { connect(ui.closeButton, &QPushButton::clicked, [=]() { QDockWidget *dw = qobject_cast<QDockWidget*>(parentWidget()); dw->close(); }); connect(ui.maxButton, &QPushButton::clicked, [=]() { if (window()->isMaximized()) { ui.maxButton->setStyleSheet("QPushButton{border-image: url(:/image/View/image/max.png);}" "QPushButton:hover{border-image: url(:/image/View/image/max_hover.png);}"); } else { ui.maxButton->setStyleSheet("QPushButton{border-image: url(:/image/View/image/restore.png);}" "QPushButton:hover{border-image: url(:/image/View/image/restore_hover.png);}"); } QDockWidget *dw = qobject_cast<QDockWidget*>(parentWidget()); dw->setFloating(!dw->isFloating()); }); }
[ "dlk254566110@163.com" ]
dlk254566110@163.com
0a5a940c97af068eb3f577242b705726fad86756
a4773892d84c7386923c404fd6149b6a01a95412
/mbed/mbed_grt_main.cpp
a5feb7b0a6423eefd2d7103454817c510d99f44f
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
rxdu/mbed_target
29b13ff75a0ff4dd17dcd76ce1f9f6d3ffaecc77
dd7af2f2903fdc633ccd6028e6ae4f7b3cdd54c8
refs/heads/master
2020-12-21T02:17:29.545366
2019-03-27T19:01:58
2019-03-27T19:01:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
990
cpp
// // File: grt_main.cpp // // Target selection: mbed_grt.tlc // Embedded hardware selection: ARM Compatible->ARM Cortex // Code generation objectives: Unspecified // Validation result: Not run // #include "mbed.h" #include "rtos.h" #include "mbed_grt_custom.h" extern void (*stepFctPtr)(void); extern void (*initFctPtr)(void); extern void (*termFctPtr)(void); osThreadId step_id; Thread step_1_thread; Ticker step_1_ticker; void step_thread() { step_id = Thread::gettid(); while (1) { Thread::signal_wait(0x1,osWaitForever); (*stepFctPtr)(); } } void step_callback() { osSignalSet(step_id, 0x1); } // with RTOS int main(void) { step_1_thread.start(callback(step_thread)); step_1_ticker.attach_us(callback(step_callback), (timestamp_t)STEP_SIZE_US); // initialize model (*initFctPtr)(); // main task waits forever Thread::wait(osWaitForever); // deinitialize model (*termFctPtr)(); return 0; } // // File trailer for generated code. // // [EOF] //
[ "olaf.hagendorf@hs-wismar.de" ]
olaf.hagendorf@hs-wismar.de
57f8d74b1762e8878d25996e7efffaa4ce2a612e
6586ec50430a7c0e9da66f9c8f13dddaddedd47f
/code_generator/location/location.h
7e10b9556ca6e4e21619ad3376c987ba24e46006
[]
no_license
ali01/galadriel
f1d3239834b2e4b70ecd962bab7d41d0c4aafb88
24fc228e9afe4ee72d81c346d9f2fab65f9458b3
refs/heads/master
2016-09-11T00:36:05.897111
2014-04-16T22:21:37
2014-04-16T22:21:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
h
#ifndef LOCATION_H_YQL62OVV #define LOCATION_H_YQL62OVV /* stl includes */ #include <iostream> using std::ostream; /* simone includes */ #include <simone/ptr_interface.h> class Location : public Simone::PtrInterface<Location> { public: typedef Simone::Ptr<Location> Ptr; typedef int Offset; enum Segment { kStack, kData, kHeap }; static Ptr LocationNew(Segment _seg, Offset _off, const string& _name) { return new Location(_seg, _off, _name); } static Ptr LocationNew(Location::Ptr _o) { return new Location(*_o); } /* attribute member functions */ const string& name() const; Segment segment() const { return segment_; } Offset offset() const { return offset_; } Offset secondaryOffset() const { return secondary_offset_; } void secondaryOffsetIs(Offset _off) { secondary_offset_ = _off; } virtual bool reference() const { return false; } virtual void referenceIs(bool _s) {} bool operator==(const Location& _other) const; protected: Location(Segment _segment, Offset _offset, const string& _name); Location(const Location& _o); /* data members */ Segment segment_; Offset offset_; string name_; Offset secondary_offset_; }; #endif
[ "alive@ali01.com" ]
alive@ali01.com
6c23caab595122268dd1af3623ee92adfeb23fa4
02e034a2ba10c6f63de7e1e3675407603be74617
/MegaMan/MachineController.cpp
5b5e3b7e330cbb5b72818688f45b54b030d7507d
[]
no_license
hienlh/My-DirectX-Framework
55c2e89a6c3f24a3b885f541d213825ebccc4f25
26fcf0f844bdfa7b3f572673f14088e92e665dc2
refs/heads/master
2023-05-23T09:08:01.327776
2021-06-06T09:56:14
2021-06-06T09:56:14
374,323,229
0
1
null
2021-06-06T09:56:15
2021-06-06T09:50:12
C++
UTF-8
C++
false
false
1,116
cpp
#include "MachineController.h" #include "GameObject.h" #include "Animator.h" #include "Macros.h" void MachineController::OnCollisionEnter(Framework::CCollision* collision) { if (m_pGameObject->GetComponent<Framework::CAnimator>()->GetBool(Bool_IsRun) == false) { auto anim = m_pGameObject->GetComponent<Framework::CAnimator>(); if (collision->CollisionBetween("Player", m_pGameObject->GetName())) { anim->SetBool(Bool_IsRun, true); } } } void MachineController::Update(const DWORD &dt) { auto anim = m_pGameObject->GetComponent<Framework::CAnimator>(); auto transform = m_pGameObject->GetComponent<Framework::CTransform>(); auto rigidBody = m_pGameObject->GetComponent<Framework::CRigidbody>(); if(anim->GetBool(Bool_IsRun) == true && transform->Get_Position().y > rigidBody->GetLimitedArea().top) { m_pGameObject->GetComponent<Framework::CTransform>()->Translate(Vector2(0, -.05) * dt); //m_player->GetComponent<Framework::CTransform>()->Translate(Vector2(0, -.05) * dt); } if(transform->Get_Position().y <= rigidBody->GetLimitedArea().top) { anim->SetBool(Bool_IsRun, false); } }
[ "hienlh1298@gmail.com" ]
hienlh1298@gmail.com
7d58922f553d795d9ea3b5b82cc6167538f41afa
cf960a1741b20a5f41d68c392f963296a9fd3f84
/msfs/FileManager.h
0a53be6fa7772acf7ea13703cf4104d66b569afb
[]
no_license
quocdoan419/Server
a00fdf65c3ee1c24dd16af0a5bad3b99561c6870
b8613fd7ce2012b61c4ebc6690e174c8a11079ee
refs/heads/master
2020-05-31T16:43:54.532391
2018-07-31T08:33:03
2018-07-31T08:33:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,005
h
#ifndef _FILEMANAGER_H_ #define _FILEMANAGER_H_ #include <map> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <string> #include <errno.h> #include <time.h> #include "FileLin.h" #include "CriticalSection.h" using namespace std; namespace msfs { class CriticalSection; class FileManager { private: FileManager() {} FileManager(const char *host, const char *disk, int totFiles, int filesPerDir) { m_host = new char[strlen(host) + 1]; m_disk = new char[strlen(disk) + 1]; m_host[strlen(host)] = '\0'; m_disk[strlen(disk)] = '\0'; strncpy(m_host, host, strlen(host)); strncpy(m_disk, disk, strlen(disk)); m_totFiles = totFiles; m_filesPerDir = filesPerDir; m_map.clear(); } ~FileManager() { if (m_host) delete [] m_host; m_host = NULL; if (m_disk) delete [] m_disk; m_disk = NULL; EntryMap::iterator it = m_map.begin(); while (it != m_map.end()) { delete it->second; m_map.erase(it++); } } FileManager(const FileManager &); FileManager operator=(const FileManager &); public: static FileManager* getInstance(const char *host, const char *disk, int totFiles, int filesPerDir) { return (m_instance) ? m_instance : (new FileManager(host, disk, totFiles, filesPerDir)); } static void destroyInstance() { if (m_instance) delete m_instance; m_instance = NULL; } int initDir(); u64 getFileCntCurr() {return m_totFiles;} int getFirstDir() {return (m_totFiles / (m_filesPerDir)) / (FIRST_DIR_MAX);} int getSecondDir() {return (m_totFiles % (m_filesPerDir * FIRST_DIR_MAX) ) / m_filesPerDir;} string createFileRelatePath(); int uploadFile(const char *type, const void *content, u32 size, char *url, char *ext = NULL); int downloadFileByUrl(char *urlEn, void *buf, u32 *size); int getRelatePathByUrl(const string &url, string &path); int getAbsPathByUrl(const string &url, string &path); protected: struct Entry { time_t m_lastAccess; size_t m_fileSize; u8* m_fileContent; Entry() { m_lastAccess = 0; m_fileSize = 0; m_fileContent = NULL; } ~Entry() { if (m_fileContent) delete [] m_fileContent; m_fileContent = NULL; } }; typedef std::map<std::string, Entry*> EntryMap; int insertEntry(const std::string& url, size_t filesize, const void* content); Entry* getEntry(const std::string& url) const { return const_cast<FileManager*>(this)->getOrCreateEntry(url,false); } Entry* getOrCreateEntry(const std::string& url, bool create); void releaseFileCache(const std::string& url); void updateMapCache(); private: char *m_host; //msfs server ip or hostname char *m_disk; //storage directory of media files u64 m_totFiles; //total files has storaged CriticalSection m_filesCs; int m_filesPerDir; //mas file nums per dir eg. xxx/xxx static const u32 MAX_FILE_SIZE_PER_FILE = 5 * 1024 * 1024; static const int FIRST_DIR_MAX =255; static const int SECOND_DIR_MAX =255; static const u64 MAX_FILE_IN_MAP = 10000; static FileManager * m_instance; EntryMap m_map; CriticalSection m_cs; }; } #endif
[ "hgl868@126.com" ]
hgl868@126.com
b52aeeafb38a9fa80d4c8e4c077ce0691ff55547
9f4c35cff855b14127e4a84e18ad8e2072113994
/src/DataSet/BumbleDataSet.cpp
aed7d360e91ae3873c0396452bf479e407a90876
[]
no_license
RyanEvanWolf/BasicSLAMStructures
cb03c0076cb8f0ac3e39a6106917eba93ffe46ae
d92c3d299ea7ff752af48e113954eea648621d23
refs/heads/master
2020-12-24T23:09:23.874751
2018-01-12T23:13:03
2018-01-12T23:13:03
100,127,986
0
0
null
null
null
null
UTF-8
C++
false
false
3,535
cpp
#include "Structures/DataSet/BumbleDataSet.hpp" namespace stereo { BumbleDataSet::BumbleDataSet(std::string root) { rootDir_=root; std::cout<<"input - "<<rootDir_<<std::endl; populateFrameList(); current_frame_=frameReferences_.begin(); ++current_frame_; } std::vector< std::string > BumbleDataSet::getFilesList(std::string dir) { //search through a directory, and populate a vector of string filenames, return a copy of the vector boost::filesystem::directory_iterator end_itr,itr(dir); std::vector<std::string> files; for (itr; itr != end_itr; ++itr) { // If it's not a directory, list it. If you want to list directories too, just remove this check. if (boost::filesystem::is_regular_file(itr->path())) { boost::filesystem::path tempPath(itr->path().string()); files.push_back(tempPath.filename().string()); } } return files; } std::vector< std::string > BumbleDataSet::getDirList(std::string dir) { //search through a directory, and populate a vector of string filenames, return a copy of the vector boost::filesystem::directory_iterator end_itr,itr(dir); std::vector<std::string> files; for (itr; itr != end_itr; ++itr) { // If it's not a directory, list it. If you want to list directories too, just remove this check. files.push_back(itr->path().string()); } //sort into descending order std::sort(files.begin(),files.end()); return files; } void BumbleDataSet::populateFrameList() { std::vector<std::string> ImageFiles; // cycle through the left camera + right camera directory ImageFiles=getDirList(rootDir_); //add left and right images to frame object + push to queue std::vector<std::string>::iterator endit=ImageFiles.end(); for(std::vector<std::string>::iterator it=ImageFiles.begin();it!=endit;++it) { BumbleFrame newFrame; newFrame.Meta_.fullDir_=*it; boost::filesystem::path Name(newFrame.Meta_.fullDir_); newFrame.Meta_.fileName_=Name.filename().string(); frameReferences_.push_back(newFrame); } } cv::Mat BumbleDataSet::getCurrent() { cv::Mat input,output; (*current_frame_).getBothImages(input); //cv::cvtColor(input, output, cv::COLOR_BayerBG2RGB); //cv::cvtColor(output, output, cv::COLOR_RGB2GRAY); std::cout<<(*current_frame_).Meta_.fileName_<<std::endl; return output; } cv::Mat BumbleDataSet::getCurrentLeft() { cv::Mat input,output; (*current_frame_).getLeftImage(input); cv::cvtColor(input, output, cv::COLOR_BayerBG2RGB); cv::cvtColor(output, output, cv::COLOR_RGB2GRAY); return output; } cv::Mat BumbleDataSet::getCurrentRight() { cv::Mat input,output; (*current_frame_).getRightImage(input); cv::cvtColor(input, output, cv::COLOR_BayerBG2RGB); cv::cvtColor(output, output, cv::COLOR_RGB2GRAY); return output; } bool BumbleDataSet::decrementFrame() { --current_frame_; if(current_frame_!=frameReferences_.begin()) { return true; } else { ++current_frame_; return false; } } bool BumbleDataSet::incrementFrame() { ++current_frame_; if(current_frame_!=frameReferences_.end()) { return true; } else { --current_frame_; return false; } } std::string BumbleDataSet::getCurrentName() { if((current_frame_!=frameReferences_.end())&&(current_frame_!=frameReferences_.begin())) { return current_frame_->Meta_.fileName_; } else { return "NULL"; } } ImageMetaData BumbleDataSet::getCurrentMeta() { if((current_frame_!=frameReferences_.end())&&(current_frame_!=frameReferences_.begin())) { return current_frame_->Meta_; } else { return ImageMetaData(); } } }
[ "ryanevwolf@gmail.com" ]
ryanevwolf@gmail.com
02ced93adb37844961123a4d95ac66f58f15620c
53e34589e5ba1046aee99e4167348672a1222ae8
/VS2017/sdk/include/um/winuser.inl
dc5f021c0bc6ff17aa7902ffb8830408d2b02fa2
[]
no_license
ir0nc0w/cross-compile_for_Windows
8088a0db9cfdeac6243b56ec0c8e79e5076990c4
08935f0864f497ee7fc6f13aba1b598701a04be1
refs/heads/master
2020-05-31T15:03:45.160869
2019-11-05T11:14:21
2019-11-05T11:14:21
190,342,498
9
1
null
null
null
null
UTF-8
C++
false
false
38,132
inl
/* Copyright (c) 2001-2018, Microsoft Corp. All rights reserved. */ #if _MSC_VER > 1000 #pragma once #endif #if defined(__cplusplus) extern "C" { #endif #if !defined(RC_INVOKED) /* RC complains about long symbols in #ifs */ #if defined(ISOLATION_AWARE_ENABLED) && (ISOLATION_AWARE_ENABLED != 0) #if _MSC_VER >= 1200 #pragma warning(push) #pragma warning(disable:4191) /* cast */ #if _MSC_VER >= 1400 #pragma warning(disable:6101) /* Because there will be success paths where out params are not initialized. */ #endif #endif #if !defined(ISOLATION_AWARE_USE_STATIC_LIBRARY) #define ISOLATION_AWARE_USE_STATIC_LIBRARY 0 #endif #if !defined(ISOLATION_AWARE_BUILD_STATIC_LIBRARY) #define ISOLATION_AWARE_BUILD_STATIC_LIBRARY 0 #endif #if !defined(ISOLATION_AWARE_INLINE) #if ISOLATION_AWARE_BUILD_STATIC_LIBRARY #define ISOLATION_AWARE_INLINE /* nothing */ #else #if defined(__cplusplus) #define ISOLATION_AWARE_INLINE inline #else #define ISOLATION_AWARE_INLINE __inline #endif #endif #endif #if !ISOLATION_AWARE_USE_STATIC_LIBRARY #endif /* ISOLATION_AWARE_USE_STATIC_LIBRARY */ ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassA(_In_ const WNDCLASSA*lpWndClass); ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassW(_In_ const WNDCLASSW*lpWndClass); BOOL IsolationAwarePrivatenCv IsolationAwareUnregisterClassA(_In_ LPCSTR lpClassName,_In_opt_ HINSTANCE hInstance); BOOL IsolationAwarePrivatenCv IsolationAwareUnregisterClassW(_In_ LPCWSTR lpClassName,_In_opt_ HINSTANCE hInstance); _Success_(return) BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpClassName,_Out_ LPWNDCLASSA lpWndClass); _Success_(return) BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpClassName,_Out_ LPWNDCLASSW lpWndClass); ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassExA(_In_ const WNDCLASSEXA*unnamed1); ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassExW(_In_ const WNDCLASSEXW*unnamed1); _Success_(return) BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoExA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpszClass,_Out_ LPWNDCLASSEXA lpwcx); _Success_(return) BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoExW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpszClass,_Out_ LPWNDCLASSEXW lpwcx); HWND IsolationAwarePrivatenCv IsolationAwareCreateWindowExA(_In_ DWORD dwExStyle,_In_opt_ LPCSTR lpClassName,_In_opt_ LPCSTR lpWindowName,_In_ DWORD dwStyle,_In_ int X,_In_ int Y,_In_ int nWidth,_In_ int nHeight,_In_opt_ HWND hWndParent,_In_opt_ HMENU hMenu,_In_opt_ HINSTANCE hInstance,_In_opt_ LPVOID lpParam); HWND IsolationAwarePrivatenCv IsolationAwareCreateWindowExW(_In_ DWORD dwExStyle,_In_opt_ LPCWSTR lpClassName,_In_opt_ LPCWSTR lpWindowName,_In_ DWORD dwStyle,_In_ int X,_In_ int Y,_In_ int nWidth,_In_ int nHeight,_In_opt_ HWND hWndParent,_In_opt_ HMENU hMenu,_In_opt_ HINSTANCE hInstance,_In_opt_ LPVOID lpParam); HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogIndirectParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEA lpTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogIndirectParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEW lpTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxIndirectParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEA hDialogTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxIndirectParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEW hDialogTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam); int IsolationAwarePrivatenCv IsolationAwareMessageBoxA(_In_opt_ HWND hWnd,_In_opt_ LPCSTR lpText,_In_opt_ LPCSTR lpCaption,_In_ UINT uType); int IsolationAwarePrivatenCv IsolationAwareMessageBoxW(_In_opt_ HWND hWnd,_In_opt_ LPCWSTR lpText,_In_opt_ LPCWSTR lpCaption,_In_ UINT uType); int IsolationAwarePrivatenCv IsolationAwareMessageBoxExA(_In_opt_ HWND hWnd,_In_opt_ LPCSTR lpText,_In_opt_ LPCSTR lpCaption,_In_ UINT uType,_In_ WORD wLanguageId); int IsolationAwarePrivatenCv IsolationAwareMessageBoxExW(_In_opt_ HWND hWnd,_In_opt_ LPCWSTR lpText,_In_opt_ LPCWSTR lpCaption,_In_ UINT uType,_In_ WORD wLanguageId); int IsolationAwarePrivatenCv IsolationAwareMessageBoxIndirectA(_In_ const MSGBOXPARAMSA*lpmbp); int IsolationAwarePrivatenCv IsolationAwareMessageBoxIndirectW(_In_ const MSGBOXPARAMSW*lpmbp); #if defined(UNICODE) #define IsolationAwareCreateDialogIndirectParam IsolationAwareCreateDialogIndirectParamW #define IsolationAwareCreateDialogParam IsolationAwareCreateDialogParamW #define IsolationAwareCreateWindowEx IsolationAwareCreateWindowExW #define IsolationAwareDialogBoxIndirectParam IsolationAwareDialogBoxIndirectParamW #define IsolationAwareDialogBoxParam IsolationAwareDialogBoxParamW #define IsolationAwareGetClassInfo IsolationAwareGetClassInfoW #define IsolationAwareGetClassInfoEx IsolationAwareGetClassInfoExW #define IsolationAwareMessageBox IsolationAwareMessageBoxW #define IsolationAwareMessageBoxEx IsolationAwareMessageBoxExW #define IsolationAwareMessageBoxIndirect IsolationAwareMessageBoxIndirectW #define IsolationAwareRegisterClass IsolationAwareRegisterClassW #define IsolationAwareRegisterClassEx IsolationAwareRegisterClassExW #define IsolationAwareUnregisterClass IsolationAwareUnregisterClassW #else /* UNICODE */ #define IsolationAwareCreateDialogIndirectParam IsolationAwareCreateDialogIndirectParamA #define IsolationAwareCreateDialogParam IsolationAwareCreateDialogParamA #define IsolationAwareCreateWindowEx IsolationAwareCreateWindowExA #define IsolationAwareDialogBoxIndirectParam IsolationAwareDialogBoxIndirectParamA #define IsolationAwareDialogBoxParam IsolationAwareDialogBoxParamA #define IsolationAwareGetClassInfo IsolationAwareGetClassInfoA #define IsolationAwareGetClassInfoEx IsolationAwareGetClassInfoExA #define IsolationAwareMessageBox IsolationAwareMessageBoxA #define IsolationAwareMessageBoxEx IsolationAwareMessageBoxExA #define IsolationAwareMessageBoxIndirect IsolationAwareMessageBoxIndirectA #define IsolationAwareRegisterClass IsolationAwareRegisterClassA #define IsolationAwareRegisterClassEx IsolationAwareRegisterClassExA #define IsolationAwareUnregisterClass IsolationAwareUnregisterClassA #endif /* UNICODE */ #if !ISOLATION_AWARE_USE_STATIC_LIBRARY ISOLATION_AWARE_INLINE ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassA(_In_ const WNDCLASSA*lpWndClass) { ATOM result = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return result; __try { result = RegisterClassA(lpWndClass); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (result == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return result; } ISOLATION_AWARE_INLINE ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassW(_In_ const WNDCLASSW*lpWndClass) { ATOM result = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return result; __try { result = RegisterClassW(lpWndClass); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (result == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return result; } ISOLATION_AWARE_INLINE BOOL IsolationAwarePrivatenCv IsolationAwareUnregisterClassA(_In_ LPCSTR lpClassName,_In_opt_ HINSTANCE hInstance) { BOOL fResult = FALSE; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return fResult; __try { fResult = UnregisterClassA(lpClassName,hInstance); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (fResult == FALSE); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return fResult; } ISOLATION_AWARE_INLINE BOOL IsolationAwarePrivatenCv IsolationAwareUnregisterClassW(_In_ LPCWSTR lpClassName,_In_opt_ HINSTANCE hInstance) { BOOL fResult = FALSE; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return fResult; __try { fResult = UnregisterClassW(lpClassName,hInstance); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (fResult == FALSE); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return fResult; } _Success_(return) ISOLATION_AWARE_INLINE BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpClassName,_Out_ LPWNDCLASSA lpWndClass) { BOOL fResult = FALSE; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return fResult; __try { fResult = GetClassInfoA(hInstance,lpClassName,lpWndClass); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (fResult == FALSE); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return fResult; } _Success_(return) ISOLATION_AWARE_INLINE BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpClassName,_Out_ LPWNDCLASSW lpWndClass) { BOOL fResult = FALSE; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return fResult; __try { fResult = GetClassInfoW(hInstance,lpClassName,lpWndClass); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (fResult == FALSE); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return fResult; } ISOLATION_AWARE_INLINE ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassExA(_In_ const WNDCLASSEXA*unnamed1) { ATOM result = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return result; __try { result = RegisterClassExA(unnamed1); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (result == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return result; } ISOLATION_AWARE_INLINE ATOM IsolationAwarePrivatenCv IsolationAwareRegisterClassExW(_In_ const WNDCLASSEXW*unnamed1) { ATOM result = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return result; __try { result = RegisterClassExW(unnamed1); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (result == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return result; } _Success_(return) ISOLATION_AWARE_INLINE BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoExA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpszClass,_Out_ LPWNDCLASSEXA lpwcx) { BOOL fResult = FALSE; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return fResult; __try { fResult = GetClassInfoExA(hInstance,lpszClass,lpwcx); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (fResult == FALSE); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return fResult; } _Success_(return) ISOLATION_AWARE_INLINE BOOL IsolationAwarePrivatenCv IsolationAwareGetClassInfoExW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpszClass,_Out_ LPWNDCLASSEXW lpwcx) { BOOL fResult = FALSE; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return fResult; __try { fResult = GetClassInfoExW(hInstance,lpszClass,lpwcx); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (fResult == FALSE); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return fResult; } ISOLATION_AWARE_INLINE HWND IsolationAwarePrivatenCv IsolationAwareCreateWindowExA(_In_ DWORD dwExStyle,_In_opt_ LPCSTR lpClassName,_In_opt_ LPCSTR lpWindowName,_In_ DWORD dwStyle,_In_ int X,_In_ int Y,_In_ int nWidth,_In_ int nHeight,_In_opt_ HWND hWndParent,_In_opt_ HMENU hMenu,_In_opt_ HINSTANCE hInstance,_In_opt_ LPVOID lpParam) { HWND windowResult = NULL; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return windowResult; __try { windowResult = CreateWindowExA(dwExStyle,lpClassName,lpWindowName,dwStyle,X,Y,nWidth,nHeight,hWndParent,hMenu,hInstance,lpParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (windowResult == NULL); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return windowResult; } ISOLATION_AWARE_INLINE HWND IsolationAwarePrivatenCv IsolationAwareCreateWindowExW(_In_ DWORD dwExStyle,_In_opt_ LPCWSTR lpClassName,_In_opt_ LPCWSTR lpWindowName,_In_ DWORD dwStyle,_In_ int X,_In_ int Y,_In_ int nWidth,_In_ int nHeight,_In_opt_ HWND hWndParent,_In_opt_ HMENU hMenu,_In_opt_ HINSTANCE hInstance,_In_opt_ LPVOID lpParam) { HWND windowResult = NULL; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return windowResult; __try { windowResult = CreateWindowExW(dwExStyle,lpClassName,lpWindowName,dwStyle,X,Y,nWidth,nHeight,hWndParent,hMenu,hInstance,lpParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (windowResult == NULL); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return windowResult; } ISOLATION_AWARE_INLINE HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { HWND windowResult = NULL; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return windowResult; __try { windowResult = CreateDialogParamA(hInstance,lpTemplateName,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (windowResult == NULL); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return windowResult; } ISOLATION_AWARE_INLINE HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { HWND windowResult = NULL; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return windowResult; __try { windowResult = CreateDialogParamW(hInstance,lpTemplateName,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (windowResult == NULL); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return windowResult; } ISOLATION_AWARE_INLINE HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogIndirectParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEA lpTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { HWND windowResult = NULL; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return windowResult; __try { windowResult = CreateDialogIndirectParamA(hInstance,lpTemplate,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (windowResult == NULL); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return windowResult; } ISOLATION_AWARE_INLINE HWND IsolationAwarePrivatenCv IsolationAwareCreateDialogIndirectParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEW lpTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { HWND windowResult = NULL; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return windowResult; __try { windowResult = CreateDialogIndirectParamW(hInstance,lpTemplate,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (windowResult == NULL); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return windowResult; } ISOLATION_AWARE_INLINE INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { INT_PTR nResult = -1; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = DialogBoxParamA(hInstance,lpTemplateName,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == -1); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCWSTR lpTemplateName,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { INT_PTR nResult = -1; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = DialogBoxParamW(hInstance,lpTemplateName,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == -1); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxIndirectParamA(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEA hDialogTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { INT_PTR nResult = -1; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = DialogBoxIndirectParamA(hInstance,hDialogTemplate,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == -1); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE INT_PTR IsolationAwarePrivatenCv IsolationAwareDialogBoxIndirectParamW(_In_opt_ HINSTANCE hInstance,_In_ LPCDLGTEMPLATEW hDialogTemplate,_In_opt_ HWND hWndParent,_In_opt_ DLGPROC lpDialogFunc,_In_ LPARAM dwInitParam) { INT_PTR nResult = -1; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = DialogBoxIndirectParamW(hInstance,hDialogTemplate,hWndParent,lpDialogFunc,dwInitParam); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == -1); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE int IsolationAwarePrivatenCv IsolationAwareMessageBoxA(_In_opt_ HWND hWnd,_In_opt_ LPCSTR lpText,_In_opt_ LPCSTR lpCaption,_In_ UINT uType) { int nResult = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = MessageBoxA(hWnd,lpText,lpCaption,uType); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE int IsolationAwarePrivatenCv IsolationAwareMessageBoxW(_In_opt_ HWND hWnd,_In_opt_ LPCWSTR lpText,_In_opt_ LPCWSTR lpCaption,_In_ UINT uType) { int nResult = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = MessageBoxW(hWnd,lpText,lpCaption,uType); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE int IsolationAwarePrivatenCv IsolationAwareMessageBoxExA(_In_opt_ HWND hWnd,_In_opt_ LPCSTR lpText,_In_opt_ LPCSTR lpCaption,_In_ UINT uType,_In_ WORD wLanguageId) { int nResult = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = MessageBoxExA(hWnd,lpText,lpCaption,uType,wLanguageId); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE int IsolationAwarePrivatenCv IsolationAwareMessageBoxExW(_In_opt_ HWND hWnd,_In_opt_ LPCWSTR lpText,_In_opt_ LPCWSTR lpCaption,_In_ UINT uType,_In_ WORD wLanguageId) { int nResult = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = MessageBoxExW(hWnd,lpText,lpCaption,uType,wLanguageId); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE int IsolationAwarePrivatenCv IsolationAwareMessageBoxIndirectA(_In_ const MSGBOXPARAMSA*lpmbp) { int nResult = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = MessageBoxIndirectA(lpmbp); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE int IsolationAwarePrivatenCv IsolationAwareMessageBoxIndirectW(_In_ const MSGBOXPARAMSW*lpmbp) { int nResult = 0 ; ULONG_PTR ulpCookie = 0; const BOOL fActivateActCtxSuccess = IsolationAwarePrivateT_SAbnPgpgk || IsolationAwarePrivateT_SqbjaYRiRY || IsolationAwarePrivatenPgViNgRzlnPgpgk(&ulpCookie); if (!fActivateActCtxSuccess) return nResult; __try { nResult = MessageBoxIndirectW(lpmbp); } __finally { if (!IsolationAwarePrivateT_SAbnPgpgk || !IsolationAwarePrivateT_SqbjaYRiRY ) { const BOOL fPreserveLastError = (nResult == 0 ); const DWORD dwLastError = fPreserveLastError ? GetLastError() : NO_ERROR; (void)IsolationAwareDeactivateActCtx(0, ulpCookie); if (fPreserveLastError) SetLastError(dwLastError); } } return nResult; } ISOLATION_AWARE_INLINE FARPROC IsolationAwarePrivatenCv WinuserIsolationAwarePrivatetRgCebPnQQeRff_HfReQP_QYY(LPCSTR pszProcName) /* This function is shared by the other stubs in this header. */ { static HMODULE s_module; const static IsolationAwarePrivatepBAFGnAG_zBqHyr_vAsB c = { IsolationAwarePrivatezlybNQyVOeNelJ, L"User32.dll" #ifdef _M_IX86 , IsolationAwarePrivatezlybNQyVOeNeln, "User32.dll" #endif }; static IsolationAwarePrivatezHGnoyr_zBqHyr_vAsB m; return IsolationAwarePrivatezltRgCebPnQQeRff(&c, &m, pszProcName); } #endif /* ISOLATION_AWARE_USE_STATIC_LIBRARY */ #define CreateDialogIndirectParamA IsolationAwareCreateDialogIndirectParamA #define CreateDialogIndirectParamW IsolationAwareCreateDialogIndirectParamW #define CreateDialogParamA IsolationAwareCreateDialogParamA #define CreateDialogParamW IsolationAwareCreateDialogParamW #define CreateWindowExA IsolationAwareCreateWindowExA #define CreateWindowExW IsolationAwareCreateWindowExW #define DialogBoxIndirectParamA IsolationAwareDialogBoxIndirectParamA #define DialogBoxIndirectParamW IsolationAwareDialogBoxIndirectParamW #define DialogBoxParamA IsolationAwareDialogBoxParamA #define DialogBoxParamW IsolationAwareDialogBoxParamW /* GetClassInfoA skipped, as it is a popular C++ member function name. */ #define GetClassInfoExA IsolationAwareGetClassInfoExA #define GetClassInfoExW IsolationAwareGetClassInfoExW /* GetClassInfoW skipped, as it is a popular C++ member function name. */ /* MessageBoxA skipped, as it is a popular C++ member function name. */ #define MessageBoxExA IsolationAwareMessageBoxExA #define MessageBoxExW IsolationAwareMessageBoxExW #define MessageBoxIndirectA IsolationAwareMessageBoxIndirectA #define MessageBoxIndirectW IsolationAwareMessageBoxIndirectW /* MessageBoxW skipped, as it is a popular C++ member function name. */ #define RegisterClassA IsolationAwareRegisterClassA #define RegisterClassExA IsolationAwareRegisterClassExA #define RegisterClassExW IsolationAwareRegisterClassExW #define RegisterClassW IsolationAwareRegisterClassW #define UnregisterClassA IsolationAwareUnregisterClassA #define UnregisterClassW IsolationAwareUnregisterClassW #if _MSC_VER >= 1200 #pragma warning(pop) #endif #endif /* ISOLATION_AWARE_ENABLED */ #endif /* RC */ #if defined(__cplusplus) } /* __cplusplus */ #endif
[ "330cjfdn@gmail.com" ]
330cjfdn@gmail.com
c073044be3cd71f61712c493aee4131aa46c33fc
55fd4557dcdcff3752dbc1d22b57fb1a00233857
/src/Vertice.cpp
42ce95a736611bee576369d9793152ea5b0e9313
[]
no_license
sitekwb/edmonds-karp-algorithm
74ed11596fdfdd242fae83ccb6984cd8e573d8d0
9318689298041cb2b20e2f7f028dc1e1694c7bef
refs/heads/master
2020-08-22T06:51:55.180125
2020-01-15T14:04:27
2020-01-15T14:04:27
216,341,649
0
1
null
null
null
null
UTF-8
C++
false
false
2,054
cpp
#include "Vertice.h" using namespace std; std::shared_ptr<Edge> Vertice::createEdge(int verticeNumber, double edgeCapacity) { if(verticeNumber < 0){ throw out_of_range("Vertice number < 0"); } auto edge = make_shared<Edge>(edgeCapacity); edges[verticeNumber] = edge; return edge; } Vertice::Vertice(double capacity) { if(capacity < 0){ throw std::out_of_range("Vertice capacity < 0"); } this->capacity = capacity; this->color = WHITE; this->parentVertice = noParent(); } const std::unordered_map<int, shared_ptr<Edge>> &Vertice::getEdges() const { return edges; } double Vertice::infinity() { return numeric_limits<double>::max(); } std::shared_ptr<Edge> Vertice::operator[](int v_2) { return edges[v_2]; } Color Vertice::getColor() const { return color; } void Vertice::setColor(Color color) { Vertice::color = color; } int Vertice::getParentVertice() const { return parentVertice; } void Vertice::setParentVertice(int parentVertice) { Vertice::parentVertice = parentVertice; } int Vertice::noParent() { return -1; } bool Vertice::hasParent() { return parentVertice != -1; } double Vertice::getCapacity() const { return capacity; } void Vertice::reduceCapacity(double capacity) { if(capacity < 0){ throw std::out_of_range("Reducing by negative capacity"); } this->capacity -= capacity; } int Vertice::getEdgesCount() { return edges.size(); } bool Vertice::issetEdge(int vIndex) { return edges.find(vIndex) != edges.cend(); } void Vertice::incrementCapacity(const double capacity) { if(capacity < 0){ throw std::out_of_range("Vertice capacity increment < 0"); } Vertice::capacity += capacity; } void Vertice::scaleCapacity(double maxCapacity) { if(maxCapacity <= 0){ throw std::out_of_range("Scaled capacity out of range"); } if (capacity != Vertice::infinity()) { capacity /= maxCapacity; } } bool Vertice::isConnected() { return getEdgesCount() > 0; }
[ "s.wojciech9@gmail.com" ]
s.wojciech9@gmail.com
cbdf6836799c2e87d2642227f22de6b4d769a29e
b13619f4e0f37e367228c4fa0263120f54ed72f4
/Bullet/BulletCollision/CollisionDispatch/btManifoldResult.cpp
0342d1f384efdccbe760bc3c41c9c973c3871f04
[]
no_license
Zenout/Bullet279-for-Marmalade
aec6cae0c67ed281ca1e8cf255699d92a7d11eb7
419c7c1ae8d155096ecd89347c3376efe86a5a3c
refs/heads/master
2016-09-05T08:51:15.109544
2012-10-21T09:48:39
2012-10-21T09:48:39
6,319,059
1
0
null
null
null
null
UTF-8
C++
false
false
4,761
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btManifoldResult.h" #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h" #include "BulletCollision/CollisionDispatch/btCollisionObject.h" ///This is to allow MaterialCombiner/Custom Friction/Restitution values ContactAddedCallback gContactAddedCallback=0; ///User can override this material combiner by implementing gContactAddedCallback and setting body0->m_collisionFlags |= btCollisionObject::customMaterialCallback; inline btScalar calculateCombinedFriction(const btCollisionObject* body0,const btCollisionObject* body1) { btScalar friction = body0->getFriction() * body1->getFriction(); const btScalar MAX_FRICTION = btScalar(10.); if (friction < -MAX_FRICTION) friction = -MAX_FRICTION; if (friction > MAX_FRICTION) friction = MAX_FRICTION; return friction; } inline btScalar calculateCombinedRestitution(const btCollisionObject* body0,const btCollisionObject* body1) { return body0->getRestitution() * body1->getRestitution(); } btManifoldResult::btManifoldResult(btCollisionObject* body0,btCollisionObject* body1) :m_manifoldPtr(0), m_body0(body0), m_body1(body1) #ifdef DEBUG_PART_INDEX ,m_partId0(-1), m_partId1(-1), m_index0(-1), m_index1(-1) #endif //DEBUG_PART_INDEX { m_rootTransA = body0->getWorldTransform(); m_rootTransB = body1->getWorldTransform(); } void btManifoldResult::addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth) { btAssert(m_manifoldPtr); //order in manifold needs to match if (depth > m_manifoldPtr->getContactBreakingThreshold()) // if (depth > m_manifoldPtr->getContactProcessingThreshold()) return; bool isNewCollision = m_manifoldPtr->getNumContacts() == 0; bool isSwapped = m_manifoldPtr->getBody0() != m_body0; btVector3 pointA = pointInWorld + normalOnBInWorld * depth; btVector3 localA; btVector3 localB; if (isSwapped) { localA = m_rootTransB.invXform(pointA ); localB = m_rootTransA.invXform(pointInWorld); } else { localA = m_rootTransA.invXform(pointA ); localB = m_rootTransB.invXform(pointInWorld); } btManifoldPoint newPt(localA,localB,normalOnBInWorld,depth); newPt.m_positionWorldOnA = pointA; newPt.m_positionWorldOnB = pointInWorld; int insertIndex = m_manifoldPtr->getCacheEntry(newPt); newPt.m_combinedFriction = calculateCombinedFriction(m_body0,m_body1); newPt.m_combinedRestitution = calculateCombinedRestitution(m_body0,m_body1); //BP mod, store contact triangles. if (isSwapped) { newPt.m_partId0 = m_partId1; newPt.m_partId1 = m_partId0; newPt.m_index0 = m_index1; newPt.m_index1 = m_index0; } else { newPt.m_partId0 = m_partId0; newPt.m_partId1 = m_partId1; newPt.m_index0 = m_index0; newPt.m_index1 = m_index1; } //printf("depth=%f\n",depth); ///@todo, check this for any side effects if (insertIndex >= 0) { //const btManifoldPoint& oldPoint = m_manifoldPtr->getContactPoint(insertIndex); m_manifoldPtr->replaceContactPoint(newPt,insertIndex); } else { insertIndex = m_manifoldPtr->addManifoldPoint(newPt); } //User can override friction and/or restitution if (gContactAddedCallback && //and if either of the two bodies requires custom material ((m_body0->getCollisionFlags() & btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK) || (m_body1->getCollisionFlags() & btCollisionObject::CF_CUSTOM_MATERIAL_CALLBACK))) { //experimental feature info, for per-triangle material etc. btCollisionObject* obj0 = isSwapped? m_body1 : m_body0; btCollisionObject* obj1 = isSwapped? m_body0 : m_body1; (*gContactAddedCallback)(m_manifoldPtr->getContactPoint(insertIndex),obj0,newPt.m_partId0,newPt.m_index0,obj1,newPt.m_partId1,newPt.m_index1); } if (gCollisionStartedCallback && isNewCollision) { gCollisionStartedCallback(m_manifoldPtr); } }
[ "jez@zenout.co.uk" ]
jez@zenout.co.uk
5b52e210a228ad7a7ab85a4b62860398149d77ee
ba9322f7db02d797f6984298d892f74768193dcf
/mts/src/model/AddMCTemplateResult.cc
481c18b0612f2246f416bebc4b7256d547cc29d6
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
2,492
cc
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/mts/model/AddMCTemplateResult.h> #include <json/json.h> using namespace AlibabaCloud::Mts; using namespace AlibabaCloud::Mts::Model; AddMCTemplateResult::AddMCTemplateResult() : ServiceResult() {} AddMCTemplateResult::AddMCTemplateResult(const std::string &payload) : ServiceResult() { parse(payload); } AddMCTemplateResult::~AddMCTemplateResult() {} void AddMCTemplateResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto _templateNode = value["Template"]; if(!_templateNode["TemplateId"].isNull()) _template_.templateId = _templateNode["TemplateId"].asString(); if(!_templateNode["Name"].isNull()) _template_.name = _templateNode["Name"].asString(); if(!_templateNode["Porn"].isNull()) _template_.porn = _templateNode["Porn"].asString(); if(!_templateNode["Terrorism"].isNull()) _template_.terrorism = _templateNode["Terrorism"].asString(); if(!_templateNode["Politics"].isNull()) _template_.politics = _templateNode["Politics"].asString(); if(!_templateNode["Ad"].isNull()) _template_.ad = _templateNode["Ad"].asString(); if(!_templateNode["Qrcode"].isNull()) _template_.qrcode = _templateNode["Qrcode"].asString(); if(!_templateNode["Live"].isNull()) _template_.live = _templateNode["Live"].asString(); if(!_templateNode["Logo"].isNull()) _template_.logo = _templateNode["Logo"].asString(); if(!_templateNode["Abuse"].isNull()) _template_.abuse = _templateNode["Abuse"].asString(); if(!_templateNode["Contraband"].isNull()) _template_.contraband = _templateNode["Contraband"].asString(); if(!_templateNode["Spam"].isNull()) _template_.spam = _templateNode["Spam"].asString(); } AddMCTemplateResult::_Template AddMCTemplateResult::get_Template()const { return _template_; }
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
6fd8e1726887116febeb816e9c6f74be80827e8b
044928a7958790d7791a6b2895e9b54167bf4c9f
/patcher/ControllerPatcherHID.cpp
e4a9560c6d37051caf6aea49bdd9ba692ae9681e
[]
no_license
shadow2560/controller_patcher
047186b2c96aa03251e5971fd37ccafefcbd7cd6
718ac61d77c076900a5e59c93892f94f9fe354a3
refs/heads/master
2021-06-19T10:21:06.085056
2017-07-20T15:28:14
2017-07-20T15:28:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,100
cpp
/**************************************************************************** * Copyright (C) 2016,2017 Maschell * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ****************************************************************************/ #include "ControllerPatcherHID.hpp" #include <malloc.h> #include <stdio.h> #include <string.h> #include <gctypes.h> #include "dynamic_libs/os_functions.h" #include "utils/logger.h" /*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * public implementation for the network controller *---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ s32 ControllerPatcherHID::externAttachDetachCallback(HIDDevice *p_device, u32 attach){ HIDClient client; memset(&client,0,sizeof(client)); return AttachDetachCallback(&client,p_device,attach); } void ControllerPatcherHID::externHIDReadCallback(u32 handle, unsigned char *buf, u32 bytes_transfered, my_cb_user * usr){ HIDReadCallback(handle,buf,bytes_transfered,usr); } /*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * private implementation for the HID Api. *---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ s32 ControllerPatcherHID::myAttachDetachCallback(HIDClient *p_client, HIDDevice *p_device, u32 attach){ return AttachDetachCallback(p_client,p_device,attach); } void ControllerPatcherHID::myHIDMouseReadCallback(u32 handle, s32 error, unsigned char *buf, u32 bytes_transfered, void *p_user){ if(error == 0){ my_cb_user *usr = (my_cb_user*)p_user; u32 slot = 0; if(usr->pad_slot < HID_MAX_PADS_COUNT){ slot = usr->pad_slot; } HID_Data * data_ptr = &(gHID_Devices[usr->slotdata.deviceslot].pad_data[slot]); HID_Mouse_Data * cur_mouse_data = &data_ptr->data_union.mouse.cur_mouse_data; data_ptr->type = DEVICE_TYPE_MOUSE; //log_printf("%02X %02X %02X %02X %02X bytes_transfered: %d\n",buf[0],buf[1],buf[2],buf[3],buf[4],bytes_transfered); if(buf[0] == 2 && bytes_transfered > 3){ // using the other mouse mode buf +=1; } s8 x_value = 0; s8 y_value = 0; x_value = buf[1]; y_value = buf[2]; cur_mouse_data->X += x_value; cur_mouse_data->deltaX = x_value; cur_mouse_data->Y += y_value; cur_mouse_data->deltaY = y_value; cur_mouse_data->left_click = buf[0]; cur_mouse_data->right_click = buf[0]>>1; if(cur_mouse_data->X < 0) cur_mouse_data->X = 0; if(cur_mouse_data->X > 1280) cur_mouse_data->X = 1280; if(cur_mouse_data->Y < 0) cur_mouse_data->Y = 0; if(cur_mouse_data->Y > 720) cur_mouse_data->Y = 720; cur_mouse_data->valuedChanged = 1; //log_printf("%02X %02X %02X %02X %02X %02X %02X %02X %d = X: %d Y: %d \n",buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7],bytes_transfered,x_value,y_value); HIDRead(handle, usr->buf, bytes_transfered, myHIDMouseReadCallback, usr); } } void ControllerPatcherHID::myHIDReadCallback(u32 handle, s32 error, unsigned char *buf, u32 bytes_transfered, void *p_user){ if(error == 0 && p_user != NULL && gHIDAttached){ my_cb_user *usr = (my_cb_user*)p_user; HIDReadCallback(handle,buf,bytes_transfered,usr); if(usr->slotdata.hidmask == gHID_LIST_DS4){ os_usleep(1000*2); //DS4 is way tooo fast. sleeping to reduce lag. (need to check the other pads) } HIDRead(handle, usr->buf, bytes_transfered, myHIDReadCallback, usr); } } /*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Intern Callback actions *---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ s32 ControllerPatcherHID::AttachDetachCallback(HIDClient *p_client, HIDDevice *p_device, u32 attach){ if(attach){ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): vid %04x pid %04x connected\n",__LINE__, SWAP16(p_device->vid),SWAP16(p_device->pid)); if(HID_DEBUG){ log_printf("interface index %02x\n", p_device->interface_index); log_printf("sub class %02x\n", p_device->sub_class); log_printf("protocol %02x\n", p_device->protocol); log_printf("max packet in %02x\n", p_device->max_packet_size_rx); log_printf("max packet out %02x\n", p_device->max_packet_size_tx); } } if(!attach){ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): vid %04x pid %04x disconnected\n",__LINE__, SWAP16(p_device->vid),SWAP16(p_device->pid)); } DeviceInfo device_info; memset(&device_info,0,sizeof(DeviceInfo)); device_info.slotdata.deviceslot = -1; device_info.vidpid.vid = SWAP16(p_device->vid); device_info.vidpid.pid = SWAP16(p_device->pid); HIDSlotData * slotdata = &(device_info.slotdata); if ((p_device->sub_class == 1) && (p_device->protocol == 1)) { //Keyboard slotdata->hidmask = gHID_LIST_KEYBOARD; slotdata->deviceslot = gHID_SLOT_KEYBOARD; //log_printf("Found Keyboard: device: %s slot: %d\n",byte_to_binary(device_info.slotdata.hidmask),device_info.slotdata.deviceslot); }else if ((p_device->sub_class == 1) && (p_device->protocol == 2)){ // MOUSE slotdata->hidmask = gHID_LIST_MOUSE; slotdata->deviceslot = gMouseSlot; //log_printf("Found Mouse: device: %s slot: %d\n",byte_to_binary(device_info.hid),device_info.slot); }else{ s32 ret; if((ret = ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info)) < 0){ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info) failed %d \n",__LINE__,ret); return HID_DEVICE_DETACH; }else{ //log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): ControllerPatcherUtils::getDeviceInfoFromVidPid(&device_info) success %d \n",__LINE__,ret); } } if(slotdata->hidmask){ if(attach){ s32 bufSize = 64; if(slotdata->hidmask != gHID_LIST_MOUSE && config_controller[slotdata->deviceslot][CONTRPS_BUF_SIZE][0] == CONTROLLER_PATCHER_VALUE_SET){ bufSize = config_controller[slotdata->deviceslot][CONTRPS_BUF_SIZE][1]; } unsigned char *buf = (unsigned char *) memalign(64,bufSize); memset(buf,0,bufSize); my_cb_user *usr = (my_cb_user *) memalign(64,sizeof(my_cb_user)); usr->buf = buf; usr->slotdata = device_info.slotdata; usr->transfersize = p_device->max_packet_size_rx; usr->handle = p_device->handle; gHIDAttached |= slotdata->hidmask; gHIDCurrentDevice |= slotdata->hidmask; s32 pads_per_device = 1; if(config_controller[slotdata->deviceslot][CONTRPS_PAD_COUNT][0] != CONTROLLER_PATCHER_INVALIDVALUE){ pads_per_device = config_controller[slotdata->deviceslot][CONTRPS_PAD_COUNT][1]; if(pads_per_device > HID_MAX_PADS_COUNT){//maximum of HID_MAX_PADS_COUNT pads_per_device = HID_MAX_PADS_COUNT; } } s32 pad_count = config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1]; if(pad_count > 0x0F) pad_count = 0; //??? s32 pad_slot = 0; s32 failed = 1; for(s32 i = 0;i<HID_MAX_PADS_COUNT;i += pads_per_device){ if(!(pad_count & (1 << i))){ failed = 0; pad_count |= (1 << i); pad_slot = i; break; } } if(failed){ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d) error: I can only handle %d devices of the same type. Sorry \n",__LINE__,HID_MAX_PADS_COUNT); if(buf){ free(buf); buf = NULL; } if(usr){ free(usr); usr = NULL; } return 0; } config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1] = pad_count; DCFlushRange(&config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1],sizeof(config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1])); DCInvalidateRange(&config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1],sizeof(config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1])); usr->pads_per_device = pads_per_device; usr->pad_slot = pad_slot; for(s32 i = 0;i<pads_per_device;i++){ memset(&gHID_Devices[slotdata->deviceslot].pad_data[pad_slot+i],0,sizeof(HID_Data)); gHID_Devices[slotdata->deviceslot].pad_data[pad_slot+i].handle = p_device->handle; //log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): saved handle %d to slot %d and pad %d\n",__LINE__,p_device->handle,slotdata->deviceslot,pad_slot); gHID_Devices[slotdata->deviceslot].pad_data[pad_slot+i].user_data = usr; gHID_Devices[slotdata->deviceslot].pad_data[pad_slot+i].slotdata = device_info.slotdata; DCFlushRange(&gHID_Devices[slotdata->deviceslot].pad_data[pad_slot+i],sizeof(HID_Data)); DCInvalidateRange(&gHID_Devices[slotdata->deviceslot].pad_data[pad_slot+i],sizeof(HID_Data)); } if(HID_DEBUG){ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): Device successfully attached\n",__LINE__); } if(slotdata->hidmask == gHID_LIST_GC){ // GC PAD //The GC Adapter has all ports in one device. Set them all. gHID_Devices[slotdata->deviceslot].pad_data[0].slotdata = device_info.slotdata; gHID_Devices[slotdata->deviceslot].pad_data[1].slotdata = device_info.slotdata; gHID_Devices[slotdata->deviceslot].pad_data[2].slotdata = device_info.slotdata; gHID_Devices[slotdata->deviceslot].pad_data[3].slotdata = device_info.slotdata; buf[0] = 0x13; HIDWrite(p_device->handle, usr->buf, 1, NULL,NULL); HIDRead(p_device->handle, usr->buf, usr->transfersize, myHIDReadCallback, usr); }else if (slotdata->hidmask == gHID_LIST_MOUSE){ HIDSetProtocol(p_device->handle, p_device->interface_index, 0, 0, 0); //HIDGetDescriptor(p_device->handle,0x22,0x00,0,my_buf,512,my_foo_cb,NULL); HIDSetIdle(p_device->handle,p_device->interface_index,1,NULL,NULL); gHID_Mouse_Mode = HID_MOUSE_MODE_AIM; HIDRead(p_device->handle, buf, p_device->max_packet_size_rx, myHIDMouseReadCallback, usr); }else if (slotdata->hidmask == gHID_LIST_SWITCH_PRO){ s32 read_result = HIDRead(p_device->handle, usr->buf, usr->transfersize, NULL, NULL); if(read_result == 64){ if(usr->buf[01] == 0x01){ //We need to do the handshake log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): Switch Pro Controller handshake needed\n",__LINE__); /** Thanks to ShinyQuagsire23 for the values (https://github.com/shinyquagsire23/HID-Joy-Con-Whispering) **/ //Get MAC buf[0] = 0x80; buf[1] = 0x01; HIDWrite(p_device->handle, usr->buf, 2, NULL,NULL); HIDRead(p_device->handle, usr->buf, usr->transfersize, NULL, NULL); //Do handshake buf[0] = 0x80; buf[1] = 0x02; HIDWrite(p_device->handle, usr->buf, 2, NULL,NULL); HIDRead(p_device->handle, usr->buf, usr->transfersize, NULL, NULL); //Talk over HID only. buf[0] = 0x80; buf[1] = 0x04; HIDWrite(p_device->handle, usr->buf, 2, NULL,NULL); HIDRead(p_device->handle, usr->buf, usr->transfersize, NULL, NULL); }else{ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): Switch Pro Controller handshake already done\n",__LINE__); } HIDRead(p_device->handle, usr->buf, usr->transfersize, myHIDReadCallback, usr); } }else if (slotdata->hidmask == gHID_LIST_KEYBOARD){ HIDSetProtocol(p_device->handle, p_device->interface_index, 1, 0, 0); HIDSetIdle(p_device->handle, p_device->interface_index, 0, 0, 0); HIDRead(p_device->handle, buf, p_device->max_packet_size_rx, myHIDReadCallback, usr); }else if (slotdata->hidmask == gHID_LIST_DS3){ HIDSetProtocol(p_device->handle, p_device->interface_index, 1, 0, 0); HIDDS3Rumble(p_device->handle,usr,0); buf[0] = 0x42; buf[1] = 0x0c; buf[2] = 0x00; buf[3] = 0x00; HIDSetReport(p_device->handle, HID_REPORT_FEATURE, PS3_F4_REPORT_ID, buf, PS3_F4_REPORT_LEN, NULL, NULL); HIDRead(p_device->handle, usr->buf, p_device->max_packet_size_rx, myHIDReadCallback, usr); }else{ HIDRead(p_device->handle, usr->buf, p_device->max_packet_size_rx, myHIDReadCallback, usr); } return HID_DEVICE_ATTACH; }else{ my_cb_user * user_data = NULL; s32 founddata = 0; for(s32 i = 0;i<HID_MAX_PADS_COUNT;i++){ if(gHID_Devices[slotdata->deviceslot].pad_data[i].handle == p_device->handle){ gHID_Devices[slotdata->deviceslot].pad_data[i].handle = 0; DCFlushRange(&gHID_Devices[slotdata->deviceslot].pad_data[i].handle,sizeof(gHID_Devices[slotdata->deviceslot].pad_data[i].handle)); DCInvalidateRange(&gHID_Devices[slotdata->deviceslot].pad_data[i].handle,sizeof(gHID_Devices[slotdata->deviceslot].pad_data[i].handle)); user_data = (my_cb_user *) gHID_Devices[slotdata->deviceslot].pad_data[i].user_data; founddata = 1; break; } } if(user_data){ config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1] &= ~ (1 << user_data->pad_slot); DCFlushRange(&config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1],sizeof(config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1])); DCInvalidateRange(&config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1],sizeof(config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1])); if(user_data->buf){ free(user_data->buf); user_data->buf = NULL; } free(user_data); user_data = NULL; }else{ if(founddata){ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): user_data null. You may have a memory leak.\n",__LINE__); } return HID_DEVICE_DETACH; } if(config_controller[slotdata->deviceslot][CONTRPS_CONNECTED_PADS][1] == 0){ gHIDAttached &= ~slotdata->hidmask; gHIDCurrentDevice &= ~slotdata->hidmask; DCFlushRange(&gHIDAttached,sizeof(gHIDAttached)); DCInvalidateRange(&gHIDAttached,sizeof(gHIDAttached)); DCFlushRange(&gHIDCurrentDevice,sizeof(gHIDCurrentDevice)); DCInvalidateRange(&gHIDCurrentDevice,sizeof(gHIDCurrentDevice)); if (slotdata->hidmask == gHID_LIST_MOUSE){ gHID_Mouse_Mode = HID_MOUSE_MODE_AIM; } }else{ if(HID_DEBUG){log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): We still have pad for deviceslot %d connected.\n",__LINE__,slotdata->deviceslot); } } if(HID_DEBUG){log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): Device successfully detached\n",__LINE__); } } }else{ log_printf("ControllerPatcherHID::AttachDetachCallback(line %d): HID-Device currently not supported! You can add support through config files\n",__LINE__); } return HID_DEVICE_DETACH; } void ControllerPatcherHID::HIDReadCallback(u32 handle, unsigned char *buf, u32 bytes_transfered, my_cb_user * usr){ ControllerPatcherUtils::doSampling(usr->slotdata.deviceslot,usr->pad_slot,false); //log_printf("my_read_cbInternal: %d %08X %d\n",bytes_transfered,usr->slotdata.hidmask,usr->slotdata.deviceslot); if(usr->slotdata.hidmask == gHID_LIST_GC){ HID_Data * data_ptr = NULL; //Copy the data for all 4 pads for(s32 i = 0;i<4;i++){ data_ptr = &(gHID_Devices[gHID_SLOT_GC].pad_data[i]); memcpy(&(data_ptr->data_union.controller.last_hid_data[0]),&(data_ptr->data_union.controller.cur_hid_data[0]),10); //save last data. memcpy(&(data_ptr->data_union.controller.cur_hid_data[0]),&buf[(i*9)+1],9); //save new data. } /* s32 i = 0; log_printf("GC1 %08X: %02X %02X %02X %02X %02X %02X %02X %02X %02X ", buf[i*9+0],buf[i*9+1],buf[i*9+2],buf[i*9+3],buf[i*9+4],buf[i*9+5],buf[i*9+6],buf[i*9+7],buf[i*9+8]);i++; log_printf("GC2 %08X: %02X %02X %02X %02X %02X %02X %02X %02X %02X ", buf[i*9+0],buf[i*9+1],buf[i*9+2],buf[i*9+3],buf[i*9+4],buf[i*9+5],buf[i*9+6],buf[i*9+7],buf[i*9+8]);i++; log_printf("GC3 %08X: %02X %02X %02X %02X %02X %02X %02X %02X %02X ", buf[i*9+0],buf[i*9+1],buf[i*9+2],buf[i*9+3],buf[i*9+4],buf[i*9+5],buf[i*9+6],buf[i*9+7],buf[i*9+8]);i++; log_printf("GC4 %08X: %02X %02X %02X %02X %02X %02X %02X %02X %02X \n", buf[i*9+0],buf[i*9+1],buf[i*9+2],buf[i*9+3],buf[i*9+4],buf[i*9+5],buf[i*9+6],buf[i*9+7],buf[i*9+8]);*/ HIDGCRumble(handle,usr); }else if(usr->slotdata.hidmask != 0){ //Depending on how the switch pro controller is connected, it has a different data format. At first we had the Bluetooth version, so we need to convert //the USB one into it now. (When it's connected via USB). The network client always sends the BT version, even if connected via USB to the PC. if(usr->slotdata.hidmask == gHID_LIST_SWITCH_PRO && buf != NULL && bytes_transfered >= 0x20){ u8 buffer[0x13]; memcpy(buffer,buf+0x0D,0x013); /** Thanks to ShinyQuagsire23 for the values (https://github.com/shinyquagsire23/HID-Joy-Con-Whispering) **/ buf[0] = 0x80; buf[1] = 0x92; buf[2] = 0x00; buf[3] = 0x01; buf[4] = 0x00; buf[5] = 0x00; buf[6] = 0x00; buf[7] = 0x00; buf[8] = 0x1F; //We want to get the next input! s32 res = HIDWrite(handle, buf, 9, NULL,NULL); if(res == 9){ //Check if it's the USB data format. if(buffer[1] == 0) return; //Converting the buttons u32 buttons = (((u32*)(buffer))[0]) & 0xFFFFFF00; u32 newButtons = 0; if((buttons & HID_SWITCH_PRO_USB_BUTTON_A_VALUE) == HID_SWITCH_PRO_USB_BUTTON_A_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_A_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_B_VALUE) == HID_SWITCH_PRO_USB_BUTTON_B_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_B_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_X_VALUE) == HID_SWITCH_PRO_USB_BUTTON_X_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_X_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_Y_VALUE) == HID_SWITCH_PRO_USB_BUTTON_Y_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_Y_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_PLUS_VALUE) == HID_SWITCH_PRO_USB_BUTTON_PLUS_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_PLUS_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_MINUS_VALUE) == HID_SWITCH_PRO_USB_BUTTON_MINUS_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_MINUS_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_HOME_VALUE) == HID_SWITCH_PRO_USB_BUTTON_HOME_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_HOME_VALUE; //if((buttons & SWITCH_PRO_USB_BUTTON_SCREENSHOT) == HID_SWITCH_PRO_USB_BUTTON_SCREENSHOT) newButtons |= HID_SWITCH_PRO_BT_BUTTON_SCREENSHOT; if((buttons & HID_SWITCH_PRO_USB_BUTTON_R_VALUE) == HID_SWITCH_PRO_USB_BUTTON_R_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_R_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_ZR_VALUE) == HID_SWITCH_PRO_USB_BUTTON_ZR_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_ZR_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_STICK_R_VALUE) == HID_SWITCH_PRO_USB_BUTTON_STICK_R_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_STICK_R_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_L_VALUE) == HID_SWITCH_PRO_USB_BUTTON_L_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_L_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_ZL_VALUE) == HID_SWITCH_PRO_USB_BUTTON_ZL_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_ZL_VALUE; if((buttons & HID_SWITCH_PRO_USB_BUTTON_STICK_L_VALUE) == HID_SWITCH_PRO_USB_BUTTON_STICK_L_VALUE) newButtons |= HID_SWITCH_PRO_BT_BUTTON_STICK_L_VALUE; u8 dpad = buffer[2]; u8 dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_NEUTRAL_VALUE; //Converting the DPAD if(((dpad & HID_SWITCH_PRO_USB_BUTTON_UP_VALUE) == HID_SWITCH_PRO_USB_BUTTON_UP_VALUE) && ((dpad & HID_SWITCH_PRO_USB_BUTTON_RIGHT_VALUE) == HID_SWITCH_PRO_USB_BUTTON_RIGHT_VALUE)){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_NE_VALUE; }else if(((dpad & HID_SWITCH_PRO_USB_BUTTON_DOWN_VALUE) == HID_SWITCH_PRO_USB_BUTTON_DOWN_VALUE) && ((dpad & HID_SWITCH_PRO_USB_BUTTON_RIGHT_VALUE) == HID_SWITCH_PRO_USB_BUTTON_RIGHT_VALUE)){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_SE_VALUE; }else if(((dpad & HID_SWITCH_PRO_USB_BUTTON_DOWN_VALUE) == HID_SWITCH_PRO_USB_BUTTON_DOWN_VALUE) && ((dpad & HID_SWITCH_PRO_USB_BUTTON_LEFT_VALUE) == HID_SWITCH_PRO_USB_BUTTON_LEFT_VALUE)){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_SW_VALUE; }else if(((dpad & HID_SWITCH_PRO_USB_BUTTON_UP_VALUE) == HID_SWITCH_PRO_USB_BUTTON_UP_VALUE) && ((dpad & HID_SWITCH_PRO_USB_BUTTON_LEFT_VALUE) == HID_SWITCH_PRO_USB_BUTTON_LEFT_VALUE)){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_NW_VALUE; }else if((dpad & HID_SWITCH_PRO_USB_BUTTON_UP_VALUE) == HID_SWITCH_PRO_USB_BUTTON_UP_VALUE){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_N_VALUE; }else if((dpad & HID_SWITCH_PRO_USB_BUTTON_RIGHT_VALUE) == HID_SWITCH_PRO_USB_BUTTON_RIGHT_VALUE){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_E_VALUE; }else if((dpad & HID_SWITCH_PRO_USB_BUTTON_DOWN_VALUE) == HID_SWITCH_PRO_USB_BUTTON_DOWN_VALUE){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_S_VALUE; }else if((dpad & HID_SWITCH_PRO_USB_BUTTON_LEFT_VALUE) == HID_SWITCH_PRO_USB_BUTTON_LEFT_VALUE){ dpadResult = HID_SWITCH_PRO_BT_BUTTON_DPAD_W_VALUE; } //Converting the stick data u8 LX = (u8) ((u16) ((buffer[0x04] << 8 &0xFF00) | (((u16)buffer[0x03])&0xFF)) >> 0x04); u8 LY = (u8)((buffer[0x05] *-1)); u8 RX = (u8) ((u16) ((buffer[0x07] << 8 &0xFF00) | (((u16)buffer[0x06])&0xFF)) >> 0x04); u8 RY = (u8)((buffer[0x08] *-1)); buf[0] = (newButtons >> 24) & 0xFF; buf[1] = (newButtons >> 16) & 0xFF; buf[2] |= dpadResult; buf[4] = LX; buf[6] = LY; buf[8] = RX; buf[10] = RY; } } s32 dsize = (HID_MAX_DATA_LENGTH_PER_PAD > bytes_transfered)? bytes_transfered : HID_MAX_DATA_LENGTH_PER_PAD; s32 skip = 0; //Input filter if( config_controller[usr->slotdata.deviceslot][CONTRPS_INPUT_FILTER][0] != CONTROLLER_PATCHER_INVALIDVALUE){ if(buf[config_controller[usr->slotdata.deviceslot][CONTRPS_INPUT_FILTER][0]] != config_controller[usr->slotdata.deviceslot][CONTRPS_INPUT_FILTER][1]){ skip = 1; } } if(!skip){ u32 slot = 0; if(usr->pad_slot < HID_MAX_PADS_COUNT){ slot = usr->pad_slot; } slot += ControllerPatcherUtils::getPadSlotInAdapter(usr->slotdata.deviceslot,buf); // If the controller has multiple slots, we need to use the right one. HID_Data * data_ptr = &(gHID_Devices[usr->slotdata.deviceslot].pad_data[slot]); memcpy(&(data_ptr->data_union.controller.last_hid_data[0]),&(data_ptr->data_union.controller.cur_hid_data[0]),dsize); // save the last data. memcpy(&(data_ptr->data_union.controller.cur_hid_data[0]),&buf[0],dsize); // save the new data. DCFlushRange(&gHID_Devices[usr->slotdata.deviceslot].pad_data[slot],sizeof(HID_Data)); data_ptr = &(gHID_Devices[usr->slotdata.deviceslot].pad_data[slot]); HIDRumble(handle,usr,slot); } } } /*---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Other functions *---------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/ CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcherHID::setVPADControllerData(VPADData * buffer,std::vector<HID_Data *>& data){ if(buffer == NULL) return CONTROLLER_PATCHER_ERROR_NULL_POINTER; HID_Data * data_cur; s32 buttons_hold; for(u32 i = 0;i<data.size();i++){ data_cur = data[i]; if(data_cur->slotdata.hidmask & gHID_LIST_MOUSE){ //Reset the input when we have no new inputs HID_Mouse_Data * mouse_data = &data_cur->data_union.mouse.cur_mouse_data; if(mouse_data->valuedChanged == 1){ //Fix for the mouse cursor mouse_data->valuedChanged = 0; }else{ mouse_data->deltaX = 0; mouse_data->deltaY = 0; } } buttons_hold = 0; ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_A); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_B); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_X); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_Y); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_LEFT); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_RIGHT); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_DOWN); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_UP); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_MINUS); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_L); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_R); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_PLUS); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_ZL); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_ZR); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_HOME); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_STICK_L); ControllerPatcherUtils::getButtonPressed(data_cur,&buttons_hold,VPAD_BUTTON_STICK_R); u32 last_emulate_stick = (data_cur->last_buttons) & VPAD_MASK_EMULATED_STICKS; // We should only need the emulated stick data. s32 last_realbuttons = (data_cur->last_buttons) & VPAD_MASK_BUTTONS; buffer->btns_h |= buttons_hold; buffer->btns_d |= (buttons_hold & (~last_realbuttons)); buffer->btns_r |= (last_realbuttons & (~buttons_hold)); ControllerPatcherUtils::convertAnalogSticks(data_cur,buffer); ControllerPatcherUtils::setEmulatedSticks(buffer,&last_emulate_stick); ControllerPatcherUtils::checkAndSetMouseMode(data_cur); ControllerPatcherUtils::setTouch(data_cur,buffer); data_cur->last_buttons = buttons_hold & VPAD_MASK_BUTTONS; data_cur->last_buttons |= last_emulate_stick; } // Caculates a valid stick position if(data.size() > 0){ ControllerPatcherUtils::normalizeStickValues(&buffer->lstick); ControllerPatcherUtils::normalizeStickValues(&buffer->rstick); } return CONTROLLER_PATCHER_ERROR_NONE; } std::vector<HID_Data *> ControllerPatcherHID::getHIDDataAll(){ u32 hid = gHIDCurrentDevice; std::vector<HID_Data *> data_list; for(s32 i = 0;i < gHIDMaxDevices;i++){ if((hid & (1 << i)) != 0){ u32 cur_hidmask = config_controller_hidmask[i]; for(s32 pad = 0; pad < HID_MAX_PADS_COUNT; pad++){ s32 res; HID_Data * new_data = NULL; if((res = ControllerPatcherHID::getHIDData(cur_hidmask,pad,&new_data)) < 0){ // Checks if the pad is invalid. log_printf("ControllerPatcherHID::getHIDDataAll(line %d): error: Error getting the HID data from HID(%s) CHAN(). Error %d\n",__LINE__,CPStringTools::byte_to_binary(cur_hidmask),pad,res); continue; } if(new_data != NULL) data_list.push_back(new_data); } } } return data_list; } /* The slotdata in the HID_Data pointer is empty. We need to provide the hidmask via the parameter */ CONTROLLER_PATCHER_RESULT_OR_ERROR ControllerPatcherHID::getHIDData(u32 hidmask, s32 pad, HID_Data ** data){ if(data == NULL) return CONTROLLER_PATCHER_ERROR_INVALID_BUFFER; if(!(hidmask & gHIDCurrentDevice)) return CONTROLLER_PATCHER_ERROR_HID_NOT_CONNECTED; if(pad < 0 && pad > 3) return CONTROLLER_PATCHER_ERROR_INVALID_CHAN; s32 device_slot = ControllerPatcherUtils::getDeviceSlot(hidmask); if(device_slot < 0){ return CONTROLLER_PATCHER_ERROR_DEVICE_SLOT_NOT_FOUND; } s32 real_pad = pad; if((device_slot != gHID_SLOT_GC) && config_controller[device_slot][CONTRPS_PAD_COUNT][0] != CONTROLLER_PATCHER_INVALIDVALUE){ s32 pad_count = config_controller[device_slot][CONTRPS_PAD_COUNT][1]; if(pad_count > HID_MAX_PADS_COUNT) pad_count = HID_MAX_PADS_COUNT; pad = (pad/(pad_count))*pad_count; } s32 result = ControllerPatcherUtils::checkActivePad(hidmask,pad); if(result < 0){ //Not pad connected to adapter return CONTROLLER_PATCHER_ERROR_NO_PAD_CONNECTED; } *data = &gHID_Devices[device_slot].pad_data[real_pad]; return CONTROLLER_PATCHER_ERROR_NONE; } void ControllerPatcherHID::HIDGCRumble(u32 handle,my_cb_user *usr){ if(usr == NULL) return; if(!ControllerPatcher::isRumbleActivated()) return; s32 rumblechanged = 0; for(s32 i = 0;i<HID_GC_PAD_COUNT;i++){ HID_Data * data_ptr = &(gHID_Devices[usr->slotdata.deviceslot].pad_data[i]); if(data_ptr->rumbleActive != usr->rumblestatus[i]){ rumblechanged = 1; } usr->rumblestatus[i] = data_ptr->rumbleActive; usr->buf[i+1] = usr->rumblestatus[i]; } usr->forceRumbleInTicks[0]--; if(rumblechanged || usr->forceRumbleInTicks[0] <= 0){ usr->buf[0] = 0x11; HIDWrite(handle, usr->buf, 5, NULL, NULL); usr->forceRumbleInTicks[0] = 10; } } void ControllerPatcherHID::HIDRumble(u32 handle,my_cb_user *usr,u32 pad){ if(usr == NULL || pad > HID_MAX_PADS_COUNT) return; if(!ControllerPatcher::isRumbleActivated()) return; s32 rumblechanged = 0; HID_Data * data_ptr = &(gHID_Devices[usr->slotdata.deviceslot].pad_data[pad]); if(data_ptr->rumbleActive != usr->rumblestatus[pad]){ usr->rumblestatus[pad] = data_ptr->rumbleActive; rumblechanged = 1; } usr->forceRumbleInTicks[pad]--; if(rumblechanged || usr->forceRumbleInTicks[pad] <= 0){ //log_printf("Rumble: %d %d\n",usr->rumblestatus[pad],usr->rumbleForce[pad]); //Seding to the network client! char bytes[6]; s32 i = 0; bytes[i++] = 0x01; bytes[i++] = (handle >> 24) & 0xFF; bytes[i++] = (handle >> 16) & 0xFF; bytes[i++] = (handle >> 8) & 0xFF; bytes[i++] = handle & 0xFF; bytes[i++] = usr->rumblestatus[pad]; UDPClient * instance = UDPClient::getInstance(); if(instance != NULL){ instance->sendData(bytes,6); } if(usr->slotdata.hidmask == gHID_LIST_DS3){ HIDDS3Rumble(handle,usr,usr->rumblestatus[pad]); }else{ // Not implemented for other devices =( } usr->forceRumbleInTicks[pad] = 10; } } static u8 ds3_rumble_Report[48] = { 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0xFF, 0x27, 0x10, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; void ControllerPatcherHID::HIDDS3Rumble(u32 handle,my_cb_user *usr,s32 rumble){ memcpy(usr->buf, ds3_rumble_Report, 48); if (rumble) { usr->buf[2] = 0x01; usr->buf[4] = 0xff; } HIDSetReport(handle, HID_REPORT_OUTPUT, PS3_01_REPORT_ID, usr->buf, 48, NULL, NULL); }
[ "Maschell@gmx.de" ]
Maschell@gmx.de
ef9f5df7c39ee37f314513f7947514d2861d4d20
4dbaea97b6b6ba4f94f8996b60734888b163f69a
/NowCoder/牛牛找工作.cpp
c74f5c7b6bc57d0330fecace67b06d290df3e56a
[]
no_license
Ph0en1xGSeek/ACM
099954dedfccd6e87767acb5d39780d04932fc63
b6730843ab0455ac72b857c0dff1094df0ae40f5
refs/heads/master
2022-10-25T09:15:41.614817
2022-10-04T12:17:11
2022-10-04T12:17:11
63,936,497
2
0
null
null
null
null
UTF-8
C++
false
false
1,262
cpp
#include <stdio.h> #include <iostream> #include <algorithm> using namespace std; struct work { int cost; int gain; bool operator<(work &b) const { if(cost == b.cost) { return gain < b.gain; } return cost < b.cost; } }; int main() { int n, m; scanf("%d%d", &n, &m); vector<work> works(n); for(int i = 0; i < n; ++i) { scanf("%d%d", &works[i].cost, &works[i].gain); } sort(works.begin(), works.end()); int pos = 0; int mx = -0x7fffffff; for(int i = 0; i < m; ++i) { if(works[i].gain > mx) { mx = works[i].gain; works[pos].cost = works[i].cost; works[pos].gain = works[i].gain; ++pos; } } for(int i = 0; i < m; ++i) { int ability; scanf("%d", &ability); int l = 0, r = pos; while(l < r) { int mid = (l + r) >> 1; if(works[mid].cost <= ability) { l = mid + 1; }else { r = mid; } } if(l == 0) { printf("0\n"); }else { printf("%d\n", works[l-1].gain); } } return 0; }
[ "54panguosheng@gmail.com" ]
54panguosheng@gmail.com
382de5d7edbb7ad560d9ba3ed69a014af9b3b1eb
6e764aef961ced2cde30ae089acb18dd809a90c1
/CF/281_A.cpp
94e2acd24dddca7db60ff69897c211d9463199df
[]
no_license
SihabSahariar/competitive-programming
34ba818d8f65707c3cb1822c0820b96eee54f28f
946983e0bf7270a2eccfd7ae8d739746aac825da
refs/heads/master
2020-07-26T01:36:22.157424
2015-10-31T09:04:19
2015-10-31T09:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
161
cpp
#include<bits/stdc++.h> using namespace std; int main() { string word; while(cin>>word) { word[0]=toupper(word[0]); cout<<word<<endl; } return 0; }
[ "munna93_bd@yahoo.com" ]
munna93_bd@yahoo.com
af51aa2a4bf1b3b0a3ad6467d64e06184904a9f1
cd28a35b77a4fe9ade88ab8a683d9ead2b780b10
/pms/catkin_ws/src/beginner_tutorials/src/talker.cpp
5de27c7bc19bc8ec523860bf17edf4b394951d17
[ "BSD-3-Clause" ]
permissive
smagri/uni_masters
e749b06cdb50a7438de4d429c2607a113566c774
7b3ce7d27f123f86d206eb58d08d9048081fa546
refs/heads/master
2022-11-19T10:11:35.731442
2020-07-23T04:09:21
2020-07-23T04:09:21
281,613,348
0
0
null
null
null
null
UTF-8
C++
false
false
537
cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include <sstream> int main(int argc, char **argv) { ros::init(argc, argv, "talker"); ros::NodeHandle n; ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000); ros::Rate loop_rate(10); int count = 0; while (ros::ok()) { std_msgs::String msg; std::stringstream ss; ss << "hello world " << count; msg.data = ss.str(); ROS_INFO("%s", msg.data.c_str()); chatter_pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++count; } return 0; }
[ "smagri@exemail.com.au" ]
smagri@exemail.com.au
56b319b37046e5ba6c6b375bf791c4013b0de354
d7a1b90af3a3e166e2be68afddada1aaaa355ee1
/geolib/csPositioning.h
823f8fee945ef76f08cad453d804b6d37c1eb862
[]
no_license
mkuric/SeismicDemo
566bdeb59cd812e92cfa8fb054668ba80d6ca7f4
3d64e37e4dc5486025ed4848577be1b34cc9afa0
refs/heads/master
2020-04-06T03:42:11.035453
2013-10-25T23:25:56
2013-10-25T23:25:56
13,783,631
1
1
null
null
null
null
UTF-8
C++
false
false
2,032
h
/* Copyright (c) Colorado School of Mines, 2013.*/ /* All rights reserved. */ struct PosParam { public: PosParam() : x(0), y(0), z(0), t(0), v(0) {} void dump() { fprintf(stdout,"%d %f %f %f %f %f\n",station,x,y,z,t,v); } PosParam( PosParam const& pos ) { station = pos.station; x = pos.x; y = pos.y; z = pos.z; t = pos.t; v = pos.v; } public: int station; double x; double y; double z; double t; double v; }; /** * Position source or receivers in OBS survey */ class csPositioning { public: static int const SOLVE_XYZ = 1; static int const SOLVE_XYZT = 2; static int const SOLVE_XYZV = 3; static int const SOLVE_XYZTV = 4; static int const SOLVE_XZ = 5; static int const SOLVE_XZT = 6; static int const SOLVE_XZV = 7; static int const SOLVE_XZTV = 8; public: csPositioning( int inversionType, int maxObs ); ~csPositioning(); // Provide initial velocity in variable x1.v // Provide first break times in variable x2.t /** * Process one location * @param x1 Approximate position of station to be solved. Provide initial velocity in field x1.v * @param x2 Positions of all stations of other domain. Provide estimated travel times in fields x2[].t * @param tdelay Time delay [s] * @param maxOffset Maximum source-receiver offset [m] Exclude all source-receiver pairs with higher offset * @param solution Computed position */ void process( int numObs, PosParam const& x1, PosParam const* x2, double tdelay, double maxOffset, PosParam& solution ); void dump( FILE* stream = stdout ) const; private: int myMaxObs; int myNumUnknowns; int myInversionType; int myIdX; int myIdY; int myIdZ; int myIdV; int myIdT; double** AA; double** mat_v; double* vec_work; double* vec_b; double* vec_w; double* vec_x2; void reallocate( int numObs ); }; } // end namespace #endif
[ "mumymania@gmail.com" ]
mumymania@gmail.com
7d1f49117b21954432c6dcecff59414ef5332d07
ce9eb3a881d5895c281e2cb90968c6bf55453b92
/src/TextureView.H
69ae5aa6dd8f3d0283e1b211bc752c5ce4106405
[]
no_license
CCCpeggy/Vector-To-Bitmap
f73f6d9975fa7d9f7b72f1c43b1c06862e63b245
47d43c2caeca77603266e24ca11a5dfeabc654d0
refs/heads/master
2022-12-26T03:51:52.843562
2020-09-15T10:55:58
2020-09-15T10:55:58
289,225,553
0
0
null
null
null
null
UTF-8
C++
false
false
734
h
#include "../Include/Common.h" #include "../Include/Shader/BasicTextureShader.h" #include "../Include/Shader/ScreentoneShader.h" #pragma once class TrainWindow; #pragma warning(push) #pragma warning(disable:4312) #pragma warning(disable:4311) #pragma warning(pop) class TextureView : public Fl_Gl_Window { public: // note that we keep the "standard widget" constructor arguments TextureView(int x, int y, int w, int h, const char* l = 0); // overrides of important window things virtual int handle(int); virtual void draw(); void openTexture(std::string); public: TrainWindow* tw; // The parent of this display window BasicTextureShader basicTeTextureShader; TextureData loadTex; bool firstDraw; };
[ "peggy19925@gmail.com" ]
peggy19925@gmail.com
547f9070524bc46c823eef05315489d8598e7cba
cd954f06232e3b9fe008f9a6291689e75f179a88
/BasicLevel_C++/1066. 图像过滤(15).cpp
bb0f46fc295127287f872bf21d36ecaaa113214e
[ "MIT" ]
permissive
upupming/algorithm
35446f4b15f3a505041ac65c1dc6f825951d8e99
a3807ba05960b9025e55d668ef95b3375ae71895
refs/heads/master
2023-08-09T03:07:18.047084
2023-08-01T05:57:13
2023-08-01T05:57:13
217,478,998
239
34
MIT
2021-08-13T05:42:26
2019-10-25T07:41:19
C++
UTF-8
C++
false
false
428
cpp
#include <iostream> using namespace std; int main() { int m, n, a, b, num, temp; scanf("%d%d%d%d%d", &m, &n, &a, &b, &num); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { scanf("%d", &temp); if (temp >= a && temp <= b) temp = num; if (j != 0) printf(" "); printf("%03d", temp); } printf("\n"); } return 0; }
[ "95323362@qq.com" ]
95323362@qq.com
9f8ae3e8f32d40a85686dc8397d5005444d746a1
cf9091e14a4490f8bac723f7cc0198d5277e6742
/QmlExtension/include/QmlExtension/Host.h
d29183a3f5f6d6b3d711c5f953a155ab6bc77bd4
[ "Apache-2.0" ]
permissive
wiphombear/cord.qml-extension
9bab44f6dd515a5b5b1a712ba6412b292b9b1b3f
1b156bbf44eabf7f691c6b1fee0f9fe0b2d87b3c
refs/heads/master
2023-03-18T04:06:46.366055
2018-11-14T08:27:56
2018-11-14T08:27:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
460
h
#pragma once #include <QtCore/QObject> #include <QtCore/QStringList> #include <QtQuick/QQuickItem> class Host : public QObject { Q_OBJECT public: explicit Host(QObject* parent = 0); virtual ~Host(); Q_INVOKABLE QStringList arguments(); Q_INVOKABLE QString hwid(bool async = false); signals: void hwidChanged(QString hwid); public: static Host *qmlAttachedProperties(QObject *obj); }; QML_DECLARE_TYPEINFO(Host, QML_HAS_ATTACHED_PROPERTIES)
[ "Clipeus@live.com" ]
Clipeus@live.com
6d23df60d03376b703655a8b4b7cc4dc13872776
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-backup/include/aws/backup/model/DescribeProtectedResourceRequest.h
88d34ac6d5598c52b7ef7fe75f22dfb9934d8916
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
3,286
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/backup/Backup_EXPORTS.h> #include <aws/backup/BackupRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Backup { namespace Model { /** */ class AWS_BACKUP_API DescribeProtectedResourceRequest : public BackupRequest { public: DescribeProtectedResourceRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DescribeProtectedResource"; } Aws::String SerializePayload() const override; /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline const Aws::String& GetResourceArn() const{ return m_resourceArn; } /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline bool ResourceArnHasBeenSet() const { return m_resourceArnHasBeenSet; } /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline void SetResourceArn(const Aws::String& value) { m_resourceArnHasBeenSet = true; m_resourceArn = value; } /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline void SetResourceArn(Aws::String&& value) { m_resourceArnHasBeenSet = true; m_resourceArn = std::move(value); } /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline void SetResourceArn(const char* value) { m_resourceArnHasBeenSet = true; m_resourceArn.assign(value); } /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline DescribeProtectedResourceRequest& WithResourceArn(const Aws::String& value) { SetResourceArn(value); return *this;} /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline DescribeProtectedResourceRequest& WithResourceArn(Aws::String&& value) { SetResourceArn(std::move(value)); return *this;} /** * <p>An Amazon Resource Name (ARN) that uniquely identifies a resource. The format * of the ARN depends on the resource type.</p> */ inline DescribeProtectedResourceRequest& WithResourceArn(const char* value) { SetResourceArn(value); return *this;} private: Aws::String m_resourceArn; bool m_resourceArnHasBeenSet; }; } // namespace Model } // namespace Backup } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
80708db00eecb0eba29d519a7ba786ec3654af70
b4f7073600455d0938d153a902e4e1a9d0b990ff
/basic_content/const/extern_const/const_file2.cpp
53729f431da3e9eb4ad9e195aa578e187735dfab
[]
no_license
Neflibatata/CPPThings
34784cb0d13b79484874e53e6f791a6448d283c2
52c5794f529396d438e447f5800836f56413cef5
refs/heads/master
2023-03-29T12:07:21.258987
2021-04-02T05:48:14
2021-04-02T05:48:14
353,918,825
5
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include<iostream> /** * by 光城 * compile: g++ -o file const_file2.cpp const_file1.cpp * execute: ./file */ extern const int ext; int main(){ std::cout<<ext<<std::endl; }
[ "1076119830@qq.com" ]
1076119830@qq.com
d88fa95c65bf7a65a2a8bed88e529e01182659ba
12d83468a3544af4e9d4f26711db1755d53838d6
/cplusplus_basic/Qt/boost/mpl/aux_/config/pp_counter.hpp
005114614a3851ac25ab0f1644c8c1c2131adce3
[]
no_license
ngzHappy/cxx17
5e06a31d127b873355cab3a8fe0524f1223715da
22d3f55bfe2a9ba300bbb65cfcbdd2dc58150ca4
refs/heads/master
2021-01-11T20:48:19.107618
2017-01-17T17:29:16
2017-01-17T17:29:16
79,188,658
1
0
null
null
null
null
UTF-8
C++
false
false
719
hpp
 #ifndef BOOST_MPL_AUX_CONFIG_PP_COUNTER_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_PP_COUNTER_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2006 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #if !defined(BOOST_MPL_AUX_PP_COUNTER) # include <Qt/boost/mpl/aux_/config/msvc.hpp> # if BOOST_WORKAROUND(BOOST_MSVC, >= 1300) # define BOOST_MPL_AUX_PP_COUNTER() __COUNTER__ # else # define BOOST_MPL_AUX_PP_COUNTER() __LINE__ # endif #endif #endif // BOOST_MPL_AUX_CONFIG_PP_COUNTER_HPP_INCLUDED
[ "819869472@qq.com" ]
819869472@qq.com
26ce63e46e5f6ca00344ecea1dcdeb704de4cb91
6a4083b2a404fd85c87f4938693b9eadcbbcbb44
/harj9/harj9.cpp
3c566febeea560ee683a3bb6d3c0427e2be94ed0
[]
no_license
pekka-m/harjoitus-09
ceec597f7dfd1fadd2d52f0564d6405de8a3908e
b9f2216ee6105171e5e410764c28dbf4652a9426
refs/heads/master
2021-01-16T19:43:36.141938
2013-10-01T13:21:37
2013-10-01T13:21:37
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,448
cpp
/********************************************************************* Tehtävä: HARJOITUS 9 Tekijä: Pekka Melgin PVM: 24.9.2013 Kuvaus: Tee ohjelma, joka toimii laskimena. Käyttäjältä kysytään kaksi kokonaislukua, jonka jälkeen ohjelma antaa valikon laskutoimituksista. Valikko nayttaa seuraavalta: VALIKKO 1. Summa 2. Erotus 3. Tulo 4. Osamaara 5. Jakojaannos Lopuksi ohjelma tulostaa valitun tuloksen naytölle. *********************************************************************/ #include <iostream> using namespace std; int main() { int luku1; int luku2; int lasku; float tulos; cout << "Anna luku 1: "; cin >> luku1; cout << "Anna luku 2: "; cin >> luku2; cout << "VALIKKO" << "\n1. Summa" << "\n2. Erotus" << "\n3. Tulo" << "\n4. Osam„„r„" << "\n5. Jakoj„„nn”s\n"; cin >> lasku; if (lasku == 1) { tulos = luku1 + luku2; cout << luku1 << " + " << luku2 << " = " << tulos; } else if (lasku == 2) { tulos = luku1 - luku2; cout << luku1 << " - " << luku2 << " = " << tulos; } else if (lasku == 3) { tulos = luku1 * luku2; cout << luku1 << " * " << luku2 << " = " << tulos; } else if (lasku == 4) { tulos = float(luku1) / float(luku2); cout << luku1 << " / " << luku2 << " = " << tulos; } else if (lasku == 5) { tulos = luku1 - luku2; cout << luku1 << " - " << luku2 << " = " << tulos; } cout << endl; }
[ "propeke@gmail.com" ]
propeke@gmail.com
420e1d9cdbea2a5a3ceb6855e5d2891187c78a51
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/shell/ext/cdfview/cdfview.cpp
3d4c7c59671147186a9559972d75df1ceac0cbeb
[]
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
5,653
cpp
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // cdfview.cpp // // IUnknown for the cdfview class. // // History: // // 3/16/97 edwardp Created. // //////////////////////////////////////////////////////////////////////////////// // // Includes // #include "stdinc.h" #include "cdfidl.h" #include "persist.h" #include "cdfview.h" #include "view.h" #include "xmlutil.h" #include "dll.h" // // Constructor and destructor. // //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // *** CCdfView::CCdfView *** // // Constructor. // //////////////////////////////////////////////////////////////////////////////// CCdfView::CCdfView ( void ) : CPersist(FALSE), // TRUE indicates cdf hasn't been parsed. m_cRef(1), m_fIsRootFolder(TRUE) { // // Memory allocs are assumed to be zero init'ed. // ASSERT(NULL == m_pcdfidl); ASSERT(NULL == m_pIXMLElementCollection); ASSERT(NULL == m_pidlPath); // // As long as this class is around the dll should stay loaded. // TraceMsg(TF_OBJECTS, "+ IShellFolder"); //TraceMsg(TF_ALWAYS, "+ IShellFolder %0x08d", this); DllAddRef(); return; } //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // *** CCdfView::CCdfView *** // // Constructor. // //////////////////////////////////////////////////////////////////////////////// CCdfView::CCdfView ( PCDFITEMIDLIST pcdfidl, LPCITEMIDLIST pidlParentPath, IXMLElementCollection* pParentIXMLElementCollection ) : CPersist(TRUE), // TRUE indicates cdf already parsed. m_cRef(1), m_fIsRootFolder(FALSE) { ASSERT(CDFIDL_IsValid(pcdfidl)); ASSERT(pParentIXMLElementCollection == NULL || XML_IsCdfidlMemberOf(pParentIXMLElementCollection, pcdfidl)); ASSERT(NULL == m_pidlPath); ASSERT(NULL == m_pIXMLElementCollection); // // Note that m_pidlPath, m_pcdfidl & m_pIXMLElementCollection could be // NULL in low memory conditions. // m_pcdfidl = (PCDFITEMIDLIST)ILCloneFirst((LPITEMIDLIST)pcdfidl); ASSERT(CDFIDL_IsValid(m_pcdfidl) || NULL == m_pcdfidl); ASSERT(ILIsEmpty(_ILNext((LPITEMIDLIST)m_pcdfidl)) || NULL == m_pcdfidl); m_pidlPath = ILCombine(pidlParentPath, (LPITEMIDLIST)m_pcdfidl); if (pParentIXMLElementCollection) { XML_GetChildElementCollection(pParentIXMLElementCollection, CDFIDL_GetIndexId(&pcdfidl->mkid), &m_pIXMLElementCollection); } // // As long as this class is around the dll should stay loaded. // TraceMsg(TF_OBJECTS, "+ IShellFolder %s", CDFIDL_GetName(pcdfidl)); //TraceMsg(TF_ALWAYS, "+ IShellFolder %0x08d", this); DllAddRef(); return; } //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // *** CCdfView::~CCdfView ** // // Destructor. // //////////////////////////////////////////////////////////////////////////////// CCdfView::~CCdfView ( void ) { ASSERT(0 == m_cRef); if (m_pidlPath) ILFree(m_pidlPath); if (m_pcdfidl) CDFIDL_Free(m_pcdfidl); if (m_pIXMLElementCollection) m_pIXMLElementCollection->Release(); // // Matching Release for the constructor Addref. // TraceMsg(TF_OBJECTS, "- IShellFolder"); //TraceMsg(TF_ALWAYS, "- IShellFolder %0x08d", this); DllRelease(); return; } // // IUnknown methods. // //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // *** CCdfView::QueryInterface ** // // Cdf view QI. // //////////////////////////////////////////////////////////////////////////////// STDMETHODIMP CCdfView::QueryInterface ( REFIID riid, void **ppv ) { ASSERT(ppv); HRESULT hr; *ppv = NULL; if (IID_IUnknown == riid || IID_IShellFolder == riid) { *ppv = (IShellFolder*)this; } else if (IID_IPersist == riid || IID_IPersistFile == riid) { *ppv = (IPersistFile*)this; } else if (IID_IPersistFolder == riid) { *ppv = (IPersistFolder*)this; } else if (IID_IPersistMoniker == riid) { *ppv = (IPersistMoniker*)this; } else if (IID_IOleObject == riid) { *ppv = (IOleObject*)this; } if (*ppv) { ((IUnknown*)*ppv)->AddRef(); hr = S_OK; } else { hr = E_NOINTERFACE; } ASSERT((SUCCEEDED(hr) && *ppv) || (FAILED(hr) && NULL == *ppv)); return hr; } //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // *** CCdfView::AddRef ** // // Cdf view AddRef. // //////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_(ULONG) CCdfView::AddRef ( void ) { ASSERT(m_cRef != 0); ASSERT(m_cRef < (ULONG)-1); return ++m_cRef; } //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ // // *** CCdfView::Release ** // // Cdf view Release. // //////////////////////////////////////////////////////////////////////////////// STDMETHODIMP_(ULONG) CCdfView::Release ( void ) { ASSERT (m_cRef != 0); ULONG cRef = --m_cRef; if (0 == cRef) delete this; return cRef; } #ifdef UNIX void unixEnsureFileScheme(TCHAR *pszIn) { if(pszIn && *pszIn == TEXT(FILENAME_SEPARATOR)) { TCHAR tmpBuffer[MAX_PATH]; int len = lstrlen(pszIn); lstrcpy(tmpBuffer,TEXT("file://")); lstrcat(tmpBuffer,pszIn); lstrcpy(pszIn,tmpBuffer); } } #endif /* UNIX */
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
b11219a5db8f8ba5a10c711d1c185f388d0c2b9d
09d43d2fe02a018f8fa851beda0c7aee01665cfa
/cmd_velsub/cmd_velsub.ino
853c79a6c8ef3df72b95dcd0366b968f50da7382
[]
no_license
kj-kx/lel-arduino-ros-cmd_vel
90e7500db510c49f7c8de4453541d9a0ae933e7c
e7f0a906cec0e7116be0bf112de4bd7df5450873
refs/heads/master
2023-07-26T17:32:19.407880
2021-09-14T08:03:59
2021-09-14T08:03:59
406,990,044
0
0
null
null
null
null
UTF-8
C++
false
false
568
ino
#include <ros.h> #include <std_msgs/String.h> #include <std_msgs/UInt16.h> #include<tf/transform_broadcaster.h> #include<nav_msgs/Odometry.h> #include<geometry_msgs/Twist.h> ros::NodeHandle nh; void Control(const geometry_msgs::Twist& cmd_vel) { Serial.println(cmd_vel.linear.x); Serial.println(cmd_vel.angular.z); } ros::Subscriber <geometry_msgs::Twist> sub("cmd_vel", &Control ); void setup() { nh.initNode(); nh.subscribe(sub);// subscribe Serial.begin(57600); } void loop() { nh.spinOnce(); delay(1000); }
[ "949921834@qq.com" ]
949921834@qq.com
794165dd3cdadb098e93f58accc7585ab242cf53
77bc7d5ee4b615a967b635d2ff745c3bc1121a5f
/AggroEngine/src/Graphics/OpenGL/Shaders/GLSLShader.hpp
1fe982e8e3a864e01d92ce0e59ce6ec6d0294421
[]
no_license
liuyirong/Aggro-Engine
ac87e926b26e5ace1539b9755911b9f7a03967e1
d5babd737b23e5742765f58b0f4af2380fee5d90
refs/heads/master
2020-06-11T03:46:46.470426
2016-12-09T04:11:10
2016-12-09T04:11:10
76,011,972
1
0
null
2016-12-09T07:23:04
2016-12-09T07:23:03
null
UTF-8
C++
false
false
738
hpp
#pragma once #include <string> #include "../../Graphics.hpp" /** * This GLSL shader class is based off the book "More OpenGL Game Programming." * * author: wcrane * since: 2013-12-28 **/ class GLSLShader { public: GLSLShader(const std::string &filename, GLenum shaderType = GL_VERTEX_SHADER); GLSLShader(GLenum shaderType = GL_VERTEX_SHADER ); ~GLSLShader(); void compile(); bool isCompiled() const; void getShaderLog(std::string &log) const; void getShaderSource(std::string &shader) const; void setShaderSource(std::string &code); GLuint getHandle() const; void getParameter(GLenum param, GLint *data) const; private: char *readShader(const std::string &filename); bool compiled_; GLint handle_; };
[ "wcrane15@gmail.com" ]
wcrane15@gmail.com
de2cd018373f7d05b7215eb8744f17ea0ced624d
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-config/include/aws/config/model/DeliveryChannelStatus.h
691a3c0b8fc55e8c29f0034f83875413cff87fda
[ "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
7,596
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/config/ConfigService_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/config/model/ConfigExportDeliveryInfo.h> #include <aws/config/model/ConfigStreamDeliveryInfo.h> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace ConfigService { namespace Model { /** * <p>The status of a specified delivery channel.</p> <p>Valid values: * <code>Success</code> | <code>Failure</code> </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/config-2014-11-12/DeliveryChannelStatus">AWS * API Reference</a></p> */ class AWS_CONFIGSERVICE_API DeliveryChannelStatus { public: DeliveryChannelStatus(); DeliveryChannelStatus(const Aws::Utils::Json::JsonValue& jsonValue); DeliveryChannelStatus& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of the delivery channel.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the delivery channel.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the delivery channel.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the delivery channel.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the delivery channel.</p> */ inline DeliveryChannelStatus& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the delivery channel.</p> */ inline DeliveryChannelStatus& WithName(Aws::String&& value) { SetName(value); return *this;} /** * <p>The name of the delivery channel.</p> */ inline DeliveryChannelStatus& WithName(const char* value) { SetName(value); return *this;} /** * <p>A list containing the status of the delivery of the snapshot to the specified * Amazon S3 bucket.</p> */ inline const ConfigExportDeliveryInfo& GetConfigSnapshotDeliveryInfo() const{ return m_configSnapshotDeliveryInfo; } /** * <p>A list containing the status of the delivery of the snapshot to the specified * Amazon S3 bucket.</p> */ inline void SetConfigSnapshotDeliveryInfo(const ConfigExportDeliveryInfo& value) { m_configSnapshotDeliveryInfoHasBeenSet = true; m_configSnapshotDeliveryInfo = value; } /** * <p>A list containing the status of the delivery of the snapshot to the specified * Amazon S3 bucket.</p> */ inline void SetConfigSnapshotDeliveryInfo(ConfigExportDeliveryInfo&& value) { m_configSnapshotDeliveryInfoHasBeenSet = true; m_configSnapshotDeliveryInfo = value; } /** * <p>A list containing the status of the delivery of the snapshot to the specified * Amazon S3 bucket.</p> */ inline DeliveryChannelStatus& WithConfigSnapshotDeliveryInfo(const ConfigExportDeliveryInfo& value) { SetConfigSnapshotDeliveryInfo(value); return *this;} /** * <p>A list containing the status of the delivery of the snapshot to the specified * Amazon S3 bucket.</p> */ inline DeliveryChannelStatus& WithConfigSnapshotDeliveryInfo(ConfigExportDeliveryInfo&& value) { SetConfigSnapshotDeliveryInfo(value); return *this;} /** * <p>A list that contains the status of the delivery of the configuration history * to the specified Amazon S3 bucket.</p> */ inline const ConfigExportDeliveryInfo& GetConfigHistoryDeliveryInfo() const{ return m_configHistoryDeliveryInfo; } /** * <p>A list that contains the status of the delivery of the configuration history * to the specified Amazon S3 bucket.</p> */ inline void SetConfigHistoryDeliveryInfo(const ConfigExportDeliveryInfo& value) { m_configHistoryDeliveryInfoHasBeenSet = true; m_configHistoryDeliveryInfo = value; } /** * <p>A list that contains the status of the delivery of the configuration history * to the specified Amazon S3 bucket.</p> */ inline void SetConfigHistoryDeliveryInfo(ConfigExportDeliveryInfo&& value) { m_configHistoryDeliveryInfoHasBeenSet = true; m_configHistoryDeliveryInfo = value; } /** * <p>A list that contains the status of the delivery of the configuration history * to the specified Amazon S3 bucket.</p> */ inline DeliveryChannelStatus& WithConfigHistoryDeliveryInfo(const ConfigExportDeliveryInfo& value) { SetConfigHistoryDeliveryInfo(value); return *this;} /** * <p>A list that contains the status of the delivery of the configuration history * to the specified Amazon S3 bucket.</p> */ inline DeliveryChannelStatus& WithConfigHistoryDeliveryInfo(ConfigExportDeliveryInfo&& value) { SetConfigHistoryDeliveryInfo(value); return *this;} /** * <p>A list containing the status of the delivery of the configuration stream * notification to the specified Amazon SNS topic.</p> */ inline const ConfigStreamDeliveryInfo& GetConfigStreamDeliveryInfo() const{ return m_configStreamDeliveryInfo; } /** * <p>A list containing the status of the delivery of the configuration stream * notification to the specified Amazon SNS topic.</p> */ inline void SetConfigStreamDeliveryInfo(const ConfigStreamDeliveryInfo& value) { m_configStreamDeliveryInfoHasBeenSet = true; m_configStreamDeliveryInfo = value; } /** * <p>A list containing the status of the delivery of the configuration stream * notification to the specified Amazon SNS topic.</p> */ inline void SetConfigStreamDeliveryInfo(ConfigStreamDeliveryInfo&& value) { m_configStreamDeliveryInfoHasBeenSet = true; m_configStreamDeliveryInfo = value; } /** * <p>A list containing the status of the delivery of the configuration stream * notification to the specified Amazon SNS topic.</p> */ inline DeliveryChannelStatus& WithConfigStreamDeliveryInfo(const ConfigStreamDeliveryInfo& value) { SetConfigStreamDeliveryInfo(value); return *this;} /** * <p>A list containing the status of the delivery of the configuration stream * notification to the specified Amazon SNS topic.</p> */ inline DeliveryChannelStatus& WithConfigStreamDeliveryInfo(ConfigStreamDeliveryInfo&& value) { SetConfigStreamDeliveryInfo(value); return *this;} private: Aws::String m_name; bool m_nameHasBeenSet; ConfigExportDeliveryInfo m_configSnapshotDeliveryInfo; bool m_configSnapshotDeliveryInfoHasBeenSet; ConfigExportDeliveryInfo m_configHistoryDeliveryInfo; bool m_configHistoryDeliveryInfoHasBeenSet; ConfigStreamDeliveryInfo m_configStreamDeliveryInfo; bool m_configStreamDeliveryInfoHasBeenSet; }; } // namespace Model } // namespace ConfigService } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
a04d8c0d80380bf8cd714cd1024d62a1cf48a30a
7ee8585aa5c1a9b1d6b4079629104eb1088fc410
/Matrix/src/Matrix.cpp
370d649fd54143423a4c15c48d614653b526b315
[ "MIT" ]
permissive
krishna2803/C-Projects
c3f6346ac3534849ad201163ff61d94bde03e048
8d9dbf298dc1ab13ae59feedf189032ca803a3ac
refs/heads/main
2023-07-12T06:22:13.395855
2021-08-16T15:30:58
2021-08-16T15:30:58
381,658,340
0
0
null
null
null
null
UTF-8
C++
false
false
10,866
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include "Matrix.hpp" // initilaize as a (rows x cols) matrix Matrix::Matrix(unsigned char rows, unsigned char cols) : rows(rows), cols(cols) { data = new float[rows * cols]; } // initilize as a square matrix Matrix::Matrix(unsigned char order) : rows(order), cols(order){ data = new float[order * order]; } // empty constructor so that // a matrix can be initialized as Matrix mat; // NOTE: REMEMBER to properly initilaize `mat` afterwards // it can cause segmentation faults if not done. Matrix::Matrix() { } Matrix::~Matrix() { // there's no need to delete [] data; } // create a matrix from a data Matrix::Matrix(unsigned char rows, unsigned char cols, void* data) : rows(rows), cols(cols) { this->data = (float*) data; } // get (row, col) element of this matrix float Matrix::get(unsigned char row, unsigned char col) const { return data[row*cols+col]; } // get [row-1][col-1] element of this matrix const float Matrix::operator()(unsigned char row, unsigned char col) const { row-=1; col-=1; return data[col*rows+col]; } // set (row, col) element of this matrix void Matrix::set(unsigned char row, unsigned char col, const float value) { data[row*cols+col] = value; } // set [row-1][col-1] element of this matrix float& Matrix::operator()(unsigned char row, unsigned char col) { row-=1; col-=1; return data[row*cols+col]; } // print this matrix to stdout void Matrix::print() const { for (unsigned char i = 0; i < rows; i++) { for (unsigned char j = 0; j < cols; j++) { printf("%.2f\t", get(i, j)); } printf("\n"); } } // convert this matrix to (const char*) // can be used for printing more than two decimal places Matrix::operator char*() const { // 12 bytes for each element (should be enough) char* buffer = new char[rows * cols * 12 + 1]; for (unsigned char i = 0; i < rows; i++) { for (unsigned char j = 0; j < cols; j++) { sprintf(buffer+strlen(buffer), "%f ", get(i, j)); } sprintf(buffer+strlen(buffer), "\n"); } sprintf(buffer+strlen(buffer), "\0"); return buffer; } // convert this matrix to (const char*) // can be used for printing more than two decimal places const char* Matrix::toString() { return (const char*) *this; } // return an (N x N) identity matrix Matrix Matrix::identity(unsigned char order) { Matrix mat(order, order); for (int i=0; i<order; i++) mat.set(i, i, 1.0f); return mat; } // return a random (rows x cols) normalised matrix // NOTE: random() is not seeded! Matrix Matrix::rand(unsigned char rows, unsigned char cols) { const float k_inverseRandMax = 1.0f / RAND_MAX; Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) mat.set(i, j, random()*k_inverseRandMax); return mat; } // return a random (order x order) normalised matrix // NOTE: random() is not seeded! Matrix Matrix::rand(unsigned char order) { return Matrix::rand(order, order); } // add a scalar to all elements Matrix Matrix::operator+(const float value) { Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) mat.set(i, j, get(i, j)+value); return mat; } // subtract scalar from all elements Matrix Matrix::operator-(const float value) { Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) mat.set(i, j, get(i, j)-value); return mat; } // multipy all elements of a matrix by some value Matrix Matrix::operator*(const float value) { Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) mat.set(i, j, get(i, j) * value); return mat; } // add two matrices Matrix Matrix::operator+(Matrix that) { if (this->rows != that.rows || this->cols != that.cols) { fprintf(stderr, "Dimension Mismatch (%ux%u) and (%ux%u).\n", this->rows, this->cols, that.rows, that.cols); throw "Dimension Mismatch.\n"; } Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) mat.set(i, j, this->get(i, j) + that.get(i, j)); return mat; } // subtract two matrices Matrix Matrix::operator-(Matrix that) { if (this->rows != that.rows || this->cols != that.cols) { fprintf(stderr, "Dimension Mismatch (%ux%u) and (%ux%u).\n", this->rows, this->cols, that.rows, that.cols); throw "Dimension Mismatch.\n"; } Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) mat.set(i, j, this->get(i, j) - that.get(i, j)); return mat; } // multiply two matrices // OPIMIZATIONS NEEDED Matrix Matrix::operator*(Matrix that) { if (this->cols != that.rows) { fprintf(stderr, "Dimension Mismatch (%ux%u) and (%ux%u).\n", this->rows, this->cols, that.rows, that.cols); throw "Dimension Mismatch.\n"; } Matrix mat(this->rows, that.cols); for (unsigned char i=0; i<mat.rows; i++) for (unsigned char j=0; j<mat.cols; j++) for (unsigned char k=0; k < cols; k++) mat.set(i,j,mat.get(i,j)+this->get(i, k)*that.get(k,j)); return mat; } // add a matrix to this matrix Matrix& Matrix::operator+=(Matrix that) { if (this->rows != that.rows || this->cols != that.cols) { fprintf(stderr, "Dimension Mismatch (%ux%u) and (%ux%u).\n", this->rows, this->cols, that.rows, that.cols); throw "Dimension Mismatch.\n"; } for (unsigned char i = 0; i < rows; i++) for (unsigned char j = 0; j < cols; j++) set(i, j, get(i, j) + that.get(i, j)); return *this; } // subtract a matrix from this matrix Matrix& Matrix::operator-=(Matrix that) { if (this->rows != that.rows || this->cols != that.cols) { fprintf(stderr, "Dimension Mismatch (%ux%u) and (%ux%u).\n", this->rows, this->cols, that.rows, that.cols); throw "Dimension Mismatch.\n"; } for (unsigned char i = 0; i < rows; i++) for (unsigned char j = 0; j < cols; j++) set(i, j, get(i, j) - that.get(i, j)); return *this; } // add a scalar to all elements of this matrix Matrix& Matrix::operator+=(const float value) { for (unsigned char i = 0; i < rows; i++) for (unsigned char j = 0; j < cols; j++) set(i, j, get(i, j)-value); return *this; } // subtract a scalar from all elements of this matrix Matrix& Matrix::operator-=(const float value) { for (unsigned char i = 0; i < rows; i++) for (unsigned char j = 0; j < cols; j++) set(i, j, get(i, j)-value); return *this; } // multiply all elements of this matrix by a scalar Matrix& Matrix::operator*=(const float value) { for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) set(i, j, get(i, j) * value); return *this; } // returns the minor (as a matrix) of an element in a matrix Matrix Matrix::minor(unsigned char row, unsigned char col) { if (cols != rows) { fprintf(stderr, "Cannot calculate minor of a non-square matrix"); throw "Non-square matrix\n"; } Matrix mat(rows-1, cols-1); unsigned char m_i=0, m_j=0; for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) { if (i == row || j == col) continue; mat.set(m_i, m_j++, get(i, j)); if (m_j == cols-1) { m_j = 0; m_i++; } } return mat; } // returns the transpose of this matrix Matrix Matrix::transpose() { Matrix mat(cols, rows); for (unsigned char i=0; i<mat.rows; i++) for (unsigned char j=0; j<mat.cols; j++) mat.set(i, j, get(j, i)); return mat; } // calculates and returns determinant of the matrix // OPIMIZATIONS NEEDED const float Matrix::determinant() { if (cols != rows) { fprintf(stderr, "Cannot calculate determinant of a non-square matrix"); throw "Non-square matrix\n"; } if (cols == 1) return get(0,0); if (cols == 2) return get(0,0)*get(1,1)-get(0,1)*get(1,0); if (cols == 3) return get(0,0)*(get(1,1)*get(2,2)-get(2,1)*get(1,2)) -get(0,1)*(get(1,0)*get(2,2)-get(2,0)*get(1,2)) +get(0,2)*(get(1,0)*get(2,1)-get(2,0)*get(1,1)); float det = 0.0f; for (unsigned char col=0; col<cols; col++) det += get(0, col) * minor(0, col).determinant() * (1-(col&1)*2); return det; } // calculates and returns adjoint of the matrix // OPIMIZATIONS NEEDED Matrix Matrix::adjoint() { if (cols != rows) { fprintf(stderr, "Cannot calculate adjoint of a non-square matrix"); throw "Non-square matrix\n"; } Matrix mat(rows, cols); for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) { // (i+j)&1 returns 1 if it is odd, 0 otherwise // (1-((i+j)&1)*2) => if (i+j) is even, multiply by 1 else multiply by -1 float val = minor(i, j).determinant() * (1-((i+j)&1)*2); if (val != 0.0f) mat.set(j, i, val); } return mat; } // calculates and returns inverse of the matrix // OPIMIZATIONS NEEDED Matrix Matrix::inverse() { if (cols != rows) { fprintf(stderr, "Cannot calculate inverse of a non-square matrix"); throw "Non-square matrix\n"; } float det = 0.0f; Matrix mat(rows, cols); if (rows == 1) { det = get(0, 0); if (det == 0.0f) { fprintf(stderr, "Cannot calculate inverse of a singular matrix"); throw "singular matrix\n"; } mat.set(0, 0, get(0, 0) / det); return mat; } if (rows == 2) { det = get(0,0)*get(1,1)-get(0,1)*get(1,0); if (det == 0.0f) { fprintf(stderr, "Cannot calculate inverse of a singular matrix"); throw "Singular matrix\n"; } mat.set(0, 0, get(1, 1)); mat.set(1, 1, get(0, 0)); mat.set(0, 1,-get(0, 1)); mat.set(1, 0,-get(1, 0)); mat *= 1.0f / det; return mat; } for (unsigned char i=0; i<rows; i++) for (unsigned char j=0; j<cols; j++) { // (i+j)&1 returns 1 if it is odd, 0 otherwise // (1-((i+j)&1)*2) => if (i+j) is even, multiply by 1 else multiply by -1 float val = minor(i, j).determinant()*(1-((i+j)&1)*2); if (!i) det += val * get(0, j); if (val != 0.0f) mat.set(j, i, val); } if (det == 0.0f) { fprintf(stderr, "Cannot calculate inverse of a singular matrix"); throw "Singular matrix\n"; } return mat * (1.0f / det); }
[ "kpandey81930@gmail.com" ]
kpandey81930@gmail.com
8d8991fb54fce661d2bc935a915b0a34cc24e166
9cd2ec7271d8e53e3c53b43ab5e7c88cefc38dab
/LearnOpenGL/Mesh.cpp
a915b930446dcafa4b5c442c066cb00bc8a735a1
[]
no_license
szneqz/SpiderGame_OpenGL
c25180fc6ab3fc9f90dcfa52703dc86032c61515
6c0084c87c7106bfbdd93ab6c4a37419e8680743
refs/heads/master
2021-03-27T04:44:57.168741
2020-03-17T07:43:49
2020-03-17T07:43:49
247,787,631
0
0
null
null
null
null
UTF-8
C++
false
false
3,764
cpp
#include "Mesh.h" Mesh::Mesh(vector<Vertex> vertic, vector<GLuint> ind, vector<Texture> textur, vector<VertexBoneData> bone_id_weights) { vertices = vertic; indices = ind; textures = textur; bones_id_weights_for_each_vertex = bone_id_weights; // Now that we have all the required data, set the vertex buffers and its attribute pointers. SetupMesh(); } Mesh::~Mesh() { //cout << " Mesh::~Mesh() " << endl; //glDeleteBuffers(1, &VBO_vertices); //glDeleteBuffers(1, &VBO_bones); //glDeleteBuffers(1, &EBO_indices); //glDeleteVertexArrays(1, &VAO); } void VertexBoneData::addBoneData(uint bone_id, float weight) { for (uint i = 0; i < NUM_BONES_PER_VEREX; i++) { if (weights[i] == 0.0) { ids[i] = bone_id; weights[i] = weight; return; } } } void Mesh::Draw(unsigned int shaders_program) { int diffuse_nr = 1; int specular_nr = 1; for (int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); string number; string name = textures[i].type; if (name == "texture_diffuse") { number = to_string(diffuse_nr++); } else if (name == "texture_specular") { number = to_string(specular_nr++); } glBindTexture(GL_TEXTURE_2D, textures[i].id); glUniform1i(glGetUniformLocation(shaders_program, ("material." + name + number).c_str()), i); //cout << "added in shader : " << ("material." + name + number).c_str() << endl; } //glUniform1f(glGetUniformLocation(shaders_program, "material.shininess"), 32.0f); //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); //glLineWidth(2); //Draw glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); for (int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } void Mesh::SetupMesh() { //vertices data glGenBuffers(1, &VBO_vertices); glBindBuffer(GL_ARRAY_BUFFER, VBO_vertices); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //bones data glGenBuffers(1, &VBO_bones); glBindBuffer(GL_ARRAY_BUFFER, VBO_bones); glBufferData(GL_ARRAY_BUFFER, bones_id_weights_for_each_vertex.size() * sizeof(bones_id_weights_for_each_vertex[0]), &bones_id_weights_for_each_vertex[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); //numbers for sequence indices glGenBuffers(1, &EBO_indices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO_indices); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // create VAO and binding data from buffers to shaders glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO_vertices); //vertex position glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0); glEnableVertexAttribArray(1); // offsetof(Vertex, normal) = returns the byte offset of that variable from the start of the struct glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, text_coords)); glBindBuffer(GL_ARRAY_BUFFER, 0); //bones glBindBuffer(GL_ARRAY_BUFFER, VBO_bones); glEnableVertexAttribArray(3); glVertexAttribIPointer(3, 4, GL_INT, sizeof(VertexBoneData), (GLvoid*)0); // for INT Ipointer glEnableVertexAttribArray(4); glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(VertexBoneData), (GLvoid*)offsetof(VertexBoneData, weights)); glBindBuffer(GL_ARRAY_BUFFER, 0); //indices glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO_indices); glBindVertexArray(0); }
[ "crashday3@o2.pl" ]
crashday3@o2.pl
ba824d16b0bf61ee7ba0767e27fcdbce8b13b961
c74b0548a1fc3eb9841a56a9dbbeb0404ac5c5db
/src/population.cpp
4d965a352a544eddb2e5721018ece0cb152bed09
[]
no_license
bingheGT/heuristic-optimization
81feccb8e6340c68de3734a99c617b276293abcb
d2dc425b9c7fe84a7f6e7d8468cae1df56ee3988
refs/heads/master
2020-07-21T17:07:16.873765
2017-09-06T07:33:58
2017-09-06T07:33:58
206,927,593
0
1
null
2019-09-07T06:42:26
2019-09-07T06:42:26
null
UTF-8
C++
false
false
3,726
cpp
/*************************************************************************** * Copyright (C) 2012 by Jérémie Dubois-Lacoste * * jeremie.dl@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <iostream> #include <fstream> #include <cmath> #include <string> #include <cstring> #include <algorithm> // std::sort #include <vector> // std::vector #include "pfspinstance.h" #include "solution.h" #include "iteratedgreedysearch.h" #include "population.h" #include "neighborhood.h" #include <chrono> using namespace std; Population::Population() { /* initialize random seed: */ // srand ( time(NULL) ); } Population::~Population() { } Solution& Population::get_parent(int solution_index){ return population[solution_index]; } long int Population::get_minimum_wct(){ return minimum_wct; } void Population::set_parent(int solution_index,Solution& new_solution){ population[solution_index] = new_solution; }; Solution& Population::get_best_parent(){ return population[best_parent]; } /* Evaluate the solutions in the population*/ void Population::evaluate(){ minimum_wct = instance.computeWCT(population[1]); best_parent = 1; //The initial parents are sorted in a multimap according to their minimum WCT sorted_parents.insert(pair<long int, int>(minimum_wct,best_parent)); for(int parent = 2; parent < population.size();parent++){ // Calculate the WCT of the solution/parent/chromosome long int wct = instance.computeWCT(population[parent]); if(wct < minimum_wct){ minimum_wct = wct; best_parent = parent; } //Insert the WCT value of the parent into a sorted map sorted_parents.insert(pair<long int, int>(wct,parent)); } } int Population::get_parent_job(int parent,int sequence){ return population[parent].get_job(sequence); } /* Generate the initial population */ void Population::initialize(){ /* Generate the first chromosome/solution according to the Liu and Reeves composite heuristic and calculate the WCT of the solution */ Solution individual_chromosome(instance.getNbJob()+1); individual_chromosome.advanced_rz_heuristic(instance,instance.getNbJob()); population[1] = individual_chromosome; /* Generate the other chromosomes randomly and calculate the WCT of the solution*/ for(int parent = 2; parent <= size;parent++){ Solution individual_chromosome(instance.getNbJob()+1); individual_chromosome.randomPermutation(); population[parent] = individual_chromosome; } }
[ "kenzoclauw@gmail.com" ]
kenzoclauw@gmail.com
4145ac7858aa684b1db2d3b0f15a800042c96b1d
5f19b7de1837b279d1eff9bac7c40036650042d1
/Chapter 9/9/9.cpp
c1c9ebef22a1da1b9f539fcf11335473904b0cb9
[]
no_license
sureshyhap/C-plus-plus-Primer
96cf75ca45242e2e39b543440b1c966b30048823
cbe7f0cb456725701c93b030a7c2dc1312ce991f
refs/heads/master
2021-07-05T15:55:42.018561
2020-11-09T20:35:32
2020-11-09T20:35:32
203,446,674
0
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
/* begin() returns a const iterator only if the object is const (otherwise it returns an iterator). cbegin() always returns a const_iterator. */
[ "sureshyhap@gmail.com" ]
sureshyhap@gmail.com
5e4023b27271c70911ccdddb094c1a3d95d7bd3b
02be4b886657442e3b491f41f186dcf3ba508135
/src/main/DataStructure/Any.cpp
363f33c67daa45ea6a3436f676b4857ba2820e2e
[]
no_license
Axure/Game-of-Life-Framework
76e6bf1ae9e01af6c962fe8cedde6bc251ed6034
d0223b6432fad4009f62e8dc3b70fd114c85cd92
refs/heads/master
2021-05-02T10:36:36.481500
2016-03-06T09:16:45
2016-03-06T09:16:45
53,260,939
2
0
null
null
null
null
UTF-8
C++
false
false
60
cpp
// // Created by 郑虎 on 2016-02-12. // #include "Any.h"
[ "axurez@vip.qq.com" ]
axurez@vip.qq.com
ab8afeb02445c9f329d6c43a0869bd38ad1726c7
82fb4b3a5bd3c47603ab97144815643ff2e92610
/C++/165. Compare Version Numbers/main.cpp
864b3ea95eb9aa7735712a8647a90e430c7b1900
[ "MIT" ]
permissive
wenqf11/LeetCode
a0f267f21193c1c9710ba4d570ae39f7467afac8
27b464044ecca8933127d1e82fa4973318d7c404
refs/heads/master
2020-04-18T02:59:01.024339
2017-10-10T03:06:28
2017-10-10T03:06:28
67,712,807
0
0
null
null
null
null
UTF-8
C++
false
false
137
cpp
#include <iostream> #include "solution.h" // Unit Test int main() { Solution s; cout << s.compareVersion("1", "1.0.0"); return 0; }
[ "qingfu.wen@gmail.com" ]
qingfu.wen@gmail.com
c6f5566558423422500a673ac102bc33d64788e2
9425b49470913fb7d6df65f1e1e23076938628c0
/01_week/lab/ex_a.cpp
24ac7f9542fc9ef884ffc4a52eef6ded69269065
[]
no_license
ramanqul/pp1-2019-fall
a3a456681b6aac322eaaf5d0d69405af798e6632
55b5701ece13563629d1088dc9fe8f08a953a158
refs/heads/master
2020-07-15T06:13:51.266168
2019-11-17T11:54:40
2019-11-17T11:54:40
205,497,935
2
4
null
null
null
null
UTF-8
C++
false
false
172
cpp
#include <iostream> #include <cmath> using namespace std; int main() { int a; int b; cin >> a; cin >> b; double h = sqrt(a*a + b*b); cout << h; return 0; }
[ "buzaubakov.raman@gmail.com" ]
buzaubakov.raman@gmail.com
768c2b5718b7e259982aaaef69f73a487530eb3c
e5ec93a45eecf20095d52d013dd1f94e293aa48b
/CSBase/InitCSBase.h
aaa70576b3ecf171ae288da0b9a831f871738e22
[]
no_license
Ethan-Zhou/Portrait
6342f13e5263fe735f12801140e36adc5772123c
9b8cc97d470274c1a57656f61d06bf7dd9972b21
refs/heads/master
2020-12-29T00:41:36.816002
2013-03-10T08:21:26
2013-03-10T08:21:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#ifndef __CSBASE_INITCSBASE_H__ #define __CSBASE_INITCSBASE_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 class CSBASE_API CInitCSBase { public: CInitCSBase(void); ~CInitCSBase(void); bool Init(void); void DeInit(void); }; CSBASE_API CInitCSBase *PInitCSBase(void); #endif __CSBASE_INITCSBASE_H__
[ "fish_wsr@hotmail.com" ]
fish_wsr@hotmail.com
d57b257c50488d914fe50fe52c1f71e07d95bbdb
b33a9177edaaf6bf185ef20bf87d36eada719d4f
/qtbase/tests/auto/corelib/thread/qreadlocker/tst_qreadlocker.cpp
927e48cf699ce7c9fefc2ed728168f99d14fe10f
[ "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-commercial-license", "LGPL-2.0-or-later", "LGPL-2.1-only", "GFDL-1.3-only", "LicenseRef-scancode-qt-commercial-1.1", "LGPL-3.0-only", "LicenseRef-scancode-qt-company-exception-lgpl-2.1", ...
permissive
wgnet/wds_qt
ab8c093b8c6eead9adf4057d843e00f04915d987
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
refs/heads/master
2021-04-02T11:07:10.181067
2020-06-02T10:29:03
2020-06-02T10:34:19
248,267,925
1
0
Apache-2.0
2020-04-30T12:16:53
2020-03-18T15:20:38
null
UTF-8
C++
false
false
5,136
cpp
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QCoreApplication> #include <QReadLocker> #include <QSemaphore> #include <QThread> class tst_QReadLockerThread : public QThread { public: QReadWriteLock lock; QSemaphore semaphore, testSemaphore; void waitForTest() { semaphore.release(); testSemaphore.acquire(); } }; class tst_QReadLocker : public QObject { Q_OBJECT public: tst_QReadLockerThread *thread; void waitForThread() { thread->semaphore.acquire(); } void releaseThread() { thread->testSemaphore.release(); } private slots: void scopeTest(); void unlockAndRelockTest(); void lockerStateTest(); }; void tst_QReadLocker::scopeTest() { class ScopeTestThread : public tst_QReadLockerThread { public: void run() { waitForTest(); { QReadLocker locker(&lock); waitForTest(); } waitForTest(); } }; thread = new ScopeTestThread; thread->start(); waitForThread(); // lock should be unlocked before entering the scope that creates the QReadLocker QVERIFY(thread->lock.tryLockForWrite()); thread->lock.unlock(); releaseThread(); waitForThread(); // lock should be locked by the QReadLocker QVERIFY(!thread->lock.tryLockForWrite()); releaseThread(); waitForThread(); // lock should be unlocked when the QReadLocker goes out of scope QVERIFY(thread->lock.tryLockForWrite()); thread->lock.unlock(); releaseThread(); QVERIFY(thread->wait()); delete thread; thread = 0; } void tst_QReadLocker::unlockAndRelockTest() { class UnlockAndRelockThread : public tst_QReadLockerThread { public: void run() { QReadLocker locker(&lock); waitForTest(); locker.unlock(); waitForTest(); locker.relock(); waitForTest(); } }; thread = new UnlockAndRelockThread; thread->start(); waitForThread(); // lock should be locked by the QReadLocker QVERIFY(!thread->lock.tryLockForWrite()); releaseThread(); waitForThread(); // lock has been explicitly unlocked via QReadLocker QVERIFY(thread->lock.tryLockForWrite()); thread->lock.unlock(); releaseThread(); waitForThread(); // lock has been explicitly relocked via QReadLocker QVERIFY(!thread->lock.tryLockForWrite()); releaseThread(); QVERIFY(thread->wait()); delete thread; thread = 0; } void tst_QReadLocker::lockerStateTest() { class LockerStateThread : public tst_QReadLockerThread { public: void run() { { QReadLocker locker(&lock); locker.relock(); locker.unlock(); waitForTest(); } waitForTest(); } }; thread = new LockerStateThread; thread->start(); waitForThread(); // even though we relock() after creating the QReadLocker, it shouldn't lock the lock more than once QVERIFY(thread->lock.tryLockForWrite()); thread->lock.unlock(); releaseThread(); waitForThread(); // if we call QReadLocker::unlock(), its destructor should do nothing QVERIFY(thread->lock.tryLockForWrite()); thread->lock.unlock(); releaseThread(); QVERIFY(thread->wait()); delete thread; thread = 0; } QTEST_MAIN(tst_QReadLocker) #include "tst_qreadlocker.moc"
[ "p_pavlov@wargaming.net" ]
p_pavlov@wargaming.net
fa8c4a8305bcbd8a5d588614eef960106297b58b
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_WaterTankBaseBP_parameters.hpp
b47c132d1c4771ed30ab1da02c5b28bd72dcdd33
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
823
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_WaterTankBaseBP_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function WaterTankBaseBP.WaterTankBaseBP_C.UserConstructionScript struct AWaterTankBaseBP_C_UserConstructionScript_Params { }; // Function WaterTankBaseBP.WaterTankBaseBP_C.ExecuteUbergraph_WaterTankBaseBP struct AWaterTankBaseBP_C_ExecuteUbergraph_WaterTankBaseBP_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
befcda5e11960ea2e098905b1e7fb59b6eb46502
f236af50bd31796471fbf4b9c1757d2b8b600af7
/external/embree/kernels/common/builder.h
2747f898ce137da495f6cc0f573eac5c0788abeb
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "IJG" ]
permissive
fly2mars/suCAM
742a4cd2db19829616a47e78c1d56ed0bceee42b
20581f4545684bb7b62ac32059f6031aa5b27f0d
refs/heads/master
2023-04-07T06:53:17.218649
2023-03-29T08:50:04
2023-03-29T08:50:04
153,613,947
8
13
null
null
null
null
UTF-8
C++
false
false
2,903
h
// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // 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. // // ======================================================================== // #pragma once #include "default.h" #include "accel.h" namespace embree { #define MODE_HIGH_QUALITY (1<<8) /*! virtual interface for all hierarchy builders */ class Builder : public RefCount { public: static const size_t DEFAULT_SINGLE_THREAD_THRESHOLD = 1024; /*! initiates the hierarchy builder */ virtual void build() = 0; /*! notifies the builder about the deletion of some geometry */ virtual void deleteGeometry(size_t geomID) {}; /*! clears internal builder state */ virtual void clear() = 0; }; /*! virtual interface for progress monitor class */ struct BuildProgressMonitor { virtual void operator() (size_t dn) const = 0; }; /*! build the progress monitor interface from a closure */ template<typename Closure> struct ProgressMonitorClosure : BuildProgressMonitor { public: ProgressMonitorClosure (const Closure& closure) : closure(closure) {} void operator() (size_t dn) const { closure(dn); } private: const Closure closure; }; template<typename Closure> __forceinline const ProgressMonitorClosure<Closure> BuildProgressMonitorFromClosure(const Closure& closure) { return ProgressMonitorClosure<Closure>(closure); } struct LineSegments; struct TriangleMesh; struct QuadMesh; class AccelSet; class Scene; typedef void (*createLineSegmentsAccelTy)(LineSegments* mesh, AccelData*& accel, Builder*& builder); typedef void (*createTriangleMeshAccelTy)(TriangleMesh* mesh, AccelData*& accel, Builder*& builder); typedef void (*createQuadMeshAccelTy)(QuadMesh* mesh, AccelData*& accel, Builder*& builder); typedef void (*createAccelSetAccelTy)(AccelSet* mesh, AccelData*& accel, Builder*& builder); }
[ "fly2mars@hotmail.com" ]
fly2mars@hotmail.com
074ab8545d4d57db97e6c9efa6e93d1eb6592848
57bb2514afa46105bb2e9018b374064e3b2ec7b7
/src/main.cpp
427bc80e8f0690b2a8a3bf4520e12972d7fcdafd
[]
no_license
diegowald/bloque05
bd099d30c4d8df5bb42fd3a7366f91e90c101612
5de432e88e2aace6665a4a911263b8f8d060f85e
refs/heads/master
2021-01-17T13:28:44.979209
2016-05-30T19:10:42
2016-05-30T19:10:42
6,578,499
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
//#include <QtGui/QApplication> #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
[ "diego.wald@gmail.com" ]
diego.wald@gmail.com
4e29cdc95b812e020eedb3d06fb60f98ae60277b
77ced4adcd029eea24fcde23ac3c4e27e465718e
/main.cpp
0a973a89bf3296d58e8b7005da710bae98a9cf50
[]
no_license
rollingstone/PIC32-Thermal-Controller
f5051ef97ac12b66d9bf0dbf3232133c540a825e
a643232e83722cca442c57ce7ab5aa2ae93f1fd9
refs/heads/master
2021-01-11T19:01:05.156576
2017-01-18T11:23:40
2017-01-18T11:23:40
79,292,434
1
1
null
null
null
null
UTF-8
C++
false
false
4,832
cpp
/* * File: main.cpp * Author: kamal * * Created on November 3, 2015, 2:04 PM */ #define _SUPPRESS_PLIB_WARNING #define _DISABLE_OPENADC10_CONFIGPORT_WARNING #include "TemperatureController.h" #include <cstdlib> #include <plib.h> #include <stdint.h> #include <xc.h> #include <time.h> //#include <filesystem> //#include <S> #include <xc.h> // DEVCFG3 // USERID = No Setting #pragma config FSRSSEL = PRIORITY_7 // Shadow Register Set Priority Select (SRS Priority 7) #pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations) #pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations) #pragma config FUSBIDIO = ON // USB USID Selection (Controlled by the USB Module) #pragma config FVBUSONIO = ON // USB VBUS ON Selection (Controlled by USB Module) // DEVCFG2 // with HS as osc source // base closk 8MHz #pragma config FPLLIDIV = DIV_1 // PLL Input Divider (2x Divider) #pragma config FPLLMUL = MUL_20 // PLL Multiplier (20x Multiplier) #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (PLL Divide by 1) #pragma config POSCMOD = HS // Primary Oscillator Configuration (HS osc mode) #pragma config UPLLIDIV = DIV_12 // USB PLL Input Divider (12x Divider) #pragma config UPLLEN = OFF // USB PLL Enable (Disabled and Bypassed) //// DEVCFG2 // with XT as osc source //#pragma config FPLLIDIV = DIV_1 // PLL Input Divider (2x Divider) //#pragma config FPLLMUL = MUL_20 // PLL Multiplier (20x Multiplier) //#pragma config UPLLIDIV = DIV_12 // USB PLL Input Divider (12x Divider) //#pragma config UPLLEN = OFF // USB PLL Enable (Disabled and Bypassed) //#pragma config FPLLODIV = DIV_1 // System PLL Output Clock Divider (PLL Divide by 1) //#pragma config POSCMOD = XT // Primary Oscillator Configuration (HS osc mode) // DEVCFG1 #pragma config FNOSC = PRIPLL // Oscillator Selection Bits (Primary Osc w/PLL (XT+,HS+,EC+PLL)) #pragma config FSOSCEN = ON // Secondary Oscillator Enable (Enabled) #pragma config IESO = ON // Internal/External Switch Over (Enabled) #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled) #pragma config FPBDIV = DIV_1 // Peripheral Clock Divisor (Pb_Clk is Sys_Clk/2) #pragma config FCKSM = CSDCMD // Clock Switching and Monitor Selection (Clock Switch Disable, FSCM Disabled) #pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576) #pragma config WINDIS = OFF // Watchdog Timer Window Enable (Watchdog Timer is in Non-Window Mode) #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled (SWDTEN Bit Controls)) //#pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window Size is 25%) // DEVCFG0 #pragma config DEBUG = ON // Background Debugger Enable (Debugger is Enabled) #pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled) #pragma config ICESEL = ICS_PGx2 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1) #pragma config PWP = OFF // Program Flash Write Protect (Disable) #pragma config BWP = OFF // Boot Flash Write Protect bit (Protection Disabled) #pragma config CP = OFF // Code Protect (Protection Disabled) using namespace std; // //void WaitMS(int ms) //{ // uint32_t ms_count = (100000L/(25*4)*8L); // // while(ms_count-- >= 0) // { // } //} //inline float ConvertToLSDTemp(int value) //{ // return (float)value * (0.3125); //} /* * */ int main(int argc, char* argv[]) { // if a system reset is required comment out the following line and run the program // SYSTEM_SOFT_RESET(); uint32_t timer_freq = 5;//Hz InitSystem(); InitTimer1(timer_freq); TemperatureSystemInit(); // ***************** The following commented out function calls perform // various tests. Used mainly for debug purposed // // TestSPi2Slave(); // TestHyperADC_SPI2Slave_Read(); // TestSPI1Master_To_SPI2SlaveData_Transfer(8L*1000000L); // TestSPi2Slave(); // Test_SPI2Slave_DataTransfer(); // Test_SPI2Slave_DataTransferWithUART1(); // Test_SPI2Slave_DataTransferWith_SPI2Command(); // ReadSPI2Slave_test(); // TestSPI1_Master(); // SPI1_TempMeasurement_LM_Thermo_Test(); // SPI1_TempMeasurement_Test(); // TestUART2DataSendToRaspberryPi(); // TestSPi2Slave_WithSendData_WithSPI2Command(); // TestSPi2Slave_WithSendData(); // InitPWM(1500,20); // SetPWMDutyCycle(1, 30); AdjustTemperature(27.0); return 0; }
[ "neo_zenith@yahoo.com" ]
neo_zenith@yahoo.com
b885f24a528f179a5824b80529fdf32864c300d9
6dcda687bc386b58c6391d150a3816adf43c7cea
/SDK/Magazine_AK12_classes.h
a968c55682c62315724811adcf33c60cd153f4ee
[]
no_license
firebiteLR/PavlovVR-SDK
813f49c03140c46c318cae15fd5a03be77a80c05
0d31dec9aa671f0e9a2fbc37a9be34a9854e06a4
refs/heads/master
2023-07-23T11:28:43.963982
2021-02-18T15:06:38
2021-02-18T15:06:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
908
h
#pragma once // Name: , Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Magazine_AK12.Magazine_AK12_C // 0x0008 (0x0548 - 0x0540) class AMagazine_AK12_C : public AMagazine_Base_C { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0540(0x0008) (ZeroConstructor, Transient, DuplicateTransient) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Magazine_AK12.Magazine_AK12_C"); return ptr; } void UserConstructionScript(); void OnReleasedFromGun(); void ExecuteUbergraph_Magazine_AK12(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "albertarlington21@gmail.com" ]
albertarlington21@gmail.com
ab96f83c599c1bf4c981d98149b1db1e7cb03a56
9f47c35857c02b39e6749bf667ae1396edbb7b0e
/ble/peripheral.cpp
370d1ea5da021d886909f791a5591b0c09e8a1b8
[]
no_license
troystribling/hue-switch-arduino
97614df206aa8bdeb58b3413eece913af9fd3139
c84ddc40c53ef852000ab039ceb3e8537468722d
refs/heads/master
2020-05-16T21:13:15.245164
2014-06-03T15:08:56
2014-06-03T15:08:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,025
cpp
#include "utils.h" #include "blue_cap_peripheral.h" #include "home_i2c_master.h" #include "peripheral.h" #include "services.h" #define EEPROM_OFFSET 32 static services_pipe_type_mapping_t services_pipe_type_mapping[NUMBER_OF_PIPES] = SERVICES_PIPE_TYPE_MAPPING_CONTENT; static hal_aci_data_t setup_msgs[NB_SETUP_MESSAGES] PROGMEM = SETUP_MESSAGES_CONTENT; Peripheral::Peripheral(uint8_t _reqn, uint8_t _rdyn, uint8_t _maxBonds, uint16_t _updatePeriod) : BlueCapBondedPeripheral(_reqn, _rdyn, EEPROM_OFFSET, _maxBonds), shouldInit(true), updatePeriod(_updatePeriod), stateObjectEEPROM(EEPROMObject<StateObject>(NUMBER_OF_STATE_OBJECTS_OFFSET, MAX_NUMBER_OF_STATE_OBJECTS)) { setServicePipeTypeMapping(services_pipe_type_mapping, NUMBER_OF_PIPES); setSetUpMessages(setup_msgs, NB_SETUP_MESSAGES); } void Peripheral::begin() { DBUG_LOG(F("Peripheral::begin")); BlueCapBondedPeripheral::begin(); } void Peripheral::loop() { if (millis() % updatePeriod == 0) { i2cMaster->wifiStatus(); } BlueCapBondedPeripheral::loop(); } // callbacks void Peripheral::didReceiveData(uint8_t characteristicId, uint8_t* data, uint8_t size) { switch(characteristicId) { case PIPE_LOCATION_LATITUDE_AND_LONGITUDE_RX_ACK: DBUG_LOG(F("PIPE_LOCATION_LATITUDE_AND_LONGITUDE_RX_ACK")); setLocation(data); break; case PIPE_HUE_LIGHTS_HUE_SWITCH_RX_ACK: DBUG_LOG(F("PIPE_HUE_LIGHTS_HUE_SWITCH_RX_ACK")); setSwitch(data); break; case PIPE_HUE_LIGHTS_HUE_SCENE_NAME_RX_ACK: DBUG_LOG(F("PIPE_HUE_LIGHTS_HUE_SCENE_NAME_RX_ACK")); setSceneName(data, size); break; case PIPE_HUE_LIGHTS_CURRENT_HUE_SCENE_ID_RX_ACK: DBUG_LOG(F("PIPE_HUE_LIGHTS_CURRENT_HUE_SCENE_ID_RX_ACK")); setCurrentSceneId(data); break; case PIPE_HUE_LIGHTS_HUE_LIGHT_COLOR_RX_ACK: DBUG_LOG(F("PIPE_HUE_LIGHTS_HUE_LIGHT_COLOR_RX_ACK")); setLightColor(data); break; case PIPE_HUE_LIGHTS_HUE_LIGHTS_COMMAND_RX_ACK: DBUG_LOG(F("PIPE_HUE_LIGHTS_HUE_LIGHTS_COMMAND_RX_ACK")); setCommand(data); break; default: break; } } void Peripheral::didReceiveCommandResponse(uint8_t commandId, uint8_t* data, uint8_t size) { switch(commandId) { case ACI_CMD_CONNECT: DBUG_LOG(F("ACI_CMD_CONNECT response received")); break; case ACI_CMD_GET_DEVICE_VERSION: DBUG_LOG(F("ACI_CMD_GET_DEVICE_VERSION response received")); break; case ACI_CMD_SET_LOCAL_DATA: DBUG_LOG(F("ACI_CMD_SET_LOCAL_DATA response received")); break; case ACI_CMD_SEND_DATA: DBUG_LOG(F("ACI_CMD_SEND_DATA response received")); break; case ACI_CMD_SEND_DATA_ACK: DBUG_LOG(F("ACI_CMD_SEND_DATA_ACK response received")); break; case ACI_CMD_SEND_DATA_NACK: DBUG_LOG(F("ACI_CMD_SEND_DATA_NACK response received")); break; case ACI_CMD_CHANGE_TIMING: DBUG_LOG(F("ACI_CMD_CHANGE_TIMING response received")); break; default: break; } } void Peripheral::didDisconnect() { DBUG_LOG(F("didDisconnect")); } void Peripheral::didTimeout() { } void Peripheral::didConnect() { DBUG_LOG(F("didConnect")); } void Peripheral::didStartAdvertising() { } void Peripheral::didReceiveError(uint8_t pipe, uint8_t errorCode) { } void Peripheral::didReceivePipeStatusChange() { } void Peripheral::didBond() { } bool Peripheral::doTimingChange() { } // acks void Peripheral::sendMessageNack(uint8_t messageID) { switch (messageID) { case HUE_LIGHTS_ALL_LIGHTS_ON_CMD: sendNack(PIPE_HUE_LIGHTS_HUE_SWITCH_RX_ACK, HUE_LIGHTS_ERROR); break; case HUE_LIGHTS_CREATE_SCENE_CMD: break; case HUE_LIGHTS_UPDATE_SCENE_CMD: break; case HUE_LIGHTS_REMOVE_SCENE_CMD: break; case HUE_LIGHTS_NEXT_SCENE_CMD: break; case HUE_LIGHTS_GET_SCENE_NAME_CMD: break; case HUE_LIGHTS_SET_SCENE_NAME_CMD: break; case HUE_LIGHTS_GET_SCENE_ID_CMD: break; case HUE_LIGHTS_GET_SCENE_CMD: break; case HUE_LIGHTS_GET_CURRENT_SCENE_ID_CMD: break; case HUE_LIGHTS_SET_CURRENT_SCENE_CMD: break; case HUE_LIGHTS_GET_LIGHT_COLOR_CMD: break; case HUE_LIGHTS_SET_LIGHT_COLOR_CMD: break; case HUE_LIGHTS_GET_LIGHT_COUNT_CMD: break; case HUE_LIGHTS_SET_LIGHT_COUNT_CMD: break; case HUE_LIGHTS_GET_SCENE_COUNT_CMD: break; case HUE_LIGHTS_ERASE_EEPROM_CMD: break; default: ERROR_LOG(F("(Peripheral::sendNack) Command ID is invalid:")); ERROR_LOG(messageID, DEC); break; } } void Peripheral::sendSwitchAck(uint8_t* data) { DBUG_LOG(F("sendSwitchAck: value")); DBUG_LOG(data[0]); sendAck(PIPE_HUE_LIGHTS_HUE_SWITCH_RX_ACK); setSwitchState(data[0]); } // update attributes void Peripheral::setLocation(uint8_t* data) { } void Peripheral::setSwitch(uint8_t* data) { uint8_t switchState = data[0]; DBUG_LOG(F("setSwitch: switchState")); DBUG_LOG(switchState); i2cMaster->setSwitch(switchState); } void Peripheral::setSceneName(uint8_t* data, uint8_t size) { } void Peripheral::setCurrentSceneId(uint8_t* data) { } void Peripheral::setLightColor(uint8_t* data) { } void Peripheral::setCommand(uint8_t* data) { } // state void Peripheral::setSwitchState(uint8_t switchState) { StateObject state; getState(state); DBUG_LOG(F("setSwitchState: new, old")); DBUG_LOG(switchState); DBUG_LOG(state.switchState); if (state.switchState != switchState) { state.switchState = switchState; sendSwitchState(state.switchState); updateState(state); } } void Peripheral::setWifiStatus(uint8_t wifiStatus) { StateObject state; getState(state); DBUG_LOG(F("setWifiStatus: new, old")); DBUG_LOG(wifiStatus); DBUG_LOG(state.wifiStatus); if (state.wifiStatus != wifiStatus) { state.wifiStatus = wifiStatus; sendWifiStatus(state.wifiStatus); updateState(state); } if (wifiStatus == 1 && shouldInit) { init(); } } void Peripheral::updateState(StateObject& state) { DBUG_LOG(F("updateState: wifiStatus, switchState")); DBUG_LOG(state.wifiStatus); DBUG_LOG(state.switchState); stateObjectEEPROM.update(0, state); } void Peripheral::getState(StateObject& state) { stateObjectEEPROM.read(0, state); DBUG_LOG(F("getState: wifiStatus, switchState")); DBUG_LOG(state.wifiStatus); DBUG_LOG(state.switchState); } void Peripheral::init() { DBUG_LOG(F("init")); shouldInit = false; StateObject state; getState(state); sendWifiStatus(state.wifiStatus); sendSwitchState(state.switchState); i2cMaster->getNumberOfLights(); i2cMaster->getNumberOfScenes(); i2cMaster->setSwitch(state.switchState); } // parameter updates void Peripheral::sendSwitchState(uint8_t switchState) { DBUG_LOG(F("sendSwitchState")); DBUG_LOG(switchState); sendData(PIPE_HUE_LIGHTS_HUE_SWITCH_TX, &switchState, PIPE_HUE_LIGHTS_HUE_SWITCH_TX_MAX_SIZE); setData(PIPE_HUE_LIGHTS_HUE_SWITCH_SET, &switchState, PIPE_HUE_LIGHTS_HUE_SWITCH_SET_MAX_SIZE); } void Peripheral::sendWifiStatus(uint8_t wifiStatus) { DBUG_LOG(F("sendWifiStatus")); DBUG_LOG(wifiStatus); sendData(PIPE_HUE_LIGHTS_HUE_STATUS_TX, &wifiStatus, PIPE_HUE_LIGHTS_HUE_STATUS_TX_MAX_SIZE); setData(PIPE_HUE_LIGHTS_HUE_STATUS_SET, &wifiStatus, PIPE_HUE_LIGHTS_HUE_STATUS_SET_MAX_SIZE); } void Peripheral::sendLightCount(uint8_t lightCount) { DBUG_LOG(F("setLightCount")); DBUG_LOG(lightCount); sendData(PIPE_HUE_LIGHTS_HUE_LIGHTS_COUNT_TX, &lightCount, PIPE_HUE_LIGHTS_HUE_LIGHTS_COUNT_TX_MAX_SIZE); setData(PIPE_HUE_LIGHTS_HUE_LIGHTS_COUNT_SET, &lightCount, PIPE_HUE_LIGHTS_HUE_LIGHTS_COUNT_SET_MAX_SIZE); } void Peripheral::sendSceneCount(uint8_t sceneCount) { DBUG_LOG(F("sendSceneCount")); DBUG_LOG(sceneCount); sendData(PIPE_HUE_LIGHTS_HUE_SCENES_COUNT_TX, &sceneCount, PIPE_HUE_LIGHTS_HUE_SCENES_COUNT_TX_MAX_SIZE); setData(PIPE_HUE_LIGHTS_HUE_SCENES_COUNT_SET, &sceneCount, PIPE_HUE_LIGHTS_HUE_SCENES_COUNT_SET_MAX_SIZE); }
[ "troy.stribling@gmail.com" ]
troy.stribling@gmail.com
e985c85094c69329c0c068c1db268677efa42cd6
6e7f81721891b0e6148b7070e261284503d8cec9
/models/lexical/token.h
7dc09226895a2962de67db191bfcad2fcf9109f1
[]
no_license
bishoyngendy/Compiler
df647db1ac4c2ed8b000161eb02c682eb07bc816
17ad7d30330c0716cfe6f697179ecaf348789557
refs/heads/master
2020-04-09T00:05:14.691054
2018-11-30T16:59:41
2018-11-30T16:59:41
149,026,228
0
1
null
null
null
null
UTF-8
C++
false
false
429
h
/* * token.h * * Created on: Mar 23, 2018 * Author: amrnasr */ #ifndef LEXICAL_ANALYZER_MODELS_TOKEN_H_ #define LEXICAL_ANALYZER_MODELS_TOKEN_H_ #include <string> using namespace std; enum TOKEN_TYPE {REAL_TOKEN, ERROR_TOKEN}; class Token { public: TOKEN_TYPE type; string lexme; string token_class; Token(TOKEN_TYPE tp, string token, string tokClass); }; #endif /* LEXICAL_ANALYZER_MODELS_TOKEN_H_ */
[ "bishoyngendy@gmail.com" ]
bishoyngendy@gmail.com
3458e52692f5a232cdd53c320ca4c95aa6a9841b
e4dad321fa283cc96bff1d98ce378ca92250bb34
/数据结构与算法/其他算法/求平方根超级函数/源.cpp
34713cd567b3fd6482b8ae2b69abf18ba5772d70
[]
no_license
maple5233/Old-Cpp-Code
0ef7f983b2f613cd20d5c9fc6e982322fb65ed2a
98fa5b0ca5112e66a0644fefa2b26478935b5005
refs/heads/master
2021-01-12T16:16:04.745352
2016-10-26T05:14:02
2016-10-26T05:14:02
71,968,532
2
0
null
null
null
null
UTF-8
C++
false
false
667
cpp
#include<iostream> using namespace std; static float CarmackSqrt(float x) { float xhalf = 0.5f * x; int i = *(int*)&x; // get bits for floating VALUE i = 0x5f3759df - (i >> 1); // gives initial guess y0 0x5f3759df is a magic number x = *(float*)&i; // convert bits BACK to float x = x*(1.5f - xhalf*x*x); // Newton step, repeating increases accuracy x = x*(1.5f - xhalf*x*x); // Newton step, repeating increases accuracy x = x*(1.5f - xhalf*x*x); // Newton step, repeating increases accuracy return (1 / x); } int main() { double no; cin >> no; cout << CarmackSqrt(no) << endl; system("pause"); }
[ "326153996@qq.com" ]
326153996@qq.com
ec02e69a5a505a3f1519ee00594d61b129664551
4ea6a61aef7ddd8785d75513a8ea73576f103d1e
/benchmarks/real-verification/inspircd-2.0.5/src/socketengines/socketengine_ports.cpp
258c89709ace33ee1129d47b43a87960c8279d76
[]
no_license
probertool/Prober
287190a03b6d6a40ba77295ccef132226f800420
c75047af835ba7ddf60fb3f72f686ea4c56a08b5
refs/heads/master
2020-09-09T07:45:33.005153
2019-11-13T05:39:15
2019-11-13T05:39:15
221,385,993
0
0
null
null
null
null
UTF-8
C++
false
false
5,173
cpp
/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2010 InspIRCd Development Team * See: http://wiki.inspircd.org/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ #include "inspircd.h" #include "exitcodes.h" #include <port.h> #ifndef __SOCKETENGINE_PORTS__ #define __SOCKETENGINE_PORTS__ #ifndef __sun # error You need Solaris 10 or later to make use of this code. #endif #include <vector> #include <string> #include <map> #include "inspircd_config.h" #include "inspircd.h" #include "socketengine.h" #include <port.h> /** A specialisation of the SocketEngine class, designed to use solaris 10 I/O completion ports */ class PortsEngine : public SocketEngine { private: /** These are used by epoll() to hold socket events */ port_event_t* events; public: /** Create a new PortsEngine * @param Instance The creator of this object */ PortsEngine(); /** Delete a PortsEngine */ virtual ~PortsEngine(); virtual bool AddFd(EventHandler* eh, int event_mask); void OnSetEvent(EventHandler* eh, int old_event, int new_event); virtual void DelFd(EventHandler* eh); virtual int DispatchEvents(); virtual std::string GetName(); virtual void WantWrite(EventHandler* eh); }; #endif #include <ulimit.h> PortsEngine::PortsEngine() { int max = ulimit(4, 0); if (max > 0) { MAX_DESCRIPTORS = max; } else { ServerInstance->Logs->Log("SOCKET", DEFAULT, "ERROR: Can't determine maximum number of open sockets!"); printf("ERROR: Can't determine maximum number of open sockets!\n"); ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } EngineHandle = port_create(); if (EngineHandle == -1) { ServerInstance->Logs->Log("SOCKET",SPARSE,"ERROR: Could not initialize socket engine: %s", strerror(errno)); ServerInstance->Logs->Log("SOCKET",SPARSE,"ERROR: This is a fatal error, exiting now."); printf("ERROR: Could not initialize socket engine: %s\n", strerror(errno)); printf("ERROR: This is a fatal error, exiting now.\n"); ServerInstance->Exit(EXIT_STATUS_SOCKETENGINE); } CurrentSetSize = 0; ref = new EventHandler* [GetMaxFds()]; events = new port_event_t[GetMaxFds()]; memset(ref, 0, GetMaxFds() * sizeof(EventHandler*)); } PortsEngine::~PortsEngine() { this->Close(EngineHandle); delete[] ref; delete[] events; } static int mask_to_events(int event_mask) { int rv = 0; if (event_mask & (FD_WANT_POLL_READ | FD_WANT_FAST_READ)) rv |= POLLRDNORM; if (event_mask & (FD_WANT_POLL_WRITE | FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE)) rv |= POLLWRNORM; return rv; } bool PortsEngine::AddFd(EventHandler* eh, int event_mask) { int fd = eh->GetFd(); if ((fd < 0) || (fd > GetMaxFds() - 1)) return false; if (ref[fd]) return false; ref[fd] = eh; SocketEngine::SetEventMask(eh, event_mask); port_associate(EngineHandle, PORT_SOURCE_FD, fd, mask_to_events(event_mask), eh); ServerInstance->Logs->Log("SOCKET",DEBUG,"New file descriptor: %d", fd); CurrentSetSize++; return true; } void PortsEngine::WantWrite(EventHandler* eh, int old_mask, int new_mask) { if (mask_to_events(new_mask) != mask_to_events(old_mask)) port_associate(EngineHandle, PORT_SOURCE_FD, eh->GetFd(), mask_to_events(new_mask), eh); } void PortsEngine::DelFd(EventHandler* eh) { int fd = eh->GetFd(); if ((fd < 0) || (fd > GetMaxFds() - 1)) return; port_dissociate(EngineHandle, PORT_SOURCE_FD, fd); CurrentSetSize--; ref[fd] = NULL; ServerInstance->Logs->Log("SOCKET",DEBUG,"Remove file descriptor: %d", fd); return true; } int PortsEngine::DispatchEvents() { struct timespec poll_time; poll_time.tv_sec = 1; poll_time.tv_nsec = 0; unsigned int nget = 1; // used to denote a retrieve request. int i = port_getn(EngineHandle, this->events, GetMaxFds() - 1, &nget, &poll_time); ServerInstance->UpdateTime(); // first handle an error condition if (i == -1) return i; TotalEvents += nget; for (i = 0; i < nget; i++) { switch (this->events[i].portev_source) { case PORT_SOURCE_FD: { int fd = this->events[i].portev_object; EventHandler* eh = ref[fd]; if (eh) { int mask = eh->GetEventMask(); if (events[i].portev_events & POLLWRNORM) mask &= ~(FD_WRITE_WILL_BLOCK | FD_WANT_FAST_WRITE | FD_WANT_SINGLE_WRITE); if (events[i].portev_events & POLLRDNORM) mask &= ~FD_READ_WILL_BLOCK; // reinsert port for next time around, pretending to be one-shot for writes SetEventMask(ev, mask); port_associate(EngineHandle, PORT_SOURCE_FD, fd, mask_to_events(mask), eh); if (events[i].portev_events & POLLRDNORM) { ReadEvents++; eh->HandleEvent(EVENT_READ); if (eh != ref[fd]) continue; } if (events[i].portev_events & POLLWRNORM) { WriteEvents++; eh->HandleEvent(EVENT_WRITE); } } } default: break; } } return i; } std::string PortsEngine::GetName() { return "ports"; } SocketEngine* CreateSocketEngine() { return new PortsEngine; }
[ "hongyuliu@salsa2.it.utsa.edu" ]
hongyuliu@salsa2.it.utsa.edu
7db40465afdaad5691bf6695d5a752bbdce051e1
a00221e88ed25a8feace316e5f7ccee09e271775
/experimental/pbwt_utils.cpp
71293f36dbaa635e759a39e9e7e6a20d1dad866c
[ "Apache-2.0" ]
permissive
hyunminkang/cramore
e335b897777204e33c470d988538016bc8669dfd
5b6b4a1b4e5aaf19f789c2f9b9bd05d54621ef48
refs/heads/master
2022-07-20T13:19:15.077090
2022-07-08T23:49:30
2022-07-08T23:49:30
141,421,811
2
3
Apache-2.0
2022-04-19T16:37:16
2018-07-18T10:50:50
C++
UTF-8
C++
false
false
6,168
cpp
/* File: utils.c * Author: Richard Durbin (rd@sanger.ac.uk) * Modified by Daniel Lawson (dan.lawson@bristol.ac.uk) in December 2014, adding gzip output for paintSparse * Copyright (C) Genome Research Limited, 1996- *------------------------------------------------------------------- * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 2.1 of the License, or (at your option) any later * version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. *------------------------------------------------------------------- * Description: core utility functions * Exported functions: * HISTORY: * Last edited: Dec 28 14:02 2014 (dl) * adding gzip output for paintSparse * Created: Thu Aug 15 18:32:26 1996 (rd) *------------------------------------------------------------------- */ #include <stdio.h> #include <stdarg.h> #include <ctype.h> #include "pbwt_utils.h" void die (char *format, ...) { va_list args ; va_start (args, format) ; fprintf (stderr, "FATAL ERROR: ") ; vfprintf (stderr, format, args) ; fprintf (stderr, "\n") ; va_end (args) ; timeUpdate (stderr) ; exit (-1) ; } void warn (char *format, ...) { static int count = 0 ; va_list args ; va_start (args, format) ; fprintf (stderr, "ERROR: ") ; vfprintf (stderr, format, args) ; fprintf (stderr, "\n") ; va_end (args) ; if (++count > 9) die ("too many errors") ; } long int totalAllocated = 0 ; void *_myalloc (long size) { void *p = (void*) malloc (size) ; if (!p) die ("myalloc failure requesting %d bytes", size) ; totalAllocated += size ; return p ; } void *_mycalloc (long number, int size) { void *p = (void*) calloc (number, size) ; if (!p) die ("mycalloc failure requesting %d of size %d bytes", number, size) ; totalAllocated += number*size ; return p ; } /*************************************************/ FILE *fopenTag (char* root, char* tag, char* mode) { if (strlen (tag) > 30) die ("tag %s in fopenTag too long - should be < 30 chars", tag) ; char *fileName = myalloc (strlen (root) + 32, char) ; strcpy (fileName, root) ; strcat (fileName, ".") ; strcat (fileName, tag) ; FILE *f = fopen (fileName, mode) ; free (fileName) ; return f ; } gzFile gzopenTag (char* root, char* tag, char* mode) { if (strlen (tag) > 40) die ("tag %s in gzopenTag too long - should be < 30 chars", tag) ; char *fileName = myalloc (strlen (root) + 42, char) ; strcpy (fileName, root) ; strcat (fileName, ".") ; strcat (fileName, tag) ; gzFile f = gzopen (fileName, mode) ; free (fileName) ; return f ; } /*************************************************/ char *fgetword (FILE *f) // pass NULL to free alloced memory { int n = 0 ; static char *buf = 0 ; int bufSize = 64 ; char *cp ; if (!f) { if (buf) free(buf); buf = NULL; return NULL; } if (!buf) buf = myalloc (bufSize, char) ; cp = buf ; while (!feof (f) && (*cp = getc (f))) if (isgraph(*cp) && !isspace(*cp)) { ++cp ; ++n ; if (n >= bufSize) { bufSize *= 2 ; if (!(buf = (char*) realloc (buf, bufSize))) die ("fgetword realloc failure requesting %d bytes", bufSize) ; } } else { while ((isspace(*cp) || !isgraph(*cp)) && *cp != '\n' && !feof(f)) *cp = getc (f) ; /* previous line was while ((*cp = getc(f)) && (isspace(*cp) || !isgraph(*cp)) && *cp != '\n' && !feof(f)) ; */ ungetc (*cp, f) ; break ; } *cp = 0 ; return buf ; } /***************** rusage for timing information ******************/ #include <sys/resource.h> #ifndef RUSAGE_SELF /* to prevent "RUSAGE_SELF redefined" gcc warning, fixme if this is more intricate */ #define RUSAGE_SELF 0 #endif #ifdef RUSAGE_STRUCTURE_DEFINITIONS struct rusage { struct timeval ru_utime; /* user time used */ struct timeval ru_stime; /* system time used */ long ru_maxrss; /* integral max resident set size */ long ru_ixrss; /* integral shared text memory size */ long ru_idrss; /* integral unshared data size */ long ru_isrss; /* integral unshared stack size */ long ru_minflt; /* page reclaims */ long ru_majflt; /* page faults */ long ru_nswap; /* swaps */ long ru_inblock; /* block input operations */ long ru_oublock; /* block output operations */ long ru_msgsnd; /* messages sent */ long ru_msgrcv; /* messages received */ long ru_nsignals; /* signals received */ long ru_nvcsw; /* voluntary context switches */ long ru_nivcsw; /* involuntary context switches */ }; struct timeval { time_t tv_sec; /* seconds since Jan. 1, 1970 */ suseconds_t tv_usec; /* and microseconds */ } ; #endif /* RUSAGE STRUCTURE_DEFINITIONS */ void timeUpdate (FILE *f) { static BOOL isFirst = TRUE ; static struct rusage rOld ; struct rusage rNew ; int secs, usecs ; getrusage (RUSAGE_SELF, &rNew) ; if (!isFirst) { secs = rNew.ru_utime.tv_sec - rOld.ru_utime.tv_sec ; usecs = rNew.ru_utime.tv_usec - rOld.ru_utime.tv_usec ; if (usecs < 0) { usecs += 1000000 ; secs -= 1 ; } fprintf (f, "user\t%d.%06d", secs, usecs) ; secs = rNew.ru_stime.tv_sec - rOld.ru_stime.tv_sec ; usecs = rNew.ru_stime.tv_usec - rOld.ru_stime.tv_usec ; if (usecs < 0) { usecs += 1000000 ; secs -= 1 ; } fprintf (f, "\tsystem\t%d.%06d", secs, usecs) ; fprintf (f, "\tmax_RSS\t%ld", rNew.ru_maxrss - rOld.ru_maxrss) ; fprintf (f, "\tMemory\t%li", totalAllocated) ; fputc ('\n', f) ; } else isFirst = FALSE ; rOld = rNew ; } /********************* end of file ***********************/
[ "hmkang@umich.edu" ]
hmkang@umich.edu
191aa2c8a06d6482e3d7cd9d7fe6362aa10dd9a1
26c11650bff8b0c554efff9047ea582260e8d6ca
/src/blocks/TorchBlock.cpp
58d6c9252006f1a770b53e60a189225e63734b23
[]
no_license
Glycaa/CrafTuX
0d85f4115607b8243a67817db65fbb49d43fda60
5ef7a342b75bb39c78fb8ac36701fca61258171b
refs/heads/master
2020-04-06T11:32:40.839406
2012-04-25T09:53:54
2012-04-25T09:53:54
3,229,611
0
0
null
null
null
null
UTF-8
C++
false
false
5,184
cpp
#include "TorchBlock.h" #include "gui/OpenGLBuffer.h" #include "gui/OpenGLVertice.h" void TorchBlock::render(OpenGLBuffer& targetBuffer, const BlockSet& blockSet, const BlockPosition& bp, const World& workingWorld) const { const GLfloat TOP_LIGHT = 1.0f; const GLfloat SIDE_LIGHT_NORMAL = 0.85f; const GLfloat BOTTOM_COLOR = 0.45f; const GLfloat XMIN = 0.45f; const GLfloat XMAX = 0.55f; const GLfloat YMIN = 0.0f; const GLfloat YMAX = 0.90f; const GLfloat ZMIN = 0.45f; const GLfloat ZMAX = 0.55f; // Front face { TexCoords* texCoords = blockSet.block->descriptor().getTexture(); OpenGLVertice v1(bp.x + XMIN, bp.y + YMIN, bp.z + ZMIN); // 0.0f,0.0f,0.0f, v1.setColors(SIDE_LIGHT_NORMAL); v1.setTextures(texCoords[0].tx, texCoords[0].ty); OpenGLVertice v2(bp.x + XMAX, bp.y + YMIN, bp.z + ZMIN); // 1.0f,0.0f,0.0f, v2.setColors(SIDE_LIGHT_NORMAL); v2.setTextures(texCoords[1].tx, texCoords[1].ty); OpenGLVertice v3(bp.x + XMAX, bp.y + YMAX, bp.z + ZMIN); // 1.0f,1.0f,0.0f, v3.setColors(TOP_LIGHT); v3.setTextures(texCoords[2].tx, texCoords[2].ty); OpenGLVertice v4(bp.x + XMIN, bp.y + YMAX, bp.z + ZMIN); // 0.0f,1.0f,0.0f, v4.setColors(TOP_LIGHT); v4.setTextures(texCoords[3].tx, texCoords[3].ty); targetBuffer.addVertices(v1, v2, v3, v4); } // Left face { TexCoords* texCoords = blockSet.block->descriptor().getTexture(); OpenGLVertice v1(bp.x + XMIN, bp.y + YMIN, bp.z + ZMAX); // 0.0f,0.0f,1.0f, v1.setColors(SIDE_LIGHT_NORMAL); v1.setTextures(texCoords[0].tx, texCoords[0].ty); OpenGLVertice v2(bp.x + XMIN, bp.y + YMIN, bp.z + ZMIN); // 0.0f,0.0f,0.0f, v2.setColors(SIDE_LIGHT_NORMAL); v2.setTextures(texCoords[1].tx, texCoords[1].ty); OpenGLVertice v3(bp.x + XMIN, bp.y + YMAX, bp.z + ZMIN); // 0.0f,1.0f,0.0f, v3.setColors(TOP_LIGHT); v3.setTextures(texCoords[2].tx, texCoords[2].ty); OpenGLVertice v4(bp.x + XMIN, bp.y + YMAX, bp.z + ZMAX); // 0.0f,1.0f,1.0f, v4.setColors(TOP_LIGHT); v4.setTextures(texCoords[3].tx, texCoords[3].ty); targetBuffer.addVertices(v1, v2, v3, v4); } // Bottom face { TexCoords* texCoords = blockSet.block->descriptor().getTexture(); OpenGLVertice v1(bp.x + XMIN, bp.y + YMIN, bp.z + ZMAX); // 0.0f,0.0f,1.0f, v1.setColors(BOTTOM_COLOR); v1.setTextures(texCoords[0].tx, texCoords[0].ty); OpenGLVertice v2(bp.x + XMAX, bp.y + YMIN, bp.z + ZMAX); // 1.0f,0.0f,1.0f, v2.setColors(BOTTOM_COLOR); v2.setTextures(texCoords[1].tx, texCoords[1].ty); OpenGLVertice v3(bp.x + XMAX, bp.y + YMIN, bp.z + ZMIN); // 1.0f,0.0f,0.0f, v3.setColors(BOTTOM_COLOR); v3.setTextures(texCoords[2].tx, texCoords[2].ty); OpenGLVertice v4(bp.x + XMIN, bp.y + YMIN, bp.z + ZMIN); // 0.0f,0.0f,0.0f, v4.setColors(BOTTOM_COLOR); v4.setTextures(texCoords[3].tx, texCoords[3].ty); targetBuffer.addVertices(v1, v2, v3, v4); } // Right face { TexCoords* texCoords = blockSet.block->descriptor().getTexture(); OpenGLVertice v1(bp.x + XMAX, bp.y + YMIN, bp.z + ZMIN); // 1.0f,0.0f,0.0f, v1.setColors(SIDE_LIGHT_NORMAL); v1.setTextures(texCoords[0].tx, texCoords[0].ty); OpenGLVertice v2(bp.x + XMAX, bp.y + YMIN, bp.z + ZMAX); // 1.0f,0.0f,1.0f, v2.setColors(SIDE_LIGHT_NORMAL); v2.setTextures(texCoords[1].tx, texCoords[1].ty); OpenGLVertice v3(bp.x + XMAX, bp.y + YMAX, bp.z + ZMAX); // 1.0f,1.0f,1.0f, v3.setColors(TOP_LIGHT); v3.setTextures(texCoords[2].tx, texCoords[2].ty); OpenGLVertice v4(bp.x + XMAX, bp.y + YMAX, bp.z + ZMIN); // 1.0f,1.0f,0.0f, v4.setColors(TOP_LIGHT); v4.setTextures(texCoords[3].tx, texCoords[3].ty); targetBuffer.addVertices(v1, v2, v3, v4); } // Top face { TexCoords* texCoords = blockSet.block->descriptor().getTexture(); OpenGLVertice v1(bp.x + XMIN, bp.y + YMAX, bp.z + ZMIN); // 0.0f,1.0f,0.0f, v1.setColors(TOP_LIGHT); v1.setTextures(texCoords[0].tx, texCoords[0].ty); OpenGLVertice v2(bp.x + XMAX, bp.y + YMAX, bp.z + ZMIN); // 1.0f,1.0f,0.0f, v2.setColors(TOP_LIGHT); v2.setTextures(texCoords[1].tx, texCoords[1].ty); OpenGLVertice v3(bp.x + XMAX, bp.y + YMAX, bp.z + ZMAX); // 1.0f,1.0f,1.0f, v3.setColors(TOP_LIGHT); v3.setTextures(texCoords[2].tx, texCoords[2].ty); OpenGLVertice v4(bp.x + XMIN, bp.y + YMAX, bp.z + ZMAX); // 0.0f,1.0f,1.0f, v4.setColors(TOP_LIGHT); v4.setTextures(texCoords[3].tx, texCoords[3].ty); targetBuffer.addVertices(v1, v2, v3, v4); } // Back face { TexCoords* texCoords = blockSet.block->descriptor().getTexture(); OpenGLVertice v1(bp.x + XMAX, bp.y + YMIN, bp.z + ZMAX); // 1.0f,0.0f,1.0f, v1.setColors(SIDE_LIGHT_NORMAL); v1.setTextures(texCoords[0].tx, texCoords[0].ty); OpenGLVertice v2(bp.x + XMIN, bp.y + YMIN, bp.z + ZMAX); // 0.0f,0.0f,1.0f, v2.setColors(SIDE_LIGHT_NORMAL); v2.setTextures(texCoords[1].tx, texCoords[1].ty); OpenGLVertice v3(bp.x + XMIN, bp.y + YMAX, bp.z + ZMAX); // 0.0f,1.0f,1.0f, v3.setColors(TOP_LIGHT); v3.setTextures(texCoords[2].tx, texCoords[2].ty); OpenGLVertice v4(bp.x + XMAX, bp.y + YMAX, bp.z + ZMAX); // 1.0f,1.0f,1.0f, v4.setColors(TOP_LIGHT); v4.setTextures(texCoords[3].tx, texCoords[3].ty); targetBuffer.addVertices(v1, v2, v3, v4); } }
[ "glycaa@gmail.com" ]
glycaa@gmail.com
b077d90abe583ec275aa00c3b410005d31c408e3
8d4fc81d795c84e90138b50cbc7b2c541fae15e5
/06_medium/102-BinaryTreeLevelOrderTraversal.cpp
4f4fb09af7154ed9d12cecd5ee7213e62715e85e
[]
no_license
leexsh/LeetCode
281d268d960f7431303adaf8c1ca401a1736c422
0c5cbfca5ab3960fac96246f8b711053efb94957
refs/heads/master
2021-07-06T10:29:05.520764
2021-01-09T08:25:49
2021-01-09T08:25:49
219,448,006
0
0
null
null
null
null
UTF-8
C++
false
false
2,124
cpp
#include "bits/stdc++.h" using namespace std; /* LeetCode-102 题目:二叉树的层次遍历 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [9,20], [15,7] ] */ /* 思路: */ class TreeNode{ public: TreeNode(int v) : val(v), left(nullptr), right(nullptr){} public: int val; TreeNode *left; TreeNode *right; }; vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> vec; if(root == nullptr){ return vec; } deque<TreeNode *> dq; // 双端队列 dq.push_back(root); while(!dq.empty()){ vector<int> nums; int num = dq.size(); for(int i = 0; i < num; ++i){ nums.push_back(dq.front()->val); if(dq.front()->left){ dq.push_back(dq.front()->left); } if(dq.front()->right){ dq.push_back(dq.front()->right); } dq.pop_front(); } vec.push_back(nums); nums.resize(0); } return vec; } class Solution { public: vector<vector<int>> res; vector<vector<int>> levelOrder(TreeNode* root) { if (!root) { return res; } deque<TreeNode*> dq; dq.push_back(root); while (!dq.empty()) { int size = dq.size(); vector<int> temp; for (int i = 0; i < size; ++i) { root = dq.front(); dq.pop_front(); temp.push_back(root->val); if (root->left) { dq.push_back(root->left); } if (root->right) { dq.push_back(root->right); } } res.push_back(temp); } return res; } }; int main(){ system("pause"); return 0; }
[ "851001285@qq.com" ]
851001285@qq.com
afc39162df6e0f5a344dbd7f8194b135209750d0
d0155fc9b326edbe41a30db5a630133b97a7f9fc
/Codigos de ejercicios en cpp/Programa 40.cpp
d032baacbdbc310c025a9615f8b2e9393fffe06d
[ "Apache-2.0" ]
permissive
EulisesBrazon/ejercicios-c-
fa8f00cc048fce87b6dee3da52bde69b1b4beb92
ea9957df80bda6a2fe504e979c62fc98e5b6150d
refs/heads/master
2022-09-19T09:40:51.510029
2022-09-01T15:55:10
2022-09-01T15:55:10
165,403,730
0
0
null
null
null
null
UTF-8
C++
false
false
573
cpp
#include<iostream> #include<conio.h> using namespace std; double mayor(double p1,double p2,double p3) { double x; if(p1>p2 && p1>p3) x=p1; else if(p2>p1 && p2>p3) x=p2; else x=p3; return x; } int main() { double p1,p2,p3; cout<<"Ingrese el valor de la primera pelicula"<<endl; cin>>p1; cout<<endl; cout<<"Ingrese el valor de la segunda pelicula"<<endl; cin>>p2; cout<<endl; cout<<"Ingrese el valor de la tercera pelicula"<<endl; cin>>p3; cout<<endl; cout<<"El valor a pagar es de "<<(p1+p2+p3)-mayor(p1,p2,p3)<<endl; getch(); return 0; }
[ "eulisesbrazon@gmail.com" ]
eulisesbrazon@gmail.com
2b189e4e39b9da588201f4c87d99b7d1a192eb36
f720d51856ffd9f505e0c10f0c8a37aef99f40ef
/ASOBU KA SHINU/Term 1-1 project final.cpp
d2c517120299454b038852cbc8b92335e1e44b75
[]
no_license
Shehabul-Islam-Sawraz/Asobu_Ka_Shinu
b8f715ef9be53e3941a7a208c490fc6141f6d559
3398182e4ba8c8ad0b727af788883d789fffade5
refs/heads/master
2023-03-15T09:53:05.032942
2021-03-07T16:43:33
2021-03-07T16:43:33
345,398,411
3
0
null
null
null
null
UTF-8
C++
false
false
62,237
cpp
#include "iGraphics.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <windows.h> #include <windowsx.h> #include <math.h> #define linenum 30 #define obsnum 20 #define dangernum 16 #define cannonnum 1 #define rectangle 18 #define numrightobstacles 7 #define numdownobstacles 4 #define screenlength 1000 #define screenwidth 650 #define pointnum -1 #define minenumber 4 double lvlend[3]={1690,2460}; int leaderlevel, linestart[5]={0,12},lineend[5]={11,27},obsstart[5]={0,8},obsend[5]={8,16},danstart[5]={0,7},danend[5]={7,16}; double pox=0, poy=0, ballx=30, bally=360, ballr=10, falling, chartimer, speedtimer, speedtimer2, speed=0,recx[30],recy[30]; double reclen[30],recwidth[30],type[30],firex,firey,v,ballx1=0,bally1=150,ballr1=40,pox1=0,area,x,y,u,ux=0,px; double dant[dangernum], danx[dangernum], dany[dangernum], danl[dangernum], danb[dangernum],danorigin[dangernum],dantravel[dangernum],dangerdx[dangernum],dangerdy[dangernum]; double _line_x[linenum], _line_y[linenum], _line_l[linenum], _line_b[linenum],_line_origin[linenum],_line_travel[linenum]; int _line_t[linenum], time_elapsed=0, score, lifebonus, levelscore, timebonus, scoredekhabo=1, leaderboardnum; char leaderboardscores[10][10]; double obsx[obsnum], obsy[obsnum], obsl[obsnum], obsb[obsnum]; int obst[obsnum], dancon[dangernum], deathtimer=-1; int posrank = 1, highscore = 0, prevlevel, menu=1, sound=1, ft=1, life=3, uacon=0, ballposition, charcon=0, level=-4, playerlevel; int intronum=1, introtimer=0, jump=0, namelen=0,ldx=2,ldy=2,completed=0; int deadcondition = 0, i,cp,p,ballfly,frontindex=0,knockout=0,index=0,backindex=7,hangindex=0,standcounter=0,run=0,extralife=1,flag=0,leveldekhao=0,expnum; int firecounter=0,downflag=0,downfall=0,downintersect=0,checkpoint=1,checkpointshow=0,checkpointshow1=0,checkindex=0; char bmpnum = '1', charpos[2]="r", bmpname[10][30]= {"Games//final1.bmp", "Games//final2.bmp", "Games//final3.bmp", "Games//final4.bmp", "Games//l21.bmp","Games//l22.bmp","Games//l23.bmp","Games//l24.bmp","Games//l25.bmp","Games//l26.bmp",}, filename[30]="Games//final1.bmp"; char charbmpname[200], playername[20], leaderboardname[10][30]; char intro[100] = "Games//intro//1//intro (1).bmp"; bool fire=false; bool mainmenu=false; bool main_menu=true; bool level_12=false; bool level_3=false; bool pause=false; char brick[25][50]={"project image\\b 0.bmp","project image\\b 1.bmp","project image\\b 2(1).bmp","project image\\b 3.bmp", "project image\\b 4.bmp","project image\\b 5.bmp","project image\\b 6(1).bmp","project image\\b 7.bmp", "project image\\b 8.bmp","project image\\b 9(1).bmp","project image\\b 10.bmp","project image\\b 11.bmp", "project image\\b 12.bmp","project image\\b 13.bmp","project image\\b 12.bmp","project image\\b 4.bmp", "project image\\b 12.bmp","project image\\b 14.bmp","project image\\b 2(2).bmp","project image\\b 6(2).bmp",}; char stand[1][40]={"project image\\stand.bmp"}; char frontrun[8][40]={"project image\\running 1.bmp","project image\\running 2.bmp","project image\\running 3.bmp","project image\\running 4.bmp", "project image\\running 5.bmp","project image\\running 6.bmp","project image\\running 7.bmp","project image\\running 8.bmp"}; char backrun[8][40]={"project image\\running 9.bmp","project image\\running 10.bmp","project image\\running 11.bmp","project image\\running 12.bmp", "project image\\running 13.bmp","project image\\running 14.bmp","project image\\running 15.bmp","project image\\running 16.bmp"}; char jump1[8][40]={"project image\\jump 1.bmp","project image\\jump 2.bmp","project image\\jump 3.bmp","project image\\jump 4.bmp", "project image\\jump 5.bmp","project image\\jump 6.bmp","project image\\jump 7.bmp","project image\\jump 8.bmp"}; char background [1][40]={"project image\\background.bmp"}; char rightobstacles[7][40]={"project image\\obstacle 1.bmp","project image\\obstacle 3.bmp","project image\\obstacle 5.bmp","project image\\obstacle 6.bmp", "project image\\obstacle 7.bmp","project image\\obstacle 8.bmp","project image\\obstacle 9.bmp"}; char downobstacles[4][40]={"project image\\obstacle 4.bmp","project image\\obstacle 11.bmp","project image\\obstacle 12.bmp", "project image\\obstacle 13.bmp"}; char minepic[4][40]={"project image\\minecraft 2.bmp","project image\\minecraft 1.bmp","project image\\bullet.bmp","project image\\bullet.bmp"}; char knock[35][60]={"project image\\ko1.bmp","project image\\ko1.bmp","project image\\ko1.bmp", "project image\\ko1.bmp","project image\\ko1.bmp","project image\\ko1.bmp", "project image\\ko1.bmp","project image\\ko3.bmp","project image\\ko3.bmp","project image\\ko3.bmp", "project image\\ko3.bmp","project image\\ko3.bmp","project image\\ko3.bmp","project image\\ko3.bmp", "project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp", "project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp", "project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp", "project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp","project image\\ko4.bmp"}; int explosion,expframenum; char expframe[34][100]={ "Games\\exp\\exp01.bmp","Games\\exp\\exp02.bmp","Games\\exp\\exp03.bmp","Games\\exp\\exp04.bmp","Games\\exp\\exp05.bmp","Games\\exp\\exp06.bmp","Games\\exp\\exp07.bmp","Games\\exp\\exp08.bmp","Games\\exp\\exp09.bmp","Games\\exp\\exp10.bmp", "Games\\exp\\exp11.bmp","Games\\exp\\exp12.bmp","Games\\exp\\exp13.bmp","Games\\exp\\exp14.bmp","Games\\exp\\exp15.bmp","Games\\exp\\exp16.bmp","Games\\exp\\exp17.bmp","Games\\exp\\exp18.bmp","Games\\exp\\exp19.bmp","Games\\exp\\exp20.bmp", "Games\\exp\\exp21.bmp","Games\\exp\\exp22.bmp","Games\\exp\\exp23.bmp","Games\\exp\\exp24.bmp","Games\\exp\\exp25.bmp","Games\\exp\\exp26.bmp","Games\\exp\\exp27.bmp","Games\\exp\\exp28.bmp","Games\\exp\\exp29.bmp","Games\\exp\\exp30.bmp", "Games\\exp\\exp31.bmp","Games\\exp\\exp32.bmp","Games\\exp\\exp33.bmp","Games\\exp\\exp34.bmp" }; void soundplay(){ if(sound<0){ PlaySound(0,0,0); return; } if(main_menu){ PlaySound("Musix\\main menu.wav",NULL,SND_LOOP | SND_ASYNC); } else if(pause){ PlaySound("Musix\\pause.wav",NULL,SND_LOOP | SND_ASYNC); } else if(level_12){ PlaySound("Musix\\level12.wav",NULL,SND_LOOP | SND_ASYNC); } // else if(level_12 && explosion){ // PlaySound("Musix\\explosion.wav",NULL, SND_ASYNC); // } else if(level_3&& fire==false){ PlaySound("Musix\\level3.wav",NULL,SND_LOOP | SND_ASYNC); } else if(level_3&& fire==true){ PlaySound("Musix\\explosion.wav",NULL, SND_ASYNC); } } void introbmpname(){ if(intronum > 58){iPauseTimer(0); level = -3; return;} strcpy(intro, "Games//intro//"); char c=intronum/10+1 + '0'; intro[14] = c; strcat(intro, "//intro ("); c=intronum%10 + '0'; intro[24] = c; strcat(intro, ").bmp"); intro[30]='\0'; intronum++; if(intronum%10==0) intronum++; introtimer++; } struct obstacless{ double birdx,birdy,speed; int birdindex; bool birdshow; }; obstacless enemy[numrightobstacles]; obstacless enemy1[numdownobstacles]; struct minecrafts{ double minex,mnx,miney,minelen,minespeed; int mineindex; }; minecrafts mine[minenumber]; void danger(int i, double x, double y, double l, double b, int type=1, int condition=0,double travel=0){ if(condition==-1&&type==4) danx[i]=x+travel-5; else danx[i]=x; if(condition==-1&&type==3) dany[i]=y+395; else dany[i]=y; danl[i]=l; danb[i]=b; dant[i]=type; dancon[i]=condition; if(type==3) danorigin[i]=y; else if(type==4) danorigin[i]=x; dantravel[i]=travel; } void dangercheck(double cx, double cy){ if(deadcondition == 1) return; if(level==1 || level==2){//added for(int i=danstart[level-1]; i<danend[level-1]; i++){ if(cx+ballr+20 > danx[i] && cx < (danx[i] + danl[i]) && cy + 70 > dany[i] && cy < (dany[i] + danb[i])){ if(dant[i] !=101){ if(dant[i]==1){ explosion=1; expnum=i; level_12=true; //soundplay(); if(sound>0) PlaySound("Musix\\explosion.wav",NULL, SND_ASYNC); } if(deathtimer>0) return; life--; if(deadcondition == 0){ deathtimer = 100; deadcondition = 1; } else{ iClear(); iSetColor(255, 0, 0); iRectangle(350, 350, 300, 50); iText(400, 360, "GAME OVER!"); } } else { if(life<3 && dancon[i]==1){ life++; dancon[i]=0; return; } } } } }//added } void line(int i, double x, double y, double len, int type=1, int travel=0, double thickness=5, int drawline=0){ _line_t[i]=type; if(type==3) _line_x[i] = x+10; else _line_x[i] = x; _line_y[i] = y; if(type==1||type==3){ _line_l[i] = len; _line_b[i] = thickness; } if(type==2||type==4){ _line_l[i] = thickness; _line_b[i] = len; } if(type==3){ _line_origin[i]=_line_x[i]; _line_travel[i]=travel; } if(type==4){ _line_origin[i]=_line_y[i]; _line_travel[i]=travel; } if(drawline>-1){ iSetColor(255, 0, 0); //iFilledRectangle(_line_x[i]+pox, _line_y[i]+poy, _line_l[i], _line_b[i]); } } void restart(){ recx[0]=0; recy[0]=140; reclen[0]=400; recwidth[0]=10; type[0]=0; recx[1]=400; recy[1]=140; reclen[1]=10; recwidth[1]=120; type[1]=1; recx[2]=410; recy[2]=250; reclen[2]=300; recwidth[2]=10; type[2]=0; recx[3]=710; recy[3]=100; reclen[3]=10; recwidth[3]=160; type[3]=2; recx[4]=720; recy[4]=100; reclen[4]=250; recwidth[4]=10; type[4]=0; recx[5]=970; recy[5]=100; reclen[5]=10; recwidth[5]=110; type[5]=1; recx[6]=980; recy[6]=200; reclen[6]=150; recwidth[6]=10; type[6]=0; recx[7]=1230; recy[7]=200; reclen[7]=150; recwidth[7]=10; type[7]=0; recx[8]=1380; recy[8]=120; reclen[8]=10; recwidth[8]=90; type[8]=2; recx[9]=1390; recy[9]=120; reclen[9]=150; recwidth[9]=10; type[9]=0; recx[10]=1650; recy[10]=120; reclen[10]=150; recwidth[10]=10; type[10]=0; recx[11]=1800; recy[11]=120; reclen[11]=10; recwidth[11]=120; type[11]=1; recx[12]=1810; recy[12]=230; reclen[12]=200; recwidth[12]=10; type[12]=0; recx[13]=2010; recy[13]=0; reclen[13]=10; recwidth[13]=240; type[13]=2; recx[14]=2170; recy[14]=230; reclen[14]=200; recwidth[14]=10; type[14]=0; recx[15]=2480; recy[15]=230; reclen[15]=250; recwidth[15]=10; type[15]=0; recx[16]=2840; recy[16]=230; reclen[16]=200; recwidth[16]=10; type[16]=0; recx[17]=3040; recy[17]=0; reclen[17]=10; recwidth[17]=240; type[17]=2; //the next 3 rectangle are related to pox recx[18]=450; recy[18]=250; reclen[18]=260; recwidth[18]=10; recx[19]=1000; recy[19]=200; reclen[19]=130; recwidth[19]=10; recx[20]=1400; recy[20]=120; reclen[20]=140; recwidth[20]=10; recx[21]=1130;recy[21]=0;reclen[21]=100;recwidth[21]=1; recx[22]=1540;recy[22]=0;reclen[22]=110;recwidth[22]=1; ux=0; if(checkpoint==1){ ballx1=0; bally1=160; pox1=0; } else if(checkpoint==2){ ballx1=1085; bally1=220; pox1=-1000; } iShowBMP2(ballx1+pox1,bally1,stand[0],255); leveldekhao=0; } int areaintersect(double l1x,double r1x,double l1y,double r1y,double l2x,double l2y,double r2x,double r2y){ if(level==3){ double a,b; a=min(r1x,r2x)-max(l1x,l2x); b=min(r1y,r2y)-max(l1y,l2y); if(a<=0 || b<=0){ return 0; } else{ return 1; } } } void enemymovement(){ if(level==3){ for(int i=0;i<numrightobstacles;i++){ if(enemy[i].birdshow){ iShowBMP2(enemy[i].birdx+pox1,enemy[i].birdy,rightobstacles[enemy[i].birdindex],255); } } } } void enemymovement1(){ if(level==3){ for(int i=0;i<numdownobstacles;i++){ if(enemy1[i].birdshow){ iShowBMP2(enemy1[i].birdx+pox1,enemy1[i].birdy,downobstacles[enemy1[i].birdindex],255); } } } } void minemovement(){ if(level==3){ for(i=0;i<minenumber;i++){ iShowBMP2(mine[i].mnx+pox1,mine[i].miney,minepic[mine[i].mineindex],255); } iShowBMP2(mine[4].minex+pox1,mine[4].miney,minepic[mine[4].mineindex],0xffffff); } } void ko(){ if(level==3){ if(knockout==1){ index++; if(index>=1 && index <=9) { ballx1-=6; bally1+=5; } if(index>=10 && index<=13) { ballx1-=5; bally1-=3; } if(index>=14 && index<=23) { ballx1-=4; bally1-=3; } if(index>=24 && index<=29) { ballx1-=2; } if(index>29) { index=0; knockout=0; restart(); soundplay(); } p=0; } else if(knockout==2){ index++; if(index>=1 && index <=9) { ballx1+=6; bally1+=5; } if(index>=10 && index<=13) { ballx1+=5; bally1-=3; } if(index>=14 && index<=23) { ballx1+=4; bally1-=3; } if(index>=24 && index<=29) { ballx1+=2; } if(index>29) { index=0; knockout=0; restart(); soundplay(); } p=0; } } } void checkshow(){ if(level==3){ if(checkpointshow==1 && checkpointshow1==1 && level==3){ iShowBMP2(50,250,"project image\\CHECKPOINT3.bmp",255); } } } void leaderboard2(char newname[20], int newscore, int playerlevel){ leaderboardnum=0; char filename[40] = "FILES//leaderboard1.txt"; filename[18] = '0' + playerlevel; char ara[12][20]; int score[12]; FILE* fp=fopen(filename, "r"); int i; printf("Level %d Prev File:\n", playerlevel); for(i=0; i<10; i++){ fscanf(fp, "%s %d", ara[i], &score[i]); if(feof(fp)) break; printf("%s %d\n", ara[i], score[i]); //if(feof(fp)) break; } fclose(fp); int flag=0; for(int j=0; j<i; j++){ if(!strcmp(ara[j], newname)){ score[j] = newscore; flag=1; break; } } if(!flag){ strcpy(ara[i], newname); score[i]=newscore; i++; } for(int j=0; j<i; j++){ for(int k=j; k<i; k++){ if(score[j] < score[k]){ int tmp=score[j]; score[j] = score[k]; score[k] = tmp; char temp[20]; strcpy(temp, ara[j]); strcpy(ara[j], ara[k]); strcpy(ara[k], temp); } } } fp=fopen(filename, "w"); for(int j=0; j<i; j++) fprintf(fp, "%s %d\n", ara[j], score[j]); fclose(fp); printf("\n\n"); printf("*****LEADERBOARD*****\n"); for (int j = 0; j < i; j++) { leaderboardnum++; if(j<10){ strcpy(leaderboardname[j], ara[j]); sprintf(leaderboardscores[j], "%07d", score[j]); } printf("%d.%20s\t%d", j + 1, ara[j], score[j]); if (!strcmp(newname, ara[j])) { posrank = j+1; printf(" <--%s", playername); } printf("\n"); } if(posrank == 1) highscore = 1; else highscore = 0; printf("\n\tYou ranked: %d\n", posrank); printf("\n\n"); } void highscore_leaderboard(){ freopen("FILES//Gamehistory.txt", "a", stdout); printf("\n\n------------------------------\n"); printf("Player name: %s Level: %d\n", playername, playerlevel); score=0; timebonus=(max(0, (500-time_elapsed))) * 30; if(playerlevel == 1) timebonus=(max(0, (650-time_elapsed))) * 100; if(playerlevel == 2) timebonus=(max(0, (1050-time_elapsed))) * 100; if(playerlevel == 3) timebonus=(max(0, (7000-time_elapsed))) * 100; lifebonus=life * 500; levelscore = playerlevel * 10000; score = levelscore + lifebonus + timebonus; { printf("Time Elapsed: %d\n", time_elapsed); printf("\nTimebonus: %d\nLifebonus: %d\nLevelscore: %d\n\tScore: %d\n", timebonus, lifebonus, levelscore, score); } leaderboard2(playername, score, playerlevel); } void iLevelCompleted(){ if(leveldekhao==1){ iShowBMP(0, 0, "project image\\Levelcompleted2.bmp"); for(i=0;i<numrightobstacles;i++){ enemy[i].birdshow=false; } for(i=0;i<numdownobstacles;i++){ enemy1[i].birdshow=false; } } else{ iShowBMP(0, 0, "Games//Menu//Levelcompleted.bmp"); } if(life == 1) iShowBMP2(273, 336, "Games//Menu//star1.bmp", 0xffffff); if(life == 2) iShowBMP2(273, 336, "Games//Menu//star2.bmp", 0xffffff); if(life == 3) iShowBMP2(273, 336, "Games//Menu//star3.bmp", 0xffffff); if(highscore) iShowBMP2(612, 212, "Games//Menu//highscore.bmp", 0xffffff); { char printscore[15]; sprintf(printscore, "Score: %06d", score); iSetColor(255, 255, 255); iText(435, 242, printscore, GLUT_BITMAP_TIMES_ROMAN_24); iShowBMP2(260, 190, "Games//leaderboard-icon-9.bmp", 0xffffff); } } void ball_position(){ ballposition=20; if(level==1 || level==2){ for(int i=linestart[level-1]; i<lineend[level-1]; i++){ if(ballx>=_line_x[i] && ballx<=_line_x[i]+_line_l[i] && bally>_line_y[i]) ballposition=i; } if(bally> _line_y[ballposition]+ 5 && uacon == 0) falling+=.025; else falling =0; } } void b_allposition(){ if(ballx1>1080 && ballx1<1120){ checkpoint=2; checkpointshow=1; checkpointshow1=1; checkindex++; if(checkindex>100){ checkpointshow1=2; } } else{ checkpointshow=0; } if(p==1 && knockout==0){ if(ballx1-5<0){ if(run==4){ run=1; } else if(run==5){ run=2; } p=0; ux=0; px=0; } if((ballx1>1130 && ballx1+ballr1<1230)||(ballx1>1540 && ballx1+ballr1<1650)||(ballx1>2010 && ballx1+ballr1<2170)||(ballx1>2370 && ballx1+ballr1<2480)||(ballx1>2730 && ballx1+ballr1 <2840)){ cp=21; v=4; downfall=0; if((ballx1>1130 && ballx1+ballr1<1230 && bally1<=212)||(ballx1>1540 && ballx1+ballr1<1650 && bally1<=132)||(ballx1>2010 && ballx1+ballr1<2170 && bally1<=250)||(ballx1>2370 && ballx1+ballr1<2480 && bally1<=250)||(ballx1>2730 && ballx1+ballr1 <2840 && bally1 <=250)){ cp=21; downfall=1; p=0; ux=0; px=0; } } if(ballx1+ballr1+5>=recx[cp+1] && bally1 <=recy[cp+1]+recwidth[cp+1] && p==1){ if(run==4) { run=1; } else if(run==5) { run=2; } p=0; ux=0; px=0; } else{ ballx1+=ux; } px-=1; if(p==1){ bally1=bally1+px; } if(bally1<=recy[cp]+recwidth[cp]+5 && p==1){ p=0; px=0; ux=0; } } if(areaintersect(ballx1,ballx1+40,bally1,bally1+60,1240,220,1240+25,220+24) && extralife==1){ if(life<3){ life++; } extralife=0; } if(areaintersect(ballx1,ballx1+40,bally1,bally1+60,3000,250,3000+50,250+31)){ level=11; leveldekhao=1; completed=1; highscore_leaderboard(); } if(ballx1+ballr1>3000){ level=11; leveldekhao=1; completed=1; highscore_leaderboard(); } if((ballx1>1130 && ballx1+ballr1<1230)||(ballx1>1540 && ballx1+ballr1<1650)||(ballx1>2010 && ballx1+ballr1<2170)||(ballx1>2370 && ballx1+ballr1<2480)||(ballx1>2730 && ballx1+ballr1 <2840)){ cp=21; v=4; ballfly=0; downfall=0; if((ballx1>1130 && ballx1+ballr1<1230 && bally1<=212)||(ballx1>1540 && ballx1+ballr1<1650 && bally1<=132)||(ballx1>2010 && ballx1+ballr1<2170 && bally1<=250)||(ballx1>2370 && ballx1+ballr1<2480 && bally1<=250)||(ballx1>2730 && ballx1+ballr1 <2840 && bally1 <=250)){ cp=21; downfall=1; } } else if(ballx1+ballr1>=1650 && ballx1+ballr1<1800){ cp=10; v=4; ballfly=0; downfall=0; } else{ for(i=0;i<=rectangle;i++){ if(ballx1>=recx[i] && ballx1+ballr1<=recx[i]+reclen[i]){ cp=i; v=4; ballfly=0; downfall=0; break; } else if((ballx1<=recx[i] && ballx1+ballr1 <=recx[i]+reclen[i])||(ballx1>=recx[i] && ballx1<=recx[i]+reclen[i] && ballx1+ballr1>recx[i]+reclen[i])||(ballx1<=recx[i] && ballx1+ballr1>=recx[i]+reclen[i])){ cp=i+1; v=4; ballfly=0; downfall=0; break; } } } if(downfall){ if(bally1<=0){ life--; if(life==0){ checkpoint=1; extralife=1; level=-1; } restart(); } } if(((GetAsyncKeyState(VK_UP) & 0x8000)==0)|| downfall==1){ if(bally1>recy[cp]+recwidth[cp]+2 && p==0){ ballfly=1; bally1=bally1-v; } } } void obstacle(int i, double x, double y, double l, double b, int type=1){ obsx[i]=x; obsy[i]=y; obsl[i]=l; obsb[i]=b; obst[i]=type; iSetColor(255, 255, 0); if(type==1){} } int obstacle_check(double cx, double cy){ if(level==1 || level==2){ for(int i=obsstart[level-1]; i<obsend[level-1]; i++){ if(cx+ballr+20 > obsx[i] && cx < (obsx[i] + obsl[i]) && cy + 70 > obsy[i] && cy < (obsy[i] + obsb[i])){ return 0; } } return 1; } } void f1(){ ///line(line_num, line_x, line_y, line_len, line_type, line_thickness); ///(by default) type = 1 horizontal line ///type = 2 vertical line ///by default lines thickness is set to 5 _line_y[20]=-345; line(0, 0, 0+350, 400); line(1, 395, 0+350, -100, 2); line(2, 395, -100+350, 300); line(3, 690, -100+350, 60, 2); line(4, 685, -40+350, 150); line(5, 925, -40+350, 250); line(6, 1175, -40+350, -150, 2); line(7, 1175, -190+350, 300); line(8, 1470, -190+350, 150, 2); line(9, 1470, -40+350, 200); line(10, 1665, 20+350, 1000, 2); line(11, 200, 200+350, 50); line(12,0,100,150); line(13,150,100,100,2); line(14,150,200,300); line(15,450,205,-110,2); line(16,450,100,250); line(17,700,100,150,2); line(18,700,250,300); line(19,1000,260,-250,2); line(20,1000,10,500); line(21,1500,10,400,2); line(22,1500,410,300); line(23,1800,420,-200,2); line(24,1800,220,350); line(25,2150,220,100,2); line(25,2150,320,300); line(26,1020,220,100,3,400); ///obstacles obstacle(0, 0, 0, 400, 352, 2); obstacle(1, 400, 0, 325, 250, 2); obstacle(2, 690, 0, 140, 310, 2); obstacle(3, 930, 0, 250, 310, 2); obstacle(4, 1175, 0, 310, 162, 2); obstacle(5, 1470, 0, 205, 315, 2); obstacle(6, 0, 0, 30, 2000, 2); obstacle(7, 0, 1000, 1600, 1000); obstacle(8, -1000, 0, 1025, 1000, 2); obstacle(9,0,0,1000,100,2); obstacle(10,150,100,300,100,2); obstacle(11,700,0,300,250,2); obstacle(12,1500,0,1650,220,2); obstacle(13,1500,220,300,190,2); obstacle(14,2131,224,200,100, 2); obstacle(15, 0, 0, 30, 2000, 2); ///dangers danger(0, 350, 350, 40, 50); danger(1, 1050, 325, 40, 50); danger(2, 1620, 320, 30, 30, 3, 0); ///moving danger vertical danger(3, 871, 425, 25, 25, 101, 1); ///life++ danger(4,395, 252, 30, 30, 4, 0, 275); ///moving danger danger(5, 1175, 162, 30, 30, 4, 0, 300); ///moving danger danger(6, 0, 0, 2000, 40, 0); ///hole danger(7, 450, 105, 30, 30, 4, 0, 230);///moving danger danger(8 ,1000, 15, 30, 30, 4, 0,480);///moving danger danger(9, 1800, 225, 30, 30, 4, 0, 300);///moving danger danger(10,1000, 15, 30, 30, 4, -1,480);///moving danger danger(11, 1200, 320, 25, 25, 101, 1);///life++ danger(12, 826, 254, 30, 30);///stationary danger danger(13, 1734, 412, 30, 30, 3, 0);///moving danger vertical danger(14 ,2228, 324, 30, 30, 3, 0);///moving danger vertical danger(15, 2437, 324, 30, 30, 3, -1);///moving danger vertical for(int i=0;i<dangernum;i++){ dangerdx[i]=2; dangerdy[i]=3; } } void timer(){ if(deathtimer >= 0){ deathtimer--; bally++; if(charbmpname[16] == 'r')ballx-=1.2; if(charbmpname[16] == 'l')ballx+=1.2; } else if(deadcondition == 1){ ballx=35; bally=360; deadcondition = 0; } if((level == 1 || level == 2 || level == 3) && (!completed)) time_elapsed++; if(level==1 || level==2){ for(int i=danstart[level-1];i<danend[level-1];i++){ if(dant[i]==3){ dany[i]+=dangerdy[i]; if(dany[i]-danorigin[i]>=400||dany[i]<danorigin[i]) dangerdy[i]*=-1; } else if(dancon[i] == -1 || dant[i] == 4){ danx[i]+=dangerdx[i]; if(danx[i]-danorigin[i]>=dantravel[i]||danx[i]<danorigin[i]) dangerdx[i]*=-1; } } for(int i=linestart[level-1];i<lineend[level-1];i++){ if(_line_t[i]==3){ _line_x[i]+=ldx; if(_line_x[i]-_line_origin[i]>=_line_travel[i]||_line_x[i]<=_line_origin[i]) ldx*=-1; if(_line_t[ballposition]==3&&!jump) ballx+=ldx; } else if(obst[i]==4){ _line_y[i]+=ldy; if(_line_t[ballposition]==4) bally+=ldy; if(_line_y[i]-_line_origin[i]>=_line_travel[i]||_line_y[i]<=_line_origin[i]) ldy*=-1; } } if(obstacle_check(ballx, bally-falling)) bally-=falling; speedtimer-=100; speedtimer2-=100; speed=3+max(max(0, 7*speedtimer/1000), max(0, 7*speedtimer2/1000)); } ///gravity if(uacon==1 && speedtimer>0) uacon=2; if(uacon==2) if(obstacle_check(ballx+ux, bally)) ballx+=ux; u-=1.25; double hobe=bally+u; if(hobe > _line_y[ballposition] && obstacle_check(ballx, hobe)){ bally=hobe; } else{ jump=0; uacon=0; ux=3; } } void charcondition(){ if(deadcondition == 1) { charcon = -1; if(deathtimer > 80){ bmpnum = '1'; return ;} if(deathtimer > 60){ bmpnum = '2'; return ;} if(deathtimer > 40){ bmpnum = '3'; return ;} if(deathtimer > 20){ bmpnum = '4'; return ;} if(deathtimer > 0){ bmpnum = '5'; return ;} } if(uacon == 0 && speedtimer2<0 && speedtimer<0){ if(charcon==0){ bmpnum++; if(bmpnum=='5') bmpnum='1'; return; } charcon=0; bmpnum='1'; chartimer=1500; } else if(uacon == 0 && (speedtimer2>0 || speedtimer>0)){ if(charcon==1){ if(speed > 7){ bmpnum++; if(bmpnum=='7') bmpnum='1'; } return; } charcon=1; bmpnum='1'; chartimer=1500; } else if(uacon==0 && speedtimer>0){ if(charcon==2){ if(speed > 7){ bmpnum++; if(bmpnum=='7') bmpnum='1'; } return; } charcon=2; bmpnum='1'; chartimer=1500; } else if(uacon !=0 && u>0){ if(charcon==3){ return; } charcon=3; bmpnum='3'; chartimer=1500; } else if(uacon != 0 && u<0){ if(charcon==4){ return; } charcon=4; bmpnum='4'; chartimer=1500; } } void charname(){ strcpy(charbmpname, "Games//char//1//"); strcat(charbmpname, charpos); if(charcon == -1){strcat(charbmpname, "d//");} if(charcon==0) strcat(charbmpname, "s//"); if(charcon==1 || charcon==2) strcat(charbmpname, "r//"); if(charcon==3 || charcon==4) strcat(charbmpname, "j//"); else strcat(charbmpname, "s//"); charbmpname[20]=bmpnum; charbmpname[21]='.'; charbmpname[22]='b'; charbmpname[23]='m'; charbmpname[24]='p'; charbmpname[25]='\0'; } void upanimation(){ if(deadcondition == 1) return; uacon=1; double x = max(0, u) + 15; if(x<33) u=x; } void poxpoy(){ if(ballx>=0 && ballx<500){ pox=0; if(level==1)strcpy(filename, bmpname[0]); if(level==2)strcpy(filename, bmpname[4]); } if(ballx>=500 && ballx<750){ pox=-350; if(level==1)strcpy(filename, bmpname[1]); if(level==2)strcpy(filename, bmpname[5]); } if(ballx>=750 && ballx<1250){ pox=-500; if(level==1)strcpy(filename, bmpname[2]); if(level==2)strcpy(filename, bmpname[6]); } if(ballx>=1250&&ballx<=1500){ pox=-1000; if(level==1)strcpy(filename, bmpname[3]); if(level==2)strcpy(filename, bmpname[7]); } if(ballx>=1500&&ballx<=2200&&level==2){ pox=-1500; if(level==2)strcpy(filename, bmpname[8]); } if(ballx>=2200){ pox=-2000; if(level==2)strcpy(filename, bmpname[9]); } } void newgame(){ if(deadcondition == 1){ deadcondition = 0; deathtimer = -1;} time_elapsed = 0; f1(); iSpecialKeyboard(GLUT_KEY_UP); ballx=35; bally=360; } void leaderboard(){ if(!strcmp(playername, "level1")) return; if(!strcmp(playername, "level2")) return; if(!strcmp(playername, "level3")) return; FILE* fp1 = fopen("FILES//profile.txt", "r"); FILE* fp2 = fopen("FILES//temp.txt", "w"); int found=0; while (1) { char tmpname[40]; int tmplevel; fscanf(fp1, "%s %d", tmpname, &tmplevel); if (feof(fp1)) break; if (!strcmp(tmpname, playername)) { found = 1; fprintf(fp2, "%s %d\n", playername, playerlevel); } else fprintf(fp2, "%s %d\n", tmpname, tmplevel); } if (!found) fprintf(fp2, "%s %d\n", playername, playerlevel); fclose(fp1); fclose(fp2); fp1 = fopen("FILES//profile.txt", "w"); fp2 = fopen("FILES//temp.txt", "r"); while (1) { int c; c=fgetc(fp2); if (feof(fp2)) break; fputc(c, fp1); } fclose(fp1); fclose(fp2); } void iLife(){ if(life>0){ iSetColor(0, 255, 0); iRectangle(850, 650, 99, 20); if(life==3) iSetColor(0, 255, 0); if(life==2) iSetColor(255, 255, 0); if(life==1) iSetColor(255, 0, 0); iFilledRectangle(850, 652, 33*life, 16); } if(life<1){ prevlevel=level; newgame(); level = -1; return; } if(ballx>lvlend[level-1]){ completed=1; highscore_leaderboard(); } } void iLevel(){ if(level==1 || level==2){ ball_position(); poxpoy(); charname(); iLife(); dangercheck(ballx, bally); iShowBMP(0, 0, "Games//BG1.bmp"); if(level==2) for(int i=linestart[level-1];i<lineend[level-1];i++){ if(_line_t[i]==3){ iShowBMP2(pox+_line_x[i]-12,poy+_line_y[i]-30, "Games//carpet2.bmp", 0xffffff); } } iSetColor(0, 255, 0); iRectangle(850, 650, 99, 20); if(life==3)iSetColor(0, 255, 0); if(life==2)iSetColor(255, 255, 0); if(life==1)iSetColor(255, 0, 0); iFilledRectangle(850, 652, 33*life, 16); for(int i=danstart[level-1]; i<danend[level-1]; i++){ if(dant[i]==1&&!explosion&&deathtimer)iShowBMP2(pox+danx[i], poy+dany[i], "Games//grenade.bmp", 0xffffff); if(dant[i]==3||dant[i]==4)iShowBMP2(pox+danx[i], poy+dany[i], "Games//bullet.bmp", 0xffffff); if(dant[i]==101 && dancon[i])iShowBMP2(pox+danx[i], poy+dany[i], "Games//life.bmp", 0xffffff);} for(int i=obsstart[level-1]; i<obsend[level-1]; i++){ if(obst[i] == 1)iShowBMP(pox+obsx[i], obsy[i], "Games//box.bmp"); else if(obst[i]==3) iFilledRectangle(pox+obsx[i],poy+obsy[i],100,5); } iShowBMP2(0, 0, filename, 0xffffff); iShowBMP2(ballx+pox-28, bally+poy-ballr/2, charbmpname, 0xffffff); if(explosion==1){ if(expframenum==34){ explosion=0; expframenum=0; soundplay(); } iShowBMP2(danx[expnum]+pox,dany[expnum]+poy-13,expframe[expframenum],0x00000); expframenum++; } } //iSetColor(0,255,0); if(level==4){ iSetColor(45,54,87); iFilledRectangle(0, 0, 1000, 700); iSetColor(255, 0, 0); iText(300,350,"Congratulations! You have completed all levels! Thank you!"); } iShowBMP2(0, 650, "Games//Menu//Menubar.bmp", 0xffffff); if(deathtimer > 0) { iShowBMP2(400, 300, "Games//dead.bmp", 0x000000); } } void iMenu(){ iShowBMP(0, 0, "Games//Menu//Menu.bmp"); iShowBMP2(412, 170, "Games//Menu//play1.bmp", 0xffffff); if(!ft)iShowBMP2(455, 170, "Games//Menu//newgame.bmp", 0xffffff); else iShowBMP2(455, 170, "Games//Menu//howto.bmp", 0xffffff); iShowBMP2(495, 170, "Games//Menu//info.bmp", 0xffffff); if(sound>0)iShowBMP2(533, 170, "Games//Menu//sound1.bmp", 0xffffff); else iShowBMP2(533, 170, "Games//Menu//sound0.bmp", 0xffffff); iShowBMP2(571, 170, "Games//Menu//quit.bmp", 0xffffff); if(mainmenu){ iSetColor(0,255,0); iText(450,140,"MAIN MENU",GLUT_BITMAP_HELVETICA_18); } } void iFailed(){ iShowBMP(0, 0, "Games//BG1.bmp"); iShowBMP2(300, 0, "Games//Menu//failed.bmp", 0xffffff); } void profile_check(){ FILE *fp = fopen("FILES//profile.txt", "r+"); int found=0, file_level; char name[20]; while(1){ fscanf(fp, "%s %d", name, &file_level); if(!strcmp(name, playername)){ playerlevel=file_level; found=1; } if(feof(fp)) break; } if(!found){ fprintf(fp, "%s %d\n", playername, 1); playerlevel=1; fclose(fp); } } void createplayername(unsigned char key){ if(key==8){ if(!namelen) return; namelen--; playername[namelen]='\0'; return; } playername[namelen] = key; namelen++; playername[namelen] = '\0'; } void iProfile(){ if(!namelen)iShowBMP(0, 0, "Games//profile//back2.bmp"); else{ iShowBMP(0, 0, "Games//profile//back.bmp"); iText(400, 183, playername, GLUT_BITMAP_TIMES_ROMAN_24); } } void smooth(){ if(level == 3 ) return; if(deadcondition == 1) return; if(GetAsyncKeyState(VK_UP) & 0x8000){ iSpecialKeyboard(GLUT_KEY_UP); } if(GetAsyncKeyState(VK_DOWN) & 0x8000){ iSpecialKeyboard(GLUT_KEY_DOWN); } if(GetAsyncKeyState(VK_RIGHT) & 0x8000){ iSpecialKeyboard(GLUT_KEY_RIGHT); } if(GetAsyncKeyState(VK_LEFT) & 0x8000){ iSpecialKeyboard(GLUT_KEY_LEFT); } if(GetAsyncKeyState(87) & 0x8000){ iSpecialKeyboard(GLUT_KEY_UP); } if(GetAsyncKeyState(83) & 0x8000){ iSpecialKeyboard(GLUT_KEY_DOWN); } if(GetAsyncKeyState(68) & 0x8000){ iSpecialKeyboard(GLUT_KEY_RIGHT); } if(GetAsyncKeyState(65) & 0x8000){ iSpecialKeyboard(GLUT_KEY_LEFT); } } void smooth1(){ if(level != 3) return; if(deadcondition == 1) return; if(GetAsyncKeyState(VK_UP) & 0x8000){ iSpecialKeyboard(GLUT_KEY_UP); } if(GetAsyncKeyState(VK_DOWN) & 0x8000){ iSpecialKeyboard(GLUT_KEY_DOWN); } if(GetAsyncKeyState(VK_RIGHT) & 0x8000){ iSpecialKeyboard(GLUT_KEY_RIGHT); } if(GetAsyncKeyState(VK_LEFT) & 0x8000){ iSpecialKeyboard(GLUT_KEY_LEFT); } if(GetAsyncKeyState(87) & 0x8000){ iSpecialKeyboard(GLUT_KEY_UP); } if(GetAsyncKeyState(83) & 0x8000){ iSpecialKeyboard(GLUT_KEY_DOWN); } if(GetAsyncKeyState(68) & 0x8000){ iSpecialKeyboard(GLUT_KEY_RIGHT); } if(GetAsyncKeyState(65) & 0x8000){ iSpecialKeyboard(GLUT_KEY_LEFT); } } void iLeaderBoard(){ iClear(); iShowBMP(0, 0, "Games//score.bmp"); char scorenum[10]; sprintf(scorenum, "%07d", levelscore); iText(162, 480, scorenum, GLUT_BITMAP_TIMES_ROMAN_24); sprintf(scorenum, "%07d", timebonus); iText(162, 400, scorenum, GLUT_BITMAP_TIMES_ROMAN_24); sprintf(scorenum, "%07d", lifebonus); iText(162, 323, scorenum, GLUT_BITMAP_TIMES_ROMAN_24); sprintf(scorenum, "%07d", score); iText(162, 203, scorenum, GLUT_BITMAP_TIMES_ROMAN_24); iText(548, 440, leaderboardname[0], GLUT_BITMAP_TIMES_ROMAN_24); iText(775, 383+67, leaderboardscores[0], GLUT_BITMAP_TIMES_ROMAN_24); if(leaderboardnum > 5) leaderboardnum = 5; for(int i=2; i<=leaderboardnum; i++){ char bmpfile[] = "Games//2.bmp"; bmpfile[7] = '0'+i; iShowBMP2(453, 415-(i-1)*67, bmpfile, 0xffffff); if(!strcmp(playername, leaderboardname[i-1])) iSetColor(255, 0, 0); else iSetColor(255, 255, 0); iText(548, 383-(i-2)*67, leaderboardname[i-1], GLUT_BITMAP_TIMES_ROMAN_24); iText(775, 383-(i-2)*67, leaderboardscores[i-1], GLUT_BITMAP_TIMES_ROMAN_24); } } void iDraw(){ if(level == -101701){ iLeaderBoard(); return; } if(level==3){ b_allposition(); } iClear(); if(!completed){ if(level==-5){ iShowBMP(0, 0, "Games//howto.bmp"); iShowBMP2(0, 650, "Games//Menu//Menubar.bmp", 0xffffff); } if(level==-6){ iShowBMP(0, 0, "Games//credits.bmp"); iShowBMP2(0, 650, "Games//Menu//Menubar.bmp", 0xffffff); } if(level==-4) iShowBMP(0, 0, intro); if(level==-3 || level==-2) iProfile(); if(level==-1) iFailed(); if(level==0) iMenu(); if(level==1 || level==2 || level==4) iLevel(); } else{ iLevelCompleted(); } if(level==3){ iShowBMP(0,0,"project image\\7.bmp"); iShowBMP2(0, 650, "Games//Menu//Menubar.bmp", 0xffffff); for(i=0;i<rectangle;i++){ iShowBMP(recx[i]+pox1,recy[i],brick[i]); //iRectangle(recx[i],recy[i],reclen[i],recwidth[i]); } iRectangle(recx[21]+pox1,recy[21],reclen[21],recwidth[21]); iRectangle(recx[22]+pox1,recy[22],reclen[22],recwidth[22]); iShowBMP(recx[18]+pox1,recy[18],brick[18]); iShowBMP(recx[19]+pox1,recy[19],brick[19]); iShowBMP(recx[20]+pox1,recy[20],"project image\\b 91.bmp"); iShowBMP(0+pox1,0,"project image\\brickbg1.bmp"); iShowBMP(410+pox1,0,"project image\\brickbg2.bmp"); iShowBMP(460+pox1,0,"project image\\brickbg3.bmp"); iShowBMP(410+pox1,140,"project image\\brickbg4.bmp"); iShowBMP(460+pox1,140,"project image\\brickbg5.bmp"); iShowBMP(710+pox1,0,"project image\\brickbg6.bmp"); iShowBMP(980+pox1,0,"project image\\brickbg7.bmp"); iShowBMP(1000+pox1,0,"project image\\brickbg8.bmp"); iShowBMP(980+pox1,100,"project image\\brickbg9.bmp"); iShowBMP(1000+pox1,100,"project image\\brickbg10.bmp"); iShowBMP(1230+pox1,0,"project image\\brickbg11.bmp"); iShowBMP(1230+pox1,140,"project image\\brickbg12.bmp"); iShowBMP(1380+pox1,0,"project image\\brickbg13.bmp"); iShowBMP(1400+pox1,0,"project image\\brickbg14.bmp"); iShowBMP(1650+pox1,0,"project image\\brickbg15.bmp"); iShowBMP(1810+pox1,0,"project image\\brickbg16.bmp"); iShowBMP(1810+pox1,140,"project image\\brickbg17.bmp"); iShowBMP(1850+pox1,0,"project image\\brickbg18.bmp"); iShowBMP(1850+pox1,140,"project image\\brickbg19.bmp"); iShowBMP(2170+pox1,0,"project image\\brickbg16.bmp"); iShowBMP(2170+pox1,140,"project image\\brickbg17.bmp"); iShowBMP(2840+pox1,0,"project image\\brickbg16.bmp"); iShowBMP(2840+pox1,140,"project image\\brickbg17.bmp"); iShowBMP(2480+pox1,0,"project image\\brickbg20.bmp"); iShowBMP(2480+pox1,140,"project image\\brickbg21.bmp"); iShowBMP(3000+pox1,250,"project image\\endpicture.bmp"); if(knockout){ iShowBMP2(ballx1+pox1,bally1,knock[index],255); } if(extralife){ iShowBMP2(1240+pox1,220,"project image\\extralife.bmp",255); } enemymovement(); enemymovement1(); minemovement(); iSetColor(0,0,255); iText(810,662,"Life: ",GLUT_BITMAP_HELVETICA_18); if(life==3){ iShowBMP2(850,650,"project image\\charlife 1.bmp",0); iShowBMP2(900,650,"project image\\charlife 1.bmp",0); iShowBMP2(950,650,"project image\\charlife 1.bmp",0); } else if(life==2){ iShowBMP2(850,650,"project image\\charlife 1.bmp",0); iShowBMP2(900,650,"project image\\charlife 1.bmp",0); } else if(life==1){ iShowBMP2(850,650,"project image\\charlife 1.bmp",0); } if(downfall){ bally1=bally1-4; } if(fire){ if(expframenum==34){ fire=false; level_3=true; expframenum=0; } iShowBMP2(x+pox1,y,expframe[expframenum],0); expframenum++; iShowBMP2(x+60+pox1,y+60,"project image\\dead.bmp",255); } if(run==0 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,stand[0],255); } else if(run==1 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,frontrun[frontindex],255); standcounter++; if(standcounter>=20){ standcounter=0; run=0; frontindex=0; } downflag=0; } else if(run==2 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,backrun[backindex],255); standcounter++; if(standcounter>=20){ standcounter=0; run=0; backindex=7; } downflag=0; } else if(run==3 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,jump1[1],255); } else if(run==4 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,jump1[3],255); } else if(run==5 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,"project image\\bjump.bmp",255); } else if(run==6 && knockout==0){ iShowBMP2(ballx1+pox1,bally1,"project image\\down.bmp",255); } if(run!=0 && run>2 && knockout==0){ standcounter++; if(standcounter>=20){ standcounter=0; run=0; } downflag=0; } checkshow(); } } void iMouseMove(int mx, int my) {} void iMouse(int button, int state, int mx, int my){ if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){ if(mainmenu){ level=0; ft=0; if(mx>=440 && mx<=560 && my>=140 && my<=175){ checkpoint=1; restart(); newgame(); completed=0; level=-2; life=3; ft=1; mainmenu=false; main_menu=true; pause=false; level_12=false; level_3=false; soundplay(); } } if(!completed){ if(level==0){ if(mx>=412 && mx<=452){ level=playerlevel; //if(playerlevel != 3) iPauseTimer() scoredekhabo=1; if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); } if(level==3){ main_menu=false; pause=false; level_12=false; level_3=true; soundplay(); } iSpecialKeyboard(GLUT_KEY_UP); ft=0; mainmenu=false; } if(mx>=455 && mx<= 495){ if(!ft){ level=playerlevel; scoredekhabo=1; life=3; if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); newgame(); } else if(level==3){ checkpoint=1; main_menu=false; pause=false; level_12=false; level_3=true; soundplay(); restart(); } } else{ level=-5; } mainmenu=false; } if(mx>495 && mx<= 535){ level=-6; } if(mx>=571 && mx<=611){ printf("Thank You %s\n", playername); exit(0); } if(mx>=533 && mx<=573){ sound*=-1; if(sound==-1){ PlaySound(0,0,0); } else if(sound==1){ if(ft==0){ main_menu=false; pause=true; level_12=false; level_3=false; soundplay(); } else{ main_menu=true; pause=false; level_12=false; level_3=false; soundplay(); } } } } } else{ if(level == -101701){ level=leaderlevel; return; } if(my >=190 && my <= 270 && mx>= 260 && mx<=340){ leaderlevel = level; level = -101701; return; } if(mx>=273 && mx<=273+127){ checkpoint=1; completed=0; level=0; life=3; ft=1; main_menu=true; pause=false; level_12=false; level_3=false; soundplay(); } if(mx>=440 && mx<=440+127){ completed=0; level=playerlevel; scoredekhabo=1; life=3; if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); newgame(); } else if(level==3){ checkpoint=1; main_menu=false; pause=false; level_12=false; level_3=true; soundplay(); restart(); } } if(mx>=600 && mx<=727){ completed=0; level=++playerlevel; scoredekhabo=1; time_elapsed=0; //level=1; leaderboard(); life=3; if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); newgame(); } else if(level==3){ checkpoint=1; main_menu=false; pause=false; level_12=false; level_3=true; soundplay(); restart(); } } mainmenu=false; } if(level>0 || level==-5 || level==-6){ if(level>0){ if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); } if(level==3){ main_menu=false; pause=false; level_12=false; level_3=true; soundplay(); } } if(mx>=0 && mx<= 50&& my>=650 &&my<=700){ mainmenu=true; if(level>0){ main_menu=false; pause=true; level_12=false; level_3=false; soundplay(); } level=0; } } else if(level == -1){ if(mx>=360 && mx <= 360 + 110){ checkpoint=1; restart(); newgame(); level=0; life=3; ft=1; main_menu=true; pause=false; level_12=false; level_3=false; soundplay(); } else if(mx>=543 && mx <= 543 + 110){ level=playerlevel; scoredekhabo=1; life=3; if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); newgame(); } else if(level==3){ checkpoint=1; main_menu=false; pause=false; level_12=false; level_3=true; fire=false; soundplay(); restart(); } } mainmenu=false; } if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {} //printf("%d %d\n",mx,my); } } void iKeyboard(unsigned char key){ if(deadcondition == 1) return; if(level == -101701){ level = leaderlevel; return; } ///notun ashche/// if(key=='A') iSpecialKeyboard(GLUT_KEY_LEFT); if(key=='S') iSpecialKeyboard(GLUT_KEY_DOWN); if(key=='D') iSpecialKeyboard(GLUT_KEY_RIGHT); if(key == 'W') iSpecialKeyboard(GLUT_KEY_UP); if(level==0 && key==13){ level=playerlevel; scoredekhabo=1; if(level==1 || level==2){ main_menu=false; pause=false; level_12=true; level_3=false; soundplay(); } if(level==3){ main_menu=false; pause=false; level_12=false; level_3=true; soundplay(); } iSpecialKeyboard(GLUT_KEY_UP); } if(level == 0 && key == 27){ printf("Thank You %s\n", playername); exit(0); } if(level!=0){ if(key == 27){ level=0; mainmenu=true; main_menu=false; pause=true; level_12=false; level_3=false; soundplay(); } } if(level == -3 || level == -2){ //printf("%d\n", key); if(level == -3 && key == 13) return; if(level==-2 && key==13){ level = 0; profile_check(); return; } createplayername(key); level=-2; } if(level==3){ if(key=='b'){ if(p==0){ p=1; ux=-25; px=20; run=5; } else if(p==1){ return; } } if(key=='f' || key=='F'){ if(p==0){ p=1; ux=25; px=20; run=4; } else if(p==1){ return; } } } } void iSpecialKeyboard(unsigned char key){ if(deadcondition == 1) return; if(level == -101701){ level = leaderlevel; return; } if(key==GLUT_KEY_RIGHT){ if(level==1 || level==2){ strcpy(charpos, "r"); if(uacon==2) return; if(uacon==1){ uacon=2; ux+=2; return; } if(obstacle_check(ballx+speed, bally)==1){ ballx+=speed; } speedtimer=1500; } if(level==3){ //level=3 if(knockout==0 && p==0){ downintersect=0; if(ballfly==0 && ballx1+ballr1+5>=recx[cp+1] && type[cp+1]==1 && downfall==0){ run=1; frontindex++; if(frontindex>=8){ frontindex=0; } return; } else if(ballfly==1 && ballx1+ballr1+5>=recx[cp+1] && bally1 <=recy[cp+1]+recwidth[cp+1] && downfall==0){ run=1; frontindex++; if(frontindex>=8){ frontindex=0; } return; } else if(ballfly==1 && bally1>recy[cp+1]+recwidth[cp+1] && downfall==0){ ballx1=ballx1+4; if(ballx1>2510) { pox1=-2460; } else if(ballx1>1950) { pox1=-1850; } else if(ballx1>1465) { pox1=-1400; } else if(ballx1>1080) { pox1=-1000; } else if(ballx1>560) { pox1=-450; } run=4; frontindex++; if(frontindex>=8){ frontindex=0; } } else{ if(ballfly==1 && downfall==0){ run=4; ballx1=ballx1+4; if(ballx1>2510) { pox1=-2460; } else if(ballx1>1950) { pox1=-1850; } else if(ballx1>1465) { pox1=-1400; } else if(ballx1>1080) { pox1=-1000; } else if(ballx1>560) { pox1=-450; } } else if(downfall==0){ ballx1=ballx1+7; if(ballx1>2510) { pox1=-2460; } else if(ballx1>1950) { pox1=-1850; } else if(ballx1>1465) { pox1=-1400; } else if(ballx1>1080) { pox1=-1000; } else if(ballx1>560) { pox1=-450; } run=1; frontindex++; if(frontindex>=8){ frontindex=0; } } } } } } if(key==GLUT_KEY_LEFT){ if(level==1 || level==2){ //printf("obspos: %lf %lf, %lf -- %lf, %lf %lf\n", ballx, bally, obsx[6], obsx[6]+obsl[6], obsy[6], obsb[6]+obsy[6]); strcpy(charpos, "l"); if(uacon==2) return; if(uacon==1){ uacon=2; ux=-3; return; } if(obstacle_check(ballx-speed-10, bally)==1){ ballx-=speed; strcpy(charpos, "l"); } speedtimer2=1500; } if(level==3){ if(knockout==0 && p==0){ downintersect=0; if(ballfly==1 && ballx1-5<recx[cp] && bally1<=recy[cp-1]+recwidth[cp-1] && downfall==0){ run=2; backindex--; if(backindex<0){ backindex=7; } return; } else if((ballfly==0 && (ballx1-5<recx[cp] || ballx1-5<recx[cp-1]) && bally1<recy[cp-1]+recwidth[cp-1])||(ballx1-5<0)){ if(downfall==0){ run=2; backindex--; if(backindex<0){ backindex=7; } return; } } else{ if(ballfly==1 && downfall==0){ run=5; ballx1=ballx1-4; if(ballx1<560) { pox1=0; } else if(ballx1<1080) { pox1=-450; } else if(ballx1<1465) { pox1=-1000; } else if(ballx1<1950) { pox1=-1400; } else if(ballx1<2510) { pox1=-1850; } } else if(downfall==0){ ballx1=ballx1-7; if(ballx1<560) { pox1=0; } else if(ballx1<1080) { pox1=-450; } else if(ballx1<1465) { pox1=-1000; } else if(ballx1<1950) { pox1=-1400; } else if(ballx1<2510) { pox1=-1850; } run=2; backindex--; if(backindex<0){ backindex=7; } } } } } } if(key==GLUT_KEY_UP){ if((level==1 || level==2) && jump<4){ jump++; if(jump%2==1){ upanimation(); } } if(level==3 && knockout==0 && p==0){ downintersect=0; if(bally1+60>screenwidth+50){ return; } else if(downfall==0){ bally1=bally1+8; run=3; } } } if(key==GLUT_KEY_DOWN && level==3 && knockout==0){ if(ballfly==0 && downfall==0){ run=6; downflag=1; downintersect=1; return; } if(bally1-5<recy[cp]+recwidth[cp] && downfall==0){ run=0; downintersect=0; return; } if(downfall==0){ bally1=bally1-5; run=0; downintersect=0; } } } void change(){ if(level==3){ if(life==0 && fire==false){ checkpoint=1; extralife=1; knockout=0; level=-1; } else if(life==0 && fire==true){ return; } else{ for(int i=0;i<numrightobstacles;i++){ enemy[i].birdx-=enemy[i].speed; if(downintersect==1){ if(areaintersect(ballx1,ballx1+35,bally1,bally1+39,enemy[i].birdx,enemy[i].birdy,enemy[i].birdx+35,enemy[i].birdy+37) && knockout==0){ fire=true; soundplay(); x=enemy[i].birdx; y=enemy[i].birdy; enemy[i].birdshow=false; life--; knockout=1; } } else if(areaintersect(ballx1,ballx1+40,bally1,bally1+60,enemy[i].birdx,enemy[i].birdy,enemy[i].birdx+35,enemy[i].birdy+37) && knockout==0){ fire=true; soundplay(); x=enemy[i].birdx; y=enemy[i].birdy; enemy[i].birdshow=false; life--; knockout=1; } if(!enemy[i].birdshow){ enemy[i].birdx=screenlength+rand()%8000; enemy[i].birdy=120+rand()%520; enemy[i].speed=6+rand()%5; enemy[i].birdshow=true; } if(enemy[i].birdx<=0){ enemy[i].birdx=screenlength+rand()%8000; enemy[i].birdy=120+rand()%520; enemy[i].speed=6+rand()%5; enemy[i].birdshow=true; } } ///change1 for(int i=0;i<numdownobstacles;i++){ enemy1[i].birdy-=enemy1[i].speed; if(downintersect==1){ if(areaintersect(ballx1,ballx1+35,bally1,bally1+39,enemy1[i].birdx,enemy1[i].birdy,enemy1[i].birdx+35,enemy1[i].birdy+37) && knockout==0){ fire=true; soundplay(); x=enemy1[i].birdx; y=enemy1[i].birdy; enemy1[i].birdshow=false; life--; knockout=1; } } else if(areaintersect(ballx1,ballx1+40,bally1,bally1+60,enemy1[i].birdx,enemy1[i].birdy,enemy1[i].birdx+35,enemy1[i].birdy+37) && knockout==0){ fire=true; soundplay(); x=enemy1[i].birdx; y=enemy1[i].birdy; enemy1[i].birdshow=false; life--; knockout=1; } if(!enemy1[i].birdshow){ enemy1[i].birdx=100+rand()%1260; enemy1[i].birdy=screenwidth+rand()%6000; enemy1[i].speed=5+rand()%5; enemy1[i].birdshow=true; } if(enemy1[i].birdy<=0){ enemy1[i].birdy=screenwidth+rand()%6000; enemy1[i].birdx=100+rand()%1260; enemy1[i].speed=5+rand()%5; enemy1[i].birdshow=true; } } ///minechange for(i=0;i<minenumber;i++){ if(mine[i].mineindex==0){ mine[i].mnx+=mine[i].minespeed; if(mine[i].mnx+25>mine[i].minex+mine[i].minelen){ mine[i].mineindex=1; } } else if(mine[i].mineindex==1){ mine[i].mnx-=mine[i].minespeed; if(mine[i].mnx<mine[i].minex){ mine[i].mineindex=0; } } if(areaintersect(ballx1,ballx1+40,bally1,bally1+60,mine[i].mnx,mine[i].miney,mine[i].mnx+25,mine[i].miney+37) && knockout==0){ life--; if(mine[i].mineindex==0){ knockout=2; } else if(mine[i].mineindex==1){ knockout=1; } } } if(mine[4].mineindex==2){ mine[4].miney+=mine[4].minespeed; if(mine[4].miney+5>mine[4].mnx+mine[4].minelen){ mine[i].mineindex=3; } } else if(mine[4].mineindex==3){ mine[4].miney-=mine[i].minespeed; if(mine[4].miney<mine[4].mnx){ mine[4].mineindex=2; } } if(areaintersect(ballx1,ballx1+40,bally1,bally1+60,mine[4].minex,mine[i].miney,mine[i].minex+30,mine[i].miney+30) && knockout==0){ life--; knockout=2; } } } } void setenemyvariables(){ for(int i=0;i<numrightobstacles;i++){ enemy[i].birdx=screenlength+rand()%10000; enemy[i].birdy=120+rand()%520; enemy[i].birdindex=rand()%7; enemy[i].speed=6+rand()%5; enemy[i].birdshow=true; } } void setenemyvariables1(){ for(int i=0;i<numdownobstacles;i++){ enemy1[i].birdy=screenwidth+rand()%10000; enemy1[i].birdx=100+rand()%1260; enemy1[i].birdindex=rand()%4; enemy1[i].speed=6+rand()%5; enemy1[i].birdshow=true; } } void minevariables(){ mine[0].minex=720; mine[0].mnx=720; mine[0].miney=110; mine[0].minelen=250; mine[0].mineindex=0; mine[0].minespeed=2; mine[1].minex=1230; mine[1].mnx=1230; mine[1].miney=210; mine[1].minelen=150; mine[1].mineindex=0; mine[1].minespeed=1; mine[2].minex=1810; mine[2].mnx=1810; mine[2].miney=240; mine[2].minelen=200; mine[2].mineindex=0; mine[2].minespeed=1.5; mine[3].minex=2480; mine[3].mnx=2480; mine[3].miney=250; mine[3].minelen=250; mine[3].mineindex=0; mine[3].minespeed=2; mine[4].minex=2900; mine[4].mnx=250; mine[4].miney=250; mine[4].minelen=200; mine[4].mineindex=2; mine[4].minespeed=4; } int main(){ newgame(); restart(); minevariables(); setenemyvariables(); setenemyvariables1(); iSetTimer(50, introbmpname); iSetTimer(80, smooth); iSetTimer(40, smooth1); iSetTimer(10, timer); iSetTimer(100, charcondition); iSetTimer(20,change); iSetTimer(80,ko); iSetTimer(50,checkshow); if(main_menu && sound>0){ PlaySound("Musix\\main menu.wav",NULL,SND_LOOP | SND_ASYNC); } iInitialize(screenlength,screenwidth+50, "Asobu Ka Shino"); return 0; }
[ "1805088@ugrad.cse.buet.ac.bd" ]
1805088@ugrad.cse.buet.ac.bd
9c4f41767a9cd7cad1d77a0b0eb33e5a59cde78e
4df8055d92200482e57126b3a9243c63725e2d8e
/PAT乙级/1050. 螺旋矩阵(25).cpp
53f5c47b56713fb602364ec3e911c901e148c023
[]
no_license
tekikesyo/PAT
47afa12e0852c011b412cd494182a888fd9a67e9
3f8c9e960477b4cb5521a3a894a67a348093f2b5
refs/heads/master
2020-05-24T14:59:09.825371
2018-02-21T14:54:56
2018-02-21T14:54:56
null
0
0
null
null
null
null
GB18030
C++
false
false
1,735
cpp
/*1050. 螺旋矩阵(25) 本题要求将给定的N个正整数按非递增的顺序,填入“螺旋矩阵”。 所谓“螺旋矩阵”,是指从左上角第1个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为m行n列,满足条件:m*n等于N;m>=n;且m-n取所有可能值中的最小值。 输入格式: 输入在第1行中给出一个正整数N,第2行给出N个待填充的正整数。所有数字不超过104,相邻数字以空格分隔。 输出格式: 输出螺旋矩阵。每行n个数字,共m行。相邻数字以1个空格分隔,行末不得有多余空格。 输入样例: 12 37 76 20 98 76 42 53 95 60 81 58 93 输出样例: 98 95 93 42 37 81 53 20 76 58 60 76 */ #include <cstdio> #include <iostream> #include <cstring> #include <string> #include <cmath> #include <vector> #include <algorithm> using namespace std; int func(int N) { int i = sqrt((double)N); while(i >= 1) { if(N % i == 0) return i; i--; } return 1; } bool cmp(int a, int b){ return a>b; } int main(){ int n; cin>>n; vector<int> a(n); int i,j; for(i=0; i<n; i++) cin>>a[i]; sort(a.begin(), a.end(), cmp); int x,y; x = func(n); y = n/x; //cout<<"n:"<<n<<" x:"<<x<<" y:"<<y<<endl; vector<vector<int>> num(y, vector<int>(x)); int k=0,l=0; int level = y/2 + y%2; for(int k=0; k<level; k++){ for(i=k; i<=x-k-1&&l<=n-1; i++) num[k][i]=a[l++]; for(i=k+1; i<=y-k-1&&l<=n-1; i++) num[i][x-k-1]=a[l++]; for(i=x-k-2; i>=k&&l<=n-1; i--) num[y-k-1][i]=a[l++]; for(i=y-k-2; i>=k+1&&l<=n-1; i--) num[i][k]=a[l++]; } for(i=0; i<y; i++){ for(j=0; j<x; j++){ cout<<num[i][j]; if(j!=x-1) cout<<" "; } cout<<endl; } system("pause"); return 0; }
[ "hushhw@sina.cn" ]
hushhw@sina.cn
420298532d5967f94c1095bb3e9a77b27d91a672
d6639a198f1c0fe58e64e2df1f4bc09d9e0978f4
/guts/UnitTest.cpp
f677d4e637ff09c2f0e46ccf8357b693fa7e7c94
[]
no_license
erwincoumans/motion-toolkit
746d258b0c6ce174645bbf5f6330ede2e9c911a3
2c0537f1eed4e8cc6caddbdd2bbb6a1b08761d1a
refs/heads/master
2016-09-06T17:04:03.305131
2015-03-05T16:49:12
2015-03-05T16:49:12
31,723,860
5
0
null
null
null
null
UTF-8
C++
false
false
2,268
cpp
#include "HashTable.hpp" #include "BinomialQueue.hpp" #include <iostream> #include <guts/Set.hpp> #include <guts/String.hpp> #include <consolid/rand32.h> typedef guts::BinomialQueue<int> Queue_t; void testQueue() { Queue_t queue; for (int i = 0; i != 100; ++i) { int x = rand32() % 97; std::cout << x << ' '; queue.push(x); } queue.decrease_key(0, 0); std::cout << std::endl; while (!queue.empty()) { int x = queue.pop(); std::cout << x << ' '; } } typedef guts::HashTable<guts::String> HashTable; static const int NUM_ITER = 1000; static const int INT_RANGE = 100000; static guts::String names[INT_RANGE]; void initNames() { for (int i = 0; i != INT_RANGE; ++i) { int length = rand32() % 32; names[i].resize(length); for (int j = 0; j != length; ++j) { names[i][j] = 'A' + (rand32() % 26); } } } unsigned int hash(int x) { return x; } void testHashTable() { HashTable hashTable(10000); for (int i = 0; i != NUM_ITER; ++i) { guts::String x = names[rand32() % INT_RANGE]; if (hashTable.retrieve(x) == 0) { //std::cout << x << ' '; hashTable.insert(x); } } //std::cout << std::endl; while (!hashTable.empty()) { guts::String x = names[rand32() % INT_RANGE]; if (hashTable.retrieve(x) != 0) { hashTable.remove(x); //std::cout << x << ' '; } } } void testSet() { guts::Set<guts::String>::RT set; for (int i = 0; i != NUM_ITER; ++i) { guts::String x = names[rand32() % INT_RANGE]; if (set.find(x) == set.end()) { //std::cout << x << ' '; set.insert(x); } } //std::cout << std::endl; while (!set.empty()) { guts::String x = names[rand32() % INT_RANGE]; if (set.find(x) != set.end()) { set.erase(x); //std::cout << x << ' '; } } } int main() { initNames(); //testQueue(); for (int k = 0; k != 100; ++k) { testHashTable(); } //testSet(); return 0; }
[ "gino.vandenbergen@0fc17d2e-f052-159a-51ff-853d4e1552da" ]
gino.vandenbergen@0fc17d2e-f052-159a-51ff-853d4e1552da
ced47c8e5728b242c3607267a21aa8be52c5a6e1
663305e4fc1cc44ce032cfbff001d7beb21d6e92
/osrm-backend/include/extractor/guidance/intersection_generator.hpp
4d23eff11a07f71541aff9fb63117215bfdeb176
[ "BSD-2-Clause" ]
permissive
yangkedc1984/Source_Codes_Collected
19e1c5887c6d5654bc76bae364a304964433a59c
668467e74301a42eebf3085add344a5ac1323120
refs/heads/master
2023-01-09T15:14:43.355589
2020-11-08T10:12:31
2020-11-08T10:12:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,835
hpp
#ifndef OSRM_EXTRACTOR_GUIDANCE_INTERSECTION_GENERATOR_HPP_ #define OSRM_EXTRACTOR_GUIDANCE_INTERSECTION_GENERATOR_HPP_ #include "extractor/compressed_edge_container.hpp" #include "extractor/guidance/coordinate_extractor.hpp" #include "extractor/guidance/intersection.hpp" #include "extractor/guidance/intersection_normalization_operation.hpp" #include "extractor/query_node.hpp" #include "extractor/restriction_map.hpp" #include "util/attributes.hpp" #include "util/node_based_graph.hpp" #include "util/typedefs.hpp" #include <unordered_set> #include <utility> #include <vector> #include <boost/optional.hpp> namespace osrm { namespace extractor { namespace guidance { struct IntersectionGenerationParameters { NodeID nid; EdgeID via_eid; }; // The Intersection Generator is given a turn location and generates an intersection representation // from it. For this all turn possibilities are analysed. // We consider turn restrictions to indicate possible turns. U-turns are generated based on profile // decisions. class IntersectionGenerator { public: IntersectionGenerator(const util::NodeBasedDynamicGraph &node_based_graph, const RestrictionMap &restriction_map, const std::unordered_set<NodeID> &barrier_nodes, const std::vector<QueryNode> &node_info_list, const CompressedEdgeContainer &compressed_edge_container); // For a source node `a` and a via edge `ab` creates an intersection at target `b`. // // a . . . b . . // . // . // IntersectionView operator()(const NodeID nid, const EdgeID via_eid) const; /* * Compute the shape of an intersection, returning a set of connected roads, without any further * concern for which of the entries are actually allowed. * The shape also only comes with turn bearings, not with turn angles. All turn angles will be * set to zero */ OSRM_ATTR_WARN_UNUSED IntersectionShape ComputeIntersectionShape(const NodeID center_node, const boost::optional<NodeID> sorting_base = boost::none, bool use_low_precision_angles = false) const; // Graph Compression cannot compress every setting. For example any barrier/traffic light cannot // be compressed. As a result, a simple road of the form `a ----- b` might end up as having an // intermediate intersection, if there is a traffic light in between. If we want to look farther // down a road, finding the next actual decision requires the look at multiple intersections. // Here we follow the road until we either reach a dead end or find the next intersection with // more than a single next road. This function skips over degree two nodes to find coorect input // for GetConnectedRoads. OSRM_ATTR_WARN_UNUSED IntersectionGenerationParameters SkipDegreeTwoNodes(const NodeID starting_node, const EdgeID via_edge) const; // Allow access to the coordinate extractor for all owners const CoordinateExtractor &GetCoordinateExtractor() const; // Check for restrictions/barriers and generate a list of valid and invalid turns present at // the node reached from `from_node` via `via_eid`. The resulting candidates have to be analysed // for their actual instructions later on. // The switch for `use_low_precision_angles` enables a faster mode that will procude less // accurate coordinates. It should be good enough to check order of turns, find straightmost // turns. Even good enough to do some simple angle verifications. It is mostly available to // allow for faster graph traversal in the extraction phase. OSRM_ATTR_WARN_UNUSED IntersectionView GetConnectedRoads(const NodeID from_node, const EdgeID via_eid, const bool use_low_precision_angles = false) const; /* * To be used in the road network, we need to check for valid/restricted turns. These two * functions transform a basic intersection / a normalised intersection into the * correct view when entering via a given edge. */ OSRM_ATTR_WARN_UNUSED IntersectionView TransformIntersectionShapeIntoView(const NodeID previous_node, const EdgeID entering_via_edge, const IntersectionShape &intersection) const; // version for normalised intersection OSRM_ATTR_WARN_UNUSED IntersectionView TransformIntersectionShapeIntoView( const NodeID previous_node, const EdgeID entering_via_edge, const IntersectionShape &normalised_intersection, const IntersectionShape &intersection, const std::vector<IntersectionNormalizationOperation> &merging_map) const; private: const util::NodeBasedDynamicGraph &node_based_graph; const RestrictionMap &restriction_map; const std::unordered_set<NodeID> &barrier_nodes; const std::vector<QueryNode> &node_info_list; // own state, used to find the correct coordinates along a road const CoordinateExtractor coordinate_extractor; // check turn restrictions to find a node that is the only allowed target when coming from a // node to an intersection // d // | // a - b - c and `only_straight_on ab | bc would return `c` for `a,b` boost::optional<NodeID> GetOnlyAllowedTurnIfExistent(const NodeID coming_from_node, const NodeID node_at_intersection) const; }; } // namespace guidance } // namespace extractor } // namespace osrm #endif /* OSRM_EXTRACTOR_GUIDANCE_INTERSECTION_GENERATOR_HPP_ */
[ "pmiori@gmail.com" ]
pmiori@gmail.com