blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
5385b37dfb13dcd354f8b239e755062727bbc0a3
f84451e430bb3b1816a4baac3125b80fab9ccaf0
/sources/EventManager.cpp
c9ce319338988cb404b73de69b4376c9ece25472
[]
no_license
Ignust/EventQueue.v2
387d486a76ed6a3feb714995d7029c40047e52bc
ccd0f399be42fd5c73ebb2c2ad7be5cddb0e979d
refs/heads/master
2022-12-01T21:03:43.044350
2020-07-29T10:55:35
2020-07-29T10:55:35
272,453,536
0
0
null
2020-07-29T10:55:36
2020-06-15T13:59:41
C++
UTF-8
C++
false
false
3,804
cpp
#include "EventManager.hpp" #include "ThreadCout.hpp" #include <thread> //#include <iostream> //using namespace std; //------------------------------------------------------------------------------------------ EventManager::EventManager() : mHandlerThreadRunning(false) //------------------------------------------------------------------------------------------ { } //------------------------------------------------------------------------------------------ EventManager::~EventManager() //------------------------------------------------------------------------------------------ { ThreadCout::get().print("EventManager::~EventManager()"); } //------------------------------------------------------------------------------------------ void EventManager::pushEvent(std::shared_ptr<Event> event) //------------------------------------------------------------------------------------------ { std::lock_guard<std::mutex> lock(mMutexSubscribers); if (mHandlerThreadRunning){ mEventQueue.push(event); } } //------------------------------------------------------------------------------------------ void EventManager::subscribe(EAction event, BasicEventHandler* handler) //------------------------------------------------------------------------------------------ { //ThreadCout::get().print("EventManager::subscribe-------------"); std::lock_guard<std::mutex> lock(mMutexSubscribers); mSubscribersMap[event].push_back(handler); if(!mHandlerThreadRunning){ mHandlerThreadRunning = true; std::thread th([&](){manageEvents();}); th.detach(); } } //------------------------------------------------------------------------------------------ void EventManager::unsubscribe(EAction event,BasicEventHandler* handler) //------------------------------------------------------------------------------------------ { std::lock_guard<std::mutex> lock(mMutexSubscribers); auto pair = mSubscribersMap.find(event); if (pair == mSubscribersMap.end()){ return; } auto & list = pair->second; for (auto it = list.begin(); it != list.end(); ++it) { if (*it == handler){ //ThreadCout::get().print("EventManager::unsubscriptionToEvent()---"); it = list.erase(it); break; } } if(list.empty()){ mSubscribersMap.erase(event); } mHandlerThreadRunning = !mSubscribersMap.empty(); } //------------------------------------------------------------------------------------------ void EventManager::manageEvents() //------------------------------------------------------------------------------------------ { //ThreadCout::get().print("EventManager::manageEvents() start"); while (mHandlerThreadRunning) { while (!mEventQueue.empty()) { mMutexEvents.lock(); std::shared_ptr<Event> tempEvent = mEventQueue.front(); mEventQueue.pop(); mMutexEvents.unlock(); sendEvent(tempEvent); } } //ThreadCout::get().print("EventManager::manageEvents() end"); } //------------------------------------------------------------------------------------------ void EventManager::sendEvent(std::shared_ptr<Event> event) //------------------------------------------------------------------------------------------ { std::lock_guard<std::mutex> lock(mMutexSubscribers); auto pair = mSubscribersMap.find(event->action); if (pair != mSubscribersMap.end()) { const auto & list = pair->second; for (auto & subscriber : list) { std::ostringstream os; os << "EventManager::sendEvent to "<<subscriber->getName() << std::endl; ThreadCout::get().print(os); subscriber->handleEvent(event); } } }
[ "andrey.las90@gmail.com" ]
andrey.las90@gmail.com
4c3359aef878b25961c0315170646b3d11e1e8b6
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/ui/browser_element_identifiers.cc
469a4b148972786129d4c885d67b16b9bff1f382
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
4,736
cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/browser_element_identifiers.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/interaction/element_tracker.h" // Please keep this list alphabetized. DEFINE_ELEMENT_IDENTIFIER_VALUE(kAddCurrentTabToReadingListElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kAppUninstallDialogOkButtonId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kAutofillCreditCardSuggestionEntryElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kAutofillSuggestionElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kBookmarkBarElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kBookmarkSidePanelWebViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kBookmarkStarViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kBrowserViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kCookieControlsIconElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kDeviceSignalsConsentCancelButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kDeviceSignalsConsentOkButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kEnhancedProtectionSettingElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kExclusiveAccessBubbleViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kExtensionsMenuButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kExtensionsRequestAccessButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kHighEfficiencyChipElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kInstallPwaElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kIntentChipElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kLocationIconElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kNewTabButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kOfferNotificationChipElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kOmniboxElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kPasswordsOmniboxKeyIconElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kPriceInsightsChipElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kPriceTrackingBookmarkViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kPriceTrackingChipElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kReadLaterSidePanelWebViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSavePasswordComboboxElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSavedTabGroupBarElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSavedTabGroupButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSavedTabGroupOverflowButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSavedTabGroupOverflowMenuId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelCloseButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelComboboxElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelCompanionToolbarButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelOpenInNewTabButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelPinButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSidePanelReadingListUnreadElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSideSearchButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kSideSearchWebViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabAlertIndicatorButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabGroupEditorBubbleCloseGroupButtonId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabGroupEditorBubbleId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabGroupEditorBubbleSaveToggleId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabGroupHeaderElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabSearchBubbleElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabSearchButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabStripElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTabStripRegionElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarAppMenuButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarAvatarButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarBackButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarBatterySaverButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarDownloadButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarForwardButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarMediaButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarSidePanelButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kToolbarTabCounterButtonElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kTopContainerElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kUserNotesSidePanelWebViewElementId); DEFINE_ELEMENT_IDENTIFIER_VALUE(kWebUIIPHDemoElementIdentifier); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kBrowserThemeChangedEventId); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kSidePanelComboboxChangedCustomEventId); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kSidePanelReadingMarkedAsReadEventId); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kSideSearchResultsClickedCustomEventId); DEFINE_CUSTOM_ELEMENT_EVENT_TYPE(kTabGroupedCustomEventId);
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
5c6f33d08f4bda45c566d07265fac311b395fca5
dd4dd96a601c3d0cc5472764a1ce2b7ec7d2a51a
/algorithm_study/2019.07.22_easy/2851_superMario.cpp
de1e5a40372224244df2a962fcf5834646cf40aa
[]
no_license
Bambia/Algorithm
23c56beba9c763ba3fc40b62d14d8773915f47a3
52b0ec5f00647fc39c4cd8a60419d011828cacc2
refs/heads/master
2022-02-26T19:36:39.377541
2019-11-16T12:59:42
2019-11-16T12:59:42
178,593,942
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
#include <iostream> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int totalScore =0,score[10]={0,},ans=0; for(int i=0; i<10; i++){ cin >> score[i]; } for(int i=0; i<10; i++){ totalScore += score[i]; if(totalScore > 100) { int cmp = totalScore - score[i]; if( (totalScore-100) - (100-cmp) <= 0) ans = totalScore; else if((totalScore-100) - (100-cmp) > 0) ans = cmp; break; } else ans = totalScore; } cout <<ans <<'\n'; return 0; }
[ "hoyean250@gmail.com" ]
hoyean250@gmail.com
f40e9ea554fc74f23cbe27c409cef3b044046217
f92bbd5524cf8c110836f7df04bace27e21617b1
/src/uint256.h
5b9574a6df9b15077e8b73535f1a20b27450cfd8
[ "MIT" ]
permissive
Palem1988/beacon
da0a03672996eeeb2f68470cb0f2f2e5667e005d
c93b771b5b217180819a04cd10596857751fa8bb
refs/heads/master
2020-08-05T08:12:16.519794
2019-08-21T00:03:59
2019-08-21T00:03:59
212,460,108
0
1
MIT
2019-10-02T23:22:29
2019-10-02T23:22:21
null
UTF-8
C++
false
false
11,445
h
// 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 // Copyright (c) 2018 LightPayCoin developers // Copyright (c) 2018 The Beacon developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UINT256_H #define BITCOIN_UINT256_H #include <assert.h> #include <cstring> #include <stdexcept> #include <stdint.h> #include <string> #include <vector> class uint_error : public std::runtime_error { public: explicit uint_error(const std::string& str) : std::runtime_error(str) {} }; /** Template base class for unsigned big integers. */ template <unsigned int BITS> class base_uint { protected: enum { WIDTH = BITS / 32 }; uint32_t pn[WIDTH]; public: base_uint() { for (int i = 0; i < WIDTH; i++) pn[i] = 0; } base_uint(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] = b.pn[i]; } bool IsNull() const { for (int i = 0; i < WIDTH; i++) if (pn[i] != 0) return false; return true; } void SetNull() { memset(pn, 0, sizeof(pn)); } base_uint& operator=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] = b.pn[i]; return *this; } base_uint(uint64_t b) { pn[0] = (unsigned int)b; pn[1] = (unsigned int)(b >> 32); for (int i = 2; i < WIDTH; i++) pn[i] = 0; } explicit base_uint(const std::string& str); explicit base_uint(const std::vector<unsigned char>& vch); bool operator!() const { for (int i = 0; i < WIDTH; i++) if (pn[i] != 0) return false; return true; } const base_uint operator~() const { base_uint ret; for (int i = 0; i < WIDTH; i++) ret.pn[i] = ~pn[i]; return ret; } const base_uint operator-() const { base_uint ret; for (int i = 0; i < WIDTH; i++) ret.pn[i] = ~pn[i]; ret++; return ret; } double getdouble() const; base_uint& operator=(uint64_t b) { pn[0] = (unsigned int)b; pn[1] = (unsigned int)(b >> 32); for (int i = 2; i < WIDTH; i++) pn[i] = 0; return *this; } base_uint& operator^=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] ^= b.pn[i]; return *this; } base_uint& operator&=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] &= b.pn[i]; return *this; } base_uint& operator|=(const base_uint& b) { for (int i = 0; i < WIDTH; i++) pn[i] |= b.pn[i]; return *this; } base_uint& operator^=(uint64_t b) { pn[0] ^= (unsigned int)b; pn[1] ^= (unsigned int)(b >> 32); return *this; } base_uint& operator|=(uint64_t b) { pn[0] |= (unsigned int)b; pn[1] |= (unsigned int)(b >> 32); return *this; } base_uint& operator<<=(unsigned int shift); base_uint& operator>>=(unsigned int shift); base_uint& operator+=(const base_uint& b) { uint64_t carry = 0; for (int i = 0; i < WIDTH; i++) { uint64_t n = carry + pn[i] + b.pn[i]; pn[i] = n & 0xffffffff; carry = n >> 32; } return *this; } base_uint& operator-=(const base_uint& b) { *this += -b; return *this; } base_uint& operator+=(uint64_t b64) { base_uint b; b = b64; *this += b; return *this; } base_uint& operator-=(uint64_t b64) { base_uint b; b = b64; *this += -b; return *this; } base_uint& operator*=(uint32_t b32); base_uint& operator*=(const base_uint& b); base_uint& operator/=(const base_uint& b); base_uint& operator++() { // prefix operator int i = 0; while (++pn[i] == 0 && i < WIDTH - 1) i++; return *this; } const base_uint operator++(int) { // postfix operator const base_uint ret = *this; ++(*this); return ret; } base_uint& operator--() { // prefix operator int i = 0; while (--pn[i] == (uint32_t)-1 && i < WIDTH - 1) i++; return *this; } const base_uint operator--(int) { // postfix operator const base_uint ret = *this; --(*this); return ret; } int CompareTo(const base_uint& b) const; bool EqualTo(uint64_t b) const; friend inline const base_uint operator+(const base_uint& a, const base_uint& b) { return base_uint(a) += b; } friend inline const base_uint operator-(const base_uint& a, const base_uint& b) { return base_uint(a) -= b; } friend inline const base_uint operator*(const base_uint& a, const base_uint& b) { return base_uint(a) *= b; } friend inline const base_uint operator/(const base_uint& a, const base_uint& b) { return base_uint(a) /= b; } friend inline const base_uint operator|(const base_uint& a, const base_uint& b) { return base_uint(a) |= b; } friend inline const base_uint operator&(const base_uint& a, const base_uint& b) { return base_uint(a) &= b; } friend inline const base_uint operator^(const base_uint& a, const base_uint& b) { return base_uint(a) ^= b; } friend inline const base_uint operator>>(const base_uint& a, int shift) { return base_uint(a) >>= shift; } friend inline const base_uint operator<<(const base_uint& a, int shift) { return base_uint(a) <<= shift; } friend inline const base_uint operator*(const base_uint& a, uint32_t b) { return base_uint(a) *= b; } friend inline bool operator==(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) == 0; } friend inline bool operator!=(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) != 0; } friend inline bool operator>(const base_uint& a, const base_uint& b) { return a.CompareTo(b) > 0; } friend inline bool operator<(const base_uint& a, const base_uint& b) { return a.CompareTo(b) < 0; } friend inline bool operator>=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) >= 0; } friend inline bool operator<=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) <= 0; } friend inline bool operator==(const base_uint& a, uint64_t b) { return a.EqualTo(b); } friend inline bool operator!=(const base_uint& a, uint64_t b) { return !a.EqualTo(b); } std::string GetHex() const; void SetHex(const char* psz); void SetHex(const std::string& str); std::string ToString() const; std::string ToStringReverseEndian() const; unsigned char* begin() { return (unsigned char*)&pn[0]; } unsigned char* end() { return (unsigned char*)&pn[WIDTH]; } const unsigned char* begin() const { return (unsigned char*)&pn[0]; } const unsigned char* end() const { return (unsigned char*)&pn[WIDTH]; } unsigned int size() const { return sizeof(pn); } uint64_t Get64(int n = 0) const { return pn[2 * n] | (uint64_t)pn[2 * n + 1] << 32; } /** * Returns the position of the highest bit set plus one, or zero if the * value is zero. */ unsigned int bits() const; uint64_t GetLow64() const { assert(WIDTH >= 2); return pn[0] | (uint64_t)pn[1] << 32; } unsigned int GetSerializeSize(int nType, int nVersion) const { return sizeof(pn); } template <typename Stream> void Serialize(Stream& s, int nType, int nVersion) const { s.write((char*)pn, sizeof(pn)); } template <typename Stream> void Unserialize(Stream& s, int nType, int nVersion) { s.read((char*)pn, sizeof(pn)); } friend class uint160; friend class uint256; friend class uint512; }; /** 160-bit unsigned big integer. */ class uint160 : public base_uint<160> { public: uint160() {} uint160(const base_uint<160>& b) : base_uint<160>(b) {} uint160(uint64_t b) : base_uint<160>(b) {} explicit uint160(const std::string& str) : base_uint<160>(str) {} explicit uint160(const std::vector<unsigned char>& vch) : base_uint<160>(vch) {} }; /** 256-bit unsigned big integer. */ class uint256 : public base_uint<256> { public: uint256() {} uint256(const base_uint<256>& b) : base_uint<256>(b) {} uint256(uint64_t b) : base_uint<256>(b) {} explicit uint256(const std::string& str) : base_uint<256>(str) {} explicit uint256(const std::vector<unsigned char>& vch) : base_uint<256>(vch) {} /** * The "compact" format is a representation of a whole * number N using an unsigned 32bit number similar to a * floating point format. * The most significant 8 bits are the unsigned exponent of base 256. * This exponent can be thought of as "number of bytes of N". * The lower 23 bits are the mantissa. * Bit number 24 (0x800000) represents the sign of N. * N = (-1^sign) * mantissa * 256^(exponent-3) * * Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn(). * MPI uses the most significant bit of the first byte as sign. * Thus 0x1234560000 is compact (0x05123456) * and 0xc0de000000 is compact (0x0600c0de) * * Bitcoin only uses this "compact" format for encoding difficulty * targets, which are unsigned 256bit quantities. Thus, all the * complexities of the sign bit and using base 256 are probably an * implementation accident. */ uint256& SetCompact(uint32_t nCompact, bool* pfNegative = NULL, bool* pfOverflow = NULL); uint32_t GetCompact(bool fNegative = false) const; uint64_t GetHash(const uint256& salt) const; }; /* uint256 from const char *. * This is a separate function because the constructor uint256(const char*) can result * in dangerously catching uint256(0). */ inline uint256 uint256S(const char* str) { uint256 rv; rv.SetHex(str); return rv; } /* uint256 from std::string. * This is a separate function because the constructor uint256(const std::string &str) can result * in dangerously catching uint256(0) via std::string(const char*). */ inline uint256 uint256S(const std::string& str) { uint256 rv; rv.SetHex(str); return rv; } /** 512-bit unsigned big integer. */ class uint512 : public base_uint<512> { public: uint512() {} uint512(const base_uint<512>& b) : base_uint<512>(b) {} uint512(uint64_t b) : base_uint<512>(b) {} explicit uint512(const std::string& str) : base_uint<512>(str) {} explicit uint512(const std::vector<unsigned char>& vch) : base_uint<512>(vch) {} uint256 trim256() const { uint256 ret; for (unsigned int i = 0; i < uint256::WIDTH; i++) { ret.pn[i] = pn[i]; } return ret; } }; inline uint512 uint512S(const std::string& str) { uint512 rv; rv.SetHex(str); return rv; } #endif // BITCOIN_UINT256_H
[ "41976657+beaconcrypto@users.noreply.github.com" ]
41976657+beaconcrypto@users.noreply.github.com
71788b02f1b52bae539655c039c91d9ebafd51da
5b97626e70689ce1c7e47133cfbf0245c0801065
/sensors/src/OneWireSensor.h
fbcdf5f098544a7726f9759c882ed1a8079bad7d
[ "Apache-2.0" ]
permissive
ieb/signalk-esp32-bridge
5f0d606bcd7a90535536646a134af419c40503d4
77838e2f40b3edf316a712dfbafdd7910d440967
refs/heads/master
2021-12-23T09:58:56.858265
2020-01-24T18:36:39
2020-01-24T18:36:39
236,060,319
1
0
null
2021-09-02T05:39:50
2020-01-24T18:33:56
JavaScript
UTF-8
C++
false
false
5,033
h
#ifndef __ONEWIRESENSOR_H__ #define __ONEWIRESENSOR_H__ #include "common.h" #ifndef TEST #define REQUIRESALARMS false #include <OneWire.h> #include <DallasTemperature.h> #define log(x) Serial.println(x) #define logHex(x) Serial.print(x, HEX) #else #define logHex(x) std::cout << x #endif #define MAX_SENSORS 5 #define VALUES_CHARACTERISTIC_UUID "f3f7dd8f-6fee-47fd-a1bf-8785cf19b622" #define IDS_CHARACTERISTIC_UUID "ee0c174e-deb8-459b-a981-a4bfd9b18ffe" DeviceAddress sensor1 = { 0x28, 0xFF, 0x51, 0x2A, 0xA3, 0x16, 0x3, 0xCD }; class OneWireSensor: public SkSensor, public BLECharacteristicCallbacks { public: typedef struct { unsigned long age; uint16_t readDuration; uint8_t nSensors; float temperature[MAX_SENSORS]; } one_wire_readings; typedef struct { uint8_t nSensors; uint8_t addresses[sizeof(DeviceAddress)*MAX_SENSORS]; } one_wire_ids; OneWireSensor(uint8_t oneWireBus) { oneWire = new OneWire(oneWireBus); sensors = new DallasTemperature(oneWire); sensors->begin(); findSensors(); if ( oneWireIds.nSensors == 0 ) { enabled = false; log("No 1wire devices attached."); return; } enabled = true; logb("Number Found :"); log(oneWireIds.nSensors); valuesCharacteristic = new BLEUUID(VALUES_CHARACTERISTIC_UUID); idsCharacteristic = new BLEUUID(IDS_CHARACTERISTIC_UUID); readDelay = 10000; log("OneWireSensort setup complete "); } ~OneWireSensor() { } void findSensors() { oneWire->reset_search(); for( int i = 0; i < MAX_SENSORS; i++ ) { // allocate space for the sensor address, its a unit8_t[] if ( !oneWire->search( &oneWireIds.addresses[sizeof(DeviceAddress)*i]) ) { oneWireIds.nSensors = i; temperatures.nSensors = i; break; } logb("Found Sensor at :"); printAddress(&oneWireIds.addresses[sizeof(DeviceAddress)*i]); } for (int i = 0; i < oneWireIds.nSensors; i++) { sensors->setResolution(&oneWireIds.addresses[sizeof(DeviceAddress)*i], 12); // 12 bit precision 0.0625 C } } void printAddress(DeviceAddress deviceAddress) { for (uint8_t i = 0; i < 8; i++) { // zero pad the address if necessary if (deviceAddress[i] < 16) logb("0"); logHex(deviceAddress[i]); } log(""); } /* * SkSensor interface */ const char * getName() { return "OneWire at values f3f7dd8f-6fee-47fd-a1bf-8785cf19b622 and ids ee0c174e-deb8-459b-a981-a4bfd9b18ffe"; } BLEUUID getCharacteristicUUID(uint8_t i) { if ( i == 0 ) { return *valuesCharacteristic;; } return *idsCharacteristic; } uint8_t getAccess(uint8_t i) { if ( i == 0 ) { return BLECharacteristic::PROPERTY_READ; } return BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE; } uint8_t getNCharacteristics() { if ( enabled ) { return 2; } return 0; } BLECharacteristicCallbacks * getCallbacks(uint8_t i) { return this; } /* * BLECharacteristicCallbacks interface */ void onRead(BLECharacteristic* pcharac) { lock(); BLEUUID uuid = pcharac->getUUID(); if ( idsCharacteristic->equals(uuid) ) { pcharac->setValue((uint8_t *)&oneWireIds, sizeof(one_wire_ids)); } else { temperatures.age = millis() - lastRead; pcharac->setValue((uint8_t *)&temperatures, sizeof(one_wire_readings)); } unlock(); } void onWrite(BLECharacteristic* pcharac) { lock(); BLEUUID uuid = pcharac->getUUID(); if ( idsCharacteristic->equals(uuid) ) { uint8_t * data = pcharac->getData(); readDelay = ((unsigned long *)data)[0]; logb("Read Delay now :"); log(readDelay); findSensors(); } unlock(); } /* * PeriodicOperation interface */ void started() { log("ReadSensors Started"); } void finished() { log("ReadSensors Exited"); } void lock() { // xSemaphoreTake(sem, portMAX_DELAY); } void unlock() { // xSemaphoreGive(sem); } void execute() { lock(); unsigned long now = millis(); sensors->requestTemperatures(); // if the last read value wasnt read, then extend the duration for (int i = 0; i < temperatures.nSensors; i++) { temperatures.temperature[i] = sensors->getTempC(&oneWireIds.addresses[sizeof(DeviceAddress)*i]); //*sensorAddress[i]); logb(temperatures.temperature[i]); logb(" "); printAddress(&oneWireIds.addresses[sizeof(DeviceAddress)*i]); //*sensorAddress[i]); } lastRead = millis(); temperatures.readDuration = (uint16_t) (lastRead - now); unlock(); } unsigned long getDelay() { return readDelay; } private: DallasTemperature * sensors; OneWire * oneWire; unsigned long readDelay; unsigned long lastRead; SemaphoreHandle_t sem; BLEUUID * valuesCharacteristic; BLEUUID * idsCharacteristic; one_wire_ids oneWireIds; one_wire_readings temperatures; }; #endif
[ "ieb@tfd.co.uk" ]
ieb@tfd.co.uk
f444d2f75352105b9a3a55ff269b655854fe63a7
eb827d7993b146cf507b57a45e420fffdf641eef
/itmo/20201123/d_cube.cpp
c4ed5d6f965d45c7b2840b3c87e7d8ec4eceecad
[]
no_license
khbminus/code2020
dfdbcae71d61d03d4457aad47ff7d4136e6fcc1e
a0d2230b0905df79ba78cb98353f4ba03f16e8b0
refs/heads/master
2023-07-16T16:08:20.629283
2021-08-29T20:35:14
2021-08-29T20:35:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
cpp
#include <bits/stdc++.h> #include <ostream> using namespace std; using ll = long long; #define SZ(x) (int)((x).size()) #define ALL(x) (x).begin(), (x).end() #define RALL(x) (x).rbegin(), (x).rend() #define TMAX(type) numeric_limits<type>::max() #define TMIN(type) numeric_limits<type>::min() #ifdef LOCAL #define ass(X) assert(X) #else #define ass(X) {} #endif int n; const int MAXN = 105; pair<int, int> arr[MAXN]; int solve() { if (!(cin >> n)) return 1; for (int i = 0; i < n; i++) cin >> arr[i].first >> arr[i].second; int ans = 1e9; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) for (int k = j + 1; k < n; k++){ int a = arr[i].first; int b = arr[j].first; int c = arr[k].first; if (a < b + c && b < a + c && c < a + b) ans = min(ans, arr[i].second + arr[j].second + arr[k].second); } if (ans < 1e9) cout << ans << '\n'; else cout << "-1\n"; return 0; } signed main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tests = 1e9; // cin >> tests; for (int i = 1; i <= tests; i++) { if (solve()) break; #ifdef LOCAL cout << "------------------------------\n"; #endif } }
[ "serega.haritontsev@gmail.com" ]
serega.haritontsev@gmail.com
8a923f918cfeeecfadf426b77083ffcdfe0c4383
c6769a12358e53c52fddfdcacb78344d446b1771
/CastorTree/src/GetEvtId.cc
2a43eae76f905a8567cdc4a9dd1a722d4d459a07
[]
no_license
xueweiphy/UACastor
d8717970b9843adc79513b51ea4c8294d89e40f3
91893bfb195ecd980b2afaf28e3fa045bca35745
refs/heads/master
2020-12-25T21:13:41.178545
2012-11-06T09:57:22
2012-11-06T09:57:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,858
cc
//-- Description: Function to retrieve Evt Id information (original author: Xavier Janssen) //-- system include files #include <iostream> //-- user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/Luminosity/interface/LumiSummary.h" #include "DataFormats/Luminosity/interface/LumiDetails.h" #include "./CastorTree.h" bool EvtIdDebug = false; void CastorTree::GetEvtId(const edm::Event& iEvent) { using namespace std; EvtId.Reset(); EvtId.Run = iEvent.id().run() ; EvtId.Evt = iEvent.id().event() ; EvtId.LumiBlock = iEvent.luminosityBlock(); edm::Timestamp Time = iEvent.time(); EvtId.Time = Time.value(); EvtId.IsData = iEvent.isRealData(); EvtId.ExpType = iEvent.experimentType(); EvtId.Bunch = iEvent.bunchCrossing(); EvtId.Orbit = iEvent.orbitNumber(); if (iEvent.isRealData()) { // Get instantanious lumi information edm::LuminosityBlock const& lumiBlock = iEvent.getLuminosityBlock(); edm::Handle<LumiSummary> lumiSummary; edm::Handle<LumiDetails> d; lumiBlock.getByLabel("lumiProducer",d); lumiBlock.getByLabel("lumiProducer", lumiSummary); const LumiSummary *lumi=lumiSummary.product(); const float istlumi=lumi->avgInsDelLumi(); const float istlumierr=d->lumiError(LumiDetails::kOCC1,iEvent.bunchCrossing()); EvtId.IstLumi = istlumi; EvtId.IstLumiErr = istlumierr; // This is the call to get the lumi per bx: double istlumiPerBX=d->lumiValue(LumiDetails::kOCC1,iEvent.bunchCrossing()); EvtId.IstLumiPerBX = istlumiPerBX; } if(EvtIdDebug) EvtId.Print(); }
[ "" ]
9a06629d3d8c5d6f66c86c6f8ac7a498c56780aa
2cf5dadd5fe8f18d6b7a107f3566913698f3f3e1
/系统模块/游戏组件/36.港式五张/游戏服务器/GameServerManager.cpp
afdba177fac22d86cca389fba8f635d869f9f4db
[]
no_license
xiaokaixuan/qipai-game
319a5af77a490daf4c825ca7f54bc0b0bbf5c1a0
fce39d8192c1ea037ff34abec3d6074d56071934
refs/heads/master
2021-01-13T16:23:13.757533
2012-06-11T10:53:16
2012-06-11T10:53:16
54,963,680
1
0
null
2016-03-29T09:35:54
2016-03-29T09:35:53
null
GB18030
C++
false
false
3,914
cpp
#include "StdAfx.h" #include "Tableframesink.h" #include "GameServerManager.h" //#include "AndroidUserItemSink.h" ////////////////////////////////////////////////////////////////////////// //全局变量 static CGameServiceManager g_GameServiceManager; //管理变量 ////////////////////////////////////////////////////////////////////////// //构造函数 CGameServiceManager::CGameServiceManager(void) { //设置属性 m_GameServiceAttrib.wKindID=KIND_ID; m_GameServiceAttrib.wChairCount=GAME_PLAYER; m_GameServiceAttrib.cbJoinInGame = FALSE; lstrcpyn(m_GameServiceAttrib.szKindName,GAME_NAME,CountArray(m_GameServiceAttrib.szKindName)); lstrcpyn(m_GameServiceAttrib.szDataBaseName,TEXT("QPTreasureDB"),CountArray(m_GameServiceAttrib.szDataBaseName)); lstrcpyn(m_GameServiceAttrib.szDescription,TEXT("港式五张游戏服务组件"),CountArray(m_GameServiceAttrib.szDescription)); lstrcpyn(m_GameServiceAttrib.szClientModuleName,TEXT("HKFiveCard.exe"),CountArray(m_GameServiceAttrib.szClientModuleName)); lstrcpyn(m_GameServiceAttrib.szServerModuleName,TEXT("HKFiveCardServer.DLL"),CountArray(m_GameServiceAttrib.szServerModuleName)); return; } //析构函数 CGameServiceManager::~CGameServiceManager(void) { } //接口查询 void * __cdecl CGameServiceManager::QueryInterface(const IID & Guid, DWORD dwQueryVer) { QUERYINTERFACE(IGameServiceManager,Guid,dwQueryVer); QUERYINTERFACE_IUNKNOWNEX(IGameServiceManager,Guid,dwQueryVer); return NULL; } //创建游戏桌 void * __cdecl CGameServiceManager::CreateTableFrameSink(const IID & Guid, DWORD dwQueryVer) { //建立对象 CTableFrameSink * pTableFrameSink=NULL; try { pTableFrameSink=new CTableFrameSink(); if (pTableFrameSink==NULL) throw TEXT("创建失败"); void * pObject=pTableFrameSink->QueryInterface(Guid,dwQueryVer); if (pObject==NULL) throw TEXT("接口查询失败"); return pObject; } catch (...) {} //清理对象 SafeDelete(pTableFrameSink); return NULL; } //获取属性 void __cdecl CGameServiceManager::GetGameServiceAttrib(tagGameServiceAttrib & GameServiceAttrib) { GameServiceAttrib=m_GameServiceAttrib; return; } //参数修改 bool __cdecl CGameServiceManager::RectifyServiceOption(tagGameServiceOption * pGameServiceOption) { //效验参数 ASSERT(pGameServiceOption!=NULL); if (pGameServiceOption==NULL) return false; //积分调整 pGameServiceOption->lCellScore=__max(1L,pGameServiceOption->lCellScore); //积分下限 if (pGameServiceOption->wServerType==GAME_GENRE_GOLD) { pGameServiceOption->lLessScore=__max(pGameServiceOption->lCellScore*10L,pGameServiceOption->lLessScore); } //积分上限 if (pGameServiceOption->lRestrictScore!=0L) { pGameServiceOption->lRestrictScore=__max(pGameServiceOption->lRestrictScore,pGameServiceOption->lLessScore); } return true; } //创建机器 VOID * __cdecl CGameServiceManager::CreateAndroidUserItemSink(REFGUID Guid, DWORD dwQueryVer) { ////变量定义 //CAndroidUserItemSink * pAndroidUserItemSink=NULL; //try //{ // //建立对象 // pAndroidUserItemSink=new CAndroidUserItemSink(); // if (pAndroidUserItemSink==NULL) throw TEXT("创建失败"); // //查询接口 // void * pObject=pAndroidUserItemSink->QueryInterface(Guid,dwQueryVer); // if (pObject==NULL) throw TEXT("接口查询失败"); // return pObject; //} //catch (...) {} ////删除对象 //SafeDelete(pAndroidUserItemSink); return NULL; } ////////////////////////////////////////////////////////////////////////// //建立对象函数 extern "C" __declspec(dllexport) void * __cdecl CreateGameServiceManager(const GUID & Guid, DWORD dwInterfaceVer) { return g_GameServiceManager.QueryInterface(Guid,dwInterfaceVer); } //////////////////////////////////////////////////////////////////////////
[ "pybmfc@gmail.com" ]
pybmfc@gmail.com
4af5d5dafdb54d8679fe9147c4a3eae93eeb57fe
c9cf0e050090d8a7ed43e88cbdbc7f1959e1223f
/src/share/core_configuration/profile/simple_modifications.hpp
43e9e7bdacb421f8801fca93e4c30684189cda35
[ "Unlicense" ]
permissive
chrismetcalf/Karabiner-Elements
47380a0f1d6abe6a88e3613007087ada313b59ca
0b0ecd4bc3bc26840a1d5bf625a6def0949277a6
refs/heads/master
2020-12-30T22:33:20.605540
2017-03-28T22:34:48
2017-03-28T22:34:48
86,512,848
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
hpp
#pragma once class simple_modifications final { public: simple_modifications(const nlohmann::json& json) { if (json.is_object()) { for (auto it = json.begin(); it != json.end(); ++it) { // it.key() is always std::string. if (it.value().is_string()) { std::string value = it.value(); pairs_.emplace_back(it.key(), value); } } std::sort(pairs_.begin(), pairs_.end(), [](const std::pair<std::string, std::string>& a, const std::pair<std::string, std::string>& b) { return SI::natural::compare<std::string>(a.first, b.first); }); } } nlohmann::json to_json(void) const { auto json = nlohmann::json::object(); for (const auto& it : pairs_) { if (!it.first.empty() && !it.second.empty() && json.find(it.first) == json.end()) { json[it.first] = it.second; } } return json; } const std::vector<std::pair<std::string, std::string>>& get_pairs(void) const { return pairs_; } void push_back_pair(void) { pairs_.emplace_back("", ""); } void erase_pair(size_t index) { if (index < pairs_.size()) { pairs_.erase(pairs_.begin() + index); } } void replace_pair(size_t index, const std::string& from, const std::string& to) { if (index < pairs_.size()) { pairs_[index].first = from; pairs_[index].second = to; } } void replace_second(const std::string& from, const std::string& to) { for (auto&& it : pairs_) { if (it.first == from) { it.second = to; return; } } } std::unordered_map<key_code, key_code> to_key_code_map(spdlog::logger& logger) const { std::unordered_map<key_code, key_code> map; for (const auto& it : pairs_) { auto& from_string = it.first; auto& to_string = it.second; auto from_key_code = types::get_key_code(from_string); if (!from_key_code) { logger.warn("unknown key_code:{0}", from_string); continue; } auto to_key_code = types::get_key_code(to_string); if (!to_key_code) { logger.warn("unknown key_code:{0}", to_string); continue; } map[*from_key_code] = *to_key_code; } return map; } private: std::vector<std::pair<std::string, std::string>> pairs_; };
[ "tekezo@pqrs.org" ]
tekezo@pqrs.org
f49e6169dff2d1e935ad68bc5a7f55cdf8edcf96
7656fc93da6ca8399f684fa884f21cfa5943a5d9
/simulation/src/DataVisualisation.cc
03bdff3737c8e03e21ac2c790f3ac03b42801803
[]
no_license
cdreisbach/PRM_SimpleG4
b980fc8160815c380889c783fd38afb4947cc096
656c79b964ba798ca7f0f742ae1de6386739bd16
refs/heads/main
2023-03-02T15:41:27.347382
2021-02-12T16:27:10
2021-02-12T16:27:10
338,288,931
0
0
null
null
null
null
UTF-8
C++
false
false
2,922
cc
#include "DataVisualisation.hh" #include "DataManager.hh" #include <TFile.h> #include <TH1D.h> #include <TGraph.h> #include <TCanvas.h> DataVisualisation* DataVisualisation::_instance = nullptr; DataVisualisation::DataVisualisation() {} DataVisualisation::~DataVisualisation() {} DataVisualisation* DataVisualisation::getInstance() { if( _instance == nullptr ) { _instance = new DataVisualisation(); } return _instance; } void DataVisualisation::saveHistograms() { DataManager::getInstance()->getOutputFile()->cd(); for ( const auto &histogram : this->_histograms ) { histogram->Write(); } } void DataVisualisation::saveGraphs() { DataManager::getInstance()->getOutputFile()->cd(); for( const auto& graph : this->_graphs ) { graph->Write(); } } void DataVisualisation::saveCanvae() { DataManager::getInstance()->getOutputFile()->cd(); for( const auto& canvas : this->_canvae ) { canvas->Write(); } } TH1 *DataVisualisation::createHistogram( TH1 *histogram ) { // Check for existing histogram bool existing = false; for( const auto& myHistogram : this->_histograms ) { if( myHistogram->GetName() == histogram->GetName() ) { existing = true; std::cout << "WARNING: Histogram with name " << histogram->GetName() << " already existing!" << std::endl; } } if( !existing ) { this->_histograms.push_back(histogram); } return histogram; } void DataVisualisation::saveData() { // Save graphs this->saveGraphs(); // Save histograms this->saveHistograms(); // Save canvae this->saveCanvae(); } TH1* DataVisualisation::makeLogBinningX( TH1* histogram ) { TAxis* axis = histogram->GetXaxis(); int bins = axis->GetNbins(); Axis_t from = axis->GetXmin(); Axis_t to = axis->GetXmax(); Axis_t width = (to - from) / bins; Axis_t* new_bins = new Axis_t[bins + 1]; for (int i = 0; i <= bins; i++) { new_bins[i] = pow(10, from + i * width); } axis->Set(bins, new_bins); delete[] new_bins; return histogram; } TGraph *DataVisualisation::createGraph(const std::string& name, TGraph *graph) { // Set name graph->SetName(name.c_str()); graph->SetTitle(""); // Check for existing graph bool existing = false; for( const auto& myGraph : this->_graphs ) { if( myGraph->GetName() == graph->GetName() ) { existing = true; std::cout << "WARNING: Histogram with name " << graph->GetName() << " already existing!" << std::endl; } } if( !existing ) { this->_graphs.push_back(graph); } return graph; } TCanvas* DataVisualisation::createCanvas( TCanvas *canvas ) { // Check for existing graph bool existing = false; for( const auto& myCanvas : this->_canvae ) { if( myCanvas->GetName() == canvas->GetName() ) { existing = true; std::cout << "WARNING: Canvas with name " << canvas->GetName() << " already existing!" << std::endl; } } if( !existing ) { this->_canvae.push_back(canvas); } return canvas; }
[ "christian.dreisbach@cern.ch" ]
christian.dreisbach@cern.ch
627448401ac205c8d633b27ffffeca227edc47d3
03f3739257988cda7542f20686104206b7a459c9
/PAT-B-1032.cpp
1f3318df8463b33b5d9fa21eb9af1737561fd2d8
[ "MIT" ]
permissive
tentonlien/personal-algorithm-practice
3bf038226c0a13e5046d51423c1cf71f22895e81
7303dcddff8d7e80f8451ddd738dedd2e7debe81
refs/heads/master
2020-03-22T00:00:58.917291
2018-06-30T04:38:42
2018-06-30T04:38:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
392
cpp
#include <iostream> using namespace std; int main() { static int sch[100000],stu[100000],scr[100000],n,max; cin>>n; for(int i=0;i<n;i++) { cin>>sch[i]>>stu[i]; scr[sch[i]-1]+=stu[i]; if(max<sch[i]-1) { max=sch[i]-1; } } int maxx=0; for(int i=0;i<max;i++) { if(scr[i]>scr[maxx]) { maxx=i; } } cout<<maxx+1<<" "<<scr[maxx]<<endl; return 0; }
[ "noreply@github.com" ]
tentonlien.noreply@github.com
78a5ad2c6ea370d842fdcde92d9696f09ebe9678
7e0b1bb05f7f482239579bf0dc60dead4fac63df
/Single_Number_v3.cpp
8e715ce0cb9d8043f19c017af0807dd70ab9b343
[ "MIT" ]
permissive
xiekch/leetcode
0bc8b4cd05d93e64218a4dd4ed0894996b403010
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
refs/heads/master
2023-05-25T06:55:32.835498
2023-05-02T09:17:25
2023-05-02T09:17:25
166,329,519
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
#include <iostream> #include <set> #include <vector> using namespace std; // Given a non-empty array of integers, every element appears twice except for // one. // Find that single one. // Your algorithm should have a linear runtime complexity. // Could you implement it without using extra memory? // https://leetcode.com/problems/single-number/solution/#approach-3-math class Solution { public: int singleNumber(vector<int> &nums) { set<int> s; int sumOfSet = 0, sumOfNums = 0; for (int i : nums) { if (s.count(i) == 0) { s.insert(i); sumOfSet += i; } sumOfNums += i; } return 2 * sumOfSet - sumOfNums; } }; Solution sol; int main(int argc, char const *argv[]) { vector<int> test = {4, 2, 4}; // {4, 1, 2, 1, 2, 4, 5}; cout << sol.singleNumber(test) << endl; return 0; }
[ "xiekch@qq.com" ]
xiekch@qq.com
6cb3e858200903698feb56c0cba34e1f8238c8dd
db9065ac82fd6684121656b4e89b4172db428ef9
/Системное программирование в среде Windows, Дж. Харт/Гл 4. Исключения/Гл 4. Исключения/main.cpp
734ea220c0ff5e151f6e81afa89a2674f49f25d6
[]
no_license
Northell/WinAPI-in-Cpp
254ed292bbdc8e32857c4f8762019d4ba1df9c40
c87d4fecad12364db514c00030ea68366989bffe
refs/heads/master
2021-12-23T02:51:09.081426
2021-10-31T19:39:06
2021-10-31T19:39:06
236,188,626
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,493
cpp
#include <windows.h> #include <iostream> /* * стр 129, гл4.1 Обычная обработка исключений */ //bool createTempFile() //{ // std::string TempFile; //Путь к файлу // HANDLE hFile; // GetTempFileName(TempFile, ...); // while (...) __try { // hFile = CreateFile(TempFile, ..., OPEN_ALWAYS, ...); // SetFilePointer(hFile, 0, NULL, FILE_END); // ... // WriteFile(hFile, ...); // i = *p; //В этом месте программы возможно возникновение исключения // CloseHandle(hFile); // // } // __except (EXEPTION_EXECUTE_HANDLER) // { // CloseHandle(hFile); // DeleteFile(TempFile); // /*Переход к выполнению очередной итерации цикла*/ // } // /*Сюда пережается управление после нормального завершения цикла.*/ //} /*Стр 137, ReportException Расширение функции ReportError для генерации формируемого приложением кода исключения вместо прекращения выполнения процесса. */ VOID ReportException(LPCSTR UserMessage, DWORD ExceptionCode) { ReportError(UserMessage, 0, TRUE); //Если ошибка критическая, сгенерировать исключение if (ExceptionCode != 0) { RaiseException((0xFFFFFFFF & ExceptionCode) | 0xE0000000, 0, 0, NULL); } return; } int main() { return 0; }
[ "northells@yandex.ru" ]
northells@yandex.ru
367f61c412bc810b3f669dce54443a35136f1a0c
365d06f77730399b85e78af4e59a55093eaef488
/src/Game.cpp
10e04e7dbec265ddc2114d260345cde788373a05
[]
no_license
MikeAndTheWorld/Rocket-Wars
bd4c3ece290f6a7fdbff73f6969a86c08760cba0
1707feb9c1c843efc03d461c56c713f4d69169aa
refs/heads/master
2021-03-24T12:18:19.251500
2017-04-02T05:44:43
2017-04-02T05:44:43
78,676,724
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
#include "Game.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <math.h> #include <string> #include <glm.hpp> #include <gtx/transform.hpp> #include <time.h> void Game::GameLoop(Window *window,Scene & scene) { //time const float TickPS = 1.0f / 60.0f; double NewTimer = glfwGetTime(); double DeltaTime = NewTimer - OldTimer; while (DeltaTime < TickPS) { NewTimer = glfwGetTime(); DeltaTime = NewTimer - OldTimer; //time step (h) } OldTimer = NewTimer; //std::cout << DeltaTime << " " << TickPS << " " << std::endl; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear scene.Update(DeltaTime); // update scene.Render(); //render glfwSwapBuffers(window->getWindow()); //window glfwPollEvents(); //window->camera.CameraUpdate(window->getWindow()); } ///////// Main loop ///////////////////////////////////// int main() { Window * window = new Window(1920, 1080 - 20);// size glewExperimental = GL_TRUE; glewInit(); glEnable(GL_DEPTH_TEST); Scene scene; // scene Game game; // game srand(time(NULL)); //FpsCamera * m_FpsCamera = new FpsCamera(window->getWindow()); scene.initScene(); // Enter the main loop while (!glfwWindowShouldClose(window->getWindow()) && !glfwGetKey(window->getWindow(), GLFW_KEY_ESCAPE)) { game.GameLoop(window, scene); } // Close window and terminate GLFW glfwTerminate(); // Exit program exit(EXIT_SUCCESS); }
[ "noreply@github.com" ]
MikeAndTheWorld.noreply@github.com
0f53fbfc729016452a313a0466aa2dbefd2619ba
ee3ca02cd75391d7f52b778b495a0661a235ac8f
/src/Sonar.h
66d3d51e6f30cd12e370ec7d0c52253377c30ebc
[]
no_license
GMIG/Instruments-Arduino
3e85731e6191fa819268ea5089fbb05f5c91c362
c5a4ce6e15886f1adcd67e4472c0839253da7d94
refs/heads/master
2020-06-20T05:27:40.137648
2019-11-06T09:25:02
2019-11-06T09:25:02
197,006,249
0
0
null
null
null
null
UTF-8
C++
false
false
910
h
#ifndef SONAR_H #define SONAR_H #include "Commandable.h" class Sonar :public Sense{ private: int pinTrig; int pinEcho; int lastDuration; int curDuration; int thr = 80; int getDataString(char * result){ sprintf(result, "%d", curDuration - lastDuration); lastDuration = curDuration; return 0; } bool hasDataToSend(){ digitalWrite(pinTrig, LOW); delayMicroseconds(2); digitalWrite(pinTrig, HIGH); delayMicroseconds(10); digitalWrite(pinTrig, LOW); curDuration = pulseIn(pinEcho, HIGH, 2000); return (abs(curDuration - lastDuration) > thr); } public: Sonar(int _pinTrig, int _pinEcho,const char * _name, ITransport* transport, bool pullup = true): Sense(transport,_name){ pinTrig = _pinTrig; pinEcho = _pinEcho; pinMode(pinTrig, OUTPUT); pinMode(pinEcho, INPUT); char r[5]; dt("100",r); } }; #endif
[ "ivan.bichenko@gmail.com" ]
ivan.bichenko@gmail.com
1b63436c741b46f626f998f0dac85c0cc9512332
8567438779e6af0754620a25d379c348e4cd5a5d
/third_party/WebKit/Source/platform/graphics/paint/PropertyTreeState.h
4bc47b12d3e873d48b453d12c87ddb4e2b4e6a3a
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
thngkaiyuan/chromium
c389ac4b50ccba28ee077cbf6115c41b547955ae
dab56a4a71f87f64ecc0044e97b4a8f247787a68
refs/heads/master
2022-11-10T02:50:29.326119
2017-04-08T12:28:57
2017-04-08T12:28:57
84,073,924
0
1
BSD-3-Clause
2022-10-25T19:47:15
2017-03-06T13:04:15
null
UTF-8
C++
false
false
6,415
h
// Copyright 2016 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 PropertyTreeState_h #define PropertyTreeState_h #include "platform/graphics/paint/ClipPaintPropertyNode.h" #include "platform/graphics/paint/EffectPaintPropertyNode.h" #include "platform/graphics/paint/TransformPaintPropertyNode.h" #include "wtf/HashFunctions.h" #include "wtf/HashTraits.h" #include "wtf/text/StringBuilder.h" namespace blink { // A complete set of paint properties including those that are inherited from // other objects. RefPtrs are used to guard against use-after-free bugs and // DCHECKs ensure PropertyTreeState never retains the last reference to a // property tree node. class PLATFORM_EXPORT PropertyTreeState { public: PropertyTreeState(const TransformPaintPropertyNode* transform, const ClipPaintPropertyNode* clip, const EffectPaintPropertyNode* effect) : m_transform(transform), m_clip(clip), m_effect(effect) { DCHECK(!m_transform || !m_transform->hasOneRef()); DCHECK(!m_clip || !m_clip->hasOneRef()); DCHECK(!m_effect || !m_effect->hasOneRef()); } bool hasDirectCompositingReasons() const; const TransformPaintPropertyNode* transform() const { DCHECK(!m_transform || !m_transform->hasOneRef()); return m_transform.get(); } void setTransform(RefPtr<const TransformPaintPropertyNode> node) { m_transform = std::move(node); } const ClipPaintPropertyNode* clip() const { DCHECK(!m_clip || !m_clip->hasOneRef()); return m_clip.get(); } void setClip(RefPtr<const ClipPaintPropertyNode> node) { m_clip = std::move(node); } const EffectPaintPropertyNode* effect() const { DCHECK(!m_effect || !m_effect->hasOneRef()); return m_effect.get(); } void setEffect(RefPtr<const EffectPaintPropertyNode> node) { m_effect = std::move(node); } // Returns the compositor element id, if any, for this property state. If // neither the effect nor transform nodes have a compositor element id then a // default instance is returned. const CompositorElementId compositorElementId() const; enum InnermostNode { None, // None means that all nodes are their root values Transform, Clip, Effect, }; // There is always a well-defined order in which the transform, clip // and effects of a PropertyTreeState apply. This method returns which // of them applies first to content drawn with this PropertyTreeState. // Note that it may be the case that multiple nodes from the same tree apply // before any from another tree. This can happen, for example, if multiple // effects or clips apply to a descendant transform state from the transform // node. // // This method is meant to be used in concert with // |PropertyTreeStateIterator|, which allows one to iterate over the nodes in // the order in which they apply. // // Example: // // Transform tree Clip tree Effect tree // ~~~~~~~~~~~~~~ ~~~~~~~~~ ~~~~~~~~~~~ // Root Root Root // | | | // T C E // // Suppose that PropertyTreeState(T, C, E).innerMostNode() is E, and // PropertytreeState(T, C, Root).innermostNode() is C. Then a PaintChunk // that has propertyTreeState = PropertyTreeState(T, C, E) can be painted // with the following display list structure: // // [BeginTransform] [BeginClip] [BeginEffect] PaintChunk drawings // [EndEffect] [EndClip] [EndTransform] // // The PropertyTreeStateIterator will behave like this: // // PropertyTreeStateIterator iterator(PropertyTreeState(T, C, E)); // DCHECK(iterator.innermostNode() == Effect); // DCHECK(iterator.next()->innermostNode() == Clip); // DCHECK(iterator.next()->innermostNode() == Transform); // DCHECK(iterator.next()->innermostNode() == None); InnermostNode innermostNode() const; #if DCHECK_IS_ON() // Dumps the tree from this state up to the root as a string. String toTreeString() const; #endif private: RefPtr<const TransformPaintPropertyNode> m_transform; RefPtr<const ClipPaintPropertyNode> m_clip; RefPtr<const EffectPaintPropertyNode> m_effect; }; inline bool operator==(const PropertyTreeState& a, const PropertyTreeState& b) { return a.transform() == b.transform() && a.clip() == b.clip() && a.effect() == b.effect(); } // Iterates over the sequence transforms, clips and effects for a // PropertyTreeState between that state and the "root" state (all nodes equal // to *::Root()), in the order that they apply. // // See also PropertyTreeState::innermostNode for a more detailed example. class PLATFORM_EXPORT PropertyTreeStateIterator { public: PropertyTreeStateIterator(const PropertyTreeState& properties) : m_properties(properties) {} const PropertyTreeState* next(); private: PropertyTreeState m_properties; }; #if DCHECK_IS_ON() template <typename PropertyTreeNode> class PropertyTreeStatePrinter { public: String pathAsString(const PropertyTreeNode* lastNode) { const PropertyTreeNode* node = lastNode; while (!node->isRoot()) { addPropertyNode(node, ""); node = node->parent(); } addPropertyNode(node, "root"); StringBuilder stringBuilder; addAllPropertyNodes(stringBuilder, node); return stringBuilder.toString(); } void addPropertyNode(const PropertyTreeNode* node, String debugInfo) { m_nodeToDebugString.set(node, debugInfo); } void addAllPropertyNodes(StringBuilder& stringBuilder, const PropertyTreeNode* node, unsigned indent = 0) { DCHECK(node); for (unsigned i = 0; i < indent; i++) stringBuilder.append(' '); if (m_nodeToDebugString.contains(node)) stringBuilder.append(m_nodeToDebugString.at(node)); stringBuilder.append(String::format(" %p ", node)); stringBuilder.append(node->toString()); stringBuilder.append("\n"); for (const auto* childNode : m_nodeToDebugString.keys()) { if (childNode->parent() == node) addAllPropertyNodes(stringBuilder, childNode, indent + 2); } } HashMap<const PropertyTreeNode*, String> m_nodeToDebugString; }; #endif } // namespace blink #endif // PropertyTreeState_h
[ "hedonist.ky@gmail.com" ]
hedonist.ky@gmail.com
1c17d35dc3e854ee53e4c7c615795146f8a4161c
0df3aac8e0affbbd00171efe78d838c357cd854c
/code/Lecture12Final/build-Lecture12-Desktop_Qt_5_9_9_MinGW_32bit-Debug/debug/moc_gchooser.cpp
86cff2549164738ce19f9de689a60991bfdd3188
[]
no_license
takohack/cs106B-2020summer
2c14ff57c6c23227073363e8099f372e19b5b405
d5a22c27d327f00b140d1f4063df84c460fb8817
refs/heads/master
2022-12-22T08:19:38.417893
2020-09-23T16:50:09
2020-09-23T16:50:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,639
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'gchooser.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.9) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Lecture12/lib/StanfordCPPLib/graphics/gchooser.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'gchooser.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.9. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata__Internal_QComboBox_t { QByteArrayData data[3]; char stringdata0[34]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata__Internal_QComboBox_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata__Internal_QComboBox_t qt_meta_stringdata__Internal_QComboBox = { { QT_MOC_LITERAL(0, 0, 19), // "_Internal_QComboBox" QT_MOC_LITERAL(1, 20, 12), // "handleChange" QT_MOC_LITERAL(2, 33, 0) // "" }, "_Internal_QComboBox\0handleChange\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data__Internal_QComboBox[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 19, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, 0 // eod }; void _Internal_QComboBox::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { _Internal_QComboBox *_t = static_cast<_Internal_QComboBox *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->handleChange(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject _Internal_QComboBox::staticMetaObject = { { &QComboBox::staticMetaObject, qt_meta_stringdata__Internal_QComboBox.data, qt_meta_data__Internal_QComboBox, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *_Internal_QComboBox::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *_Internal_QComboBox::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata__Internal_QComboBox.stringdata0)) return static_cast<void*>(this); if (!strcmp(_clname, "_Internal_QWidget")) return static_cast< _Internal_QWidget*>(this); return QComboBox::qt_metacast(_clname); } int _Internal_QComboBox::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QComboBox::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "unclejyj@gmail.com" ]
unclejyj@gmail.com
47468b58e14cfe1c796f62c41cc4e41f69ebce35
6e80245fe676033b8b0fb7e07963ad1b10ce4541
/chromium/extensions/components/native_app_window/native_app_window_views.h
b63535cbb5a88c8a9b98bc7da985a6518614ace5
[ "BSD-3-Clause" ]
permissive
Sporif/darker-vivaldi
81cfefe1209af0d07c45ea47a67a21f1639e8c18
b74ea1f30f0a3f1eb867a968027b9d11c150e4d6
refs/heads/master
2021-01-19T00:23:24.530407
2017-04-03T21:11:38
2017-04-03T21:11:38
87,162,323
2
0
null
null
null
null
UTF-8
C++
false
false
7,591
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. #ifndef EXTENSIONS_COMPONENTS_NATIVE_APP_WINDOW_NATIVE_APP_WINDOW_VIEWS_H_ #define EXTENSIONS_COMPONENTS_NATIVE_APP_WINDOW_NATIVE_APP_WINDOW_VIEWS_H_ #include <memory> #include "base/macros.h" #include "base/observer_list.h" #include "content/public/browser/web_contents_observer.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/native_app_window.h" #include "extensions/browser/app_window/size_constraints.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/widget_observer.h" class SkRegion; namespace content { class BrowserContext; class RenderViewHost; class WebContents; } namespace extensions { class Extension; } namespace ui { class MenuModel; } namespace views { class MenuRunner; class WebView; } namespace native_app_window { // A NativeAppWindow backed by a views::Widget. This class may be used alone // as a stub or subclassed (for example, ChromeNativeAppWindowViews). class NativeAppWindowViews : public extensions::NativeAppWindow, public content::WebContentsObserver, public views::WidgetDelegateView, public views::WidgetObserver { public: NativeAppWindowViews(); ~NativeAppWindowViews() override; void Init(extensions::AppWindow* app_window, const extensions::AppWindow::CreateParams& create_params); // Signal that CanHaveTransparentBackground has changed. void OnCanHaveAlphaEnabledChanged(); extensions::AppWindow* app_window() { return app_window_; } const extensions::AppWindow* app_window() const { return app_window_; } views::WebView* web_view() { return web_view_; } const views::WebView* web_view() const { return web_view_; } views::Widget* widget() { return widget_; } const views::Widget* widget() const { return widget_; } void set_window_for_testing(views::Widget* window) { widget_ = window; } void set_web_view_for_testing(views::WebView* view) { web_view_ = view; } protected: // Initializes |widget_| for |app_window|. virtual void InitializeWindow( extensions::AppWindow* app_window, const extensions::AppWindow::CreateParams& create_params); // ui::BaseWindow implementation. bool IsActive() const override; bool IsMaximized() const override; bool IsMinimized() const override; bool IsFullscreen() const override; gfx::NativeWindow GetNativeWindow() const override; gfx::Rect GetRestoredBounds() const override; ui::WindowShowState GetRestoredState() const override; gfx::Rect GetBounds() const override; void Show() override; void ShowInactive() override; void Hide() override; void Close() override; void Activate() override; void Deactivate() override; void Maximize() override; void Minimize() override; void Restore() override; void SetBounds(const gfx::Rect& bounds) override; void FlashFrame(bool flash) override; bool IsAlwaysOnTop() const override; void SetAlwaysOnTop(bool always_on_top) override; // WidgetDelegate implementation. void OnWidgetMove() override; views::View* GetInitiallyFocusedView() override; bool CanResize() const override; bool CanMaximize() const override; bool CanMinimize() const override; base::string16 GetWindowTitle() const override; bool ShouldShowWindowTitle() const override; bool ShouldShowWindowIcon() const override; void SaveWindowPlacement(const gfx::Rect& bounds, ui::WindowShowState show_state) override; void DeleteDelegate() override; views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; bool ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) override; bool ExecuteWindowsCommand(int command_id) override; void HandleKeyboardCode(ui::KeyboardCode code) override; // WidgetObserver implementation. void OnWidgetDestroying(views::Widget* widget) override; void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override; void OnWidgetActivationChanged(views::Widget* widget, bool active) override; // WebContentsObserver implementation. void RenderViewCreated(content::RenderViewHost* render_view_host) override; void RenderViewHostChanged(content::RenderViewHost* old_host, content::RenderViewHost* new_host) override; // views::View implementation. void Layout() override; void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; gfx::Size GetMinimumSize() const override; gfx::Size GetMaximumSize() const override; void OnFocus() override; // NativeAppWindow implementation. void SetFullscreen(int fullscreen_types) override; bool IsFullscreenOrPending() const override; void UpdateWindowIcon() override; void UpdateWindowTitle() override; void UpdateDraggableRegions( const std::vector<extensions::DraggableRegion>& regions) override; SkRegion* GetDraggableRegion() override; void UpdateShape(std::unique_ptr<SkRegion> region) override; void HandleKeyboardEvent( const content::NativeWebKeyboardEvent& event) override; bool IsFrameless() const override; bool HasFrameColor() const override; SkColor ActiveFrameColor() const override; SkColor InactiveFrameColor() const override; gfx::Insets GetFrameInsets() const override; void HideWithApp() override; void ShowWithApp() override; gfx::Size GetContentMinimumSize() const override; gfx::Size GetContentMaximumSize() const override; void SetContentSizeConstraints(const gfx::Size& min_size, const gfx::Size& max_size) override; bool CanHaveAlphaEnabled() const override; void SetVisibleOnAllWorkspaces(bool always_visible) override; // web_modal::WebContentsModalDialogHost implementation. gfx::NativeView GetHostView() const override; gfx::Point GetDialogPosition(const gfx::Size& size) override; gfx::Size GetMaximumDialogSize() override; void AddObserver(web_modal::ModalDialogHostObserver* observer) override; void RemoveObserver(web_modal::ModalDialogHostObserver* observer) override; private: // Informs modal dialogs that they need to update their positions. void OnViewWasResized(); extensions::AppWindow* app_window_; // Not owned. views::WebView* web_view_; views::Widget* widget_; std::unique_ptr<SkRegion> draggable_region_; bool frameless_; bool resizable_; extensions::SizeConstraints size_constraints_; views::UnhandledKeyboardEventHandler unhandled_keyboard_event_handler_; base::ObserverList<web_modal::ModalDialogHostObserver> observer_list_; // NOTE(pettern@vivaldi): If true, this window is hidden for the user but // "visible" for the underlying chromium code so that a thumbnail can be // generated. bool thumbnail_window_; // NOTE(jarle@vivaldi): If true, the view has been shown at least once, and // it's ok to change the widget's saved window state in the Show() method. // This is to ensure that the window's saved state is preserved on init. // Ref.: VB-10039 bool shown_; DISALLOW_COPY_AND_ASSIGN(NativeAppWindowViews); }; } // namespace native_app_window #endif // EXTENSIONS_COMPONENTS_NATIVE_APP_WINDOW_NATIVE_APP_WINDOW_VIEWS_H_
[ "ricardo.amendoeira@ist.utl.pt" ]
ricardo.amendoeira@ist.utl.pt
46f2d7801621be52595f4a65e7bb91506a212d94
346870024d3943cdaba16472b8502f0955a184f2
/AST/AST.cpp
c6a2cc40a44e13990961cc8dec5999e6fe81e2d2
[]
no_license
cybex-dev/Robot-Compiler
3a2add8de9c248877d0b00b1f72a25ba280fe95f
e0ed32e0fc913f702c18db18f4be5b4e66a30177
refs/heads/master
2020-05-30T03:49:01.714515
2019-06-23T19:05:54
2019-06-23T19:05:54
189,522,548
2
1
null
null
null
null
UTF-8
C++
false
false
107
cpp
// // Created by cybex on 2019/05/03. // #include "AST.h" std::string AST::describe() { return ""; }
[ "k4gcybex@gmail.com" ]
k4gcybex@gmail.com
2244b2634421f76178495b492ece70f314b988b9
99a4d1d6b8bdb83007faaf7bf14687719a084887
/zetasql/base/statusor.h
773a17497d45ddb336a3c65705f3b6f2eac018bb
[ "Apache-2.0" ]
permissive
MartinSahlen/zetasql
e3a2c39ee1c5c0deb19b0f3843ca858be9220653
5ad34de91ba535716ef41e72c4f6c0f5dac2ab5b
refs/heads/master
2020-06-17T11:01:47.986213
2019-09-18T09:57:36
2019-09-18T09:57:36
194,493,534
0
0
Apache-2.0
2019-06-30T08:35:33
2019-06-30T08:35:33
null
UTF-8
C++
false
false
15,925
h
// // Copyright 2018 ZetaSQL Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef THIRD_PARTY_ZETASQL_ZETASQL_BASE_STATUSOR_H_ #define THIRD_PARTY_ZETASQL_ZETASQL_BASE_STATUSOR_H_ // StatusOr<T> is the union of a Status object and a T // object. StatusOr models the concept of an object that is either a // usable value, or an error Status explaining why such a value is // not present. To this end, StatusOr<T> does not allow its Status // value to be OkStatus(). // // The primary use-case for StatusOr<T> is as the return value of a // function which may fail. // // Example usage of a StatusOr<T>: // // StatusOr<Foo> result = DoBigCalculationThatCouldFail(); // if (result) { // result->DoSomethingCool(); // } else { // LOG(ERROR) << result.status(); // } // // Example that is guaranteed crash if the result holds no value: // // StatusOr<Foo> result = DoBigCalculationThatCouldFail(); // const Foo& foo = result.ValueOrDie(); // foo.DoSomethingCool(); // // Example usage of a StatusOr<std::unique_ptr<T>>: // // StatusOr<std::unique_ptr<Foo>> result = FooFactory::MakeNewFoo(arg); // if (!result.ok()) { // Don't omit .ok(). // LOG(ERROR) << result.status(); // } else if (*result == nullptr) { // LOG(ERROR) << "Unexpected null pointer"; // } else { // (*result)->DoSomethingCool(); // } // // Example factory implementation returning StatusOr<T>: // // StatusOr<Foo> FooFactory::MakeFoo(int arg) { // if (arg <= 0) { // return // ::zetasql_base::Status(::zetasql_base::StatusCode:kInvalidArgument, // "Arg must be positive"); // } // return Foo(arg); // } // #include <new> #include <string> #include <type_traits> #include <utility> #include "absl/base/attributes.h" #include "absl/base/macros.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" #include "zetasql/base/logging.h" #include "zetasql/base/status.h" #include "zetasql/base/statusor_internals.h" namespace zetasql_base { // Returned StatusOr objects may not be ignored. template <typename T> class ABSL_MUST_USE_RESULT StatusOr; template <typename T> class StatusOr : private statusor_internal::StatusOrData<T>, private statusor_internal::TraitsBase< std::is_copy_constructible<T>::value, std::is_move_constructible<T>::value> { template <typename U> friend class StatusOr; typedef statusor_internal::StatusOrData<T> Base; public: using element_type = T; // Constructs a new StatusOr with Status::UNKNOWN status. This is marked // 'explicit' to try to catch cases like 'return {};', where people think // StatusOr<std::vector<int>> will be initialized with an empty vector, // instead of a Status::UNKNOWN status. explicit StatusOr(); // StatusOr<T> will be copy constructible/assignable if T is copy // constructible. StatusOr(const StatusOr&) = default; StatusOr& operator=(const StatusOr&) = default; // StatusOr<T> will be move constructible/assignable if T is move // constructible. StatusOr(StatusOr&&) = default; StatusOr& operator=(StatusOr&&) = default; // Converting constructors from StatusOr<U>, when T is constructible from U. // To avoid ambiguity, they are disabled if T is also constructible from // StatusOr<U>. Explicit iff the corresponding construction of T from U is // explicit. template < typename U, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<T, U>>, std::is_constructible<T, const U&>, std::is_convertible<const U&, T>, absl::negation<statusor_internal::IsStatusOrConversionAmbiguous< T, U>>>::value, int> = 0> StatusOr(const StatusOr<U>& other) // NOLINT : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {} template < typename U, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<T, U>>, std::is_constructible<T, const U&>, absl::negation<std::is_convertible<const U&, T>>, absl::negation<statusor_internal::IsStatusOrConversionAmbiguous< T, U>>>::value, int> = 0> explicit StatusOr(const StatusOr<U>& other) : Base(static_cast<const typename StatusOr<U>::Base&>(other)) {} template < typename U, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>, std::is_convertible<U&&, T>, absl::negation<statusor_internal::IsStatusOrConversionAmbiguous< T, U>>>::value, int> = 0> StatusOr(StatusOr<U>&& other) // NOLINT : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {} template < typename U, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>, absl::negation<std::is_convertible<U&&, T>>, absl::negation<statusor_internal::IsStatusOrConversionAmbiguous< T, U>>>::value, int> = 0> explicit StatusOr(StatusOr<U>&& other) : Base(static_cast<typename StatusOr<U>::Base&&>(other)) {} // Conversion copy/move assignment operator, T must be constructible and // assignable from U. Only enable if T cannot be directly assigned from // StatusOr<U>. template < typename U, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<T, U>>, std::is_constructible<T, const U&>, std::is_assignable<T, const U&>, absl::negation< statusor_internal::IsStatusOrConversionAssigmentAmbiguous< T, U>>>::value, int> = 0> StatusOr& operator=(const StatusOr<U>& other) { this->Assign(other); return *this; } template < typename U, absl::enable_if_t< absl::conjunction< absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>, std::is_assignable<T, U&&>, absl::negation< statusor_internal::IsStatusOrConversionAssigmentAmbiguous< T, U>>>::value, int> = 0> StatusOr& operator=(StatusOr<U>&& other) { this->Assign(std::move(other)); return *this; } // Constructs a new StatusOr with the given value. After calling this // constructor, this->ok() will be true and the contained value may be // retrieved with ValueOrDie(), operator*(), or operator->(). // // NOTE: Not explicit - we want to use StatusOr<T> as a return type // so it is convenient and sensible to be able to do 'return T()' // when the return type is StatusOr<T>. // // REQUIRES: T is copy constructible. StatusOr(const T& value); // Constructs a new StatusOr with the given non-ok status. After calling this // constructor, this->ok() will be false and calls to ValueOrDie() will // CHECK-fail. // // NOTE: Not explicit - we want to use StatusOr<T> as a return // value, so it is convenient and sensible to be able to do 'return // Status()' when the return type is StatusOr<T>. // // REQUIRES: !status.ok(). This requirement is DCHECKed. // In optimized builds, passing OkStatus() here will have the effect // of passing INTERNAL as a fallback. StatusOr(const Status& status); StatusOr& operator=(const Status& status); // Similar to the `const T&` overload. // // REQUIRES: T is move constructible. StatusOr(T&& value); // RValue versions of the operations declared above. StatusOr(Status&& status); StatusOr& operator=(Status&& status); // Constructs the inner value T in-place using the provided args, using the // T(args...) constructor. template <typename... Args> explicit StatusOr(absl::in_place_t, Args&&... args); template <typename U, typename... Args> explicit StatusOr(absl::in_place_t, std::initializer_list<U> ilist, Args&&... args); // Constructs the inner value T in-place using the provided args, using the // T(U) (direct-initialization) constructor. Only valid if T can be // constructed from a U. Can accept move or copy constructors. Explicit it // U is not convertible to T. To avoid ambiguity, this is disabled if U is // a StatusOr<J>, where J is convertible to T. template < typename U = T, absl::enable_if_t< absl::conjunction< statusor_internal::IsStatusOrDirectInitializationValid<T, U&&>, std::is_constructible<T, U&&>, std::is_convertible<U&&, T>>::value, int> = 0> StatusOr(U&& u) // NOLINT : StatusOr(absl::in_place, std::forward<U>(u)) {} template < typename U = T, absl::enable_if_t< absl::conjunction< statusor_internal::IsStatusOrDirectInitializationValid<T, U&&>, std::is_constructible<T, U&&>, absl::negation<std::is_convertible<U&&, T>>>::value, int> = 0> explicit StatusOr(U&& u) // NOLINT : StatusOr(absl::in_place, std::forward<U>(u)) {} // Returns this->ok() explicit operator bool() const { return ok(); } // Returns this->status().ok() ABSL_MUST_USE_RESULT bool ok() const { return this->status_.ok(); } // Returns a reference to our status. If this contains a T, then // returns OkStatus(). const Status& status() const&; Status status() &&; // Returns a reference to our current value, or CHECK-fails if !this->ok(). If // you have already checked the status using this->ok() or operator bool(), // then you probably want to use operator*() or operator->() to access the // current value instead of ValueOrDie(). // // Note: for value types that are cheap to copy, prefer simple code: // // T value = statusor.ValueOrDie(); // // Otherwise, if the value type is expensive to copy, but can be left // in the StatusOr, simply assign to a reference: // // T& value = statusor.ValueOrDie(); // or `const T&` // // Otherwise, if the value type supports an efficient move, it can be // used as follows: // // T value = std::move(statusor).ValueOrDie(); // // The std::move on statusor instead of on the whole expression enables // warnings about possible uses of the statusor object after the move. const T& ValueOrDie() const&; T& ValueOrDie() &; const T&& ValueOrDie() const&&; T&& ValueOrDie() &&; // Returns a reference to the current value. // // REQUIRES: this->ok() == true, otherwise the behavior is undefined. // // Use this->ok() or `operator bool()` to verify that there is a current // value. Alternatively, see ValueOrDie() for a similar API that guarantees // CHECK-failing if there is no current value. // const T& operator*() const&; T& operator*() &; const T&& operator*() const&&; T&& operator*() &&; // Returns a pointer to the current value. // // REQUIRES: this->ok() == true, otherwise the behavior is undefined. // // Use this->ok() or `operator bool()` to verify that there is a current // value. const T* operator->() const; T* operator->(); // Returns a copy of the current value if this->ok() == true. Otherwise // returns a default value. template <typename U> T value_or(U&& default_value) const&; template <typename U> T value_or(U&& default_value) &&; // Ignores any errors. This method does nothing except potentially suppress // complaints from any tools that are checking that errors are not dropped on // the floor. void IgnoreError() const; private: using statusor_internal::StatusOrData<T>::Assign; template <typename U> void Assign(const StatusOr<U>& other); template <typename U> void Assign(StatusOr<U>&& other); }; //////////////////////////////////////////////////////////////////////////////// // Implementation details for StatusOr<T> template <typename T> StatusOr<T>::StatusOr() : Base(Status(zetasql_base::StatusCode::kUnknown, "")) {} template <typename T> StatusOr<T>::StatusOr(const T& value) : Base(value) {} template <typename T> StatusOr<T>::StatusOr(const Status& status) : Base(status) {} template <typename T> StatusOr<T>& StatusOr<T>::operator=(const Status& status) { this->Assign(status); return *this; } template <typename T> StatusOr<T>::StatusOr(T&& value) : Base(std::move(value)) {} template <typename T> StatusOr<T>::StatusOr(Status&& status) : Base(std::move(status)) {} template <typename T> StatusOr<T>& StatusOr<T>::operator=(Status&& status) { this->Assign(std::move(status)); return *this; } template <typename T> template <typename U> inline void StatusOr<T>::Assign(const StatusOr<U>& other) { if (other.ok()) { this->Assign(other.ValueOrDie()); } else { this->Assign(other.status()); } } template <typename T> template <typename U> inline void StatusOr<T>::Assign(StatusOr<U>&& other) { if (other.ok()) { this->Assign(std::move(other).ValueOrDie()); } else { this->Assign(std::move(other).status()); } } template <typename T> template <typename... Args> StatusOr<T>::StatusOr(absl::in_place_t, Args&&... args) : Base(absl::in_place, std::forward<Args>(args)...) {} template <typename T> template <typename U, typename... Args> StatusOr<T>::StatusOr(absl::in_place_t, std::initializer_list<U> ilist, Args&&... args) : Base(absl::in_place, ilist, std::forward<Args>(args)...) {} template <typename T> const Status& StatusOr<T>::status() const & { return this->status_; } template <typename T> Status StatusOr<T>::status() && { return ok() ? OkStatus() : std::move(this->status_); } template <typename T> const T& StatusOr<T>::ValueOrDie() const& { this->EnsureOk(); return this->data_; } template <typename T> T& StatusOr<T>::ValueOrDie() & { this->EnsureOk(); return this->data_; } template <typename T> const T&& StatusOr<T>::ValueOrDie() const&& { this->EnsureOk(); return std::move(this->data_); } template <typename T> T&& StatusOr<T>::ValueOrDie() && { this->EnsureOk(); return std::move(this->data_); } template <typename T> const T& StatusOr<T>::operator*() const& { this->EnsureOk(); return this->data_; } template <typename T> T& StatusOr<T>::operator*() & { this->EnsureOk(); return this->data_; } template <typename T> const T&& StatusOr<T>::operator*() const&& { this->EnsureOk(); return std::move(this->data_); } template <typename T> T&& StatusOr<T>::operator*() && { this->EnsureOk(); return std::move(this->data_); } template <typename T> const T* StatusOr<T>::operator->() const { this->EnsureOk(); return &this->data_; } template <typename T> T* StatusOr<T>::operator->() { this->EnsureOk(); return &this->data_; } template <typename T> template <typename U> T StatusOr<T>::value_or(U&& default_value) const& { if (ok()) { return this->data_; } return std::forward<U>(default_value); } template <typename T> template <typename U> T StatusOr<T>::value_or(U&& default_value) && { if (ok()) { return std::move(this->data_); } return std::forward<U>(default_value); } template <typename T> void StatusOr<T>::IgnoreError() const { // no-op } } // namespace zetasql_base #endif // THIRD_PARTY_ZETASQL_ZETASQL_BASE_STATUSOR_H_
[ "matthewbr@google.com" ]
matthewbr@google.com
471a69e83540b16248160b509fff250561bb3cf6
bef56ea19df6f3e540c101b8517a2114675b804a
/APIGame_base/PlayerScript.cpp
cb65205b6e2ee8fbe8907d201a286e447973b285
[]
no_license
kwt1326/2DProject
2b0b829dd7331ca4ad3aa87e5c529fe157e23fb3
940f0721ac5e4e216ef9b763ac888260aad34fb0
refs/heads/master
2022-01-27T23:41:33.703150
2022-01-17T00:31:28
2022-01-17T00:31:28
149,836,434
1
0
null
null
null
null
UHC
C++
false
false
8,680
cpp
#include "PlayerScript.h" #include "Transform.h" #include "input.h" #include "Animation.h" #include "AnimationClip.h" #include "image.h" #include "Renderer.h" #include "Ray2D.h" #include "Component.h" #include "LOG_MGR.h" #include "Gamemanager.h" #include "ObjectManager.h" #include "ColliderManager.h" #include "Camera2D.h" #include "FSMMarcine.h" // state #include "PlayerStartState.h" #include "PlayerMoveState.h" #include "PlayerJumpState.h" #include "PlayerDashState.h" #include "PlayerShotState.h" #include "PlayerIdleState.h" #include "PlayerLandWallState.h" #include "PlayerGAMEOVERState.h" #define PLAYER_H_HALFSIZE 20 #define PLAYER_V_HALFSIZE 50 PlayerScript::PlayerScript() { m_pPlayer = PLAYER_INSTANCE; m_ChangeDirection = true; m_isjump = false; m_bStartCharge = false; m_maxspeed = PLAYER_INSTANCE->GetMaxSpeed(); m_playerstate = NULL; m_Cooltime = 0.f; std::fill_n(m_wparam, 255, 0); } PlayerScript::~PlayerScript() { } bool PlayerScript::IsScrolling(bool bX) { Rect screen = GAME_MGR->Getrect(); double recthalfsize_X = screen.Right / 2; double recthalfsize_Y = screen.Bottom / 2; if (bX) { return (m_pPlayer->GetWorldPosition().x > recthalfsize_X && m_pPlayer->GetWorldPosition().x < m_pRelationCamera->GetMaxMovablePosition().x) ? true : false; } else { return (m_pPlayer->GetWorldPosition().y > recthalfsize_Y && m_pPlayer->GetWorldPosition().y < m_pRelationCamera->GetMaxMovablePosition().y) ? true : false; } } void PlayerScript::SetComparePosition(Vector2 vPos, Vector2 vWorldPos) { Rect screen = GAME_MGR->Getrect(); double recthalfsize_X = screen.Right / 2; double recthalfsize_Y = screen.Bottom / 2; if (IsScrolling(true)) { vPos.x = recthalfsize_X; // 수평만 고정, 수직은 버벅임 발생으로 다르게 처리 } m_pPlayer->SetPosition(vPos); m_pPlayer->SetWorldPosition(vWorldPos); } void PlayerScript::Update(float dt) { ProcessPlayer(dt); m_pMachine->_Update(dt); // FSM Pattern Realtime Update } void PlayerScript::Init() { Vector2& pos = m_pPlayer->GetPosition(); m_pRigidbody = m_pPlayer->GetComponent<Rigidbody>(); GameObject* pgameobject = OBJECT_MGR->GetInstance()->FindObject("Background"); m_pRelationCamera = pgameobject->GetComponent<Camera2D>(); p_Anim = GetComponent<Animation>(); m_pPlayer->SetPlayerSpeed(p_PlayerSpeed = 400.f); m_pPlayer->SetDashSpeed(750.f); m_pPlayer->SetHealth(10); m_dt_time = 0; DrawHealthBar(); m_Transform->SetAllofTransform(NULL, Vector2(0.5f, 0.5f), Vector2(2.0f, 2.0f), Vector2(1.f, 1.f), NULL, NULL, pos, pos); m_pMachine = m_pPlayer->GetComponent<FSMMarcine>(); m_pMachine->InsertState(STARTSTATE_ID, new PlayerStartState()); m_pMachine->InsertState(IDLESTATE_ID, new PlayerIdleState()); m_pMachine->InsertState(JUMPSTATE_ID, new PlayerJumpState()); m_pMachine->InsertState(MOVESTATE_ID, new PlayerMoveState()); //m_pMachine->InsertState(SHOTSTATE_ID, new PlayerShotState()); // shot 은 상태처리 하면 망가진다. m_pMachine->InsertState(DASHSTATE_ID, new PlayerDashState()); m_pMachine->InsertState(LANDWALLSTATE_ID, new PlayerLandWallState()); m_pMachine->InsertState(GAMEOVERSTATE_ID, new PlayerGAMEOVERState()); m_pMachine->GetState(GAMEOVERSTATE_ID)->SetOwner(PLAYER_INSTANCE); m_pMachine->ChangeState(STARTSTATE_ID); } void PlayerScript::Release() { } void PlayerScript::ProcessPlayer(float dt) { if (input::GetKey(VK_LEFT)) m_ChangeDirection = false; else if (input::GetKey(VK_RIGHT)) m_ChangeDirection = true; m_pPlayer->SetDirection(m_ChangeDirection); m_pPlayer->GetShotpos()->ShotPosChangeofDir(m_ChangeDirection); ChangePlayerAnimState(m_pMachine->GetCurAnimState()); UpdateShot(); if (m_pRigidbody->OnRectColliderEnter_PLAYER(m_pPlayer)) { GameStart(m_pPlayer); } else if (m_pRigidbody->GetGravity() == Vector2::Zero) { m_pRigidbody->SetGravity(Vector2(0, 300.f)); } } void PlayerScript::ChangeShotAnimByState(int enumChargeState) { if ((m_pMachine->GetCurAnimState().compare("STATE_COMJUMP") == 0) && (m_pPlayer->GetJump() == true)) m_pMachine->SetAnimState("STATE_SHOTJUMP"); else if ((m_pMachine->GetCurAnimState().compare("STATE_COMRUN") == 0) && (m_pPlayer->GetJump() == false)) m_pMachine->SetAnimState("STATE_SHOTRUN"); else if ((m_pMachine->GetCurAnimState().compare("STATE_COMIDLE") == 0) && (m_pPlayer->GetJump() == false)) { switch (enumChargeState) { case ROCKMAN_BUSTER_NC: m_pMachine->SetAnimState("STATE_SHOTIDLE"); break; case ROCKMAN_BUSTER_CR1: m_pMachine->SetAnimState("STATE_SHOTIDLE_CHARGESHOT1"); break; case ROCKMAN_BUSTER_CR2: m_pMachine->SetAnimState("STATE_SHOTIDLE_CHARGESHOT2"); break; default: break; } } else if ((m_pMachine->GetCurAnimState().compare("STATE_DASHING") == 0) && (m_pPlayer->GetJump() == false)) m_pMachine->SetAnimState("STATE_SHOTDASH"); } void PlayerScript::UpdateShot() { if (!m_pPlayer->GetGamestart()) return; AnimationClip* pCurClip = p_Anim->GetAnimationClip(); // Charge begin if ((input::GetKey('X') || input::GetKey('x')) && m_bStartCharge == false) // Charge start { if (0.5f < TIME_MGR->StopStopWatch(false)) { TIME_MGR->StopStopWatch(true); m_bStartCharge = true; TIME_MGR->BeginStopWatch(); } } else if ((input::GetKey('X') || input::GetKey('x')) == false && m_bStartCharge == true) // Shot { m_bStartCharge = false; int nChargeMode = ROCKMAN_BUSTER_NC; double chargertime = TIME_MGR->StopStopWatch(true); if (chargertime < 0.5f) { Attack* bullet = new Attack(m_pPlayer, PROJECTILE, ROCKMAN_BUSTER_NC, PLAYER_INSTANCE->GetShotLoc(), 1); OBJECT_MGR->AddObject(bullet); } else if (chargertime > 0.5f && chargertime < 1.5f) { Attack* bullet = new Attack(m_pPlayer, PROJECTILE, ROCKMAN_BUSTER_CR1, PLAYER_INSTANCE->GetShotLoc(), 2); OBJECT_MGR->AddObject(bullet); nChargeMode = ROCKMAN_BUSTER_CR1; } else if (chargertime > 1.5f) { Attack* bullet = new Attack(m_pPlayer, PROJECTILE, ROCKMAN_BUSTER_CR2, PLAYER_INSTANCE->GetShotLoc(), 5); OBJECT_MGR->AddObject(bullet); nChargeMode = ROCKMAN_BUSTER_CR2; } EFFECT_MGR->StopEffect("ROCKMAN_CHARGE_1"); EFFECT_MGR->StopEffect("ROCKMAN_CHARGE_2"); ChangeShotAnimByState(nChargeMode); // Shot Delay 측정 시작 TIME_MGR->BeginStopWatch(); return; } // During to Charge if (m_bStartCharge) { if (TIME_MGR->StopStopWatch(false) > 0.5f) { if (!EFFECT_MGR->IsAlreadyAppliedEffect("ROCKMAN_CHARGE_1")) EFFECT_MGR->ActivateEffect("ROCKMAN_CHARGE_1", m_pPlayer->GetTransform()->GetPosition()); else EFFECT_MGR->TranslatePosEffect("ROCKMAN_CHARGE_1", m_pPlayer->GetPosition()); } if (TIME_MGR->StopStopWatch(false) > 1.5f) { if (!EFFECT_MGR->IsAlreadyAppliedEffect("ROCKMAN_CHARGE_2")) EFFECT_MGR->ActivateEffect("ROCKMAN_CHARGE_2", m_pPlayer->GetTransform()->GetPosition()); else EFFECT_MGR->TranslatePosEffect("ROCKMAN_CHARGE_2", m_pPlayer->GetPosition()); } } if ((pCurClip->GetName().find("SHOT") != std::string::npos) && (pCurClip->IsPlay() == false)) { if (m_pMachine->GetCurStateID() == IDLESTATE_ID) m_pMachine->SetAnimState("STATE_COMIDLE"); else m_pMachine->ChangeState(IDLESTATE_ID); } } void PlayerScript::Move(float dt) { PlayerObject* player = PLAYER_INSTANCE; PlayerScript* script = player->GetComponent<PlayerScript>(); float moveenergy = player->GetPlayerSpeed() * dt; float yAxis = player->GetWorldPosition().y; if (input::GetKey(VK_LEFT) && player->GetBlockState() != LEFT_BLOCK) { script->SetComparePosition(Vector2(player->GetPosition().x - moveenergy, player->GetPosition().y), Vector2(player->GetWorldPosition().x - moveenergy, yAxis)); } else if (input::GetKey(VK_RIGHT) && player->GetBlockState() != RIGHT_BLOCK) { script->SetComparePosition(Vector2(player->GetPosition().x + moveenergy, player->GetPosition().y), Vector2(player->GetWorldPosition().x + moveenergy, yAxis)); } } void PlayerScript::DrawHealthBar() { Rectangle(COLLIDER_MGR->GetHdc(), 50, 350 - m_pPlayer->GetHealth() * 10, 70, 350); } void PlayerScript::ReplaceHealth(int nValue) { m_pPlayer->SetHealth(m_pPlayer->GetHealth() + nValue); DrawHealthBar(); if (m_pPlayer->GetHealth() <= 0) { m_pMachine->ChangeState(GAMEOVERSTATE_ID); } } void PlayerScript::ChangePlayerAnimState(std::string state) { if (!m_ChangeDirection) state = "R/" + state; AnimationClip* compare_clip = m_pPlayer->GetClip(state); if (compare_clip) { if (p_Anim->GetAnimationClip() != compare_clip) p_Anim->Play(compare_clip); } } bool PlayerScript::GameStart(PlayerObject* player) { if (m_pMachine->GetCurAnimState().compare("STATE_FALLDOWN") == 0) m_pMachine->Update(0); return true; }
[ "u1326@hotmail.com" ]
u1326@hotmail.com
6333cdfc5f0bff401866101aa84e7ceac0ddf70f
aa593434b039f15f3927aff624862a802152eedc
/Code/Sources/XPLProcessors/XPLCompilerTool.cpp
f824aed97e043631de2bee818c28c3e2d013e02b
[ "MIT" ]
permissive
vmlemon/Software
5915e25e7ec1ee4983532d92997256c89c4370b7
a237bf2a6698bf7bc6c8282227fc22b627e512cc
refs/heads/master
2023-03-17T20:57:40.124235
2018-07-21T19:25:14
2018-07-21T19:25:14
529,062,513
1
0
null
2022-08-26T00:36:38
2022-08-26T00:36:38
null
UTF-8
C++
false
false
915
cpp
/* XPL Compiler Tool.c */ /* Driver to allow running XPL as an MPW tool */ #include "XPLCompiler.h" extern int compiler_main (int argc, char * const argv[]); short locate_include_file (void*, const char*, char **, void **, FSSpec *) {return (0);} void release_include_file(void*, void *) {} void report_error_string (void*, long, long, void*) {} int main(int argc, char *argv[]) { // Debug if (0) { argc = 9; argv[0] = (char *)"/usr/local/bin/XPLCompiler"; argv[1] = (char *)"-md"; argv[2] = (char *)"/Volumes/CJ Data/Dropbox/Projects/SDC/Synclavier Development 5.2/Projects/AbleBrowser/../../Able"; argv[3] = (char *)"-od"; argv[4] = (char *)"/Volumes/CJ Cache/XPL Build Products/"; argv[5] = (char *)"-q"; argv[6] = (char *)":oputil:OPLIST"; argv[7] = (char *)"-of"; argv[8] = (char *)":W0:*SYSTEM:oplist"; } return (compiler_main(argc, argv)); }
[ "cjones@synclavier.com" ]
cjones@synclavier.com
e3718a0b824a6259b3c78235714d661da3bc34d9
3523da0c44c11d931319a82e639cfa5f77c30031
/source/d3d12/d3d12_command_list.hpp
69b77eae3c7a14db4c5f856a4c12e7db0899e63a
[ "BSD-3-Clause", "MIT" ]
permissive
samkatakouzinos/reshade
be6d2f958b1306a96937b25f312cf235c145a065
b47fe90544a4c5d23cdddadaf9d1d9da07c54aa0
refs/heads/main
2023-04-07T04:13:29.402348
2023-03-29T19:29:36
2023-03-29T19:29:36
131,559,764
0
0
BSD-3-Clause
2018-05-25T01:18:25
2018-04-30T05:38:08
C++
UTF-8
C++
false
false
12,581
hpp
/* * Copyright (C) 2014 Patrick Mours * SPDX-License-Identifier: BSD-3-Clause OR MIT */ #pragma once #include "d3d12_impl_command_list.hpp" struct D3D12Device; struct DECLSPEC_UUID("479B29E3-9A2C-11D0-B696-00A0C903487A") D3D12GraphicsCommandList final : ID3D12GraphicsCommandList8, public reshade::d3d12::command_list_impl { D3D12GraphicsCommandList(D3D12Device *device, ID3D12GraphicsCommandList *original); #pragma region IUnknown HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObj) override; ULONG STDMETHODCALLTYPE AddRef() override; ULONG STDMETHODCALLTYPE Release() override; #pragma endregion #pragma region ID3D12Object HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData) override; HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID guid, UINT DataSize, const void *pData) override; HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID guid, const IUnknown *pData) override; HRESULT STDMETHODCALLTYPE SetName(LPCWSTR Name) override; #pragma endregion #pragma region ID3D12DeviceChild HRESULT STDMETHODCALLTYPE GetDevice(REFIID riid, void **ppvDevice) override; #pragma endregion #pragma region ID3D12CommandList D3D12_COMMAND_LIST_TYPE STDMETHODCALLTYPE GetType() override; #pragma endregion #pragma region ID3D12GraphicsCommandList HRESULT STDMETHODCALLTYPE Close() override; HRESULT STDMETHODCALLTYPE Reset(ID3D12CommandAllocator *pAllocator, ID3D12PipelineState *pInitialState) override; void STDMETHODCALLTYPE ClearState(ID3D12PipelineState *pPipelineState) override; void STDMETHODCALLTYPE DrawInstanced(UINT VertexCountPerInstance, UINT InstanceCount, UINT StartVertexLocation, UINT StartInstanceLocation) override; void STDMETHODCALLTYPE DrawIndexedInstanced(UINT IndexCountPerInstance, UINT InstanceCount, UINT StartIndexLocation, INT BaseVertexLocation, UINT StartInstanceLocation) override; void STDMETHODCALLTYPE Dispatch(UINT ThreadGroupCountX, UINT ThreadGroupCountY, UINT ThreadGroupCountZ) override; void STDMETHODCALLTYPE CopyBufferRegion(ID3D12Resource *pDstBuffer, UINT64 DstOffset, ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT64 NumBytes) override; void STDMETHODCALLTYPE CopyTextureRegion(const D3D12_TEXTURE_COPY_LOCATION *pDst, UINT DstX, UINT DstY, UINT DstZ, const D3D12_TEXTURE_COPY_LOCATION *pSrc, const D3D12_BOX *pSrcBox) override; void STDMETHODCALLTYPE CopyResource(ID3D12Resource *pDstResource, ID3D12Resource *pSrcResource) override; void STDMETHODCALLTYPE CopyTiles(ID3D12Resource *pTiledResource, const D3D12_TILED_RESOURCE_COORDINATE *pTileRegionStartCoordinate, const D3D12_TILE_REGION_SIZE *pTileRegionSize, ID3D12Resource *pBuffer, UINT64 BufferStartOffsetInBytes, D3D12_TILE_COPY_FLAGS Flags) override; void STDMETHODCALLTYPE ResolveSubresource(ID3D12Resource *pDstResource, UINT DstSubresource, ID3D12Resource *pSrcResource, UINT SrcSubresource, DXGI_FORMAT Format) override; void STDMETHODCALLTYPE IASetPrimitiveTopology(D3D12_PRIMITIVE_TOPOLOGY PrimitiveTopology) override; void STDMETHODCALLTYPE RSSetViewports(UINT NumViewports, const D3D12_VIEWPORT *pViewports) override; void STDMETHODCALLTYPE RSSetScissorRects(UINT NumRects, const D3D12_RECT *pRects) override; void STDMETHODCALLTYPE OMSetBlendFactor(const FLOAT BlendFactor[4]) override; void STDMETHODCALLTYPE OMSetStencilRef(UINT StencilRef) override; void STDMETHODCALLTYPE SetPipelineState(ID3D12PipelineState *pPipelineState) override; void STDMETHODCALLTYPE ResourceBarrier(UINT NumBarriers, const D3D12_RESOURCE_BARRIER *pBarriers) override; void STDMETHODCALLTYPE ExecuteBundle(ID3D12GraphicsCommandList *pCommandList) override; void STDMETHODCALLTYPE SetDescriptorHeaps(UINT NumDescriptorHeaps, ID3D12DescriptorHeap *const *ppDescriptorHeaps) override; void STDMETHODCALLTYPE SetComputeRootSignature(ID3D12RootSignature *pRootSignature) override; void STDMETHODCALLTYPE SetGraphicsRootSignature(ID3D12RootSignature *pRootSignature) override; void STDMETHODCALLTYPE SetComputeRootDescriptorTable(UINT RootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) override; void STDMETHODCALLTYPE SetGraphicsRootDescriptorTable(UINT RootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE BaseDescriptor) override; void STDMETHODCALLTYPE SetComputeRoot32BitConstant(UINT RootParameterIndex, UINT SrcData, UINT DestOffsetIn32BitValues) override; void STDMETHODCALLTYPE SetGraphicsRoot32BitConstant(UINT RootParameterIndex, UINT SrcData, UINT DestOffsetIn32BitValues) override; void STDMETHODCALLTYPE SetComputeRoot32BitConstants(UINT RootParameterIndex, UINT Num32BitValuesToSet, const void *pSrcData, UINT DestOffsetIn32BitValues) override; void STDMETHODCALLTYPE SetGraphicsRoot32BitConstants(UINT RootParameterIndex, UINT Num32BitValuesToSet, const void *pSrcData, UINT DestOffsetIn32BitValues) override; void STDMETHODCALLTYPE SetComputeRootConstantBufferView(UINT RootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) override; void STDMETHODCALLTYPE SetGraphicsRootConstantBufferView(UINT RootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) override; void STDMETHODCALLTYPE SetComputeRootShaderResourceView(UINT RootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) override; void STDMETHODCALLTYPE SetGraphicsRootShaderResourceView(UINT RootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) override; void STDMETHODCALLTYPE SetComputeRootUnorderedAccessView(UINT RootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) override; void STDMETHODCALLTYPE SetGraphicsRootUnorderedAccessView(UINT RootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS BufferLocation) override; void STDMETHODCALLTYPE IASetIndexBuffer(const D3D12_INDEX_BUFFER_VIEW *pView) override; void STDMETHODCALLTYPE IASetVertexBuffers(UINT StartSlot, UINT NumViews, const D3D12_VERTEX_BUFFER_VIEW *pViews) override; void STDMETHODCALLTYPE SOSetTargets(UINT StartSlot, UINT NumViews, const D3D12_STREAM_OUTPUT_BUFFER_VIEW *pViews) override; void STDMETHODCALLTYPE OMSetRenderTargets(UINT NumRenderTargetDescriptors, const D3D12_CPU_DESCRIPTOR_HANDLE *pRenderTargetDescriptors, BOOL RTsSingleHandleToDescriptorRange, const D3D12_CPU_DESCRIPTOR_HANDLE *pDepthStencilDescriptor) override; void STDMETHODCALLTYPE ClearDepthStencilView(D3D12_CPU_DESCRIPTOR_HANDLE DepthStencilView, D3D12_CLEAR_FLAGS ClearFlags, FLOAT Depth, UINT8 Stencil, UINT NumRects, const D3D12_RECT *pRects) override; void STDMETHODCALLTYPE ClearRenderTargetView(D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetView, const FLOAT ColorRGBA[4], UINT NumRects, const D3D12_RECT *pRects) override; void STDMETHODCALLTYPE ClearUnorderedAccessViewUint(D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, ID3D12Resource *pResource, const UINT Values[4], UINT NumRects, const D3D12_RECT *pRects) override; void STDMETHODCALLTYPE ClearUnorderedAccessViewFloat(D3D12_GPU_DESCRIPTOR_HANDLE ViewGPUHandleInCurrentHeap, D3D12_CPU_DESCRIPTOR_HANDLE ViewCPUHandle, ID3D12Resource *pResource, const FLOAT Values[4], UINT NumRects, const D3D12_RECT *pRects) override; void STDMETHODCALLTYPE DiscardResource(ID3D12Resource *pResource, const D3D12_DISCARD_REGION *pRegion) override; void STDMETHODCALLTYPE BeginQuery(ID3D12QueryHeap *pQueryHeap, D3D12_QUERY_TYPE Type, UINT Index) override; void STDMETHODCALLTYPE EndQuery(ID3D12QueryHeap *pQueryHeap, D3D12_QUERY_TYPE Type, UINT Index) override; void STDMETHODCALLTYPE ResolveQueryData(ID3D12QueryHeap *pQueryHeap, D3D12_QUERY_TYPE Type, UINT StartIndex, UINT NumQueries, ID3D12Resource *pDestinationBuffer, UINT64 AlignedDestinationBufferOffset) override; void STDMETHODCALLTYPE SetPredication(ID3D12Resource *pBuffer, UINT64 AlignedBufferOffset, D3D12_PREDICATION_OP Operation) override; void STDMETHODCALLTYPE SetMarker(UINT Metadata, const void *pData, UINT Size) override; void STDMETHODCALLTYPE BeginEvent(UINT Metadata, const void *pData, UINT Size) override; void STDMETHODCALLTYPE EndEvent() override; void STDMETHODCALLTYPE ExecuteIndirect(ID3D12CommandSignature *pCommandSignature, UINT MaxCommandCount, ID3D12Resource *pArgumentBuffer, UINT64 ArgumentBufferOffset, ID3D12Resource *pCountBuffer, UINT64 CountBufferOffset) override; #pragma endregion #pragma region ID3D12GraphicsCommandList1 void STDMETHODCALLTYPE AtomicCopyBufferUINT(ID3D12Resource *pDstBuffer, UINT64 DstOffset, ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT Dependencies, ID3D12Resource *const *ppDependentResources, const D3D12_SUBRESOURCE_RANGE_UINT64 *pDependentSubresourceRanges) override; void STDMETHODCALLTYPE AtomicCopyBufferUINT64(ID3D12Resource *pDstBuffer, UINT64 DstOffset, ID3D12Resource *pSrcBuffer, UINT64 SrcOffset, UINT Dependencies, ID3D12Resource *const *ppDependentResources, const D3D12_SUBRESOURCE_RANGE_UINT64 *pDependentSubresourceRanges) override; void STDMETHODCALLTYPE OMSetDepthBounds(FLOAT Min, FLOAT Max) override; void STDMETHODCALLTYPE SetSamplePositions(UINT NumSamplesPerPixel, UINT NumPixels, D3D12_SAMPLE_POSITION *pSamplePositions) override; void STDMETHODCALLTYPE ResolveSubresourceRegion(ID3D12Resource *pDstResource, UINT DstSubresource, UINT DstX, UINT DstY, ID3D12Resource *pSrcResource, UINT SrcSubresource, D3D12_RECT *pSrcRect, DXGI_FORMAT Format, D3D12_RESOLVE_MODE ResolveMode) override; void STDMETHODCALLTYPE SetViewInstanceMask(UINT Mask) override; #pragma endregion #pragma region ID3D12GraphicsCommandList2 void STDMETHODCALLTYPE WriteBufferImmediate(UINT Count, const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER *pParams, const D3D12_WRITEBUFFERIMMEDIATE_MODE *pModes) override; #pragma endregion #pragma region ID3D12GraphicsCommandList3 void STDMETHODCALLTYPE SetProtectedResourceSession(ID3D12ProtectedResourceSession *pProtectedResourceSession) override; #pragma endregion #pragma region ID3D12GraphicsCommandList4 void STDMETHODCALLTYPE BeginRenderPass(UINT NumRenderTargets, const D3D12_RENDER_PASS_RENDER_TARGET_DESC *pRenderTargets, const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC *pDepthStencil, D3D12_RENDER_PASS_FLAGS Flags) override; void STDMETHODCALLTYPE EndRenderPass(void) override; void STDMETHODCALLTYPE InitializeMetaCommand(ID3D12MetaCommand *pMetaCommand, const void *pInitializationParametersData, SIZE_T InitializationParametersDataSizeInBytes) override; void STDMETHODCALLTYPE ExecuteMetaCommand(ID3D12MetaCommand *pMetaCommand, const void *pExecutionParametersData, SIZE_T ExecutionParametersDataSizeInBytes) override; void STDMETHODCALLTYPE BuildRaytracingAccelerationStructure(const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC *pDesc, UINT NumPostbuildInfoDescs, const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC *pPostbuildInfoDescs) override; void STDMETHODCALLTYPE EmitRaytracingAccelerationStructurePostbuildInfo(const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC *pDesc, UINT NumSourceAccelerationStructures, const D3D12_GPU_VIRTUAL_ADDRESS *pSourceAccelerationStructureData) override; void STDMETHODCALLTYPE CopyRaytracingAccelerationStructure(D3D12_GPU_VIRTUAL_ADDRESS DestAccelerationStructureData, D3D12_GPU_VIRTUAL_ADDRESS SourceAccelerationStructureData, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE Mode) override; void STDMETHODCALLTYPE SetPipelineState1(ID3D12StateObject *pStateObject) override; void STDMETHODCALLTYPE DispatchRays(const D3D12_DISPATCH_RAYS_DESC *pDesc) override; #pragma endregion #pragma region ID3D12GraphicsCommandList5 void STDMETHODCALLTYPE RSSetShadingRate(D3D12_SHADING_RATE BaseShadingRate, const D3D12_SHADING_RATE_COMBINER *pCombiners) override; void STDMETHODCALLTYPE RSSetShadingRateImage(ID3D12Resource *pShadingRateImage) override; #pragma endregion #pragma region ID3D12GraphicsCommandList6 void STDMETHODCALLTYPE DispatchMesh(UINT ThreadGroupCountX, UINT ThreadGroupCountY, UINT ThreadGroupCountZ) override; #pragma endregion #pragma region ID3D12GraphicsCommandList7 void STDMETHODCALLTYPE Barrier(UINT32 NumBarrierGroups, const D3D12_BARRIER_GROUP *pBarrierGroups) override; #pragma endregion #pragma region ID3D12GraphicsCommandList8 void STDMETHODCALLTYPE OMSetFrontAndBackStencilRef(UINT FrontStencilRef, UINT BackStencilRef) override; #pragma endregion bool check_and_upgrade_interface(REFIID riid); ULONG _ref = 1; unsigned int _interface_version = 0; D3D12Device *const _device; };
[ "crosiredev@gmail.com" ]
crosiredev@gmail.com
eba0077839bd717b95e2887e66bfc687acca4456
50fd4227fb802d65ae6620a3859dd992cb650717
/src/dpso/ocr/remote_files_lang_manager.cpp
1f5cb8c483efe180cf8298ae7d0d1cfcdaaa261d
[ "Zlib" ]
permissive
danpla/dpscreenocr
626c8004a388289589fa254b8b8916b8a3ada50a
00ef775dae03e6de74bc07cfd04a0918febc8e30
refs/heads/master
2023-08-16T07:01:34.946170
2023-08-15T19:13:28
2023-08-15T19:13:28
173,785,193
193
19
Zlib
2020-05-29T19:56:53
2019-03-04T16:55:10
C++
UTF-8
C++
false
false
10,461
cpp
#include "ocr/remote_files_lang_manager.h" #include <cassert> #include <jansson.h> #include "dpso_net/download_file.h" #include "dpso_net/error.h" #include "dpso_net/get_data.h" #include "dpso_utils/os.h" #include "dpso_utils/sha256_file.h" #include "dpso_utils/str.h" #include "ocr/lang_code_validator.h" #include "ocr/lang_manager_error.h" namespace dpso::ocr { namespace { void rethrowNetErrorAsLangManagerError(const char* message) { try { throw; } catch (net::ConnectionError&) { throw LangManagerNetworkConnectionError{message}; } catch (net::Error&) { throw LangManagerError{message}; } } struct JsonRefDecrementer { void operator()(json_t* json) const { json_decref(json); } }; using JsonUPtr = std::unique_ptr<json_t, JsonRefDecrementer>; const json_t* get(const json_t* object, const char* key) { if (const auto* obj = json_object_get(object, key)) return obj; throw LangManagerError{str::printf("No \"%s\"", key)}; } std::string getStr(const json_t* object, const char* key) { if (const auto* obj = get(object, key); const auto* val = json_string_value(obj)) return {val, json_string_length(obj)}; throw LangManagerError{ str::printf("\"%s\" is not a string", key)}; } std::int64_t getInt(const json_t* object, const char* key) { if (const auto* obj = get(object, key); json_is_integer(obj)) return json_integer_value(obj); throw LangManagerError{ str::printf("\"%s\" is not an integer", key)}; } } RemoteFilesLangManager::RemoteFilesLangManager( const char* dataDir, const char* userAgent, const char* infoFileUrl, const std::vector<std::string>& localLangCodes) : dataDir{dataDir} , userAgent{userAgent} , infoFileUrl{infoFileUrl} { for (const auto& langCode : localLangCodes) langInfos.push_back( {langCode, LangState::installed, {}, {}, {}}); } bool RemoteFilesLangManager::shouldIgnoreLang( const char* langCode) const { (void)langCode; return false; } int RemoteFilesLangManager::getNumLangs() const { return langInfos.size(); } std::string RemoteFilesLangManager::getLangCode(int langIdx) const { return langInfos[langIdx].code; } std::string RemoteFilesLangManager::getLangName(int langIdx) const { return getLangName(getLangCode(langIdx).c_str()); } LangManager::LangState RemoteFilesLangManager::getLangState( int langIdx) const { return langInfos[langIdx].state; } void RemoteFilesLangManager::fetchExternalLangs() { clearExternalLangs(); for (const auto& externalLang : getExternalLangs( infoFileUrl.c_str(), userAgent.c_str())) if (!shouldIgnoreLang(externalLang.code.c_str())) addExternalLang(externalLang); } static net::DownloadProgressHandler makeDownloadProgressHandler( const LangManager::ProgressHandler& progressHandler, bool& canceled) { return [&, lastProgress = -1]( std::int64_t curSize, std::optional<std::int64_t> totalSize) mutable { if (!progressHandler) return true; auto progress = -1; if (totalSize) { if (*totalSize == 0) progress = 100; else progress = static_cast<float>(curSize) / *totalSize * 100; if (progress == lastProgress) return true; lastProgress = progress; } canceled = !progressHandler(progress); return !canceled; }; } void RemoteFilesLangManager::installLang( int langIdx, const ProgressHandler& progressHandler) { try { os::makeDirs(dataDir.c_str()); } catch (os::Error& e) { throw LangManagerError{str::printf( "Can't create directory \"%s\": %s", dataDir.c_str(), e.what())}; } auto& langInfo = langInfos[langIdx]; assert(langInfo.sha256 != langInfo.externalSha256); assert(!langInfo.url.empty()); const auto filePath = getFilePath(langIdx); bool canceled{}; try { net::downloadFile( langInfo.url.c_str(), userAgent.c_str(), filePath.c_str(), makeDownloadProgressHandler(progressHandler, canceled)); } catch (net::Error& e) { rethrowNetErrorAsLangManagerError(str::printf( "Can't download \"%s\" to \"%s\": %s", langInfo.url.c_str(), filePath.c_str(), e.what()).c_str()); } if (canceled) return; langInfo.state = LangState::installed; langInfo.sha256 = langInfo.externalSha256; // Even though we know the digest in advance, we cannot save it // before the language file is downloaded, as this would // prematurely overwrite the existing digest file in case of a // language update. try { saveSha256File(filePath.c_str(), langInfo.sha256.c_str()); } catch (Sha256FileError&) { // Ignore errors, as the language file is already downloaded // anyway, and the previous one is overwritten in case of an // update. } } void RemoteFilesLangManager::removeLang(int langIdx) { const auto filePath = getFilePath(langIdx); try { os::removeFile(filePath.c_str()); } catch (os::Error& e) { throw LangManagerError{str::printf( "Can't remove \"%s\": %s", filePath.c_str(), e.what())}; } if (auto& langInfo = langInfos[langIdx]; !langInfo.url.empty()) { langInfo.state = LangState::notInstalled; langInfo.sha256.clear(); } else langInfos.erase(langInfos.begin() + langIdx); try { removeSha256File(filePath.c_str()); } catch (Sha256FileError&) { } } std::vector<RemoteFilesLangManager::ExternalLangInfo> RemoteFilesLangManager::parseJsonFileInfo(const char* jsonData) { json_error_t jsonError; const JsonUPtr json{json_loads(jsonData, 0, &jsonError)}; if (!json) throw LangManagerError{jsonError.text}; if (!json_is_array(json.get())) throw LangManagerError{"Root is not an array"}; std::vector<ExternalLangInfo> result; for (std::size_t i = 0; i < json_array_size(json.get()); ++i) try { const auto* fileInfo = json_array_get(json.get(), i); if (!json_is_object(fileInfo)) throw LangManagerError{"Not an object"}; const auto code = getStr(fileInfo, "code"); try { validateLangCode(code.c_str()); } catch (InvalidLangCodeError& e) { throw LangManagerError{str::printf( "Invalid code \"%s\": %s", code.c_str(), e.what())}; } result.push_back( { code, getStr(fileInfo, "sha256"), getInt(fileInfo, "size"), getStr(fileInfo, "url") }); } catch (LangManagerError& e) { throw LangManagerError{str::printf( "Array item %zu: %s", i, e.what())}; } return result; } std::vector<RemoteFilesLangManager::ExternalLangInfo> RemoteFilesLangManager::getExternalLangs( const char* infoFileUrl, const char* userAgent) { std::string jsonData; try { jsonData = net::getData(infoFileUrl, userAgent); } catch (net::Error& e) { rethrowNetErrorAsLangManagerError(str::printf( "Can't get data from \"%s\": %s", infoFileUrl, e.what()).c_str()); } try { return parseJsonFileInfo(jsonData.c_str()); } catch (LangManagerError& e) { throw LangManagerError{str::printf( "Can't parse JSON info file from \"%s\": %s", infoFileUrl, e.what())}; } } void RemoteFilesLangManager::clearExternalLangs() { for (auto iter = langInfos.begin(); iter < langInfos.end();) { if (iter->state == LangState::notInstalled) { iter = langInfos.erase(iter); continue; } iter->state = LangState::installed; iter->externalSha256.clear(); iter->url.clear(); ++iter; } } void RemoteFilesLangManager::addExternalLang( const ExternalLangInfo& externalLang) { for (auto& langInfo : langInfos) { if (langInfo.code != externalLang.code) continue; // Old external langs should be cleared before adding new // ones. assert(langInfo.state == LangState::installed); assert(langInfo.externalSha256.empty()); assert(langInfo.url.empty()); langInfo.externalSha256 = externalLang.sha256; langInfo.url = externalLang.url; const auto filePath = getFilePath(langInfo.code); // As a small optimization, check the file sizes first to // avoid calculating SHA-256 if the sizes are different. std::int64_t fileSize{}; try { fileSize = os::getFileSize(filePath.c_str()); } catch (os::Error& e) { throw LangManagerError{str::printf( "Can't get size of \"%s\": %s", filePath.c_str(), e.what())}; } if (fileSize != externalLang.size) { langInfo.state = LangState::updateAvailable; return; } if (langInfo.sha256.empty()) try { langInfo.sha256 = getSha256HexDigestWithCaching( filePath.c_str()); } catch (Sha256FileError& e) { throw LangManagerError{str::printf( "Can't get SHA-256 of \"%s\": %s", filePath.c_str(), e.what())}; } if (langInfo.sha256 != langInfo.externalSha256) langInfo.state = LangState::updateAvailable; return; } langInfos.push_back( { externalLang.code, LangState::notInstalled, {}, externalLang.sha256, externalLang.url }); } std::string RemoteFilesLangManager::getFilePath( const std::string& langCode) const { return dataDir + *os::dirSeparators + getFileName(langCode.c_str()); } std::string RemoteFilesLangManager::getFilePath(int langIdx) const { return getFilePath(langInfos[langIdx].code); } }
[ "daniel.plakhotich@gmail.com" ]
daniel.plakhotich@gmail.com
4225f51f19f43fd5c89c88467660886e9f6be168
1647bd8dddd75064d1dda276b8bcdc3dcce6c925
/DAY04/ex01/PowerFist.cpp
38479318a832ed9b0e507f837fc09ec48d4fe9b6
[]
no_license
angieshu/CPP-Piscine
fd69f2c9e3e9a10a80f37ee2e3e39763f1aca97d
ab8bc2d45207559f6fd924faaeda593947a6b69b
refs/heads/master
2021-01-01T06:46:04.053983
2017-07-18T18:00:06
2017-07-18T18:00:06
97,503,600
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PowerFist.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ashulha <ashulha@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/08 14:06:24 by ashulha #+# #+# */ /* Updated: 2017/07/08 16:37:35 by ashulha ### ########.fr */ /* */ /* ************************************************************************** */ #include "PowerFist.hpp" PowerFist::PowerFist(void): AWeapon("Power Fist", 8, 50) { return; } PowerFist::PowerFist(PowerFist const & p) { *this = p; return; } void PowerFist::attack(void) const { std::cout << "* pschhh... SBAM! *" << std::endl; return; } PowerFist::~PowerFist(void) { return; }
[ "ashulha@e1z2r8p7.42.us.org" ]
ashulha@e1z2r8p7.42.us.org
5d0c203c667fb08e659232a45f586235fd55cf79
4d048737e5f4c64ad0219518253cae18ed5b83b1
/test/fun.cpp
0b9efcffcf0ebb783538c6f5736d406f69eb3853
[]
no_license
oli-obk/julius_tutorial
9e994d8ae7b1843964162c188262f23530f19625
e08d139c09378587986d464506eab7a9e9b6e237
refs/heads/master
2021-01-22T11:41:56.575360
2014-09-07T15:26:06
2014-09-07T15:26:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
98
cpp
int zufall(int max) { return 40; // ich hab nen würfel geworfen, die zahl ist also zufällig }
[ "julius@julius-obk.de" ]
julius@julius-obk.de
5e3bc7bb55ce402f738e8a8f54924d543767db25
b4f16267d2e19062ec962681c927ef143823a69f
/projekt/problemi/3-sat.cpp
f2b2a5f6d60d10f7d2351d9054e72b87a1df4f09
[]
no_license
astajd/meta-projekt
e8189aedd299d34cb4056e4f8f7ad9e10cc5ac09
84250a9751bf73e50f1f7bc97b69c9c37791ba8f
refs/heads/master
2020-12-25T06:05:24.794628
2012-11-18T11:43:38
2012-11-18T11:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,477
cpp
#include "3-sat.h" // Grnerator speudoslucajnih brojeva unsigned long init[4] = {0x123, 0x234, 0x345, 0x456}, length = 4; MTRand_int32 irand(init, length); MTRand drand(time(0)); //Konstruktor klase Jedinka Jedinka::Jedinka() { for(int i = 0; i < VEL_JEDINKE; ++i) { if((int)(irand()*drand()*10) % 10 < 5) this->bitVektor.push_back(false); else this->bitVektor.push_back(true); } // treba izracunati sada funkciju dobrote } Jedinka::Jedinka(vector<bool> vb) { // treba izracunati dobrotu } /* funkcija stvori_novu_populaciju() /* parametri: Jedinka&, int /* povratna vrijednost: void /* opis: puni vektor populacija sa jedinkama na 2 nacina ovisno o statusu. Ako je status PRAZNA onda puni sve na slucajan nacin /* ako je status IZ_POSTOJECE onda vrsi selekciju prema funckiji dobrote i uzima odredjni postotak najboljih. /* moguce dopune: prvenstveno funkcija u slucaju IZ_POSTOJECE vrati nepotpun vektor jedinki gdje treba dodati mutaciju i krizanje /* pa bi se moglo sloziti da se to automatski radi u ovoj funckciji što bi main ucinilo trivijalnim /************************************************************************************/ void stvori_novu_populaciju(vector<Jedinka>& populacija,int status) { if( status == PRAZNA ) for(int i = 0; i < VEL_POP; ++i) populacija.push_back(Jedinka()); else if( status == IZ_POSTOJECE ) { // slekcija najboljih // krizanje // mutacija } }
[ "anto@cabraja.(none)" ]
anto@cabraja.(none)
7b55a97744a7652be6b8f14e04b86d4afbd7f829
6e31752dab1b418fc288f6205cd8d050d62aa019
/imu.cpp
2667b5671db5e22545603e5726655e74f18299a8
[]
no_license
timwu/ostrich
39fc939d4075e2aec294f5ed5fdbfd44ced7e106
26b41de953d293627871fcc92955fbafc777e071
refs/heads/master
2016-09-06T10:35:20.320922
2014-10-23T09:33:46
2014-10-23T09:33:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,836
cpp
/* * gyro.c * * Created on: Apr 5, 2014 * Author: tim */ #include <ch.h> #include <hal.h> #include <MPU6050.h> #include <math.h> #include "util.h" #define ALMOST_ZERO 0.25 #define ROUND(x) ((x) < ALMOST_ZERO && (x) > -ALMOST_ZERO ? 0 : (x)); #define CALIBRATION_SAMPLES 128 #define TO_DEGREES(x) ((180 / M_PI) * x) #define ACCEL_WEIGHT 0.5 #define UPDATE_INTERVAL_MS 50 static int16_t gyroOffset[3]; static double pitchOffset, rollOffset; static double pitch, roll; static double yawRate; static WORKING_AREA(updateThreadArea, 64); static I2CConfig i2cconfig; static MPU6050 mpu6050; __attribute__((noreturn)) static msg_t imuUpdate(void *) { int16_t ax, ay, az, gx, gy, gz; double prevPitch = pitch, prevRoll = roll, dt; long tick = halGetCounterValue(); while (true) { mpu6050.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); yawRate = ROUND((gz - gyroOffset[2]) / 131.0); dt = ((double) (halGetCounterValue() - tick)) / halGetCounterFrequency(); pitch = ACCEL_WEIGHT * (TO_DEGREES(atan2(ax, az)) - pitchOffset) + (1 - ACCEL_WEIGHT) * (((gy - gyroOffset[1]) / 131.0) * dt + prevPitch); roll = ACCEL_WEIGHT * (TO_DEGREES(atan2(ay, az)) - rollOffset) + (1 - ACCEL_WEIGHT) * (((gx - gyroOffset[0]) / 131.0) * dt + prevRoll); tick = halGetCounterValue(); prevPitch = pitch; prevRoll = roll; chThdSleepMilliseconds(UPDATE_INTERVAL_MS); } } void imuSetup() { i2cStart(&I2CD1, &i2cconfig); mpu6050.initialize(); mpu6050.setFullScaleGyroRange(MPU6050_GYRO_FS_250); mpu6050.setFullScaleAccelRange(MPU6050_ACCEL_FS_8); printf("IMU calibrating...\r\n"); int32_t gyroSum[3] = {0, 0, 0}, accelSum[3] = {0, 0, 0}; int16_t ax, ay, az, gx, gy, gz; int16_t i; for (i = 0; i < CALIBRATION_SAMPLES; i++) { mpu6050.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); accelSum[0] += ax; accelSum[1] += ay; accelSum[2] += az; gyroSum[0] += gx; gyroSum[1] += gy; gyroSum[2] += gz; chThdSleepMilliseconds(1); } gyroOffset[0] = gyroSum[0] / CALIBRATION_SAMPLES; gyroOffset[1] = gyroSum[1] / CALIBRATION_SAMPLES; gyroOffset[2] = gyroSum[2] / CALIBRATION_SAMPLES; accelSum[0] /= CALIBRATION_SAMPLES; accelSum[1] /= CALIBRATION_SAMPLES; accelSum[2] /= CALIBRATION_SAMPLES; pitchOffset = TO_DEGREES(atan2(accelSum[0], accelSum[2])); rollOffset = TO_DEGREES(atan2(accelSum[1], accelSum[2])); pitch = 0; roll = 0; printf("Gyro calibration complete. Offsets: (%d, %d, %d)\r\n", gyroOffset[0], gyroOffset[1], gyroOffset[2]); printf("Pitch offset = %f, roll offset = %f\r\n", pitchOffset, rollOffset); chThdCreateStatic(updateThreadArea, sizeof(updateThreadArea), NORMALPRIO, imuUpdate, NULL); } double imuGetYawRate() { return yawRate; } double imuGetPitch() { return pitch; } double imuGetRoll() { return roll; }
[ "tim.wu.0@gmail.com" ]
tim.wu.0@gmail.com
d462482b0c146c6b8d806a0d6f708f34bbe27120
3c5c1e3836edf3e9627a64600785503d1814df51
/build/Android/Debug/app/src/main/include/Fuse.Properties.h
81b86f45875f544b1d0d312f6d992f0e2a7977c3
[]
no_license
fypwyt/wytcarpool
70a0c9ca12d0f2981187f2ea21a8a02ee4cbcbd4
4fbdeedf261ee8ecd563260816991741ec701432
refs/heads/master
2021-09-08T10:32:17.612628
2018-03-09T05:24:54
2018-03-09T05:24:54
124,490,692
0
0
null
null
null
null
UTF-8
C++
false
false
2,734
h
// This file was generated based on C:/Users/Brian/AppData/Local/Fusetools/Packages/Fuse.Common/1.6.0/Properties.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{struct Properties;}} namespace g{namespace Fuse{struct PropertyHandle;}} namespace g{ namespace Fuse{ // public sealed class Properties :15 // { uType* Properties_typeof(); void Properties__ctor__fn(Properties* __this); void Properties__AddToList_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uObject* val); void Properties__Clear_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle); void Properties__Clear1_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uObject* val, bool* all); void Properties__CreateHandle_fn(::g::Fuse::PropertyHandle** __retval); void Properties__ForeachInList_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uDelegate* action, uArray* state); void Properties__ForeachInList1_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uDelegate* action, uObject* state); void Properties__Get_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uObject** __retval); void Properties__Has_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, bool* __retval); void Properties__New1_fn(Properties** __retval); void Properties__RemoveFromList_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uObject* val); void Properties__Set_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uObject* val); void Properties__TryGet_fn(Properties* __this, ::g::Fuse::PropertyHandle* handle, uObject** val, bool* __retval); struct Properties : uObject { uStrong<Properties*> _next; uStrong< ::g::Fuse::PropertyHandle*> _handle; uStrong<uObject*> _value; static uSStrong<uObject*> NoValue_; static uSStrong<uObject*>& NoValue() { return Properties_typeof()->Init(), NoValue_; } void ctor_(); void AddToList(::g::Fuse::PropertyHandle* handle, uObject* val); void Clear(::g::Fuse::PropertyHandle* handle); void Clear1(::g::Fuse::PropertyHandle* handle, uObject* val, bool all); void ForeachInList(::g::Fuse::PropertyHandle* handle, uDelegate* action, uArray* state); void ForeachInList1(::g::Fuse::PropertyHandle* handle, uDelegate* action, uObject* state); uObject* Get(::g::Fuse::PropertyHandle* handle); bool Has(::g::Fuse::PropertyHandle* handle); void RemoveFromList(::g::Fuse::PropertyHandle* handle, uObject* val); void Set(::g::Fuse::PropertyHandle* handle, uObject* val); bool TryGet(::g::Fuse::PropertyHandle* handle, uObject** val); static ::g::Fuse::PropertyHandle* CreateHandle(); static Properties* New1(); }; // } }} // ::g::Fuse
[ "s1141120@studentdmn.ouhk.edu.hk" ]
s1141120@studentdmn.ouhk.edu.hk
81f8385fc5c0adce53cf3ae10429eacb197b7d4d
39f5ed1178375c65876323589a03ef5daf6e4739
/remoting/protocol/webrtc_video_frame_adapter.cc
d6101980df9d94f2b3295ead677c488aed3ad5fa
[ "BSD-3-Clause" ]
permissive
berber1016/chromium
2718166c02fcb3aad24cc3bd326a4f8d2d7c0cae
9dc373d511536c916dec337b4ccc53106967d28d
refs/heads/main
2023-03-21T21:53:55.686443
2021-05-14T10:13:20
2021-05-14T10:13:20
367,332,075
1
0
BSD-3-Clause
2021-05-14T10:46:30
2021-05-14T10:46:29
null
UTF-8
C++
false
false
1,756
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/webrtc_video_frame_adapter.h" #include <utility> #include "base/notreached.h" #include "third_party/webrtc/rtc_base/ref_counted_object.h" namespace remoting { namespace protocol { WebrtcVideoFrameAdapter::WebrtcVideoFrameAdapter( std::unique_ptr<webrtc::DesktopFrame> frame) : frame_(std::move(frame)), frame_size_(frame_->size()) {} WebrtcVideoFrameAdapter::~WebrtcVideoFrameAdapter() = default; // static webrtc::VideoFrame WebrtcVideoFrameAdapter::CreateVideoFrame( std::unique_ptr<webrtc::DesktopFrame> desktop_frame) { rtc::scoped_refptr<WebrtcVideoFrameAdapter> adapter = new rtc::RefCountedObject<WebrtcVideoFrameAdapter>( std::move(desktop_frame)); return webrtc::VideoFrame::Builder().set_video_frame_buffer(adapter).build(); } std::unique_ptr<webrtc::DesktopFrame> WebrtcVideoFrameAdapter::TakeDesktopFrame() { return std::move(frame_); } webrtc::VideoFrameBuffer::Type WebrtcVideoFrameAdapter::type() const { return Type::kNative; } int WebrtcVideoFrameAdapter::width() const { return frame_size_.width(); } int WebrtcVideoFrameAdapter::height() const { return frame_size_.height(); } rtc::scoped_refptr<webrtc::I420BufferInterface> WebrtcVideoFrameAdapter::ToI420() { // Strictly speaking all adapters must implement ToI420(), so that if the // external encoder fails, an internal libvpx could be used. But the // remoting encoder already uses libvpx, so there's no reason for fallback to // happen. NOTIMPLEMENTED(); return nullptr; } } // namespace protocol } // namespace remoting
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
3bee0eb5896dc53630e67e43645be01ce695f9dc
266f0d4982fd884390f8b561b6a0b6f181b456a0
/cpp/stack.cpp
597a1f4832a42dcab30901e60850b379246e43df
[ "Apache-2.0" ]
permissive
liangyouchen/htql
ea013bcfaa67b6328614f06e8eac45ef83bad8c6
885ac1d05ffbb15ea8e85af54d8654cca0764115
refs/heads/main
2023-07-02T00:33:35.781843
2021-08-15T14:43:34
2021-08-15T14:43:34
323,594,411
0
0
null
null
null
null
UTF-8
C++
false
false
5,447
cpp
// LASTMODIFY CLY20000430 #include "log.h" #include "stack.h" #if defined(_DEBUG) && defined(DEBUG_NEW) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif tStack::tStack(){ Key=NULL; Value=NULL; Next=NULL; PreSearch=NULL; Type=0; Data=0; } tStack::tStack(char *OneKey, char* TheValue){ Key=NULL; Value=NULL; Next=NULL; PreSearch=NULL; Type=0; Data=0; if (OneKey) Key=(char*)malloc(sizeof(char)*(strlen(OneKey)+1)); if (TheValue) Value=(char*)malloc(sizeof(char)*(strlen(TheValue)+1)); Data=0; Type=0; if (TheValue && Value==NULL) { if (Key) free(Key); Key=NULL; } if (Key && OneKey) if (OneKey) strcpy(Key,OneKey); if (Value&& TheValue) strcpy(Value,TheValue); } tStack::tStack(int StackType, long TheData, const char* OneKey, const char* TheValue) { Key=NULL; Value=NULL; Next=NULL; PreSearch=NULL; Data=TheData; Type=StackType; if (OneKey) Key=(char*)malloc(sizeof(char)*(strlen(OneKey)+1)); if (TheValue) Value=(char*)malloc(sizeof(char)*(strlen(TheValue)+1)); if (TheValue && Value==NULL) { if (Key) free(Key); Key=NULL; } if (Key && OneKey) if (OneKey) strcpy(Key,OneKey); if (Value&& TheValue) strcpy(Value,TheValue); } tStack::~tStack(){ reset(); } int tStack::reset(){ if (Key) free(Key); if (Value) free(Value); if (Next) { tStack* old=Next; tStack* p=old->Next; while (p) { old->Next=NULL; delete(old); old=p; p=old->Next; } delete old; } Key=NULL; Value=NULL; Next=NULL; PreSearch=NULL; Data=0; return True; } tStack* tStack::add(const char* OneKey, const char* TheValue, int AddToTail){ tStack* newStack=NULL; tStack* tmp; if (AddToTail){ for (tmp=this; tmp->Next; tmp=tmp->Next); newStack=new tStack(Type,0,OneKey,TheValue); if (!newStack->Key) { delete newStack; return NULL; } tmp->Next=newStack; }else{ newStack=new tStack(Type,0,OneKey,TheValue); if (!newStack->Key){ delete newStack; return NULL; } newStack->Next=Next; Next=newStack; } return newStack; } tStack* tStack::set(long TheData, const char* OneKey, const char* TheValue){ tStack* newStack=NULL; tStack* tmp; if (Type == ordFILO || Type == ordFIFO){ newStack= add(OneKey, TheValue,Type == ordFIFO); newStack->Data = TheData; return newStack; } switch (Type){ case ordINCDATA: for (tmp=this; tmp->Next && TheData > tmp->Next->Data; tmp=tmp->Next); /*if (tmp->Next && tmp->Next->Data == TheData){ if ( tmp->Next->newKey(OneKey) && tmp->Next->newValue(TheValue) ) return tmp->Next; else return NULL; }*/ break; case ordDECDATA: for (tmp=this; tmp->Next && TheData < tmp->Next->Data; tmp=tmp->Next); break; case ordINCVALUE: for (tmp=this; tmp->Next && strcmp(TheValue, tmp->Next->Value) > 0; tmp=tmp->Next); break; case ordDECVALUE: for (tmp=this; tmp->Next && strcmp(TheValue, tmp->Next->Value) < 0; tmp=tmp->Next); break; case ordINCKEY: for (tmp=this; tmp->Next && strcmp(OneKey, tmp->Next->Key) > 0; tmp=tmp->Next); break; case ordDECKEY: for (tmp=this; tmp->Next && strcmp(OneKey, tmp->Next->Key) < 0; tmp=tmp->Next); break; default: tmp=this; break; } newStack=new tStack(Type,TheData,OneKey,TheValue); if (!newStack->Key){ delete newStack; return NULL; } if (Type==ordINCDATA || Type==ordINCVALUE || Type==ordINCKEY){ newStack->Next = tmp->Next; tmp->Next=newStack; }else{ if (tmp->Next) { newStack->Next = tmp->Next->Next; tmp->Next->Next=newStack; }else{ tmp->Next=newStack; } } return newStack; } char* tStack::newKey(const char* OneKey, long len){ if (len<=0) len = strlen(OneKey); if (!Key || len>=sizeof(Key) ){ if (Key) free(Key); Key=(char*)malloc(sizeof(char)*(len+1)); if (!Key) return NULL; } memcpy(Key, OneKey, len); Key[len]=0; return Key; } char* tStack::newValue(const char* TheValue, long len){ if (len<=0 && TheValue) len = strlen(TheValue); else if (len<0) len=0; if (!Value || (size_t) len>strlen(Value) ){ if (Value) free(Value); Value=(char*)malloc(sizeof(char)*(len+1)); if (!Value) return NULL; } if (TheValue){ if ((size_t) len>strlen(TheValue)){ strcpy(Value, TheValue); }else{ memcpy(Value, TheValue, len); Value[len]=0; } }else{ Value[0]=0; } return Value; } int tStack::match(const char* OneKey){ if (Key && strcmp(OneKey, Key)==0) return True; return False; } tStack* tStack::search(const char* OneKey, char** ValuePointer){ if (ValuePointer) *ValuePointer=NULL; PreSearch=Next; while (PreSearch){ if (PreSearch->match(OneKey)){ if (ValuePointer) *ValuePointer=PreSearch->Value; return PreSearch; } PreSearch=PreSearch->Next; } return NULL; } tStack* tStack::search(long TheData){ // *ValuePointer=NULL; PreSearch=Next; while (PreSearch){ if (PreSearch->Data == TheData){ return PreSearch; } PreSearch=PreSearch->Next; } return NULL; } tStack* tStack::searchNext(const char* OneKey, char** ValuePointer){ if (ValuePointer) *ValuePointer=NULL; if (PreSearch) PreSearch=PreSearch->Next; while (PreSearch){ if (PreSearch->match(OneKey)){ if (ValuePointer) *ValuePointer=PreSearch->Value; return PreSearch; } PreSearch=PreSearch->Next; } return 0; }
[ "lchen@vps.server.local" ]
lchen@vps.server.local
de0ff8d81fb18611102e6095a6ede47181f2b481
7d11198a7c7be87fad7f64695059a3e4e71c4bee
/src/ui/space_browser.h
59bd28864fd9f740f9c50508a1091a1f579ab630
[]
no_license
mdecicco/rosen
18d06d3321d84bfca6f07799ad27eb0ead5f5b26
d74e799ca45b83b7f9a76c647e060264f128d970
refs/heads/master
2021-05-27T08:16:17.161048
2020-05-14T02:13:14
2020-05-14T02:13:14
254,244,283
0
0
null
null
null
null
UTF-8
C++
false
false
671
h
#pragma once #include <r2/config.h> #include <managers/space_man.h> namespace rosen { class ui_man; class space_browser { public: space_browser(space_man* smgr, ui_man* umgr); ~space_browser(); void update(r2::f32 frameDt, r2::f32 updateDt); void render(bool* isOpen); void element_ui(space_element_entity* element); void collider_ui(space_collision_element_entity* collider); void light_ui(space_light_element_entity* light); void camera_ui(rosen_space::camera_node* cam, r2::u32 idx); void poi_clicked(const r2::mstring& name); protected: space_man* m_mgr; ui_man* m_ui; // ui params r2::i32 m_selectedSpaceIdx; }; };
[ "mdecicco8@gmail.com" ]
mdecicco8@gmail.com
364f2c23a514704b9d4ebb56c1acf99bff610c87
c666425a87aa2ee1d777c5187104fa5ddcdaa399
/Packages/bag2scans/src/record.cc
1eebbb3e581ba6373783a0eac9df797c1125ebd7
[]
no_license
SiChiTong/3D-Scan-acquisition-using-Teach-in-with-ROS
b348552519b434359e360cba195b6e6063c7de61
c58d80015019ef27c604c967d5ea2a014dae7898
refs/heads/master
2021-08-23T23:04:29.686962
2017-12-07T00:53:55
2017-12-07T00:53:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,352
cc
#include "rosbag2/recorder.h" #include "rosbag/exceptions.h" #include <rclock/logDir.h> #include <string> using std::string; int main(int argc, char** argv) { ros::init(argc, argv, "record", ros::init_options::AnonymousName); ros::NodeHandle n; string filename; n.param<std::string>("/log/bagfile", filename, "log.bag"); // wait for global logging directory to become available ros::service::waitForService("logDirectory"); rclock::logDir::Request empty; rclock::logDir::Response dir; // get loggin dir ros::service::call("logDirectory", empty, dir); filename = dir.directory + filename; // /tmp/dat/YY_MM_DD_HH_MM_SS/scan3d/ rosbag2::RecorderOptions opts; opts.topics.push_back("/IrmaClock"); opts.topics.push_back("/LMS"); opts.topics.push_back("/VMC"); opts.topics.push_back("/Vel"); opts.topics.push_back("/clock"); opts.topics.push_back("/imu_data"); opts.topics.push_back("/odom"); opts.topics.push_back("/robot_pose_ekf/odom_combined"); opts.topics.push_back("/map"); opts.topics.push_back("/riegl"); opts.topics.push_back("/rieglstatus"); opts.topics.push_back("/tf"); opts.topics.push_back("/riegltime"); opts.prefix = filename; opts.append_date = false; // Run the recorder rosbag2::Recorder recorder(opts); int result = recorder.run(); return result; }
[ "oliver.struckmeier@onlinehome.de" ]
oliver.struckmeier@onlinehome.de
c589310bd2e33ec30c14ffdb36651061bf42c450
61b1d35d29bc40bcb378f94fa62a7051bd0bd581
/solution/common/src/common.cpp
4cced2525e7dd44428aa3c1b6e3f3442225dd1c8
[]
no_license
silverfield/ttbl-final
8fe81b87d4fb561d0b356f513dbbd24202f3952d
86fe7f564de2654115c4fbaf1408724b27f203ff
refs/heads/master
2021-01-22T14:39:15.080455
2013-05-04T16:51:54
2013-05-04T16:51:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,074
cpp
/*****************************************************************/ /* Includes /*****************************************************************/ #include "string.h" #include <sstream> #include <iostream> #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <time.h> #include "common.h" using namespace std; using namespace boost; /*****************************************************************/ /* Functions - general /*****************************************************************/ string fExec(const char* cmd) { FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[128]; string result = ""; while(!feof(pipe)) { if(fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } string fCharArrayToString(const char *iCharArray) { string lResult(iCharArray); //for (int i = 0; iCharArray[i] != 0; i++) { // lResult += iCharArray[i]; //} return lResult; } vector<string> fSplitString(string iString, char iSeparator) { vector<string> lItems; string lItem = ""; for (string::iterator i = iString.begin(); i != iString.end(); i++) { if (*i == iSeparator) { lItems.push_back(lItem); lItem = ""; continue; } lItem += *i; } lItems.push_back(lItem); return lItems; } vector<string> fSplitString(string iString, string iSeparator) { vector<string> lItems; split(lItems, iString, is_any_of(iSeparator)); //TODO change to exact return lItems; } string fIntToStr(int iInteger) { //stringstream lStream; //lStream << iInteger; char lBuffer [30]; sprintf(lBuffer, "%d", iInteger); return fCharArrayToString(lBuffer); } int fStrToIntNoCheck(string iString) { return atoi(iString.c_str()); } int fStrToInt(string iString) { if (fIsInt(iString) == false) { return -1; } return atoi(iString.c_str()); } string fDoubleToStr(double iDouble) { char lBuffer[30]; snprintf(lBuffer, sizeof(lBuffer), "%g", iDouble); return fCharArrayToString(lBuffer); } double fStrToDouble(string iString) { if (fIsDouble(iString) == false) { return 0; } return atof(iString.c_str()); } double fStrToDoubleNoCheck(string iString) { return atof(iString.c_str()); } bool fIsDouble(string iString) { bool lGotDot = false; for (string::size_type i = 0; i < iString.size(); i++) { if (i == 0 && iString[i] == '-') { continue; } if (iString[i] == '.' && (lGotDot || i == 0)) { return false; } else if (iString[i] == '.') { lGotDot = true; continue; } if (isdigit(iString[i]) == false) { return false; } } return true; } bool fIsInt(string iString) { for (string::size_type i = 0; i < iString.size(); i++) { if (i == 0 && iString[i] == '-') { continue; } if (isdigit(iString[i]) == false) { return false; } } return true; } string fCharRemove(string iString, char iChar) { string lResult = ""; for (int i = 0; i < iString.size(); i++) { if (iString[i] != iChar) { lResult += iString[i]; } } return lResult; } string fJustFileName(string iFileName) { vector<string> lParts = fSplitString(iFileName, "/"); vector<string> lNameExt = fSplitString(lParts[lParts.size() - 1], "."); return lNameExt[0]; } string fPadString(string iString, int iTotalWidth) { string lResult = iString; int lPadding = max(0, iTotalWidth - (int)iString.size()); string lPaddingString(lPadding, ' '); lResult += lPaddingString; return lResult; } string fPadInt(int iInt, int iTotalWidth) { string lResult = fIntToStr(iInt); int lPadding = max(0, iTotalWidth - (int)lResult.size()); string lPaddingString(lPadding, '0'); lResult = lPaddingString + lResult; return lResult; } string fGetLongString(int iSize) { string lResult = ""; for (int i = 0; i < iSize; i += 100) { lResult += string(100, '-'); } return lResult; } vector<int> fRandomPermutation(int iN) { vector<int> lResult = fIdentityVector(iN); for (int i = 1; i < iN; i++) { int lPos = rand() % (i + 1); int lTemp = lResult[i]; lResult[i] = lResult[lPos]; lResult[lPos] = lTemp; } return lResult; } vector<int> fIdentityVector(int iN) { vector<int> lResult; lResult.reserve(iN); for (int i = 0; i < iN; i++) { lResult.push_back(i); } return lResult; } int fRound(double iDouble) { if ((iDouble - (double)((int)iDouble)) >= 0.5) { return 1 + (int)iDouble; } return (int)iDouble; } /*****************************************************************/ /* Time related /*****************************************************************/ int fTimeToMinutes(Time iTime) { return iTime.cDays * 24 * 60 + iTime.cHours * 60 + iTime.cMinutes; } Time fMinutesToTime(int iMinutes) { Time lTime; lTime.cMinutes = iMinutes % 60; iMinutes /= 60; lTime.cHours = iMinutes % 24; iMinutes /= 24; lTime.cDays = iMinutes; return lTime; } string fTimeToString(Time iTime) { return fIntToStr(iTime.cDays) + " " + fPadInt(iTime.cHours, 2) + ":" + fPadInt(iTime.cMinutes, 2); } Time fStringToTimeNoCheck(string iTimeString) { //eg. 134 23:59 Time lTime; //lTime.cDays = fStrToInt(lDayHours[0]); lTime.cDays = fStrToIntNoCheck(iTimeString.substr(0, iTimeString.size() - 6)); //vector<string> lHourMinutes = fSplitString(lDayHours[1], ":"); //lTime.cHours = fStrToInt(lHourMinutes[0]); lTime.cHours = fStrToIntNoCheck(iTimeString.substr(iTimeString.size() - 5, 2)); //lTime.cMinutes = fStrToInt(lHourMinutes[1]); lTime.cMinutes = fStrToIntNoCheck(iTimeString.substr(iTimeString.size() - 2, 2)); return lTime; } Time fStringToTime(string iTimeString) { //eg. 134 23:59 Time lTime; if (iTimeString.size() < 7) { return lTime; } //lTime.cDays = fStrToInt(lDayHours[0]); lTime.cDays = fStrToInt(iTimeString.substr(0, iTimeString.size() - 6)); //vector<string> lHourMinutes = fSplitString(lDayHours[1], ":"); //lTime.cHours = fStrToInt(lHourMinutes[0]); lTime.cHours = fStrToInt(iTimeString.substr(iTimeString.size() - 5, 2)); //lTime.cMinutes = fStrToInt(lHourMinutes[1]); lTime.cMinutes = fStrToInt(iTimeString.substr(iTimeString.size() - 2, 2)); return lTime; }
[ "ferohajnovic@gmail.com" ]
ferohajnovic@gmail.com
ee68bdfc6d7c83d1c7f9bc9a06d85477db2f30d6
6250cf5f3bc3f2e748a1ddf8bb2de3dbe5652ba0
/2019/qualification/C/pangram.cpp
404b4a781087fe9e6ca0e71f577e2c1279e9c774
[ "MIT" ]
permissive
qkniep/google-code-jam
ecab75a6edec6f9c2a1b230973fcf36ec9f56d70
b6b6b1f2e4927a2059848df4c8e955a7d20b1a62
refs/heads/master
2021-05-01T18:05:34.655020
2021-01-26T09:00:41
2021-01-26T09:00:41
121,002,367
0
0
null
null
null
null
UTF-8
C++
false
false
1,581
cpp
#include <array> #include <iostream> #include <set> #include <vector> std::set<int> panPrimes; std::vector<std::array<int, 2>> factors; int gcd(int a, int b) { while (b != 0) { int t = a % b; a = b; b = t; } return a; } char charForPrime(int prime) { int c = 0; for (int p : panPrimes) { if (p < prime) c++; } return 'A' + c; } bool findSolution(int id, int offset) { std::string s; int a, b; for (size_t i = 0; i < factors.size(); ++i) { a = factors[i][offset]; b = factors[i][1-offset]; s.push_back(charForPrime(a)); if (i == factors.size()-1) continue; if (factors[i+1][0] == b) offset = 0; else if (factors[i+1][1] == b) offset = 1; else return false; } s.push_back(charForPrime(b)); std::cout << "Case #" << id << ": " << s << std::endl; return true; } void findFactors(int L, const std::vector<int>& list) { factors.clear(); panPrimes.clear(); int f1, f2, toCopy = 0; for (int i = 0; i < L; ++i) { if (i < L-1) { if (list[i] == list[i+1]) { toCopy++; continue; } f1 = gcd(list[i], list[i+1]); } f2 = list[i] / f1; factors.push_back({f1, f2}); for (; toCopy > 0; toCopy--) { factors.push_back({f1, f2}); } panPrimes.insert(f1); panPrimes.insert(f2); } } int main() { int T; std::cin >> T; for (int t = 1; t <= T; ++t) { int N, L; std::cin >> N >> L; std::vector<int> list; for (int i = 0; i < L; ++i) { int x; std::cin >> x; list.push_back(x); } findFactors(L, list); if (!findSolution(t, 0)) { findSolution(t, 1); } } }
[ "hello@quentinkniep.com" ]
hello@quentinkniep.com
1fb061af5a898016f4e40b94210c8a4bab2bc912
37ffd116535acab191da2b4c62dfd58868f8287b
/palindrome_linked_list/solution.cpp
a772dd2e12f828676c2282699674e8915ea70552
[]
no_license
huwenboshi/leetcode_exercises
c1a494dd4452d2644d21d7bb337f8b268508df17
73bb1741070b50b7729afe7e2edb79d224b2a6d4
refs/heads/master
2019-06-24T14:20:27.149089
2016-08-30T06:43:08
2016-08-30T06:43:08
66,914,041
1
0
null
null
null
null
UTF-8
C++
false
false
1,977
cpp
#include <stdio.h> #include <stdlib.h> struct ListNode { int val; struct ListNode *next; }; void print_list(struct ListNode* head) { while(head != NULL) { printf("%d ", head->val); head = head->next; } printf("\n"); } struct ListNode* reverseList(struct ListNode* head) { if(head == NULL || head->next == NULL) { return head; } struct ListNode *ptr1=head, *ptr2=head->next, *ptr3=head->next->next; ptr1->next = NULL; while(ptr3 != NULL) { ptr2->next = ptr1; ptr1 = ptr2; ptr2 = ptr3; ptr3 = ptr3->next; } ptr2->next = ptr1; return ptr2; } bool isPalindrome(struct ListNode* head) { int length = 0; struct ListNode *ptr = head; while(ptr != NULL) { length += 1; ptr = ptr->next; } if(length <= 1) { return true; } struct ListNode *first_half = head; ptr = head; for(int i=0; i<length/2-1; i++) { ptr = ptr->next; } struct ListNode *second_half = ptr->next; if(length % 2 != 0) { second_half = second_half->next; } ptr->next = NULL; second_half = reverseList(second_half); while(first_half != NULL && second_half != NULL) { if(first_half->val != second_half->val) { return false; } first_half = first_half->next; second_half = second_half->next; } return true; } int main() { struct ListNode one; one.val = 1; struct ListNode two; two.val = 2; struct ListNode three; three.val = 3; struct ListNode four; four.val = 4; struct ListNode three2; three2.val = 3; struct ListNode two2; two2.val = 2; struct ListNode one2; one2.val = 1; one.next = &two; //two.next = &three; two.next = NULL; three.next = &four; four.next = &three2; three2.next = &two2; two2.next = &one2; one2.next = NULL; print_list(&one); printf("%d\n", isPalindrome(&one)); }
[ "shihuwenbo@ucla.edu" ]
shihuwenbo@ucla.edu
0994f4383ca3a78a64f87bfe5fdf26ccfcbccdfa
552e8f8a14209c214789894f91ecdaf0dd00e98b
/StaticHttpServer/Response.h
25672f7968ffa0b3545515e715d2b25d1e1f9ae7
[ "MIT" ]
permissive
ZiJiaW/StaticHttpServer
2f9200362f920d3c5e5ad3a652230fa70ff778b9
92f9eedfd91d7549a87f9a4d50a6f05ee547fcc8
refs/heads/master
2020-08-28T11:29:18.230252
2019-12-01T04:58:17
2019-12-01T04:58:17
217,685,389
0
0
null
null
null
null
GB18030
C++
false
false
1,153
h
#pragma once #include "basic.h" namespace http { class Response { public: Response() = default; ~Response() = default; // 因为单次http应答发送完就会销毁,这里禁止copy,以减少不必要的开销 // 也可以用智能指针,但是这样比较cool~~ Response(const Response &rsp) = delete; Response &operator=(const Response &rsp) = delete; Response(Response &&rsp) noexcept = default; Response &operator=(Response &&rsp) noexcept = default; void set_code(StatusCode code) { code_ = code; } void set_headline(const std::string &hl) { headline_ = hl; } void set_header(std::string &&name, std::string &&value) { headers_.push_back(std::make_pair(std::move(name), std::move(value))); } void set_body(std::string &&body) { body_ = std::move(body); } void push_body(const char *buf, std::size_t size) { body_.append(buf, size); } std::size_t body_size() { return body_.size(); } std::string ToString(); private: std::string headline_; std::vector<std::pair<std::string, std::string>> headers_; std::string body_; StatusCode code_; }; }// namespace http
[ "964513305@qq.com" ]
964513305@qq.com
f34e9e1747a52b0f03747f9b0ab91fbb07b1fab7
47abd462bf24f3b19000d88b7f9d63622a1a3fe6
/JB/Week1/3015_Patrick/compare.cpp
49a2b53ec83f07ec62cdd0e10da20eacf09267a8
[ "Apache-2.0" ]
permissive
alps-jbnu/ALPS_2020_Summer_Study
1f5b9e59ca2e8dcd10fdeced043f19e3a3b5aeeb
3656d5c6ab44f7f43c1f8c691e75352495c76adc
refs/heads/master
2022-12-16T04:28:25.099163
2020-08-27T07:20:31
2020-08-27T07:20:31
277,059,912
1
0
null
null
null
null
UTF-8
C++
false
false
3,052
cpp
// code by KiWan #include <iostream> #include <string> #include <cstring> #include <vector> #include <queue> #include <set> #include <cmath> #include <algorithm> #include <stack> using namespace std; #define INF 987654321 #define INF2 1e9; #define MOD 998244353 #define pii pair<int, int> #define pll pair<long long, long long> typedef long long ll; int N; int main() { ios_base ::sync_with_stdio(false); cin.tie(NULL); cin >> N; stack<pll> st; ll f, s; //f는 키, s는 나와 키가 같은 사람의 수 ll ans = 0; while (N--) { cin >> f; s = 1; // 나와 키가 같은 사람은 나 1명이다. if (st.empty()) { //지금 아무도 줄 서 있지 않다면 그냥 push st.push({f, s}); } else { while (true) { //스택에는 지금까지 내앞에 줄을 서있는 사람이 들어있습니다. //이때 내가 해당 스택에 들어가고자 하는데 //나 보다 키가 작은 사람이 이미 내 앞에 있으면 //나로 인해 그 키가 작은 사람은 내 뒤에 오게 될 사람과 짝을 짓지 못하게 됩니다. //그래서 현재 스택에 나보다 키가 큰 사람이 있으면 그 사람과 나를 짝을 짓고 //나보다 키가 작은 사람들은 스택에서 pop합니다. if (st.empty()) { //그러다가 나보다 키가 작은 사람이 더이상 내앞에 없으면 나를 push st.push({f, s}); break; } else if (st.top().first <= f) { //해당사람이 나보다 키가 작거나 같으면 pll tmp = st.top(); st.pop(); // 그사람을 빼줍니다. ans += tmp.second; // 이때 second는 중복된 연속된 사람의 수를 의미 합니다. //그러니 222224와 같다고 할때 내앞에 똑같은 2가 5개가 있는 꼴인데 전부 4랑 짝을지을수 있으니 //ans += 5를 해주는 것과 같습니다. if (tmp.first == f) { // 근데 만약 나와 키가 같다면 s += tmp.second; //현재 내가 만난 나와 키가 같은 사람의 수를 s에 더해줍니다. 다음차례에 나는 스택에 들어 갈 것입니다. } } else if (st.top().first > f) { //만약 나보다 키가 큰사람이 스택에 있다면 st.push({f, s}); //나는 그냥 넣어줍니다. 왜냐하면 키큰 사람보다 앞에 있는 사람과 나는 짝을 지을 수 없기 때문입니다. ans++; break; } } } } cout << ans; return 0; }
[ "danieltiger60@gmail.com" ]
danieltiger60@gmail.com
5de08395e91e1ed0bc6422520efcdccc1127b9dc
0fc1c12ee854d3d5cc6d8f07a279e4bdc0d792fb
/Client/ProgressDlg.cpp
fedca9e2c0289e7bd53088dbb07352f990d971ad
[]
no_license
webs3c/remote_control
c5c58ba3b15096e936314cc4995afbcab59e0f0a
a5b1cb28c176323fbcd69a242cf14b29366bd52b
refs/heads/master
2021-01-02T08:50:40.929835
2014-05-03T15:53:33
2014-05-03T15:53:33
null
0
0
null
null
null
null
GB18030
C++
false
false
7,907
cpp
// ProgressDlg.cpp : 实现文件 // #include "stdafx.h" #include "Client.h" #include "ProgressDlg.h" #include "SystemManager.h" // CProgressDlg 对话框 typedef struct { TCHAR *title; int nWidth; }COLUMN_PRO; //进程List列表信息 COLUMN_PRO g_Column[] = { {_T("进程名称"), 102 }, {_T("进程ID"), 82 }, {_T("线程总数"), 82 }, {_T("进程优先级"), 82 }, {_T("进程路径"), 210 } }; static int g_Pro_Len = 0; //列长度 static int g_Pro_Count = sizeof(g_Column) / sizeof(COLUMN_PRO) ; //list控件列表数目 IMPLEMENT_DYNAMIC(CProgressDlg, CDialog) CProgressDlg::CProgressDlg(CWnd* pParent /*=NULL*/, SOCKET sock) : CDialog(CProgressDlg::IDD, pParent) { m_socket = sock; m_pWndMsg = pParent; m_bRefresh = false; } CProgressDlg::~CProgressDlg() { } void CProgressDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_PROGRESS, m_proListCtrl); } BEGIN_MESSAGE_MAP(CProgressDlg, CDialog) ON_NOTIFY(NM_RCLICK, IDC_LIST_PROGRESS, &CProgressDlg::OnNMRClickListProgress) ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_PROGRESS, &CProgressDlg::OnLvnItemchangedListProgress) ON_COMMAND(ID_PROC_TASKKILL, &CProgressDlg::OnProcTaskkill) ON_COMMAND(ID_PROC_REFRESH, &CProgressDlg::OnProcRefresh) END_MESSAGE_MAP() // CProgressDlg 消息处理程序 BOOL CProgressDlg::PreTranslateMessage(MSG* pMsg) { // TODO: 在此添加专用代码和/或调用基类 if ( WM_KEYDOWN == pMsg->message) { int nVirtKey = (int)pMsg->wParam; if (VK_RETURN == nVirtKey || VK_ESCAPE == nVirtKey) //如果按下的是回车键或ESC键,则截断消息 { return TRUE; } } return CDialog::PreTranslateMessage(pMsg); } BOOL CProgressDlg::OnInitDialog() { CDialog::OnInitDialog(); // TODO: 在此添加额外的初始化 DlgInit(); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void CProgressDlg::DlgInit() { for (int Index = 0 ; Index < g_Pro_Count ; Index++) //插入列 { m_proListCtrl.InsertColumn(Index, g_Column[Index].title); m_proListCtrl.SetColumnWidth(Index, g_Column[Index].nWidth); g_Pro_Len += g_Column[Index].nWidth; } m_proListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES); m_MenuBmp[0].LoadBitmap(IDB_BMP_TASKKILL); m_MenuBmp[1].LoadBitmap(IDB_BMP_REFRESH); MSGINFO tagMsgInfo; memset(&tagMsgInfo, 0, sizeof(MSGINFO)); tagMsgInfo.nMsgCmd = CMD_PROGRESS; //进程管理查看 bool bSuccess = true; m_moduleSocket.SendCommand(m_socket, (char*)&tagMsgInfo, sizeof(MSGINFO), &bSuccess); if (!bSuccess) { ::MessageBox(this->m_hWnd, _T("查看进程信息失败!"), _T("提示"), MB_OK | MB_ICONWARNING); } } void CProgressDlg::SetProcessInfo( IN PROGRESS_C tagProInfo ) { CString strProName = _T(""); //进程名 CString strPid = _T(""); //进程的PID CString strThreadCount = _T(""); //进程下的所有线程数 CString strLevel = _T(""); //进程的优先级 CString strProPath = _T(""); //进程的路径 //显示到界面上 strProName.Format(_T("%s"), tagProInfo.szProName); strPid.Format(_T("%d"), tagProInfo.nPid); strThreadCount.Format(_T("%d"), tagProInfo.nThreadCount); strLevel = GetProcessLevel(tagProInfo.nLevel); strProPath.Format(_T("%s"), tagProInfo.szProPath); if (m_bRefresh) { m_proListCtrl.DeleteAllItems(); //如果是刷新,则删除所有项 m_bRefresh = false; } int nIndex = m_proListCtrl.GetItemCount(); m_proListCtrl.InsertItem(nIndex, strProName); m_proListCtrl.SetItemText(nIndex, 1, strPid); m_proListCtrl.SetItemText(nIndex, 2, strThreadCount); m_proListCtrl.SetItemText(nIndex, 3, strLevel); m_proListCtrl.SetItemText(nIndex, 4, strProPath); m_proListCtrl.SetItemData(nIndex, (DWORD_PTR)tagProInfo.nPid); //更新状态栏 CString strCount = _T(""); strCount.Format(_T("数量:%d"), nIndex); CString strKillInfo = _T(""); if (1 == tagProInfo.nTag) { strKillInfo = _T("进程结束成功!"); } else if (2 == tagProInfo.nTag) { strKillInfo = _T("进程结束失败!"); } UpDataStatusBar(strKillInfo, strCount); } CString CProgressDlg::GetProcessLevel(IN int proLevel) { //进程优先级 CString strLevel = _T(""); switch (proLevel) { case UNKNOWN_LEVEL: { strLevel = _T("未知"); } break; case NORMAL: { strLevel = _T("普通"); } break; case IDLE: { strLevel = _T("低"); } break; case REALTIME: { strLevel = _T("实时"); } break; case HIGH: { strLevel = _T("高"); } break; case ABOVENORMAL: { strLevel = _T("高于标准"); } break; case BELOWNORMAL: { strLevel = _T("低于标准"); } break; } return strLevel; } //更新状态栏 void CProgressDlg::UpDataStatusBar(IN CString strLeft, IN CString strRight) { ::SendMessage( ((CSystemManager*)this->m_pWndMsg)->m_sysStatusBar, SB_SETTEXT, (WPARAM)0, (LPARAM)strLeft.GetBuffer(0)); ::SendMessage( ((CSystemManager*)this->m_pWndMsg)->m_sysStatusBar, SB_SETTEXT, (WPARAM)1, (LPARAM)strRight.GetBuffer(1)); } void CProgressDlg::OnNMRClickListProgress(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 int nItem = pNMItemActivate->iItem; //选中项的索引值 if (-1 == nItem) { return ; } CMenu processMenu; //操作目录 processMenu.LoadMenu(IDR_MENU_PROCESS); CMenu *pSubMenu = processMenu.GetSubMenu(0); pSubMenu->SetMenuItemBitmaps(ID_PROC_TASKKILL, MF_BYCOMMAND, &m_MenuBmp[0], &m_MenuBmp[0]); //图标 pSubMenu->SetMenuItemBitmaps(ID_PROC_REFRESH, MF_BYCOMMAND, &m_MenuBmp[1], &m_MenuBmp[1]); CPoint point; GetCursorPos(&point); //获取光标位置 pSubMenu->TrackPopupMenu(TPM_LEFTALIGN, point.x, point.y, this); *pResult = 0; } void CProgressDlg::OnLvnItemchangedListProgress(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 CString strShowMsg = _T("进程名称: "); int nItem = pNMLV->iItem; if (-1 == nItem) { return; } CString strProName = m_proListCtrl.GetItemText(nItem, 0); //进程名 CString strProPid = m_proListCtrl.GetItemText(nItem, 1); //进程的PID strShowMsg = strShowMsg + strProName + _T(" ID:") + strProPid; ::SendMessage( ((CSystemManager*)this->m_pWndMsg)->m_sysStatusBar, SB_SETTEXT, (WPARAM)0, (LPARAM)strShowMsg.GetBuffer(0)); *pResult = 0; } //关闭指定的进程 void CProgressDlg::OnProcTaskkill() { // TODO: 在此添加命令处理程序代码 POSITION pos; pos = m_proListCtrl.GetFirstSelectedItemPosition(); if (NULL == pos) { return ; } int nItem = m_proListCtrl.GetNextSelectedItem(pos); PROGRESS_C tagProInfo; memset(&tagProInfo, 0, sizeof(PROGRESS_C)); tagProInfo.nPid = m_proListCtrl.GetItemData(nItem); //获取PID值 MSGINFO tagMsgInfo; memset(&tagMsgInfo, 0, sizeof(MSGINFO)); tagMsgInfo.nMsgCmd = CMD_PROC_TASKKILL; //结束进程 memcpy((char*)tagMsgInfo.context, (char*)&tagProInfo, sizeof(PROGRESS_C)); bool bSuccess = true; m_moduleSocket.SendCommand(m_socket, (char*)&tagMsgInfo, sizeof(MSGINFO), &bSuccess); m_bRefresh = true; } //刷新进程列表 void CProgressDlg::OnProcRefresh() { // TODO: 在此添加命令处理程序代码 m_bRefresh = true; MSGINFO tagMsgInfo; memset(&tagMsgInfo, 0, sizeof(MSGINFO)); tagMsgInfo.nMsgCmd = CMD_PROGRESS; //发送刷新命令 bool bSuccess = true; m_moduleSocket.SendCommand(m_socket, (char*)&tagMsgInfo, sizeof(MSGINFO), &bSuccess); } void CProgressDlg::OnCancel() { // TODO: 在此添加专用代码和/或调用基类 DestroyWindow(); delete this; } void CProgressDlg::PostNcDestroy() { // TODO: 在此添加专用代码和/或调用基类 ((CSystemManager*)this->m_pParentWnd)->m_progressDlg = NULL; CDialog::PostNcDestroy(); }
[ "hswjzhang@gmail.com" ]
hswjzhang@gmail.com
0cfe40867c73d9433d85f535dfc88cf0e3614b44
d03f3469179a0884d387ccd49ce00eb9e75354c5
/src/solvers/ABT/solver/search/steppers/default_rollout.hpp
66f0d72e0585034252d00fdcd558dc912ce83a7c
[]
no_license
Ningg17/oppt
b9063d30acee090b16b97c7857660afdc2ebb122
750c265d059ff43f27aaf8f407639e062a1d7da8
refs/heads/master
2023-07-22T15:54:16.969457
2021-07-19T16:03:05
2021-07-19T16:03:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,218
hpp
/** @file default_rollout.hpp * * Defines a simple rollout strategy that queries the model for a history-based rollout action. * This is done via the StepGenerator and StepGeneratory factory classes in search_interface.hpp. */ #ifndef SOLVER_DEFAULTROLLOUTSTRATEGY_HPP_ #define SOLVER_DEFAULTROLLOUTSTRATEGY_HPP_ #include "solvers/ABT/solver/search/SearchStatus.hpp" #include "solvers/ABT/solver/search/search_interface.hpp" namespace abt { class HistoricalData; class HistorySequence; class Solver; /** A StepGenerator implementation that simply queries the model for a rollout action at each * time step. */ class DefaultRolloutGenerator: public StepGenerator { public: /** Makes a new DefaultRolloutGenerator, which will be associated with the given solver, and * will only take the specified maximum # of steps in depth. */ DefaultRolloutGenerator(SearchStatus &status, Solver *solver, long maxNSteps); virtual ~DefaultRolloutGenerator() = default; _NO_COPY_OR_MOVE(DefaultRolloutGenerator); virtual Model::StepResult getStep(HistoryEntry const *entry, State const *state, HistoricalData const *data, Action *action=nullptr) override; private: /** The associated model, which will be queried to generate steps. */ Model *model_; /** The maximum # of steps to take. */ long maxNSteps_; /** The number of steps taken so far. */ long currentNSteps_; }; /** A factory class to create instances of DefaultRolloutGenerator. */ class DefaultRolloutFactory: public StepGeneratorFactory { public: /** Creates a new rollout factory with the given solver, and the given max # of steps. */ DefaultRolloutFactory(Solver *solver, long maxNSteps); virtual ~DefaultRolloutFactory() = default; _NO_COPY_OR_MOVE(DefaultRolloutFactory); virtual std::unique_ptr<StepGenerator> createGenerator(SearchStatus &status, HistoryEntry const *entry, State const *state, HistoricalData const *data) override; private: /** The associated solver. */ Solver *solver_; /** The maximum number of steps to take in a rollout. */ long maxNSteps_; }; } /* namespace abt */ #endif /* SOLVER_DEFAULTROLLOUTSTRATEGY_HPP_ */
[ "hoergems@gmail.com" ]
hoergems@gmail.com
62003dfa78b264643c3a74e7fe8be7ad2f1843e0
c26d325bca488b2f071f15e7dd09a54a7bba2cf2
/Task 2/tsepov_artyom.cpp
aee2d118cea63e6b4dbb14ce24ac660db052d597
[]
no_license
devmentality/cpp-ft201-2019
ef8388b77dbfb5dee0fab7e4ec64b22b56d11ee8
6529edf9ee2dfa121ab76a9e2727d1f4df71cacc
refs/heads/master
2020-05-06T13:34:32.272691
2019-05-26T10:01:42
2019-05-26T10:01:42
180,143,869
0
1
null
2019-04-09T17:02:19
2019-04-08T12:25:49
C++
UTF-8
C++
false
false
7,743
cpp
#pragma comment(linker, "/STACK:16777216") #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> #include <algorithm> #include <map> #include <set> #include <string> #include <queue> #include <unordered_map> #include <cmath> #include <iterator> #include <stack> #include <unordered_set> #include <bitset> #include <climits> using namespace std; struct Block { bool free; char depth; Block *prev; Block *next; }; class LinkedList { public: Block * head; char currentDepth; LinkedList(int depth) { head = NULL; currentDepth = depth; } void Add(Block *block) { if (head == NULL) //if empty list { block->prev = block; block->next = block; head = block; return; } Block *start = head; size_t block_position = (size_t)block; while (1) //find first position after block { size_t position = (size_t)start; if (position > block_position) break; start = start->next; if (start == head) //if position after last element break; } Block *insert = start->prev; //get position to insert insert->next = block; block->prev = insert; start->prev = block; block->next = start; if (start == head) //if add before head then change head to block head = block; } void Remove(Block *block) { if (block == block->prev) //if one element { block->next = NULL; block->prev = NULL; head = NULL; return; } Block *prev = block->prev; Block *next = block->next; prev->next = next; next->prev = prev; if (block == head) //if block is head element, then change head to next head = head->next; } }; const int MAXI_POW = 16; const int MIN_POW = 4; class Allocator { private: size_t size; void * memory; LinkedList ** lists; size_t MAX_POW; public: Allocator(size_t _size) { if (_size > MAXI_POW) throw "Too big size"; if (_size < MIN_POW) throw "Too small size"; MAX_POW = _size; size = 1 << _size; memory = malloc(size); int len = MAX_POW - MIN_POW + 1; lists = new LinkedList*[len]; for (size_t i = 0; i < len; i++) lists[i] = new LinkedList(MIN_POW + i); Block *first = (Block*)memory; first->free = true; first->depth = MAX_POW; lists[len - 1]->Add(first); } void* Alloc(size_t _size) { size_t blockSize = 1 << MIN_POW; for (size_t i = 0; i < MAX_POW - MIN_POW + 1; i++) //go from min to max size { if (blockSize < _size + sizeof(Block)) //find first good blockSize { blockSize *= 2; continue; } if (lists[i]->head == NULL) //check the existence of block { blockSize *= 2; continue; } Block* goodBlock = lists[i]->head; size_t curSize = (1 << (goodBlock->depth)) / 2; while (curSize >= _size + sizeof(Block)) //if can split on 2 part(size / 2 > current) { lists[goodBlock->depth - MIN_POW]->Remove(goodBlock); //remove current block and add 2 parts Block* secondBlock = (Block*)(size_t(goodBlock) + curSize); secondBlock->free = true; secondBlock->depth = goodBlock->depth - 1; goodBlock->depth--; lists[secondBlock->depth - MIN_POW]->Add(goodBlock); lists[secondBlock->depth - MIN_POW]->Add(secondBlock); curSize /= 2; } goodBlock->free = false; lists[goodBlock->depth - MIN_POW]->Remove(goodBlock); return goodBlock; } throw "Not enough memory for this block"; } void Free(void *ptr) { size_t start = (size_t)ptr; Block* del = (Block*)start; size_t delSize = 1 << del->depth; del->free = true; lists[del->depth - MIN_POW]->Add(del); while (del->depth < MAX_POW) //go up, while can union 2 parts { size_t change = size_t(del) - size_t(memory); bool leftElement = true; if (change / delSize % 2 == 1) leftElement = false; Block *left = del, *right = (Block*)(size_t(del) + delSize); if (!leftElement) { left = (Block*)(size_t(del) - delSize); right = del; } if (!(left->free && right->free && (left->depth == right->depth))) //if not can union break; lists[left->depth - MIN_POW]->Remove(left); lists[right->depth - MIN_POW]->Remove(right); left->depth++; lists[left->depth - MIN_POW]->Add(left); del = left; delSize *= 2; } } void Show() { for (int i = MIN_POW; i <= MAX_POW; i++) { cout << "Depth=" << i << ": "; if (lists[i - MIN_POW]->head == NULL) { cout << "empty\n"; continue; } auto start = lists[i - MIN_POW]->head; cout << size_t(start) - size_t(memory) << " "; start = start->next; while (start != lists[i - MIN_POW]->head) { cout << size_t(start) - size_t(memory) << " "; //print offset from start position start = start->next; } cout << "\n"; } } }; void TestOneBigBlock() { cout << "------------------------------------\n"; cout << "START TestOneBigBlock\n"; Allocator alloc(10); //2^10 alloc.Alloc(700); alloc.Show(); //all empty, no free memory cout << "END TestOneBigBlock\n"; cout << "------------------------------------\n\n"; } void TestAllocAndFree() //In the end one free block { cout << "------------------------------------\n"; cout << "START TestAllocAndFree\n"; Allocator alloc(10); auto elem = alloc.Alloc(500); alloc.Free(elem); alloc.Show(); cout << "END TestAllocAndFree\n"; cout << "------------------------------------\n\n"; } void TestAllocAllMemory() //Check that can fill all memory { cout << "------------------------------------\n"; cout << "START TestAllocAllMemory\n"; Allocator alloc(10); for (int i = 0; i < 8; i++) { alloc.Alloc(128 - sizeof(Block)); } alloc.Show(); cout << "END TestAllocAllMemory\n"; cout << "------------------------------------\n\n"; } void TestAllocManyBlocksThenFreeOne() { cout << "------------------------------------\n"; cout << "START TestAllocManyBlocksThenFreeOne\n"; Allocator alloc(10); alloc.Alloc((1 << 4) - sizeof(Block)); alloc.Alloc((1 << 5) - sizeof(Block)); alloc.Alloc((1 << 6) - sizeof(Block)); auto t = alloc.Alloc((1 << 7) - sizeof(Block)); alloc.Alloc((1 << 8) - sizeof(Block)); alloc.Free(t); alloc.Show(); cout << "END TestAllocManyBlocksThenFreeOne\n"; cout << "------------------------------------\n\n"; } void TestTooBigAlloc() { cout << "------------------------------------\n"; cout << "START TestTooBigAlloc\n"; Allocator alloc(10); try { alloc.Alloc(2000); } catch (char* a) { cout << a << "\n"; } //alloc.Show(); cout << "END TestTooBigAlloc\n"; cout << "------------------------------------\n\n"; } void TestTooBigAllocator() { cout << "------------------------------------\n"; cout << "START TestTooBigAllocator\n"; try { Allocator alloc(50); } catch (char* a) { cout << a << "\n"; } //alloc.Show(); cout << "END TestTooBigAllocator\n"; cout << "------------------------------------\n\n"; } void TestTooSmallAllocator() { cout << "------------------------------------\n"; cout << "START TestTooSmallAllocator\n"; try { Allocator alloc(1); } catch (char* a) { cout << a << "\n"; } //alloc.Show(); cout << "END TestTooSmallAllocator\n"; cout << "------------------------------------\n\n"; } void TestRandomAllocThenFreeAll() { cout << "------------------------------------\n"; cout << "START TestRandomAllocThenFreeAll\n"; Allocator alloc(10); vector<void*> all; for (int i = 0; i < 10; i++) { auto t = alloc.Alloc(((rand() % 50) + 50) % 50 + 16); all.push_back(t); } for (auto e : all) { alloc.Free(e); } alloc.Show(); cout << "END TestRandomAllocThenFreeAll\n"; cout << "------------------------------------\n\n"; } int main() { TestOneBigBlock(); TestAllocAndFree(); TestAllocAllMemory(); TestAllocManyBlocksThenFreeOne(); TestTooBigAlloc(); TestTooBigAllocator(); TestTooSmallAllocator(); TestRandomAllocThenFreeAll(); return 0; }
[ "noreply@github.com" ]
devmentality.noreply@github.com
edab6035371f367c4fb96b931d598b68f4d4b4a0
c0b2abf06ea0daebf3cd29c58b0f999255dc200a
/algorithm_toolbox/wk2/2/fractional_knapsack/fractional_knapsack.cpp
397a34e13e0517627b9faf40112bc53c1a6a4b2a
[]
no_license
moyuanhuang/coursera_algorithm_design_cse202
9c599eb3b058c6cf2daf7b402dfa0d4596deaf55
240b12c0ee21eafb6c9f738a31f81ce1837fc88d
refs/heads/master
2021-01-20T06:52:29.335001
2017-03-19T04:34:43
2017-03-19T04:34:43
82,598,418
0
0
null
null
null
null
UTF-8
C++
false
false
1,296
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool cmp(pair<long long, long long> p1, pair<long long, long long> p2){ double vpw1 = (double)p1.first/(double)p1.second; double vpw2 = (double)p2.first/(double)p2.second; return vpw1 > vpw2; } double get_optimal_value(long long capacity, vector<long long> weights, vector<long long> values) { double value = 0.0; // write your code here vector<pair<long long, long long> > vpw(weights.size()); for(int i = 0; i < vpw.size(); i++){ vpw[i] = make_pair(values[i],weights[i]); } sort(vpw.begin(), vpw.end(), cmp); for(pair<long long, long long> p: vpw){ if(capacity >= p.second) { value += p.first; capacity -= p.second; } else{ double unit = double(p.first)/double(p.second); value += unit * capacity; capacity = 0; } if(capacity == 0) break; } return value; } int main() { int n; long long capacity; std::cin >> n >> capacity; vector<long long> values(n); vector<long long> weights(n); for (int i = 0; i < n; i++) { std::cin >> values[i] >> weights[i]; } double optimal_value = get_optimal_value(capacity, weights, values); std::cout.precision(10); std::cout << optimal_value << std::endl; return 0; }
[ "moyuanhuang@gmail.com" ]
moyuanhuang@gmail.com
e05ee6489ff6402df8ebc750511456b676fd48d2
16b14cf2eb43ed536634fda93d5ff6b98aa759eb
/PA7/Menu_testing/include/graphics.h
8cf5b7a15383fc4cdde9a0b6cd750cf55bb00f10
[]
no_license
franklandorian/cs480Haymore
f517c6453430d43758901c8dfcd1d09dfc8f24ee
e781b3f6c838e3b89bc01410243a57a009dd0dc3
refs/heads/master
2020-07-14T21:03:20.676344
2020-01-03T00:27:17
2020-01-03T00:27:17
205,401,867
0
0
null
null
null
null
UTF-8
C++
false
false
753
h
#ifndef GRAPHICS_H #define GRAPHICS_H #define GLM_ENABLE_EXPERIMENTAL #include <iostream> using namespace std; #include "graphics_headers.h" #include "camera.h" #include "shader.h" #include "object.h" class Graphics { public: Graphics(); Graphics(string vShader, string fShader); ~Graphics(); bool Initialize(int width, int height); void Update(unsigned int dt, int keyValue); void Render(); private: std::string ErrorString(GLenum error); Camera *m_camera; Shader *m_shader; GLint m_projectionMatrix; GLint m_viewMatrix; GLint m_modelMatrix; Object *m_cube; // String variables to pass in to the Shader object std::string m_Vertex; std::string m_Fragment; }; #endif /* GRAPHICS_H */
[ "ikuznetsov@nevada.unr.edu" ]
ikuznetsov@nevada.unr.edu
de18fba727f3c5786a1d5791491c4fc89f1cf866
af71799a53c07e13f2f4c323391c77364c2b48c7
/libraries/Ticker/examples/Blinker/Blinker.ino
ffefa76f3c29bebc4fe168fd591527f33d1cc8f4
[]
no_license
phillipsback/A71
e200ec8e96d9f7c5861d4f9fbf102f9a27b15372
b0d6b279f26f7e277b45d3c51aa76b397db455bc
refs/heads/master
2023-07-28T09:06:44.932093
2021-04-30T01:45:18
2021-04-30T01:45:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
805
ino
#include <Arduino.h> #include <Ticker.h> // attach a LED to pPIO 13 #define LED_PIN 13 Ticker blinker(TIMER0); Ticker toggler(TIMER1); Ticker changer(TIMER2); float blinkerPace = 0.1; //seconds const float togglePeriod = 5; //seconds void change() { blinkerPace = 0.5; } void blink() { digitalWrite(LED_PIN, !digitalRead(LED_PIN)); } void toggle() { static bool isBlinking = false; if (isBlinking) { blinker.detach(); isBlinking = false; } else { blinker.attach(blinkerPace, blink); isBlinking = true; } digitalWrite(LED_PIN, LOW); //make sure LED on on after toggling (pin LOW = led ON) } void setup() { pinMode(LED_PIN, OUTPUT); toggler.attach(togglePeriod, toggle); changer.once(30, change); } void loop() { }
[ "qitas@qitas.cn" ]
qitas@qitas.cn
3842098d4ede340bdc0b03e2102b70c6a3ecc65a
8a1302c7f69db619ec871375635dc264fd3e3dbb
/src/components/store/hstore/src/hstore_kv_types.h
5e306eb27ecd9cb072426567d9be8e95b3a748c3
[ "Apache-2.0" ]
permissive
Bhaskers-Blu-Org1/mcas
5a1f65178d2e71f8dd90a388ac7fc7f95f6cd0fe
5abab4d9682f099e55e352ec3e0b78577ee5087f
refs/heads/master
2022-04-15T21:03:44.594501
2020-04-03T22:26:43
2020-04-03T22:26:43
275,845,938
0
1
NOASSERTION
2020-06-29T14:53:57
2020-06-29T14:53:56
null
UTF-8
C++
false
false
1,337
h
/* Copyright [2017-2020] [IBM 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. */ #ifndef MCAS_HSTORE_KV_TYPES_H_ #define MCAS_HSTORE_KV_TYPES_H_ #include "hstore_config.h" #include "persist_fixed_string.h" #include <api/kvstore_itf.h> #include <common/utils.h> /* epoch_now */ #include <tuple> namespace impl { inline tsc_time_t epoch_to_tsc(epoch_time_t e) { return e; } inline epoch_time_t tsc_to_epoch(tsc_time_t t) { return t; } inline tsc_time_t tsc_now() { return epoch_to_tsc(epoch_now()); } } template <typename Deallocator> struct hstore_kv_types { using dealloc_t = Deallocator; using key_t = persist_fixed_string<char, 24, dealloc_t>; using mapped_t = std::tuple< persist_fixed_string<char, 24, dealloc_t> #if ENABLE_TIMESTAMPS , tsc_time_t #endif >; }; #endif
[ "daniel.waddington@acm.org" ]
daniel.waddington@acm.org
33485cf338e363a5aa21cf0684fcf9759e5d5383
2110f57f842379f05c0bee73bbca2f6d35b66d78
/_1026.ino
c6a44f4427dae07062fb4c4605916a2140789880
[]
no_license
kutmicro2017/2014136019
4df6bea7b0df2e11d83c6971451c767cefb5e2a7
86287edb9d534f2eac6594249f4f498a966f7cc3
refs/heads/master
2021-05-16T09:42:33.441726
2017-12-12T06:21:49
2017-12-12T06:21:49
104,576,638
0
0
null
null
null
null
UTF-8
C++
false
false
12,358
ino
// 시간 관련 상수 #define GREEN_DELAY 10 // 초록불 지속 시간(s) #define BLINK_COUNT 3 // 노란불 점멸 횟수 #define GREEN_TO_YELLOW 1 // 버튼을 누르고 노란불이 켜질 때까지의 시간(s) #define RED_DELAY 5 // 보행자 버튼 지속 시간(s) // 차량 신호등 // 상하 -> 좌우 방향으로 반복 // 1차 배열: { 상(i = 0), 좌(i = 1), 하(i = 0), 우(i = 0) } // 2차 배열: { 빨간불, 노란불, 초록불 } int LED[4][3] = { { 22, 24, 26 }, { 23, 25, 27 }, { 28, 30, 32 }, { 29, 31, 33 } }; int buttonUD = 9; // 보행자 버튼(상하) int buttonLR = 8; // 보행자 버튼(좌우) volatile bool stateUD = true; // 보행자 버튼(상하) 상태(true : 버튼을 누르지 않은 상태) volatile bool stateLR = true; // 보행자 버튼(좌우) 상태(true : 버튼을 누르지 않은 상태) // 보행자 신호등 // 8x8 도트 매트릭스 핀 번호 정의 int uCol[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; // 열(정지 신호) int uRow[] = { 21, 20, 19, 18, 17, 16, 15, 14 }; // 행(정지 신호) int dCol[] = { 34, 36, 38, 40, 42, 44, 46, 48}; // 열(통행 신호) int dRow[] = { 35, 37, 39, 41, 43, 45, 47, 49 }; // 행(통행 신호) // 잔여 시간 타이머 int remainingTime[10][8][4] = { { // 0 { 1, 1, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }, { // 1 { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }, { // 2 { 1, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0}, { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }, { // 3 { 1, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }, { // 4 { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }, { // 5 { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }, { // 6 { 1, 1, 1, 0 }, { 1, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }, { // 7 { 1, 1, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }, { // 8 { 1, 1, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } }, { // 9 { 1, 1, 1, 0 }, { 1, 0, 1, 0 }, { 1, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 }, { 0, 0, 0, 0 } } }; // 보행자 신호 패턴 int pattern[2][8][8] = { { // STOP {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 1, 1, 0, 0, 1}, {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 0} }, { // PASS {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 0, 1, 0, 0, 0}, {1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 1, 0, 0, 1}, {0, 0, 0, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 0, 1, 1, 0} } }; // 사전 설정 void setup() { // LED의 출력 모드 설정 for(int i = 0; i < 4; i++) { for(int j = 0; j < 3; j++) pinMode(LED[i][j], OUTPUT); } // 스위치의 입력 모드 설정 // 그냥 INPUT을 사용할 경우 스위치가 계속해서 눌러지는 상태가 되므로 한 번만 눌러도 동작이 가능한 INPUT_PULLUP을 사용 pinMode(buttonUD, INPUT_PULLUP); pinMode(buttonLR, INPUT_PULLUP); // 도트 매트릭스 출력 모드 설정 for(int i = 0; i < 8; i++) { pinMode(uRow[i], OUTPUT); pinMode(uCol[i], OUTPUT); pinMode(dRow[i], OUTPUT); pinMode(dCol[i], OUTPUT); } // 모든 LED의 빨간신호가 켜짐 for(int i = 0; i < 4; i++) digitalWrite(LED[i][0], HIGH); } // 루프 void loop() { for(int i = 0; i < 2; i++) { // 신호등 빨간신호 꺼짐 digitalWrite(LED[i][0], LOW); digitalWrite(LED[i + 2][0], LOW); // 신호등 초록신호 켜짐 digitalWrite(LED[i][2], HIGH); digitalWrite(LED[i + 2][2], HIGH); // 초록신호가 켜진 상태에서 아래 함수를 이용하여 스위치 동작 확인 buttonInterrrupt(GREEN_DELAY); // 신호등 초록신호 꺼짐 digitalWrite(LED[i][2], LOW); digitalWrite(LED[i + 2][2], LOW); // 신호등 노랑신호 켜짐 yellowBlink(i); // 신호등 빨간신호 켜짐(그 다음 LED로 넘어감) digitalWrite(LED[i][0], HIGH); digitalWrite(LED[i + 2][0], HIGH); } } // 신호등 노랑신호 점멸 함수(0.5초 켜졌다 0.5초 꺼짐) void yellowBlink(int a) { for(int i = BLINK_COUNT; i > 0 ; i--) { digitalWrite(LED[a][1], HIGH); // 노란불 켜짐 digitalWrite(LED[a + 2][1], HIGH); for(int j = 0; j < 25; j++) { // =delay(500) (각 함수가 10ms씩 걸리므로 20 * 25 = 500) displaySignal(a); // 보행자 신호 패턴 표시 displayTime(a, i); // 잔여 시간 표시 } digitalWrite(LED[a][1], LOW); // 노란불 꺼짐 digitalWrite(LED[a + 2][1], LOW); for(int j = 0; j < 25; j++) { // 위와 동일 displaySignal(a); displayTime(a, i); } } } // LED가 초록불인지 확인 후 해당 인덱스를 반환하는 함수 int check() { for(int i = 0; i < 2; i++) { if(digitalRead(LED[i][2]) == HIGH && digitalRead(LED[i + 2][2]) == HIGH) return i; } } // ms 단위로 스위치가 눌렸는지 확인하는 함수 // polling 방법을 이용하므로 계속해서 확인을 해주어야함 // 만약 스위치를 눌렀다는 것을 확인하면 동작하고 있는 신호등의 초록불은 꺼지고 노란불이 깜빡거리며 빨간불로 바뀜 void buttonInterrrupt(int t) { for(int i = t * 50; i > 0; i--) { if(isPushUD() == false) { // 보행자 버튼(상하) 누른 경우 if(check() == 1) changeLight(check()); // 좌우 신호등이 초록불일 때 상하 신호등과 좌우 신호등의 신호 바꾸기 i = t * 50; // 상하 신호등 초록불 지속시간 초기화 stateUD = true; } if(isPushLR() == false) { // 보행자 버튼(좌우) 누른 경우 if(check() == 0) changeLight(check()); // 상하 신호등이 초록불일 때 좌우 신호등과 상하 신호등의 신호 바꾸기 i = t * 50; // 좌우 신호등 초록불 지속시간 초기화 stateLR = true; } displaySignal(check()); // 보행자 신호 패턴 표시 displayTime(check(), (i / 50) + BLINK_COUNT + 1); // 잔여 시간 표시(초록불 지속 시간 + 노란불 지속 시간 + 1초(0초가 되자마자 체인지하기 위해)) } } // 버튼이 눌렸을 경우 불빛이 바뀌는 절차를 구현한 함수 void changeLight(int a) { for(int i = GREEN_TO_YELLOW * 50; i > 0; i--) { // =delay(GREEN_TO_YELLOW * 1000) displaySignal(a); displayTime(a, i / 50 + 4); } digitalWrite(LED[a][2], LOW); // 초록불 꺼짐 digitalWrite(LED[a + 2][2], LOW); yellowBlink(a); // 노란불 점멸 if(a == 1) a = -1; // 좌우 신호등이 초록불일 때 반대쪽 신호등의 빨간불이 꺼지도록 매개변수 값 임시 설정 digitalWrite(LED[a + 1][0], LOW); // 반대쪽 신호등 빨간불 꺼짐 digitalWrite(LED[a + 3][0], LOW); digitalWrite(LED[a + 1][2], HIGH); // 반대쪽 신호등 초록불 켜짐 digitalWrite(LED[a + 3][2], HIGH); if(a == -1) a = 1; // 매개변수 값 복귀 digitalWrite(LED[a][0], HIGH); // 빨간불 켜짐 digitalWrite(LED[a + 2][0], HIGH); for(int i = RED_DELAY * 50; i > 0; i--) { // =delay(RED_DELAY * 1000) displaySignal(!a); // 보행자 신호등의 패턴과 잔여 시간을 반대로 표시(0 <-> 1) displayTime(!a, i / 50 + BLINK_COUNT + 1); } if(a == 1) a = -1; // 좌우 신호등이 초록불일 때 반대쪽 신호등의 빨간불이 꺼지도록 매개변수 값 임시 설정 digitalWrite(LED[a + 1][2], LOW); // 반대쪽 신호등 초록불 꺼짐 digitalWrite(LED[a + 3][2], LOW); yellowBlink(a + 1); // 노란불 점멸 digitalWrite(LED[a + 1][0], HIGH); // 반대쪽 신호등 빨간불 켜짐 digitalWrite(LED[a + 3][0], HIGH); if(a == -1) a = 1; // 매개변수 값 복귀 digitalWrite(LED[a][0], LOW); // 빨간불 꺼짐 digitalWrite(LED[a + 2][0], LOW); digitalWrite(LED[a][2], HIGH); // 초록불 켜짐 digitalWrite(LED[a + 2][2], HIGH); } // 단순히 스위치를 눌렀을 때 동작할 수 있는 조건(스위치를 누르면 false가 반환)을 반환하기 위한 함수 // 스위치를 눌렀을 때를 LOW로 가정하여 상태를 false로 만들어줌 bool isPushUD() { // 보행자 버튼(상하) 상태 if(digitalRead(buttonUD) == LOW) stateUD = false; return stateUD; } bool isPushLR() { // 보행자 버튼(좌우) 상태 if(digitalRead(buttonLR) == LOW) stateLR = false; return stateLR; } // 정지 신호 도트 매트릭스 초기화 void clearStopSign() { for(int k = 0; k < 8; k++) { digitalWrite(uRow[k], LOW); digitalWrite(uCol[k], HIGH); } } // 통행 신호 도트 매트릭스 초기화 void clearPassSign() { for(int k = 0; k < 8; k++) { digitalWrite(dRow[k], LOW); digitalWrite(dCol[k], HIGH); } } // 보행자 정지/통행 신호 표시(10ms) (매개변수 i = 상하(0) or 좌우(1)) void displaySignal(int i) { for(int r = 0; r < 8; r++) { if(i == 1) { // 좌우 신호등이 초록불일 때 clearStopSign(); // 보행자 정지 신호등에 정지 패턴 출력 digitalWrite(uRow[r], HIGH); for(int c = 0; c < 8; c++) if(pattern[0][r][c]) digitalWrite(uCol[c], LOW); } else { // 상하 신호등이 초록불일 때 clearPassSign(); // 보행자 통행 신호등에 통행 패턴 출력 digitalWrite(dRow[r], HIGH); for(int c = 0; c < 8; c++) if(pattern[1][r][c]) digitalWrite(dCol[c], LOW); } delay(1); // 1초 딜레이를 유지함으로써 출력이 제대로 되도록 함 } delay(2); clearStopSign(); clearPassSign(); } // 잔여 시간 표시(10ms) (매개변수 i = 상하(0) or 좌우(1), t = 초) void displayTime(int i, int t) { for(int r = 0; r < 8; r++) { if(i == 0) { // 상하 신호등이 초록불일 때 clearStopSign(); // 보행자 정지 신호등에 잔여 시간 표시 digitalWrite(uRow[r], HIGH); for(int c = 0; c < 4; c++) { if(remainingTime[t / 10][r][c]) digitalWrite(uCol[c], LOW); // 십의 자리 출력 if(remainingTime[t % 10][r][c]) digitalWrite(uCol[c + 4], LOW); // 일의 자리 출력 } } else { // 좌우 신호등이 초록불일 때 clearPassSign(); // 보행자 통행 신호등에 잔여 시간 표시 digitalWrite(dRow[r], HIGH); for(int c = 0; c < 4; c++) { if(remainingTime[t / 10][r][c]) digitalWrite(dCol[c], LOW); // 십의 자리 출력 if(remainingTime[t % 10][r][c]) digitalWrite(dCol[c + 4], LOW); // 일의 자리 출력 } } delay(1); } delay(2); clearStopSign(); clearPassSign(); }
[ "noreply@github.com" ]
kutmicro2017.noreply@github.com
afed862d544630b793d1be0a96ff59b6d2f36ee8
c351647722914caa93b18aed09354455c0afee8e
/Swift-Interoperability/CPlusPlusLinkage.cpp
f3ca3cfe8a940f0803d8cab9cb5a0f588fe49137
[ "MIT" ]
permissive
CoronaCards/sample-ios-ChildView-swift
b425a23d839543d4909de37f85c3d6cbb469f5d5
e61e07407a46ddee28a9ba10b1dd11810a69bd32
refs/heads/master
2020-04-16T15:41:41.836605
2017-04-07T20:04:31
2017-04-07T20:04:31
27,197,236
2
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
// // CPlusPlusLinkage.cpp // ChildView-swift // // Copyright (c) 2014 Corona Labs Inc. All rights reserved. // // NOTE: Swift projects do not normally have C++ code. // Compiling this empty stub file ensures that Xcode links in C++ libraries // which are required by CoronaCards.framework.
[ "walterlua@coronalabs.com" ]
walterlua@coronalabs.com
9927e8bcae0731ca1995c86416f88ef357fe137c
5ef1f4a690f96741c00e2afb0a3aa7327bd5e67e
/Server/Source.cpp
c84a28101f95ee24aa5fd5b264eb468e049ef824
[]
no_license
darienmiller88/GUI-Chat
725c8226329aeeeb5714fce90601eea123db1b6f
8cb9dcbc56e9738796ed26069bf8e67aea7c0c41
refs/heads/master
2021-01-01T11:44:20.219650
2020-02-09T07:33:43
2020-02-09T07:33:43
239,264,380
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include <iostream> #include <SFML/Graphics.hpp> #include "Server.h" using namespace sf; int main() { constexpr uint16_t PORT = 2000; Server server(PORT); server.runServer(); }
[ "noreply@github.com" ]
darienmiller88.noreply@github.com
b0779209b334c916f6c62df4a89eaf5b6acacbe9
2c10a546a1061131a03f6f974119263ff3e79f39
/FFX_Dodger/FFX_Dodger.ino
7b39af1d5a3cb6dcf3569902e14e92da4b4e3895
[]
no_license
Elstinko/FFXLightningDodger
94695485b05dec3710ce08c1f26798de3a127243
e315c850ecfd3ac297e97634074e73a3f9d22134
refs/heads/master
2020-06-05T09:39:35.230205
2019-06-17T20:22:40
2019-06-17T20:22:40
192,395,721
1
0
null
null
null
null
UTF-8
C++
false
false
1,659
ino
// PhotoResistor (LDR) on pin A0 // Servo on pin 9 #include <Servo.h> Servo servo1; const int lightPin = A0; // LDR Pin const int servoPin = 9; // Servo Pin int angle = 0; // Servo Angle int servoMove = 70; // The amount the servo moves in degrees int count = 0; // Counts number of dodges // Begin serial communication with a computer if one is plugged in via USB // Then links Servo Pin to Servo Object void setup() { Serial.begin(9600); servo1.attach(servoPin); } // Main program loop void loop() { //This line is used for calibrating the arduino to your tv //It will print to your computer the current light level reading off of the LDR sensor //You can delete this line once you calibrate your code so you can see the dodge counter more easily Serial.println(analogRead(lightPin)); //Slight delay prevents the servo from trying to dodge the same lightning strike twice delay(200); // Checks to see if lightning has flashed // The "400" is the number you will need to change that will trigger the servo to dodge in the game if(analogRead(lightPin) >= 400){ // The next two lines provide a counter of the number of lightning bolts currently dodged if you have the Arduino plugged into a PC count++; Serial.println(count); // Moves servo 70 degrees to press x button for (angle = 0; angle <= servoMove; angle += 10) { servo1.write(angle); delay(30); } // Moves servo 70 degrees back to its original position for (angle = servoMove; angle <= 0; angle -= 10) { servo1.write(angle); delay(30); } } }
[ "noreply@github.com" ]
Elstinko.noreply@github.com
5264661f7b32c373124dda1acd11499dc55697c2
c65da772244d12dd64b96a23842ca416915a875f
/components/launch_process_test_server.cpp
10a3f12c52a60ac7c6d044b172af7d9e0d251908
[]
no_license
akheir/launch_process
76934862f2f86a804fc50e07bde505b4e3ba8fd5
db88e4688768a7bc0da906dafa6176f371a20da5
refs/heads/master
2021-08-08T06:50:49.178304
2017-11-09T19:34:41
2017-11-09T19:34:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
cpp
// Copyright (c) 2016 Hartmut Kaiser // // 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) #include <hpx/include/actions.hpp> #include <hpx/include/components.hpp> #include <components/launch_process_test_server.hpp> /////////////////////////////////////////////////////////////////////////////// // Test-component which is instantiated by the launching process and registered // with AGAS such that the launched process can use it. HPX_REGISTER_ACTION(launch_process_get_message_action); HPX_REGISTER_ACTION(launch_process_set_message_action); HPX_REGISTER_COMPONENT_MODULE(); /////////////////////////////////////////////////////////////////////////////// // We use a special component registry for this component as it has to be // disabled by default. All tests requiring this component to be active will // enable it explicitly. typedef hpx::components::component<launch_process::test_server> server_type; HPX_REGISTER_DISABLED_COMPONENT_FACTORY(server_type, launch_process_test_server)
[ "kheirkhahan@gmail.com" ]
kheirkhahan@gmail.com
b8c2974f034ba52e5b5cf96adb4fc4f64cae03a1
d51d6d76cb481c7e4cfc03c7934c4f34f214544b
/modules/task_2/METHOD_GAUSS_NADIR/main.cpp
0ed8b0ea80ffdc294aca223ae1240ad3140fef52
[ "BSD-3-Clause" ]
permissive
drwff/pp_2020_autumn_informatics
04cc496b9b639e6139d78dfbe7a35877ed0d506c
6205735ad7b3b65a66e43a6d53c7b4dacd5815c4
refs/heads/master
2023-01-24T13:51:18.455724
2020-12-05T12:37:38
2020-12-05T12:37:38
305,469,621
1
0
BSD-3-Clause
2020-12-05T12:37:40
2020-10-19T17:56:03
C++
UTF-8
C++
false
false
2,459
cpp
// Copyright 2020 Nadir mohammed #include <gtest-mpi-listener.hpp> #include <gtest/gtest.h> #include<mpi.h> #include<vector> #include "./Methodgauss.h" TEST(GAUSS_PARALLEL_MPI, 2x3) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int row = 2, col = 3; double* array1{ new double[row * col]{ 1, 2, 3, 4, 5, 6 } }; double* sub_solution1 = new double[row]; methodGaussParallel(array1, sub_solution1, row, col); //************************************** std::vector<std::vector<double>> array2{ {1, 2, 3} , {4, 5, 6} }; double* sub_solution2 = new double[row]; methodGauss(array2, sub_solution2, row); if (rank == 0) { for (int i = 0; i < row; i++) { ASSERT_NEAR(sub_solution1[i], sub_solution2[i], 0.00001); } } delete[] array1; delete[] sub_solution1; } TEST(GAUSS_PARALLEL_MPI, 3x4) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int row = 3, col = 4; double* array1{ new double[row * col]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } }; double* sub_solution1 = new double[row]; methodGaussParallel(array1, sub_solution1, row, col); //************************************** std::vector<std::vector<double>> array2{ {1, 2, 3, 4} , {5, 6, 7, 8} , {9, 10, 11, 12} }; double* sub_solution2 = new double[row]; methodGauss(array2, sub_solution2, row); if (rank == 0) { for (int i = 0; i < row; i++) { for (int i = 0; i < row; i++) { ASSERT_NEAR(sub_solution1[i], sub_solution2[i], 0.00001); } } delete[] array1; delete[] sub_solution1; } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
[ "63372033+davinci17@users.noreply.github.com" ]
63372033+davinci17@users.noreply.github.com
2156cdc3ad7ef6a7cff3d10b23df592baac3ea61
84897b6a25f876b21246c2c7e1404c9c411be987
/src/include/common/RCBitlDecoder.inl
78791e9c906b52306759e0906ed78c500ee55c2d
[]
no_license
drivestudy/HaoZip
07718a53e38bc5893477575ddf3fccfb3b18c5fd
9e0564b4a11870224543357004653b798fd625e0
refs/heads/master
2021-07-24T06:33:24.651453
2017-11-05T01:19:18
2017-11-05T01:19:18
null
0
0
null
null
null
null
GB18030
C++
false
false
2,717
inl
/******************************************************************************** * 版权所有(C)2008,2009,2010,好压软件工作室,保留所有权利。 * ******************************************************************************** * 作者 : HaoZip * * 版本 : 1.7 * * 联系方式: haozip@gmail.com * * 官方网站: www.haozip.com * ********************************************************************************/ ///////////////////////////////////////////////////////////////// //RCBitlDecoder class implementation BEGIN_NAMESPACE_RCZIP template<class TInByte> RCBitlDecoder<TInByte>::RCBitlDecoder(): m_normalValue(0) { } template<class TInByte> RCBitlDecoder<TInByte>::~RCBitlDecoder() { } template<class TInByte> void RCBitlDecoder<TInByte>::Init() { RCBitlBaseDecoder<TInByte>::Init(); m_normalValue = 0 ; } template<class TInByte> void RCBitlDecoder<TInByte>::Normalize() { for (; this->m_bitPos >= 8; this->m_bitPos -= 8) { byte_t b = 0; if (!this->m_stream.ReadByte(b)) { b = 0xFF; // check it this->m_numExtraBytes++; } m_normalValue = (b << (RCBitlDecoderData::s_kNumBigValueBits - this->m_bitPos)) | m_normalValue; this->m_value = (this->m_value << 8) | RCBitlDefs::Instance().s_kInvertTable[b]; } } template<class TInByte> uint32_t RCBitlDecoder<TInByte>::GetValue(int32_t numBits) { Normalize(); return ((this->m_value >> (8 - this->m_bitPos)) & RCBitlDecoderData::s_kMask) >> (RCBitlDecoderData::s_kNumValueBits - numBits); } template<class TInByte> void RCBitlDecoder<TInByte>::MovePos(int32_t numBits) { this->m_bitPos += numBits; m_normalValue >>= numBits; } template<class TInByte> uint32_t RCBitlDecoder<TInByte>::ReadBits(int32_t numBits) { Normalize(); uint32_t res = m_normalValue & ( (1 << numBits) - 1); MovePos(numBits); return res; } template<class TInByte> void RCBitlDecoder<TInByte>::AlignToByte() { MovePos((32 - this->m_bitPos) & 7) ; } template<class TInByte> byte_t RCBitlDecoder<TInByte>::ReadByte() { if (this->m_bitPos == RCBitlDecoderData::s_kNumBigValueBits) { byte_t b = 0; if (!this->m_stream.ReadByte(b)) { b = 0xFF; this->m_numExtraBytes++; } return b; } { byte_t b = (byte_t)(m_normalValue & 0xFF); MovePos(8); return b ; } } END_NAMESPACE_RCZIP
[ "zhou_jiafeng@aliyun.com" ]
zhou_jiafeng@aliyun.com
94eb87efa014e8aed47258635e66bb49a7aa41af
80b7386a59ef9fbb9b5b0ee1d6477ede59340915
/cf270-140928/源2.cpp
d934266bb38649498456c8184aed11c1bae309fe
[]
no_license
zhangtufei/CodeForces
86e2b7493137da65847ac9d39c95cd689648ec7e
d15e8a1b9e9a359a62a1ee128aef7dd33297c06d
refs/heads/master
2021-01-19T07:16:42.344163
2015-07-01T09:48:16
2015-07-01T09:48:16
38,363,241
0
0
null
null
null
null
UTF-8
C++
false
false
1,154
cpp
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <map> #include <math.h> using namespace std; int main() { int n, k; while (cin >> n) { cin >> k; map<int, int> fl; int temp; for (int i = 1; i <= n; ++i) { cin >> temp; ++fl[temp]; } long long sum = 0; map<int, int>::iterator iter = fl.begin(); for (; iter != fl.end(); ++iter) { while (iter->second >= k) { iter->second -= k; sum += (iter->first-1); } } iter = fl.begin(); int fll[2010]; memset(fll, 0, sizeof(fll)); for (; iter != fl.end(); ++iter) { if (iter->second) { fll[iter->first] = iter->second; } } --iter; int t = iter->first; while (t>=2) { if (fll[t]<=0) { t -= 1; continue; } sum += (t - 1); int temp = k-fll[t]; fll[t] = 0; t -= 1; while (temp - fll[t] >= 0) { if (t<= 2) break; if (!fll[t]) { t-= 1; continue; } temp -= fll[t]; fll[t] = 0; --t; } if (t>=2) fll[t] -= temp; if (t<=2 && fll[2] > 0) { sum += 1; break; } } cout << sum * 2 << endl; } return 0; }
[ "412710370@qq.com" ]
412710370@qq.com
483962b6d7486368c541b2fc62f4069885f74cbc
96c2f55e386ce7b5657a6e69938aff7a7fb3e221
/Plugins/DlgSystem/Source/DlgSystem/Public/IO/IDlgWriter.h
c5b415bd5cc4c5c17c74c23cce609757bb02580d
[ "MIT" ]
permissive
zhyinty/NotYetDlgSystemSample
cdce2c77e0bdeff4a5b95d9d9e615252942e4b76
affc21070bda2330796df39bccd9692217721e7a
refs/heads/master
2020-03-31T17:08:23.080205
2018-10-10T10:55:26
2018-10-10T10:55:26
152,408,302
0
0
null
null
null
null
UTF-8
C++
false
false
3,283
h
// Copyright 2017-2018 Csaba Molnar, Daniel Butum #pragma once #include "UnrealType.h" /** * The writer will ignore properties by default that are marked DEPRECATED or TRANSIENT, see SkipFlags variable. * * Limitations: * - TSet or TMap with the KeyType as float or structures that have floats, this is very bad you should not do this anyways * - limitation for each type you can see inside DlgIoTester.cpp in the Options. * - Having an uninitialized UObject property inside a USTRUCT (https://answers.unrealengine.com/questions/566684/editor-crashes-on-startup-if-uninitialized-uproper.html) * THIS CRASHES THE WRITERS so initialize them with nullptr * * MetaData specifiers: * Unfortunately they only work in editor build * The class can be used in exported game too, but the MetaData specifiers are ignored * * - DlgNoExport: property is skipped - WARNING: should be only used on editor only variables, * in non-editor builds you should use the properties from the SkipFlags * - DlgWriteIndex: used on complex (struct/object) arrays, element index is exported as comment * - DlgLinePerItem: used to force primitive container to write each element into a new line (TODO: MAP SUPPORT) * - DlgSaveOnlyReference: UObject path is serialized instead of UObject (can be used for DataAsset like objects stored in content browser) * ATM IT ONLY WORKS IF IT IS NOT INSIDE A CONTAINER DIRECTLY (can be e.g. inside a struct inside a container tho) * */ class DLGSYSTEM_API IDlgWriter { public: virtual ~IDlgWriter() {} /** Has to be called before ExportToFile in order to have something to write */ virtual void Write(const UStruct* StructDefinition, const void* Object) = 0; virtual bool ExportToFile(const FString& FileName) = 0; virtual const FString& GetAsString() const = 0; /** Can we skip this property from exporting? */ static bool CanSkipProperty(const UProperty* Property) { if (!IsValid(Property)) { return true; } #if WITH_EDITOR if (Property->HasMetaData(TEXT("DlgNoExport"))) { return true; } #endif if (Property->HasAnyPropertyFlags(SkipFlags)) { return true; } return false; } /** Should write one item per line for Property? */ static bool CanWriteOneLinePerItem(const UProperty* Property) { #if WITH_EDITOR return Property->HasMetaData(TEXT("DlgLinePerItem")); #else return false; #endif } /** Should write the index number for Property? */ static bool CanWriteIndex(const UProperty* Property) { #if WITH_EDITOR return Property->HasMetaData(TEXT("DlgWriteIndex")); #else return false; #endif } /** Decides if the path to the object should be serialized, or the object itself */ virtual bool CanSaveAsReference(const UProperty* Property) { // UClass if (Property->IsA<UClassProperty>()) { return true; } #if WITH_EDITOR return Property->HasMetaData(TEXT("DlgSaveOnlyReference")); #else return false; #endif } // bLogVerbose: bool IsLogVerbose() const { return bLogVerbose; } void SetLogVerbose(bool bValue) { bLogVerbose = bValue; } protected: /** The properties with these flags set will be ignored from writing. */ static constexpr int64 SkipFlags = CPF_Deprecated | CPF_Transient; // Should this class verbose log? bool bLogVerbose = false; };
[ "zywgg@icloud.com" ]
zywgg@icloud.com
b40c500062213fdfdb89507b30cc91881744ea1a
8318a1144be4872574ac1ceabd854f836e7362c2
/SFML-2.4.2/include/SFML/Graphics/Glyph.hpp
6ac213eb5cc5872372a7a3d7a447a3a93b3a184c
[]
no_license
ValeryStatinov/Patterns_project
239647f8adf62437acd94e6957f58de9c0173125
be29148e817b8a1fb431174a613ee166fb44f9e1
refs/heads/master
2021-01-25T10:06:28.417815
2018-05-23T01:15:42
2018-05-23T01:15:42
123,339,860
0
0
null
2020-02-16T11:09:14
2018-02-28T20:40:26
C++
UTF-8
C++
false
false
2,751
hpp
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2017 Laurent Gomila (laurent@sfml-dev.org) // // 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 SFML_GLYPH_HPP #define SFML_GLYPH_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include "../Graphics/Export.hpp" #include "../Graphics/Rect.hpp" namespace sf { //////////////////////////////////////////////////////////// /// \brief Structure describing a glyph /// //////////////////////////////////////////////////////////// class SFML_GRAPHICS_API Glyph { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////// Glyph() : advance(0) {} //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// float advance; ///< Offset to move horizontally to the next character FloatRect bounds; ///< Bounding rectangle of the glyph, in coordinates relative to the baseline IntRect textureRect; ///< Texture coordinates of the glyph inside the font's texture }; } // namespace sf #endif // SFML_GLYPH_HPP //////////////////////////////////////////////////////////// /// \class sf::Glyph /// \ingroup graphics /// /// A glyph is the visual representation of a character. /// /// The sf::Glyph structure provides the information needed /// to handle the glyph: /// \li its coordinates in the font's texture /// \li its bounding rectangle /// \li the offset to apply to get the starting position of the next glyph /// /// \see sf::Font /// ////////////////////////////////////////////////////////////
[ "stv1k@stv1k-deb" ]
stv1k@stv1k-deb
fbb604e41afa7bc4de8e77a4c926743bf9310712
34a7f4ea3debd4d501aab16b2d746653317ecf6b
/auto_diff/include/node/Node.h
26ad91c7095d00f8f91a2d1c9ec069020fc8c7bb
[]
no_license
zakheav/machine_learning
06416c7ed4ce5273016093cc578a6fd0a13322fb
ba9f78f9aa5e92e9d60e72f0f10e9c430a24b162
refs/heads/master
2021-01-11T16:09:56.023090
2020-05-17T07:54:48
2020-05-17T07:54:48
80,023,610
1
3
null
null
null
null
UTF-8
C++
false
false
651
h
#ifndef NODE_H_ #define NODE_H_ #include <string> #include <vector> #include "../Tensor.h" /*节点的基类*/ class Node { public: std::string op_name;// 节点名字(全局唯一) std::vector<Node*> parents;// 输入节点 Tensor* output;// 输出 Tensor* sum_grad; int need_update; int end_node; float a;// 学习率 virtual void op ();// 该计算节点的运算函数 virtual void grad_op ();// 该计算节点对于输入的导函数 virtual void update ();// 根据梯度更新 Node (); Node (std::string name); ~Node (); }; #endif
[ "18810543471@163.com" ]
18810543471@163.com
b2ac0417400c40028c6aabfb248bb9976b24889a
756c34ddf5edfa3b11928160750a3136ba286787
/include/occa/lang/type/vartype.hpp
60563b08550a7fc2e82ac557fd43b58a374147f0
[ "MIT" ]
permissive
myfreebrain/occa
4a1ed60852e8eba1dcc9383fea918fb6f8ffc996
ebdb659c804f91f1e0f32fd700f9fe229458033c
refs/heads/master
2020-05-31T07:42:11.238757
2019-05-14T20:44:13
2019-05-14T21:34:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,618
hpp
#ifndef OCCA_LANG_TYPE_VARTYPE_HEADER #define OCCA_LANG_TYPE_VARTYPE_HEADER #include <occa/lang/type/type.hpp> namespace occa { namespace lang { class vartype_t { public: qualifiers_t qualifiers; identifierToken *typeToken; const type_t *type; pointerVector pointers; token_t *referenceToken; arrayVector arrays; int bitfield; vartype_t(); vartype_t(const type_t &type_); vartype_t(const identifierToken &typeToken_, const type_t &type_); vartype_t(const vartype_t &other); ~vartype_t(); vartype_t& operator = (const vartype_t &other); void clear(); bool isValid() const; bool isNamed() const; std::string name() const; fileOrigin origin() const; bool isPointerType() const; void setReferenceToken(token_t *token); bool isReference() const; dtype_t dtype() const; bool operator == (const vartype_t &other) const; bool operator != (const vartype_t &other) const; bool has(const qualifier_t &qualifier) const; vartype_t& operator += (const qualifier_t &qualifier); vartype_t& operator -= (const qualifier_t &qualifier); vartype_t& operator += (const qualifiers_t &qualifiers_); void add(const fileOrigin &origin, const qualifier_t &qualifier); void add(const qualifierWithSource &qualifier); void add(const int index, const fileOrigin &origin, const qualifier_t &qualifier); void add(const int index, const qualifierWithSource &qualifier); vartype_t& operator += (const pointer_t &pointer); vartype_t& operator += (const pointerVector &pointers_); vartype_t& operator += (const array_t &array); vartype_t& operator += (const arrayVector &arrays_); bool hasAttribute(const std::string &attr) const; vartype_t declarationType() const; vartype_t flatten() const; void printDeclaration(printer &pout, const std::string &varName, const bool printType = true) const; void printExtraDeclaration(printer &pout, const std::string &varName) const; void printWarning(const std::string &message) const; void printError(const std::string &message) const; }; io::output& operator << (io::output &out, const vartype_t &type); printer& operator << (printer &pout, const vartype_t &type); } } #endif
[ "dmed256@gmail.com" ]
dmed256@gmail.com
f2bea0389123c937a322a2d966c2cb17fa1394c4
68de3cf64bed153c466de0e0abb90e0cddb499da
/RHeroes/shared/configreader.h
2567ff65d29774173a3ed9b99f3be8bbd7b75d44
[]
no_license
yuyuyu00/Tesi
d2e5610eae0773220256b7641ac36cb2cb78b778
8ecb2f089ec6a6bb9cea79eac679e297ca7d416b
refs/heads/master
2021-01-19T09:37:33.337054
2016-03-09T21:35:18
2016-03-09T21:35:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,562
h
#ifndef CONFIGREADER_H #define CONFIGREADER_H #include <QObject> #include <QFile> namespace Config{ /** * the class implements a reader for the configurations * of the single robots. */ class ConfigReader : public QObject { Q_OBJECT public: /** * Constructor for the ConfigReader. * @param filePath of the configuration file. */ explicit ConfigReader(const QString &filePath, QObject *parent = 0); /** * Destroyer for the class */ virtual ~ConfigReader(); /** * Method that reads the config file and then sets the variable * in the shared configurations. * @return -1 if the file can not be opend; -2 if there's a syntax error. 0 if everything goes right. */ int readFileAndCompileConfigs(); signals: public slots: private: void setVariable(const QString &varName, const QString &varValue); void setVariableString(const QString &varName, const QString &value); void setVariableNumber(const QString &varName, double value); void setSLAMVariable(const QString &varName, const QString &varValue); void setPRMVariable(const QString &varName, const QString &varValue); void setOBSVariable(const QString &varName, const QString &varValue); void convertTo(const QString &strValue, int &value) const; void convertTo(const QString &strValue, double &value) const; QString nameFormat(const QString &name) const; QString filePath; }; } #endif // CONFIGREADER_H
[ "giuseppe.andrea.f@alice.it" ]
giuseppe.andrea.f@alice.it
5e326c4a08817622c31cfd497b5a0121d5847b78
c51febc209233a9160f41913d895415704d2391f
/library/ATF/std__exceptionDetail.hpp
10c2bc0625044926dca8b954a74580343abb879a
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
415
hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <std__exceptionInfo.hpp> START_ATF_NAMESPACE namespace std { namespace Detail { extern ::std::array<hook_record, 5> exception_functions; }; // end namespace Detail }; // end namespace std END_ATF_NAMESPACE
[ "b1ll.cipher@yandex.ru" ]
b1ll.cipher@yandex.ru
8c5b23c9843fa7728cbc7b3c313dddc90a7dc14a
33771f76da1cf363ca014c83599d6fcc73414ab2
/src/wallet/test/coinselector_tests.cpp
152bc74656d60411efb906757960713860973627
[ "MIT" ]
permissive
Quang7hong81/Bitcoin-V
94e215b3c9834f34501d031fdd70990774ccd256
f31543eeff790c544bcd440d9b1e98d7ab337458
refs/heads/master
2023-07-08T16:12:39.032637
2019-03-07T06:12:32
2019-03-07T06:12:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,787
cpp
// Copyright (c) 2017-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/wallet.h> #include <wallet/coinselection.h> #include <wallet/coincontrol.h> #include <amount.h> #include <primitives/transaction.h> #include <random.h> #include <test/test_bitcoin.h> #include <wallet/test/wallet_test_fixture.h> #include <boost/test/unit_test.hpp> #include <random> BOOST_FIXTURE_TEST_SUITE(coinselector_tests, WalletTestingSetup) // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles #define RUN_TESTS 100 // some tests fail 1% of the time due to bad luck. // we repeat those tests this many times and only complain if all iterations of the test fail #define RANDOM_REPEATS 5 std::vector<std::unique_ptr<CWalletTx>> wtxn; typedef std::set<CInputCoin> CoinSet; static std::vector<COutput> vCoins; static CWallet testWallet("dummy", WalletDatabase::CreateDummy()); static CAmount balance = 0; CoinEligibilityFilter filter_standard(1, 6, 0); CoinEligibilityFilter filter_confirmed(1, 1, 0); CoinEligibilityFilter filter_standard_extra(6, 6, 0); CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0); static void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set) { CMutableTransaction tx; tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; set.emplace_back(MakeTransactionRef(tx), nInput); } static void add_coin(const CAmount& nValue, int nInput, CoinSet& set) { CMutableTransaction tx; tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; set.emplace(MakeTransactionRef(tx), nInput); } static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) { balance += nValue; static int nextLockTime = 0; CMutableTransaction tx; tx.nLockTime = nextLockTime++; // so all transactions get different hashes tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; if (fIsFromMe) { // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(), // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe() tx.vin.resize(1); } std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx)))); if (fIsFromMe) { wtx->fDebitCached = true; wtx->nDebitCached = 1; } COutput output(wtx.get(), nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */); vCoins.push_back(output); testWallet.AddToWallet(*wtx.get()); wtxn.emplace_back(std::move(wtx)); } static void empty_wallet(void) { vCoins.clear(); wtxn.clear(); balance = 0; } static bool equal_sets(CoinSet a, CoinSet b) { std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin()); return ret.first == a.end() && ret.second == b.end(); } static CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool) { utxo_pool.clear(); CAmount target = 0; for (int i = 0; i < utxos; ++i) { target += (CAmount)1 << (utxos+i); add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool); add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool); } return target; } inline std::vector<OutputGroup>& GroupCoins(const std::vector<CInputCoin>& coins) { static std::vector<OutputGroup> static_groups; static_groups.clear(); for (auto& coin : coins) static_groups.emplace_back(coin, 0, true, 0, 0); return static_groups; } inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& coins) { static std::vector<OutputGroup> static_groups; static_groups.clear(); for (auto& coin : coins) static_groups.emplace_back(coin.GetInputCoin(), coin.nDepth, coin.tx->fDebitCached && coin.tx->nDebitCached == 1 /* HACK: we can't figure out the is_me flag so we use the conditions defined above; perhaps set safe to false for !fIsFromMe in add_coin() */, 0, 0); return static_groups; } // Branch and bound coin selection tests BOOST_AUTO_TEST_CASE(bnb_search_test) { LOCK(testWallet.cs_wallet); // Setup std::vector<CInputCoin> utxo_pool; CoinSet selection; CoinSet actual_selection; CAmount value_ret = 0; CAmount not_input_fees = 0; ///////////////////////// // Known Outcome tests // ///////////////////////// BOOST_TEST_MESSAGE("Testing known outcomes"); // Empty utxo pool BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); selection.clear(); // Add utxos add_coin(1 * CENT, 1, utxo_pool); add_coin(2 * CENT, 2, utxo_pool); add_coin(3 * CENT, 3, utxo_pool); add_coin(4 * CENT, 4, utxo_pool); // Select 1 Cent add_coin(1 * CENT, 1, actual_selection); BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); // Select 2 Cent add_coin(2 * CENT, 2, actual_selection); BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 2 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); // Select 5 Cent add_coin(3 * CENT, 3, actual_selection); add_coin(2 * CENT, 2, actual_selection); BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 5 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); // Select 11 Cent, not possible BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 11 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); actual_selection.clear(); selection.clear(); // Select 10 Cent add_coin(5 * CENT, 5, utxo_pool); add_coin(4 * CENT, 4, actual_selection); add_coin(3 * CENT, 3, actual_selection); add_coin(2 * CENT, 2, actual_selection); add_coin(1 * CENT, 1, actual_selection); BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); BOOST_CHECK(equal_sets(selection, actual_selection)); actual_selection.clear(); selection.clear(); // Negative effective value // Select 10 Cent but have 1 Cent not be possible because too small add_coin(5 * CENT, 5, actual_selection); add_coin(3 * CENT, 3, actual_selection); add_coin(2 * CENT, 2, actual_selection); BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 5000, selection, value_ret, not_input_fees)); // Select 0.25 Cent, not possible BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.25 * CENT, 0.5 * CENT, selection, value_ret, not_input_fees)); actual_selection.clear(); selection.clear(); // Iteration exhaustion test CAmount target = make_hard_case(17, utxo_pool); BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), target, 0, selection, value_ret, not_input_fees)); // Should exhaust target = make_hard_case(14, utxo_pool); BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), target, 0, selection, value_ret, not_input_fees)); // Should not exhaust // Test same value early bailout optimization add_coin(7 * CENT, 7, actual_selection); add_coin(7 * CENT, 7, actual_selection); add_coin(7 * CENT, 7, actual_selection); add_coin(7 * CENT, 7, actual_selection); add_coin(2 * CENT, 7, actual_selection); add_coin(7 * CENT, 7, utxo_pool); add_coin(7 * CENT, 7, utxo_pool); add_coin(7 * CENT, 7, utxo_pool); add_coin(7 * CENT, 7, utxo_pool); add_coin(2 * CENT, 7, utxo_pool); for (int i = 0; i < 50000; ++i) { add_coin(5 * CENT, 7, utxo_pool); } BOOST_CHECK(SelectCoinsBnB(GroupCoins(utxo_pool), 30 * CENT, 5000, selection, value_ret, not_input_fees)); //////////////////// // Behavior tests // //////////////////// // Select 1 Cent with pool of only greater than 5 Cent utxo_pool.clear(); for (int i = 5; i <= 20; ++i) { add_coin(i * CENT, i, utxo_pool); } // Run 100 times, to make sure it is never finding a solution for (int i = 0; i < 100; ++i) { BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 2 * CENT, selection, value_ret, not_input_fees)); } // Make sure that effective value is working in SelectCoinsMinConf when BnB is used CoinSelectionParams coin_selection_params_bnb(true, 0, 0, CFeeRate(3000), 0); CoinSet setCoinsRet; CAmount nValueRet; bool bnb_used; empty_wallet(); add_coin(1); vCoins.at(0).nInputBytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params_bnb, bnb_used)); // Make sure that we aren't using BnB when there are preset inputs empty_wallet(); add_coin(5 * CENT); add_coin(3 * CENT); add_coin(2 * CENT); CCoinControl coin_control; coin_control.fAllowOtherInputs = true; coin_control.Select(COutPoint(vCoins.at(0).tx->GetHash(), vCoins.at(0).i)); BOOST_CHECK(testWallet.SelectCoins(vCoins, 10 * CENT, setCoinsRet, nValueRet, coin_control, coin_selection_params_bnb, bnb_used)); BOOST_CHECK(!bnb_used); BOOST_CHECK(!coin_selection_params_bnb.use_bnb); } BOOST_AUTO_TEST_CASE(knapsack_solver_test) { CoinSet setCoinsRet, setCoinsRet2; CAmount nValueRet; bool bnb_used; LOCK(testWallet.cs_wallet); // test multiple times to allow for differences in the shuffle order for (int i = 0; i < RUN_TESTS; i++) { empty_wallet(); // with an empty wallet we can't even pay one cent BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); add_coin(1*CENT, 4); // add a new 1 cent coin // with a new 1 cent coin, we still can't find a mature 1 cent BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // but we can find a new 1 cent BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * CENT); add_coin(2*CENT); // add a mature 2 cent coin // we can't make 3 cents of mature coins BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // we can make 3 cents of new coins BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 3 * CENT); add_coin(5*CENT); // add a mature 5 cent coin, add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses add_coin(20*CENT); // and a mature 20 cent coin // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38 // we can't make 38 cents only if we disallow new coins: BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // we can't even make 37 cents if we don't allow new coins even if they're from us BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, filter_standard_extra, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // but we can make 37 cents if we accept new coins from ourself BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 37 * CENT); // and we can make 38 cents if we accept all new coins BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 38 * CENT); // try making 34 cents from 1,2,5,10,20 - we can't do it exactly BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible) // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5 BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 7 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough. BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(nValueRet == 8 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10) BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 10 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin empty_wallet(); add_coin( 6*CENT); add_coin( 7*CENT); add_coin( 8*CENT); add_coin(20*CENT); add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total // check that we have 71 and not 72 BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30 // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins // now try making 11 cents. we should get 5+6 BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 11 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // check that the smallest bigger coin is used add_coin( 1*COIN); add_coin( 2*COIN); add_coin( 3*COIN); add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTCV in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTCV in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // empty the wallet and start again, now with fractions of a cent, to test small change avoidance empty_wallet(); add_coin(MIN_CHANGE * 1 / 10); add_coin(MIN_CHANGE * 2 / 10); add_coin(MIN_CHANGE * 3 / 10); add_coin(MIN_CHANGE * 4 / 10); add_coin(MIN_CHANGE * 5 / 10); // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // but if we add a bigger coin, small change is avoided add_coin(1111*MIN_CHANGE); // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5 BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount // if we add more small coins: add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 7 / 10); // and try again to make 1.0 * MIN_CHANGE BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf) // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change empty_wallet(); for (int j = 0; j < 20; j++) add_coin(50000 * COIN); BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins // if there's not enough in the smaller coins to make at least 1 * MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0), // we need to try finding an exact subset anyway // sometimes it will fail, and so we use the next biggest coin: empty_wallet(); add_coin(MIN_CHANGE * 5 / 10); add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 7 / 10); add_coin(1111 * MIN_CHANGE); BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0) empty_wallet(); add_coin(MIN_CHANGE * 4 / 10); add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 8 / 10); add_coin(1111 * MIN_CHANGE); BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6 // test avoiding small change empty_wallet(); add_coin(MIN_CHANGE * 5 / 100); add_coin(MIN_CHANGE * 1); add_coin(MIN_CHANGE * 100); // trying to make 100.01 from these three coins BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // test with many inputs for (CAmount amt=1500; amt < COIN; amt*=10) { empty_wallet(); // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input) for (uint16_t j = 0; j < 676; j++) add_coin(amt); BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, filter_confirmed, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); if (amt - 2000 < MIN_CHANGE) { // needs more than one input: uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt); CAmount returnValue = amt * returnSize; BOOST_CHECK_EQUAL(nValueRet, returnValue); BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize); } else { // one input is sufficient: BOOST_CHECK_EQUAL(nValueRet, amt); BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); } } // test randomness { empty_wallet(); for (int i2 = 0; i2 < 100; i2++) add_coin(COIN); // picking 50 from 100 coins doesn't depend on the shuffle, // but does depend on randomness in the stochastic approximation code BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet , nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2)); int fails = 0; for (int j = 0; j < RANDOM_REPEATS; j++) { // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time // run the test RANDOM_REPEATS times and only complain if all of them fail BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, GroupCoins(vCoins), setCoinsRet , nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, filter_standard, GroupCoins(vCoins), setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); if (equal_sets(setCoinsRet, setCoinsRet2)) fails++; } BOOST_CHECK_NE(fails, RANDOM_REPEATS); // add 75 cents in small change. not enough to make 90 cents, // then try making 90 cents. there are multiple competing "smallest bigger" coins, // one of which should be picked at random add_coin(5 * CENT); add_coin(10 * CENT); add_coin(15 * CENT); add_coin(20 * CENT); add_coin(25 * CENT); fails = 0; for (int j = 0; j < RANDOM_REPEATS; j++) { // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time // run the test RANDOM_REPEATS times and only complain if all of them fail BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, GroupCoins(vCoins), setCoinsRet , nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, filter_standard, GroupCoins(vCoins), setCoinsRet2, nValueRet, coin_selection_params, bnb_used)); if (equal_sets(setCoinsRet, setCoinsRet2)) fails++; } BOOST_CHECK_NE(fails, RANDOM_REPEATS); } } empty_wallet(); } BOOST_AUTO_TEST_CASE(ApproximateBestSubset) { CoinSet setCoinsRet; CAmount nValueRet; bool bnb_used; LOCK(testWallet.cs_wallet); empty_wallet(); // Test vValue sort order for (int i = 0; i < 1000; i++) add_coin(1000 * COIN); add_coin(3 * COIN); BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, filter_standard, GroupCoins(vCoins), setCoinsRet, nValueRet, coin_selection_params, bnb_used)); BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); empty_wallet(); } // Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value BOOST_AUTO_TEST_CASE(SelectCoins_test) { // Random generator stuff std::default_random_engine generator; std::exponential_distribution<double> distribution (100); FastRandomContext rand; // Run this test 100 times for (int i = 0; i < 100; ++i) { empty_wallet(); // Make a wallet with 1000 exponentially distributed random inputs for (int j = 0; j < 1000; ++j) { add_coin((CAmount)(distribution(generator)*10000000)); } // Generate a random fee rate in the range of 100 - 400 CFeeRate rate(rand.randrange(300) + 100); // Generate a random target value between 1000 and wallet balance CAmount target = rand.randrange(balance - 1000) + 1000; // Perform selection CoinSelectionParams coin_selection_params_knapsack(false, 34, 148, CFeeRate(0), 0); CoinSelectionParams coin_selection_params_bnb(true, 34, 148, CFeeRate(0), 0); CoinSet out_set; CAmount out_value = 0; bool bnb_used = false; BOOST_CHECK(testWallet.SelectCoinsMinConf(target, filter_standard, GroupCoins(vCoins), out_set, out_value, coin_selection_params_bnb, bnb_used) || testWallet.SelectCoinsMinConf(target, filter_standard, GroupCoins(vCoins), out_set, out_value, coin_selection_params_knapsack, bnb_used)); BOOST_CHECK_GE(out_value, target); } } BOOST_AUTO_TEST_SUITE_END()
[ "nullfunctor@bitcoinv.org" ]
nullfunctor@bitcoinv.org
efcf532402deabddcb259475392fc5571e454544
ded926558f8fa5def08a847192b5d3a7ad801a3d
/TicTacToe/TicTacToeTests/TicTacToeTest.cpp
6a1bfa5b05857133066fc77c966ebdf6583fe7f3
[]
no_license
8thlight/cpp-training-custom
03e745ebb5cc3d2d72f442397166ce7089ba87e3
627ce11bbbaa649735a5b498cf847c6c877f4354
refs/heads/master
2020-04-18T23:30:42.673535
2019-03-12T14:42:44
2019-03-12T14:42:44
167,823,109
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
// Copyright 2019 < 8th Light > #include <gtest/gtest.h> #include "../TicTacToe/TicTacToe.hpp" #include "../TicTacToe/RandomPlayer.hpp" #include "StubUI.hpp" namespace training { TEST(TicTacToe, hvhGameP1Wins) { StubUI stubUI({ "1", "1", "4", "2", "5", "3" }); TicTacToe ttt(stubUI, 3); ttt.start(); EXPECT_TRUE(stubUI.wasWinAnnounced()); } TEST(TicTacToe, cvcGame) { StubUI stubUI({ "4" }); TicTacToe ttt(stubUI, 3); ttt.start(); EXPECT_TRUE(stubUI.wasWinAnnounced() || stubUI.wasDrawAnnounced()); } } // namespace training
[ "devlin.glasman@gmail.com" ]
devlin.glasman@gmail.com
0e7a2020a4e5871fe48247224231b683b7274929
8c6047251fab46c71030b8fc4fac995c3269639f
/modules/wechat_qrcode/src/zxing/common/unicomblock.hpp
df08d140ebbeb0c6c31899cdc718b359d849b311
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-Warranty", "LicenseRef-scancode-unknown-license-reference" ]
permissive
DevenLu/opencv_contrib
01210c07b292f2290861df1e51b27cc5fb9295c9
273246d8572cf005c7648e60c6cef78240edfb3e
refs/heads/master
2023-02-12T21:40:03.347386
2021-01-15T08:15:00
2021-01-15T08:15:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
hpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. #ifndef __ZXING_COMMON_UNICOMBLOCK_HPP__ #define __ZXING_COMMON_UNICOMBLOCK_HPP__ #include "zxing/common/bitmatrix.hpp" #include "zxing/common/counted.hpp" #include <cstring> #include <vector> namespace zxing { class UnicomBlock : public Counted { public: UnicomBlock(int iMaxHeight, int iMaxWidth); ~UnicomBlock(); void Init(); void Reset(Ref<BitMatrix> poImage); unsigned short GetUnicomBlockIndex(int y, int x); int GetUnicomBlockSize(int y, int x); int GetMinPoint(int y, int x, int &iMinY, int &iMinX); int GetMaxPoint(int y, int x, int &iMaxY, int &iMaxX); private: void Bfs(int y, int x); int m_iHeight; int m_iWidth; unsigned short m_iNowIdx; bool m_bInit; std::vector<unsigned short> m_vcIndex; std::vector<unsigned short> m_vcCount; std::vector<int> m_vcMinPnt; std::vector<int> m_vcMaxPnt; std::vector<int> m_vcQueue; static short SEARCH_POS[4][2]; Ref<BitMatrix> m_poImage; }; } // namespace zxing #endif // __ZXING_COMMON_UNICOMBLOCK_HPP__
[ "zhigangdai@hotmail.com" ]
zhigangdai@hotmail.com
9c415064fcb4c6b4f29ba2ecb0ab1bcb85735507
1dd1f9ec7b329f08be32041ee6ab917336781ad7
/src/Character.cpp
367d4b11a6b4c8148ef32098414b2a98ee63ade3
[]
no_license
FiBe4000/fibengine4000
0af651891ce1e4562048d7d11bdfb89891bc8774
c9a2b00b4373eaf8e4c55dce32f9d125731a5a04
refs/heads/master
2021-01-21T11:45:08.332212
2015-12-05T22:08:16
2015-12-05T22:08:16
35,506,181
0
0
null
null
null
null
UTF-8
C++
false
false
5,394
cpp
#include "Character.h" #include "GameEngine.h" Character::Character(std::string charFilename) : animChar(sf::seconds(0.2), true, false) { char filename[30]; int i; for(i=0; i<charFilename.length(); i++) filename[i] = charFilename.at(i); filename[i] = '\0'; if(!characterTexture.loadFromFile(filename)) { std::cerr << "Error: " << charFilename << " could not be found" << std::endl; GameEngine::Stop(); } characterTexture.setSmooth(false); walkingAnimationDown.setSpriteSheet(characterTexture); walkingAnimationLeft.setSpriteSheet(characterTexture); walkingAnimationRight.setSpriteSheet(characterTexture); walkingAnimationUp.setSpriteSheet(characterTexture); walkingAnimationUp.addFrame(sf::IntRect(24,0,13,18)); walkingAnimationUp.addFrame(sf::IntRect(48,1,13,18)); walkingAnimationUp.addFrame(sf::IntRect(24,0,13,18)); walkingAnimationUp.addFrame(sf::IntRect(0,1,13,18)); walkingAnimationDown.addFrame(sf::IntRect(24,64,13,18)); walkingAnimationDown.addFrame(sf::IntRect(48,65,13,18)); walkingAnimationDown.addFrame(sf::IntRect(24,64,13,18)); walkingAnimationDown.addFrame(sf::IntRect(0,65,13,18)); walkingAnimationRight.addFrame(sf::IntRect(24,32,13,18)); walkingAnimationRight.addFrame(sf::IntRect(48,33,13,18)); walkingAnimationRight.addFrame(sf::IntRect(24,32,13,18)); walkingAnimationRight.addFrame(sf::IntRect(0,33,13,18)); walkingAnimationLeft.addFrame(sf::IntRect(24,96,13,18)); walkingAnimationLeft.addFrame(sf::IntRect(48,97,13,18)); walkingAnimationLeft.addFrame(sf::IntRect(24,96,13,18)); walkingAnimationLeft.addFrame(sf::IntRect(0,97,13,18)); /* walkingAnimationDown.addFrame(sf::IntRect(32, 0, 32, 32)); walkingAnimationDown.addFrame(sf::IntRect(64, 0, 32, 32)); walkingAnimationDown.addFrame(sf::IntRect(32, 0, 32, 32)); walkingAnimationDown.addFrame(sf::IntRect( 0, 0, 32, 32)); walkingAnimationLeft.addFrame(sf::IntRect(32, 32, 32, 32)); walkingAnimationLeft.addFrame(sf::IntRect(64, 32, 32, 32)); walkingAnimationLeft.addFrame(sf::IntRect(32, 32, 32, 32)); walkingAnimationLeft.addFrame(sf::IntRect( 0, 32, 32, 32)); walkingAnimationRight.addFrame(sf::IntRect(32, 64, 32, 32)); walkingAnimationRight.addFrame(sf::IntRect(64, 64, 32, 32)); walkingAnimationRight.addFrame(sf::IntRect(32, 64, 32, 32)); walkingAnimationRight.addFrame(sf::IntRect( 0, 64, 32, 32)); walkingAnimationUp.addFrame(sf::IntRect(32, 96, 32, 32)); walkingAnimationUp.addFrame(sf::IntRect(64, 96, 32, 32)); walkingAnimationUp.addFrame(sf::IntRect(32, 96, 32, 32)); walkingAnimationUp.addFrame(sf::IntRect( 0, 96, 32, 32)); */ position.x = 0.f; position.y = 0.f; animChar.setPosition(position); Animation* currentAnimation = &walkingAnimationRight; animChar.play(*currentAnimation); Moving = false; } Character::~Character() { } void Character::moveDown(bool CanMove, float moveSpeed) { FrameTime = FrameClock.restart(); currentAnimation = &walkingAnimationDown; animChar.play(*currentAnimation); //movement = sf::Vector2f(0.f, 0.f); if(CanMove) { position.y += moveSpeed * GameEngine::gEngine.GetFrameTime(); //movement.y += moveSpeed; Moving = true; //GetAnimation().move(position * FrameTime.asSeconds()); } else { animChar.stop(); } } void Character::moveUp(bool CanMove, float moveSpeed) { FrameTime = FrameClock.restart(); currentAnimation = &walkingAnimationUp; animChar.play(*currentAnimation); //movement = sf::Vector2f(0.f, 0.f); //animChar.play(*currentAnimation); if(CanMove) { position.y -= moveSpeed * GameEngine::gEngine.GetFrameTime();; //movement.y -= moveSpeed; Moving = true; //GetAnimation().move(position * FrameTime.asSeconds()); } else { animChar.stop(); } } void Character::moveRight(bool CanMove, float moveSpeed) { FrameTime = FrameClock.restart(); currentAnimation = &walkingAnimationRight; animChar.play(*currentAnimation); //movement = sf::Vector2f(0.f, 0.f); //animChar.play(*currentAnimation); if(CanMove) { position.x += moveSpeed * GameEngine::gEngine.GetFrameTime();; //movement.x += moveSpeed; Moving = true; //GetAnimation().move(position * FrameTime.asSeconds()); } else { animChar.stop(); } } void Character::moveLeft(bool CanMove, float moveSpeed) { FrameTime = FrameClock.restart(); currentAnimation = &walkingAnimationLeft; animChar.play(*currentAnimation); //movement = sf::Vector2f(0.f, 0.f); //animChar.play(*currentAnimation); if(CanMove) { position.x -= moveSpeed * GameEngine::gEngine.GetFrameTime();; //movement.x -= moveSpeed; Moving = true; //GetAnimation().move(position * FrameTime.asSeconds()); } else { animChar.stop(); } } void Character::stop() { Moving = false; //movement = sf::Vector2f(0.f, 0.f); } void Character::update() { if(!Moving) { animChar.stop(); } //GetAnimation().move(movement * FrameTime.asSeconds()); updatePosition(); animChar.update(FrameTime); }
[ "fibeube@gmail.com" ]
fibeube@gmail.com
ff6abb13ca2d3408de13680c6d9fc1629e87e0ef
84d89cf12742f556d0201be63777d833c0c0df0a
/Autonomous Snowplow 2019/dead_reckoning.h
2e46bd01ec82717c13119f0c494ddc3782048932
[]
no_license
ISURobotics/AutonomousSnowplow2019
b50db478a451f0e83102abbdaa740c20fcbea7b7
ac0a70d0524321981c39b52c6c810b8ba629ada5
refs/heads/master
2021-07-12T09:57:20.946764
2019-01-06T21:23:01
2019-01-06T21:23:01
140,986,573
1
3
null
2018-09-22T20:57:12
2018-07-15T00:16:41
C++
UTF-8
C++
false
false
600
h
#pragma once #include <ctime> #include <cmath> #include "snowplow_type.h" #define PI ( 3.14159265 ) class dead_reckoning { public: dead_reckoning(atomic<double> * x_pos, atomic<double> * y_pos, atomic<double> * orientation, drive_data_pkt * drive_pkt, atomic<long> * timestamp); private: atomic<double> * prv_x_ref; atomic<double> * prv_y_ref; atomic<double> * prv_ori_ref; drive_data_pkt * prv_drive_pkt_ref; atomic<long> * prv_timestamp_ref; double x_prev; double y_prev; double time_initial; double delta_time; double deca_x; double deca_y; public: void UpdatePosition(); };
[ "AndrewHancock0@Gmail.com" ]
AndrewHancock0@Gmail.com
65225986873c4e16da9d7fbec08b598054d4974c
cbba4843ce29e263bb6a4b371547cdc7b1cde095
/DISCONTINUED/includes-aj/assembler/MacroAssemblerCodeRef.h
a02939a3c4abba6725cca006ac2d195212011ffe
[ "Apache-2.0" ]
permissive
openaphid/Runtime
e5c15adbec0c8d64a3cee4f0e707ff4127387b5f
f2d779b45632bba438e2a9a655166f4963274425
refs/heads/master
2021-06-20T08:45:50.765804
2021-03-10T09:10:26
2021-03-10T09:10:26
4,126,273
56
5
null
null
null
null
UTF-8
C++
false
false
6,288
h
/* Copyright 2012 Aphid Mobile 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. */ /* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MacroAssemblerCodeRef_h #define MacroAssemblerCodeRef_h #include "ExecutableAllocator.h" #include "PassRefPtr.h" #include "RefPtr.h" #include "UnusedParam.h" #if ENABLE(ASSEMBLER) // ASSERT_VALID_CODE_POINTER checks that ptr is a non-null pointer, and that it is a valid // instruction address on the platform (for example, check any alignment requirements). #if CPU(ARM_THUMB2) // ARM/thumb instructions must be 16-bit aligned, but all code pointers to be loaded // into the processor are decorated with the bottom bit set, indicating that this is // thumb code (as oposed to 32-bit traditional ARM). The first test checks for both // decorated and undectorated null, and the second test ensures that the pointer is // decorated. #define ASSERT_VALID_CODE_POINTER(ptr) \ ASSERT(reinterpret_cast<intptr_t>(ptr) & ~1); \ ASSERT(reinterpret_cast<intptr_t>(ptr) & 1) #define ASSERT_VALID_CODE_OFFSET(offset) \ ASSERT(!(offset & 1)) // Must be multiple of 2. #else #define ASSERT_VALID_CODE_POINTER(ptr) \ ASSERT(ptr) #define ASSERT_VALID_CODE_OFFSET(offset) // Anything goes! #endif namespace AJ { // FunctionPtr: // // FunctionPtr should be used to wrap pointers to C/C++ functions in JSC // (particularly, the stub functions). class FunctionPtr { public: FunctionPtr() : m_value(0) { } template<typename FunctionType> explicit FunctionPtr(FunctionType* value) #if COMPILER(RVCT) // RVTC compiler needs C-style cast as it fails with the following error // Error: #694: reinterpret_cast cannot cast away const or other type qualifiers : m_value((void*)(value)) #else : m_value(reinterpret_cast<void*>(value)) #endif { ASSERT_VALID_CODE_POINTER(m_value); } void* value() const { return m_value; } void* executableAddress() const { return m_value; } private: void* m_value; }; // ReturnAddressPtr: // // ReturnAddressPtr should be used to wrap return addresses generated by processor // 'call' instructions exectued in JIT code. We use return addresses to look up // exception and optimization information, and to repatch the call instruction // that is the source of the return address. class ReturnAddressPtr { public: ReturnAddressPtr() : m_value(0) { } explicit ReturnAddressPtr(void* value) : m_value(value) { ASSERT_VALID_CODE_POINTER(m_value); } explicit ReturnAddressPtr(FunctionPtr function) : m_value(function.value()) { ASSERT_VALID_CODE_POINTER(m_value); } void* value() const { return m_value; } private: void* m_value; }; // MacroAssemblerCodePtr: // // MacroAssemblerCodePtr should be used to wrap pointers to JIT generated code. class MacroAssemblerCodePtr { public: MacroAssemblerCodePtr() : m_value(0) { } explicit MacroAssemblerCodePtr(void* value) #if CPU(ARM_THUMB2) // Decorate the pointer as a thumb code pointer. : m_value(reinterpret_cast<char*>(value) + 1) #else : m_value(value) #endif { ASSERT_VALID_CODE_POINTER(m_value); } explicit MacroAssemblerCodePtr(ReturnAddressPtr ra) : m_value(ra.value()) { ASSERT_VALID_CODE_POINTER(m_value); } void* executableAddress() const { return m_value; } #if CPU(ARM_THUMB2) // To use this pointer as a data address remove the decoration. void* dataLocation() const { ASSERT_VALID_CODE_POINTER(m_value); return reinterpret_cast<char*>(m_value) - 1; } #else void* dataLocation() const { ASSERT_VALID_CODE_POINTER(m_value); return m_value; } #endif bool operator!() { return !m_value; } private: void* m_value; }; // MacroAssemblerCodeRef: // // A reference to a section of JIT generated code. A CodeRef consists of a // pointer to the code, and a ref pointer to the pool from within which it // was allocated. class MacroAssemblerCodeRef { public: MacroAssemblerCodeRef() : m_size(0) { } MacroAssemblerCodeRef(void* code, PassRefPtr<ExecutablePool> executablePool, size_t size) : m_code(code) , m_executablePool(executablePool) , m_size(size) { } MacroAssemblerCodePtr m_code; RefPtr<ExecutablePool> m_executablePool; size_t m_size; }; } // namespace AJ #endif // ENABLE(ASSEMBLER) #endif // MacroAssemblerCodeRef_h
[ "openaphid@gmail.com" ]
openaphid@gmail.com
3a633f5688bc4333cb9a3f29137e0be4f166a6bc
99566774a6ddd652f5520916aa924b6c8ad01461
/Source/Voxel/Public/VoxelTools/VoxelProjectionTools.h
161ceb3a585778c8498b3c2e91ff49dec0908beb
[ "MIT" ]
permissive
aurodev/VoxelPlugin
20c8e6d0069e4da28c95c304bdf0241d4fe11875
bd1679a3541485a9e2e9555deaba43f9b38607b2
refs/heads/master
2021-04-17T13:02:27.660228
2020-01-26T10:02:46
2020-01-26T10:02:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,933
h
// Copyright 2020 Phyronnaz #pragma once #include "CoreMinimal.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "Kismet/KismetSystemLibrary.h" #include "CollisionQueryParams.h" #include "VoxelTools/VoxelSurfaceTools.h" #include "VoxelProjectionTools.generated.h" class AVoxelWorld; USTRUCT(BlueprintType, meta = (HasNativeMake="Voxel.VoxelProjectionTools.MakeVoxelLineTraceParameters")) struct FVoxelLineTraceParameters { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel") TEnumAsByte<ECollisionChannel> CollisionChannel = ECollisionChannel::ECC_WorldDynamic; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel") TArray<TEnumAsByte<ECollisionChannel>> CollisionChannelsToIgnore; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel") TArray<AActor*> ActorsToIgnore; UPROPERTY(EditAnywhere, AdvancedDisplay, BlueprintReadWrite, Category = "Voxel") TEnumAsByte<EDrawDebugTrace::Type> DrawDebugType = EDrawDebugTrace::None; UPROPERTY(EditAnywhere, AdvancedDisplay, BlueprintReadWrite, Category = "Voxel") FLinearColor TraceColor = FLinearColor::Red; UPROPERTY(EditAnywhere, AdvancedDisplay, BlueprintReadWrite, Category = "Voxel") FLinearColor TraceHitColor = FLinearColor::Green; UPROPERTY(EditAnywhere, AdvancedDisplay, BlueprintReadWrite, Category = "Voxel") float DrawTime = 5.0f; FCollisionQueryParams GetParams() const; FCollisionResponseContainer GetResponseContainer() const; void DrawDebug(const UWorld* World, const FVector& Start, const FVector& End, bool bHit, const FHitResult& OutHit) const; }; UENUM(BlueprintType) enum class EVoxelProjectionShape : uint8 { Circle, Square }; USTRUCT(BlueprintType) struct FVoxelProjectionHit { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel") FIntVector VoxelPosition = FIntVector(ForceInit); // Position on the projection plane UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel") FVector2D PlanePosition = FVector2D(ForceInit); UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Voxel") FHitResult Hit = FHitResult(ForceInit); }; UCLASS() class VOXEL_API UVoxelProjectionTools : public UBlueprintFunctionLibrary { GENERATED_BODY() public: // Needed because else we need to add 2 MakeArrays node... // Make voxel line trace parameters UFUNCTION(BlueprintPure, Category = "Voxel", meta = (AdvancedDisplay = "CollisionChannelsToIgnore, ActorsToIgnore, DrawDebugType, TraceColor, TraceHitColor, DrawTime", AutoCreateRefTerm = "CollisionChannelsToIgnore, ActorsToIgnore")) static FVoxelLineTraceParameters MakeVoxelLineTraceParameters( TArray<TEnumAsByte<ECollisionChannel>> CollisionChannelsToIgnore, TArray<AActor*> ActorsToIgnore, TEnumAsByte<ECollisionChannel> CollisionChannel = ECollisionChannel::ECC_WorldDynamic, TEnumAsByte<EDrawDebugTrace::Type> DrawDebugType = EDrawDebugTrace::None, FLinearColor TraceColor = FLinearColor::Red, FLinearColor TraceHitColor = FLinearColor::Green, float DrawTime = 5.0f); public: /** * Find voxels using linetraces * @param World The voxel world * @param Parameters Linetraces parameters * @param Position The center of the linetraces * @param Direction The direction of the linetraces * @param Radius The radius in world space (cm) * @param Shape The shape of the rays start positions * @param NumRays The approximate number of rays to trace * @param MaxDistance The max ray distance * @return Number of rays actually traced (should be close to NumRays) */ UFUNCTION(BlueprintCallable, Category = "Voxel|Tools|Projection Tools", meta = (DefaultToSelf = "World")) static int32 FindProjectionVoxels( TArray<FVoxelProjectionHit>& Hits, AVoxelWorld* World, FVoxelLineTraceParameters Parameters, FVector Position, FVector Direction, float Radius = 100.f, EVoxelProjectionShape Shape = EVoxelProjectionShape::Circle, float NumRays = 100.f, float MaxDistance = 1e9); /** * Find voxels using linetraces, asynchronously * @param World The voxel world * @param Parameters Linetraces parameters * @param Position The center of the linetraces * @param Direction The direction of the linetraces * @param Radius The radius in world space (cm) * @param Shape The shape of the rays start positions * @param NumRays The approximate number of rays to trace * @param MaxDistance The max ray distance * @return Number of rays actually traced (should be close to NumRays) */ UFUNCTION(BlueprintCallable, Category = "Voxel|Tools|Projection Tools", meta = (DefaultToSelf = "World", Latent, LatentInfo="LatentInfo", WorldContext = "WorldContextObject", AdvancedDisplay = "bHideLatentWarnings")) static int32 FindProjectionVoxelsAsync( UObject* WorldContextObject, FLatentActionInfo LatentInfo, TArray<FVoxelProjectionHit>& Hits, AVoxelWorld* World, FVoxelLineTraceParameters Parameters, FVector Position, FVector Direction, float Radius = 100.f, EVoxelProjectionShape Shape = EVoxelProjectionShape::Circle, float NumRays = 100.f, float MaxDistance = 1e9, bool bHideLatentWarnings = false); public: UFUNCTION(BlueprintCallable, Category = "Voxel|Tools|Projection Tools") static TArray<FIntVector> GetHitsPositions( const TArray<FVoxelProjectionHit>& Hits); UFUNCTION(BlueprintCallable, Category = "Voxel|Tools|Projection Tools") static FVector GetHitsAverageNormal( const TArray<FVoxelProjectionHit>& Hits); UFUNCTION(BlueprintCallable, Category = "Voxel|Tools|Projection Tools") static FVector GetHitsAveragePosition( const TArray<FVoxelProjectionHit>& Hits); // Note: will use a constant voxel value of 1 UFUNCTION(BlueprintCallable, Category = "Voxel|Tools|Projection Tools") static TArray<FSurfaceVoxel> CreateSurfaceVoxelsFromHits(const TArray<FVoxelProjectionHit>& Hits); public: // NumRays might be slightly lower than the actual number of traced rays // Returns num rays actually traced template<typename T> static int32 GenerateRays( const FVector& Position, const FVector& Direction, const float Radius, const EVoxelProjectionShape Shape, const float NumRays, const float MaxDistance, T Lambda) { if (!ensure(Direction.IsNormalized())) return 0; if (NumRays <= 0) return 0; const auto GetTangent = [](const FVector& N) { // Compute tangent // N dot T = 0 // <=> N.X * T.X + N.Y * T.Y + N.Z * T.Z = 0 // <=> T.Z = -1 / N.Z * (N.X * T.X + N.Y * T.Y) if N.Z != 0 if (N.Z != 0) { return FVector(1, 1, -1 / double(N.Z) * (N.X + N.Y)).GetSafeNormal(); } else { return FVector(0, 0, 1); } }; const FVector Tangent = GetTangent(Direction); const FVector BiTangent = FVector::CrossProduct(Tangent, Direction).GetSafeNormal(); // NumRays is the area; get the radius we would get from such area const float NumRaysInRadius = Shape == EVoxelProjectionShape::Circle ? FMath::Sqrt(NumRays / PI) : FMath::Sqrt(NumRays) / 2; const int32 Count = FMath::CeilToInt(NumRaysInRadius); const float RadiusSquared = FMath::Square(Radius); int32 NumRaysActuallyTraced = 0; for (int32 U = -Count; U <= Count; U++) { for (int32 V = -Count; V <= Count; V++) { const FVector2D PlanePosition = FVector2D(U, V) * Radius / Count; if (Shape == EVoxelProjectionShape::Circle && PlanePosition.SizeSquared() >= RadiusSquared) { continue; } const FVector Start = Position + (Tangent * PlanePosition.X + BiTangent * PlanePosition.Y); const FVector End = Start + Direction * MaxDistance; Lambda(Start, End, PlanePosition); NumRaysActuallyTraced++; } } return NumRaysActuallyTraced; } };
[ "phyronnaz@gmail.com" ]
phyronnaz@gmail.com
a948d057066f9245a805aca0b92d6c6e5b2111bf
d72a33659c0af3f18fdb29edb8c85e3e261017fa
/filterCommon.h
559c5b040be8b396a979d6f8e98e9fbf5650a47f
[]
no_license
littlebeanfang/arcfilter
f0f22f9792a5b5e2ba9ad51e30dd2c906b080742
6d0e34fccec5fdf5b38d217ac99609d2c07e9f89
refs/heads/master
2020-05-20T06:37:23.487459
2011-04-16T15:58:46
2011-04-16T15:58:46
35,925,461
0
0
null
null
null
null
UTF-8
C++
false
false
4,313
h
/****************************************** * * filterCommon.h * * Shane Bergsma * June 3, 2010 * ******************************************/ #ifndef FILTERCOMMON_H #define FILTERCOMMON_H #include <stdio.h> // For sprintf #include <stdlib.h> // For all the exit()'s called by the mains #include <tr1/unordered_map> // For storing the weights #include <tr1/unordered_set> // For storing the taboo lists #include <string> #include <vector> #include <bitset> // For filtering decisions, FilterVals type const int MAXSENTSIZE = 999; // For the efficient bitvector, and for int2str typedef std::tr1::unordered_set<std::string> RuleLists; typedef std::vector<std::string> StrVec; // For the output of the rules: typedef std::bitset<MAXSENTSIZE> FilterVals; // For the scores of the other filters: typedef std::vector<float> FilterScores; typedef std::vector<bool> eightB; typedef std::vector<float> eightF; // For the two pair filters: typedef std::vector<float> twoW; typedef std::tr1::unordered_map<std::string,eightF> LinearWeightsMap; typedef std::tr1::unordered_map<std::string,twoW> UltraPairWeightsMap; typedef std::tr1::unordered_map<std::string,float> QuadWeightMap; typedef std::vector< std::pair<std::string,float> > RealFeats; // Load in all the rules for simple filtering of arcs void initializeTaboos(RuleLists& tabooHeads, RuleLists& noLeftHead, RuleLists& noRightHead, RuleLists& tabooPairs); // Quickly turn an integer into a string: For efficiency: Use fact we // never have a distance or index > 999 // Whoops : you need another byte for the '\0' guy that terminates strings! inline std::string fastInt2Str(int d) { static char buf[4]; sprintf(buf, "%d", d); return buf; } // Preprocess the input lines as I did when training: inline void normLines(std::string &input) { for (std::string::iterator cItr=input.begin(); cItr != input.end(); cItr++) { if (*cItr == '#') *cItr = '|'; // '#' means comments elsewhere else if (*cItr == ':') *cItr = ';'; // ':' separates features and weights elsewhere } } // Preprocess the input words to convert digits to 0 inline void normWords(std::string &input) { for (std::string::iterator cItr=input.begin(); cItr != input.end(); cItr++) if (isdigit(*cItr)) *cItr = '0'; } inline void safeNeighbourDoubleGet(int nbh, const StrVec &words, const StrVec &tags, int sentSize, std::string *wordNbh, std::string *tagNbh) { if (nbh > 0 && nbh < sentSize) { *wordNbh = words[nbh]; *tagNbh = tags[nbh]; return; } //else { // if (nbh < 1 || nbh >= words.size()) { *wordNbh = "~"; *tagNbh = "~"; // } } inline void safeNeighbourTagGet(int nbh, const StrVec &tags, int sentSize, std::string *tagNbh) { if (nbh > 0 && nbh < sentSize) { *tagNbh = tags[nbh]; return; }// else { // if (nbh < 1 || nbh >= tags.size()) { *tagNbh = "~"; } // Quantize the distance into several ranges, currently used for // head-mod links and mod-root links. inline std::string binDistance(int d); // Build a feature vector given the current words and tags: void buildLinearFeatureVector(int pos, const StrVec &words, const StrVec &tags, int sentSize, StrVec &feats); // Build a feature vector given a pair of words and tags void buildQuadraticFeatureVector(int h, int m, const StrVec &words, const StrVec &tags, int sentSize, const std::vector<float> &logPrecomputes, StrVec &binfeats, RealFeats &realfeats); // Get the 0/1 predictions for each filter void getLinearFilterPredictions(const LinearWeightsMap &linWeights, const StrVec &feats, eightB &preds); // Get the floating-point scores for each of the nine ultra filters: void getUltraLinearFilterScores(const LinearWeightsMap &linWeights, const StrVec &feats, eightF &preds); // Get the 0/1 prediction for the quadratic bool getQuadraticFilterPredictions(const QuadWeightMap &quadWeights, const StrVec &binFeats, const RealFeats &realFeats); // Load the weight matrix from file: void initializeLinearWeights(char *filename, LinearWeightsMap &linWeights); // Load the ultra 2-D pair weight matrix from file: void initializeUltraPairWeights(char *filename, UltraPairWeightsMap &pairWeights); // Load the weight vector from file: void initializeQuadWeights(char *filename, QuadWeightMap &quadWeights); #endif // FILTERCOMMON_H
[ "bergsma@cs.ualberta.ca@99770927-89b6-3fda-ff45-25cc84932d1e" ]
bergsma@cs.ualberta.ca@99770927-89b6-3fda-ff45-25cc84932d1e
5e193b230c92f5a54f399171055f859edb47982d
6a9b877ca9b18ccf3764a999340aeda1679eb76c
/src/capengine/tiledtileset.cpp
0b7ef1ef0d2d1252950264b587e831a849d7de56
[]
no_license
calebpalmer/capengine
f63299ce55bba6621d021daa4d5857efcc12a1b4
d6851a776372e676afcb17711cec115cdcf2b392
refs/heads/master
2023-07-07T09:07:38.862127
2023-06-29T23:44:52
2023-06-29T23:44:52
8,950,745
1
0
null
null
null
null
UTF-8
C++
false
false
1,539
cpp
#include "tiledtileset.h" #include "CapEngineException.h" #include "VideoManager.h" #include "captypes.h" #include "locator.h" #include <boost/throw_exception.hpp> #include <fstream> namespace CapEngine { TiledTileset::TiledTileset(const jsoncons::json &in_data, std::optional<std::filesystem::path> in_path) : m_texture(getNullTexturePtr()), m_path(in_path) { if (m_path) { m_image = m_path->parent_path() / in_data["image"].as<std::string>(); } else { m_image = in_data["image"].as<std::string>(); } m_imageHeight = in_data["imageheight"].as<int>(); m_imageWidth = in_data["imagewidth"].as<int>(); m_tileWidth = in_data["tilewidth"].as<int>(); m_tileHeight = in_data["tileheight"].as<int>(); } TiledTileset TiledTileset::create(std::filesystem::path in_path) { std::ifstream f{in_path}; auto json = jsoncons::json::parse(f); return TiledTileset(json, in_path); } const std::string &TiledTileset::image() const { return m_image; } int TiledTileset::imageWidth() const { return m_imageWidth; } int TiledTileset::imageHeight() const { return m_imageHeight; } int TiledTileset::tileWidth() const { return m_tileWidth; } int TiledTileset::tileHeight() const { return m_tileHeight; } void TiledTileset::loadTexture() { m_texture = CapEngine::Locator::videoManager->loadImagePtr(m_image); } Texture &TiledTileset::texture() { if (m_texture) return *m_texture; else BOOST_THROW_EXCEPTION(CapEngineException("Texture not loaded. Must call loadTexture() first.")); ; } } // namespace CapEngine
[ "palmer.caleb@gmail.com" ]
palmer.caleb@gmail.com
0657932a3d196e22bc95a8a356ae84ffaace72ee
9fc919b7e778361bc81137f6a0a1abe6acbc74bc
/onerut_normal_operator/src/domain_custom.cpp
d9a035aaf1df55f7767cdc0a3c0ed567d77d1b23
[]
no_license
MateuszSnamina/onerut
315f712d36d2ebc797e0292b9d78b7629d81df2c
a38b3790f995aac1a89f415c47f27f7b63bf8c0d
refs/heads/master
2020-04-16T10:41:44.417458
2019-06-02T21:49:07
2019-06-02T21:49:07
165,513,612
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
#include<cassert> #include<onerut_normal_operator/domain_custom.hpp> namespace onerut_normal_operator { CustomDomain::CustomDomain(std::vector<std::string> state_names) : _state_names(state_names) { } uint32_t CustomDomain::size() const { return _state_names.size(); } std::string CustomDomain::state_name(uint32_t index) const { assert(index < _state_names.size()); return _state_names[index]; } }
[ "mateusz.snamina@gmail.com" ]
mateusz.snamina@gmail.com
bc47c87a39c08a404efcf0eeceb105e83f3fd456
0d653408de7c08f1bef4dfba5c43431897097a4a
/cmajor/system-x/kernel/Compression.cpp
264de192b4a91b7bd68a9d0e6b1778caad1c101e
[]
no_license
slaakko/cmajorm
948268634b8dd3e00f86a5b5415bee894867b17c
1f123fc367d14d3ef793eefab56ad98849ee0f25
refs/heads/master
2023-08-31T14:05:46.897333
2023-08-11T11:40:44
2023-08-11T11:40:44
166,633,055
7
2
null
null
null
null
UTF-8
C++
false
false
3,307
cpp
// ================================= // Copyright (c) 2022 Seppo Laakko // Distributed under the MIT license // ================================= #include <system-x/kernel/Compression.hpp> #include <system-x/kernel/IO.hpp> #include <system-x/kernel/Process.hpp> #include <system-x/machine/Processor.hpp> #include <system-x/machine/Machine.hpp> #include <system-x/machine/Memory.hpp> #include <soulng/util/DeflateStream.hpp> #include <soulng/util/MemoryReader.hpp> #include <algorithm> namespace cmsx::kernel { DecompressionFile::DecompressionFile(Process* process, uint64_t sourceBufferAddr, uint64_t count) : File("DECOMPRESSION") { compressedData = ReadProcessMemory(process, sourceBufferAddr, count); soulng::util::MemoryReader reader(compressedData.data(), 8); soulng::util::MemoryStream compressedMemoryStream(compressedData.data() + 8, std::max(static_cast<int64_t>(0), static_cast<int64_t>(compressedData.size()) - 8)); soulng::util::DeflateStream extractStream(soulng::util::CompressionMode::decompress, compressedMemoryStream); int64_t size = reader.ReadLong(); for (int64_t i = 0; i < size; ++i) { int x = extractStream.ReadByte(); if (x != -1) { decompressedMemoryStream.Write(static_cast<uint8_t>(x)); } } } void DecompressionFile::Close(cmsx::kernel::Process* process) { compressedData.clear(); delete this; } void DecompressionFile::GetData(Process* process, uint64_t targetBufferAddr, uint64_t count) { cmsx::machine::Memory& mem = process->GetProcessor()->GetMachine()->Mem(); mem.NCopy(decompressedMemoryStream.Content().data(), process->RV(), targetBufferAddr, count); } int32_t Decompress(Process* process, int64_t bufferAddr, int64_t count) { DecompressionFile* file = new DecompressionFile(process, bufferAddr, count); return process->GetFileTable().AddFile(file); } int64_t GetDecompressedDataSize(Process* process, int32_t dd) { ProcessFileTable& fileTable = process->GetFileTable(); File* file = fileTable.GetFile(dd); if (file->IsDecompressionFile()) { DecompressionFile* decompressionFile = static_cast<DecompressionFile*>(file); return decompressionFile->Size(); } else { throw SystemError(EBADF, std::to_string(dd) + " is not a decompression file descriptor", __FUNCTION__); } } void GetDecompressedData(Process* process, int32_t dd, int64_t bufferAddr, int64_t count) { ProcessFileTable& fileTable = process->GetFileTable(); File* file = fileTable.GetFile(dd); if (file->IsDecompressionFile()) { DecompressionFile* decompressionFile = static_cast<DecompressionFile*>(file); decompressionFile->GetData(process, bufferAddr, count); } else { throw SystemError(EBADF, std::to_string(dd) + " is not a decompression file descriptor", __FUNCTION__); } } void CloseDecompression(Process* process, int32_t dd) { ProcessFileTable& fileTable = process->GetFileTable(); File* file = fileTable.GetFile(dd); if (file->IsDecompressionFile()) { fileTable.CloseFile(dd, process); } else { throw SystemError(EBADF, std::to_string(dd) + " is not a decompression file descriptor", __FUNCTION__); } } } // namespace cmsx::kernel
[ "slaakko@gmail.com" ]
slaakko@gmail.com
f06e2f3aad424f2a3f51b052884a7a275e98443c
043932e98e00d1340b75b6163f4b08d2663449be
/AI.cpp
86c24d2c3d29c366227802b802429e95bf5e47c4
[]
no_license
shaammurali/conquest
2598ed0a05ebc64310daf130ea6153f67e72681e
5723888b111e42c79f3f3480ece03b1fb6f53f3b
refs/heads/master
2020-12-29T18:52:34.725029
2015-04-13T16:52:55
2015-04-13T16:52:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,157
cpp
#include "AI.h" #include "strategy.h" #include "aggressive.h" #include "defensive.h" #include "random.h" AI::AI(int id) { isComputer = true; playerID = id; name = "CPU"+to_string(id); int num = strat->getStrategy(); switch (num) { case 0: strat = new aggressive(); stratType = "aggressive"; break; case 1: strat = new defensive(); stratType = "defensive"; break; case 2: strat = new random(); stratType = "random"; break; } } AI::AI(int id, string inStrat) { int result; isComputer = true; playerID = id; name = "CPU"+to_string(id); if (inStrat == "aggressive") result = 0; else if (inStrat == "defensive") result = 1; else result = 2; switch (result) { case 0: strat = new aggressive(); stratType = "aggressive"; break; case 1: strat = new defensive(); stratType = "defensive"; break; case 2: strat = new random(); stratType = "random"; break; } } AI::AI() { isComputer = true; name = "CPU"; int num = strat->getStrategy(); switch (num) { case 0: strat = new aggressive(); break; case 1: strat = new defensive(); break; case 2: strat = new random(); break; } }
[ "mrj1m0thy4@gmail.com" ]
mrj1m0thy4@gmail.com
5f71bb965f106371bd8a433f2e7bd8715367f253
2efc948cd67ffd5457da77c785ffee418e14166a
/CPTTRN6.cpp
4de23e264db695228ed980be3504919e2ad62d48
[]
no_license
aguilarpgc/SPOJ
8d469c462a264fcda98007fe16a9b193612d61a0
302e910d58ec7f6388a1e9a25eb0bd36d2216868
refs/heads/master
2021-06-04T11:53:12.831106
2018-03-14T16:42:39
2018-03-14T16:42:39
30,810,821
6
3
null
null
null
null
UTF-8
C++
false
false
547
cpp
#include <iostream> using namespace std; int main() { int t; int l,c,h,w; cin >> t; int l1,c1; while (t--) { cin >> l >> c >> h >> w; l1 = h + (l * (h + 1)) ; c1 = w + (c * (w + 1)); for (int i = 1; i <= l1; i++){ for (int j = 1; j <= c1; j++){ if (i % (h + 1) == 0) { if (j % (w + 1) == 0) { printf("+"); } else { printf("-"); } } else if (j % (w + 1) == 0) { printf("|"); } else { printf("."); } } cout << endl; } cout << endl; } return 0; }
[ "aguilarpgc@gmail.com" ]
aguilarpgc@gmail.com
640fbbdb2381f2198c0b626bf191f70c3cf843f4
de3b508a5a5183c74221760344400e89c9f0c5fa
/work_1/work_1/SunArr_1.cpp
f2dd48f476af7262da0978ca9ee7be7fbc074e58
[]
no_license
eumenide/ALG_18
bf78dffb9ba872d5a9258388e1f509f1142340c4
2f7ee5da44fb6852ea64c59633e8f11a71262954
refs/heads/master
2020-04-18T22:09:19.067692
2019-01-27T10:57:51
2019-01-27T10:57:51
162,644,823
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
cpp
#include <iostream> #include <sstream> #include <vector> #include <deque> #include "function.h" using namespace std; void SunArr_1(){ string str; int left,right,num,counts,a; vector<int> vec; deque<int> qmax,qmin; getline(cin, str); stringstream input(str); while(input >> a){ vec.push_back(a); } cin >> num; counts = left = right = 0; while(left < vec.size()){ while(right < vec.size()){ while(!qmax.empty() && vec[right] >= vec[qmax.back()]){ qmax.pop_back(); } qmax.push_back(right); while(!qmin.empty() && vec[right] <= vec[qmin.back()]){ qmin.pop_back(); } qmin.push_back(right); if(vec[qmax.front()] - vec[qmin.front()] > num){ break; } right++; } if(left == qmax.front()){ qmax.pop_front(); } if(left == qmin.front()){ qmin.pop_front(); } counts += right - left; left++; } cout << (1 + vec.size()) * vec.size() / 2 - counts << endl; }
[ "eumescan@qq.com" ]
eumescan@qq.com
a6e5c5794aa0bc50068ff561d2b3e5fb50cee538
60c87069f3f70964f54b8515886f1a3deb1a4429
/qp_solver/include/qp_solver/pose_optimization/PoseOptimizationProblem.hpp
0cab11e3fbdf677c6b20168342c4e2f69aecf7e5
[]
no_license
HITSZ-LeggedRobotics/quadruped_locomotion
367ebbb420a8da629e8ce4f49c683e87a33e8621
5ec4feb3496348aa8d984c50c1cb9d7f854ac11e
refs/heads/master
2022-06-14T22:12:38.432967
2022-05-18T10:39:05
2022-05-18T10:39:05
177,237,609
6
5
null
2020-07-17T07:07:33
2019-03-23T03:05:33
C++
UTF-8
C++
false
false
888
hpp
/* * PoseOptimizationProblem.hpp * * Created on: Mar 23, 2017 * Author: Péter Fankhauser * Institute: ETH Zurich */ #pragma once #include "qp_solver/pose_optimization/PoseOptimizationObjectiveFunction.hpp" #include "qp_solver/pose_optimization/PoseOptimizationFunctionConstraints.hpp" //#include <numopt_common/ConstrainedNonlinearProblem.hpp> namespace free_gait { class PoseOptimizationProblem //: public numopt_common::ConstrainedNonlinearProblem { public: PoseOptimizationProblem(std::shared_ptr<PoseOptimizationObjectiveFunction> objectiveFunction, std::shared_ptr<PoseOptimizationFunctionConstraints> functionConstraints); virtual ~PoseOptimizationProblem(); std::shared_ptr<PoseOptimizationObjectiveFunction> objectiveFunction_; std::shared_ptr<PoseOptimizationFunctionConstraints> functionConstraints_; }; } /* namespace */
[ "wshy1995@outlook.com" ]
wshy1995@outlook.com
a7dfab01c62d251ccbc9518123d96e11a5b58067
2dddf7b3f4d6b6f41adb100bb6690d5f93810cde
/gmw/util/typedefs.h
f69c025ea0029d2f619ce43f862490391e8ce9f6
[ "MIT" ]
permissive
rlaishra/Privacy-Aware-Friends-Recommendation
234b7cde5300d6f9509299a8a4eba3b9b37ab214
a5757ef0b409bbcdebdb4e43b510a8d4d9070230
refs/heads/master
2020-03-27T19:55:47.354401
2018-09-01T18:18:44
2018-09-01T18:18:44
147,021,965
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
h
#ifndef __TYPEDEFS_H__BY_SGCHOI #define __TYPEDEFS_H__BY_SGCHOI // Modified by Haoyi Shi #ifdef WIN32 #include <WinSock2.h> #include <windows.h> typedef unsigned short USHORT; typedef int socklen_t; typedef long long INT64; #pragma comment(lib, "wsock32.lib") #define SleepMiliSec(x) Sleep(x) typedef long long INT64; #else //WIN32 typedef int BOOL; typedef unsigned long DWORD; typedef unsigned int UINT; typedef long LONG; typedef unsigned long ULONG; typedef unsigned short USHORT; typedef unsigned char BYTE; typedef long long INT64; #define FALSE 0 #define TRUE 1 #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> typedef int SOCKET; #define INVALID_SOCKET -1 #define SleepMiliSec(x) usleep((x)<<10) #endif// WIN32 #include <cstring> #include <string> #include <vector> #include <iostream> using namespace std; #endif //__TYPEDEFS_H__BY_SGCHOI
[ "rlaishra@syr.edu" ]
rlaishra@syr.edu
75dd791cf6e0f42b676e6043cd62dda3c6cc1380
a58738a702f389b1f6b5848dfdf92597b45f7f00
/BinarySearchTree.inl
d6df35d3e0228d5646a434f45a871ac1544ce71d
[]
no_license
janmarkusmilan/Vi-Editor
5135ae291b58ca8d09440fc89365a3642f9c53ae
565f84896bb32f7054a81bb0c1e8de13ac83df7d
refs/heads/master
2020-09-01T21:56:22.149756
2019-11-01T22:04:00
2019-11-01T22:04:00
219,069,015
0
0
null
null
null
null
UTF-8
C++
false
false
10,149
inl
#include "BinarySearchTree.h" #include "BinaryNode.h" #include <iostream> using namespace std; template<class ItemType> shared_ptr<BinaryNode<ItemType>> BinarySearchTree<ItemType>::placeNode(shared_ptr<BinaryNode<ItemType>> subTreePtr, shared_ptr<BinaryNode<ItemType>> newNodePtr) { if (subTreePtr == nullptr) return newNodePtr; else { if (subTreePtr->getItem() > newNodePtr->getItem()) subTreePtr->setLeftChildPtr(placeNode(subTreePtr->getLeftChildPtr(), newNodePtr)); else subTreePtr->setRightChildPtr(placeNode(subTreePtr->getRightChildPtr(), newNodePtr)); return subTreePtr; } // end if } // end placeNode template<class ItemType> shared_ptr<BinaryNode<ItemType>> BinarySearchTree<ItemType>::removeValue(shared_ptr<BinaryNode<ItemType>> subTreePtr, const ItemType target, bool& success) { if (subTreePtr == nullptr) { // Not found here success = false; return subTreePtr; } if (subTreePtr->getItem() == target) { // Item is in the root of some subtree subTreePtr = removeNode(subTreePtr); success = true; return subTreePtr; } else { if (subTreePtr->getItem() > target) { // Search the left subtree subTreePtr->setLeftChildPtr(removeValue(subTreePtr->getLeftChildPtr(), target, success)); } else { // Search the right subtree subTreePtr->setRightChildPtr(removeValue(subTreePtr->getRightChildPtr(), target, success)); } return subTreePtr; } // end if } // end removeValue template<class ItemType> shared_ptr<BinaryNode<ItemType>> BinarySearchTree<ItemType>::removeNode(shared_ptr<BinaryNode<ItemType>> nodePtr) { // Case 1) Node is a leaf - it is deleted // Case 2) Node has one child - parent adopts child // Case 3) Node has two children: // Traditional implementation: Find successor node. // Alternate implementation: Find successor value and replace node's value; // alternate does not need pass-by-reference if (nodePtr->isLeaf()) { nodePtr.reset(); return nodePtr; // delete and return nullptr } else if (nodePtr->getLeftChildPtr() == nullptr) // Has rightChild only { return nodePtr->getRightChildPtr(); } else if (nodePtr->getRightChildPtr() == nullptr) // Has left child only { return nodePtr->getLeftChildPtr(); } else // Has two children { // Traditional way to remove a value in a node with two children ItemType newNodeValue; nodePtr->setRightChildPtr(removeLeftmostNode(nodePtr->getRightChildPtr(), newNodeValue)); nodePtr->setItem(newNodeValue); return nodePtr; // Alernative way to remove a value in a node with two children; does not require pass-by-reference. // We need to check whether this right child has a left child. // This is similar to the base case in "findSuccessorValue" but we need to remove the // special case where the right child *is* the inorder successor /* shared_ptr<BinaryNode<ItemType>> myRightChildPtr = nodePtr->getRightChildPtr(); shared_ptr<BinaryNode<ItemType>> myLeftGrandChildPtr = myRightChildPtr->getLeftChildPtr(); // Special case - right child is successor if (myLeftGrandChildPtr == nullptr) { nodePtr->setItem(myRightChildPtr->getItem()); nodePtr->setRightChildPtr(removeNode(myRightChildPtr)); return nodePtr; } else { // Now we can recurse nodePtr->setItem(findSuccessorValue(nodePtr->getRightChildPtr())); return nodePtr; } // end if */ } // end if } // end removeNode template<class ItemType> shared_ptr<BinaryNode<ItemType>> BinarySearchTree<ItemType>::removeLeftmostNode(shared_ptr<BinaryNode<ItemType>> nodePtr, ItemType& inorderSuccessor) { if (nodePtr->getLeftChildPtr() == nullptr) { inorderSuccessor = nodePtr->getItem(); return removeNode(nodePtr); } else { nodePtr->setLeftChildPtr(removeLeftmostNode(nodePtr->getLeftChildPtr(), inorderSuccessor)); return nodePtr; } // end if } // end removeLeftmostNode /* template<class ItemType> ItemType BinarySearchTree<ItemType>::findSuccessorValue(shared_ptr<BinaryNode<ItemType>> subTreePtr) { shared_ptr<BinaryNode<ItemType>> myLeftChildPtr = subTreePtr->getLeftChildPtr(); if (myLeftChildPtr->getLeftChildPtr() == nullptr) { ItemType nodeItemValue = myLeftChildPtr->getItem(); subTreePtr->setLeftChildPtr(removeNode(myLeftChildPtr)); return nodeItemValue; } else { return findSuccessorValue(subTreePtr->getLeftChildPtr()); } // end if } // end findSuccessorValue */ // Override findNode because now we can use a binary search: template<class ItemType> shared_ptr<BinaryNode<ItemType>> BinarySearchTree<ItemType>::findNode(shared_ptr<BinaryNode<ItemType>> subTreePtr, const ItemType& target) const { // Uses a binary search if (subTreePtr == nullptr) return subTreePtr; // Not found else if (subTreePtr->getItem() == target) return subTreePtr; // Found else if (subTreePtr->getItem() > target) // Search left subtree return findNode(subTreePtr->getLeftChildPtr(), target); else // Search right subtree return findNode(subTreePtr->getRightChildPtr(), target); } // end findNode ////////////////////////////////////////////////////////////// // PUBLIC METHODS BEGIN HERE ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// // Constructor and Destructor Section ////////////////////////////////////////////////////////////// template<class ItemType> BinarySearchTree<ItemType>::BinarySearchTree() { } // end default constructor template<class ItemType> BinarySearchTree<ItemType>::BinarySearchTree(const ItemType& rootItem) : rootPtr(make_shared<BinaryNode<ItemType>>(rootItem, nullptr, nullptr)) { } // end constructor template<class ItemType> BinarySearchTree<ItemType>::BinarySearchTree(const BinarySearchTree<ItemType>& treePtr) { rootPtr = this->copyTree(treePtr.rootPtr); // Call inherited method } // end copy constructor template<class ItemType> BinarySearchTree<ItemType>::~BinarySearchTree() { this->destroyTree(rootPtr); // Call inherited method } // end destructor ////////////////////////////////////////////////////////////// // Public BinaryTreeInterface Methods Section ////////////////////////////////////////////////////////////// template<class ItemType> bool BinarySearchTree<ItemType>::isEmpty() const { return rootPtr == nullptr; } // end isEmpty template<class ItemType> int BinarySearchTree<ItemType>::getHeight() const { return this->getHeightHelper(rootPtr); // Call inherited method } // end getHeight template<class ItemType> int BinarySearchTree<ItemType>::getNumberOfNodes() const { return this->getNumberOfNodesHelper(rootPtr); // Call inherited method } // end getNumberOfNodes template<class ItemType> void BinarySearchTree<ItemType>::clear() { this->destroyTree(rootPtr); // Call inherited method rootPtr.reset(); } // end clear template<class ItemType> ItemType BinarySearchTree<ItemType>::getRootData() const throw(PrecondViolatedExcept) { if (isEmpty()) throw PrecondViolatedExcept("getRootData() called with empty tree."); return rootPtr->getItem(); } // end getRootData // Must override setRootData to disable its affect: template<class ItemType> void BinarySearchTree<ItemType>::setRootData(const ItemType& newItem) const throw(PrecondViolatedExcept) { throw PrecondViolatedExcept("Cannot change root value in a BST!"); } // end setRootData template<class ItemType> bool BinarySearchTree<ItemType>::add(const ItemType& newData) { auto newNodePtr = make_shared<BinaryNode<ItemType>>(newData); rootPtr = placeNode(rootPtr, newNodePtr); return true; } // end add template<class ItemType> bool BinarySearchTree<ItemType>::remove(const ItemType& target) { bool isSuccessful = false; // call may change isSuccessful rootPtr = removeValue(rootPtr, target, isSuccessful); return isSuccessful; } // end remove // Override getEntry to use our improved findNode: template<class ItemType> ItemType BinarySearchTree<ItemType>::getEntry(const ItemType& anEntry) const throw(NotFoundException) { shared_ptr<BinaryNode<ItemType>> nodeWithEntry = findNode(rootPtr, anEntry); if (nodeWithEntry == nullptr) throw NotFoundException("Entry not found in tree."); else return nodeWithEntry->getItem(); } // end getEntry // Override contains to use our improved findNode: template<class ItemType> bool BinarySearchTree<ItemType>::contains(const ItemType& anEntry) const { return (findNode(rootPtr, anEntry) != nullptr); // nullptr is same as false } // end contains ////////////////////////////////////////////////////////////// // Public Traversals Section ////////////////////////////////////////////////////////////// template<class ItemType> void BinarySearchTree<ItemType>::preorderTraverse(void visit(ItemType&)) const { this->preorder(visit, rootPtr); // Call inherited method } // end preorderTraverse template<class ItemType> void BinarySearchTree<ItemType>::inorderTraverse(void visit(ItemType&)) const { this->inorder(visit, rootPtr); // Call inherited method } // end inorderTraverse template<class ItemType> void BinarySearchTree<ItemType>::postorderTraverse(void visit(ItemType&)) const { this->postorder(visit, rootPtr); // Call inherited method } // end postorderTraverse ////////////////////////////////////////////////////////////// // Overloaded Operator ////////////////////////////////////////////////////////////// template<class ItemType> BinarySearchTree<ItemType>& BinarySearchTree<ItemType>:: operator=(const BinarySearchTree<ItemType>& rightHandSide) { if (!isEmpty()) clear(); this = copyTree(&rightHandSide); // Call inherited method return *this; } // end operator= // end BinarySearchTree.inl
[ "noreply@github.com" ]
janmarkusmilan.noreply@github.com
8c420bb7b575bf78ccc489e6c6f78751b7c35c5a
3600a432047413f3d571ec84cb93255cfb190212
/chapter_17/17.18_SmallestSuperSequence.cpp
a6dabe1fa0ecc80071b667085992632fd53101a5
[]
no_license
abhisehekkumr/ctci
d3e91e075ff8dd5cc1146db665b286b788cea0b5
cf57494972367dde5f2c761f02ca9cace29ed2de
refs/heads/master
2022-02-02T09:39:27.875720
2019-08-06T08:39:43
2019-08-06T08:39:43
197,932,422
0
0
null
null
null
null
UTF-8
C++
false
false
2,450
cpp
/* given two arrays one smaller and one longer find the smallest super subsequence in longer array resturn distance */ #include<iostream> #include<unordered_map> using namespace std; // elements will be in order void print(int bigger[], int n, int smaller[], int m, int element,int start = -1, int index = 0){ if(m == 0){ std::cout << start << " " << index-1 << '\n'; return; } if(n == 0) return; if(bigger[0] == smaller[0]){ if(smaller[0] == element) print(bigger+1,n-1,smaller+1,m-1,element,index,index+1); else print(bigger+1,n-1,smaller+1,m-1,element,start,index+1); } print(bigger+1,n-1,smaller,m,element,start,index+1); } int smallestSuperSequence(int bigger[], int smaller[], int n, int m){ unordered_map<int,bool> map; for(int i = 0; i < m; i++) map[smaller[i]] = true; int start = 0, end = 999999999; for(int i = 0; i < n - 2; i++){ bool found = true; if(map.count(bigger[i])){ int j; int count = 0; for(j = i; j < n; j++){ if(map.count(bigger[j])){ if(map[bigger[j]]){ map[bigger[j]] = false; count += 1; } else{ found = false; break; } } if(count == map.size()) break; } if(found){ if((end - start) > (j - i)){ start = i; end = j; std::cout << i << " " << j << '\n'; } } for(int j = 0; j < map.size(); j++) map[smaller[j]] = true; } } std::cout << start << " " << end << '\n'; return 0; } int main(){ int n; cin >> n; int smaller[n]; for(int i = 0; i < n; i++) cin >> smaller[i]; int m; cin >> m; int bigger[m]; for(int i = 0; i < m; i++) cin >> bigger[i]; //print(bigger,m,smaller,n,smaller[0]); std::cout << smallestSuperSequence(bigger,smaller,m,n) << '\n'; } /* 3 1 5 9 17 7 5 9 0 2 1 3 5 7 9 1 1 5 8 8 9 7 */
[ "abhishekak98148@gmail.com" ]
abhishekak98148@gmail.com
d1e6ad172e086b4e3727c6ea73ebc9b3d5b5f1f1
4dfa6232cf91f1c04d50809915078dc71fb371b4
/dnn/src/x86/convolution/avx/convolution_xcorr_fh3_avx.cpp
c4127c766eef76f0afb5b49cdf66b96b97c68728
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
hookex/MegEngine
81c0539a3247873bdabe0e6f22e265e22249e98a
47fd33880d2db3cae98c55911bb29328cdd5d7e4
refs/heads/master
2022-08-01T02:04:06.431689
2020-05-22T11:10:17
2020-05-22T11:10:17
250,200,281
1
0
NOASSERTION
2020-03-26T08:22:39
2020-03-26T08:22:39
null
UTF-8
C++
false
false
69,836
cpp
/** * \file dnn/src/x86/convolution/avx/convolution_xcorr_fh3_avx.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #define SIMD_H1 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ } \ } while (0) #define SIMD_H2 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ } \ } while (0) #define SIMD_H3 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ } \ } while (0) #define SIMD_H4 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ } \ } while (0) #define SIMD_H5 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ } \ } while (0) #define SIMD_H6 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ __m256 res5; \ res5 = _mm256_loadu_ps(dst_dd + 5 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 7 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res5 = _mm256_add_ps(res5, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ _mm256_storeu_ps(dst_dd + 5 * dst_w, res5); \ } \ } while (0) #define SIMD_H7 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ __m256 res5; \ res5 = _mm256_loadu_ps(dst_dd + 5 * dst_w); \ __m256 res6; \ res6 = _mm256_loadu_ps(dst_dd + 6 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 7 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 8 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res6 = _mm256_add_ps(res6, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ _mm256_storeu_ps(dst_dd + 5 * dst_w, res5); \ _mm256_storeu_ps(dst_dd + 6 * dst_w, res6); \ } \ } while (0) #define SIMD_H8 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ __m256 res5; \ res5 = _mm256_loadu_ps(dst_dd + 5 * dst_w); \ __m256 res6; \ res6 = _mm256_loadu_ps(dst_dd + 6 * dst_w); \ __m256 res7; \ res7 = _mm256_loadu_ps(dst_dd + 7 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 7 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 8 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 9 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res7 = _mm256_add_ps(res7, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ _mm256_storeu_ps(dst_dd + 5 * dst_w, res5); \ _mm256_storeu_ps(dst_dd + 6 * dst_w, res6); \ _mm256_storeu_ps(dst_dd + 7 * dst_w, res7); \ } \ } while (0) #define SIMD_H9 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ __m256 res5; \ res5 = _mm256_loadu_ps(dst_dd + 5 * dst_w); \ __m256 res6; \ res6 = _mm256_loadu_ps(dst_dd + 6 * dst_w); \ __m256 res7; \ res7 = _mm256_loadu_ps(dst_dd + 7 * dst_w); \ __m256 res8; \ res8 = _mm256_loadu_ps(dst_dd + 8 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 7 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 8 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 9 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 10 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res8 = _mm256_add_ps(res8, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ _mm256_storeu_ps(dst_dd + 5 * dst_w, res5); \ _mm256_storeu_ps(dst_dd + 6 * dst_w, res6); \ _mm256_storeu_ps(dst_dd + 7 * dst_w, res7); \ _mm256_storeu_ps(dst_dd + 8 * dst_w, res8); \ } \ } while (0) #define SIMD_H10 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ __m256 res5; \ res5 = _mm256_loadu_ps(dst_dd + 5 * dst_w); \ __m256 res6; \ res6 = _mm256_loadu_ps(dst_dd + 6 * dst_w); \ __m256 res7; \ res7 = _mm256_loadu_ps(dst_dd + 7 * dst_w); \ __m256 res8; \ res8 = _mm256_loadu_ps(dst_dd + 8 * dst_w); \ __m256 res9; \ res9 = _mm256_loadu_ps(dst_dd + 9 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 7 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 8 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 9 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res9 = _mm256_add_ps(res9, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 10 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res9 = _mm256_add_ps(res9, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 11 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res9 = _mm256_add_ps(res9, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ _mm256_storeu_ps(dst_dd + 5 * dst_w, res5); \ _mm256_storeu_ps(dst_dd + 6 * dst_w, res6); \ _mm256_storeu_ps(dst_dd + 7 * dst_w, res7); \ _mm256_storeu_ps(dst_dd + 8 * dst_w, res8); \ _mm256_storeu_ps(dst_dd + 9 * dst_w, res9); \ } \ } while (0) #define SIMD_H11 \ do { \ const size_t sh = dh; \ const float* src_d = src + sh * src_w; \ float* dst_d = dst + dh * dst_w; \ size_t dw = dst_w_beg; \ for (; dw < dst_w_end; dw += 8) { \ const size_t sw = dw; \ float* dst_dd = dst_d + dw; \ __m256 tmp0; \ __m256 tmp1; \ __m256 res0; \ res0 = _mm256_loadu_ps(dst_dd + 0 * dst_w); \ __m256 res1; \ res1 = _mm256_loadu_ps(dst_dd + 1 * dst_w); \ __m256 res2; \ res2 = _mm256_loadu_ps(dst_dd + 2 * dst_w); \ __m256 res3; \ res3 = _mm256_loadu_ps(dst_dd + 3 * dst_w); \ __m256 res4; \ res4 = _mm256_loadu_ps(dst_dd + 4 * dst_w); \ __m256 res5; \ res5 = _mm256_loadu_ps(dst_dd + 5 * dst_w); \ __m256 res6; \ res6 = _mm256_loadu_ps(dst_dd + 6 * dst_w); \ __m256 res7; \ res7 = _mm256_loadu_ps(dst_dd + 7 * dst_w); \ __m256 res8; \ res8 = _mm256_loadu_ps(dst_dd + 8 * dst_w); \ __m256 res9; \ res9 = _mm256_loadu_ps(dst_dd + 9 * dst_w); \ __m256 res10; \ res10 = _mm256_loadu_ps(dst_dd + 10 * dst_w); \ for (size_t fw = 0; fw < flt_w; ++fw) { \ const float* src_dd = src_d + sw + fw; \ __m256 vf0 = _mm256_broadcast_ss(&filter[0 * flt_w + fw]); \ __m256 vf1 = _mm256_broadcast_ss(&filter[1 * flt_w + fw]); \ __m256 vf2 = _mm256_broadcast_ss(&filter[2 * flt_w + fw]); \ tmp0 = _mm256_loadu_ps(src_dd + 0 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 1 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 2 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res0 = _mm256_add_ps(res0, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 3 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res1 = _mm256_add_ps(res1, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 4 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res2 = _mm256_add_ps(res2, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 5 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res3 = _mm256_add_ps(res3, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 6 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res4 = _mm256_add_ps(res4, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 7 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res5 = _mm256_add_ps(res5, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 8 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res6 = _mm256_add_ps(res6, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 9 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res9 = _mm256_add_ps(res9, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res7 = _mm256_add_ps(res7, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 10 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf0); \ res10 = _mm256_add_ps(res10, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res9 = _mm256_add_ps(res9, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res8 = _mm256_add_ps(res8, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 11 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf1); \ res10 = _mm256_add_ps(res10, tmp1); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res9 = _mm256_add_ps(res9, tmp1); \ tmp0 = _mm256_loadu_ps(src_dd + 12 * src_w); \ tmp1 = _mm256_mul_ps(tmp0, vf2); \ res10 = _mm256_add_ps(res10, tmp1); \ } \ _mm256_storeu_ps(dst_dd + 0 * dst_w, res0); \ _mm256_storeu_ps(dst_dd + 1 * dst_w, res1); \ _mm256_storeu_ps(dst_dd + 2 * dst_w, res2); \ _mm256_storeu_ps(dst_dd + 3 * dst_w, res3); \ _mm256_storeu_ps(dst_dd + 4 * dst_w, res4); \ _mm256_storeu_ps(dst_dd + 5 * dst_w, res5); \ _mm256_storeu_ps(dst_dd + 6 * dst_w, res6); \ _mm256_storeu_ps(dst_dd + 7 * dst_w, res7); \ _mm256_storeu_ps(dst_dd + 8 * dst_w, res8); \ _mm256_storeu_ps(dst_dd + 9 * dst_w, res9); \ _mm256_storeu_ps(dst_dd + 10 * dst_w, res10); \ } \ } while (0) #include <immintrin.h> #include <avxintrin.h> #include <algorithm> #include "../convolution_direct_special_cases.h" namespace megdnn { namespace x86 { namespace detail { void convolution_xcorr_fh3_avx(const float *src, const float *filter, float *dst, const size_t src_h, const size_t src_w, const size_t dst_h, const size_t dst_w, const size_t flt_w) { (void)src_h; const size_t dst_h_beg = 0; const size_t dst_h_end = dst_h; const size_t dst_w_beg = 0; const size_t dst_w_end = dst_w; size_t dh = dst_h_beg; for (; dh + 11 <= dst_h_end; dh += 11) { SIMD_H11; } switch (dst_h_end - dh) { case 1: SIMD_H1; break; case 2: SIMD_H2; break; case 3: SIMD_H3; break; case 4: SIMD_H4; break; case 5: SIMD_H5; break; case 6: SIMD_H6; break; case 7: SIMD_H7; break; case 8: SIMD_H8; break; case 9: SIMD_H9; break; case 10: SIMD_H10; break; } } } // namespace detail } // namespace x86 } // namespace megdnn #undef SIMD_H1 #undef SIMD_H2 #undef SIMD_H3 #undef SIMD_H4 #undef SIMD_H5 #undef SIMD_H6 #undef SIMD_H7 #undef SIMD_H8 #undef SIMD_H9 #undef SIMD_H10 #undef SIMD_H11
[ "megengine@megvii.com" ]
megengine@megvii.com
08f9e8190ef470919cc3998cfe86e6ece79f3398
9cbc0e36b1ca9875150fd86bda05537798cd0ec0
/main.cpp
9fd3f3d6dc3ef2d6731e06cc86935059f05923bc
[]
no_license
MyGitWk/Linear-Searchs
3e0d7b33adb92a123715440ea54d4e3513fed6a9
7d687e4f2e4636aa2bfb0ffcf104624d790f2af5
refs/heads/master
2021-01-14T06:02:24.306014
2020-02-24T01:32:00
2020-02-24T01:32:00
242,621,236
0
0
null
null
null
null
UTF-8
C++
false
false
836
cpp
// linearsearch #include <iostream> using namespace std; int linearSearchAlgorithm(int arrayElements[], int sizeOfArray, int searchValue) { for(int i = 0; i < sizeOfArray; i++) { if (searchValue == arrayElements[i]) { return i; } } return -1; } int main() { int a[] = {35, 63, 17, 41, 77, 26, 71, 53, 62, 14}; int valueEntered; cout << "Enter an integer: " << endl; cin >> valueEntered; int result = linearSearchAlgorithm(a, 10, valueEntered); if(result >= 0) { cout << "The number " << a[result] << " was found at the" " element with index # " << result << endl; } else { cout << "Sorry, the number " << valueEntered << " was not found. " << endl; } }
[ "noreply@github.com" ]
MyGitWk.noreply@github.com
de32f786003c06b81de3a8bcc61d974677025598
f44c08ce003a10a368a84300eaff55911f8c7857
/Ray Tracing/Optimized/Ray Tracing/hitable.h
f08088373e4ae2d121b7e23fcd24642b1116d832
[]
no_license
Benves-7/Raytracing
c5dcb0ecbef14fe9a44e58d11a06831bd01c7112
e16f9375bf8e85b6d9cc6fa7b25e51f68d59c1a2
refs/heads/master
2021-03-12T10:18:13.607928
2020-09-22T08:27:10
2020-09-22T08:27:10
246,611,438
0
0
null
null
null
null
UTF-8
C++
false
false
406
h
// // Created by benves-7 on 9/10/19. // #ifndef HITABLE_H #define HITABLE_H #include "ray.h" class material; struct hit_record { hit_record() { mat_ptr = NULL; } float t = 0.0f; vec3 p; vec3 normal; material *mat_ptr; }; class hitable { public: virtual ~hitable() = default; virtual bool hit(const ray& r, float t_min, float t_max, hit_record& rec) const = 0; }; #endif
[ "benjamin_gb_w@hotmail.com" ]
benjamin_gb_w@hotmail.com
f6cf3f49ef04844ffb6a58c27235375f05750477
a13e24b39fab4f5d9bc57d0bd5eb536c38a5eef1
/tools/CastorViewer/PrecompiledHeader.cpp
3fee3a86c36167c4b2ab5410c979907b127485bb
[ "MIT" ]
permissive
DragonJoker/Castor3D
2bbd0eeba403a37570bfc959d58a6c8a01429c60
32a2e4bc5c6ea0d0a27f3c58f8edb74fbc7e59ce
refs/heads/development
2023-09-04T15:46:36.438955
2023-08-30T05:37:14
2023-08-30T12:34:39
34,847,313
424
18
MIT
2023-09-14T11:10:10
2015-04-30T09:53:00
C++
UTF-8
C++
false
false
33
cpp
#include "PrecompiledHeader.hpp"
[ "dragonjoker59@hotmail.com" ]
dragonjoker59@hotmail.com
f8739db36d226d92c7b5d1dd0513c693520f4873
4c66c96fb4393bf494372b528fde7ff7b65613bc
/main.cpp
1b9f4f40e42f9dfa31012b0860419b077b3cab55
[]
no_license
Paxon96/Complex
93b1d5a06f4cc1fd3a9d32f44b1f404d94ef4cfb
92c80c12286e9f92e8bf095560f62f56d40a7202
refs/heads/master
2020-03-12T02:24:57.372479
2018-04-20T19:01:12
2018-04-20T19:01:12
130,401,615
0
0
null
null
null
null
UTF-8
C++
false
false
461
cpp
#include<iostream> #include<math.h> #include <stdlib.h> #include "complex.h" using namespace std; int main() { Complex c1(5,2), c2(3,-2); Complex c3(3.0,5.90), c4(1,1); Complex c5; c5 = 2 * c1; cout << c5<< endl; //cout<< amplituda(c3) << endl << faza(c3) << endl; //cout << c4 << endl << czRzecz(c2) << "\t" << czUro(c2) << endl; //cout<< amplituda(c3) << endl; c5 = c2 * c1; cout << c5<< endl; c5 = c3 + c4; cout << c5<< endl; return 0; }
[ "bwloczyk@gmail.com" ]
bwloczyk@gmail.com
ba5b268c6ad5465be3cae0843392ce4cdfc25b1f
ed953b899b3196ef2dfd576554c7e18372c05701
/tools/simulator/src/Object.h
172cac39d585b0aea6a03b5ba96ba010dce998e4
[]
no_license
thomaav/slamdunk
804408c1a0c507b65c88e2b2720e29b24a360942
322d61e49b1d637afa1ccf4830b42b2b1923c372
refs/heads/master
2020-04-11T12:16:21.235642
2018-11-27T14:06:56
2018-11-27T14:06:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
323
h
#pragma once #include "linmath.h" #include "Ray.h" #include "BBox.h" class Object { public: Object() noexcept; virtual ~Object(); virtual float GetIntersection(const Ray &ray); virtual vec3 GetNormalAt(const vec3 &intersectionPosition); virtual vec3 GetTexCoords(vec3 &normal, const vec3 &hitPoint); BBox bbox; };
[ "hallvste@stud.ntnu.no" ]
hallvste@stud.ntnu.no
f0d2b6d0d9959b0653c8b5e4cb76b884013996ba
8c976a35a194e40c50fbac564ed3d8e168dfabf9
/mainwindow.cpp
bf89e20b5333bdbf392c0f6affed8bd643174b15
[]
no_license
yarinmanjarres/interpretador2
8a5fc339cc0af9671d71714c49bb498118e569af
75c7300a1a9331ca8fbba776914776b2413b81d6
refs/heads/master
2021-08-26T06:41:29.339653
2017-11-21T23:34:06
2017-11-21T23:34:06
111,613,196
0
0
null
null
null
null
UTF-8
C++
false
false
3,768
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "QFileDialog" #include "QMessageBox" #include "QDebug" #include "lexer2.h" #include "parser2.h" #include <stdio.h> #include <iostream> #include <stdlib.h> #include "QDir" using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } bool MainWindow::on_actionGuardar_triggered() { if (curFile.isEmpty()){ return on_actionGuardar_triggered(); }else{ return saveFile(); } } bool MainWindow::on_actionGuardar_Como_triggered() { QString fileName = QFileDialog :: getSaveFileName( this, "TextEditor - Save as", "/home/diego/Documentos/SEMESTRE_VI/COMPILADORES/Taller_parser", "Text Files (*.txt):: All File (*.*) "); if(!fileName.isEmpty()){ curFile = fileName; return saveFile(); } return false; } bool MainWindow::saveFile() { QFile file(curFile); if(file.open(QFile::WriteOnly)){ file.write(ui->plainTextEdit->toPlainText().toUtf8()); return true; }else{ QMessageBox::warning( this, "TexEditor", tr("cannot write file %1. \nError: %2") .arg(curFile) .arg(file.errorString())); return false; } } bool MainWindow::maybesave() { if(ui->plainTextEdit->document()->isModified()){ QMessageBox :: StandardButton ret = QMessageBox :: warning( this, "TexEditor", tr("The Document has been Modified" "Do you want to save your changes?"), QMessageBox :: Yes | QMessageBox :: No | QMessageBox :: Cancel ); if(ret == QMessageBox :: Yes){ return on_actionGuardar_triggered(); }else if(ret == QMessageBox :: Cancel) return false; } return true; } void MainWindow::on_actionAbrir_Archivo_triggered() { if(maybesave()){ QString fileName = QFileDialog :: getOpenFileName( this, "TexEditor - Openfile", "/home/diego/Documentos/SEMESTRE_VI/COMPILADORES/Taller_parser", "Text Files (*.txt):: All File (*.*) "); if(!fileName.isEmpty()){ QFile file(fileName); if(file.open(QFile :: ReadOnly)){ ui->plainTextEdit->setPlainText(file.readAll()); }else{ QMessageBox :: warning( this, "TexEditor", tr("cannot write file %1. \nError: %2") .arg(fileName) .arg(file.errorString())); } } } } void MainWindow::on_actionNueva_clae_triggered() { return; } void MainWindow::on_actionCorrer_triggered() { Lexer c = Lexer() ; char NombreArchivo[50]; QString name = QFileInfo(curFile).fileName(); /* string name2 = name.toStdString(); for(int i=0; i < name2.length(); i++){ NombreArchivo[i] = name2[i]; }*/ qDebug()<<name; int resultado = c.lexer(name.toLocal8Bit().constData()); if(resultado == 1){ ui->textEdit->setText("No se puede leer el archivo."); return; } if(resultado == 2){ ui->textEdit->setText("Compilado con exito!"); return; } if(resultado == 3){ ui->textEdit->setText("Error Sintactico."); return; } ui->textEdit->setText("Error Sintactico."); }
[ "noreply@github.com" ]
yarinmanjarres.noreply@github.com
a65f16518e3b1daac5ad8c15d9535420ed0d28ce
2fc31c059c2339a550382f8f9d2ab42769abbb03
/Contributions/Aditya_199301262/strings.cpp
8c998c586c2b610e05565cec6617228feedd6faf
[]
no_license
mujacm/CPP
f7ab86a0dc427734a0047ff72e911b1e726e4b7b
b9f71aff4ef5ecc7703cf0d49e8517c040b0417c
refs/heads/main
2023-02-23T12:35:10.092364
2020-10-31T16:30:20
2020-10-31T16:30:20
307,752,203
2
39
null
2023-07-02T08:18:36
2020-10-27T15:54:24
C++
UTF-8
C++
false
false
768
cpp
/* Problem: Given a string, S , of length that is indexed from 0 to N-1 , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail). Note: 0 is considered to be an even index. Sample Input: MANIPAL Sample Output: MNPL AIA */ #include <vector> #include <iostream> #include <string> using namespace std; int main() { string str; cin>>str; for(unsigned j=0;j< str.length();j++) { if(j%2==0) cout<<str[j]; } cout<<" "; for(unsigned j=0;j< str.length();j++) { if(j%2!=0) cout<<str[j]; } return 0; }
[ "adityavinod333@gmail.com" ]
adityavinod333@gmail.com
c0bff10d52022e30ccd1f59fa48e0db0a30ab655
2d7575b7ed33465d4bfa2466efe09a49f96b1cd3
/modules/gpuarithm/test/test_precomp.hpp
faa0f5adbdbc2a17009ff3c20fa908da618b9ada
[]
no_license
Bustedblah/opencv
4c75724b4075cd5b784896da23e8ebe972318dc5
c0c575d68e0cd63329c311b101be4d24e9d89e0c
refs/heads/master
2021-01-18T06:41:23.920093
2013-09-20T07:08:09
2013-09-20T07:08:09
12,998,026
1
0
null
null
null
null
UTF-8
C++
false
false
2,677
hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wmissing-declarations" # if defined __clang__ || defined __APPLE__ # pragma GCC diagnostic ignored "-Wmissing-prototypes" # pragma GCC diagnostic ignored "-Wextra" # endif #endif #ifndef __OPENCV_TEST_PRECOMP_HPP__ #define __OPENCV_TEST_PRECOMP_HPP__ #include <functional> #include "opencv2/ts.hpp" #include "opencv2/ts/gpu_test.hpp" #include "opencv2/gpuarithm.hpp" #include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "cvconfig.h" #endif
[ "vlad.vinogradov@itseez.com" ]
vlad.vinogradov@itseez.com
58e9f05cca0cd85e67f7a822a676394807bf245d
9d621e7ad2960608d475b44a1a6426c95e7e8955
/Codeforces/236-A/236-A-34243096.cpp
7d6bdff3d5a920d157e5dc6d53498d21175fc544
[]
no_license
vijayphoenix/Competitive-programming
0c80a69135205c12f18e29292da77f073993590b
5332c6ac016a9dc1753a5e6737ef93f688b8a4f6
refs/heads/master
2020-04-22T17:52:12.882748
2019-02-13T18:16:25
2019-02-13T18:16:25
170,556,782
1
0
null
null
null
null
UTF-8
C++
false
false
302
cpp
#include <iostream> #include <algorithm> using namespace std; int main() { int a[26]={0}; int sum=0; char c; c=getchar(); while(c!='\n') { a[c%'a']=1; c=getchar(); } for(int i=0;i<26;i++) sum+=a[i]; (sum%2==0)?cout<<"CHAT WITH HER!":cout<<"IGNORE HIM!"; }
[ "cs17btech11040@iith.ac.in" ]
cs17btech11040@iith.ac.in
5f3ecff526c61239f7344177f26e12fa9f2d9ee3
2a30edf598cda428a10a344b37a2eb295c9e85db
/leetcode9_math.cpp
20ee9fd262a583253ea6cc386e00b7cec3de5979
[]
no_license
Jushelf/leetcode
75cacc91c79f3d8136bb7c8b1333a9b5926be6a5
a946b448d461df62bc354cae51ce3e4a6da111e0
refs/heads/main
2023-07-27T22:04:22.580770
2021-09-10T05:52:04
2021-09-10T05:52:04
404,959,887
0
0
null
null
null
null
UTF-8
C++
false
false
404
cpp
class Solution { public: bool isPalindrome(int x) { if(x < 0 || (x != 0 && x % 10 == 0)) { return false; } int s = 0; int r; while(s < x) { r = x % 10; x /= 10; s = s * 10 + r; } cout << "s: " << s << "x: " << x; return (s == x) || (s / 10 == x); } };
[ "noreply@github.com" ]
Jushelf.noreply@github.com
1845bd067686456457a1be30ffbdac8b5074f112
791faf5e1bb8db6ad1765b356304ccb1e04454fb
/TLX/Old Toki/Bab 2/2D - Soal Tambahan/1.cpp
bbede5ab9e70c5a9e3c164eaf8230960ad34466b
[]
no_license
ecojuntak/competitive-programming
77d5977b59c2ea19d0f3e366ce2b080332d6ac53
2d5522d75cf3d2652cf34a040752c64047319022
refs/heads/master
2021-01-25T09:45:11.388531
2018-02-28T17:57:44
2018-02-28T17:57:44
123,317,766
2
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
#include <bits/stdc++.h> using namespace std; int main() { long long int a,b,count; scanf("%lld",&a); for(int i=0;i<a;i++) { count = 0; scanf("%lld",&b); for(int j=1;j<=sqrt(b)+1;j++) { if(b%j==0) count++; if(count > 4) { printf("TIDAK\n"); break; } } if(count <= 4)printf("YA\n"); } return 0; }
[ "if415009@students.del.ac.id" ]
if415009@students.del.ac.id
8b6e9e6edcabf25f059a19ec878f51e35b258470
225b4c43e9ef623f2631e0372ed4aadcf3306331
/Core/Logger.h
e7f07fefac85eb10394f4979d6552913da348216
[]
no_license
mbaptist34/physics-engine
7999b1b165724625400fbd83b81e924eb29e5530
9df80da783be1a8fbb1dc2b528bdc72ed2afca35
refs/heads/master
2021-01-19T02:23:26.383357
2017-11-15T03:58:42
2017-11-15T03:58:42
59,861,629
0
0
null
null
null
null
UTF-8
C++
false
false
778
h
#ifndef ____Logger__ #define ____Logger__ #include <fstream> #include <string> #include "ProjectBuildSettings.h" //These are const ints so that we can binary and them const int LOG_APP = 1; const int LOG_CLIENT = 2; const int LOG_SERVER = 4; const int LOG_USER = 8; #define LOG_STRINGS 256 class Logger { private: Logger(); //Singleton, can't be instantiated. std::ofstream appLog; std::ofstream clientLog; std::ofstream serverLog; std::string logStrings[LOG_STRINGS]; bool loadStrings(); public: static Logger &Get(); bool Init(); void Write(int target, const char *msg, ...); void Write(int target, unsigned long msgID, ...); }; #define LOGGER Logger::Get() #endif /* defined(____Logger__) */
[ "mbaptist34@gmail.com" ]
mbaptist34@gmail.com
0ee7d5b7f5b1dc5437f287d631bf21a787f39ec1
1dc65fd957e4943d9acd7c78cfe769e236ff36df
/lesson07/app/src/main/jni/GLES2Lesson.h
9eee6e1a2ac6aa3b043341e4d9708c5b5603594e
[ "BSD-2-Clause" ]
permissive
JobsSteve/nehe-ndk-gles20
32d0579ceb16905acf1cd3043749dfe2779d0213
2e9bc30854a46465fa2cc23ec3d9e5f1b2cc1acf
refs/heads/master
2021-01-19T22:22:21.934339
2016-06-22T04:02:29
2016-06-22T04:02:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,558
h
// // Created by monty on 23/11/15. // #ifndef LESSON02_GLES2LESSON_H #define LESSON02_GLES2LESSON_H namespace odb { class GLES2Lesson { void fetchShaderLocations(); void setPerspective(); void prepareShaderProgram(); void clearBuffers(); void resetTransformMatrices(); void printVerboseDriverInformation(); void createVBOs(); void deleteVBOs(); void drawGeometry(const int vertexVbo, const int indexVbo, int vertexCount, const glm::mat4 &transform); GLuint createProgram(const char *pVertexSource, const char *pFragmentSource); GLuint loadShader(GLenum shaderType, const char *pSource); const static float cubeVertices[6 * 4 * 9]; const static unsigned short cubeIndices[6 * 6]; const static glm::vec4 ambientLightFullColor; const static glm::vec4 ambientLightOffColor; glm::mat4 cubeTransformMatrix; glm::mat4 projectionMatrix; GLint vertexAttributePosition; GLint modelMatrixAttributePosition; GLint samplerUniformPosition; GLint textureCoordinatesAttributePosition; GLint projectionMatrixAttributePosition; GLint normalAttributePosition; GLuint gProgram; GLuint textureId; //VBO stuff GLuint vboCubeVertexDataIndex; GLuint vboCubeVertexIndicesIndex; int *textureData; int textureWidth; int textureHeight; GLint currentFilter; float cubeRotationAngleYZ; float cubeRotationAngleXZ; glm::vec4 diffuseLightDirection; glm::vec4 diffuseLightColor; glm::vec4 ambientLightColor; GLint diffuseLightDirectionShaderLocation; GLint diffuseLightColorShaderLocation; GLint ambientLightColorShaderLocation; float rotationXZSpeed; float rotationYZSpeed; public: GLES2Lesson(); ~GLES2Lesson(); bool init(float w, float h, const std::string &vertexShader, const std::string &fragmentShader); void setTexture(int *bitmapData, int width, int height, int format); void render(); void shutdown(); void tick(); void toggleFiltering(); void toggleLightning(); void speedUpXZ(); void speedDownXZ(); void speedUpYZ(); void speedDownYZ(); void reset(); void setSpeeds(const glm::vec2 &param); }; } #endif //LESSON02_GLES2LESSON_H
[ "danielmonteiro@id.uff.br" ]
danielmonteiro@id.uff.br
cd4f0ffb070c58cf3c9a1a9c8b058ff13eb34791
29731c445e5bce0f7f894ca622c480aa059b7b5e
/Very_Final_Conquest/GameEngine/Main.cpp
fe7ca5844a38783a366a24e936589a1c58f9e0ee
[]
no_license
MrJangoBox/JugaadProjectC345
89a4ec69379e8fcdcadd1d0e73af73f4387925aa
5619af8302bf80848e653b605f7c12f3fa304e49
refs/heads/master
2021-01-13T02:06:19.385530
2015-04-15T10:56:00
2015-04-15T10:56:00
30,091,690
0
0
null
null
null
null
UTF-8
C++
false
false
956
cpp
#include<iostream> #include <time.h> #include "MainPlayPhase.h" #include "StartupPhase.h" #include "LoadData.h" using namespace std; int main() { srand((unsigned int)time(0)); cout << "\t\tRISK- GameEngine!" << endl; cout << "NOTE: This is a game for 2- 6 players only!\n" << endl; cout << "Choose the number of players : " << endl; int userInput = 0; cin >> userInput; //Valid input Check: while( (userInput < 2) || (userInput > 6) ) { if(userInput < 1) cout << userInput << " : Invalid number of players!\n" << endl; if(userInput == 1) cout << "You cannot play by yourself!\n" << endl; else if(userInput > 6) cout << userInput << "Maximum number of players in RISK is 6!\n"<< endl; cout << "INVALID! Try again :" << endl; cin >> userInput; } cout << "Intialising " << userInput << " players.\n" << endl; StartupPhase game = StartupPhase:: StartupPhase(userInput); game.StartGame(); system("PAUSE"); return 0; }
[ "D3t0ur@hotmail.com" ]
D3t0ur@hotmail.com
f60b9c0e024c50e3e50a4257f9b35522e5ee4c53
a6f6620f77874d8e5b461520d590d7bd40579e6b
/Documents/2_dev/of_v0.9.8_osx_release/apps/myApps/yaritoriOTS_rebooted/src/visual/MotionManager.cpp
87b4479472e77a1ef1d9c1beb5b009d94bf69212
[]
no_license
sonir/1504_weaverStorm
d4d764863415a94b282ba0da61ee635f1b9ee63b
0c49be280e767f0bbdcc991da0c6a6bf78c70158
refs/heads/master
2021-01-22T11:58:50.235473
2019-01-13T10:34:46
2019-01-13T10:34:46
33,766,016
0
0
null
null
null
null
UTF-8
C++
false
false
6,751
cpp
// // MotionManager.cpp // yaritori // // Created by Hana on 2018/01/05. // // #include "MotionManager.hpp" #include <cassert> MotionManager::MotionManager() { //Reset solo soloCount = 0; for(int i = 0; i < AG_MAX; i++) { isSolo[i] = false; soloTimers[i].ready(); } aspect = gismo.width_rate; setEvents(); } void MotionManager::initVbo() { shapeBuf.nodeNum = 0; shapeBuf.edgeNum = 0; shapeBuf.color = 0.0; nodeVbo.setAttributeData(shader.getAttributeLocation("point_size"), shapeBuf.pointSize, 1, VBO_VERTS_MAX, GL_DYNAMIC_DRAW); nodeVbo.setVertexData(shapeBuf.nodePos, VBO_VERTS_MAX, GL_DYNAMIC_DRAW); nodeVbo.setColorData(shapeBuf.nodeColors, VBO_VERTS_MAX, GL_DYNAMIC_DRAW); edgeVbo.setVertexData(shapeBuf.nodePos, VBO_EDGES_MAX, GL_DYNAMIC_DRAW); edgeVbo.setColorData(shapeBuf.edgeColors, VBO_EDGES_MAX, GL_DYNAMIC_DRAW); edgeVbo.setIndexData(shapeBuf.edgeIndices, VBO_EDGES_MAX, GL_DYNAMIC_DRAW); } void MotionManager::addNode(ofVec2f nodePos, float size) { shapeBuf.nodePos[shapeBuf.nodeNum] = nodePos; shapeBuf.pointSize[shapeBuf.nodeNum] = size; shapeBuf.nodeColors[shapeBuf.nodeNum] = shapeBuf.color; shapeBuf.nodeNum++; } void MotionManager::addEdgeIndices(int id_a, int id_b) { shapeBuf.edgeIndices[shapeBuf.edgeNum] = id_a; shapeBuf.edgeNum++; shapeBuf.edgeIndices[shapeBuf.edgeNum] = id_b; shapeBuf.edgeNum++; } void MotionManager::setColor(float c) { for(int i = 0; i < AG_MAX; i++){ agent[i].setColor(c); interactLine[i].setColor(c); } } void MotionManager::setEvents() { GismoManager& gismo = GismoManager::getInstance(); auto colorEvent = [&](void* args){ //<- keep this desctiption param_u* params = (param_u *)args; float c = params[0].fval; this->setColor(c); }; gismo.lambdaAdd("/agentColor", colorEvent); auto trembleEvent = [&](void* args){ //<- keep this desctiption param_u* params = (param_u *)args; bool enable = params[0].bval; if(enable) { this -> setTremble(ANIMATION_MODE_TREMBLE); } else { this -> setTremble(ANIMATION_MODE_NORMAL); } }; gismo.lambdaAdd("/tremble", trembleEvent); } void MotionManager::setShapes() { for(int i = 0; i < AG_MAX; i++){ agent[i].pShape = &pShapes[i]; agent[i].initVbo(); } } void MotionManager::solo(int _id, bool status, float duration) { if(status != 0) { addSolo(_id, duration); } else { deleteSolo(_id); } } void MotionManager::addSolo(int _id, float duration) { isSolo[_id] = true; soloTimers[_id].bang(duration * 1000.0); soloCount++; } void MotionManager::deleteSolo(int _id) { isSolo[_id] = false; soloCount--; soloTimers[_id].ready(); } void MotionManager::updateSolo() { soloCount = 0; for(int i = 0; i < AG_MAX; i++){ if(isSolo[i]) { float val = soloTimers[i].get(); if (1.0 <= val) { deleteSolo(i); } soloCount++; } } } void MotionManager::update() { updateSolo(); } void MotionManager::drawAll() { int count = gismo.agents.count; ag_t* agents = gismo.getAgents(); //sets agents pointer ag_t* ag; for(int i = 0; i < count; i++){ ag = agents; //Set agent address if(ag->active){ //square(ag->posi.x, ag->posi.y, ag->size, 0.0f, true); agent[i].pAg = ag; agent[i].move(ag->posi.x, ag->posi.y); agent[i].update(); agent[i].draw(); // ofSetColor(255, 0, 0); // ofDrawBitmapString(i, ag->posi.x * aspect * BASE_HEIGHT, ag->posi.y * BASE_HEIGHT); // ofDrawCircle(ag->posi.x * BASE_HEIGHT * aspect, ag->posi.y * BASE_HEIGHT, 3); //Draw interaction if(ag->interact_with != -1) { int targetID = ag->interact_with; ag_t* target = gismo.getAgent(targetID); if(ag->condition == CHASE && target->condition == RUN) { // lineManager.lineTo(i, agent[i].center.x, agent[i].center.y, agent[targetID].center.x, agent[targetID].center.y, agent[i].size); interactLine[i].myPos.x = agent[i].center.x; interactLine[i].myPos.y = agent[i].center.y; interactLine[i].lineTo(agent[targetID].center.x, agent[targetID].center.y, agent[i].size); } } } agents++; } // lineManager.draw(); } void MotionManager::drawSolo() { int count = gismo.agents.count; ag_t* agents = gismo.getAgents(); //sets agents pointer ag_t* ag; for(int i =0; i < count; i++){ ag = &agents[i]; if(ag->active) { agent[i].pAg = ag; agent[i].move(ag->posi.x, ag->posi.y); agent[i].update(); if(isSolo[i]) { agent[i].draw(); //Draw Interaction if(ag->interact_with != -1) { int targetID = ag->interact_with; ag_t* target = gismo.getAgent(targetID); if(ag->condition == CHASE && target->condition == RUN) { // lineManager.lineTo(i, agent[i].center.x, agent[i].center.y, agent[targetID].center.x, agent[targetID].center.y, agent[i].size); interactLine[i].myPos.x = agent[i].center.x; interactLine[i].myPos.y = agent[i].center.y; interactLine[i].lineTo(agent[targetID].center.x, agent[targetID].center.y, agent[i].size); } } } } //agents++; } // lineManager.draw(); } void MotionManager::draw() { if(soloCount == 0) { drawAll(); } else { drawSolo(); } // ofSetColor(ofFloatColor(color)); // nodeVbo.updateVertexData(vbo.nodePos, vbo.nodeNum); // nodeVbo.updateColorData(vbo.nodeColors, vbo.nodeNum); // nodeVbo.draw(GL_POINTS, 0, vbo.nodeNum); } bool MotionManager::isSoloMode() { bool result = false; if (soloCount == 0) { result = false; } else { result = true; } return result; } void MotionManager::setTremble(animation_mode_e state) { for(int i = 0; i < AG_MAX; i++) { agent[i].animationMode = state; } }
[ "isana@sonir.jp" ]
isana@sonir.jp
a4e4d24189cbaf65645c8cc11a039364ea1a662b
57774e3ee8b1cd6b96aac2169f8c8945f6e67fa6
/ex03/ZombieHorde.cpp
2371d27c1a8b2f91739b66c76e2072f74978bd34
[]
no_license
HyoungHoKim/cpp_module_01
390013e57d28d50c5ddbd0d71c1336da6386d78a
5fb75cb82790162509cfc8002e78fdfd69e977d4
refs/heads/master
2023-05-27T13:53:49.274489
2021-06-10T03:40:55
2021-06-10T03:40:55
373,777,222
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include "ZombieHorde.hpp" ZombieHorde::ZombieHorde(int _n) { std::string name_pool[8] = { "red", "blue", "green", "yellow", "pink", "black", "white", "rainbow" }; this->n = _n; this->zombie = new Zombie[n]; int num; srand((unsigned int)time(NULL)); for (int i = 0; i < this->n; i++) { num = rand() % 8; zombie[i].set_zombie_type_name("ZombieHorde", name_pool[num]); zombie[i].announce(); } } ZombieHorde::~ZombieHorde() { delete[] this->zombie; }
[ "dkdemfp2@naver.com" ]
dkdemfp2@naver.com
7f0752926ff184aef9b145c375903c5d1ae6249b
cb24f64c0eee77f80ef07538e845a6278b224214
/ui/ofxSITextInput.h
da00a4cb726e9d1295242e926f1768a6ae201431
[]
no_license
martial/ofxSuperInterface
34c076ec2a522543da159010ff925c121337354a
c1f8e638a9a7d3374d580195cc2d12ae9fc5415d
refs/heads/master
2021-01-01T20:48:54.464267
2012-04-04T13:47:54
2012-04-04T13:47:54
2,333,060
3
0
null
null
null
null
UTF-8
C++
false
false
806
h
// // ofxSITextInput.h // superInterface // // Ported from code by by Elliot Woods on 12/09/2011. // Copyright 2011 Kimchi and Chips. // MIT license #ifndef SUPINTSTXTINPUT #define SUPINTSTXTINPUT #include "ofMain.h" #include "ofxSIComponent.h" #include "ofxSISwitch.h" class ofxSITextInput : public ofxSISwitch { public : ofxSITextInput(); void setup(ofxSuperInterface * mom, int xGridPos, int yGridPos, int wGridSize, int hGridSize, string label = "inputTxt"); void update(); void draw(); private: void keyPressedEvent(ofKeyEventArgs &a); void keyPressed(int key); void onRollOut(); void onRollOver(); ofRectangle getBoundingBox(); string text; int position; int marginLeft; }; #endif
[ "martialou@gmail.com" ]
martialou@gmail.com
b509c21e88351b33696e4fe8a236eebc7e7569a8
4fcc010579218a20d2ff59bcb9f2c688a354c05b
/MeKaSlug/One_BS_Cover.h
b3e3b40e053e0df294290f45c0deca773c138cd2
[]
no_license
hki2345/MetalSlug
ef6bdc646800d2f14e242cd7370e44cb6d18145c
ecf3c220e78452288abab5e5b4eee86d93b27343
refs/heads/master
2020-03-30T03:30:22.479081
2019-04-01T10:40:11
2019-04-01T10:40:11
150,691,841
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
474
h
#pragma once #include "TheOne.h" class Alpha_Renderer; class One_BS_Cover : public TheOne { private: Alpha_Renderer* BSC; float AlphaTime; float AlphaSpeed; int Alpha; bool Fade; bool FadeCheck; public: // false ¸é ¾Æ¿ô - true ¸é ÀÎ bool& fade() { return Fade; } bool& fade_check() { return FadeCheck; } void Init_FadeIn(const bool& _End = false); void Init_FadeOut(); void Init(); void Update(); public: One_BS_Cover(); ~One_BS_Cover(); };
[ "hki2345@users.noreply.github.com" ]
hki2345@users.noreply.github.com
92949815a367dbe76215d7dfa06dec395c35cdbb
f9034f7517c8ed650b2ae921cc1d6a5f6ee9851c
/DragonFly VOS/TXP-VOS/Old/System/Applications/text editor/textedit/StdAfx.cpp
ba3da7fb4eff97d66410990ba976dd4760b1b852
[]
no_license
tophatyouaredoomed/The-Toppest-of-Hats
e532ea6eb9810cbed92a3cc491fe3a5cae8ed48b
83c7237cff1ee8271090fdf018fd966e78a0db7b
refs/heads/master
2020-03-19T10:49:14.037308
2018-06-07T01:23:19
2018-06-07T01:23:19
136,403,391
0
0
null
null
null
null
UTF-8
C++
false
false
202
cpp
// stdafx.cpp : source file that includes just the standard includes // TextEdit.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "kevin51jiang@email.com" ]
kevin51jiang@email.com
97e35ed2e93b88af1e91e6f7344f533dc723fe2b
297497957c531d81ba286bc91253fbbb78b4d8be
/third_party/libwebrtc/modules/desktop_capture/win/dxgi_output_duplicator.h
20ef3fc865ccf7691fbb11f9681ef93fd4ce7d13
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
2,795
h
#ifndef MODULES_DESKTOP_CAPTURE_WIN_DXGI_OUTPUT_DUPLICATOR_H_ #define MODULES_DESKTOP_CAPTURE_WIN_DXGI_OUTPUT_DUPLICATOR_H_ #include <comdef.h> #include <dxgi.h> #include <dxgi1_2.h> #include <wrl/client.h> #include <memory> #include <string> #include <vector> #include "modules/desktop_capture/desktop_frame_rotation.h" #include "modules/desktop_capture/desktop_geometry.h" #include "modules/desktop_capture/desktop_region.h" #include "modules/desktop_capture/shared_desktop_frame.h" #include "modules/desktop_capture/win/d3d_device.h" #include "modules/desktop_capture/win/dxgi_context.h" #include "modules/desktop_capture/win/dxgi_texture.h" #include "rtc_base/thread_annotations.h" namespace webrtc { class DxgiOutputDuplicator { public: using Context = DxgiOutputContext; DxgiOutputDuplicator(const D3dDevice& device, const Microsoft::WRL::ComPtr<IDXGIOutput1>& output, const DXGI_OUTPUT_DESC& desc); DxgiOutputDuplicator(DxgiOutputDuplicator&& other); ~DxgiOutputDuplicator(); bool Initialize(); bool Duplicate(Context* context, DesktopVector offset, SharedDesktopFrame* target); DesktopRect desktop_rect() const { return desktop_rect_; } const std::string& device_name() const { return device_name_; } void Setup(Context* context); void Unregister(const Context* const context); int64_t num_frames_captured() const; void TranslateRect(const DesktopVector& position); private: void DetectUpdatedRegion(const DXGI_OUTDUPL_FRAME_INFO& frame_info, DesktopRegion* updated_region); bool DoDetectUpdatedRegion(const DXGI_OUTDUPL_FRAME_INFO& frame_info, DesktopRegion* updated_region); void LogMouseCursor(const DXGI_OUTDUPL_FRAME_INFO& frame_info); bool ReleaseFrame(); bool DuplicateOutput(); DesktopRect GetTranslatedDesktopRect(DesktopVector offset) const; DesktopRect GetUntranslatedDesktopRect() const; void SpreadContextChange(const Context* const context); DesktopSize desktop_size() const; const D3dDevice device_; const Microsoft::WRL::ComPtr<IDXGIOutput1> output_; const std::string device_name_; DesktopRect desktop_rect_; Microsoft::WRL::ComPtr<IDXGIOutputDuplication> duplication_; DXGI_OUTDUPL_DESC desc_; std::vector<uint8_t> metadata_; std::unique_ptr<DxgiTexture> texture_; Rotation rotation_; DesktopSize unrotated_size_; std::vector<Context*> contexts_; std::unique_ptr<SharedDesktopFrame> last_frame_; DesktopVector last_frame_offset_; int64_t num_frames_captured_ = 0; }; } #endif
[ "mcastelluccio@mozilla.com" ]
mcastelluccio@mozilla.com
49b39137442e6040d4a424d00ed54605cf22def9
a82dfb61b17fa66b9c75fe871401cff77aa77f56
/libmcell/api/rng_state.cpp
1c5b6da8c9e5869ca21e8ab6a09388ae360a85ad
[ "MIT" ]
permissive
mcellteam/mcell
49ca84048a091de8933adccc083d31b7bcb1529e
3920aec22c55013b78f7d6483b81f70a0d564d22
refs/heads/master
2022-12-23T15:01:51.931150
2021-09-29T16:49:14
2021-09-29T16:49:14
10,253,341
29
12
NOASSERTION
2021-07-08T01:56:40
2013-05-23T20:59:54
C++
UTF-8
C++
false
false
935
cpp
/****************************************************************************** * * Copyright (C) 2020 by * The Salk Institute for Biological Studies * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ******************************************************************************/ #include "api/rng_state.h" #include "rng.h" using namespace std; namespace MCell { namespace API { RngState::RngState(const rng_state& rng) { assert(RNG_SIZE == RANDSIZ); randcnt = rng.randcnt; aa = rng.aa; bb = rng.bb; cc = rng.cc; cc = rng.cc; std::copy(&rng.randrsl[0], &rng.randrsl[RANDSIZ], std::back_inserter(randslr)); std::copy(&rng.mm[0], &rng.mm[RANDSIZ], std::back_inserter(mm)); rngblocks = rng.rngblocks; // counter for simulation stats, does not affect simulation } } // namespace API } // namespace MCell
[ "ahusar@salk.edu" ]
ahusar@salk.edu
6bf26a8a01904870d6b747ee934eac6b077d2074
1aa084b739cdbd9fd8b17ba73db3336550bb5a21
/loadgraph/mnist_keras.cc
44d1fd592bc9b9a7ed5bfaf4a25ad45181a09cb0
[ "MIT" ]
permissive
yukiB/tf-keras-speed-test
162f4907741bb85350ab861d360096d4fbc032c3
5069b03c2e980c78c0c708466387dbcd1c39ba93
refs/heads/master
2020-05-27T21:16:12.891031
2017-03-04T07:36:32
2017-03-04T07:36:32
83,648,178
5
3
null
null
null
null
UTF-8
C++
false
false
7,015
cc
// ************************************************************************** // MIT License // // Copyright (c) [2016-2018] [Jacky-Tung] // (2017 convert to keras conv example by YukiB) // // 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. // *************************************************************************** // --------------------------------------------------------------------------------- // The mnist.cc is a example to show how to use tensorflow c++ api to load the graph // and do the prediction. Based on "jim-fleming/loading a tensorflow graph with the // c plus api", I add much more complicate example. After finish reading the code, I // hope you can understand // 1. how to load graph // 2. how to declare a tensor and put data to tensor correctly // 3. how to read output tensor and do the prediction // // Reference: // 1. load mnist data is reference by https://github.com/krck/MNIST_Loader // 2. how to use tensorflow c++ api to load the graph is reference by // https://medium.com/jim-fleming/loading-a-tensorflow-graph-with-the-c-api-4caaff88463f#.chz3r27xt // --------------------------------------------------------------------------------- #include "tensorflow/core/public/session.h" #include "tensorflow/core/platform/env.h" #include "MNIST.h" #include <iostream> #include <chrono> #include <fstream> #include <string> #include <vector> #include <sstream> using namespace std; using namespace chrono; using namespace tensorflow; int main(int argc, char* argv[]) { std::chrono::system_clock::time_point total_start; total_start = std::chrono::system_clock::now(); // Initialize a tensorflow session cout << "start initalize session" << "\n"; Session* session; Status status = NewSession(SessionOptions(), &session); if (!status.ok()) { cout << status.ToString() << "\n"; return 1; } const char* file_name; const char* default_file_name = "./frozen_graph_keras.pb"; const char* input_name; const char* default_input_name = "input"; const char* output_name; const char* default_output_name = "Softmax"; if (argc == 4) { file_name = argv[1]; input_name = argv[2]; output_name = argv[3]; } else { file_name = default_file_name; input_name = default_input_name; output_name = default_output_name; } cout << "load " << file_name << endl; // Read in the protobuf graph we exported // (The path seems to be relative to the cwd. Keep this in mind // when using `bazel run` since the cwd isn't where you call // `bazel run` but from inside a temp folder.) GraphDef graph_def; status = ReadBinaryProto(Env::Default(), file_name, &graph_def); if (!status.ok()) { cout << status.ToString() << "\n"; return 1; } cout << "loaded graph" << "\n"; // Add the graph to the session status = session->Create(graph_def); if (!status.ok()) { cout << status.ToString() << "\n"; return 1; } cout << "preparing input data..." << endl; // config setting int imageDim = 784; int nTests = 10000; // Setup inputs and outputs: Tensor x(DT_FLOAT, TensorShape({nTests, imageDim})); MNIST mnist = MNIST("./MNIST_data/"); auto dst = x.flat<float>().data(); for (int i = 0; i < nTests; i++) { auto img = mnist.testData.at(i).pixelData; std::copy_n(img.begin(), imageDim, dst); dst += imageDim; } cout << "data is ready" << endl; vector<pair<string, Tensor>> inputs = { {input_name, x} }; cout << "run test" << endl; std::chrono::system_clock::time_point start, end; start = std::chrono::system_clock::now(); // The session will initialize the outputs vector<Tensor> outputs; // Run the session, evaluating our "softmax" operation from the graph status = session->Run(inputs, {output_name}, {}, &outputs); if (!status.ok()) { cout << status.ToString() << "\n"; return 1; }else{ cout << "Success load graph !! " << "\n"; } // start compute the accuracy, // arg_max is to record which index is the largest value after // computing softmax, and if arg_max is equal to testData.label, // means predict correct. int nHits = 0; for (vector<Tensor>::iterator it = outputs.begin() ; it != outputs.end(); ++it) { auto items = it->shaped<float, 2>({nTests, 10}); // 10 represent number of class for(int i = 0 ; i < nTests ; i++){ int arg_max = 0; float val_max = items(i, 0); for (int j = 0; j < 10; j++) { if (items(i, j) > val_max) { arg_max = j; val_max = items(i, j); } } if (arg_max == mnist.testData.at(i).label) { nHits++; } } } float accuracy = (float)nHits/nTests; cout << "accuracy is : " << accuracy << ", and Done!!" << "\n"; end = std::chrono::system_clock::now(); double elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count(); cout << "elapsed time " << elapsed / 1000.0 << "[msec]" << endl; // Predition test start = std::chrono::system_clock::now(); for (int i = 0; i < nTests; i++) { Tensor minix(DT_FLOAT, TensorShape({1, imageDim})); auto dst = minix.flat<float>().data(); auto img = mnist.testData.at(i).pixelData; std::copy_n(img.begin(), imageDim, dst); vector<pair<string, Tensor>> miniInputs = { {input_name, minix} }; vector<Tensor> miniOutputs; status = session->Run(miniInputs, {output_name}, {}, &miniOutputs); if (!status.ok()) { cout << status.ToString() << "\n"; return 1; } } end = std::chrono::system_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count(); cout << "elapsed time for " << nTests << " prediction " << elapsed / 1000.0 << "[msec]" << endl; double total_elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end-total_start).count(); cout << "total elapsed time " << total_elapsed / 1000.0 << "[msec]" << endl; return 0; }
[ "yuki@xcoo.jp" ]
yuki@xcoo.jp