blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
a3994fdfca21d15947d83171d92fd59c67629a74
dcdf8a7edb8a765707459a540997750402f65bea
/src/zpiv/zpivtracker.cpp
63ea9b38b84e3e38b1caa1ac2b3d0419bdab0225
[ "MIT" ]
permissive
ifinmakassar/BitalGO
a313fa0e2015cc02fa3dc8d63d8d3a692dd8b019
f8f5e126a7c808f72ff85b32e28c09a45fe684ca
refs/heads/master
2022-04-06T12:33:49.209408
2020-03-16T06:15:12
2020-03-16T06:15:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,696
cpp
// Copyright (c) 2018 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <zpiv/deterministicmint.h> #include "zpivtracker.h" #include "util.h" #include "sync.h" #include "main.h" #include "txdb.h" #include "walletdb.h" #include "zpiv/accumulators.h" #include "zpiv/zpivwallet.h" #include "witness.h" using namespace std; CzALGTracker::CzALGTracker(std::string strWalletFile) { this->strWalletFile = strWalletFile; mapSerialHashes.clear(); mapPendingSpends.clear(); fInitialized = false; } CzALGTracker::~CzALGTracker() { mapSerialHashes.clear(); mapPendingSpends.clear(); } void CzALGTracker::Init() { //Load all CZerocoinMints and CDeterministicMints from the database if (!fInitialized) { ListMints(false, false, true); fInitialized = true; } } bool CzALGTracker::Archive(CMintMeta& meta) { if (mapSerialHashes.count(meta.hashSerial)) mapSerialHashes.at(meta.hashSerial).isArchived = true; CWalletDB walletdb(strWalletFile); CZerocoinMint mint; if (walletdb.ReadZerocoinMint(meta.hashPubcoin, mint)) { if (!CWalletDB(strWalletFile).ArchiveMintOrphan(mint)) return error("%s: failed to archive zerocoinmint", __func__); } else { //failed to read mint from DB, try reading deterministic CDeterministicMint dMint; if (!walletdb.ReadDeterministicMint(meta.hashPubcoin, dMint)) return error("%s: could not find pubcoinhash %s in db", __func__, meta.hashPubcoin.GetHex()); if (!walletdb.ArchiveDeterministicOrphan(dMint)) return error("%s: failed to archive deterministic ophaned mint", __func__); } LogPrintf("%s: archived pubcoinhash %s\n", __func__, meta.hashPubcoin.GetHex()); return true; } bool CzALGTracker::UnArchive(const uint256& hashPubcoin, bool isDeterministic) { CWalletDB walletdb(strWalletFile); if (isDeterministic) { CDeterministicMint dMint; if (!walletdb.UnarchiveDeterministicMint(hashPubcoin, dMint)) return error("%s: failed to unarchive deterministic mint", __func__); Add(dMint, false); } else { CZerocoinMint mint; if (!walletdb.UnarchiveZerocoinMint(hashPubcoin, mint)) return error("%s: failed to unarchivezerocoin mint", __func__); Add(mint, false); } LogPrintf("%s: unarchived %s\n", __func__, hashPubcoin.GetHex()); return true; } CMintMeta CzALGTracker::Get(const uint256 &hashSerial) { if (!mapSerialHashes.count(hashSerial)) return CMintMeta(); return mapSerialHashes.at(hashSerial); } CMintMeta CzALGTracker::GetMetaFromPubcoin(const uint256& hashPubcoin) { for (auto it : mapSerialHashes) { CMintMeta meta = it.second; if (meta.hashPubcoin == hashPubcoin) return meta; } return CMintMeta(); } bool CzALGTracker::GetMetaFromStakeHash(const uint256& hashStake, CMintMeta& meta) const { for (auto& it : mapSerialHashes) { if (it.second.hashStake == hashStake) { meta = it.second; return true; } } return false; } CoinWitnessData* CzALGTracker::GetSpendCache(const uint256& hashStake) { AssertLockHeld(cs_spendcache); if (!mapStakeCache.count(hashStake)) { std::unique_ptr<CoinWitnessData> uptr(new CoinWitnessData()); mapStakeCache.insert(std::make_pair(hashStake, std::move(uptr))); return mapStakeCache.at(hashStake).get(); } return mapStakeCache.at(hashStake).get(); } bool CzALGTracker::ClearSpendCache() { AssertLockHeld(cs_spendcache); if (!mapStakeCache.empty()) { mapStakeCache.clear(); return true; } return false; } std::vector<uint256> CzALGTracker::GetSerialHashes() { vector<uint256> vHashes; for (auto it : mapSerialHashes) { if (it.second.isArchived) continue; vHashes.emplace_back(it.first); } return vHashes; } CAmount CzALGTracker::GetBalance(bool fConfirmedOnly, bool fUnconfirmedOnly) const { CAmount nTotal = 0; //! zerocoin specific fields std::map<libzerocoin::CoinDenomination, unsigned int> myZerocoinSupply; for (auto& denom : libzerocoin::zerocoinDenomList) { myZerocoinSupply.insert(make_pair(denom, 0)); } { //LOCK(cs_pivtracker); // Get Unused coins for (auto& it : mapSerialHashes) { CMintMeta meta = it.second; if (meta.isUsed || meta.isArchived) continue; bool fConfirmed = ((meta.nHeight < chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) && !(meta.nHeight == 0)); if (fConfirmedOnly && !fConfirmed) continue; if (fUnconfirmedOnly && fConfirmed) continue; nTotal += libzerocoin::ZerocoinDenominationToAmount(meta.denom); myZerocoinSupply.at(meta.denom)++; } } if (nTotal < 0 ) nTotal = 0; // Sanity never hurts return nTotal; } CAmount CzALGTracker::GetUnconfirmedBalance() const { return GetBalance(false, true); } std::vector<CMintMeta> CzALGTracker::GetMints(bool fConfirmedOnly) const { vector<CMintMeta> vMints; for (auto& it : mapSerialHashes) { CMintMeta mint = it.second; if (mint.isArchived || mint.isUsed) continue; bool fConfirmed = (mint.nHeight < chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()); if (fConfirmedOnly && !fConfirmed) continue; vMints.emplace_back(mint); } return vMints; } //Does a mint in the tracker have this txid bool CzALGTracker::HasMintTx(const uint256& txid) { for (auto it : mapSerialHashes) { if (it.second.txid == txid) return true; } return false; } bool CzALGTracker::HasPubcoin(const CBigNum &bnValue) const { // Check if this mint's pubcoin value belongs to our mapSerialHashes (which includes hashpubcoin values) uint256 hash = GetPubCoinHash(bnValue); return HasPubcoinHash(hash); } bool CzALGTracker::HasPubcoinHash(const uint256& hashPubcoin) const { for (auto it : mapSerialHashes) { CMintMeta meta = it.second; if (meta.hashPubcoin == hashPubcoin) return true; } return false; } bool CzALGTracker::HasSerial(const CBigNum& bnSerial) const { uint256 hash = GetSerialHash(bnSerial); return HasSerialHash(hash); } bool CzALGTracker::HasSerialHash(const uint256& hashSerial) const { auto it = mapSerialHashes.find(hashSerial); return it != mapSerialHashes.end(); } bool CzALGTracker::UpdateZerocoinMint(const CZerocoinMint& mint) { if (!HasSerial(mint.GetSerialNumber())) return error("%s: mint %s is not known", __func__, mint.GetValue().GetHex()); uint256 hashSerial = GetSerialHash(mint.GetSerialNumber()); //Update the meta object CMintMeta meta = Get(hashSerial); meta.isUsed = mint.IsUsed(); meta.denom = mint.GetDenomination(); meta.nHeight = mint.GetHeight(); mapSerialHashes.at(hashSerial) = meta; //Write to db return CWalletDB(strWalletFile).WriteZerocoinMint(mint); } bool CzALGTracker::UpdateState(const CMintMeta& meta) { CWalletDB walletdb(strWalletFile); if (meta.isDeterministic) { CDeterministicMint dMint; if (!walletdb.ReadDeterministicMint(meta.hashPubcoin, dMint)) { // Check archive just in case if (!meta.isArchived) return error("%s: failed to read deterministic mint from database", __func__); // Unarchive this mint since it is being requested and updated if (!walletdb.UnarchiveDeterministicMint(meta.hashPubcoin, dMint)) return error("%s: failed to unarchive deterministic mint from database", __func__); } dMint.SetTxHash(meta.txid); dMint.SetHeight(meta.nHeight); dMint.SetUsed(meta.isUsed); dMint.SetDenomination(meta.denom); dMint.SetStakeHash(meta.hashStake); if (!walletdb.WriteDeterministicMint(dMint)) return error("%s: failed to update deterministic mint when writing to db", __func__); } else { CZerocoinMint mint; if (!walletdb.ReadZerocoinMint(meta.hashPubcoin, mint)) return error("%s: failed to read mint from database", __func__); mint.SetTxHash(meta.txid); mint.SetHeight(meta.nHeight); mint.SetUsed(meta.isUsed); mint.SetDenomination(meta.denom); if (!walletdb.WriteZerocoinMint(mint)) return error("%s: failed to write mint to database", __func__); } mapSerialHashes[meta.hashSerial] = meta; return true; } void CzALGTracker::Add(const CDeterministicMint& dMint, bool isNew, bool isArchived, CzALGWallet* zALGWallet) { bool iszALGWalletInitialized = (NULL != zALGWallet); CMintMeta meta; meta.hashPubcoin = dMint.GetPubcoinHash(); meta.nHeight = dMint.GetHeight(); meta.nVersion = dMint.GetVersion(); meta.txid = dMint.GetTxHash(); meta.isUsed = dMint.IsUsed(); meta.hashSerial = dMint.GetSerialHash(); meta.hashStake = dMint.GetStakeHash(); meta.denom = dMint.GetDenomination(); meta.isArchived = isArchived; meta.isDeterministic = true; if (! iszALGWalletInitialized) zALGWallet = new CzALGWallet(strWalletFile); meta.isSeedCorrect = zALGWallet->CheckSeed(dMint); if (! iszALGWalletInitialized) delete zALGWallet; mapSerialHashes[meta.hashSerial] = meta; if (isNew) CWalletDB(strWalletFile).WriteDeterministicMint(dMint); } void CzALGTracker::Add(const CZerocoinMint& mint, bool isNew, bool isArchived) { CMintMeta meta; meta.hashPubcoin = GetPubCoinHash(mint.GetValue()); meta.nHeight = mint.GetHeight(); meta.nVersion = libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()); meta.txid = mint.GetTxHash(); meta.isUsed = mint.IsUsed(); meta.hashSerial = GetSerialHash(mint.GetSerialNumber()); uint256 nSerial = mint.GetSerialNumber().getuint256(); meta.hashStake = Hash(nSerial.begin(), nSerial.end()); meta.denom = mint.GetDenomination(); meta.isArchived = isArchived; meta.isDeterministic = false; meta.isSeedCorrect = true; mapSerialHashes[meta.hashSerial] = meta; if (isNew) CWalletDB(strWalletFile).WriteZerocoinMint(mint); } void CzALGTracker::SetPubcoinUsed(const uint256& hashPubcoin, const uint256& txid) { if (!HasPubcoinHash(hashPubcoin)) return; CMintMeta meta = GetMetaFromPubcoin(hashPubcoin); meta.isUsed = true; mapPendingSpends.insert(make_pair(meta.hashSerial, txid)); UpdateState(meta); } void CzALGTracker::SetPubcoinNotUsed(const uint256& hashPubcoin) { if (!HasPubcoinHash(hashPubcoin)) return; CMintMeta meta = GetMetaFromPubcoin(hashPubcoin); meta.isUsed = false; if (mapPendingSpends.count(meta.hashSerial)) mapPendingSpends.erase(meta.hashSerial); UpdateState(meta); } void CzALGTracker::RemovePending(const uint256& txid) { uint256 hashSerial; for (auto it : mapPendingSpends) { if (it.second == txid) { hashSerial = it.first; break; } } if (hashSerial > 0) mapPendingSpends.erase(hashSerial); } bool CzALGTracker::UpdateStatusInternal(const std::set<uint256>& setMempool, CMintMeta& mint) { //! Check whether this mint has been spent and is considered 'pending' or 'confirmed' // If there is not a record of the block height, then look it up and assign it uint256 txidMint; bool isMintInChain = zerocoinDB->ReadCoinMint(mint.hashPubcoin, txidMint); //See if there is internal record of spending this mint (note this is memory only, would reset on restart) bool isPendingSpend = static_cast<bool>(mapPendingSpends.count(mint.hashSerial)); // See if there is a blockchain record of spending this mint uint256 txidSpend; bool isConfirmedSpend = zerocoinDB->ReadCoinSpend(mint.hashSerial, txidSpend); // Double check the mempool for pending spend if (isPendingSpend) { uint256 txidPendingSpend = mapPendingSpends.at(mint.hashSerial); if (!setMempool.count(txidPendingSpend) || isConfirmedSpend) { RemovePending(txidPendingSpend); isPendingSpend = false; LogPrintf("%s : Pending txid %s removed because not in mempool\n", __func__, txidPendingSpend.GetHex()); } } bool isUsed = isPendingSpend || isConfirmedSpend; if (!mint.nHeight || !isMintInChain || isUsed != mint.isUsed) { CTransaction tx; uint256 hashBlock; // Txid will be marked 0 if there is no knowledge of the final tx hash yet if (mint.txid == 0) { if (!isMintInChain) { LogPrintf("%s : Failed to find mint in zerocoinDB %s\n", __func__, mint.hashPubcoin.GetHex().substr(0, 6)); mint.isArchived = true; Archive(mint); return true; } mint.txid = txidMint; } if (setMempool.count(mint.txid)) return true; // Check the transaction associated with this mint if (!IsInitialBlockDownload() && !GetTransaction(mint.txid, tx, hashBlock, true)) { LogPrintf("%s : Failed to find tx for mint txid=%s\n", __func__, mint.txid.GetHex()); mint.isArchived = true; Archive(mint); return true; } // An orphan tx if hashblock is in mapBlockIndex but not in chain active if (mapBlockIndex.count(hashBlock) && !chainActive.Contains(mapBlockIndex.at(hashBlock))) { LogPrintf("%s : Found orphaned mint txid=%s\n", __func__, mint.txid.GetHex()); mint.isUsed = false; mint.nHeight = 0; if (tx.IsCoinStake()) { mint.isArchived = true; Archive(mint); } return true; } // Check that the mint has correct used status if (mint.isUsed != isUsed) { LogPrintf("%s : Set mint %s isUsed to %d\n", __func__, mint.hashPubcoin.GetHex(), isUsed); mint.isUsed = isUsed; return true; } } return false; } std::set<CMintMeta> CzALGTracker::ListMints(bool fUnusedOnly, bool fMatureOnly, bool fUpdateStatus, bool fWrongSeed) { CWalletDB walletdb(strWalletFile); if (fUpdateStatus) { std::list<CZerocoinMint> listMintsDB = walletdb.ListMintedCoins(); for (auto& mint : listMintsDB) Add(mint); LogPrint("zero", "%s: added %d zerocoinmints from DB\n", __func__, listMintsDB.size()); std::list<CDeterministicMint> listDeterministicDB = walletdb.ListDeterministicMints(); CzALGWallet* zALGWallet = new CzALGWallet(strWalletFile); for (auto& dMint : listDeterministicDB) { Add(dMint, false, false, zALGWallet); } delete zALGWallet; LogPrint("zero", "%s: added %d dzpiv from DB\n", __func__, listDeterministicDB.size()); } std::vector<CMintMeta> vOverWrite; std::set<CMintMeta> setMints; std::set<uint256> setMempool; { LOCK(mempool.cs); mempool.getTransactions(setMempool); } std::map<libzerocoin::CoinDenomination, int> mapMaturity = GetMintMaturityHeight(); for (auto& it : mapSerialHashes) { CMintMeta mint = it.second; //This is only intended for unarchived coins if (mint.isArchived) continue; // Update the metadata of the mints if requested if (fUpdateStatus && UpdateStatusInternal(setMempool, mint)) { if (mint.isArchived) continue; // Mint was updated, queue for overwrite vOverWrite.emplace_back(mint); } if (fUnusedOnly && mint.isUsed) continue; if (fMatureOnly) { // Not confirmed if (!mint.nHeight || mint.nHeight > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) continue; if (mint.nHeight >= mapMaturity.at(mint.denom)) continue; } if (!fWrongSeed && !mint.isSeedCorrect) continue; setMints.insert(mint); } //overwrite any updates for (CMintMeta& meta : vOverWrite) UpdateState(meta); return setMints; } void CzALGTracker::Clear() { mapSerialHashes.clear(); }
[ "kyzer@traebit.ca" ]
kyzer@traebit.ca
6606c5252905861cffcc7ee9e514579d2c35c417
ffa83215d4a44581f44173100331bda1900b24fe
/build/iOS/Preview/include/Fuse.Controls.TextInput.h
0199a483ca6573278b57648cab9fdeb8a73f1bf4
[]
no_license
imkimbosung/ARkit_fuse
167d1c77ee497d5b626e69af16e0e84b13c54457
3b378d6408551d6867f2e5b3d7d8b6f5114e7f69
refs/heads/master
2020-04-19T02:34:33.970273
2019-02-04T08:26:54
2019-02-04T08:26:54
167,907,696
0
0
null
null
null
null
UTF-8
C++
false
false
3,127
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls.Primitives/1.10.0-rc1/TextControls/TextInput.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.ITextEditControl.h> #include <Fuse.Controls.TextInputControl.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ISourceLocation.h> #include <Fuse.ITemplateSource.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Triggers.IValue-1.h> #include <Fuse.Visual.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.String.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Controls{struct TextEdit;}}} namespace g{namespace Fuse{namespace Controls{struct TextInput;}}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Controls{ // public class TextInput :98 // { struct TextInput_type : ::g::Fuse::Controls::TextInputControl_type { ::g::Fuse::Controls::ITextEditControl interface19; }; TextInput_type* TextInput_typeof(); void TextInput__ctor_7_fn(TextInput* __this); void TextInput__get_ActionStyle_fn(TextInput* __this, int32_t* __retval); void TextInput__set_ActionStyle_fn(TextInput* __this, int32_t* value); void TextInput__add_ActionTriggered_fn(TextInput* __this, uDelegate* value); void TextInput__remove_ActionTriggered_fn(TextInput* __this, uDelegate* value); void TextInput__Create_fn(::g::Fuse::Controls::TextEdit** __retval); void TextInput__get_EditorAlignment_fn(TextInput* __this, int32_t* __retval); void TextInput__set_EditorAlignment_fn(TextInput* __this, int32_t* value); void TextInput__get_IsPassword_fn(TextInput* __this, bool* __retval); void TextInput__set_IsPassword_fn(TextInput* __this, bool* value); void TextInput__New3_fn(TextInput** __retval); void TextInput__get_PlaceholderColor_fn(TextInput* __this, ::g::Uno::Float4* __retval); void TextInput__set_PlaceholderColor_fn(TextInput* __this, ::g::Uno::Float4* value); void TextInput__get_PlaceholderText_fn(TextInput* __this, uString** __retval); void TextInput__set_PlaceholderText_fn(TextInput* __this, uString* value); struct TextInput : ::g::Fuse::Controls::TextInputControl { void ctor_7(); int32_t ActionStyle(); void ActionStyle(int32_t value); void add_ActionTriggered(uDelegate* value); void remove_ActionTriggered(uDelegate* value); int32_t EditorAlignment(); void EditorAlignment(int32_t value); bool IsPassword(); void IsPassword(bool value); ::g::Uno::Float4 PlaceholderColor(); void PlaceholderColor(::g::Uno::Float4 value); uString* PlaceholderText(); void PlaceholderText(uString* value); static ::g::Fuse::Controls::TextEdit* Create(); static TextInput* New3(); }; // } }}} // ::g::Fuse::Controls
[ "ghalsru@naver.com" ]
ghalsru@naver.com
ba85712df598a27fd26aec8fa089f1337aba6221
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/hunk_3816.cpp
46c0196c6d616693c7c306955fa410edd910d3a8
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
804
cpp
extern void *create_object(const unsigned char *sha1, int type, void *obj); -/** Returns the object, having parsed it to find out what it is. **/ +/* + * Returns the object, having parsed it to find out what it is. + * + * Returns NULL if the object is missing or corrupt. + */ struct object *parse_object(const unsigned char *sha1); +/* + * Like parse_object, but will die() instead of returning NULL. If the + * "name" parameter is not NULL, it is included in the error message + * (otherwise, the sha1 hex is given). + */ +struct object *parse_object_or_die(const unsigned char *sha1, const char *name); + /* Given the result of read_sha1_file(), returns the object after * parsing it. eaten_p indicates if the object has a borrowed copy * of buffer and the caller should not free() it.
[ "993273596@qq.com" ]
993273596@qq.com
4dd4ab229abfe1424cdca631914437c39fbd7793
1d41b872938bdfcdd7de0ca46284eaf26b5f1dfa
/CSCI-2312-Object-Oriented-Programming/Battleship_Final_Project/Computer.cpp
33c5c6b810eb3ac31cefc9f67607162b19bd1bfd
[]
no_license
vanctate/Computer-Science-Coursework
7dc3a7e45b98107f86ed6e4be5dfc9b190594438
bb9746249686651031380669781949fc29aeb04c
refs/heads/master
2020-05-24T22:00:20.131642
2019-05-19T17:34:59
2019-05-19T17:34:59
187,487,656
1
5
null
null
null
null
UTF-8
C++
false
false
15,786
cpp
/* - Patrick Tate - Final Project - CSCI 2312 - Program written using Xcode on MacOS - Program Status: this program runs and compiles on the csegrid */ #include "Computer.h" #include <iostream> using namespace std; //instantiate 5 Watervehicle objects for the computer's fleet Computer::Computer() { name = "Computer"; WaterVehicle carrier("Carrier", 5); setCarrier(carrier); WaterVehicle battleship("Battleship", 4); setBattleship(battleship); WaterVehicle cruiser("Cruiser", 3); setCruiser(cruiser); WaterVehicle submarine("Submarine", 3); setSubmarine(submarine); WaterVehicle destroyer("Destroyer", 2); setDestroyer(destroyer); } //randomly determines orientation, starting position //while loop runs until there is space for that ship and the position isn't occupied by another ship void Computer::placeShip(WaterVehicle &obj) { do { obj.determineOrientation(); obj.determineStartPos(); obj.checkSpace(); checkOccupied(obj); } while ((!obj.getSpace()) || (obj.getOccupied())); } //once the Watervehicle object is determined to be in legal position, it is inserted into the yourGrid //'F' marks a ship that hasn't been hit yet, for example, a Destroyer ship is of length 2, so it //takes up 2 spaces on the grid and will look like FF void Computer::insertShip(WaterVehicle &obj) { if (obj.getOrientation() == 'h') { for (int i = 0; i < obj.getLength(); i++) { *getYourGrid(obj.getSRow(), obj.getSCol() + i) = 'F'; }//for }//if else if (obj.getOrientation() == 'v'){ for (int i = 0; i < obj.getLength(); i++) { *getYourGrid(obj.getSRow() + i, obj.getSCol()) = 'F'; }//for }//if obj.setPlaced(true); } //ensures that a ship's placement doesn't overlap at all with any other ship's location //returns true if area isn't occupied, returns false if any section of placement is occupied bool Computer::checkOccupied(WaterVehicle &obj) { bool legal = true; //orientation = horizontal if (obj.getOrientation() == 'h') { for (int i = 0; i < obj.getLength(); i++) { if (*getYourGrid(obj.getSRow(), obj.getSCol() + i) == 'F') { obj.setOccupied(true); legal = false; }//if occupied }//for }//if horizontal //orientation = vertical if (obj.getOrientation() == 'v') { for (int i = 0; i < obj.getLength(); i++) { if (*getYourGrid(obj.getSRow() + i, obj.getSCol()) == 'F') { obj.setOccupied(true); legal = false; }//if occupied }//for }//if vertical if (legal) { obj.setOccupied(false); } return legal; } //places all 5 Watervehicle ships in random positions bool Computer::placeShips() { placeShip(carrier); insertShip(carrier); placeShip(battleship); insertShip(battleship); placeShip(cruiser); insertShip(cruiser); placeShip(submarine); insertShip(submarine); placeShip(destroyer); insertShip(destroyer); return true; } //printing computer's grid at the end void Computer::printCompYourGrid() { std::cout << "Grid Key: O = open position, F = occupied by a ship.\n"; std::cout << "Grid Key: X = hit ship in that position, M = missed.\n\n"; std::cout << "Computer's ship grid:" << std::endl << std::endl; std::string columns = "ABCDEFGHIJ"; int rows[10] = {1,2,3,4,5,6,7,8,9,10}; std::cout << "\t"; for (int i = 0; i < 10; i++) { std::cout << columns[i] << "\t"; }//for columns std::cout << std::endl << std::endl; for (int r = 0; r < 10; r++) { std::cout << rows[r]; for (int c = 0; c < 10; c++) { cout << "\t" << *(getYourGrid(0 + r,0 + c)); }//for columns std::cout << std::endl << std::endl; }//for rows } //randomly generate random row and random column //determine if User object has a ship there //change Computer's attack grid accordingly //ensure each grid location is only attacked once void Computer::generateAttack(User obj) { int randRow, randCol; bool newShot = false; char temp;//for converting int column value to a letter to correspond with the grid do { randRow = (int)rand()%10;//random row 0-9 randCol = (int)rand()%10;//random column 0-9 if ((*getAttackGrid(randRow, randCol) != 'X') && (*getAttackGrid(randRow, randCol) != 'M')){ newShot = true; } } while (newShot != true);//ensure spot is only attacked once temp = randCol + 65;//convert randCol to letter A-J for printing std::cout << "Computer attacking position: " << randRow+1 << temp << endl; if (*obj.getYourGrid(randRow, randCol) == 'O') { std::cout << "Computer missed!\n"; *getAttackGrid(randRow, randCol) = 'M';//set attack grid to miss }//if Computer missed else if (*obj.getYourGrid(randRow, randCol) == 'F'){ std::cout << "Computer got a hit!\n"; *getAttackGrid(randRow, randCol) = 'X';//set attack grid to hit }//if Computer hit } //checks if each of Computer's ships were hit and sets their hits variable accordingly //also sets User's score to the total of all the hits void Computer::checkAllHits(User &user) { int totalHits = 0; int carrierHits = 0, battleshipHits = 0, cruiserHits = 0, submarineHits = 0, destroyerHits = 0; //check carrier hits ******************************************** //if horizontal if (carrier.getOrientation() == 'h') { for (int i = 0; i < carrier.getLength(); i++) { if (*user.getAttackGrid(carrier.getSRow(), carrier.getSCol()+i) == 'X') { carrierHits++; //change Computer's grid to reflect the hit *getYourGrid(carrier.getSRow(), carrier.getSCol()+i) = 'X'; carrier.setHits(carrierHits); //if ship was sunk display this message if (carrier.getMessage()) { if (carrier.getHits() == carrier.getLength()) { carrier.setSunk(true); std::cout << "You sunk " << getName() << "'s " << carrier.getName() << ".\n"; carrier.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += carrierHits;//for setting User's score }// if horizontal //if vertical if (carrier.getOrientation() == 'v') { for (int i = 0; i < carrier.getLength(); i++) { if (*user.getAttackGrid(carrier.getSRow()+i, carrier.getSCol()) == 'X') { carrierHits++; //change Computer's grid to reflect the hit *getYourGrid(carrier.getSRow()+i, carrier.getSCol()) = 'X'; carrier.setHits(carrierHits); //if ship was sunk display this message if (carrier.getMessage()) { if (carrier.getHits() == carrier.getLength()) { carrier.setSunk(true); std::cout << "You sunk " << getName() << "'s " << carrier.getName() << ".\n"; carrier.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += carrierHits;//for setting User's score }//if vertical //check battleship hits ******************************************** //if horizontal if (battleship.getOrientation() == 'h') { for (int i = 0; i < battleship.getLength(); i++) { if (*user.getAttackGrid(battleship.getSRow(), battleship.getSCol()+i) == 'X') { battleshipHits++; //change Computer's grid to reflect the hit *getYourGrid(battleship.getSRow(), battleship.getSCol()+i) = 'X'; battleship.setHits(battleshipHits); //if ship was sunk display this message if (battleship.getMessage()) { if (battleship.getHits() == battleship.getLength()) { battleship.setSunk(true); std::cout << "You sunk " << getName() << "'s " << battleship.getName() << ".\n"; battleship.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += battleshipHits;//for setting User's score }//if horizontal //if vertical if (battleship.getOrientation() == 'v') { for (int i = 0; i < battleship.getLength(); i++) { if (*user.getAttackGrid(battleship.getSRow()+i, battleship.getSCol()) == 'X') { battleshipHits++; //change Computer's grid to reflect the hit *getYourGrid(battleship.getSRow()+i, battleship.getSCol()) = 'X';//works battleship.setHits(battleshipHits); //if ship was sunk display this message if (battleship.getMessage()) { if (battleship.getHits() == battleship.getLength()) { battleship.setSunk(true); std::cout << "You sunk " << getName() << "'s " << battleship.getName() << ".\n"; battleship.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += battleshipHits;//for setting User's score }//if vertical //check cruiser hits ******************************************** //if horizontal if (cruiser.getOrientation() == 'h') { for (int i = 0; i < cruiser.getLength(); i++) { if (*user.getAttackGrid(cruiser.getSRow(), cruiser.getSCol()+i) == 'X') { cruiserHits++; //change Computer's grid to reflect the hit *getYourGrid(cruiser.getSRow(), cruiser.getSCol()+i) = 'X'; cruiser.setHits(cruiserHits); //if ship was sunk display this message if (cruiser.getMessage()) { if (cruiser.getHits() == cruiser.getLength()) { cruiser.setSunk(true); std::cout << "You sunk " << getName() << "'s " << cruiser.getName() << ".\n"; cruiser.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += cruiserHits;//for setting User's score }//if horizontal //if vertical if (cruiser.getOrientation() == 'v') { for (int i = 0; i < cruiser.getLength(); i++) { if (*user.getAttackGrid(cruiser.getSRow()+i, cruiser.getSCol()) == 'X') { cruiserHits++; //change Computer's grid to reflect the hit *getYourGrid(cruiser.getSRow()+i, cruiser.getSCol()) = 'X'; cruiser.setHits(cruiserHits); //if ship was sunk display this message if (cruiser.getMessage()) { if (cruiser.getHits() == cruiser.getLength()) { cruiser.setSunk(true); std::cout << "You sunk " << getName() << "'s " << cruiser.getName() << ".\n"; cruiser.setMessage(false); }// if ship sunk }//if }//if }//for totalHits += cruiserHits;//for setting User's score }//if vertical //check submarine hits ******************************************** //if horizontal if (submarine.getOrientation() == 'h') { for (int i = 0; i < submarine.getLength(); i++) { if (*user.getAttackGrid(submarine.getSRow(), submarine.getSCol()+i) == 'X') { submarineHits++; //change Computer's grid to reflect the hit *getYourGrid(submarine.getSRow(), submarine.getSCol()+i) = 'X';//works submarine.setHits(submarineHits); //if ship was sunk display this message if (submarine.getMessage()) { if (submarine.getHits() == submarine.getLength()) { submarine.setSunk(true); std::cout << "You sunk " << getName() << "'s " << submarine.getName() << ".\n"; submarine.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += submarineHits;//for setting User's score }//if horizontal //if vertical if (submarine.getOrientation() == 'v') { for (int i = 0; i < submarine.getLength(); i++) { if (*user.getAttackGrid(submarine.getSRow()+i, submarine.getSCol()) == 'X') { submarineHits++; //change Computer's grid to reflect the hit *getYourGrid(submarine.getSRow()+i, submarine.getSCol()) = 'X'; submarine.setHits(submarineHits); //if ship was sunk display this message if (submarine.getMessage()) { if (submarine.getHits() == submarine.getLength()) { submarine.setSunk(true); std::cout << "You sunk " << getName() << "'s " << submarine.getName() << ".\n"; submarine.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += submarineHits;//for setting User's score }//if vertical //check destroyer hits ******************************************** //if horizontal if (destroyer.getOrientation() == 'h') { for (int i = 0; i < destroyer.getLength(); i++) { if (*user.getAttackGrid(destroyer.getSRow(), destroyer.getSCol()+i) == 'X') { destroyerHits++; //change Computer's grid to reflect the hit *getYourGrid(destroyer.getSRow(), destroyer.getSCol()+i) = 'X';//works destroyer.setHits(destroyerHits); //if ship was sunk display this message if (destroyer.getMessage()) { if (destroyer.getHits() == destroyer.getLength()) { destroyer.setSunk(true); std::cout << "You sunk " << getName() << "'s " << destroyer.getName() << ".\n"; destroyer.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += destroyerHits;//for setting User's score }//if horizontal //if vertical if (destroyer.getOrientation() == 'v') { for (int i = 0; i < destroyer.getLength(); i++) { if (*user.getAttackGrid(destroyer.getSRow()+i, destroyer.getSCol()) == 'X') { destroyerHits++; //change Computer's grid to reflect the hit *getYourGrid(destroyer.getSRow()+i, destroyer.getSCol()) = 'X';//works destroyer.setHits(destroyerHits); //if ship was sunk display this message if (destroyer.getMessage()) { if (destroyer.getHits() == destroyer.getLength()) { destroyer.setSunk(true); std::cout << "You sunk " << getName() << "'s " << destroyer.getName() << ".\n"; destroyer.setMessage(false); }//if ship sunk }//if }//if }//for totalHits += destroyerHits;//for setting User's score }//if vertical //set User's score to the total amount of hits user.setScore(totalHits); }
[ "vanctate@gmail.com" ]
vanctate@gmail.com
244f0d8a787a3ede21373bde8016006aa8689fc8
edeb2efadd3773ae866b77519613e89fc4e039bb
/modules/canbus/vehicle/ge3/ge3_controller.cc
cfa0388386bd1fe93409454ca131b02a86c1b24e
[ "Apache-2.0" ]
permissive
zhucm1/apollo
14db9ca7c09a586914bf886dcfdaa614dca7a8ec
7062a990cbe161471e8c74d0ee67330a28774000
refs/heads/master
2020-05-15T11:26:31.612399
2019-05-09T02:42:30
2019-05-09T02:42:30
182,224,422
3
0
Apache-2.0
2019-05-09T02:42:31
2019-04-19T07:45:49
C++
UTF-8
C++
false
false
29,238
cc
/* Copyright 2019 The Apollo Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "modules/canbus/vehicle/ge3/ge3_controller.h" #include "modules/canbus/vehicle/ge3/ge3_message_manager.h" #include "modules/canbus/vehicle/vehicle_controller.h" #include "modules/common/proto/vehicle_signal.pb.h" #include "modules/common/time/time.h" #include "modules/drivers/canbus/can_comm/can_sender.h" #include "modules/drivers/canbus/can_comm/protocol_data.h" namespace apollo { namespace canbus { namespace ge3 { using ::apollo::common::ErrorCode; using ::apollo::control::ControlCommand; using ::apollo::drivers::canbus::ProtocolData; namespace { const int32_t kMaxFailAttempt = 10; const int32_t CHECK_RESPONSE_STEER_UNIT_FLAG = 1; const int32_t CHECK_RESPONSE_SPEED_UNIT_FLAG = 2; } // namespace ErrorCode Ge3Controller::Init( const VehicleParameter& params, CanSender<ChassisDetail>* const can_sender, MessageManager<::apollo::canbus::ChassisDetail>* const message_manager) { if (is_initialized_) { AINFO << "Ge3Controller has already been initiated."; return ErrorCode::CANBUS_ERROR; } vehicle_params_.CopyFrom( common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param()); params_.CopyFrom(params); if (!params_.has_driving_mode()) { AERROR << "Vehicle conf pb not set driving_mode."; return ErrorCode::CANBUS_ERROR; } if (can_sender == nullptr) { return ErrorCode::CANBUS_ERROR; } can_sender_ = can_sender; if (message_manager == nullptr) { AERROR << "protocol manager is null."; return ErrorCode::CANBUS_ERROR; } message_manager_ = message_manager; // sender part pc_bcm_201_ = dynamic_cast<Pcbcm201*>( message_manager_->GetMutableProtocolDataById(Pcbcm201::ID)); if (pc_bcm_201_ == nullptr) { AERROR << "Pcbcm201 does not exist in the Ge3MessageManager!"; return ErrorCode::CANBUS_ERROR; } pc_bcs_202_ = dynamic_cast<Pcbcs202*>( message_manager_->GetMutableProtocolDataById(Pcbcs202::ID)); if (pc_bcs_202_ == nullptr) { AERROR << "Pcbcs202 does not exist in the Ge3MessageManager!"; return ErrorCode::CANBUS_ERROR; } pc_epb_203_ = dynamic_cast<Pcepb203*>( message_manager_->GetMutableProtocolDataById(Pcepb203::ID)); if (pc_epb_203_ == nullptr) { AERROR << "Pcepb203 does not exist in the Ge3MessageManager!"; return ErrorCode::CANBUS_ERROR; } pc_eps_204_ = dynamic_cast<Pceps204*>( message_manager_->GetMutableProtocolDataById(Pceps204::ID)); if (pc_eps_204_ == nullptr) { AERROR << "Pceps204 does not exist in the Ge3MessageManager!"; return ErrorCode::CANBUS_ERROR; } pc_vcu_205_ = dynamic_cast<Pcvcu205*>( message_manager_->GetMutableProtocolDataById(Pcvcu205::ID)); if (pc_vcu_205_ == nullptr) { AERROR << "Pcvcu205 does not exist in the Ge3MessageManager!"; return ErrorCode::CANBUS_ERROR; } can_sender_->AddMessage(Pcbcm201::ID, pc_bcm_201_, false); can_sender_->AddMessage(Pcbcs202::ID, pc_bcs_202_, false); can_sender_->AddMessage(Pcepb203::ID, pc_epb_203_, false); can_sender_->AddMessage(Pceps204::ID, pc_eps_204_, false); can_sender_->AddMessage(Pcvcu205::ID, pc_vcu_205_, false); // Need to sleep to ensure all messages received AINFO << "Ge3Controller is initialized."; is_initialized_ = true; return ErrorCode::OK; } Ge3Controller::~Ge3Controller() {} bool Ge3Controller::Start() { if (!is_initialized_) { AERROR << "Ge3Controller has NOT been initialized."; return false; } const auto& update_func = [this] { SecurityDogThreadFunc(); }; thread_.reset(new std::thread(update_func)); return true; } void Ge3Controller::Stop() { if (!is_initialized_) { AERROR << "Ge3Controller stops or starts improperly!"; return; } if (thread_ != nullptr && thread_->joinable()) { thread_->join(); thread_.reset(); AINFO << "Ge3Controller stopped."; } } Chassis Ge3Controller::chassis() { chassis_.Clear(); ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); // 21, 22, previously 1, 2 if (driving_mode() == Chassis::EMERGENCY_MODE) { set_chassis_error_code(Chassis::NO_ERROR); } chassis_.set_driving_mode(driving_mode()); chassis_.set_error_code(chassis_error_code()); // 3 chassis_.set_engine_started(true); // check if there is not ge3, no chassis detail can be retrieved and return if (!chassis_detail.has_ge3()) { AERROR << "NO GE3 chassis information!"; return chassis_; } Ge3 ge3 = chassis_detail.ge3(); // 5 if (ge3.has_scu_bcs_3_308()) { Scu_bcs_3_308 scu_bcs_3_308 = ge3.scu_bcs_3_308(); if (scu_bcs_3_308.has_bcs_rrwheelspd()) { if (chassis_.has_wheel_speed()) { chassis_.mutable_wheel_speed()->set_is_wheel_spd_rr_valid( scu_bcs_3_308.bcs_rrwheelspdvd()); chassis_.mutable_wheel_speed()->set_wheel_direction_rr( (WheelSpeed::WheelSpeedType)scu_bcs_3_308.bcs_rrwheeldirection()); chassis_.mutable_wheel_speed()->set_wheel_spd_rr( scu_bcs_3_308.bcs_rrwheelspd()); } } if (scu_bcs_3_308.has_bcs_rlwheelspd()) { if (chassis_.has_wheel_speed()) { chassis_.mutable_wheel_speed()->set_is_wheel_spd_rl_valid( scu_bcs_3_308.bcs_rlwheelspdvd()); chassis_.mutable_wheel_speed()->set_wheel_direction_rl( (WheelSpeed::WheelSpeedType)scu_bcs_3_308.bcs_rlwheeldirection()); chassis_.mutable_wheel_speed()->set_wheel_spd_rl( scu_bcs_3_308.bcs_rlwheelspd()); } } if (scu_bcs_3_308.has_bcs_frwheelspd()) { if (chassis_.has_wheel_speed()) { chassis_.mutable_wheel_speed()->set_is_wheel_spd_fr_valid( scu_bcs_3_308.bcs_frwheelspdvd()); chassis_.mutable_wheel_speed()->set_wheel_direction_fr( (WheelSpeed::WheelSpeedType)scu_bcs_3_308.bcs_frwheeldirection()); chassis_.mutable_wheel_speed()->set_wheel_spd_fr( scu_bcs_3_308.bcs_frwheelspd()); } } if (scu_bcs_3_308.has_bcs_flwheelspd()) { if (chassis_.has_wheel_speed()) { chassis_.mutable_wheel_speed()->set_is_wheel_spd_fl_valid( scu_bcs_3_308.bcs_flwheelspdvd()); chassis_.mutable_wheel_speed()->set_wheel_direction_fl( (WheelSpeed::WheelSpeedType)scu_bcs_3_308.bcs_flwheeldirection()); chassis_.mutable_wheel_speed()->set_wheel_spd_fl( scu_bcs_3_308.bcs_flwheelspd()); } } } if (ge3.has_scu_bcs_2_307() && ge3.scu_bcs_2_307().has_bcs_vehspd()) { chassis_.set_speed_mps( static_cast<float>(ge3.scu_bcs_2_307().bcs_vehspd())); } else { chassis_.set_speed_mps(0); } // 7 // ge3 only has fuel percentage // to avoid confusing, just don't set chassis_.set_fuel_range_m(0); if (ge3.has_scu_vcu_1_312() && ge3.scu_vcu_1_312().has_vcu_accpedact()) { chassis_.set_throttle_percentage( static_cast<float>(ge3.scu_vcu_1_312().vcu_accpedact())); } else { chassis_.set_throttle_percentage(0); } // 9 if (ge3.has_scu_bcs_1_306() && ge3.scu_bcs_1_306().has_bcs_brkpedact()) { chassis_.set_brake_percentage( static_cast<float>(ge3.scu_bcs_1_306().bcs_brkpedact())); } else { chassis_.set_brake_percentage(0); } // 23, previously 10 if (ge3.has_scu_vcu_1_312() && ge3.scu_vcu_1_312().has_vcu_gearact()) { switch (ge3.scu_vcu_1_312().vcu_gearact()) { case Scu_vcu_1_312::VCU_GEARACT_INVALID: { chassis_.set_gear_location(Chassis::GEAR_INVALID); } break; case Scu_vcu_1_312::VCU_GEARACT_DRIVE: { chassis_.set_gear_location(Chassis::GEAR_DRIVE); } break; case Scu_vcu_1_312::VCU_GEARACT_NEUTRAL: { chassis_.set_gear_location(Chassis::GEAR_NEUTRAL); } break; case Scu_vcu_1_312::VCU_GEARACT_REVERSE: { chassis_.set_gear_location(Chassis::GEAR_REVERSE); } break; case Scu_vcu_1_312::VCU_GEARACT_PARK: { chassis_.set_gear_location(Chassis::GEAR_PARKING); } break; default: chassis_.set_gear_location(Chassis::GEAR_INVALID); break; } } else { chassis_.set_gear_location(Chassis::GEAR_INVALID); } // 11 if (ge3.has_scu_eps_311() && ge3.scu_eps_311().has_eps_steerangle()) { chassis_.set_steering_percentage( static_cast<float>(ge3.scu_eps_311().eps_steerangle() / vehicle_params_.max_steer_angle() * M_PI / 1.80)); } else { chassis_.set_steering_percentage(0); } // 13 if (ge3.has_scu_epb_310() && ge3.scu_epb_310().has_epb_sysst()) { chassis_.set_parking_brake(ge3.scu_epb_310().epb_sysst() == Scu_epb_310::EPB_SYSST_APPLIED); } else { chassis_.set_parking_brake(false); } // 14, 15: ge3 light control if (ge3.has_scu_bcm_304() && ge3.scu_bcm_304().has_bcm_highbeamst() && Scu_bcm_304::BCM_HIGHBEAMST_ACTIVE == ge3.scu_bcm_304().bcm_highbeamst()) { if (chassis_.has_signal()) { chassis_.mutable_signal()->set_high_beam(true); } } else { if (chassis_.has_signal()) { chassis_.mutable_signal()->set_high_beam(false); } } // 16, 17 if (ge3.has_scu_bcm_304()) { Scu_bcm_304 scu_bcm_304 = ge3.scu_bcm_304(); if (scu_bcm_304.has_bcm_leftturnlampst() && Scu_bcm_304::BCM_LEFTTURNLAMPST_ACTIVE == scu_bcm_304.bcm_leftturnlampst()) { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_LEFT); } else if (scu_bcm_304.has_bcm_rightturnlampst() && Scu_bcm_304::BCM_RIGHTTURNLAMPST_ACTIVE == scu_bcm_304.bcm_rightturnlampst()) { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_RIGHT); } else { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_NONE); } } else { chassis_.mutable_signal()->set_turn_signal( common::VehicleSignal::TURN_NONE); } // 18 if (ge3.has_scu_bcm_304() && ge3.scu_bcm_304().has_bcm_hornst() && Scu_bcm_304::BCM_HORNST_ACTIVE == ge3.scu_bcm_304().bcm_hornst()) { chassis_.mutable_signal()->set_horn(true); } else { chassis_.mutable_signal()->set_horn(false); } // vin number will be written into KVDB once. chassis_.mutable_license()->set_vin(""); if (ge3.has_scu_1_301() && ge3.has_scu_2_302() && ge3.has_scu_3_303()) { Scu_1_301 scu_1_301 = ge3.scu_1_301(); Scu_2_302 scu_2_302 = ge3.scu_2_302(); Scu_3_303 scu_3_303 = ge3.scu_3_303(); if (scu_2_302.has_vin00() && scu_2_302.has_vin01() && scu_2_302.has_vin02() && scu_2_302.has_vin03() && scu_2_302.has_vin04() && scu_2_302.has_vin05() && scu_2_302.has_vin06() && scu_2_302.has_vin07() && scu_3_303.has_vin08() && scu_3_303.has_vin09() && scu_3_303.has_vin10() && scu_3_303.has_vin11() && scu_3_303.has_vin12() && scu_3_303.has_vin13() && scu_3_303.has_vin14() && scu_3_303.has_vin15() && scu_1_301.has_vin16()) { int n[17]; n[0] = scu_2_302.vin00(); n[1] = scu_2_302.vin01(); n[2] = scu_2_302.vin02(); n[3] = scu_2_302.vin03(); n[4] = scu_2_302.vin04(); n[5] = scu_2_302.vin05(); n[6] = scu_2_302.vin06(); n[7] = scu_2_302.vin07(); n[8] = scu_3_303.vin08(); n[9] = scu_3_303.vin09(); n[10] = scu_3_303.vin10(); n[11] = scu_3_303.vin11(); n[12] = scu_3_303.vin12(); n[13] = scu_3_303.vin13(); n[14] = scu_3_303.vin14(); n[15] = scu_3_303.vin15(); n[16] = scu_1_301.vin16(); char ch[17]; memset(&ch, '\0', sizeof(ch)); for (int i = 0; i < 17; i++) { ch[i] = static_cast<char>(n[i]); } if (chassis_.has_license()) { chassis_.mutable_license()->set_vin(ch); } } } // give engage_advice based on error_code and canbus feedback if (chassis_error_mask_) { if (chassis_.has_engage_advice()) { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); chassis_.mutable_engage_advice()->set_reason("Chassis error!"); } } else if (chassis_.parking_brake() || CheckSafetyError(chassis_detail)) { if (chassis_.has_engage_advice()) { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); chassis_.mutable_engage_advice()->set_reason( "Vehicle is not in a safe state to engage!"); } } else { if (chassis_.has_engage_advice()) { chassis_.mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::READY_TO_ENGAGE); } } return chassis_; } void Ge3Controller::Emergency() { set_driving_mode(Chassis::EMERGENCY_MODE); ResetProtocol(); // In emergency case, the hazard lamp should be on pc_bcm_201_->set_pc_hazardlampreq(Pc_bcm_201::PC_HAZARDLAMPREQ_REQ); set_chassis_error_code(Chassis::CHASSIS_ERROR); } ErrorCode Ge3Controller::EnableAutoMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE) { AINFO << "already in COMPLETE_AUTO_DRIVE mode"; return ErrorCode::OK; } pc_bcs_202_->set_pc_brkpedenable(Pc_bcs_202::PC_BRKPEDENABLE_ENABLE); pc_vcu_205_->set_pc_accpedenable(Pc_vcu_205::PC_ACCPEDENABLE_ENABLE); pc_vcu_205_->set_pc_gearenable(Pc_vcu_205::PC_GEARENABLE_ENABLE); pc_epb_203_->set_pc_epbenable(Pc_epb_203::PC_EPBENABLE_ENABLE); pc_eps_204_->set_pc_steerenable(Pc_eps_204::PC_STEERENABLE_ENABLE); can_sender_->Update(); const int32_t flag = CHECK_RESPONSE_STEER_UNIT_FLAG | CHECK_RESPONSE_SPEED_UNIT_FLAG; if (!CheckResponse(flag, true)) { AERROR << "Failed to switch to COMPLETE_AUTO_DRIVE mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::COMPLETE_AUTO_DRIVE); // If the auto mode can be set normally, the harzad lamp should be off. pc_bcm_201_->set_pc_hazardlampreq(Pc_bcm_201::PC_HAZARDLAMPREQ_NOREQ); AINFO << "Switch to COMPLETE_AUTO_DRIVE mode ok."; return ErrorCode::OK; } ErrorCode Ge3Controller::DisableAutoMode() { ResetProtocol(); can_sender_->Update(); set_driving_mode(Chassis::COMPLETE_MANUAL); set_chassis_error_code(Chassis::NO_ERROR); AINFO << "Switch to COMPLETE_MANUAL OK."; return ErrorCode::OK; } ErrorCode Ge3Controller::EnableSteeringOnlyMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY) { set_driving_mode(Chassis::AUTO_STEER_ONLY); AINFO << "Already in AUTO_STEER_ONLY mode"; return ErrorCode::OK; } pc_bcs_202_->set_pc_brkpedenable(Pc_bcs_202::PC_BRKPEDENABLE_DISABLE); pc_vcu_205_->set_pc_accpedenable(Pc_vcu_205::PC_ACCPEDENABLE_DISABLE); pc_vcu_205_->set_pc_gearenable(Pc_vcu_205::PC_GEARENABLE_DISABLE); pc_epb_203_->set_pc_epbenable(Pc_epb_203::PC_EPBENABLE_DISABLE); pc_eps_204_->set_pc_steerenable(Pc_eps_204::PC_STEERENABLE_ENABLE); can_sender_->Update(); if (!CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, true)) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::AUTO_STEER_ONLY); // If the auto mode can be set normally, the harzad lamp should be off. pc_bcm_201_->set_pc_hazardlampreq(Pc_bcm_201::PC_HAZARDLAMPREQ_NOREQ); AINFO << "Switch to AUTO_STEER_ONLY mode ok."; return ErrorCode::OK; } ErrorCode Ge3Controller::EnableSpeedOnlyMode() { if (driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_SPEED_ONLY) { set_driving_mode(Chassis::AUTO_SPEED_ONLY); AINFO << "Already in AUTO_SPEED_ONLY mode"; return ErrorCode::OK; } pc_bcs_202_->set_pc_brkpedenable(Pc_bcs_202::PC_BRKPEDENABLE_ENABLE); pc_vcu_205_->set_pc_accpedenable(Pc_vcu_205::PC_ACCPEDENABLE_ENABLE); pc_vcu_205_->set_pc_gearenable(Pc_vcu_205::PC_GEARENABLE_ENABLE); pc_epb_203_->set_pc_epbenable(Pc_epb_203::PC_EPBENABLE_ENABLE); pc_eps_204_->set_pc_steerenable(Pc_eps_204::PC_STEERENABLE_DISABLE); can_sender_->Update(); if (!CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, true)) { AERROR << "Failed to switch to AUTO_STEER_ONLY mode."; Emergency(); set_chassis_error_code(Chassis::CHASSIS_ERROR); return ErrorCode::CANBUS_ERROR; } set_driving_mode(Chassis::AUTO_SPEED_ONLY); // If the auto mode can be set normally, the harzad lamp should be off. pc_bcm_201_->set_pc_hazardlampreq(Pc_bcm_201::PC_HAZARDLAMPREQ_NOREQ); AINFO << "Switch to AUTO_SPEED_ONLY mode ok."; return ErrorCode::OK; } // NEUTRAL, REVERSE, DRIVE void Ge3Controller::Gear(Chassis::GearPosition gear_position) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "This drive mode no need to set gear."; return; } switch (gear_position) { case Chassis::GEAR_NEUTRAL: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_NEUTRAL); break; } case Chassis::GEAR_REVERSE: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_REVERSE); break; } case Chassis::GEAR_DRIVE: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_DRIVE); break; } case Chassis::GEAR_PARKING: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_PARK); break; } case Chassis::GEAR_LOW: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_INVALID); break; } case Chassis::GEAR_NONE: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_INVALID); break; } case Chassis::GEAR_INVALID: { AERROR << "Gear command is invalid!"; pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_INVALID); break; } default: { pc_vcu_205_->set_pc_gearreq(Pc_vcu_205::PC_GEARREQ_INVALID); break; } } } // brake with new acceleration // acceleration:0.00~99.99, unit: // acceleration:0.0 ~ 7.0, unit:m/s^2 // acceleration_spd:60 ~ 100, suggest: 90 // -> pedal void Ge3Controller::Brake(double pedal) { // Update brake value based on mode if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } pc_bcs_202_->set_pc_brkpedreq(pedal); } // drive with old acceleration // gas:0.00~99.99 unit: void Ge3Controller::Throttle(double pedal) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } pc_vcu_205_->set_pc_accpedreq(pedal); } // ge3 default, -470 ~ 470, left:+, right:- // need to be compatible with control module, so reverse // steering with old angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ void Ge3Controller::Steer(double angle) { if (!(driving_mode() == Chassis::COMPLETE_AUTO_DRIVE || driving_mode() == Chassis::AUTO_STEER_ONLY)) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() / M_PI * 180 * angle / 100.0; pc_eps_204_->set_pc_steerangreq(real_angle)->set_pc_steerspdreq(500); } // drive with acceleration/deceleration // acc:-7.0 ~ 5.0, unit:m/s^2 void Ge3Controller::Acceleration(double acc) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_SPEED_ONLY) { AINFO << "The current drive mode does not need to set acceleration."; return; } // None } // steering with new angle speed // angle:-99.99~0.00~99.99, unit:, left:-, right:+ // angle_spd:0.00~99.99, unit:deg/s void Ge3Controller::Steer(double angle, double angle_spd) { if (driving_mode() != Chassis::COMPLETE_AUTO_DRIVE && driving_mode() != Chassis::AUTO_STEER_ONLY) { AINFO << "The current driving mode does not need to set steer."; return; } const double real_angle = vehicle_params_.max_steer_angle() / M_PI * 180 * angle / 100.0; const double real_angle_spd = ProtocolData<::apollo::canbus::ChassisDetail>::BoundedValue( vehicle_params_.min_steer_angle_rate() / M_PI * 180, vehicle_params_.max_steer_angle_rate() / M_PI * 180, vehicle_params_.max_steer_angle_rate() / M_PI * 180 * angle_spd / 100.0); pc_eps_204_->set_pc_steerangreq(real_angle) ->set_pc_steerspdreq(static_cast<int>(real_angle_spd)); } void Ge3Controller::SetEpbBreak(const ControlCommand& command) { if (command.parking_brake()) { pc_epb_203_->set_pc_epbreq(Pc_epb_203::PC_EPBREQ_APPLY); } else { pc_epb_203_->set_pc_epbreq(Pc_epb_203::PC_EPBREQ_RELEASE); } } void Ge3Controller::SetBeam(const ControlCommand& command) { if (command.signal().high_beam()) { pc_bcm_201_->set_pc_lowbeamreq(Pc_bcm_201::PC_LOWBEAMREQ_NOREQ); pc_bcm_201_->set_pc_highbeamreq(Pc_bcm_201::PC_HIGHBEAMREQ_REQ); } else if (command.signal().low_beam()) { pc_bcm_201_->set_pc_lowbeamreq(Pc_bcm_201::PC_LOWBEAMREQ_REQ); pc_bcm_201_->set_pc_highbeamreq(Pc_bcm_201::PC_HIGHBEAMREQ_NOREQ); } else { pc_bcm_201_->set_pc_lowbeamreq(Pc_bcm_201::PC_LOWBEAMREQ_NOREQ); pc_bcm_201_->set_pc_highbeamreq(Pc_bcm_201::PC_HIGHBEAMREQ_NOREQ); } } void Ge3Controller::SetHorn(const ControlCommand& command) { if (command.signal().horn()) { pc_bcm_201_->set_pc_hornreq(Pc_bcm_201::PC_HORNREQ_REQ); } else { pc_bcm_201_->set_pc_hornreq(Pc_bcm_201::PC_HORNREQ_NOREQ); } } void Ge3Controller::SetTurningSignal(const ControlCommand& command) { // Set Turn Signal auto signal = command.signal().turn_signal(); if (signal == common::VehicleSignal::TURN_LEFT) { pc_bcm_201_->set_pc_leftturnlampreq(Pc_bcm_201::PC_LEFTTURNLAMPREQ_REQ); pc_bcm_201_->set_pc_rightturnlampreq(Pc_bcm_201::PC_RIGHTTURNLAMPREQ_NOREQ); } else if (signal == common::VehicleSignal::TURN_RIGHT) { pc_bcm_201_->set_pc_leftturnlampreq(Pc_bcm_201::PC_LEFTTURNLAMPREQ_NOREQ); pc_bcm_201_->set_pc_rightturnlampreq(Pc_bcm_201::PC_RIGHTTURNLAMPREQ_REQ); } else { pc_bcm_201_->set_pc_leftturnlampreq(Pc_bcm_201::PC_LEFTTURNLAMPREQ_NOREQ); pc_bcm_201_->set_pc_rightturnlampreq(Pc_bcm_201::PC_RIGHTTURNLAMPREQ_NOREQ); } } void Ge3Controller::ResetProtocol() { message_manager_->ResetSendMessages(); } bool Ge3Controller::CheckChassisError() { ChassisDetail chassis_detail; message_manager_->GetSensorData(&chassis_detail); if (!chassis_detail.has_ge3()) { AERROR_EVERY(100) << "ChassisDetail has NO ge3 vehicle info." << chassis_detail.DebugString(); return false; } Ge3 ge3 = chassis_detail.ge3(); // check steer error if (ge3.has_scu_eps_311()) { if (Scu_eps_311::EPS_FAULTST_FAULT == ge3.scu_eps_311().eps_faultst()) { return true; } } // check vcu error if (ge3.has_scu_vcu_1_312() && Scu_vcu_1_312::VCU_FAULTST_NORMAL != ge3.scu_vcu_1_312().vcu_faultst()) { return true; } // check braking error if (ge3.has_scu_bcs_1_306()) { if (Scu_bcs_1_306::BCS_FAULTST_FAULT == ge3.scu_bcs_1_306().bcs_faultst()) { return true; } } // check gear error if (ge3.has_scu_vcu_1_312()) { if (Scu_vcu_1_312::VCU_GEARFAULTST_FAULT == ge3.scu_vcu_1_312().vcu_gearfaultst()) { return true; } } // check parking error if (ge3.has_scu_epb_310()) { if (Scu_epb_310::EPB_FAULTST_FAULT == ge3.scu_epb_310().epb_faultst()) { return true; } } // check the whole vehicle error if (ge3.has_scu_1_301()) { if (Scu_1_301::SCU_FAULTST_NORMAL != ge3.scu_1_301().scu_faultst()) { return true; } } return false; } void Ge3Controller::SecurityDogThreadFunc() { int32_t vertical_ctrl_fail = 0; int32_t horizontal_ctrl_fail = 0; if (can_sender_ == nullptr) { AERROR << "Failed to run SecurityDogThreadFunc() because can_sender_ is " "nullptr."; return; } while (!can_sender_->IsRunning()) { std::this_thread::yield(); } std::chrono::duration<double, std::micro> default_period{50000}; int64_t start = 0; int64_t end = 0; while (can_sender_->IsRunning()) { start = ::apollo::common::time::AsInt64<::apollo::common::time::micros>( ::apollo::common::time::Clock::Now()); const Chassis::DrivingMode mode = driving_mode(); bool emergency_mode = false; // 1. horizontal control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_STEER_ONLY) && !CheckResponse(CHECK_RESPONSE_STEER_UNIT_FLAG, false)) { ++horizontal_ctrl_fail; if (horizontal_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { horizontal_ctrl_fail = 0; } // 2. vertical control check if ((mode == Chassis::COMPLETE_AUTO_DRIVE || mode == Chassis::AUTO_SPEED_ONLY) && !CheckResponse(CHECK_RESPONSE_SPEED_UNIT_FLAG, false)) { ++vertical_ctrl_fail; if (vertical_ctrl_fail >= kMaxFailAttempt) { emergency_mode = true; set_chassis_error_code(Chassis::MANUAL_INTERVENTION); } } else { vertical_ctrl_fail = 0; } if (CheckChassisError()) { set_chassis_error_code(Chassis::CHASSIS_ERROR); emergency_mode = true; } if (emergency_mode && mode != Chassis::EMERGENCY_MODE) { set_driving_mode(Chassis::EMERGENCY_MODE); message_manager_->ResetSendMessages(); } end = ::apollo::common::time::AsInt64<::apollo::common::time::micros>( ::apollo::common::time::Clock::Now()); std::chrono::duration<double, std::micro> elapsed{end - start}; if (elapsed < default_period) { std::this_thread::sleep_for(default_period - elapsed); } else { AERROR << "Too much time consumption in Ge3Controller looping process:" << elapsed.count(); } } } bool Ge3Controller::CheckResponse(const int32_t flags, bool need_wait) { int32_t retry_num = 20; ChassisDetail chassis_detail; bool is_eps_online = false; bool is_vcu_online = false; bool is_esp_online = false; do { if (message_manager_->GetSensorData(&chassis_detail) != ErrorCode::OK) { AERROR_EVERY(100) << "get chassis detail failed."; return false; } bool check_ok = true; if (flags & CHECK_RESPONSE_STEER_UNIT_FLAG) { is_eps_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_eps_online() && chassis_detail.check_response().is_eps_online(); check_ok = check_ok && is_eps_online; } if (flags & CHECK_RESPONSE_SPEED_UNIT_FLAG) { is_vcu_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_vcu_online() && chassis_detail.check_response().is_vcu_online(); is_esp_online = chassis_detail.has_check_response() && chassis_detail.check_response().has_is_esp_online() && chassis_detail.check_response().is_esp_online(); check_ok = check_ok && is_vcu_online && is_esp_online; } if (check_ok) { return true; } AINFO << "Need to check response again."; if (need_wait) { --retry_num; std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(20)); } } while (need_wait && retry_num); AINFO << "check_response fail: is_eps_online:" << is_eps_online << ", is_vcu_online:" << is_vcu_online << ", is_esp_online:" << is_esp_online; return false; } void Ge3Controller::set_chassis_error_mask(const int32_t mask) { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); chassis_error_mask_ = mask; } int32_t Ge3Controller::chassis_error_mask() { std::lock_guard<std::mutex> lock(chassis_mask_mutex_); return chassis_error_mask_; } Chassis::ErrorCode Ge3Controller::chassis_error_code() { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); return chassis_error_code_; } void Ge3Controller::set_chassis_error_code( const Chassis::ErrorCode& error_code) { std::lock_guard<std::mutex> lock(chassis_error_code_mutex_); chassis_error_code_ = error_code; } bool Ge3Controller::CheckSafetyError( const ::apollo::canbus::ChassisDetail& chassis_detail) { return false; } } // namespace ge3 } // namespace canbus } // namespace apollo
[ "qi.stephen.luo@gmail.com" ]
qi.stephen.luo@gmail.com
c6b25cec636f37b3566a7c0a5d559d31db0c6bf2
a1c1e3b63413b672156fc0f402c0e7372b15ec52
/tests/evolucionToroideTEST.cpp
00257798c65f62cf8f2c5df515fe459b58f2d15b
[]
no_license
dbernard96/tpImplementacion
23e86bb91db21234a0a1f379e1b4e3b3f4a25f00
1663165c2805cd07153e561bfc849601235f9365
refs/heads/master
2020-04-03T13:41:05.542272
2018-12-10T21:23:46
2018-12-10T21:23:46
155,293,609
0
0
null
null
null
null
UTF-8
C++
false
false
2,811
cpp
#include "../solucion.h" #include "gtest/gtest.h" #include <algorithm> using namespace std; TEST(evolucionToroideTEST, toroideDiagonalTresPorTresUnPaso){ toroide t = { {true, false, false}, {false, true, false}, {false, false, true} }; //1*0 0 1*0 //0 1 0 0 1 //0 0 1 0 0 //1 0 0 1 0 //0*1 0 0*1 toroide evo_t = { {true, true, true}, {true, true, true}, {true, true, true} }; // 1 1 1 // 1 1 1 // 1 1 1 evolucionToroide(t); EXPECT_EQ(t, evo_t); } TEST(evolucionToroideTEST, toroideDiagonalTresPorTresDosPasos){ toroide t = { {true, false, false}, {false, true, false}, {false, false, true} }; // Ver toroideDiagonalTresPorTresUnPaso toroide evo_t = { {false, false, false}, {false, false, false}, {false, false, false} }; evolucionToroide(t); evolucionToroide(t); EXPECT_EQ(t, evo_t); } TEST(evolucionToroideTEST, toroideTodoFalso20Pasos){ toroide t = { {false, false, false}, {false, false, false}, {false, false, false} }; toroide evo_t = { {false, false, false}, {false, false, false}, {false, false, false} }; for (int i = 0; i < 20; ++i) evolucionToroide(t); EXPECT_EQ(t, evo_t); } TEST(evolucionToroideTEST, toroideUnaFilaTrueEnCentro){ toroide t = { {false, true, false}}; //0*0 1 0*0 //0 0 1 0 0 //0*0 1 0*0 toroide evo_t = { {true, true, true}}; evolucionToroide(t); EXPECT_EQ(t, evo_t); } TEST(evolucionToroideTEST, toroideUnaColumnaTrueEnCentro){ toroide t = { {false}, {true}, {false}}; // Ver toroideUnaFilaTrueEnCentro toroide evo_t = { {true}, {true}, {true}}; evolucionToroide(t); EXPECT_EQ(t, evo_t); } TEST(evolucionToroideTEST, toroideUnaFilaFTTF){ toroide t = { {false, true, true, false}}; //0*0 1 1 0*0 //0 0 1 1 0 0 //0*0 1 1 0*0 toroide evo_t = { {true, false, false, true}}; evolucionToroide(t); EXPECT_EQ(t, evo_t); } TEST(evolucionToroideTEST, toroide5EvolucionesVsEvolucion5){ toroide t = { {false, false, false, false, false}, {false, true, true, false, true}, {false, false, true, false, true}, {false, true, true, false, true}, {false, false, false, false, true}, {false, true, false, false, false}, {false, true, false, false, true} }; toroide t2 = t; for (int i = 0; i < 5; ++i) evolucionToroide(t); toroide evo_5 = evolucionMultiple(t2, 5); EXPECT_EQ(t, evo_5); } TEST(evolucionToroideTEST, toroideDiagonalSeHaceTodoTrue){ toroide t1 = { {true, false, false}, {false, true, false}, {false, false, true} }; toroide t2 = { {true, true, true}, {true, true, true}, {true, true, true}}; evolucionToroide(t1); EXPECT_EQ(t1, t2); }
[ "davidbernard456@gmail.com" ]
davidbernard456@gmail.com
9b1dd5bcfd7880efd266845aee8fdfe1f151c9c9
06eb60c98f4d106fc3bb3d0b7e990828b87d714d
/Source/WebCore/html/parser/XSSAuditor.cpp
9dc1026f23089bfdb932af7df4d0815cbc4194f1
[]
no_license
snyh/dui
9486a81d97ec1173b161b6aef8fcea21066aebff
c4464629f1efdecae792ed3abc2a7fc9ce9b88db
refs/heads/master
2021-01-25T08:28:55.224303
2013-10-23T00:42:02
2013-10-23T00:42:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,692
cpp
/* * Copyright (C) 2011 Adam Barth. All Rights Reserved. * Copyright (C) 2011 Daniel Bates (dbates@intudata.com). * * 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. */ #include "config.h" #include "html/parser/XSSAuditor.h" #include "platform/text/DecodeEscapeSequences.h" #include "dom/Document.h" #include "loader/DocumentLoader.h" #include "platform/network/FormData.h" #include "page/Frame.h" #include "html/parser/HTMLDocumentParser.h" #include "HTMLNames.h" #include "html/HTMLParamElement.h" #include "html/parser/HTMLParserIdioms.h" #include "platform/KURL.h" #include "page/Settings.h" #include "platform/text/TextEncoding.h" #include "loader/TextResourceDecoder.h" #include "XLinkNames.h" #include "html/parser/XSSAuditorDelegate.h" #if ENABLE(SVG) #include "SVGNames.h" #endif #include <wtf/MainThread.h> namespace WebCore { using namespace HTMLNames; static bool isNonCanonicalCharacter(UChar c) { // We remove all non-ASCII characters, including non-printable ASCII characters. // // Note, we don't remove backslashes like PHP stripslashes(), which among other things converts "\\0" to the \0 character. // Instead, we remove backslashes and zeros (since the string "\\0" =(remove backslashes)=> "0"). However, this has the // adverse effect that we remove any legitimate zeros from a string. // // For instance: new String("http://localhost:8000") => new String("http://localhost:8"). return (c == '\\' || c == '0' || c == '\0' || c >= 127); } static String canonicalize(const String& string) { return string.removeCharacters(&isNonCanonicalCharacter); } static bool isRequiredForInjection(UChar c) { return (c == '\'' || c == '"' || c == '<' || c == '>'); } static bool isTerminatingCharacter(UChar c) { return (c == '&' || c == '/' || c == '"' || c == '\'' || c == '<' || c == '>' || c == ','); } static bool isHTMLQuote(UChar c) { return (c == '"' || c == '\''); } static bool isJSNewline(UChar c) { // Per ecma-262 section 7.3 Line Terminators. return (c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029); } static bool startsHTMLCommentAt(const String& string, size_t start) { return (start + 3 < string.length() && string[start] == '<' && string[start+1] == '!' && string[start+2] == '-' && string[start+3] == '-'); } static bool startsSingleLineCommentAt(const String& string, size_t start) { return (start + 1 < string.length() && string[start] == '/' && string[start+1] == '/'); } static bool startsMultiLineCommentAt(const String& string, size_t start) { return (start + 1 < string.length() && string[start] == '/' && string[start+1] == '*'); } // If other files need this, we should move this to HTMLParserIdioms.h template<size_t inlineCapacity> bool threadSafeMatch(const Vector<UChar, inlineCapacity>& vector, const QualifiedName& qname) { return equalIgnoringNullity(vector, qname.localName().impl()); } static bool hasName(const HTMLToken& token, const QualifiedName& name) { return threadSafeMatch(token.name(), name); } static bool findAttributeWithName(const HTMLToken& token, const QualifiedName& name, size_t& indexOfMatchingAttribute) { // Notice that we're careful not to ref the StringImpl here because we might be on a background thread. const String& attrName = name.namespaceURI() == XLinkNames::xlinkNamespaceURI ? "xlink:" + name.localName().string() : name.localName().string(); for (size_t i = 0; i < token.attributes().size(); ++i) { if (equalIgnoringNullity(token.attributes().at(i).name, attrName)) { indexOfMatchingAttribute = i; return true; } } return false; } static bool isNameOfInlineEventHandler(const Vector<UChar, 32>& name) { const size_t lengthOfShortestInlineEventHandlerName = 5; // To wit: oncut. if (name.size() < lengthOfShortestInlineEventHandlerName) return false; return name[0] == 'o' && name[1] == 'n'; } static bool isDangerousHTTPEquiv(const String& value) { String equiv = value.stripWhiteSpace(); return equalIgnoringCase(equiv, "refresh") || equalIgnoringCase(equiv, "set-cookie"); } static inline String decode16BitUnicodeEscapeSequences(const String& string) { // Note, the encoding is ignored since each %u-escape sequence represents a UTF-16 code unit. return decodeEscapeSequences<Unicode16BitEscapeSequence>(string, UTF8Encoding()); } static inline String decodeStandardURLEscapeSequences(const String& string, const TextEncoding& encoding) { // We use decodeEscapeSequences() instead of decodeURLEscapeSequences() (declared in KURL.h) to // avoid platform-specific URL decoding differences (e.g. KURLGoogle). return decodeEscapeSequences<URLEscapeSequence>(string, encoding); } static String fullyDecodeString(const String& string, const TextEncoding& encoding) { size_t oldWorkingStringLength; String workingString = string; do { oldWorkingStringLength = workingString.length(); workingString = decode16BitUnicodeEscapeSequences(decodeStandardURLEscapeSequences(workingString, encoding)); } while (workingString.length() < oldWorkingStringLength); workingString.replace('+', ' '); workingString = canonicalize(workingString); return workingString; } static bool isSemicolonSeparatedAttribute(const HTMLToken::Attribute& attribute) { #if ENABLE(SVG) return threadSafeMatch(attribute.name, SVGNames::valuesAttr); #else return false; #endif } static bool semicolonSeparatedValueContainsJavaScriptURL(const String& value) { Vector<String> valueList; value.split(';', valueList); for (size_t i = 0; i < valueList.size(); ++i) { if (protocolIsJavaScript(valueList[i])) return true; } return false; } XSSAuditor::XSSAuditor() : m_isEnabled(false) , m_didSendValidCSPHeader(false) , m_didSendValidXSSProtectionHeader(false) , m_state(Uninitialized) , m_scriptTagNestingLevel(0) , m_encoding(UTF8Encoding()) { // Although tempting to call init() at this point, the various objects // we want to reference might not all have been constructed yet. } void XSSAuditor::initForFragment() { ASSERT(isMainThread()); ASSERT(m_state == Uninitialized); m_state = Initialized; // When parsing a fragment, we don't enable the XSS auditor because it's // too much overhead. ASSERT(!m_isEnabled); } void XSSAuditor::init(Document* document, XSSAuditorDelegate* auditorDelegate) { const size_t miniumLengthForSuffixTree = 512; // FIXME: Tune this parameter. const int suffixTreeDepth = 5; ASSERT(isMainThread()); if (m_state == Initialized) return; ASSERT(m_state == Uninitialized); m_state = Initialized; if (Frame* frame = document->frame()) if (Settings* settings = frame->settings()) m_isEnabled = settings->xssAuditorEnabled(); if (!m_isEnabled) return; m_documentURL = document->url().copy(); // In theory, the Document could have detached from the Frame after the // XSSAuditor was constructed. if (!document->frame()) { m_isEnabled = false; return; } if (m_documentURL.isEmpty()) { // The URL can be empty when opening a new browser window or calling window.open(""). m_isEnabled = false; return; } if (m_documentURL.protocolIsData()) { m_isEnabled = false; return; } if (document->decoder()) m_encoding = document->decoder()->encoding(); m_decodedURL = fullyDecodeString(m_documentURL.string(), m_encoding); if (m_decodedURL.find(isRequiredForInjection) == notFound) m_decodedURL = String(); String httpBodyAsString; if (DocumentLoader* documentLoader = document->frame()->loader()->documentLoader()) { DEFINE_STATIC_LOCAL(String, XSSProtectionHeader, (ASCIILiteral("X-XSS-Protection"))); String headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader); String errorDetails; unsigned errorPosition = 0; String reportURL; KURL xssProtectionReportURL; // FIXME: Combine the two report URLs in some reasonable way. if (auditorDelegate) auditorDelegate->setReportURL(xssProtectionReportURL.copy()); FormData* httpBody = documentLoader->originalRequest().httpBody(); if (httpBody && !httpBody->isEmpty()) { httpBodyAsString = httpBody->flattenToString(); if (!httpBodyAsString.isEmpty()) { m_decodedHTTPBody = fullyDecodeString(httpBodyAsString, m_encoding); if (m_decodedHTTPBody.find(isRequiredForInjection) == notFound) m_decodedHTTPBody = String(); if (m_decodedHTTPBody.length() >= miniumLengthForSuffixTree) m_decodedHTTPBodySuffixTree = adoptPtr(new SuffixTree<ASCIICodebook>(m_decodedHTTPBody, suffixTreeDepth)); } } } if (m_decodedURL.isEmpty() && m_decodedHTTPBody.isEmpty()) { m_isEnabled = false; return; } } PassOwnPtr<XSSInfo> XSSAuditor::filterToken(const FilterTokenRequest& request) { ASSERT(m_state == Initialized); return nullptr; } bool XSSAuditor::filterStartToken(const FilterTokenRequest& request) { bool didBlockScript = eraseDangerousAttributesIfInjected(request); if (hasName(request.token, paramTag)) didBlockScript |= filterParamToken(request); else if (hasName(request.token, iframeTag)) didBlockScript |= filterIframeToken(request); else if (hasName(request.token, metaTag)) didBlockScript |= filterMetaToken(request); else if (hasName(request.token, baseTag)) didBlockScript |= filterBaseToken(request); else if (hasName(request.token, formTag)) didBlockScript |= filterFormToken(request); else if (hasName(request.token, inputTag)) didBlockScript |= filterInputToken(request); else if (hasName(request.token, buttonTag)) didBlockScript |= filterButtonToken(request); return didBlockScript; } void XSSAuditor::filterEndToken(const FilterTokenRequest& request) { } bool XSSAuditor::filterCharacterToken(const FilterTokenRequest& request) { ASSERT(m_scriptTagNestingLevel); if (isContainedInRequest(m_cachedDecodedSnippet) && isContainedInRequest(decodedSnippetForJavaScript(request))) { request.token.eraseCharacters(); request.token.appendToCharacter(' '); // Technically, character tokens can't be empty. return true; } return false; } bool XSSAuditor::filterScriptToken(const FilterTokenRequest& request) { return false; } bool XSSAuditor::filterObjectToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); bool didBlockScript = false; if (isContainedInRequest(decodedSnippetForName(request))) { didBlockScript |= eraseAttributeIfInjected(request, dataAttr, blankURL().string(), SrcLikeAttribute); didBlockScript |= eraseAttributeIfInjected(request, typeAttr); didBlockScript |= eraseAttributeIfInjected(request, classidAttr); } return didBlockScript; } bool XSSAuditor::filterParamToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, paramTag)); size_t indexOfNameAttribute; if (!findAttributeWithName(request.token, nameAttr, indexOfNameAttribute)) return false; const HTMLToken::Attribute& nameAttribute = request.token.attributes().at(indexOfNameAttribute); if (!HTMLParamElement::isURLParameter(String(nameAttribute.value))) return false; return eraseAttributeIfInjected(request, valueAttr, blankURL().string(), SrcLikeAttribute); } bool XSSAuditor::filterEmbedToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); bool didBlockScript = false; if (isContainedInRequest(decodedSnippetForName(request))) { didBlockScript |= eraseAttributeIfInjected(request, codeAttr, String(), SrcLikeAttribute); didBlockScript |= eraseAttributeIfInjected(request, srcAttr, blankURL().string(), SrcLikeAttribute); didBlockScript |= eraseAttributeIfInjected(request, typeAttr); } return didBlockScript; } bool XSSAuditor::filterIframeToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, iframeTag)); bool didBlockScript = false; if (isContainedInRequest(decodedSnippetForName(request))) { didBlockScript |= eraseAttributeIfInjected(request, srcAttr, String(), SrcLikeAttribute); didBlockScript |= eraseAttributeIfInjected(request, srcdocAttr, String(), ScriptLikeAttribute); } return didBlockScript; } bool XSSAuditor::filterMetaToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, metaTag)); return eraseAttributeIfInjected(request, http_equivAttr); } bool XSSAuditor::filterBaseToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, baseTag)); return eraseAttributeIfInjected(request, hrefAttr); } bool XSSAuditor::filterFormToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, formTag)); return eraseAttributeIfInjected(request, actionAttr, blankURL().string()); } bool XSSAuditor::filterInputToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, inputTag)); return eraseAttributeIfInjected(request, formactionAttr, blankURL().string(), SrcLikeAttribute); } bool XSSAuditor::filterButtonToken(const FilterTokenRequest& request) { ASSERT(request.token.type() == HTMLToken::StartTag); ASSERT(hasName(request.token, buttonTag)); return eraseAttributeIfInjected(request, formactionAttr, blankURL().string(), SrcLikeAttribute); } bool XSSAuditor::eraseDangerousAttributesIfInjected(const FilterTokenRequest& request) { DEFINE_STATIC_LOCAL(String, safeJavaScriptURL, (ASCIILiteral("javascript:void(0)"))); bool didBlockScript = false; for (size_t i = 0; i < request.token.attributes().size(); ++i) { const HTMLToken::Attribute& attribute = request.token.attributes().at(i); bool isInlineEventHandler = isNameOfInlineEventHandler(attribute.name); // FIXME: It would be better if we didn't create a new String for every attribute in the document. String strippedValue = stripLeadingAndTrailingHTMLSpaces(String(attribute.value)); bool valueContainsJavaScriptURL = (!isInlineEventHandler && protocolIsJavaScript(strippedValue)) || (isSemicolonSeparatedAttribute(attribute) && semicolonSeparatedValueContainsJavaScriptURL(strippedValue)); if (!isInlineEventHandler && !valueContainsJavaScriptURL) continue; if (!isContainedInRequest(decodedSnippetForAttribute(request, attribute, ScriptLikeAttribute))) continue; request.token.eraseValueOfAttribute(i); if (valueContainsJavaScriptURL) request.token.appendToAttributeValue(i, safeJavaScriptURL); didBlockScript = true; } return didBlockScript; } bool XSSAuditor::eraseAttributeIfInjected(const FilterTokenRequest& request, const QualifiedName& attributeName, const String& replacementValue, AttributeKind treatment) { size_t indexOfAttribute = 0; if (findAttributeWithName(request.token, attributeName, indexOfAttribute)) { const HTMLToken::Attribute& attribute = request.token.attributes().at(indexOfAttribute); if (isContainedInRequest(decodedSnippetForAttribute(request, attribute, treatment))) { if (threadSafeMatch(attributeName, srcAttr) && isLikelySafeResource(String(attribute.value))) return false; if (threadSafeMatch(attributeName, http_equivAttr) && !isDangerousHTTPEquiv(String(attribute.value))) return false; request.token.eraseValueOfAttribute(indexOfAttribute); if (!replacementValue.isEmpty()) request.token.appendToAttributeValue(indexOfAttribute, replacementValue); return true; } } return false; } String XSSAuditor::decodedSnippetForName(const FilterTokenRequest& request) { // Grab a fixed number of characters equal to the length of the token's name plus one (to account for the "<"). return fullyDecodeString(request.sourceTracker.sourceForToken(request.token), m_encoding).substring(0, request.token.name().size() + 1); } String XSSAuditor::decodedSnippetForAttribute(const FilterTokenRequest& request, const HTMLToken::Attribute& attribute, AttributeKind treatment) { // The range doesn't inlcude the character which terminates the value. So, // for an input of |name="value"|, the snippet is |name="value|. For an // unquoted input of |name=value |, the snippet is |name=value|. // FIXME: We should grab one character before the name also. int start = attribute.nameRange.start - request.token.startIndex(); int end = attribute.valueRange.end - request.token.startIndex(); String decodedSnippet = fullyDecodeString(request.sourceTracker.sourceForToken(request.token).substring(start, end - start), m_encoding); decodedSnippet.truncate(kMaximumFragmentLengthTarget); if (treatment == SrcLikeAttribute) { int slashCount = 0; bool commaSeen = false; // In HTTP URLs, characters following the first ?, #, or third slash may come from // the page itself and can be merely ignored by an attacker's server when a remote // script or script-like resource is requested. In DATA URLS, the payload starts at // the first comma, and the the first /*, //, or <!-- may introduce a comment. Characters // following this may come from the page itself and may be ignored when the script is // executed. For simplicity, we don't differentiate based on URL scheme, and stop at // the first # or ?, the third slash, or the first slash or < once a comma is seen. for (size_t currentLength = 0; currentLength < decodedSnippet.length(); ++currentLength) { UChar currentChar = decodedSnippet[currentLength]; if (currentChar == '?' || currentChar == '#' || ((currentChar == '/' || currentChar == '\\') && (commaSeen || ++slashCount > 2)) || (currentChar == '<' && commaSeen)) { decodedSnippet.truncate(currentLength); break; } if (currentChar == ',') commaSeen = true; } } else if (treatment == ScriptLikeAttribute) { // Beware of trailing characters which came from the page itself, not the // injected vector. Excluding the terminating character covers common cases // where the page immediately ends the attribute, but doesn't cover more // complex cases where there is other page data following the injection. // Generally, these won't parse as javascript, so the injected vector // typically excludes them from consideration via a single-line comment or // by enclosing them in a string literal terminated later by the page's own // closing punctuation. Since the snippet has not been parsed, the vector // may also try to introduce these via entities. As a result, we'd like to // stop before the first "//", the first <!--, the first entity, or the first // quote not immediately following the first equals sign (taking whitespace // into consideration). To keep things simpler, we don't try to distinguish // between entity-introducing amperands vs. other uses, nor do we bother to // check for a second slash for a comment, nor do we bother to check for // !-- following a less-than sign. We stop instead on any ampersand // slash, or less-than sign. size_t position = 0; if ((position = decodedSnippet.find("=")) != notFound && (position = decodedSnippet.find(isNotHTMLSpace, position + 1)) != notFound && (position = decodedSnippet.find(isTerminatingCharacter, isHTMLQuote(decodedSnippet[position]) ? position + 1 : position)) != notFound) { decodedSnippet.truncate(position); } } return decodedSnippet; } String XSSAuditor::decodedSnippetForJavaScript(const FilterTokenRequest& request) { String string = request.sourceTracker.sourceForToken(request.token); size_t startPosition = 0; size_t endPosition = string.length(); size_t foundPosition = notFound; // Skip over initial comments to find start of code. while (startPosition < endPosition) { while (startPosition < endPosition && isHTMLSpace(string[startPosition])) startPosition++; // Under SVG/XML rules, only HTML comment syntax matters and the parser returns // these as a separate comment tokens. Having consumed whitespace, we need not look // further for these. if (request.shouldAllowCDATA) break; // Under HTML rules, both the HTML and JS comment synatx matters, and the HTML // comment ends at the end of the line, not with -->. if (startsHTMLCommentAt(string, startPosition) || startsSingleLineCommentAt(string, startPosition)) { while (startPosition < endPosition && !isJSNewline(string[startPosition])) startPosition++; } else if (startsMultiLineCommentAt(string, startPosition)) { if (startPosition + 2 < endPosition && (foundPosition = string.find("*/", startPosition + 2)) != notFound) startPosition = foundPosition + 2; else startPosition = endPosition; } else break; } String result; while (startPosition < endPosition && !result.length()) { // Stop at next comment (using the same rules as above for SVG/XML vs HTML), when we // encounter a comma, or when we exceed the maximum length target. The comma rule // covers a common parameter concatenation case performed by some webservers. // After hitting the length target, we can only stop at a point where we know we are // not in the middle of a %-escape sequence. For the sake of simplicity, approximate // not stopping inside a (possibly multiply encoded) %-esacpe sequence by breaking on // whitespace only. We should have enough text in these cases to avoid false positives. for (foundPosition = startPosition; foundPosition < endPosition; foundPosition++) { if (!request.shouldAllowCDATA) { if (startsSingleLineCommentAt(string, foundPosition) || startsMultiLineCommentAt(string, foundPosition)) { foundPosition += 2; break; } if (startsHTMLCommentAt(string, foundPosition)) { foundPosition += 4; break; } } if (string[foundPosition] == ',' || (foundPosition > startPosition + kMaximumFragmentLengthTarget && isHTMLSpace(string[foundPosition]))) { break; } } result = fullyDecodeString(string.substring(startPosition, foundPosition - startPosition), m_encoding); startPosition = foundPosition + 1; } return result; } bool XSSAuditor::isContainedInRequest(const String& decodedSnippet) { if (decodedSnippet.isEmpty()) return false; if (m_decodedURL.find(decodedSnippet, 0, false) != notFound) return true; if (m_decodedHTTPBodySuffixTree && !m_decodedHTTPBodySuffixTree->mightContain(decodedSnippet)) return false; return m_decodedHTTPBody.find(decodedSnippet, 0, false) != notFound; } bool XSSAuditor::isLikelySafeResource(const String& url) { // Give empty URLs and about:blank a pass. Making a resourceURL from an // empty string below will likely later fail the "no query args test" as // it inherits the document's query args. if (url.isEmpty() || url == blankURL().string()) return true; // If the resource is loaded from the same host as the enclosing page, it's // probably not an XSS attack, so we reduce false positives by allowing the // request, ignoring scheme and port considerations. If the resource has a // query string, we're more suspicious, however, because that's pretty rare // and the attacker might be able to trick a server-side script into doing // something dangerous with the query string. if (m_documentURL.host().isEmpty()) return false; KURL resourceURL(m_documentURL, url); return (m_documentURL.host() == resourceURL.host() && resourceURL.query().isEmpty()); } bool XSSAuditor::isSafeToSendToAnotherThread() const { return m_documentURL.isSafeToSendToAnotherThread() && m_decodedURL.isSafeToSendToAnotherThread() && m_decodedHTTPBody.isSafeToSendToAnotherThread() && m_cachedDecodedSnippet.isSafeToSendToAnotherThread(); } } // namespace WebCore
[ "snyh@snyh.org" ]
snyh@snyh.org
8cc333258ddd8532c30d0e726ee3a74d6212900e
4212b420e0067e14c97d14a31b6444c28215903f
/Programs/myLibrary/makeTest/PatriciaTree/patricia.cpp
b17ac992d0725f579be8554fa22d4b66287d8866
[]
no_license
StavrosMar/CPP
929f6dc4e642a32e8d0bd84994b94b90cd19f64e
3512dc09bf6b2a93130898c16471768052ad5ca1
refs/heads/master
2021-09-23T18:16:55.619093
2021-09-13T17:41:05
2021-09-13T17:41:05
86,387,879
0
0
null
2018-08-06T15:41:03
2017-03-27T21:57:04
C++
UTF-8
C++
false
false
307
cpp
#include "patricia.h" template <class T> Node<T>::Node() { left = this; right = this; bitIndex = 0; //the rest default construction. } template <class T> Node<T>::Node(const string& key, const T& data) { left = this; right = this; bitIndex = 0.0; this->data = data; this->key = key; } //#endif
[ "redenicht@hotmail.com" ]
redenicht@hotmail.com
30a8490f985195b1b83c0cc992fff09e5ede2ddf
fbb03f0345a0ac574a1696449ec756c308b4c5c7
/Source/ProjectFPSTest/ProjectFPSTestProjectile.cpp
ff5d842b31e5f349bdddefbab765f8a648a74554
[]
no_license
BlancLohan/GALandProject
bccdb4712c57b01505afb39b55a9d41054fc3a0b
6501545c5fa7c32f6863112ce5c37374ea28b909
refs/heads/main
2023-03-29T10:46:57.006496
2021-04-06T19:43:58
2021-04-06T19:43:58
355,117,700
0
0
null
null
null
null
UTF-8
C++
false
false
1,794
cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "ProjectFPSTestProjectile.h" #include "GameFramework/ProjectileMovementComponent.h" #include "Components/SphereComponent.h" AProjectFPSTestProjectile::AProjectFPSTestProjectile() { // Use a sphere as a simple collision representation CollisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp")); CollisionComp->InitSphereRadius(5.0f); CollisionComp->BodyInstance.SetCollisionProfileName("Projectile"); CollisionComp->OnComponentHit.AddDynamic(this, &AProjectFPSTestProjectile::OnHit); // set up a notification for when this component hits something blocking // Players can't walk on it CollisionComp->SetWalkableSlopeOverride(FWalkableSlopeOverride(WalkableSlope_Unwalkable, 0.f)); CollisionComp->CanCharacterStepUpOn = ECB_No; // Set as root component RootComponent = CollisionComp; // Use a ProjectileMovementComponent to govern this projectile's movement ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileComp")); ProjectileMovement->UpdatedComponent = CollisionComp; ProjectileMovement->InitialSpeed = 3000.f; ProjectileMovement->MaxSpeed = 3000.f; ProjectileMovement->bRotationFollowsVelocity = true; ProjectileMovement->bShouldBounce = true; // Die after 3 seconds by default InitialLifeSpan = 3.0f; } void AProjectFPSTestProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { // Only add impulse and destroy projectile if we hit a physics if ((OtherActor != NULL) && (OtherActor != this) && (OtherComp != NULL) && OtherComp->IsSimulatingPhysics()) { OtherComp->AddImpulseAtLocation(GetVelocity() * 100.0f, GetActorLocation()); Destroy(); } }
[ "blanclohan2@gmail.com" ]
blanclohan2@gmail.com
63c2c75cb224b9024194cb01d9db934eb71121a3
9e52f9ebd890948abee5a56594dd70038ed3072d
/matlab_tools/CloudsGPUPro6-master/CPUT/CPUT/CPUTPostProcess.cpp
389f29e13fd0327906e13d84445fa85766d1f340
[ "MIT", "BSD-3-Clause" ]
permissive
CS1371/textbook
9b9585ba3b04a46dcf7f2c44346eb12dabff39e3
57bc0fd7cd69bc60f556b231c79679cac3455e4b
refs/heads/master
2020-09-11T17:09:38.080789
2020-07-15T20:05:06
2020-07-15T20:05:06
222,132,166
0
0
MIT
2020-04-13T15:47:11
2019-11-16T17:05:37
C++
UTF-8
C++
false
false
6,072
cpp
//-------------------------------------------------------------------------------------- // Copyright 2013 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS." // INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY, // INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE, // INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. //-------------------------------------------------------------------------------------- #include "CPUT_DX11.h" #include "CPUTPostProcess.h" #include "CPUTRenderTarget.h" #include "CPUTAssetLibrary.h" #include "CPUTMaterial.h" #include "CPUTSprite.h" //----------------------------------------- CPUTPostProcess::~CPUTPostProcess() { SAFE_DELETE( mpFullScreenSprite ); SAFE_RELEASE( mpMaterialComposite ); SAFE_RELEASE( mpMaterialBlurVertical ); SAFE_RELEASE( mpMaterialBlurHorizontal ); SAFE_RELEASE( mpMaterialDownSampleLogLum ); SAFE_RELEASE( mpMaterialDownSample4x4Alpha ); SAFE_RELEASE( mpMaterialDownSample4x4 ); SAFE_RELEASE( mpMaterialDownSampleBackBuffer4x4 ); SAFE_RELEASE( mpMaterialSpriteNoAlpha ); SAFE_DELETE(mpRT1x1 ); SAFE_DELETE(mpRT4x4 ); SAFE_DELETE(mpRT64x64 ); SAFE_DELETE(mpRTDownSample4x4PingPong ); SAFE_DELETE(mpRTDownSample4x4 ); // SAFE_DELETE(mpRTSourceRenderTarget ); // We don't allocate this. Don't delete it. } //----------------------------------------- void CPUTPostProcess::CreatePostProcess( CPUTRenderTargetColor *pSourceRenderTarget ){ mpRTSourceRenderTarget = pSourceRenderTarget; DXGI_FORMAT sourceFormat = mpRTSourceRenderTarget->GetColorFormat(); UINT sourceWidth = mpRTSourceRenderTarget->GetWidth(); UINT sourceHeight = mpRTSourceRenderTarget->GetHeight(); mpRTDownSample4x4 = new CPUTRenderTargetColor(); mpRTDownSample4x4PingPong = new CPUTRenderTargetColor(); mpRT64x64 = new CPUTRenderTargetColor(); mpRT4x4 = new CPUTRenderTargetColor(); mpRT1x1 = new CPUTRenderTargetColor(); mpRTDownSample4x4->CreateRenderTarget( _L("$PostProcessDownsample4x4"), sourceWidth/4, sourceHeight/4, sourceFormat ); mpRTDownSample4x4PingPong->CreateRenderTarget( _L("$PostProcessDownsample4x4PingPong"), sourceWidth/4, sourceHeight/4, sourceFormat ); mpRT64x64->CreateRenderTarget( _L("$PostProcessRT64x64"), 64, 64, DXGI_FORMAT_R32_FLOAT ); mpRT4x4->CreateRenderTarget( _L("$PostProcessRT4x4"), 8, 8, DXGI_FORMAT_R32_FLOAT ); mpRT1x1->CreateRenderTarget( _L("$PostProcessRT1x1"), 1, 1, DXGI_FORMAT_R32_FLOAT ); CPUTAssetLibrary *pLibrary = CPUTAssetLibrary::GetAssetLibrary(); mpMaterialDownSampleBackBuffer4x4 = pLibrary->GetMaterial(_L("PostProcess/DownSampleBackBuffer4x4")); mpMaterialDownSample4x4 = pLibrary->GetMaterial(_L("PostProcess/DownSample4x4")); mpMaterialDownSample4x4Alpha = pLibrary->GetMaterial(_L("PostProcess/DownSample4x4Alpha")); mpMaterialDownSampleLogLum = pLibrary->GetMaterial(_L("PostProcess/DownSampleLogLum")); mpMaterialBlurHorizontal = pLibrary->GetMaterial(_L("PostProcess/BlurHorizontal")); mpMaterialBlurVertical = pLibrary->GetMaterial(_L("PostProcess/BlurVertical")); mpMaterialComposite = pLibrary->GetMaterial(_L("PostProcess/Composite")); mpMaterialSpriteNoAlpha = pLibrary->GetMaterial(_L("PostProcess/Sprite")); mpFullScreenSprite = new CPUTSprite(); mpFullScreenSprite->CreateSprite( -1.0f, -1.0f, 2.0f, 2.0f, _L("Sprite") ); } UINT gPostProcessingMode = 0; //----------------------------------------- void CPUTPostProcess::PerformPostProcess( CPUTRenderParameters &renderParams ) { mpRTDownSample4x4->SetRenderTarget( renderParams); mpFullScreenSprite->DrawSprite( renderParams, *mpMaterialDownSampleBackBuffer4x4 ); mpRTDownSample4x4->RestoreRenderTarget( renderParams ); // Compute average of log of luminance by downsampling log to 64x64, then 4x4, then 1x1 mpRT64x64->SetRenderTarget(renderParams); mpFullScreenSprite->DrawSprite(renderParams, *mpMaterialDownSampleLogLum); mpRT64x64->RestoreRenderTarget( renderParams ); mpRT4x4->SetRenderTarget(renderParams); mpFullScreenSprite->DrawSprite(renderParams, *mpMaterialDownSample4x4); mpRT4x4->RestoreRenderTarget( renderParams ); mpRT1x1->SetRenderTarget(renderParams); mpFullScreenSprite->DrawSprite( renderParams, *mpMaterialDownSample4x4Alpha ); // Partially blend with previous to smooth result over time mpRT1x1->RestoreRenderTarget( renderParams ); // Better blur for bloom UINT ii; UINT numBlurs = 1; // TODO: expose as a config param for( ii=0; ii<numBlurs; ii++ ) { mpRTDownSample4x4PingPong->SetRenderTarget(renderParams); mpFullScreenSprite->DrawSprite( renderParams, *mpMaterialBlurHorizontal ); mpRTDownSample4x4PingPong->RestoreRenderTarget( renderParams ); mpRTDownSample4x4->SetRenderTarget( renderParams); mpFullScreenSprite->DrawSprite( renderParams, *mpMaterialBlurVertical ); mpRTDownSample4x4->RestoreRenderTarget( renderParams ); } mpFullScreenSprite->DrawSprite(renderParams, *mpMaterialComposite); }
[ "alexhrao@gmail.com" ]
alexhrao@gmail.com
87151569473b833a627cc29e1d9ad9ecefac75a6
bebbc4d83e2be98b9c99a31331db1b13ac003619
/GSLAM/orbslam/LoopClosing.h
edf7ebe4824158eb35bc6c26afafe5dbf0daafb8
[]
no_license
B0RJA/GSLAM
46d382e547014d25904173b5bfc2852f80e9535c
0926845cb5bd5657ec13981d3ca64e8d5cbcc89b
refs/heads/master
2021-01-20T16:11:56.933316
2017-05-10T06:11:22
2017-05-10T06:11:22
90,826,594
0
0
null
2017-05-10T06:01:36
2017-05-10T06:01:36
null
UTF-8
C++
false
false
2,807
h
/** * This file is part of ORB-SLAM. * * Copyright (C) 2014 Raúl Mur-Artal <raulmur at unizar dot es> (University of Zaragoza) * For more information see <http://webdiis.unizar.es/~raulmur/orbslam/> * * ORB-SLAM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ORB-SLAM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ORB-SLAM. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LOOPCLOSING_H #define LOOPCLOSING_H #include <boost/thread.hpp> #include "g2o/types/types_seven_dof_expmap.h" #include "OSLAM.h" #include "KeyFrame.h" #include "LocalMapping.h" #include "Map.h" #include "ORBVocabulary.h" #include "Tracking.h" #include "KeyFrameDatabase.h" namespace ORB_SLAM { class Tracking; class LocalMapping; class KeyFrameDatabase; class LoopClosing { public: typedef pair<set<KeyFrame*>,int> ConsistentGroup; typedef map<KeyFrame*,g2o::Sim3,std::less<KeyFrame*>, Eigen::aligned_allocator<std::pair<const KeyFrame*, g2o::Sim3> > > KeyFrameAndPose; public: LoopClosing(Map* pMap, KeyFrameDatabase* pDB, ORBVocabulary* pVoc); void SetTracker(Tracking* pTracker); void SetLocalMapper(LocalMapping* pLocalMapper); void Run(); void InsertKeyFrame(KeyFrame *pKF); void RequestReset(); protected: bool CheckNewKeyFrames(); bool DetectLoop(); bool ComputeSim3(); void SearchAndFuse(KeyFrameAndPose &CorrectedPosesMap); void CorrectLoop(); void ResetIfRequested(); bool mbResetRequested; boost::mutex mMutexReset; Map* mpMap; Tracking* mpTracker; KeyFrameDatabase* mpKeyFrameDB; ORBVocabulary* mpORBVocabulary; LocalMapping *mpLocalMapper; std::list<KeyFrame*> mlpLoopKeyFrameQueue; boost::mutex mMutexLoopQueue; std::vector<float> mvfLevelSigmaSquare; // Loop detector parameters float mnCovisibilityConsistencyTh; // Loop detector variables KeyFrame* mpCurrentKF; KeyFrame* mpMatchedKF; std::vector<ConsistentGroup> mvConsistentGroups; std::vector<KeyFrame*> mvpEnoughConsistentCandidates; std::vector<KeyFrame*> mvpCurrentConnectedKFs; std::vector<MapPoint*> mvpCurrentMatchedPoints; std::vector<MapPoint*> mvpLoopMapPoints; cv::Mat mScw; g2o::Sim3 mg2oScw; double mScale_cw; long unsigned int mLastLoopKFid; }; } //namespace ORB_SLAM #endif // LOOPCLOSING_H
[ "zd5945@126.com" ]
zd5945@126.com
ed0007c4272b44b82a778c0662d4d55a59d48d35
aafccc71b3ba659a9b6a606d805d9889c9fabc09
/hackerearth/octoberSky/terminators.cpp
bcba251b81eb4352fe98f12ae6d517eff3bb33c2
[]
no_license
abhashksingh/practice-programs
6bf37670e8f385a2bb274bb14ffb9052944a9ab5
02602f61ad4812726dedb6c760c81dc647244b8c
refs/heads/master
2021-01-25T05:23:09.630415
2014-08-24T17:07:10
2014-08-24T17:07:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,481
cpp
#include <iostream> #include <string> #include <vector> using namespace std; int max(int a, int b); int lcs_dynamic(vector<int>X, vector<int> Y, int m, int n); void find_lis(vector<int> &a, vector<int> &b); int main(void) { int t,n,i=0; cin>>t; while(t--) { cin>>n; int t1,t2; vector<int>d1,lisd1,seqd1;//int* d1 = new int[n]; vector<int>d2,lisd2,seqd2;//int* d2 = new int[n]; for(i=0;i<n;i++) { cin>>t1>>t2;//d1[i]>>d2[i]; d1.push_back(t1); d2.push_back(t2); //cout<<d1[i]<<" "<<d2[i]<<endl; } find_lis(d1,seqd1); find_lis(d2,seqd2); for (size_t i = 0; i < seqd1.size(); i++) { lisd1.push_back(d1[seqd1[i]]); } for (size_t i = 0; i < seqd2.size(); i++) { lisd2.push_back(d2[seqd2[i]]); } //printf("%d ", d1[seqd1[i]]); cout<<lcs_dynamic(lisd1,lisd2,lisd1.size(),lisd2.size())<<endl;//<<endl<<endl<<endl<<endl; } } int max(int a, int b) { return (a > b)? a : b; } int lcs_dynamic(vector<int>X, vector<int> Y, int m, int n) { int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note *that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i=0; i<=m; i++) { for (j=0; j<=n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if(X[i-1] == Y[j-1]) L[i][j] = L[i-1][j-1] + 1; else L[i][j] = max(L[i-1][j], L[i][j-1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } /* Finds longest strictly increasing subsequence. O(n log k) algorithm. */ void find_lis(vector<int> &a, vector<int> &b) { vector<int> p(a.size()); int u, v; if (a.empty()) return; b.push_back(0); for (size_t i = 1; i < a.size(); i++) { // If next element a[i] is greater than last element of current longest subsequence a[b.back()], just push it at back of "b" and continue if (a[b.back()] < a[i]) { p[i] = b.back(); b.push_back(i); continue; } /* Binary search to find the smallest element referenced by b which is just bigger than a[i] * Note : Binary search is performed on b (and not a). Size of b is always <=k and hence contributes O(log k) to complexity. */ for (u = 0, v = b.size()-1; u < v;) { int c = (u + v) / 2; if (a[b[c]] < a[i]) u=c+1; else v=c; } /* Update b if new value is smaller then previously referenced value */ if (a[i] < a[b[u]]) { if(u > 0) { p[i] = b[u-1]; } b[u] = i; } } for (u = b.size(), v = b.back(); u--; v = p[v]) b[u] = v; }
[ "superabhash@gmail.com" ]
superabhash@gmail.com
7caf9301db727017dd066d9cf0f0c48f0407318f
3e7e738b1a1f2cf872627b1c77a332aba6011aa2
/EnviroTron/firmware/LTR-329.cpp
53d26a2b2573db22015140d22af5747519e1fc51
[]
no_license
watsonboyett/marvin
ee567e897b8d746a2635b526ed11f1ba19b0750d
97e628178310ae57c8d59e26492c36d88f3bcaf2
refs/heads/master
2020-12-25T16:55:03.148311
2019-10-10T08:53:31
2019-10-10T08:53:31
49,543,308
1
0
null
null
null
null
UTF-8
C++
false
false
3,561
cpp
#pragma once #include "I2C_Utils.h" #include <Arduino.h> #define ALS_ADDR (0x29) #define ALS_GAIN_1X (0) #define ALS_GAIN_2X (1) #define ALS_GAIN_4X (2) #define ALS_GAIN_8X (3) #define ALS_GAIN_48X (6) #define ALS_GAIN_96X (7) #define ALS_MODE_STANDBY (0) #define ALS_MODE_ACTIVE (1) #define ALS_CONTR_ADDR (0x80) typedef union { uint8_t reg; struct { bool ALS_Mode : 1; bool SW_Reset : 1; uint8_t ALS_Gain : 3; uint8_t reserved : 3; }; } ALS_CONTR_t; #define ALS_INT_TIME_100ms (0) #define ALS_INT_TIME_50ms (1) #define ALS_INT_TIME_200ms (2) #define ALS_INT_TIME_400ms (3) #define ALS_INT_TIME_150ms (4) #define ALS_INT_TIME_250ms (5) #define ALS_INT_TIME_300ms (6) #define ALS_INT_TIME_350ms (7) #define ALS_MEAS_RATE_50ms (0) #define ALS_MEAS_RATE_100ms (1) #define ALS_MEAS_RATE_200ms (2) #define ALS_MEAS_RATE_500ms (3) #define ALS_MEAS_RATE_1000ms (4) #define ALS_MEAS_RATE_2000ms (5) #define ALS_MEAS_RATE_ADDR (0x85) typedef union { uint8_t reg; struct { uint8_t ALS_Meas_Rate : 3; uint8_t ALS_Int_Time : 3; uint8_t reserved : 2; }; } ALS_MEAS_RATE_t; #define ALS_DATA_CH1_LOW_ADDR (0x88) #define ALS_DATA_CH1_HIGH_ADDR (0x89) #define ALS_DATA_CH0_LOW_ADDR (0x8A) #define ALS_DATA_CH0_HIGH_ADDR (0x8B) typedef union { uint16_t value; struct { uint8_t byte_low; uint8_t byte_high; }; } ALS_DATA_t; #define ALS_PS_STATUS_ADDR (0x8C) typedef union { uint8_t reg; struct { uint8_t reserved : 2; bool ALS_Data_Status : 1; bool ALS_Int_status : 1; uint8_t ALS_Gain : 3; bool ALS_Data_Valid : 1; }; } ALS_PS_STATUS_t; ALS_CONTR_t ALS_control = {0}; float ALS_GainFactor = 1; float CalcGainFactor() { switch(ALS_control.ALS_Gain) { case (ALS_GAIN_1X): ALS_GainFactor = 1 / 1.0; break; case (ALS_GAIN_2X): ALS_GainFactor = 1 / 2.0; break; case (ALS_GAIN_4X): ALS_GainFactor = 1 / 4.0; break; case (ALS_GAIN_8X): ALS_GainFactor = 1 / 8.0; break; case (ALS_GAIN_48X): ALS_GainFactor = 1 / 48.0; break; case (ALS_GAIN_96X): ALS_GainFactor = 1 / 96.0; break; } } bool ALS_configured = false; ALS_MEAS_RATE_t ALS_meas = {0}; void ALS_Setup() { if (!ALS_configured) { delay(1200); ALS_control.ALS_Gain = ALS_GAIN_8X; ALS_control.ALS_Mode = ALS_MODE_ACTIVE; I2C_WriteByte(ALS_ADDR, ALS_CONTR_ADDR, ALS_control.reg); delay(20); ALS_meas.ALS_Meas_Rate = ALS_MEAS_RATE_100ms; ALS_meas.ALS_Int_Time = ALS_INT_TIME_50ms; I2C_WriteByte(ALS_ADDR, ALS_MEAS_RATE_ADDR, ALS_meas.reg); ALS_configured = true; } CalcGainFactor(); } ALS_DATA_t ALS_vis = {0}; ALS_DATA_t ALS_ir = {0}; const float ALS_VIS_CORRECTION_FACTOR = 18.0; float ALS_GetAmbientLightLevel() { float level = (float) ALS_vis.value * ALS_GainFactor * ALS_VIS_CORRECTION_FACTOR; return level; } const float ALS_IR_CORRECTION_FACTOR = 4.5; float ALS_GetIrLightLevel() { float level = (float) ALS_ir.value * ALS_GainFactor * ALS_IR_CORRECTION_FACTOR; return level; } ALS_PS_STATUS_t ALS_status; void ALS_MeasureLight() { // Read data from light sensor I2C_ReadByte(ALS_ADDR, ALS_PS_STATUS_ADDR, &ALS_status.reg, 1); if (ALS_status.ALS_Data_Status) { I2C_ReadByte(ALS_ADDR, ALS_DATA_CH1_LOW_ADDR, &ALS_ir.byte_low, 1); I2C_ReadByte(ALS_ADDR, ALS_DATA_CH1_HIGH_ADDR, &ALS_ir.byte_high, 1); I2C_ReadByte(ALS_ADDR, ALS_DATA_CH0_LOW_ADDR, &ALS_vis.byte_low, 1); I2C_ReadByte(ALS_ADDR, ALS_DATA_CH0_HIGH_ADDR, &ALS_vis.byte_high, 1); } }
[ "watsonboyett@gmail.com" ]
watsonboyett@gmail.com
ab5e13bad1289ffb610611c32bfbdd2bc26cb1f8
ac88987e5c32ed58db7f8ee2e630ce968a44e507
/xoslib/c/src/lib/XosWebRtc/XosWebRtcClient/XosMac/XosMacWebRtcClientBaseWindowPeerImplement.hh
e89a4332d9fe96beb0c1e24ca66c9fdcfe658a9e
[]
no_license
iamrameshkumar/XosWebRTC
d4121f7b29c246a0376da161dc53d4b6f68b50b7
10d022475675dd0640e8a7233f179b8300a94f59
refs/heads/master
2021-05-27T15:14:47.385666
2013-08-08T21:09:26
2013-08-08T21:09:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,758
hh
/////////////////////////////////////////////////////////////////////// /// Copyright 2012, Google Inc. /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions are met: /// /// 1. Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// 2. Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// 3. The name of the author may not be used to endorse or promote products /// derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. /// /// File: XosMacWebRtcClientBaseWindowPeerImplement.hh /// /// Author: $author$ /// Date: 4/12/2012 /////////////////////////////////////////////////////////////////////// #ifndef _XOSMACWEBRTCCLIENTBASEWINDOWPEERIMPLEMENT_HH #define _XOSMACWEBRTCCLIENTBASEWINDOWPEERIMPLEMENT_HH #include "XosWebRtcClientBaseWindow.hpp" #include "XosMacWindow.hh" #if defined(c_NAMESPACE) namespace c_NAMESPACE { #endif // defined(c_NAMESPACE) typedef XosMacWindowImplement XosWebRtcClientBaseWindowPeerImplementImplement; typedef XosMacWindow XosWebRtcClientBaseWindowPeerImplementExtend; /////////////////////////////////////////////////////////////////////// /// Class: XosWebRtcClientBaseWindowPeerImplement /// /// Author: $author$ /// Date: 4/12/2012 /////////////////////////////////////////////////////////////////////// class _EXPORT_CLASS XosWebRtcClientBaseWindowPeerImplement : virtual public XosWebRtcClientBaseWindowPeerImplementImplement, public XosWebRtcClientBaseWindowPeerImplementExtend { public: typedef XosWebRtcClientBaseWindowPeerImplementImplement Implements; typedef XosWebRtcClientBaseWindowPeerImplementExtend Extends; typedef XosWebRtcClientBaseWindow UIWindow; UIWindow& m_uiWindow; /////////////////////////////////////////////////////////////////////// /// Constructor: XosWebRtcClientBaseWindowPeerImplement /// /// Author: $author$ /// Date: 4/12/2012 /////////////////////////////////////////////////////////////////////// XosWebRtcClientBaseWindowPeerImplement (UIWindow& uiWindow) : m_uiWindow(uiWindow) { m_uiWindow.AttachWindowPeer(this); } virtual ~XosWebRtcClientBaseWindowPeerImplement() { m_uiWindow.DetachWindowPeer(); } virtual void OnOpen() { m_uiWindow.InitUIMessageThread(); m_uiWindow.OnOpen(); } virtual void OnClose() { m_uiWindow.OnClose(); m_uiWindow.FinishUIMessageThread(); } }; #if defined(c_NAMESPACE) } #endif // defined(c_NAMESPACE) #endif // _XOSMACWEBRTCCLIENTBASEWINDOWPEERIMPLEMENT_HH
[ "medusade@cox.net" ]
medusade@cox.net
5aeecd3a9cdca093fc8a4084fd3ee50aac857481
c1ff870879152fba2b54eddfb7591ec322eb3061
/plugins/render/ogreRender/3rdParty/ogre/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgram.cpp
bf45978a32ade8f43e33c4d83ee936bfb4f0415c
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
MTASZTAKI/ApertusVR
1a9809fb7af81c3cd7fb732ed481ebe4ce66fefa
424ec5515ae08780542f33cc4841a8f9a96337b3
refs/heads/0.9
2022-12-11T20:03:42.926813
2019-10-11T09:29:45
2019-10-11T09:29:45
73,708,854
188
55
MIT
2022-12-11T08:53:21
2016-11-14T13:48:00
C++
UTF-8
C++
false
false
28,305
cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2016 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLSLExtSupport.h" #include "OgreGLSLLinkProgram.h" #include "OgreStringConverter.h" #include "OgreGLSLGpuProgram.h" #include "OgreGLSLProgram.h" #include "OgreGLSLLinkProgramManager.h" #include "OgreException.h" #include "OgreGpuProgramManager.h" namespace Ogre { namespace GLSL { // a builtin custom attrib name // ---------------------------------------------- // 0 gl_Vertex vertex // 1 n/a blendWeights // 2 gl_Normal normal // 3 gl_Color colour // 4 gl_SecondaryColor secondary_colour // 5 gl_FogCoord fog_coord // 7 n/a blendIndices // 8 gl_MultiTexCoord0 uv0 // 9 gl_MultiTexCoord1 uv1 // 10 gl_MultiTexCoord2 uv2 // 11 gl_MultiTexCoord3 uv3 // 12 gl_MultiTexCoord4 uv4 // 13 gl_MultiTexCoord5 uv5 // 14 gl_MultiTexCoord6 uv6, tangent // 15 gl_MultiTexCoord7 uv7, binormal GLSLLinkProgram::CustomAttribute GLSLLinkProgram::msCustomAttributes[] = { CustomAttribute("vertex", GLGpuProgram::getFixedAttributeIndex(VES_POSITION, 0)), CustomAttribute("blendWeights", GLGpuProgram::getFixedAttributeIndex(VES_BLEND_WEIGHTS, 0)), CustomAttribute("normal", GLGpuProgram::getFixedAttributeIndex(VES_NORMAL, 0)), CustomAttribute("colour", GLGpuProgram::getFixedAttributeIndex(VES_DIFFUSE, 0)), CustomAttribute("secondary_colour", GLGpuProgram::getFixedAttributeIndex(VES_SPECULAR, 0)), CustomAttribute("blendIndices", GLGpuProgram::getFixedAttributeIndex(VES_BLEND_INDICES, 0)), CustomAttribute("uv0", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 0)), CustomAttribute("uv1", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 1)), CustomAttribute("uv2", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 2)), CustomAttribute("uv3", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 3)), CustomAttribute("uv4", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 4)), CustomAttribute("uv5", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 5)), CustomAttribute("uv6", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 6)), CustomAttribute("uv7", GLGpuProgram::getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 7)), CustomAttribute("tangent", GLGpuProgram::getFixedAttributeIndex(VES_TANGENT, 0)), CustomAttribute("binormal", GLGpuProgram::getFixedAttributeIndex(VES_BINORMAL, 0)), }; GLint getGLGeometryInputPrimitiveType(RenderOperation::OperationType operationType, bool requiresAdjacency) { switch (operationType) { case RenderOperation::OT_POINT_LIST: return GL_POINTS; case RenderOperation::OT_LINE_LIST: case RenderOperation::OT_LINE_STRIP: return requiresAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES; default: case RenderOperation::OT_TRIANGLE_LIST: case RenderOperation::OT_TRIANGLE_STRIP: case RenderOperation::OT_TRIANGLE_FAN: return requiresAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES; } } //----------------------------------------------------------------------- GLint getGLGeometryOutputPrimitiveType(RenderOperation::OperationType operationType) { switch (operationType) { case RenderOperation::OT_POINT_LIST: return GL_POINTS; case RenderOperation::OT_LINE_STRIP: return GL_LINE_STRIP; case RenderOperation::OT_TRIANGLE_STRIP: return GL_TRIANGLE_STRIP; default: OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Geometry shader output operation type can only be point list," "line strip or triangle strip", "GLSLLinkProgram::getGLGeometryOutputPrimitiveType"); } } //----------------------------------------------------------------------- GLSLLinkProgram::GLSLLinkProgram(GLSLGpuProgram* vertexProgram, GLSLGpuProgram* geometryProgram, GLSLGpuProgram* fragmentProgram) : mVertexProgram(vertexProgram) , mGeometryProgram(geometryProgram) , mFragmentProgram(fragmentProgram) , mUniformRefsBuilt(false) , mLinked(false) , mTriedToLinkAndFailed(false) , mSkeletalAnimation(false) { // Initialise uniform cache mUniformCache = new GLUniformCache(); } //----------------------------------------------------------------------- GLSLLinkProgram::~GLSLLinkProgram(void) { glDeleteObjectARB(mGLHandle); delete mUniformCache; mUniformCache = 0; } //----------------------------------------------------------------------- void GLSLLinkProgram::activate(void) { if (!mLinked && !mTriedToLinkAndFailed) { glGetError(); //Clean up the error. Otherwise will flood log. mGLHandle = glCreateProgramObjectARB(); GLenum glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLLinkProgram::activate", "Error Creating GLSL Program Object", 0 ); } if ( GpuProgramManager::getSingleton().canGetCompiledShaderBuffer() && GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(getCombinedName()) ) { getMicrocodeFromCache(); } else { compileAndLink(); } buildGLUniformReferences(); extractAttributes(); } if (mLinked) { GLenum glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLLinkProgram::Activate", "Error prior to using GLSL Program Object : ", mGLHandle, false, false); } glUseProgramObjectARB( mGLHandle ); glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLLinkProgram::Activate", "Error using GLSL Program Object : ", mGLHandle, false, false); } } } //----------------------------------------------------------------------- void GLSLLinkProgram::getMicrocodeFromCache(void) { GpuProgramManager::Microcode cacheMicrocode = GpuProgramManager::getSingleton().getMicrocodeFromCache(getCombinedName()); GLenum binaryFormat = *((GLenum *)(cacheMicrocode->getPtr())); uint8 * programBuffer = cacheMicrocode->getPtr() + sizeof(GLenum); size_t sizeOfBuffer = cacheMicrocode->size() - sizeof(GLenum); glProgramBinary(mGLHandle, binaryFormat, programBuffer, static_cast<GLsizei>(sizeOfBuffer) ); glGetProgramiv(mGLHandle, GL_LINK_STATUS, &mLinked); if (!mLinked) { // // Something must have changed since the program binaries // were cached away. Fallback to source shader loading path, // and then retrieve and cache new program binaries once again. // compileAndLink(); } } //----------------------------------------------------------------------- void GLSLLinkProgram::extractAttributes(void) { size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute); for (size_t i = 0; i < numAttribs; ++i) { const CustomAttribute& a = msCustomAttributes[i]; GLint attrib = glGetAttribLocationARB(mGLHandle, a.name.c_str()); if (attrib != -1) { mValidAttributes.insert(a.attrib); } } } //----------------------------------------------------------------------- GLuint GLSLLinkProgram::getAttributeIndex(VertexElementSemantic semantic, uint index) { return GLGpuProgram::getFixedAttributeIndex(semantic, index); } //----------------------------------------------------------------------- bool GLSLLinkProgram::isAttributeValid(VertexElementSemantic semantic, uint index) { return mValidAttributes.find(getAttributeIndex(semantic, index)) != mValidAttributes.end(); } //----------------------------------------------------------------------- void GLSLLinkProgram::buildGLUniformReferences(void) { if (!mUniformRefsBuilt) { const GpuConstantDefinitionMap* vertParams = 0; const GpuConstantDefinitionMap* fragParams = 0; const GpuConstantDefinitionMap* geomParams = 0; if (mVertexProgram) { vertParams = &(mVertexProgram->getGLSLProgram()->getConstantDefinitions().map); } if (mGeometryProgram) { geomParams = &(mGeometryProgram->getGLSLProgram()->getConstantDefinitions().map); } if (mFragmentProgram) { fragParams = &(mFragmentProgram->getGLSLProgram()->getConstantDefinitions().map); } GLSLLinkProgramManager::getSingleton().extractUniforms( mGLHandle, vertParams, geomParams, fragParams, mGLUniformReferences); mUniformRefsBuilt = true; } } //----------------------------------------------------------------------- void GLSLLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params, uint16 mask, GpuProgramType fromProgType) { // iterate through uniform reference list and update uniform values GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin(); GLUniformReferenceIterator endUniform = mGLUniformReferences.end(); // determine if we need to transpose matrices when binding int transpose = GL_TRUE; if ((fromProgType == GPT_FRAGMENT_PROGRAM && mVertexProgram && (!mVertexProgram->getGLSLProgram()->getColumnMajorMatrices())) || (fromProgType == GPT_VERTEX_PROGRAM && mFragmentProgram && (!mFragmentProgram->getGLSLProgram()->getColumnMajorMatrices())) || (fromProgType == GPT_GEOMETRY_PROGRAM && mGeometryProgram && (!mGeometryProgram->getGLSLProgram()->getColumnMajorMatrices()))) { transpose = GL_FALSE; } for (;currentUniform != endUniform; ++currentUniform) { // Only pull values from buffer it's supposed to be in (vertex or fragment) // This method will be called twice, once for vertex program params, // and once for fragment program params. if (fromProgType == currentUniform->mSourceProgType) { const GpuConstantDefinition* def = currentUniform->mConstantDef; if (def->variability & mask) { GLsizei glArraySize = (GLsizei)def->arraySize; bool shouldUpdate = true; switch (def->constType) { case GCT_INT1: case GCT_INT2: case GCT_INT3: case GCT_INT4: case GCT_SAMPLER1D: case GCT_SAMPLER1DSHADOW: case GCT_SAMPLER2D: case GCT_SAMPLER2DSHADOW: case GCT_SAMPLER2DARRAY: case GCT_SAMPLER3D: case GCT_SAMPLERCUBE: shouldUpdate = mUniformCache->updateUniform(currentUniform->mLocation, params->getIntPointer(def->physicalIndex), static_cast<GLsizei>(def->elementSize * def->arraySize * sizeof(int))); break; default: shouldUpdate = mUniformCache->updateUniform(currentUniform->mLocation, params->getFloatPointer(def->physicalIndex), static_cast<GLsizei>(def->elementSize * def->arraySize * sizeof(float))); break; } if(!shouldUpdate) continue; // get the index in the parameter real list switch (def->constType) { case GCT_FLOAT1: glUniform1fvARB(currentUniform->mLocation, glArraySize, params->getFloatPointer(def->physicalIndex)); break; case GCT_FLOAT2: glUniform2fvARB(currentUniform->mLocation, glArraySize, params->getFloatPointer(def->physicalIndex)); break; case GCT_FLOAT3: glUniform3fvARB(currentUniform->mLocation, glArraySize, params->getFloatPointer(def->physicalIndex)); break; case GCT_FLOAT4: glUniform4fvARB(currentUniform->mLocation, glArraySize, params->getFloatPointer(def->physicalIndex)); break; case GCT_MATRIX_2X2: glUniformMatrix2fvARB(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); break; case GCT_MATRIX_2X3: if (GLEW_VERSION_2_1) { glUniformMatrix2x3fv(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); } break; case GCT_MATRIX_2X4: if (GLEW_VERSION_2_1) { glUniformMatrix2x4fv(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); } break; case GCT_MATRIX_3X2: if (GLEW_VERSION_2_1) { glUniformMatrix3x2fv(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); } break; case GCT_MATRIX_3X3: glUniformMatrix3fvARB(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); break; case GCT_MATRIX_3X4: if (GLEW_VERSION_2_1) { glUniformMatrix3x4fv(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); } break; case GCT_MATRIX_4X2: if (GLEW_VERSION_2_1) { glUniformMatrix4x2fv(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); } break; case GCT_MATRIX_4X3: if (GLEW_VERSION_2_1) { glUniformMatrix4x3fv(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); } break; case GCT_MATRIX_4X4: glUniformMatrix4fvARB(currentUniform->mLocation, glArraySize, transpose, params->getFloatPointer(def->physicalIndex)); break; case GCT_INT1: glUniform1ivARB(currentUniform->mLocation, glArraySize, (GLint*)params->getIntPointer(def->physicalIndex)); break; case GCT_INT2: glUniform2ivARB(currentUniform->mLocation, glArraySize, (GLint*)params->getIntPointer(def->physicalIndex)); break; case GCT_INT3: glUniform3ivARB(currentUniform->mLocation, glArraySize, (GLint*)params->getIntPointer(def->physicalIndex)); break; case GCT_INT4: glUniform4ivARB(currentUniform->mLocation, glArraySize, (GLint*)params->getIntPointer(def->physicalIndex)); break; case GCT_SAMPLER1D: case GCT_SAMPLER1DSHADOW: case GCT_SAMPLER2D: case GCT_SAMPLER2DSHADOW: case GCT_SAMPLER2DARRAY: case GCT_SAMPLER3D: case GCT_SAMPLERCUBE: // samplers handled like 1-element ints glUniform1ivARB(currentUniform->mLocation, 1, (GLint*)params->getIntPointer(def->physicalIndex)); break; case GCT_UNKNOWN: default: break; } // end switch #if OGRE_DEBUG_MODE GLenum glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLLinkProgram::updateUniforms", "Error updating uniform", 0 ); } #endif } // variability & mask } // fromProgType == currentUniform->mSourceProgType } // end for } //----------------------------------------------------------------------- void GLSLLinkProgram::updatePassIterationUniforms(GpuProgramParametersSharedPtr params) { if (params->hasPassIterationNumber()) { size_t index = params->getPassIterationNumberIndex(); GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin(); GLUniformReferenceIterator endUniform = mGLUniformReferences.end(); // need to find the uniform that matches the multi pass entry for (;currentUniform != endUniform; ++currentUniform) { // get the index in the parameter real list if (index == currentUniform->mConstantDef->physicalIndex) { if(!mUniformCache->updateUniform(currentUniform->mLocation, params->getFloatPointer(index), static_cast<GLsizei>(currentUniform->mConstantDef->elementSize * currentUniform->mConstantDef->arraySize * sizeof(float)))) return; } } } } //----------------------------------------------------------------------- Ogre::String GLSLLinkProgram::getCombinedName() { String name; if (mVertexProgram) { name += "Vertex Program:" ; name += mVertexProgram->getName(); } if (mFragmentProgram) { name += " Fragment Program:" ; name += mFragmentProgram->getName(); } if (mGeometryProgram) { name += " Geometry Program:" ; name += mGeometryProgram->getName(); } return name; } //----------------------------------------------------------------------- void GLSLLinkProgram::compileAndLink() { if (mVertexProgram) { // compile and attach Vertex Program if (!mVertexProgram->getGLSLProgram()->compile(true)) { // todo error return; } mVertexProgram->getGLSLProgram()->attachToProgramObject(mGLHandle); setSkeletalAnimationIncluded(mVertexProgram->isSkeletalAnimationIncluded()); // Some drivers (e.g. OS X on nvidia) incorrectly determine the attribute binding automatically // and end up aliasing existing built-ins. So avoid! // Bind all used attribs - not all possible ones otherwise we'll get // lots of warnings in the log, and also may end up aliasing names used // as varyings by accident // Because we can't ask GL whether an attribute is used in the shader // until it is linked (chicken and egg!) we have to parse the source size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute); const String& vpSource = mVertexProgram->getGLSLProgram()->getSource(); for (size_t i = 0; i < numAttribs; ++i) { const CustomAttribute& a = msCustomAttributes[i]; // we're looking for either: // attribute vec<n> <semantic_name> // in vec<n> <semantic_name> // The latter is recommended in GLSL 1.3 onwards // be slightly flexible about formatting String::size_type pos = vpSource.find(a.name); bool foundAttr = false; while (pos != String::npos && !foundAttr) { String::size_type startpos = vpSource.find("attribute", pos < 20 ? 0 : pos-20); if (startpos == String::npos) startpos = vpSource.find("in", pos-20); if (startpos != String::npos && startpos < pos) { // final check String expr = vpSource.substr(startpos, pos + a.name.length() - startpos); StringVector vec = StringUtil::split(expr); if ((vec[0] == "in" || vec[0] == "attribute") && vec[2] == a.name) { glBindAttribLocationARB(mGLHandle, a.attrib, a.name.c_str()); foundAttr = true; } } // Find the position of the next occurrence if needed pos = vpSource.find(a.name, pos + a.name.length()); } } } if (mGeometryProgram) { // compile and attach Geometry Program if (!mGeometryProgram->getGLSLProgram()->compile(true)) { // todo error return; } mGeometryProgram->getGLSLProgram()->attachToProgramObject(mGLHandle); //Don't set adjacency flag. We handle it internally and expose "false" RenderOperation::OperationType inputOperationType = mGeometryProgram->getGLSLProgram()->getInputOperationType(); glProgramParameteriEXT(mGLHandle, GL_GEOMETRY_INPUT_TYPE_EXT, getGLGeometryInputPrimitiveType(inputOperationType, mGeometryProgram->isAdjacencyInfoRequired())); RenderOperation::OperationType outputOperationType = mGeometryProgram->getGLSLProgram()->getOutputOperationType(); glProgramParameteriEXT(mGLHandle, GL_GEOMETRY_OUTPUT_TYPE_EXT, getGLGeometryOutputPrimitiveType(outputOperationType)); glProgramParameteriEXT(mGLHandle, GL_GEOMETRY_VERTICES_OUT_EXT, mGeometryProgram->getGLSLProgram()->getMaxOutputVertices()); } if (mFragmentProgram) { // compile and attach Fragment Program if (!mFragmentProgram->getGLSLProgram()->compile(true)) { // todo error return; } mFragmentProgram->getGLSLProgram()->attachToProgramObject(mGLHandle); } // now the link glLinkProgramARB( mGLHandle ); glGetObjectParameterivARB( mGLHandle, GL_OBJECT_LINK_STATUS_ARB, &mLinked ); mTriedToLinkAndFailed = !mLinked; // force logging and raise exception if not linked GLenum glErr = glGetError(); if(glErr != GL_NO_ERROR) { reportGLSLError( glErr, "GLSLLinkProgram::compileAndLink", "Error linking GLSL Program Object : ", mGLHandle, !mLinked, !mLinked ); } if(mLinked) { logObjectInfo( getCombinedName() + String(" GLSL link result : "), mGLHandle ); } if (mLinked) { if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() ) { // add to the microcode to the cache String name; name = getCombinedName(); // get buffer size GLint binaryLength = 0; glGetProgramiv(mGLHandle, GL_PROGRAM_BINARY_LENGTH, &binaryLength); // turns out we need this param when loading // it will be the first bytes of the array in the microcode GLenum binaryFormat = 0; // create microcode GpuProgramManager::Microcode newMicrocode = GpuProgramManager::getSingleton().createMicrocode(binaryLength + sizeof(GLenum)); // get binary uint8 * programBuffer = newMicrocode->getPtr() + sizeof(GLenum); glGetProgramBinary(mGLHandle, binaryLength, NULL, &binaryFormat, programBuffer); // save binary format memcpy(newMicrocode->getPtr(), &binaryFormat, sizeof(GLenum)); // add to the microcode to the cache GpuProgramManager::getSingleton().addMicrocodeToCache(name, newMicrocode); } } } //----------------------------------------------------------------------- } // namespace GLSL } // namespace Ogre
[ "peter.kovacs@sztaki.mta.hu" ]
peter.kovacs@sztaki.mta.hu
0159e14bfa1b2b0613051d43b14d582314ea2272
85ffcf5d7297d5e6c98b5507f90539b24cadd9a6
/maintenanceModelFile/maintenanceModelFile/renderingwidget.cpp
e13eb0f6b2cf9aed5e0a1b58a4996f6e20e8fdf2
[]
no_license
HUkiah/dailyCoding
f9f18b7c8b6dd9f8ab8bddf99d7e939ab570ba5d
c5ce9d750f823f3958894bd4d310b682e982bd09
refs/heads/master
2021-01-02T09:17:11.407195
2017-10-27T10:18:43
2017-10-27T10:18:43
99,182,067
0
0
null
null
null
null
GB18030
C++
false
false
15,019
cpp
#include "renderingwidget.h" #include <gl\GLU.h> #include "globalFunctions.h" #include "QDebug" #include <QKeyEvent> #include <QTime> #include "QFileDialog" #include "QTextCodec" RenderingWidget::RenderingWidget(QWidget *parent) : QOpenGLWidget(parent), has_lighting_(false), eye_distance_(5.0), is_draw_point_(false), is_draw_edge_(false), is_draw_face_(true) { ptr_arcball_ = new CArcBall(width(), height()); ptr_arcball_module_ = new CArcBall(width(), height()); ptr_mesh_ = new Mesh3D(); is_move_module_ = (false); is_load_texture_ = false; is_draw_axes_ = false; is_draw_texture_ = (false); is_draw_grid_ = (false); eye_goal_[0] = eye_goal_[1] = eye_goal_[2] = 0.0; eye_direction_[0] = eye_direction_[1] = 0.0; eye_direction_[2] = 1.0; } RenderingWidget::~RenderingWidget() { SafeDelete(ptr_arcball_); SafeDelete(ptr_arcball_module_); SafeDelete(ptr_mesh_); } void RenderingWidget::initializeGL() { glClearColor(.1, .1, .1, 0.0); glShadeModel(GL_SMOOTH);//平滑渐变 对应的GL_FLAT是单色方式(两点间取一点的颜色着色) glEnable(GL_DOUBLEBUFFER);//启用双缓冲 //glEnable(GL_CULL_FACE);//开启剔除操作效果 避免不必要的渲染 glEnable(GL_COLOR_MATERIAL);//用颜色材质,使我们可以用颜色来贴物体 glColorMaterial(GL_FRONT, GL_DIFFUSE);//最开始颜色材质对应的是ambient(环境)的。所以要给为diffuse(传播) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);//则表示源颜色乘以自身的alpha 值,目标颜色乘以1.0减去源颜色的alpha值(不透明度) glEnable(GL_BLEND);//开启混合功能 glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);//采样质量按照像素(GL_NICEST)进行。(GL_FASTEST)顶点、反走样 glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); glEnable(GL_DEPTH_TEST);//只绘制最前面的一层 glClearDepth(1);//功能为指定深度缓冲区的清除值(0-1) SetLight(); } void RenderingWidget::resizeGL(int w, int h) { h = (h == 0) ? 1 : h; ptr_arcball_->reSetBound(w, h); ptr_arcball_module_->reSetBound(w, h); glViewport(0, 0, w, h);//视口位置、大小 glMatrixMode(GL_PROJECTION);//投影矩阵Model( 将要对投影矩阵操作) glLoadIdentity();//重置当前指定的矩阵为单位矩阵 gluPerspective(45.0, GLdouble(w) / GLdouble(h), 0.1, 1000);//指定了观察的视景体 glMatrixMode(GL_MODELVIEW);//Object space to Eyes space(将要设置模型空间位置) glLoadIdentity();//(设置其为单位矩阵) } void RenderingWidget::paintGL() { glShadeModel(GL_SMOOTH);//设置着色模式 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);//清除屏幕显示内容 深度和颜色都要清一下 if (has_lighting_) { SetLight(); } else { glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); } glMatrixMode(GL_MODELVIEW);//(将要设置模型空间位置) glLoadIdentity();//(设置其为单位矩阵) register vec eyepos = eye_distance_*eye_direction_; gluLookAt(eyepos[0], eyepos[1], eyepos[2],//eye position eye_goal_[0], eye_goal_[1], eye_goal_[2],//eye angel 0.0, 1.0, 0.0);// Y coordinate glPushMatrix(); glMultMatrixf(ptr_arcball_->GetBallMatrix()); //用矩阵M 调用glMultMatrix 对顶点v的变换就从原来的C × v变成C × M × v Render(); glPopMatrix(); } void RenderingWidget::SetLight() { /** 定义光源的属性值 */ //GLfloat LightAmbient[] = { 0.4f, 0.4f, 0.4f, 1.0f }; /**< 环境光参数 */ GLfloat LightDiffuse[] = { 0.8f, 0.9f, 0.9f, 1.0f }; /**< 漫射光参数 */ //GLfloat LightSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f }; /**< 镜面光参数 */ GLfloat LightPosition0[] = { 0.0f, -1.414f, 1.0f, 0.0f }; /**< 光源位置 */ GLfloat LightPosition1[] = { 1.0f, 1.414f, 0.0f, 0.0f }; /**< 光源位置 */ GLfloat lmodel_ambient[] = { 0.5f, 0.5f, 0.5f, 1.0f }; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);//选择光照模型:其包括四项内容 ////全局环境光强度 ////观察点靠近场景还是位于无穷远处 ////对物体的正面和背面是否采用相同的光照计算 ////以及是否将镜面反射颜色同环境颜色和散射颜色分开,并在纹理操作后应用它 glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);//把无限远的观察点改为局部观察点 /** 设置光源的属性值 */ glLightfv(GL_LIGHT0, GL_POSITION, LightPosition0); glLightfv(GL_LIGHT1, GL_POSITION, LightPosition1); //glLightfv(GL_LIGHT0, GL_AMBIENT, LightAmbient); /**< 设置环境光 */ glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse); /**< 设置漫射光 */ glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); //glLightfv(GL_LIGHT0, GL_SPECULAR, LightSpecular); /**< 设置漫射光 */ /** 启用光源 */ glEnable(GL_LIGHTING);//启用光照 glEnable(GL_LIGHT0);//启用指定光源 glEnable(GL_LIGHT1);//启用指定光源 } void RenderingWidget::Render() { //DrawAxes(is_draw_axes_); DrawGrid(is_draw_grid_); //DrawPoints(is_draw_point_); DrawEdge(is_draw_edge_); DrawFace(is_draw_face_); //DrawTexture(is_draw_texture_); } //绘轴 void RenderingWidget::DrawAxes(bool bv) { if (!bv) return; //x axis glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINES); glVertex3f(0, 0, 0); glVertex3f(0.7, 0.0, 0.0); glEnd(); glPushMatrix(); glTranslatef(0.7, 0, 0); glRotatef(90, 0.0, 1.0, 0.0); glPopMatrix(); //y axis glColor3f(0.0, 1.0, 0.0); glBegin(GL_LINES); glVertex3f(0, 0, 0); glVertex3f(0.0, 0.7, 0.0); glEnd(); glPushMatrix(); glTranslatef(0.0, 0.7, 0); glRotatef(90, -1.0, 0.0, 0.0); glPopMatrix(); //z axis glColor3f(0.0, 0.0, 1.0); glBegin(GL_LINES); glVertex3f(0, 0, 0); glVertex3f(0.0, 0.0, 0.7); glEnd(); glPushMatrix(); glTranslatef(0.0, 0, 0.7); glPopMatrix(); glColor3f(1.0, 1.0, 1.0); } void RenderingWidget::DrawPoints(bool bv) { if (!bv || ptr_mesh_ == NULL) return; if (ptr_mesh_->num_of_vertex_list() == 0) { return; } const std::vector<HE_vert*>& verts = *(ptr_mesh_->get_vertex_list()); glBegin(GL_POINTS); for (size_t i = 0; i != ptr_mesh_->num_of_vertex_list(); ++i) { glNormal3fv(verts[i]->normal().data()); glVertex3fv((verts[i]->position()*scaleV).data()); } glEnd(); } void RenderingWidget::DrawEdge(bool bv) { if (!bv || ptr_mesh_ == NULL) return; if (ptr_mesh_->num_of_face_list() == 0) { return; } const std::vector<HE_edge *>& edges = *(ptr_mesh_->get_edges_list()); const std::vector<HE_edge *>& bedges = *(ptr_mesh_->get_bedges_list()); for (size_t i = 0; i != edges.size(); ++i) { glBegin(GL_LINES); glColor3f(0.0, 0.0, 0.0); glNormal3fv(edges[i]->start_->normal().data()); glVertex3fv((edges[i]->start_->position()*scaleV).data()); glNormal3fv(edges[i]->pvert_->normal().data()); glVertex3fv((edges[i]->pvert_->position()*scaleV).data()); glEnd(); } for (size_t i = 0; i != bedges.size(); ++i) { glBegin(GL_LINES); glColor3f(1.0, 0.0, 0.0); glNormal3fv(bedges[i]->start_->normal().data()); glVertex3fv((bedges[i]->start_->position()*scaleV).data()); glNormal3fv(bedges[i]->pvert_->normal().data()); glVertex3fv((bedges[i]->pvert_->position()*scaleV).data()); glEnd(); } auto bl = ptr_mesh_->GetBLoop(); for (size_t i = 0; i != bl.size(); i++) { glBegin(GL_LINE_LOOP); glColor3f(1.0, 0.0, 0.0); for (int j = 0; j < bl[i].size(); j++) { glNormal3fv(bl[i][j]->start_->normal().data()); glVertex3fv((bl[i][j]->start_->position()*scaleV).data()); } glEnd(); } } void RenderingWidget::DrawFace(bool bv) { if (!bv || ptr_mesh_ == NULL) return; if (ptr_mesh_->num_of_face_list() == 0) { return; } const std::vector<HE_face *>& faces = *(ptr_mesh_->get_faces_list()); glBegin(GL_TRIANGLES); glColor4f(.8, .5, .5, 0.9); for (size_t i = 0; i < faces.size(); ++i) { if (ptr_mesh_->Tria[i].selected==1) { glColor3f(0.8,0, 0); HE_edge *pedge(faces.at(i)->pedge_); do { if (pedge == NULL) { break; } if (pedge == NULL || pedge->pface_->id() != faces.at(i)->id()) { faces.at(i)->pedge_ = NULL; qDebug() << faces.at(i)->id() << "facet display wrong"; break; } glNormal3fv(pedge->pvert_->normal().data()); glVertex3fv((pedge->pvert_->position()*scaleV).data()); pedge = pedge->pnext_; } while (pedge != faces.at(i)->pedge_); } else { glColor3f(0.8, 0.8, 0.8); HE_edge *pedge(faces.at(i)->pedge_); do { if (pedge == NULL) { break; } if (pedge == NULL || pedge->pface_->id() != faces.at(i)->id()) { faces.at(i)->pedge_ = NULL; qDebug() << faces.at(i)->id() << "facet display wrong"; break; } glNormal3fv(pedge->pvert_->normal().data()); glVertex3fv((pedge->pvert_->position()*scaleV).data()); pedge = pedge->pnext_; } while (pedge != faces.at(i)->pedge_); } } glEnd(); //return; } void RenderingWidget::DrawTexture(bool bv) { if (!bv) return; if (ptr_mesh_->num_of_face_list() == 0 || !is_load_texture_) return; //默认使用球面纹理映射,效果不好 ptr_mesh_->SphereTex(); const std::vector<HE_face *>& faces = *(ptr_mesh_->get_faces_list()); glBindTexture(GL_TEXTURE_2D, texture_[0]); glBegin(GL_TRIANGLES); for (size_t i = 0; i != faces.size(); ++i) { HE_edge *pedge(faces.at(i)->pedge_); do { /* 请在此处绘制纹理,添加纹理坐标即可 */ glTexCoord2fv(pedge->pvert_->texCoord_.data()); glNormal3fv(pedge->pvert_->normal().data()); glVertex3fv((pedge->pvert_->position()*scaleV).data()); pedge = pedge->pnext_; } while (pedge != faces.at(i)->pedge_); } glEnd(); } void RenderingWidget::DrawGrid(bool bv) { if (!bv) return; //x axis //glDisable(GL_LIGHTING); glColor3f(0.9, 0.9, 0.9); glBegin(GL_LINES); Vec3f box(ptr_mesh_->getBoundingBox().at(0)*scaleV - ptr_mesh_->getBoundingBox().at(1)*scaleV); for (int i = 1; i < 16; i++) { glVertex2f(-box[0], -box[1] + i*box[1] / 8); glVertex2f(box[0], -box[1] + i*box[1] / 8); glVertex2f(-box[0] + i*box[0] / 8, -box[1]); glVertex2f(-box[0] + i*box[0] / 8, box[1]); } glEnd(); //glEnable(GL_LIGHTING); } void RenderingWidget::mousePressEvent(QMouseEvent *e) { switch (e->button()) { case Qt::LeftButton: { makeCurrent(); ptr_arcball_->MouseDown(e->pos()); update(); } break; case Qt::MidButton: current_position_ = e->pos(); break; case Qt::RightButton: { break; } default: break; } } void RenderingWidget::mouseMoveEvent(QMouseEvent *e) { switch (e->buttons()) { setCursor(Qt::ClosedHandCursor);//改变鼠标样式(close) case Qt::LeftButton: ptr_arcball_->MouseMove(e->pos()); break; case Qt::MidButton: if (ptr_mesh_ != NULL) { eye_goal_[0] -= ptr_mesh_->getBoundingBox().at(0).at(2)*scaleV*GLfloat(e->x() - current_position_.x()) / GLfloat(width()); eye_goal_[1] += ptr_mesh_->getBoundingBox().at(0).at(2)*scaleV*GLfloat(e->y() - current_position_.y()) / GLfloat(height()); } current_position_ = e->pos(); break; default: break; } update(); } void RenderingWidget::mouseReleaseEvent(QMouseEvent *e) { switch (e->button()) { case Qt::LeftButton: if (is_move_module_) { ptr_arcball_module_->MouseUp(e->pos()); } else { ptr_arcball_->MouseUp(e->pos()); } setCursor(Qt::ArrowCursor); ptr_arcball_->MouseUp(e->pos()); setCursor(Qt::ArrowCursor); break; case Qt::RightButton: break; default: break; } } void RenderingWidget::mouseDoubleClickEvent(QMouseEvent *e) { switch (e->button()) { default: break; } update(); } void RenderingWidget::wheelEvent(QWheelEvent *e) { if (ptr_mesh_ != NULL) { eye_distance_ -= e->delta()*ptr_mesh_->getBoundingBox().at(0).at(2)*scaleV / 1000; } eye_distance_ = eye_distance_ < 0 ? 0 : eye_distance_; update(); } void RenderingWidget::ReadMesh() { QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间 QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式 ptr_arcball_->reSetBound(width(), height()); ptr_arcball_module_->reSetBound(width(), height()); ptr_mesh_->ClearData(); is_draw_grid_ = true; is_draw_face_ = true; is_draw_cutpieces_ = true; is_draw_hatch_ = true; has_lighting_ = true; QString filename = QFileDialog:: getOpenFileName(this, tr("Read Mesh"), "C:/Users/h/Desktop/", tr("Meshes (*.obj *.stl)")); if (filename.isEmpty()) { //emit(operatorInfo(QString("Read Mesh Failed!"))); return; } //中文路径支持 QTextCodec *code = QTextCodec::codecForName("gd18030"); QTextCodec::setCodecForLocale(code); //mycut->clearcut(); QByteArray byfilename = filename.toLocal8Bit(); QFileInfo fileinfo = QFileInfo(filename); //qDebug() << "read Mesh start time" << str; //qDebug() << byfilename.data(); qDebug() << "load model time at " << time; if (fileinfo.suffix() == "obj") { ptr_mesh_->LoadFromOBJFile(byfilename.data()); } else if (fileinfo.suffix() == "stl" || fileinfo.suffix() == "STL") { ptr_mesh_->LoadFromSTLFile(byfilename.data()); } // m_pMesh->LoadFromOBJFile(filename.toLatin1().data()); //emit(operatorInfo(QString("Read Mesh from") + filename + QString(" Done"))); //emit(meshInfo(ptr_mesh_->num_of_vertex_list(), ptr_mesh_->num_of_edge_list(), ptr_mesh_->num_of_face_list())); float max_ = ptr_mesh_->getBoundingBox().at(0).at(0); max_ = max_ > ptr_mesh_->getBoundingBox().at(0).at(1) ? max_ : ptr_mesh_->getBoundingBox().at(0).at(1); max_ = max_ > ptr_mesh_->getBoundingBox().at(0).at(2) ? max_ : ptr_mesh_->getBoundingBox().at(0).at(2); //updateGL(); update(); time = QDateTime::currentDateTime();//获取系统现在的时间 str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式 //qDebug() << "read mesh end time :" << str; // qDebug() << "孔洞个数为:" << ptr_mesh_->GetBLoop().size(); // qDebug() << "法向面片错误" <<sss; //qDebug() << "法向错误面片个数:"<<sss; qDebug() << "load model end at" << time; qDebug() << ptr_mesh_->get_faces_list()->size(); qDebug() << ptr_mesh_->getBoundingBox().at(0)[0] * 2 << ptr_mesh_->getBoundingBox().at(0)[1] * 2 << ptr_mesh_->getBoundingBox().at(0)[2]; //ptr_arcball_->PlaceBall(scaleV); scaleT = scaleV; eye_distance_ = 2 * max_; } void RenderingWidget::WriteMesh() { if (ptr_mesh_->num_of_vertex_list() == 0) { emit(QString("The Mesh is Empty !")); return; } QString filename = QFileDialog:: getSaveFileName(this, tr("Write Mesh"), "..", tr("Meshes (*.txt)")); if (filename.isEmpty()) return; QByteArray byfilename = filename.toLocal8Bit(); ptr_mesh_->WriteToOBJFile(byfilename.data()); } void RenderingWidget::CheckLight() { has_lighting_ = !has_lighting_; update(); } void RenderingWidget::CheckDrawEdge() { is_draw_edge_ = !is_draw_edge_; update(); } void RenderingWidget::MntnMesh() { qDebug() << "Maintenance Model !"; }
[ "han_wenm@163.com" ]
han_wenm@163.com
696c20fac7c894ed78e7d388b2ced6d316a57fe8
d87e36e4bc70788eac1474607185ce79838d5358
/week-10/day-2/first_network_steps/Server_sr.hpp
1b7451aea0465e57e6ffda8d1d0ca667aa0786fc
[]
no_license
greenfox-zerda-sparta/korompaidani
0e5a3a580658a35c3245da3046bb86544a8b842f
ead60c4d18dd0feba9a0e49758dffdba8ffa3bda
refs/heads/master
2021-01-12T18:15:09.459661
2017-03-31T09:41:51
2017-03-31T09:41:51
71,350,705
0
0
null
null
null
null
UTF-8
C++
false
false
662
hpp
#pragma once #include <iostream> #include <SDL.h> #include <SDL_net.h> #include <conio.h> #include <string> #include <cstring> #include <WindowsX.h> class Server_sr { private: IPaddress ip; TCPsocket server; TCPsocket client; SDLNet_SocketSet set; bool set_stat; char client_chars[100]; const char* server_chars; std::string client_mess; std::string server_mess; public: Server_sr(); void server_init(); void server_accept(); void server_contact(); void server_send(std::string); void server_client_open(); std::string server_receive(); void server_client_close(); void server_close(); void server_run(); ~Server_sr(); };
[ "korompaidani@gmail.com" ]
korompaidani@gmail.com
09d85b256eb7d6c151e62c0c4d14d4d374dd0fb1
6ab01c6ec943a61e2aa64518cf4c7ec957e30425
/Codes_Library/C/LM35_example/LM35_example.ino/LM35_example.ino.ino
6e87b832735efb2be2dfc8160765e3036186f628
[]
no_license
fgdangiolo/Arduino
cdce3923007d396f046c0f559514297d11c78077
08e9fe15b7fdd6d8a7f970edd78dd3ee67a1babf
refs/heads/master
2021-04-06T16:40:22.811176
2020-07-07T02:04:15
2020-07-07T02:04:15
125,305,929
0
0
null
null
null
null
UTF-8
C++
false
false
621
ino
/* ***************************************************************** * LM35 Library * File: LM35.ino * VERSION: 1.0 * Author: Federico Gabriel D'Angiolo * Description: This file contains skecth for LM 35 and Arduino *******************************************************************/ #include "LM35.h" void setup() { Serial.begin(9600); } void loop() { //Obtain and print temperature in Celsius Serial.println("Temperature in Celsius "); Serial.println(cels()); delay(1000); //Obtain and print temperature in Celsius Serial.println("Temperature in Fahrenheit "); Serial.println(fahr()); delay(1000); }
[ "fgdangiolo@gmail.com" ]
fgdangiolo@gmail.com
635f3c305ec304f853e4d571f736d910fea00c92
6ddce707b62dfeac62d270ed0c63ebbfb45b8fc6
/CPP/PeripheralInterface/SensorBaro.hpp
e159ce5407dbf3316d53d6576d32dc6e2d53d4b0
[]
no_license
imagineimage/FlightController
f1f3e4b0f9aaca97f775b3c16301e0679cdf53e8
9c16fca0c9f1946563c237fa86e985813b307807
refs/heads/master
2022-12-01T09:24:45.521534
2020-08-08T08:42:56
2020-08-08T08:42:56
286,930,944
0
0
null
2020-08-12T06:06:31
2020-08-12T06:06:31
null
UTF-8
C++
false
false
527
hpp
#ifndef __SENSORBARO__H #define __SENSORBARO__H #include "MsgBus/MsgType.hpp" #include "MsgBus/MsgBus.hpp" #include "Usec.h" namespace FC{ class SensorBaro{ public: void setBaro(float pressure/*[hPa]*/, float temperature/*[degC]*/); private: struct Barometer barometer; }; void SensorBaro::setBaro(float pressure, float temperature){ this->barometer.timestamp = microsecond(); this->barometer.pressure = pressure; this->barometer.temperature = temperature; msgBus.setBarometer(this->barometer); } } #endif
[ "46369795+cjw8809@users.noreply.github.com" ]
46369795+cjw8809@users.noreply.github.com
670a43a4346e455cf041e0e24c1d60537cd5cf12
d983d0f13f4bbd4beba4081e89a7a072fc88561e
/SEControl/SEControlDlg.cpp
05067887871195f06d24a8c6bea507a1449758d3
[]
no_license
catlincao/CPcontrol
a40afd6d47e68d07b566100a1bbb5033d9b1c882
b5aa0d2d427bc9bf6d20228ee80735747818e179
refs/heads/master
2020-04-04T13:25:10.974130
2018-11-03T07:32:21
2018-11-03T07:32:21
155,961,099
0
0
null
null
null
null
GB18030
C++
false
false
12,548
cpp
// SEControlDlg.cpp : 实现文件 // #include "stdafx.h" #include <string> #include <vector> #include <fstream> #include "GEP.H" #include "SEControlDlg.h" using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CSEControlDlg 对话框 CSEControlDlg::CSEControlDlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_SECONTROL_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); //instance = this; /*使用redis必须添加上去*/ WSAData wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); } void CSEControlDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CSEControlDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(ID_OPEN, &CSEControlDlg::OnBnClickedOpen) ON_BN_CLICKED(IDC_CLOSE, &CSEControlDlg::OnBnClickedClose) ON_BN_CLICKED(ID_RESET, &CSEControlDlg::OnBnClickedReset) ON_BN_CLICKED(IDC_OPENL, &CSEControlDlg::OnBnClickedOpenl) ON_BN_CLICKED(IDC_CLOSEL, &CSEControlDlg::OnBnClickedClosel) ON_BN_CLICKED(IDC_RESETL, &CSEControlDlg::OnBnClickedResetl) ON_BN_CLICKED(IDC_LED, &CSEControlDlg::OnBnClickedLed) END_MESSAGE_MAP() // CSEControlDlg 消息处理程序 BOOL CSEControlDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 //ComListInit(); // TODO: 在此添加额外的初始化代码 /////////////////////////////////////////////////////////////////////////////////////////////////// /* 固高运动控制卡 */ //rtn = GT_Close(); //关闭运动控制卡 //error(rtn); //rtn = GT_Open(); //打开运动控制卡 //error(rtn); //rtn = GT_HardRst(); //初始化运动控制卡 //error(rtn); /////////////////////////////////////////////////////////////////////////////////////////////////// lpPara[0] = _T("openCamera1"); lpPara[1] = _T("openCamera2"); lpPara[2] = _T("openCamera3"); lpPara[3] = _T("openCamera4"); lpPara[4] = _T("openCamera5"); lpPara[5] = _T("openCamera6"); SetDlgItemInt(IDC_NAME, 0, 0); SetDlgItemInt(IDC_NAMEL, 0, 0); GetDlgItem(IDC_CLOSE)->EnableWindow(false); GetDlgItem(IDC_CLOSEL)->EnableWindow(false); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CSEControlDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CSEControlDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CSEControlDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CSEControlDlg::OnBnClickedOpen() { ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* CreateProcess 方法 */ ZeroMemory(&StartupInfo[0], sizeof(StartupInfo[0])); ZeroMemory(&StartupInfo[1], sizeof(StartupInfo[1])); ZeroMemory(&StartupInfo[2], sizeof(StartupInfo[2])); ZeroMemory(&StartupInfo[3], sizeof(StartupInfo[3])); ZeroMemory(&StartupInfo[4], sizeof(StartupInfo[4])); ZeroMemory(&StartupInfo[5], sizeof(StartupInfo[5])); StartupInfo[0].cb = sizeof(StartupInfo[0]); StartupInfo[1].cb = sizeof(StartupInfo[1]); StartupInfo[2].cb = sizeof(StartupInfo[2]); StartupInfo[3].cb = sizeof(StartupInfo[3]); StartupInfo[4].cb = sizeof(StartupInfo[4]); StartupInfo[5].cb = sizeof(StartupInfo[5]); CreateProcess(_T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara[0], NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[0], &ProcessInfo[0]); CreateProcess(_T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara[1], NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[1], &ProcessInfo[1]); CreateProcess(_T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara[2], NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[2], &ProcessInfo[2]); CreateProcess(_T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara[3], NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[3], &ProcessInfo[3]); CreateProcess(_T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara[4], NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[4], &ProcessInfo[4]); CreateProcess(_T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara[5], NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[5], &ProcessInfo[5]); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* ShellExecute 方法 */ /*lpPara = _T("openCamera1"); ShellExecute(NULL, _T("open"), _T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara, NULL, SW_SHOWNORMAL); lpPara = _T("openCamera2"); ShellExecute(NULL, _T("open"), _T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara, NULL, SW_SHOWNORMAL); lpPara = _T("openCamera3"); ShellExecute(NULL, _T("open"), _T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara, NULL, SW_SHOWNORMAL); lpPara = _T("openCamera4"); ShellExecute(NULL, _T("open"), _T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara, NULL, SW_SHOWNORMAL); lpPara = _T("openCamera5"); ShellExecute(NULL, _T("open"), _T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara, NULL, SW_SHOWNORMAL); lpPara = _T("openCamera6"); ShellExecute(NULL, _T("open"), _T("..\\..\\ImageSaver\\release\\ImageSaver.exe"), lpPara, NULL, SW_SHOWNORMAL);*/ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GetDlgItem(ID_OPEN)->EnableWindow(false); GetDlgItem(IDC_CLOSE)->EnableWindow(true); } void CSEControlDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 //每次时间到都使用PubSubManager类的处理函数来判断是否有消息发布 m_psM.OnTimer(); CDialogEx::OnTimer(nIDEvent); } void CSEControlDlg::OnBnClickedClose() { // TODO: 在此添加控件通知处理程序代码 ::TerminateProcess(ProcessInfo[0].hProcess, 0); ::TerminateProcess(ProcessInfo[1].hProcess, 0); ::TerminateProcess(ProcessInfo[2].hProcess, 0); ::TerminateProcess(ProcessInfo[3].hProcess, 0); ::TerminateProcess(ProcessInfo[4].hProcess, 0); ::TerminateProcess(ProcessInfo[5].hProcess, 0); GetDlgItem(ID_OPEN)->EnableWindow(true); GetDlgItem(IDC_CLOSE)->EnableWindow(false); } void CSEControlDlg::OnBnClickedReset() { // TODO: 在此添加控件通知处理程序代码 string files[6] = { _T("E:\\document\\subway_tunnel_program\\data\\image\\cam1.txt"), _T("E:\\document\\subway_tunnel_program\\data\\image\\cam2.txt"), _T("E:\\document\\subway_tunnel_program\\data\\image\\cam3.txt"), _T("E:\\document\\subway_tunnel_program\\data\\image\\cam4.txt"), _T("E:\\document\\subway_tunnel_program\\data\\image\\cam5.txt"), _T("E:\\document\\subway_tunnel_program\\data\\image\\cam6.txt") }; int temp; for (string file : files) { temp = GetDlgItemInt(IDC_NAME, NULL, 0);//读取第一个名字的序号 ofstream namefile(file, ios::trunc); /*由于重置的数字长度可能小于TXT文件中保留的数字长度,如果直接把文件光标移到最开始(下一句代码),则会导致命名错误。如: TXT文件中保存的数字是100,如果想重置为20,输入20后,光标移到最开始,TXT文件会被重写为200,显然不对,所以需要清空。而在 前面保存图像的代码中,TXT文件的数字是用“++”来实现累加的,所以后面重写的数字长度一定不比之前的短,所以没问题。 */ /*namefile.seekg(0, ios::beg);*/ namefile << temp; namefile.close(); } } void CSEControlDlg::OnBnClickedOpenl() { // TODO: 在此添加控件通知处理程序代码 ZeroMemory(&StartupInfo[6], sizeof(StartupInfo[6])); StartupInfo[6].cb = sizeof(StartupInfo[6]); CreateProcess(_T("E:\\document\\subway_tunnel_program\\LMSDEMO_Example\\bin\\Debug\\LMS_connectionExample.exe"), NULL, NULL, NULL, FALSE, 0, NULL, NULL, &StartupInfo[6], &ProcessInfo[6]); GetDlgItem(IDC_OPENL)->EnableWindow(false); GetDlgItem(IDC_CLOSEL)->EnableWindow(true); } void CSEControlDlg::OnBnClickedClosel() { // TODO: 在此添加控件通知处理程序代码 ::TerminateProcess(ProcessInfo[6].hProcess, 0); GetDlgItem(IDC_OPENL)->EnableWindow(true); GetDlgItem(IDC_CLOSEL)->EnableWindow(false); } void CSEControlDlg::OnBnClickedResetl() { // TODO: 在此添加控件通知处理程序代码 string file = _T("E:\\document\\subway_tunnel_program\\data\\LMS\\flag.txt"); int temp; temp = GetDlgItemInt(IDC_NAMEL, NULL, 0);//读取第一个名字的序号 ofstream namefile(file, ios::trunc); /*由于重置的数字长度可能小于TXT文件中保留的数字长度,如果直接把文件光标移到最开始(下一句代码),则会导致命名错误。如: TXT文件中保存的数字是100,如果想重置为20,输入20后,光标移到最开始,TXT文件会被重写为200,显然不对,所以需要清空。而在 前面保存图像的代码中,TXT文件的数字是用“++”来实现累加的,所以后面重写的数字长度一定不比之前的短,所以没问题。 */ /*namefile.seekg(0, ios::beg);*/ namefile << temp; namefile.close(); } void CSEControlDlg::OnBnClickedLed() { if (ledflag == 0) { GT_ExOpt(0x4);//比较端口(0x4和0x2)电压不一致,打开led ledflag = 1; } else if (ledflag == 1) { GT_ExOpt(0x4);//比较端口(0x4和0x2)电压一致,关闭led GT_ExOpt(0x2); ledflag = 0; } else { GT_ExOpt(0x4); ledflag = 1; } } void error(short rtn) { switch (rtn) { case -1: printf("\a\nCommunication Error !"); break; case 0: break; case 1: printf("\a\nCommand Error !"); break; case 2: printf("\a\nRadius or chord is 0 !"); break; case 3: printf("\a\nLength is 0 or overflow !"); break; case 4: printf("\a\nVelocity or acceleration is less then 0 !"); break; case 5: printf("\a\nChord is greater than diameter !"); break; case 7: printf("\a\nParameter error !"); break; default: printf("\a\nError Code = %d ", rtn); break; } }
[ "catlincao@yeah.net" ]
catlincao@yeah.net
c8fab05fdc88a7ac753723369bd3673045960bf9
cf23d693dcb969b0233c0cca6d6f6fb3d16be475
/CheckIfStringRotated/main.cpp
47c90370eda777f1bc1dbf3b55c5a86bf7fe778a
[]
no_license
Zenikolas/AlgorithmsTraining
82d0f449c1d50b908d9072c715140329c1c528ba
273ab3268aa48432f2fbb30dd781bb80585c69b0
refs/heads/master
2021-07-10T20:58:08.035716
2021-02-16T08:39:55
2021-02-16T08:39:55
229,748,305
0
0
null
null
null
null
UTF-8
C++
false
false
855
cpp
#include <string> #include <gtest/gtest.h> // check of candidate string is rotated from original one bool checkIfStringRotated(const std::string& original, const std::string& candidate) { // assume original = xy; then rotated string is yx. If we compound yxyx then in the // middle will be original string std::string yxyx = candidate + candidate; size_t pos = yxyx.find(original); if (pos == std::string::npos) { return false; } return yxyx.substr(pos, original.size()) == original; } TEST(CheckIfStringRotated, SmokeTest) { ASSERT_TRUE(checkIfStringRotated("bottleneck", "neckbottle")); } TEST(CheckIfStringRotated, SameTest) { ASSERT_TRUE(checkIfStringRotated("bottleneck", "bottleneck")); } TEST(CheckIfStringRotated, SameSymbolsTest) { ASSERT_TRUE(checkIfStringRotated("aaaaaaa", "aaaaaaa")); }
[ "zenikolas256@gmail.com" ]
zenikolas256@gmail.com
75f1266356c1042d9d4c5b64ab1b58ca952bec58
4cd0b9ce7c2e2a57623cc71b936c6dcda79bdd5c
/fpdfsdk/pwl/cpwl_timer.h
1e93333e6e79df1b2809456332694a6b888f3f9f
[ "BSD-3-Clause" ]
permissive
prepare/pdfium
32b8f9cecc2dd98cd578d2b4e8d882e5c4f0e1ed
92770e8072cd3a38597966116045147c78b5a359
refs/heads/master
2021-01-21T04:43:53.541194
2018-12-23T06:55:27
2018-12-23T06:55:27
27,119,109
7
3
null
2015-08-11T13:40:07
2014-11-25T09:47:59
C++
UTF-8
C++
false
false
947
h
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef FPDFSDK_PWL_CPWL_TIMER_H_ #define FPDFSDK_PWL_CPWL_TIMER_H_ #include "core/fxcrt/unowned_ptr.h" class CFX_SystemHandler; class CPWL_TimerHandler; class CPWL_Timer { public: CPWL_Timer(CPWL_TimerHandler* pAttached, CFX_SystemHandler* pSystemHandler); ~CPWL_Timer(); static void TimerProc(int32_t idEvent); int32_t SetPWLTimer(int32_t nElapse); void KillPWLTimer(); private: static constexpr int32_t kInvalidTimerID = 0; bool HasValidID() const { return m_nTimerID != kInvalidTimerID; } int32_t m_nTimerID = kInvalidTimerID; UnownedPtr<CPWL_TimerHandler> const m_pAttached; UnownedPtr<CFX_SystemHandler> const m_pSystemHandler; }; #endif // FPDFSDK_PWL_CPWL_TIMER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
383430650dfadd1a4458b17d773f74dcc67b2fb6
c301c81f7560125e130a9eb67f5231b3d08a9d67
/lc/lc/2021_target/companies/fb/youtube/lc_268_missing_number.cpp
5ae42a49e05565f91899a341f96bae912f395381
[]
no_license
vikashkumarjha/missionpeace
f55f593b52754c9681e6c32d46337e5e4b2d5f8b
7d5db52486c55b48fe761e0616d550439584f199
refs/heads/master
2021-07-11T07:34:08.789819
2021-07-06T04:25:18
2021-07-06T04:25:18
241,745,271
0
0
null
null
null
null
UTF-8
C++
false
false
760
cpp
#include "header.hpp" using namespace std; /* * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find * the one that is missing from the array. * * Example 1: * * Input: [3,0,1] * Output: 2 * Example 2: * * Input: [9,6,4,2,3,5,7,0,1] * Output: 8 * * * */ /* class Solution { public int missingNumber(int[] nums) { int missing = nums.length; for (int i = 0; i < nums.length; i++) { missing ^= i ^ nums[i]; } return missing; } } */ int missingNumber(vector<int>& nums) { set<int> s(nums.begin(), nums.end()); int N = nums.size() + 1; for ( int i = 0; i < N; i++) { if ( !s.count(i)) { return i; } } return -1; }
[ "codingprepviks@gmail.com" ]
codingprepviks@gmail.com
d6aeb65432a7cff60b1752f14fc843b3b763460a
7de65570bacb4769a4496d0325e5f846314f53ab
/Classes/GameScene.h
6948e9990164de78a7aadb5ece0e18f62b6ed960
[]
no_license
ShmilyMx/-----
fd31d0fb72da0d2d3d9dedad9183f121bd8be7b5
74c19f5589b8a7a884209a209d42494d33f9c876
refs/heads/master
2021-01-10T15:39:17.130911
2015-11-29T11:26:12
2015-11-29T11:26:12
47,060,740
0
0
null
null
null
null
GB18030
C++
false
false
602
h
#include "cocos2d.h" USING_NS_CC; class GameScene :public Layer { public: GameScene(); ~GameScene(); static Scene *createScene(); bool init(); CREATE_FUNC(GameScene); void updatedown(float); private: //创建13*10的矩阵 void createBox(); //保存创建的矩阵 LayerColor **m_box; //存放创建的东西 LayerColor **m_tetris; void createTetris(); //存放产生的tetris Vector<LayerColor *>m_vecboxs; //判断是否移到最下面了 bool isDown; bool isUpdate; //存放产生的是哪种tetris int TetrisNumber; //存放我所变换的数 int changeNumber; };
[ "502920301@qq.com" ]
502920301@qq.com
30c803cc430462d1b2d724e483e733260a1e7b14
a586af5c4255c02129052b226e05848247d75b66
/word_count_10.12.cpp
eab8ed7a46cef3f89b804b37d2b14115a0724083
[]
no_license
NewLionwang/c-plus-plus-primer4_ex
c821134365c4ba63878f57a90408d982d2dda08d
682d50a29b2ec43f7629515d1001bcd8bc82fe84
refs/heads/master
2021-06-01T06:50:10.617036
2016-07-19T16:45:13
2016-07-19T16:45:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
/************************************************************************* > File Name: word_count_10.12.cpp > Author: wangxiaoxian > Mail: 634897019@qq.com > Created Time: Wed 20 Jul 2016 12:28:09 AM CST ************************************************************************/ #include<iostream> #include<string> #include<map> using namespace std; int main() { map<string, int> word_count; string word; cout << "input you word for count:\n" << endl; while(cin >> word) { pair<map<string,int>::iterator, bool> ret = word_count.insert(make_pair(word, 1)); if(!ret.second) //插入操作没有做,说明该关键字早已经存在,只需要将其对应的值+1 ++ret.first->second; } map<string, int>::iterator map_it = word_count.begin(); while(map_it != word_count.end()) { cout << map_it->first << " cout: " << map_it->second << endl; ++map_it; } }
[ "wangxiaoxian@ebupt.com" ]
wangxiaoxian@ebupt.com
2e867a35bc0a38dc30c2f34810dc2fd4b9a384e5
c548e27e8cac875c27edb7e000b5458b1e5d4022
/743/A. Vladik and flights/Source.cpp
71b3922ed0d56362c7d390c552681a81aa79fabe
[]
no_license
adamhasselwander/cf
cf73206af807d9247dc8be6cd74a31c71dfb4e26
fe919b5cd7441678f04a348530f6b980652c0558
refs/heads/master
2018-09-30T20:49:18.876138
2018-07-08T18:35:20
2018-07-08T18:35:20
107,027,994
0
0
null
null
null
null
UTF-8
C++
false
false
745
cpp
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #define sd(n) scanf("%d",&n) == 0 #define sl(n) scanf("%I64d",&n) == 0 #define ss(n) scanf("%s",n) == 0 #define sc(n) scanf(" %c",&n) == 0 #define pd(x) printf("%d", x) #define ps(x) printf("%s", x) #define pl(x) printf("%I64d", x) #define rep(i, begin, end) for (decltype(begin) i = begin; i < end; i++) #define revrep(i, begin, end) for (decltype(begin) i = end - 1; i >= begin; i--) #define all(a) a.begin(), a.end() using namespace std; typedef long long ll; typedef vector<int> vi; typedef vector<long> vl; typedef pair<int, int> pii; char arr[100000]; int main() { int a, b, n; sd(n); sd(a); sd(b); a--; b--; char c; rep(i, 0, n) sc(arr[i]); pd(arr[a] != arr[b]); }
[ "adam.hasselwander@gmail.com" ]
adam.hasselwander@gmail.com
facd36379d580842518615381424ca4d3d1b1668
22cbd2f2c3e5420c3e4f54e4b32f314a9fc90e38
/src/Project_FFT/src/Unit_test_twiddleFactor.cpp
8f83265996ec6d41ab21f7fb1c89d4b2ac878bff
[]
no_license
jingbosu/FFT
6cc2caf7a413730bd1d5390e9f51809342fbb2aa
20b37b6cc154e1504903820ef314327ce9543f37
refs/heads/master
2021-01-10T09:11:59.902879
2016-01-29T16:40:48
2016-01-29T16:40:48
46,337,655
1
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
/* * Unit_test_twiddleFactor.cpp * * Created on: 24 nov. 2015 * Author: su */ #include "TwiddleFactor.h" #include <iostream> using namespace std; int main() { TwiddleFactor twiddleFactor; for(int i = 0; i<10; i++){ cout<<"TW["<<i<<"] = "<<twiddleFactor.vec_comp[i]<<endl; } return 0; }
[ "jingbosu2010@hotmail.com" ]
jingbosu2010@hotmail.com
51c1f5f0766df84cd1955b96f6f669d48a883ea9
19a843ca2a4af4ccf7488a0dface7d89f9ec4d46
/potd/potd-q25/Queue.h
87615e28046b74ffac5fe7540d3280e504c38f2b
[]
no_license
andyz2045/CS225-Data-Structures
eae021f2670828985abbdfdadbe04e0e79f7513f
8961e7d1363f32552add7020d98d8faf175b02a2
refs/heads/master
2022-11-28T23:40:44.187842
2020-08-05T13:50:37
2020-08-05T13:50:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
251
h
#pragma once #include <cstddef> #include<vector> class Queue { public: Queue(); int size() const; bool isEmpty() const; void enqueue(int value); int dequeue(); ~Queue(); std::vector<int> v; };
[ "57075708+yuw14@users.noreply.github.com" ]
57075708+yuw14@users.noreply.github.com
eca4cb3689285185a18ee714a66640429be8b636
e9854cb02e90dab7ec0a49c65f658babba819d56
/Curve Editor Framework/QT/src/corelib/concurrent/qtconcurrentexception.cpp
0440ad8ad76e2a3ef4cb94b715da739455ef5490
[]
no_license
katzeforest/Computer-Animation
2bbb1df374d65240ca2209b3a75a0b6a8b99ad58
01481111a622ae8812fb0b76550f5d66de206bab
refs/heads/master
2021-01-23T19:46:13.455834
2015-06-08T21:29:02
2015-06-08T21:29:02
37,092,780
1
1
null
null
null
null
UTF-8
C++
false
false
6,224
cpp
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtconcurrentexception.h" #ifndef QT_NO_QFUTURE #ifndef QT_NO_EXCEPTIONS QT_BEGIN_NAMESPACE /*! \class QtConcurrent::Exception \brief The Exception class provides a base class for exceptions that can transferred across threads. \since 4.4 Qt Concurrent supports throwing and catching exceptions across thread boundaries, provided that the exception inherit from QtConcurrent::Exception and implement two helper functions: \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 0 QtConcurrent::Exception subclasses must be thrown by value and caught by reference: \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 1 If you throw an exception that is not a subclass of QtConcurrent::Exception, the Qt Concurrent functions will throw a QtConcurrent::UnhandledException in the receiver thread. When using QFuture, transferred exceptions will be thrown when calling the following functions: \list \o QFuture::waitForFinished() \o QFuture::result() \o QFuture::resultAt() \o QFuture::results() \endlist */ /*! \fn QtConcurrent::Exception::raise() const In your QtConcurrent::Exception subclass, reimplement raise() like this: \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 2 */ /*! \fn QtConcurrent::Exception::clone() const In your QtConcurrent::Exception subclass, reimplement clone() like this: \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 3 */ /*! \class QtConcurrent::UnhandledException \brief The UnhandledException class represents an unhandled exception in a worker thread. \since 4.4 If a worker thread throws an exception that is not a subclass of QtConcurrent::Exception, the Qt Concurrent functions will throw a QtConcurrent::UnhandledException on the receiver thread side. Inheriting from this class is not supported. */ /*! \fn QtConcurrent::UnhandledException::raise() const \internal */ /*! \fn QtConcurrent::UnhandledException::clone() const \internal */ namespace QtConcurrent { void Exception::raise() const { Exception e = *this; throw e; } Exception *Exception::clone() const { return new Exception(*this); } void UnhandledException::raise() const { UnhandledException e = *this; throw e; } Exception *UnhandledException::clone() const { return new UnhandledException(*this); } #ifndef qdoc namespace internal { class Base { public: Base(Exception *exception) : exception(exception), refCount(1), hasThrown(false) { } ~Base() { delete exception; } Exception *exception; QAtomicInt refCount; bool hasThrown; }; ExceptionHolder::ExceptionHolder(Exception *exception) : base(new Base(exception)) {} ExceptionHolder::ExceptionHolder(const ExceptionHolder &other) : base(other.base) { base->refCount.ref(); } void ExceptionHolder::operator=(const ExceptionHolder &other) { if (base == other.base) return; if (base->refCount.deref() == false) delete base; base = other.base; base->refCount.ref(); } ExceptionHolder::~ExceptionHolder() { if (base->refCount.deref() == 0) delete base; } Exception *ExceptionHolder::exception() const { return base->exception; } void ExceptionStore::setException(const Exception &e) { if (hasException() == false) exceptionHolder = ExceptionHolder(e.clone()); } bool ExceptionStore::hasException() const { return (exceptionHolder.exception() != 0); } ExceptionHolder ExceptionStore::exception() { return exceptionHolder; } void ExceptionStore::throwPossibleException() { /* On win32-g++, with GCC 3.4.2 std::uncaught_exception() isn't reliable. */ if (hasException() #ifndef Q_CC_MINGW && std::uncaught_exception() == false #endif ) { exceptionHolder.base->hasThrown = true; exceptionHolder.exception()->raise(); } } bool ExceptionStore::hasThrown() const { return exceptionHolder.base->hasThrown; } } // namespace internal #endif //qdoc } // namespace QtConcurrent QT_END_NAMESPACE #endif // QT_NO_EXCEPTIONS #endif // QT_NO_CONCURRENT
[ "sonyang@seas.upenn.edu" ]
sonyang@seas.upenn.edu
7999490a97a52920f40bf7b0521c55da304db03a
66ad8092e76209cc9bda3ee031d78dbb32502513
/Source/WebKit2/WebProcess/WebPage/mac/PlatformCALayerRemote.h
5267682e4b28cfe78d86e089b6605dbcfda18741
[]
no_license
lshi2017/wpe
3f660591ca5ff53b58c9c87c8f60b7ff23dac355
f23416d8b4b52d61d3963800769cee1f71c8441b
refs/heads/master
2023-01-05T20:09:16.057534
2017-08-23T19:41:20
2017-08-23T19:41:20
99,706,298
2
1
null
2022-12-21T03:13:19
2017-08-08T15:11:38
C++
UTF-8
C++
false
false
9,085
h
/* * Copyright (C) 2013 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. */ #pragma once #include "RemoteLayerTreeTransaction.h" #include <WebCore/PlatformCALayer.h> #include <WebCore/PlatformLayer.h> namespace WebCore { class LayerPool; } namespace WebKit { class RemoteLayerTreeContext; class PlatformCALayerRemote : public WebCore::PlatformCALayer { public: static Ref<PlatformCALayerRemote> create(WebCore::PlatformCALayer::LayerType, WebCore::PlatformCALayerClient*, RemoteLayerTreeContext&); static Ref<PlatformCALayerRemote> create(PlatformLayer *, WebCore::PlatformCALayerClient*, RemoteLayerTreeContext&); static Ref<PlatformCALayerRemote> create(const PlatformCALayerRemote&, WebCore::PlatformCALayerClient*, RemoteLayerTreeContext&); virtual ~PlatformCALayerRemote(); PlatformLayer* platformLayer() const override { return nullptr; } void recursiveBuildTransaction(RemoteLayerTreeContext&, RemoteLayerTreeTransaction&); void setNeedsDisplayInRect(const WebCore::FloatRect& dirtyRect) override; void setNeedsDisplay() override; void copyContentsFromLayer(PlatformCALayer*) override; WebCore::PlatformCALayer* superlayer() const override; void removeFromSuperlayer() override; void setSublayers(const WebCore::PlatformCALayerList&) override; void removeAllSublayers() override; void appendSublayer(WebCore::PlatformCALayer&) override; void insertSublayer(WebCore::PlatformCALayer&, size_t index) override; void replaceSublayer(WebCore::PlatformCALayer& reference, WebCore::PlatformCALayer&) override; const WebCore::PlatformCALayerList* customSublayers() const override { return nullptr; } void adoptSublayers(WebCore::PlatformCALayer& source) override; void addAnimationForKey(const String& key, WebCore::PlatformCAAnimation&) override; void removeAnimationForKey(const String& key) override; RefPtr<WebCore::PlatformCAAnimation> animationForKey(const String& key) override; void animationStarted(const String& key, CFTimeInterval beginTime) override; void animationEnded(const String& key) override; void setMask(WebCore::PlatformCALayer*) override; bool isOpaque() const override; void setOpaque(bool) override; WebCore::FloatRect bounds() const override; void setBounds(const WebCore::FloatRect&) override; WebCore::FloatPoint3D position() const override; void setPosition(const WebCore::FloatPoint3D&) override; WebCore::FloatPoint3D anchorPoint() const override; void setAnchorPoint(const WebCore::FloatPoint3D&) override; WebCore::TransformationMatrix transform() const override; void setTransform(const WebCore::TransformationMatrix&) override; WebCore::TransformationMatrix sublayerTransform() const override; void setSublayerTransform(const WebCore::TransformationMatrix&) override; bool isHidden() const override; void setHidden(bool) override; bool contentsHidden() const override; void setContentsHidden(bool) override; bool userInteractionEnabled() const override; void setUserInteractionEnabled(bool) override; void setBackingStoreAttached(bool) override; bool backingStoreAttached() const override; bool backingContributesToMemoryEstimate() const override { return backingStoreAttached(); } bool geometryFlipped() const override; void setGeometryFlipped(bool) override; bool isDoubleSided() const override; void setDoubleSided(bool) override; bool masksToBounds() const override; void setMasksToBounds(bool) override; bool acceleratesDrawing() const override; void setAcceleratesDrawing(bool) override; bool wantsDeepColorBackingStore() const override; void setWantsDeepColorBackingStore(bool) override; bool supportsSubpixelAntialiasedText() const override; void setSupportsSubpixelAntialiasedText(bool) override; CFTypeRef contents() const override; void setContents(CFTypeRef) override; void setContentsRect(const WebCore::FloatRect&) override; void setMinificationFilter(WebCore::PlatformCALayer::FilterType) override; void setMagnificationFilter(WebCore::PlatformCALayer::FilterType) override; WebCore::Color backgroundColor() const override; void setBackgroundColor(const WebCore::Color&) override; void setBorderWidth(float) override; void setBorderColor(const WebCore::Color&) override; float opacity() const override; void setOpacity(float) override; void setFilters(const WebCore::FilterOperations&) override; static bool filtersCanBeComposited(const WebCore::FilterOperations&); void copyFiltersFrom(const WebCore::PlatformCALayer&) override; #if ENABLE(CSS_COMPOSITING) void setBlendMode(WebCore::BlendMode) override; #endif void setName(const String&) override; void setSpeed(float) override; void setTimeOffset(CFTimeInterval) override; float contentsScale() const override; void setContentsScale(float) override; float cornerRadius() const override; void setCornerRadius(float) override; void setEdgeAntialiasingMask(unsigned) override; // FIXME: Having both shapeRoundedRect and shapePath is redundant. We could use shapePath for everything. WebCore::FloatRoundedRect shapeRoundedRect() const override; void setShapeRoundedRect(const WebCore::FloatRoundedRect&) override; WebCore::Path shapePath() const override; void setShapePath(const WebCore::Path&) override; WebCore::WindRule shapeWindRule() const override; void setShapeWindRule(WebCore::WindRule) override; WebCore::GraphicsLayer::CustomAppearance customAppearance() const override; void updateCustomAppearance(WebCore::GraphicsLayer::CustomAppearance) override; WebCore::TiledBacking* tiledBacking() override { return nullptr; } Ref<WebCore::PlatformCALayer> clone(WebCore::PlatformCALayerClient* owner) const override; Ref<PlatformCALayer> createCompatibleLayer(WebCore::PlatformCALayer::LayerType, WebCore::PlatformCALayerClient*) const override; void enumerateRectsBeingDrawn(CGContextRef, void (^block)(CGRect)) override; virtual uint32_t hostingContextID(); unsigned backingStoreBytesPerPixel() const override; void setClonedLayer(const PlatformCALayer*); RemoteLayerTreeTransaction::LayerProperties& properties() { return m_properties; } const RemoteLayerTreeTransaction::LayerProperties& properties() const { return m_properties; } void didCommit(); void clearContext() { m_context = nullptr; } RemoteLayerTreeContext* context() const { return m_context; } protected: PlatformCALayerRemote(WebCore::PlatformCALayer::LayerType, WebCore::PlatformCALayerClient* owner, RemoteLayerTreeContext& context); PlatformCALayerRemote(const PlatformCALayerRemote&, WebCore::PlatformCALayerClient*, RemoteLayerTreeContext&); void updateClonedLayerProperties(PlatformCALayerRemote& clone, bool copyContents = true) const; private: bool isPlatformCALayerRemote() const override { return true; } void ensureBackingStore(); void updateBackingStore(); void removeSublayer(PlatformCALayerRemote*); bool requiresCustomAppearanceUpdateOnBoundsChange() const; WebCore::LayerPool& layerPool() override; RemoteLayerTreeTransaction::LayerProperties m_properties; WebCore::PlatformCALayerList m_children; PlatformCALayerRemote* m_superlayer { nullptr }; PlatformCALayerRemote* m_maskLayer { nullptr }; HashMap<String, RefPtr<WebCore::PlatformCAAnimation>> m_animations; bool m_acceleratesDrawing { false }; bool m_wantsDeepColorBackingStore { false }; RemoteLayerTreeContext* m_context; }; } // namespace WebKit SPECIALIZE_TYPE_TRAITS_PLATFORM_CALAYER(WebKit::PlatformCALayerRemote, isPlatformCALayerRemote())
[ "lshi@espial.com" ]
lshi@espial.com
6e3677c39238340a18960a3541f91b429f0a7648
c99cc13d116e8dc280e008d8ce2c2a181b580709
/AudioEngine/AudioCapture.h
6a7065c09ac5f167c73b158f238eab12e024a4dc
[]
no_license
mehome/live_core
8440f86addd8d43cc0e7db5830f5361e637bc184
24d420a69379f697026cb47edfd1a3ed82eb2e4b
refs/heads/master
2022-12-16T01:35:08.811029
2020-09-17T09:03:31
2020-09-17T09:03:31
null
0
0
null
null
null
null
GB18030
C++
false
false
4,517
h
#ifndef __AUDIO_CAPTURE_INCLUDE__ #define __AUDIO_CAPTURE_INCLUDE__ #include "IAudioCapture.h" #include <atomic> #include "PhaseCheck.h" #include <atomic> class IDataReceiver; class IAudioEncoder; #define ALL_CH 8 //混音路数,最大为8 class AudioCapture : public IAudioCapture { public: AudioCapture(IDataReceiver *dataReiciever, int SampleRateHz); ~AudioCapture(); public: virtual void SetSampleRateHz(const int& iSampleRateHz); virtual bool InitPlaybackSource(wchar_t* deviceId); virtual bool AddRecodingSource(const TYPE_RECODING_SOURCE& sourceType, void **pAudioSource, const bool& isNoiseGate, void **param, const int& paramCnt); virtual bool SetNoiseGate(bool isNoise, int closeThreshold, int openThreshold); //添加麦克风设备 virtual bool SetMicDeviceInfo(DeviceInfo,bool isNoise,int closeThreshold,int openThreshold, int iAudioSampleRate, HRESULT& reuslt); virtual bool DelAudioSource(void *auduiSource); virtual void SetPlaybackVolume(const float& plackBackVol); virtual void SetMicVolume(const float& micVol); virtual void ClearRecodingSource(); virtual void SetAudioListening(IDataReceiver*); virtual bool Start(); virtual void SetPriority(int); virtual void SetInterval(int); virtual void Shutdown(); virtual UINT GetSampleRateHz() const; virtual UINT NumAudioChannels() const; virtual UINT GetBitsPerSample() const; virtual void GetAudioMeter(float& audioMag, float& audioPeak, float& audioMax); virtual void GetMicOrignalAudiometer(float& audioMag, float& audioPeak, float& audioMax); virtual float MuteMic(bool); virtual float MuteSpeaker(bool); virtual float GetMicVolunm(); virtual float GetSpekerVolumn(); virtual bool GetCurrentMic(DeviceInfo &deviceInfo); virtual void SetForceMono(bool); virtual bool GetForceMono(); virtual void SetSaveMicAudio(bool bSave); void CaptureAudioLoop(); void Process(); private: bool AddCoreAudioSource(DeviceInfo *device, const bool& isNoiseGate,void **); void AddAudioSource(IAudioSource *source); void RemoveAudioSource(IAudioSource *source); bool QueryAudioBuffers(QWORD &sleepTime); bool QueryNewAudio(QWORD& sleepTime); static DWORD __stdcall CaptureAudioThread(LPVOID lpUnused); void WaitForShutdownComplete(); void SyncAudioVolumn(float* mixBuffer/*List<float> &mixBuffer*/, UINT &audioFramesSinceMixaudioMaxUpdate); void SyncMicAudioVolumn(float* mixBuffer/*List<float> &mixBuffer*/, UINT &audioFramesSinceMixaudioMaxUpdate); bool IsSaveMicOrignalAudioState(); private: #ifdef DEBUG_AUDIO_CAPTURE // IAudioEncoder* mAudioEncoder; // FILE* mAacFile; FILE* mRawFile; FILE* mDeckFile; #endif FILE* mRawFile; FILE* mMixAudioFile; FILE* mMicAudioFile; FILE* mMediaAudioFile; FILE* mPlayerAudioFile; private: UINT mSampleRateHz; UINT mAudioChannels; bool mForceMicMono; //true 为单声道 bool mUsingPushToTalk; CircularList<uint64_t> mBufferedAudioTimes; IAudioSource *mPlaybackAudio = nullptr; IAudioSource *mMicAudio = nullptr; List<IAudioSource*> auxAudioSources; HANDLE mAuxAudioMutex; HANDLE mAudioFilterMutex; PhaseCheck *mPhaseCheckPtr = nullptr; uint64_t mLatestAudioTime; uint64_t mLatestQueryAudioTime; //float mCurDesktopVol; //扬声器音量 //std::atomic<float> mPlaybackVol; std::atomic<float> mPlaybackBackVol; //麦克风音量 float mCurMicVol; float mMicVol; float mMicBackVol; bool mRunning; std::atomic_bool mStart; HANDLE mCaptureThread; float mPlaybackMag; float mMicMag; float mPlaybackPeak; float mMicPeak; float mPlaybackMax; float mMicMax; //for output audio 音频输出 float mMixAudioMag; //混音后杂质 float mMixAudioPeak; //混音后峰值 float mMixAudioMax; //混音后音响最大 //for micMix audio float mMixMicAudioMag; float mMixMicAudioPeak; float mMixMicAudioMax; // HANDLE mSoundDataMutex; IDataReceiver *mDataReceiver = nullptr; //mediaCore IDataReceiver *mDataListening = nullptr; //回调监听 List<float> mInputBuffer; bool mRecievedFirstAudioFrame; int m_interval = 2; int m_priority = THREAD_PRIORITY_NORMAL; HANDLE mSaveMicAudioMutex; bool m_bSaveMicOrignalAudio; QWORD mDurationTime = 0; }; #endif
[ "ke.xu@vhall.com" ]
ke.xu@vhall.com
4dbcf63d8fdcfb074d70ac4123a8ff93c33eb346
5a8b9a20f7c498981eb4ea33c1cba4b9554440b4
/Xindows/src/site/download/Download.h
844a761ad015ae637d8570ad28aaf561b93f55c0
[]
no_license
mensong/IE5.5_vs2008
82ae91b3e45d312589b6fb461ceef5608dfb2f6b
6149654180d0f422355e38b0c5d8e84e6e8c6a0c
refs/heads/master
2022-05-01T07:32:15.727457
2018-11-14T03:07:51
2018-11-14T03:07:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,161
h
#ifndef __XINDOWS_SITE_DOWNLOAD_DOWNLOAD_H__ #define __XINDOWS_SITE_DOWNLOAD_DOWNLOAD_H__ #include <IImgCtx.h> // Declarations --------------------------------------------------------- class CImgTask; class CDocument; class CDwnCtx; class CDwnInfo; class CDwnLoad; class CDwnBindData; class CDwnDoc; class CPostItem; class CArtPlayer; // Definitions ---------------------------------------------------------- #define DWNLOAD_NOTLOADED IMGLOAD_NOTLOADED #define DWNLOAD_LOADING IMGLOAD_LOADING #define DWNLOAD_STOPPED IMGLOAD_STOPPED #define DWNLOAD_ERROR IMGLOAD_ERROR #define DWNLOAD_COMPLETE IMGLOAD_COMPLETE #define DWNLOAD_MASK IMGLOAD_MASK #define DWNCHG_COMPLETE IMGCHG_COMPLETE #define DWNCTX_HTM 0 // DWNTYPE_HTM #define DWNCTX_IMG 1 // DWNTYPE_IMG #define DWNCTX_BITS 2 // DWNTYPE_BITS #define DWNCTX_FILE 3 // DWNTYPE_FILE #define DWNCTX_MAX 4 #define DWNF_COLORMODE DWN_COLORMODE // 0x0000002F #define DWNF_DOWNLOADONLY DWN_DOWNLOADONLY // 0x00000040 #define DWNF_FORCEDITHER DWN_FORCEDITHER // 0x00000080 #define DWNF_RAWIMAGE DWN_RAWIMAGE // 0x00000100 #define DWNF_MIRRORIMAGE DWN_MIRRORIMAGE // 0x00000200 // Note: This block of flags overlaps the state flags on purpose as they are // not needed at the same time. #define DWNF_GETCONTENTTYPE 0x00010000 #define DWNF_GETREFRESH 0x00020000 #define DWNF_GETMODTIME 0x00040000 #define DWNF_GETFILELOCK 0x00080000 #define DWNF_GETFLAGS 0x00100000 // both reqflags and security flags #define DWNF_ISDOCBIND 0x00200000 #define DWNF_NOAUTOBUFFER 0x00400000 #define DWNF_IGNORESECURITY 0x00800000 #define DWNF_GETSTATUSCODE 0x01000000 #define DWNF_HANDLEECHO 0x02000000 #define DWNF_GETSECCONINFO 0x04000000 #define DWNF_NOOPTIMIZE 0x08000000 #define DWNF_STATE 0xFFFF0000 #define SZ_DWNBINDINFO_OBJECTPARAM _T("__DWNBINDINFO") #define SZ_HTMLLOADOPTIONS_OBJECTPARAM _T("__HTMLLOADOPTIONS") // Types ---------------------------------------------------------------- #define PFNDWNCHAN PFNIMGCTXCALLBACK typedef class CImgTask* (NEWIMGTASKFN)(); struct MIMEINFO { CLIPFORMAT cf; LPCTSTR pch; NEWIMGTASKFN* pfnImg; int ids; }; struct GIFFRAME; struct IMGANIMSTATE { DWORD dwLoopIter; // Current iteration of looped animation, not actually used for Netscape compliance reasons GIFFRAME* pgfFirst; // First frame GIFFRAME* pgfDraw; // Last frame we need to draw DWORD dwNextTimeMS; // Time to display pgfDraw->pgfNext, or next iteration BOOL fLoop; BOOL fStop; }; class CTreePos; struct HTMPASTEINFO { CODEPAGE cp; // Source CodePage for pasting int cbSelBegin; int cbSelEnd; CTreePos* ptpSelBegin; CTreePos* ptpSelEnd; CString cstrSourceUrl; }; struct DWNLOADINFO { CDwnBindData* pDwnBindData; // Bind data already in progress CDwnDoc* pDwnDoc; // CDwnDoc for binding IInternetSession* pInetSess; // Internet session to use if possible LPCTSTR pchUrl; // Bind data provided by URL IStream* pstm; // Bind data provided by IStream IMoniker* pmk; // Bind data provided by Moniker IBindCtx* pbc; // IBindCtx to use for binding BOOL fForceInet; // Force use of pInetSess BOOL fClientData; // Keep document open BOOL fResynchronize; // Don't believe dwRefresh from pDwnDoc BOOL fUnsecureSource;// Assume source is not https-secure DWORD dwProgClass; // used by CBitsCtx to override PROGSINK_CLASS (see CBitsInfo::Init) }; struct DWNDOCINFO { CDwnBindData* pDwnBindData; // CDwnBindData awaiting callback void* pvArg; // Argument for callback }; DECLARE_CDataAry(CAryDwnDocInfo, DWNDOCINFO); // Prototypes ----------------------------------------------------------------- HRESULT NewDwnCtx(UINT dt, BOOL fLoad, DWNLOADINFO* pdli, CDwnCtx** ppDwnCtx); int GetDefaultColorMode(); MIMEINFO* GetMimeInfoFromClipFormat(CLIPFORMAT cf); MIMEINFO* GetMimeInfoFromMimeType(const TCHAR* pchMime); int NormalizerCR(BOOL* pfEndCR, LPTSTR pchStart, LPTSTR* ppchEnd); int NormalizerChar(LPTSTR pchStart, LPTSTR* ppchEnd, BOOL* pfAscii=NULL); IInternetSession* TlsGetInternetSession(); class CDwnChan : public CBaseFT { typedef CBaseFT super; private: DECLARE_MEMCLEAR_NEW_DELETE() public: CDwnChan(CRITICAL_SECTION* pcs=NULL); void SetCallback(PFNDWNCHAN pfnCallback, void* pvCallback); void Disconnect(); #ifdef _DEBUG virtual char* GetOnMethodCallName() = 0; #endif protected: virtual void Passivate(); void Signal(); NV_DECLARE_ONCALL_METHOD(OnMethodCall, onmethodcall, (DWORD_PTR dwContext)); private: BOOL _fSignalled; PFNDWNCHAN _pfnCallback; void* _pvCallback; THREADSTATE* _pts; }; class CDwnCtx : public CDwnChan { typedef CDwnChan super; friend class CDwnInfo; private: DECLARE_MEMCLEAR_NEW_DELETE() public: #ifdef _DEBUG void EnterCriticalSection(); void LeaveCriticalSection(); BOOL EnteredCriticalSection(); #endif LPCTSTR GetUrl(); MIMEINFO* GetMimeInfo(); HRESULT GetFile(LPTSTR* ppch); FILETIME GetLastMod(); DWORD GetSecFlags(); HRESULT SetProgSink(IProgSink* pProgSink); ULONG GetState(BOOL fClear=FALSE); void SetLoad(BOOL fLoad, DWNLOADINFO* pdli, BOOL fReload); CDwnCtx* GetDwnCtxNext() { return(_pDwnCtxNext); } CDwnLoad* GetDwnLoad(); // Get AddRef'd CDwnLoad protected: virtual void Passivate(); CDwnInfo* GetDwnInfo() { return(_pDwnInfo); } void SetDwnInfo(CDwnInfo* pDwnInfo) { _pDwnInfo = pDwnInfo; } void Signal(WORD wChg); // Data members CDwnCtx* _pDwnCtxNext; CDwnInfo* _pDwnInfo; IProgSink* _pProgSink; WORD _wChg; WORD _wChgReq; BOOL _fLoad; }; // flags for CopyOriginalSource #define HTMSRC_FIXCRLF 0x1 #define HTMSRC_MULTIBYTE 0x2 #define HTMSRC_PRETRANSFORM 0x04 // flags for DrawImage #define DRAWIMAGE_NHPALETTE 0x01 // DrawImage - set if being drawn from a non-halftone palette #define DRAWIMAGE_NOTRANS 0x02 // DrawImage - set to ignore transparency #define DRAWIMAGE_MASKONLY 0x04 // DrawImage - set to draw the transparency mask only class CImgCtx : public CDwnCtx, public IImgCtx { typedef CDwnCtx super; friend class CImgInfo; public: DECLARE_MEMCLEAR_NEW_DELETE() // IUnknown members STDMETHOD(QueryInterface)(REFIID, void**); STDMETHOD_(ULONG,AddRef)(); STDMETHOD_(ULONG,Release)(); // IImgCtx members STDMETHOD(Load)(LPCWSTR pszUrl, DWORD dwFlags); STDMETHOD(SelectChanges)(ULONG ulChgOn, ULONG ulChgOff, BOOL fSignal); STDMETHOD(SetCallback)(PFNIMGCTXCALLBACK pfnCallback, void* pvCallback); STDMETHOD(Disconnect)(); STDMETHOD(GetUpdateRects)(RECT* prc, RECT* prectImg, LONG* pcrc); STDMETHOD(GetStateInfo)(ULONG* pulState, SIZE* psize, BOOL fClearChanges); STDMETHOD(GetPalette)(HPALETTE* phpal); STDMETHOD(Draw)(HDC hdc, LPRECT prcBounds); STDMETHOD(Tile)(HDC hdc, POINT* pptOrg, RECT* prcClip, SIZE* psizePrint); STDMETHOD(StretchBlt)(HDC hdc, int dstX, int dstY, int dstXE, int dstYE, int srcX, int srcY, int srcXE, int srcYE, DWORD dwROP); // CImgCtx members CImgCtx(); ULONG GetState() { return(super::GetState(FALSE)); } ULONG GetState(BOOL fClear, SIZE* psize); HRESULT SaveAsBmp(IStream* pStm, BOOL fFileHeader); void Tile(HDC hdc, POINT* pptOrg, RECT* prcClip, SIZE* psizePrint, COLORREF crBack, IMGANIMSTATE* pImgAnimState, DWORD dwFlags); BOOL NextFrame(IMGANIMSTATE* pImgAnimState, DWORD dwCurTimeMS, DWORD* pdwFrameTimeMS); void DrawFrame(HDC hdc, IMGANIMSTATE* pImgAnimState, RECT* prcDst, RECT* prcSrc, RECT* prcDestFull, DWORD dwFlags=0); void InitImgAnimState(IMGANIMSTATE* pImgAnimState); DWORD_PTR GetImgId() { return (DWORD_PTR) GetImgInfo(); } HRESULT DrawEx(HDC hdc, LPRECT prcBounds, DWORD dwFlags); // allows dwFlags to be supplied CArtPlayer* GetArtPlayer(); #ifdef _DEBUG virtual char* GetOnMethodCallName() { return "CImgCtx::OnMethodCall"; } #endif protected: CImgInfo* GetImgInfo() { return((CImgInfo*)GetDwnInfo()); } void Init(CImgInfo* pImgInfo); void Signal(WORD wChg, BOOL fInvalAll, int yBot); void TileFast(HDC hdc, RECT* prc, LONG xSrcOrg, LONG ySrcOrg, BOOL fOpaque, COLORREF crBack, IMGANIMSTATE* pImgAnimState, DWORD dwFlags); void TileSlow(HDC hdc, RECT* prc, LONG xSrcOrg, LONG ySrcOrg, SIZE* psizePrint, BOOL fOpaque, COLORREF crBack, IMGANIMSTATE* pImgAnimState, DWORD dwFlags); // Data members LONG _yTop; LONG _yBot; }; class CBitsCtx : public CDwnCtx { typedef CDwnCtx super; friend class CBitsInfo; public: DECLARE_MEMCLEAR_NEW_DELETE() // CBitsCtx methods ULONG GetState() { return(super::GetState(FALSE)); } void SelectChanges(ULONG ulChgOn, ULONG ulChgOff, BOOL fSignal); HRESULT GetStream(IStream** ppStream); #ifdef _DEBUG virtual char* GetOnMethodCallName() { return "CBitsCtx::OnMethodCall"; } #endif }; // CDwnDoc -------------------------------------------------------------------- class CDwnDoc : public CDwnChan, public IAuthenticate, public IWindowForBindingUI { typedef CDwnChan super; public: DECLARE_MEMCLEAR_NEW_DELETE() CDwnDoc(); virtual ~CDwnDoc(); // IUnknown methods STDMETHOD(QueryInterface)(REFIID iid, LPVOID* ppv); STDMETHOD_(ULONG,AddRef)() { return(super::AddRef()); } STDMETHOD_(ULONG,Release)() { return(super::Release()); } // CDwnDoc methods void SetBindf(DWORD dwBindf) { _dwBindf = dwBindf; } void SetDocBindf(DWORD dwBindf) { _dwDocBindf = dwBindf; } void SetLoadf(DWORD dwLoadf) { _dwLoadf = dwLoadf; } void SetDownf(DWORD dwDownf) { _dwDownf = dwDownf; } void SetRefresh(DWORD dwRefresh) { _dwRefresh = dwRefresh; } void SetDocCodePage(CODEPAGE cp) { _cpDoc = cp; } void SetURLCodePage(CODEPAGE cp) { _cpURL = cp; } HRESULT SetAcceptLanguage(LPCTSTR psz) { RRETURN(SetString(&_cstrAcceptLang, psz)); } HRESULT SetUserAgent(LPCTSTR psz) { RRETURN(SetString(&_cstrUserAgent, psz)); } HRESULT SetAuthorColors(LPCTSTR pchColors, int cchColors=-1); void AddBytesRead(DWORD dw) { _dwRead += dw; } void TakeRequestHeaders(BYTE** ppb, ULONG* pcb); BYTE* GetRequestHeaders() { return _pbRequestHeaders; } ULONG GetRequestHeadersLength() { return _cbRequestHeaders; } DWORD GetBindf() { return(_dwBindf); } DWORD GetDocBindf() { return(_dwDocBindf); } DWORD GetLoadf() { return(_dwLoadf); } DWORD GetDownf() { return(_dwDownf); } DWORD GetRefresh() { return(_dwRefresh); } DWORD GetDocCodePage() { return(_cpDoc); } DWORD GetURLCodePage() { return(_cpURL); } LPCTSTR GetAcceptLanguage() { return(_cstrAcceptLang); } LPCTSTR GetUserAgent() { return(_cstrUserAgent); } HRESULT GetColors(CColorInfo* pCI); DWORD GetBytesRead() { return(_dwRead); } CDocument* GetCDoc() { return(_pDoc); } void SetDownloadNotify(IDownloadNotify* pDownloadNotify); IDownloadNotify*GetDownloadNotify() { return(_pDownloadNotify); } static HRESULT Load(IStream* pstm, CDwnDoc** ppDwnDoc); static HRESULT Save(CDwnDoc* pDwnDoc, IStream* pstm); static ULONG GetSaveSize(CDwnDoc* pDwnDoc); void SetDoc(CDocument* pDoc); void Disconnect(); BOOL IsDocThread() { return(_dwThreadId == GetCurrentThreadId()); } HRESULT AddDocThreadCallback(CDwnBindData* pDwnBindData, void* pvArg); HRESULT QueryService(BOOL fBindOnApt, REFGUID rguid, REFIID riid, void** ppvObj); void PreventAuthorPalette() { _fGotAuthorPalette = TRUE; } BOOL WantAuthorPalette() { return !_fGotAuthorPalette; } BOOL GotAuthorPalette() { return _fGotAuthorPalette&&(_ape!=NULL); } #ifdef _DEBUG virtual char* GetOnMethodCallName() { return("CDwnDoc::OnMethodCall"); } #endif // IAuthenticate methods STDMETHOD(Authenticate)(HWND* phwnd, LPWSTR* ppszUsername, LPWSTR* ppszPassword); // IWindowForBindingUI methods STDMETHOD(GetWindow)(REFGUID rguidReason, HWND* phwnd); protected: static HRESULT SetString(CString* pcstr, LPCTSTR psz); void OnDocThreadCallback(); static void CALLBACK OnDocThreadCallback(void* pvObj, void* pvArg) { ((CDwnDoc*)pvArg)->OnDocThreadCallback(); } // Data members CDocument* _pDoc; // The document itself DWORD _dwThreadId; // Thread Id of the document DWORD _dwBindf; // See BINDF_* flags DWORD _dwDocBindf; // Bindf to be used for doc load only DWORD _dwLoadf; // See DLCTL_* flags DWORD _dwDownf; // See DWNF_* flags DWORD _dwRefresh; // Refresh level DWORD _cpDoc; // Codepage (Document) DWORD _cpURL; // Codepage (URL) DWORD _dwRead; // Number of bytes downloaded CString _cstrAcceptLang; // Accept language for headers CString _cstrUserAgent; // User agent for headers CAryDwnDocInfo _aryDwnDocInfo; // Bindings waiting for callback BOOL _fCallbacks; // DwnDoc is accepting callbacks BOOL _fGotAuthorPalette; // Have we got the author defined palette (or is too late) UINT _cpe; // Number of author defined colors PALETTEENTRY* _ape; // Author defined palette ULONG _cbRequestHeaders; // Byte length of the following field BYTE* _pbRequestHeaders; // Raw request headers to use (ASCII) IDownloadNotify* _pDownloadNotify; // Free-threaded callback to notify of downloads (see dwndoc.cxx) }; DEFINE_GUID(IID_IDwnBindInfo, 0x3050f3c3, 0x98b5, 0x11cf, 0xbb, 0x82, 0x00, 0xaa, 0x00, 0xbd, 0xce, 0x0b); // CDwnBindInfo --------------------------------------------------------------- class CDwnBindInfo : public CBaseFT, public IBindStatusCallback, public IServiceProvider, public IHttpNegotiate, public IInternetBindInfo { typedef CBaseFT super; friend HRESULT CreateDwnBindInfo(IUnknown*, IUnknown**); public: DECLARE_MEMCLEAR_NEW_DELETE() CDwnBindInfo(); // IUnknown methods STDMETHOD(QueryInterface)(REFIID iid, LPVOID* ppv); STDMETHOD_(ULONG,AddRef)(); STDMETHOD_(ULONG,Release)(); // IBindStatusCallback methods STDMETHOD(OnStartBinding)(DWORD dwReserved, IBinding* pib); STDMETHOD(GetPriority)(LONG* pnPriority); STDMETHOD(OnLowResource)(DWORD dwReserved); STDMETHOD(OnProgress)(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText); STDMETHOD(OnStopBinding)(HRESULT hresult, LPCWSTR szError); STDMETHOD(GetBindInfo)(DWORD* grfBINDF, BINDINFO* pbindinfo); STDMETHOD(OnDataAvailable)(DWORD grfBSCF, DWORD dwSize, FORMATETC* pformatetc, STGMEDIUM* pstgmed); STDMETHOD(OnObjectAvailable)(REFIID riid, IUnknown* punk); // IInternetBindInfo methods STDMETHOD(GetBindString)(ULONG ulStringType, LPOLESTR* ppwzStr, ULONG cEl, ULONG* pcElFetched); // IServiceProvider methods STDMETHOD(QueryService)(REFGUID rguidService, REFIID riid, void** ppvObj); // IHttpNegotiate methods STDMETHOD(BeginningTransaction)(LPCWSTR szURL, LPCWSTR szHeaders, DWORD dwReserved, LPWSTR* pszAdditionalHeaders); STDMETHOD(OnResponse)(DWORD dwResponseCode, LPCWSTR szResponseHeaders, LPCWSTR szRequestHeaders, LPWSTR* pszAdditionalRequestHeaders); // CDwnBindInfo methods void SetDwnDoc(CDwnDoc* pDwnDoc); void SetIsDocBind() { _fIsDocBind = TRUE; } CDwnDoc* GetDwnDoc() { return(_pDwnDoc); } virtual UINT GetScheme(); LPCTSTR GetContentType() { return(_cstrContentType); } LPCTSTR GetCacheFilename() { return(_cstrCacheFilename); } virtual BOOL IsBindOnApt() { return(TRUE); } #ifdef _DEBUG virtual BOOL CheckThread() { return(TRUE); } #endif protected: virtual ~CDwnBindInfo(); static BOOL CanMarshalIID(REFIID riid); static HRESULT ValidateMarshalParams(REFIID riid, void* pvInterface, DWORD dwDestContext, void* pvDestContext, DWORD mshlflags); // Data members CDwnDoc* _pDwnDoc; // CDwnDoc for this binding BOOL _fIsDocBind; // Binding for document itself CString _cstrContentType; // Content type of this binding CString _cstrCacheFilename; // cache file name for this file }; #endif //__XINDOWS_SITE_DOWNLOAD_DOWNLOAD_H__
[ "mail0668@gmail.com" ]
mail0668@gmail.com
34fe55d0bd40602cf3fed35e6320e53265318483
ba3ee053b194066495133ff6c797bf5af6991d0c
/gdb/event.cc
991e8350327679cc55b7f6d43d66e82017062621
[ "MIT" ]
permissive
jnow-87/vimgdb
abb2bc7392ca947af235339f0a15db51a5164535
2c0631816fa8217a102f036a748f726e3eb6f59d
refs/heads/master
2023-06-24T12:00:12.669294
2023-06-18T10:43:22
2023-06-18T10:43:22
35,759,547
0
0
null
null
null
null
UTF-8
C++
false
false
292
cc
#include <gdb/event.h> gdb_event_t::gdb_event_t(){ reason = 0; thread_id = 0; } gdb_event_t::~gdb_event_t(){ delete [] reason; } gdb_event_stop_t::gdb_event_stop_t(){ frame = 0; signal = 0; } gdb_event_stop_t::~gdb_event_stop_t(){ gdb_frame_t::release(frame); delete [] signal; }
[ "jan.nowotsch@gmail.com" ]
jan.nowotsch@gmail.com
86e29dd6173edbfe535fe56fa1cdff524f20a0db
c2aab7c3c7db45473bcb1b2421279116e9e19017
/Sansa and XOR.cpp
0010a2c58de75c7ae811358b32b8e0e1fd864be8
[]
no_license
rajat641/Algorithms
6bc30214bfcb87e08cfcee956f9547bb6e4e9d10
ca6c1448dee74c858a9e38024eddcb6111e40827
refs/heads/master
2020-08-15T19:23:35.394897
2020-05-04T10:46:59
2020-05-04T10:46:59
215,395,461
1
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; long long int a[4*100001]; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n; cin>>n; while(n--){ int x; cin>>x; long long int res=0; for(int u=1;u<=x;u++){ cin>>a[u]; if(u%2==1) res^= a[u]; } if(x%2==0) puts("0"); else printf("%lld\n",res);//<<endl; } return 0; }
[ "singhrajat641@gmail.com" ]
singhrajat641@gmail.com
903aad4951c5f4b2904136a3806fb6a9879aa097
9d8a75c2193b02f89e14900b7e30852c7d04e3b9
/synchclient/trunk/src/SYNCH/synchcore/FileUtils.h
4f7f559203d7859fdb6c3905affd7c2d99a95e7e
[]
no_license
GekkaKatsu/SYNCH
48572f2479f35701edb77c1c2c1e72a0bc522740
4893e406eefe5ca8b123aa39ad37f1eeb273dffe
refs/heads/master
2021-03-12T23:27:54.282730
2011-06-26T16:43:30
2011-06-26T16:43:30
1,756,174
0
0
null
null
null
null
UTF-8
C++
false
false
293
h
/* Посвещается моей любимой девушке Katsu Arsur */ #ifndef FILEUTILS_H #define FILEUTILS_H #include "synchcore.h" #include <QStringList> #include <QFileDialog> namespace FileUtils { QStringList SYNCHCORE_EXPORT getDirectoryNames(); } #endif // FILEUTILS_H
[ "yetanotherbot@yandex.ru" ]
yetanotherbot@yandex.ru
6ad793a1deb3b7a8a4c430b7cce04ddb05749e6b
7575668a328508652e169653d37eddaa08396a62
/Native/3rd/FBXSDK/FBX/GfxAsset_MeshCreater.cpp
f11822d927dc365c0a6b5f5b511e88a7879a60db
[]
no_license
huangdonghai/titan3d
dad61082d27ba1c65b0de7b3ca9d4a299ff1123c
571bce8ad677efb6ce3d92441b5af0b2340ff74f
refs/heads/master
2022-12-31T15:35:53.529550
2020-10-20T10:41:35
2020-10-20T10:41:35
null
0
0
null
null
null
null
GB18030
C++
false
false
18,483
cpp
#include "GfxAsset_MeshCreater.h" #include "GfxFBXManager.h" #include "FbxDataConverter.h" #include "../../Bricks/Animation/Pose/GfxAnimationPose.h" #include "../../Bricks/Animation/Skeleton/GfxSkeleton.h" #include "../../Graphics/Mesh/GfxSkinModifier.h" #include "../../Graphics/Mesh/GfxMeshPrimitives.h" #include "../../Graphics/Mesh/GfxMdfQueue.h" #include "GfxAsset_SubMesh.h" #include "GfxFileImportOption.h" #define new VNEW NS_BEGIN RTTI_IMPL(EngineNS::GfxAsset_MeshCreater, EngineNS::GfxAssetCreater); GfxAsset_MeshCreater::GfxAsset_MeshCreater() { } GfxAsset_MeshCreater::~GfxAsset_MeshCreater() { } bool IsSkeletonNode(FbxNode* boneNode) { if (boneNode == NULL) return false; auto name = FbxDataConverter::ConvertToStdString(boneNode->GetName()); FbxNodeAttribute* attr = boneNode->GetNodeAttribute(); if (attr == NULL) return false; FbxNodeAttribute::EType attType = attr->GetAttributeType(); if (attType == FbxNodeAttribute::eSkeleton || attType == FbxNodeAttribute::eNull) return true; else return false; } bool IsFbxRootNode(FbxNode* boneNode) { if (boneNode == NULL) return true; auto name = FbxDataConverter::ConvertToStdString(boneNode->GetName()); FbxNodeAttribute* attr = boneNode->GetNodeAttribute(); if (attr == NULL && name == "RootNode") return true; else return false; } FbxNode* GetSkeletonRootNode(FbxNode* boneNode) { auto name = FbxDataConverter::ConvertToStdString(boneNode->GetName()); FbxNodeAttribute* attr = boneNode->GetNodeAttribute(); FbxNodeAttribute::EType attType = attr->GetAttributeType(); if (attType == FbxNodeAttribute::eSkeleton || attType == FbxNodeAttribute::eNull) { FbxSkeleton* fbxBone = (FbxSkeleton*)attr; if (fbxBone->GetSkeletonType() == FbxSkeleton::eRoot) { auto parent = boneNode->GetParent(); if (parent != nullptr && parent->GetNodeAttribute() != nullptr) { auto parentAttType = parent->GetNodeAttribute()->GetAttributeType(); if (attType != FbxNodeAttribute::eSkeleton && attType != FbxNodeAttribute::eNull) { return boneNode; } } } } if (!IsSkeletonNode(boneNode->GetParent()) || IsFbxRootNode(boneNode->GetParent())) { return boneNode; } return GetSkeletonRootNode(boneNode->GetParent()); } //生成没在cluster里的骨骼 void GfxAsset_MeshCreater::RecursionCalculateBone(FbxNode* boneNode, GfxSkeleton* skeleton, std::vector<BoneCluster> boneClusters) { if (boneNode == NULL) return; auto boneName = FbxDataConverter::ConvertToStdString(boneNode->GetName()); auto r = boneNode->LclRotation.Get(); auto t = boneNode->LclTranslation.Get(); auto s = boneNode->LclScaling.Get(); //CalculateGlobalTransform(boneNode); auto bone = skeleton->FindBone(boneName.c_str()); if (bone) { for (int i = 0; i < boneNode->GetChildCount(); ++i) { RecursionCalculateBone(boneNode->GetChild(i), skeleton, boneClusters); } } else { FbxNodeAttribute* attr = boneNode->GetNodeAttribute(); if (!attr) return; FbxNodeAttribute::EType attType = attr->GetAttributeType(); if (attType != FbxNodeAttribute::eSkeleton && attType != FbxNodeAttribute::eNull) return; FbxSkeleton* fbxBone = (FbxSkeleton*)attr; GfxBoneDesc* boneDesc = new GfxBoneDesc(); boneDesc->SetName(boneName.c_str()); auto mat = boneNode->EvaluateGlobalTransform(); auto scaleT = mat.GetT() * mAssetImportOption->Scale; mat.SetT(scaleT); //boneDesc->SetBindMatrix(&FbxDataConverter::ConvertMatrix(mat)); auto v3dMat = v3dxMatrix4::IDENTITY; boneDesc->SetBindMatrix(&v3dMat); //if (fbxBone->GetSkeletonType() != FbxSkeleton::eRoot) { FbxNode* parentNode = boneNode->GetParent(); if (parentNode != NULL) { FbxNodeAttribute* parentAttr = parentNode->GetNodeAttribute(); if (parentAttr != NULL) { if (parentAttr->GetAttributeType() == FbxNodeAttribute::eSkeleton || parentAttr->GetAttributeType() == FbxNodeAttribute::eNull) { auto parentNodeName = FbxDataConverter::ConvertToStdString(parentNode->GetName()); boneDesc->SetParent(parentNodeName.c_str()); } } } } auto newBone = skeleton->NewBone(boneDesc); for (int i = 0; i < boneNode->GetChildCount(); ++i) { RecursionCalculateBone(boneNode->GetChild(i), skeleton, boneClusters); } } } void ReCalculateBoneBindMatrix(GfxBone* child, GfxBone* parent, GfxSkeleton* skeleton) { if (parent != NULL) { //child->mSharedData->InitMatrix = child->mSharedData->InitMatrix * parent->mSharedData->InitMatrix; } for (UINT i = 0; i < child->GetChildNumber(); ++i) { ReCalculateBoneBindMatrix(skeleton->GetBone(child->GetChild(i)), child, skeleton); } } void GfxAsset_MeshCreater::Process(IRenderContext* rc, FbxScene* scene, GfxFileImportOption* fileImportOption, GfxFBXManager* manager) { if (!mAssetImportOption->IsImport) return; auto meshImportOption = (GfxMeshImportOption*)mAssetImportOption; FbxNode* node = mAssetImportOption->FBXNode; auto att = node->GetNodeAttribute(); if (att->GetAttributeType() != IAT_Mesh) return; auto mesh = (FbxMesh*)att; OnImportMessageDumping(AMT_Import, 0, "Processing", 0); // Must do this before triangulating the mesh due to an FBX bug in TriangulateMeshAdvance // Convert mesh, NURBS and patch into triangle mesh FbxGeometryConverter GeometryConverter(manager->GetSDKManager()); int LayerSmoothingCount = mesh->GetLayerCount(FbxLayerElement::eSmoothing); for (int i = 0; i < LayerSmoothingCount; i++) { FbxLayerElementSmoothing const* SmoothingInfo = mesh->GetLayer(0)->GetSmoothing(); if (SmoothingInfo && SmoothingInfo->GetMappingMode() != FbxLayerElement::eByPolygon) { GeometryConverter.ComputePolygonSmoothingFromEdgeSmoothing(mesh, i); } } GeometryConverter.Triangulate(scene, /*replace*/true); auto controlPointsCount = mesh->GetControlPointsCount(); auto controlPoints = mesh->GetControlPoints(); auto polyCount = mesh->GetPolygonCount(); //auto polyVertexCount = mesh->GetPolygonVertexCount(); //split submesh by material std::vector<std::vector<int>*> subMeshIndices; auto nodeMatCount = node->GetMaterialCount(); auto elementMatCount = mesh->GetElementMaterialCount(); if (elementMatCount == 0 || nodeMatCount == 0) { subMeshIndices.push_back(new std::vector<int>()); for (int i = 0; i < polyCount; ++i) { subMeshIndices[0]->push_back(i); } } else { for (int i = 0; i < nodeMatCount; ++i) { subMeshIndices.push_back(new std::vector<int>()); } for (int i = 0; i < elementMatCount; ++i) { auto mat = node->GetMaterial(i); auto elementMat = mesh->GetElementMaterial(i); auto indices = elementMat->GetIndexArray(); auto mode = elementMat->GetMappingMode(); if (mode == FbxLayerElement::eByPolygon) { auto count = indices.GetCount(); int matId = 0; for (int j = 0; j < polyCount; ++j) { auto lMatId = indices.GetAt(j); subMeshIndices[lMatId]->push_back(j); auto material = node->GetMaterial(lMatId); } } else { int matId = 0; for (int j = 0; j < polyCount; ++j) { auto lMatId = indices.GetAt(0); subMeshIndices[lMatId]->push_back(j); auto material = node->GetMaterial(lMatId); } } } } for (int i = 0; i < (int)subMeshIndices.size(); ++i) { for (int j = i; j < (int)subMeshIndices.size(); ++j) { if (subMeshIndices[i]->size() < subMeshIndices[j]->size()) { auto iIndices = subMeshIndices[i]; subMeshIndices[i] = subMeshIndices[j]; subMeshIndices[j] = iIndices; } } } GfxAsset_SubMesh* subMesh = new GfxAsset_SubMesh[subMeshIndices.size()]; for (int i = 0; i < subMeshIndices.size(); ++i) { subMesh[i].PolyIndices = *subMeshIndices[i]; subMesh[i].PolyCount = (int)subMeshIndices[i]->size(); subMesh[i].AssetCreater = this; subMesh[i].Process(rc, scene, fileImportOption, meshImportOption, manager); } std::vector<DrawPrimitiveDesc> descs; UINT startIndex = 0; for (int i = 0; i < subMeshIndices.size(); ++i) { DrawPrimitiveDesc desc; desc.PrimitiveType = EPT_TriangleList; desc.BaseVertexIndex = 0; desc.StartIndex = startIndex; desc.NumInstances = 1; desc.NumPrimitives = subMesh[i].PolyCount; startIndex += desc.NumPrimitives * 3; descs.push_back(desc); } GfxAsset_SubMesh& biggestMesh = subMesh[0]; for (int i = 1; i < subMeshIndices.size(); ++i) { subMesh[i].MergeTo(&biggestMesh); } auto renderVertexCount = biggestMesh.VertexCount(); auto& vertexSkinIndex = biggestMesh.VertexSkinIndex; auto& vertexSkinWeight = biggestMesh.VertexSkinWeight; BYTE* skinIndexsStream = new BYTE[4 * renderVertexCount]; float* skinWeightsStream = new float[4 * renderVertexCount]; if (meshImportOption->HaveSkin) { //build skeleton std::vector < BoneCluster> BoneClusters; mFullSkeleton = new GfxSkeleton(); GfxSkeleton* meshSubSkeleton = new GfxSkeleton(); { auto skinDeformerCount = mesh->GetDeformerCount(FbxDeformer::EDeformerType::eSkin); if (skinDeformerCount > 0) { for (int i = 0; i < skinDeformerCount; ++i) { FbxSkin* skin = (FbxSkin*)mesh->GetDeformer(i, FbxDeformer::EDeformerType::eSkin); auto clusterCount = skin->GetClusterCount(); for (int clusterIndex = 0; clusterIndex < clusterCount; ++clusterIndex) { bool illegalScale = false; FbxCluster* cluster = skin->GetCluster(clusterIndex); FbxNode* link = cluster->GetLink(); auto boneName = FbxDataConverter::ConvertToStdString(link->GetName()); auto lclR = link->LclRotation.Get(); auto lclT = link->LclTranslation.Get(); auto lclS = link->LclScaling.Get(); FbxAMatrix linkTransformMatrix, transformMatrix; linkTransformMatrix = cluster->GetTransformLinkMatrix(linkTransformMatrix); auto linkrot = linkTransformMatrix.GetR(); auto linktran = linkTransformMatrix.GetT(); auto linkscale = linkTransformMatrix.GetS(); if (Math::Abs((float)linkscale[0] - 1) > SMALL_EPSILON || Math::Abs((float)linkscale[1] - 1) > SMALL_EPSILON || Math::Abs((float)linkscale[2] - 1) > SMALL_EPSILON) { illegalScale = true; } transformMatrix = cluster->GetTransformMatrix(transformMatrix); auto rot = transformMatrix.GetR(); auto tran = transformMatrix.GetT(); auto scale = transformMatrix.GetS(); if (Math::Abs((float)scale[0] - 1) > SMALL_EPSILON || Math::Abs((float)scale[1] - 1) > SMALL_EPSILON || Math::Abs((float)scale[2] - 1) > SMALL_EPSILON) { illegalScale = true; } if (illegalScale) { std::string name(boneName); std::string message("Bone has illegal Scale"); OnImportMessageDumping(AMT_Error, 0, (name + ":" + message).c_str(), 0.0f); } FbxNodeAttribute* attr = link->GetNodeAttribute(); FbxNodeAttribute::EType attType = attr->GetAttributeType(); if (attType != FbxNodeAttribute::eSkeleton && attType != FbxNodeAttribute::eNull) continue; FbxSkeleton* fbxBone = (FbxSkeleton*)attr; GfxBoneDesc* boneDesc = new GfxBoneDesc(); boneDesc->SetName(boneName.c_str()); auto mat = transformMatrix.Inverse() * linkTransformMatrix; auto scaleT = mat.GetT() * mAssetImportOption->Scale * fileImportOption->mScaleFactor; mat.SetT(scaleT); auto v3dMat = FbxDataConverter::ConvertMatrix(mat); boneDesc->SetBindMatrix(&v3dMat); //if (fbxBone->GetSkeletonType() != FbxSkeleton::eRoot) { FbxNode* parentNode = link->GetParent(); if (parentNode != NULL) { FbxNodeAttribute* parentAttr = parentNode->GetNodeAttribute(); if (parentAttr != NULL) { if (parentAttr->GetAttributeType() == FbxNodeAttribute::eSkeleton || parentAttr->GetAttributeType() == FbxNodeAttribute::eNull) { auto parentNodeName = FbxDataConverter::ConvertToStdString(parentNode->GetName()); boneDesc->SetParent(parentNodeName.c_str()); } } } } auto newBone = mFullSkeleton->NewBone(boneDesc); BoneCluster boneCluster; boneCluster.Bone = newBone; boneCluster.FBXCluster = cluster; BoneClusters.push_back(boneCluster); if (fbxBone->GetSkeletonType() == FbxSkeleton::eRoot) { mFullSkeleton->SetRoot(boneName.c_str()); } auto newMeshBone = meshSubSkeleton->NewBone(boneDesc); if (fbxBone->GetSkeletonType() == FbxSkeleton::eRoot) { meshSubSkeleton->SetRoot(boneName.c_str()); } } if (clusterCount > 0) { FbxCluster* cluster = skin->GetCluster(0); FbxNode* link = cluster->GetLink(); auto root = GetSkeletonRootNode(link); RecursionCalculateBone(root, mFullSkeleton, BoneClusters); auto rootName = FbxDataConverter::ConvertToStdString(root->GetName()); mFullSkeleton->SetRoot(rootName.c_str()); } } mFullSkeleton->GenerateHierarchy(); ReCalculateBoneBindMatrix(mFullSkeleton->GetRoot(), NULL, mFullSkeleton); } } //build skinModifier auto skinModifier = new GfxSkinModifier(); skinModifier->SetSkeleton(meshSubSkeleton); mMeshPrimitives->GetMdfQueue()->AddModifier(skinModifier); for (int i = 0; i < renderVertexCount; ++i) { auto size = vertexSkinIndex[i].size(); for (int j = 0; j < size; ++j) { for (int k = j + 1; k < size; ++k) { if (vertexSkinWeight[i][j] < vertexSkinWeight[i][k]) { auto temp = vertexSkinWeight[i][j]; vertexSkinWeight[i][j] = vertexSkinWeight[i][k]; vertexSkinWeight[i][k] = temp; auto tempIndex = vertexSkinIndex[i][j]; vertexSkinIndex[i][j] = vertexSkinIndex[i][k]; vertexSkinIndex[i][k] = tempIndex; } } } } //build skin stream for (int i = 0; i < renderVertexCount; ++i) { auto size = vertexSkinIndex[i].size(); float totalWeight = 0.0f; if (size > 4) size = 4; for (int j = 0; j < size; ++j) { totalWeight += vertexSkinWeight[i][j]; } for (int j = 0; j < 4; ++j) { if (j < size) { skinIndexsStream[i * 4 + j] = vertexSkinIndex[i][j]; skinWeightsStream[i * 4 + j] = vertexSkinWeight[i][j] / totalWeight; } else { skinIndexsStream[i * 4 + j] = 0; skinWeightsStream[i * 4 + j] = 0; } } } } OnImportMessageDumping(AMT_Import, 0, "Build Stream", 0.5f); //build stream auto polyVertexCount = biggestMesh.IndexCount(); auto& renderVertexs = biggestMesh.Vertexs; v3dxVector3* posStream = new v3dxVector3[renderVertexCount]; v3dxVector3* normalStream = new v3dxVector3[renderVertexCount]; v3dVector4_t* tangentStream = new v3dVector4_t[renderVertexCount]; v3dxVector2* uvStream = new v3dxVector2[renderVertexCount]; v3dxVector2* lightMapStream = new v3dxVector2[renderVertexCount]; DWORD* vertexColorStream = new DWORD[renderVertexCount]; UINT16* renderIndex16 = NULL; UINT* renderIndex32 = NULL; bool isIndex32 = false; //copy { if (biggestMesh.IsIndex32()) { isIndex32 = true; renderIndex32 = biggestMesh.VertexIndices.data(); } else { renderIndex16 = new UINT16[polyVertexCount]; for (int i = 0; i < polyVertexCount; ++i) { renderIndex16[i] = (UINT16)biggestMesh.VertexIndices[i]; } } for (int i = 0; i < renderVertexCount; ++i) { posStream[i] = renderVertexs[i].Postion; normalStream[i] = renderVertexs[i].Normal; tangentStream[i] = renderVertexs[i].TangentChirality; vertexColorStream[i] = renderVertexs[i].Color.getABGR(); uvStream[i] = renderVertexs[i].UV; lightMapStream[i] = renderVertexs[i].UV2; } } bool hasVertexColor = true; mesh->GetElementVertexColorCount(); if (mesh->GetElementVertexColorCount() > 0) { auto lVertexColorMappingMode = mesh->GetElementVertexColor(0)->GetMappingMode(); if (lVertexColorMappingMode == FbxGeometryElement::eNone) { //Don't have VertexColor hasVertexColor = false; } } else { //Don't have VertexColor hasVertexColor = false; } //set stream { mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_Position, posStream, (UINT)((UINT)sizeof(v3dxVector3) * renderVertexCount), sizeof(v3dxVector3), 0); if (hasVertexColor) mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_Color, vertexColorStream, (UINT)((UINT)sizeof(DWORD) * renderVertexCount), sizeof(DWORD), 0); mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_Normal, normalStream, (UINT)((UINT)sizeof(v3dxVector3) * renderVertexCount), sizeof(v3dxVector3), 0); mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_UV, uvStream, (UINT)((UINT)sizeof(v3dxVector2) * renderVertexCount), sizeof(v3dxVector2), 0); mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_LightMap, lightMapStream, (UINT)((UINT)sizeof(v3dxVector2) * renderVertexCount), sizeof(v3dxVector2), 0); mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_Tangent, tangentStream, (UINT)((UINT)sizeof(v3dVector4_t) * renderVertexCount), sizeof(v3dVector4_t), 0); if (isIndex32) { mMeshPrimitives->SetGeomtryMeshIndex(rc, renderIndex32, polyVertexCount * sizeof(UINT), EIndexBufferType::IBT_Int32, 0); } else { mMeshPrimitives->SetGeomtryMeshIndex(rc, renderIndex16, polyVertexCount * sizeof(UINT16), EIndexBufferType::IBT_Int16, 0); } if (meshImportOption->HaveSkin) { mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_SkinIndex, skinIndexsStream, 4 * renderVertexCount * sizeof(BYTE), 4 * sizeof(BYTE), 0); mMeshPrimitives->SetGeomtryMeshStream(rc, EVertexSteamType::VST_SkinWeight, skinWeightsStream, 4 * renderVertexCount * sizeof(float), 4 * sizeof(float), 0); } } //build aabb { v3dxBox3 aabb; for (int i = 0; i < renderVertexCount; i++) { aabb.OptimalVertex(posStream[i]); } mMeshPrimitives->SetAABB(aabb); } //delete stream { delete[] posStream; delete[] normalStream; delete[] tangentStream; delete[] uvStream; delete[] lightMapStream; if (renderIndex16) { delete[] renderIndex16; } if (renderIndex32) { // renderIndex32 is vertexIndex } //delete[] pControlPoints; //delete[] pAssetVertexs; } //final for (int i = 0; i < descs.size(); ++i) { mMeshPrimitives->PushAtomLOD(i, &descs[i]); } OnImportMessageDumping(AMT_Import, 0, "ProcessDone", 1.0f); } NS_END using namespace EngineNS; extern "C" { CSharpAPI1(EngineNS, GfxAsset_MeshCreater, SetMeshPrimitives, GfxMeshPrimitives*); CSharpReturnAPI0(GfxSkeleton*, EngineNS, GfxAsset_MeshCreater, GetFullSkeleton); }
[ "1832617@qq.com" ]
1832617@qq.com
16dfec59ed6d7b52801d95c986ae1b48b00a1232
497babdddf1fd52bfc727e83f188692804899dc4
/network/epoll/tcpaccept.cpp
3395a9847df890861ec92bfac8d1f58ab3011e5a
[ "MIT" ]
permissive
asummersday/zsummer
c371c2ed0095ca9bc0c655fab2eef1a17169ba91
092a239051b8c8cf92f7675ea0ffe26f920acbf9
refs/heads/master
2021-01-15T21:34:48.737635
2013-04-26T08:25:16
2013-04-26T08:25:16
9,095,360
2
0
null
2013-04-26T08:25:10
2013-03-29T08:58:42
C++
UTF-8
C++
false
false
4,964
cpp
/* * ZSUMMER License * ----------- * * ZSUMMER is licensed under the terms of the MIT license reproduced below. * This means that ZSUMMER is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2012 YaweiZhang <yawei_zhang@foxmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * =============================================================================== * * (end of COPYRIGHT) */ #include "tcpaccept.h" #include "tcpsocket.h" #include "epoll.h" using namespace zsummer; zsummer::network::ITcpAccept * zsummer::network::CreateTcpAccept() { return new CTcpAccept; } void zsummer::network::DestroyTcpAccept(zsummer::network::ITcpAccept *s) { delete s; } CTcpAccept::CTcpAccept() { m_port = 0; m_cb = NULL; memset(&m_handle, 0, sizeof(m_handle)); } CTcpAccept::~CTcpAccept() { } bool CTcpAccept::BindIOServer(IIOServer * ios) { m_ios =ios; return true; } bool CTcpAccept::SetCallbck(ITcpAcceptCallback * cb) { m_cb = cb; return true; } bool CTcpAccept::OpenAccept(const char * ip, unsigned short port) { if (m_cb == NULL) { LCF("ERR: callback not set!"); return false; } if (m_ios == NULL) { LCF("ERR: IIOServer not bind!"); return false; } if (m_handle._socket != 0) { LCF("ERR: socket is aready valid!"); return false; } m_handle._socket = socket(AF_INET, SOCK_STREAM, 0); if (m_handle._socket == -1) { LCF("ERR: socket create err errno =" << strerror(errno)); return false; } SetNonBlock(m_handle._socket); int bReuse = 1; if (setsockopt(m_handle._socket, SOL_SOCKET, SO_REUSEADDR, &bReuse, sizeof(bReuse)) != 0) { LCW("WAR: socket set reuse fail! errno=" << strerror(errno)); } m_addr.sin_family = AF_INET; m_addr.sin_addr.s_addr = inet_addr(ip); m_addr.sin_port = htons(port); if (bind(m_handle._socket, (sockaddr *) &m_addr, sizeof(m_addr)) != 0) { LCF("ERR: socket bind err, errno=" << strerror(errno)); close(m_handle._socket); m_handle._socket = 0; return false; } if (listen(m_handle._socket, 200) != 0) { LCF("ERR: socket listen err, errno=" << strerror(errno)); close(m_handle._socket); m_handle._socket = 0; return false; } m_handle._event.events = EPOLLIN; m_handle._event.data.ptr = &m_handle; m_handle._ptr = this; m_handle._type = tagRegister::REG_ACCEPT; if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_ADD, m_handle._socket, &m_handle._event) != 0) { LCF("ERR: epoll ctl accept err! errno=" << strerror(errno)); return false; } return true; } bool CTcpAccept::OnEPOLLMessage(bool bSuccess) { if (!bSuccess) { LCF("ERR: accept EPOLLERR, errno=" << strerror(errno)); Close(); return false; } else { LCD("INFO: onaccept on link"); sockaddr_in cltaddr; memset(&cltaddr, 0, sizeof(cltaddr)); socklen_t len = sizeof(cltaddr); int s = accept(m_handle._socket, (sockaddr *)&cltaddr, &len); if (s == -1) { if (errno != EAGAIN && errno != EWOULDBLOCK) { LCE("ERR: accept -1, errno=" << strerror(errno)); Close(); return false; } return true; } SetNonBlock(s); CTcpSocket * ps = (CTcpSocket *)CreateTcpSocket(); ps->m_handle._socket = s; ps->m_handle._event.data.ptr = & ps->m_handle; ps->m_handle._ptr = ps; ps->m_handle._type = tagRegister::REG_RECV; ps->m_bNeedDestroy = true; memcpy(&ps->m_addr, &cltaddr, sizeof(ps->m_addr)); m_cb->OnAccept(ps); } return true; } bool CTcpAccept::Close() { if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_DEL, m_handle._socket, &m_handle._event) != 0) { LCE("ERR: epoll ctl DEL err! errno=" << strerror(errno)); } shutdown(m_handle._socket, SHUT_RDWR); close(m_handle._socket); ((CIOServer*)m_ios)->PostMsg(PCK_ACCEPT_CLOSE, this); return true; } void CTcpAccept::OnPostClose() { m_cb->OnClose(); }
[ "yawei_zhang@foxmail.com" ]
yawei_zhang@foxmail.com
f920bf931a28eb568f97b2a762189f054a039a34
c140bf3623841d93c8753ab91507fb601a6ece35
/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.cc
ac670f01a3dadee0ed1ab87a02dfc5033eb3cf2e
[ "BSD-3-Clause" ]
permissive
quinndiggity/chromium
c991156cda0e3857ed8ecb1cb0a7ac5d18cc842c
0c062061326cd05a1ab884e5b2d6e03e2b79f215
refs/heads/master
2022-10-19T11:54:34.859476
2018-06-24T21:33:26
2018-06-24T21:33:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,594
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_regular.h" #include <stdint.h> #include <utility> #include "apps/app_lifetime_monitor_factory.h" #include "base/base64url.h" #include "base/bind.h" #include "base/command_line.h" #include "base/json/json_string_value_serializer.h" #include "base/linux_util.h" #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/sys_info.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/default_clock.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/cryptauth/chrome_cryptauth_service_factory.h" #include "chrome/browser/chromeos/login/easy_unlock/chrome_proximity_auth_client.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_notification_controller.h" #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_reauth.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/gcm/gcm_profile_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/common/chrome_features.h" #include "chrome/common/extensions/api/easy_unlock_private.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/pref_names.h" #include "chromeos/chromeos_features.h" #include "chromeos/components/proximity_auth/logging/logging.h" #include "chromeos/components/proximity_auth/proximity_auth_pref_names.h" #include "chromeos/components/proximity_auth/proximity_auth_profile_pref_manager.h" #include "chromeos/components/proximity_auth/proximity_auth_system.h" #include "chromeos/components/proximity_auth/screenlock_bridge.h" #include "chromeos/components/proximity_auth/switches.h" #include "components/cryptauth/cryptauth_access_token_fetcher.h" #include "components/cryptauth/cryptauth_client_impl.h" #include "components/cryptauth/cryptauth_enrollment_manager.h" #include "components/cryptauth/cryptauth_enrollment_utils.h" #include "components/cryptauth/cryptauth_gcm_manager_impl.h" #include "components/cryptauth/local_device_data_provider.h" #include "components/cryptauth/remote_device_loader.h" #include "components/cryptauth/secure_message_delegate_impl.h" #include "components/gcm_driver/gcm_profile_service.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_manager.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/user_manager/user_manager.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "extensions/browser/event_router.h" #include "extensions/common/constants.h" #include "google_apis/gaia/gaia_auth_util.h" namespace chromeos { namespace { // Key name of the local device permit record dictonary in kEasyUnlockPairing. const char kKeyPermitAccess[] = "permitAccess"; // Key name of the remote device list in kEasyUnlockPairing. const char kKeyDevices[] = "devices"; enum class SmartLockToggleFeature { DISABLE = false, ENABLE = true }; // The result of a SmartLock operation. enum class SmartLockResult { FAILURE = false, SUCCESS = true }; enum class SmartLockEnabledState { ENABLED = 0, DISABLED = 1, UNSET = 2, COUNT }; void LogToggleFeature(SmartLockToggleFeature toggle) { UMA_HISTOGRAM_BOOLEAN("SmartLock.ToggleFeature", static_cast<bool>(toggle)); } void LogToggleFeatureDisableResult(SmartLockResult result) { UMA_HISTOGRAM_BOOLEAN("SmartLock.ToggleFeature.Disable.Result", static_cast<bool>(result)); } void LogSmartLockEnabledState(SmartLockEnabledState state) { UMA_HISTOGRAM_ENUMERATION("SmartLock.EnabledState", state, SmartLockEnabledState::COUNT); } } // namespace EasyUnlockServiceRegular::EasyUnlockServiceRegular( Profile* profile, device_sync::DeviceSyncClient* device_sync_client) : EasyUnlockServiceRegular( profile, std::make_unique<EasyUnlockNotificationController>(profile), device_sync_client) {} EasyUnlockServiceRegular::EasyUnlockServiceRegular( Profile* profile, std::unique_ptr<EasyUnlockNotificationController> notification_controller, device_sync::DeviceSyncClient* device_sync_client) : EasyUnlockService(profile), turn_off_flow_status_(EasyUnlockService::IDLE), scoped_crypt_auth_device_manager_observer_(this), will_unlock_using_easy_unlock_(false), lock_screen_last_shown_timestamp_(base::TimeTicks::Now()), deferring_device_load_(false), notification_controller_(std::move(notification_controller)), device_sync_client_(device_sync_client), shown_pairing_changed_notification_(false), weak_ptr_factory_(this) { if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { // If this is the first GetSyncedDevices() call on DeviceSyncClient, it // won't have devices cached yet. |is_waiting_for_initial_sync_| is flipped // to indicate that we are waiting for this initial sync, to be inspected // in OnNewDevicesSynced(). OnNewDevicesSynced() needs to know that it is // receiving the initial sync, not a newly forced one, in order to prevent // it from running unrelated logic. if (device_sync_client_->GetSyncedDevices().empty()) is_waiting_for_initial_sync_ = true; else remote_device_unlock_keys_before_sync_ = GetUnlockKeys(); device_sync_client_->AddObserver(this); } } EasyUnlockServiceRegular::~EasyUnlockServiceRegular() { registrar_.RemoveAll(); if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) device_sync_client_->RemoveObserver(this); } // TODO(jhawkins): This method with |has_unlock_keys| == true is the only signal // that SmartLock setup has completed successfully. Make this signal more // explicit. void EasyUnlockServiceRegular::LoadRemoteDevices() { bool has_unlock_keys; if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { has_unlock_keys = !GetUnlockKeys().empty(); } else { has_unlock_keys = !GetCryptAuthDeviceManager()->GetUnlockKeys().empty(); } // TODO(jhawkins): The enabled pref should not be tied to whether unlock keys // exist; instead, both of these variables should be used to determine // IsEnabled(). pref_manager_->SetIsEasyUnlockEnabled(has_unlock_keys); if (has_unlock_keys) { // If |has_unlock_keys| is true, then the user must have successfully // completed setup. Track that the IsEasyUnlockEnabled pref is actively set // by the user, as opposed to passively being set to disabled (the default // state). pref_manager_->SetEasyUnlockEnabledStateSet(); LogSmartLockEnabledState(SmartLockEnabledState::ENABLED); } else { SetProximityAuthDevices(GetAccountId(), cryptauth::RemoteDeviceRefList(), base::nullopt /* local_device */); if (pref_manager_->IsEasyUnlockEnabledStateSet()) { LogSmartLockEnabledState(SmartLockEnabledState::DISABLED); } else { LogSmartLockEnabledState(SmartLockEnabledState::UNSET); } return; } // This code path may be hit by: // 1. New devices were synced on the lock screen. // 2. The service was initialized while the login screen is still up. if (proximity_auth::ScreenlockBridge::Get()->IsLocked()) { PA_LOG(INFO) << "Deferring device load until screen is unlocked."; deferring_device_load_ = true; return; } if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { UseLoadedRemoteDevices(GetUnlockKeys()); } else { remote_device_loader_.reset(new cryptauth::RemoteDeviceLoader( GetCryptAuthDeviceManager()->GetUnlockKeys(), proximity_auth_client()->GetAccountId(), GetCryptAuthEnrollmentManager()->GetUserPrivateKey(), cryptauth::SecureMessageDelegateImpl::Factory::NewInstance())); // OnRemoteDevicesLoaded() will call on UseLoadedRemoteDevices() with the // devices it receives. remote_device_loader_->Load( base::Bind(&EasyUnlockServiceRegular::OnRemoteDevicesLoaded, weak_ptr_factory_.GetWeakPtr())); } } void EasyUnlockServiceRegular::OnRemoteDevicesLoaded( const cryptauth::RemoteDeviceList& remote_devices) { DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); cryptauth::RemoteDeviceRefList remote_device_refs; for (auto& remote_device : remote_devices) { remote_device_refs.push_back(cryptauth::RemoteDeviceRef( std::make_shared<cryptauth::RemoteDevice>(remote_device))); } UseLoadedRemoteDevices(remote_device_refs); } void EasyUnlockServiceRegular::UseLoadedRemoteDevices( const cryptauth::RemoteDeviceRefList& remote_devices) { SetProximityAuthDevices( GetAccountId(), remote_devices, base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi) ? device_sync_client_->GetLocalDeviceMetadata() : base::nullopt); // We need to store a copy of |remote devices_| in the TPM, so it can be // retrieved on the sign-in screen when a user session has not been started // yet. std::unique_ptr<base::ListValue> device_list(new base::ListValue()); for (const auto& device : remote_devices) { std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); std::string b64_public_key, b64_psk; base::Base64UrlEncode(device.public_key(), base::Base64UrlEncodePolicy::INCLUDE_PADDING, &b64_public_key); base::Base64UrlEncode(device.persistent_symmetric_key(), base::Base64UrlEncodePolicy::INCLUDE_PADDING, &b64_psk); dict->SetString("name", device.name()); dict->SetString("psk", b64_psk); // TODO(jhawkins): Remove the bluetoothAddress field from this proto. dict->SetString("bluetoothAddress", std::string()); if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { dict->SetString("permitId", "permit://google.com/easyunlock/v1/" + gaia::CanonicalizeEmail( GetAccountId().GetUserEmail())); } else { dict->SetString("permitId", "permit://google.com/easyunlock/v1/" + proximity_auth_client()->GetAccountId()); } dict->SetString("permitRecord.id", b64_public_key); dict->SetString("permitRecord.type", "license"); dict->SetString("permitRecord.data", b64_public_key); std::unique_ptr<base::ListValue> beacon_seed_list(new base::ListValue()); for (const auto& beacon_seed : device.beacon_seeds()) { std::string b64_beacon_seed; base::Base64UrlEncode(beacon_seed.SerializeAsString(), base::Base64UrlEncodePolicy::INCLUDE_PADDING, &b64_beacon_seed); beacon_seed_list->AppendString(b64_beacon_seed); } std::string serialized_beacon_seeds; JSONStringValueSerializer serializer(&serialized_beacon_seeds); serializer.Serialize(*beacon_seed_list); dict->SetString("serializedBeaconSeeds", serialized_beacon_seeds); device_list->Append(std::move(dict)); } // TODO(tengs): Rename this function after the easy_unlock app is replaced. SetRemoteDevices(*device_list); } proximity_auth::ProximityAuthPrefManager* EasyUnlockServiceRegular::GetProximityAuthPrefManager() { return pref_manager_.get(); } EasyUnlockService::Type EasyUnlockServiceRegular::GetType() const { return EasyUnlockService::TYPE_REGULAR; } AccountId EasyUnlockServiceRegular::GetAccountId() const { const SigninManagerBase* signin_manager = SigninManagerFactory::GetForProfileIfExists(profile()); // |profile| has to be a signed-in profile with SigninManager already // created. Otherwise, just crash to collect stack. DCHECK(signin_manager); const AccountInfo account_info = signin_manager->GetAuthenticatedAccountInfo(); return account_info.email.empty() ? EmptyAccountId() : AccountId::FromUserEmailGaiaId( gaia::CanonicalizeEmail(account_info.email), account_info.gaia); } void EasyUnlockServiceRegular::LaunchSetup() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); LogToggleFeature(SmartLockToggleFeature::ENABLE); // Force the user to reauthenticate by showing a modal overlay (similar to the // lock screen). The password obtained from the reauth is cached for a short // period of time and used to create the cryptohome keys for sign-in. if (short_lived_user_context_ && short_lived_user_context_->user_context()) { OpenSetupApp(); } else { bool reauth_success = EasyUnlockReauth::ReauthForUserContext( base::Bind(&EasyUnlockServiceRegular::OpenSetupAppAfterReauth, weak_ptr_factory_.GetWeakPtr())); if (!reauth_success) OpenSetupApp(); } } void EasyUnlockServiceRegular::HandleUserReauth( const UserContext& user_context) { // Cache the user context for the next X minutes, so the user doesn't have to // reauth again. short_lived_user_context_.reset(new ShortLivedUserContext( user_context, apps::AppLifetimeMonitorFactory::GetForBrowserContext(profile()), base::ThreadTaskRunnerHandle::Get().get())); } void EasyUnlockServiceRegular::OpenSetupAppAfterReauth( const UserContext& user_context) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); HandleUserReauth(user_context); OpenSetupApp(); // Use this opportunity to clear the crytohome keys if it was not already // cleared earlier. const base::ListValue* devices = GetRemoteDevices(); if (!devices || devices->empty()) { EasyUnlockKeyManager* key_manager = UserSessionManager::GetInstance()->GetEasyUnlockKeyManager(); key_manager->RefreshKeys( user_context, base::ListValue(), base::Bind(&EasyUnlockServiceRegular::SetHardlockAfterKeyOperation, weak_ptr_factory_.GetWeakPtr(), EasyUnlockScreenlockStateHandler::NO_PAIRING)); } } void EasyUnlockServiceRegular::SetHardlockAfterKeyOperation( EasyUnlockScreenlockStateHandler::HardlockState state_on_success, bool success) { if (success) SetHardlockStateForUser(GetAccountId(), state_on_success); // Even if the refresh keys operation suceeded, we still fetch and check the // cryptohome keys against the keys in local preferences as a sanity check. CheckCryptohomeKeysAndMaybeHardlock(); } void EasyUnlockServiceRegular::ClearPermitAccess() { DictionaryPrefUpdate pairing_update(profile()->GetPrefs(), prefs::kEasyUnlockPairing); pairing_update->RemoveWithoutPathExpansion(kKeyPermitAccess, NULL); } const base::ListValue* EasyUnlockServiceRegular::GetRemoteDevices() const { const base::DictionaryValue* pairing_dict = profile()->GetPrefs()->GetDictionary(prefs::kEasyUnlockPairing); const base::ListValue* devices = NULL; if (pairing_dict && pairing_dict->GetList(kKeyDevices, &devices)) return devices; return NULL; } void EasyUnlockServiceRegular::SetRemoteDevices( const base::ListValue& devices) { std::string remote_devices_json; JSONStringValueSerializer serializer(&remote_devices_json); serializer.Serialize(devices); PA_LOG(INFO) << "Setting RemoteDevices:\n " << remote_devices_json; DictionaryPrefUpdate pairing_update(profile()->GetPrefs(), prefs::kEasyUnlockPairing); if (devices.empty()) pairing_update->RemoveWithoutPathExpansion(kKeyDevices, NULL); else pairing_update->SetKey(kKeyDevices, devices.Clone()); RefreshCryptohomeKeysIfPossible(); } void EasyUnlockServiceRegular::RunTurnOffFlow() { if (turn_off_flow_status_ == PENDING) return; LogToggleFeature(SmartLockToggleFeature::DISABLE); SetTurnOffFlowStatus(PENDING); if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { // Disabling EASY_UNLOCK_HOST is a special case that does not require a // public key to be passed; EASY_UNLOCK_HOST will be disabled for all hosts. device_sync_client_->SetSoftwareFeatureState( std::string() /* public_key */, cryptauth::SoftwareFeature::EASY_UNLOCK_HOST, false /* enabled */, false /* is_exclusive */, base::BindOnce(&EasyUnlockServiceRegular::OnTurnOffEasyUnlockCompleted, weak_ptr_factory_.GetWeakPtr())); } else { DCHECK(!cryptauth_client_); std::unique_ptr<cryptauth::CryptAuthClientFactory> factory = proximity_auth_client()->CreateCryptAuthClientFactory(); cryptauth_client_ = factory->CreateInstance(); cryptauth::ToggleEasyUnlockRequest request; request.set_enable(false); request.set_apply_to_all(true); cryptauth_client_->ToggleEasyUnlock( request, base::Bind(&EasyUnlockServiceRegular::OnToggleEasyUnlockApiComplete, weak_ptr_factory_.GetWeakPtr()), base::Bind(&EasyUnlockServiceRegular::OnToggleEasyUnlockApiFailed, weak_ptr_factory_.GetWeakPtr())); } } void EasyUnlockServiceRegular::ResetTurnOffFlow() { cryptauth_client_.reset(); SetTurnOffFlowStatus(IDLE); } EasyUnlockService::TurnOffFlowStatus EasyUnlockServiceRegular::GetTurnOffFlowStatus() const { return turn_off_flow_status_; } std::string EasyUnlockServiceRegular::GetChallenge() const { return std::string(); } std::string EasyUnlockServiceRegular::GetWrappedSecret() const { return std::string(); } void EasyUnlockServiceRegular::RecordEasySignInOutcome( const AccountId& account_id, bool success) const { NOTREACHED(); } void EasyUnlockServiceRegular::RecordPasswordLoginEvent( const AccountId& account_id) const { NOTREACHED(); } void EasyUnlockServiceRegular::InitializeInternal() { proximity_auth::ScreenlockBridge::Get()->AddObserver(this); pref_manager_.reset(new proximity_auth::ProximityAuthProfilePrefManager( profile()->GetPrefs())); // TODO(tengs): Due to badly configured browser_tests, Chrome crashes during // shutdown. Revisit this condition after migration is fully completed. if (!base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) { // Note: There is no local state in tests. if (g_browser_process->local_state()) { pref_manager_->StartSyncingToLocalState(g_browser_process->local_state(), GetAccountId()); } if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { remote_device_unlock_keys_before_sync_ = GetUnlockKeys(); } else { scoped_crypt_auth_device_manager_observer_.Add( GetCryptAuthDeviceManager()); } LoadRemoteDevices(); } registrar_.Init(profile()->GetPrefs()); registrar_.Add( proximity_auth::prefs::kProximityAuthIsChromeOSLoginEnabled, base::Bind(&EasyUnlockServiceRegular::RefreshCryptohomeKeysIfPossible, weak_ptr_factory_.GetWeakPtr())); } void EasyUnlockServiceRegular::ShutdownInternal() { short_lived_user_context_.reset(); turn_off_flow_status_ = EasyUnlockService::IDLE; proximity_auth::ScreenlockBridge::Get()->RemoveObserver(this); if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) device_sync_client_->RemoveObserver(this); else scoped_crypt_auth_device_manager_observer_.RemoveAll(); } bool EasyUnlockServiceRegular::IsAllowedInternal() const { user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (!user_manager->IsLoggedInAsUserWithGaiaAccount()) return false; // TODO(tengs): Ephemeral accounts generate a new enrollment every time they // are added, so disable Smart Lock to reduce enrollments on server. However, // ephemeral accounts can be locked, so we should revisit this use case. if (user_manager->IsCurrentUserNonCryptohomeDataEphemeral()) return false; if (!ProfileHelper::IsPrimaryProfile(profile())) return false; if (!profile()->GetPrefs()->GetBoolean(prefs::kEasyUnlockAllowed)) return false; return true; } bool EasyUnlockServiceRegular::IsEnabled() const { return pref_manager_ && pref_manager_->IsEasyUnlockEnabled(); } bool EasyUnlockServiceRegular::IsChromeOSLoginEnabled() const { return pref_manager_ && pref_manager_->IsChromeOSLoginEnabled(); } void EasyUnlockServiceRegular::OnWillFinalizeUnlock(bool success) { will_unlock_using_easy_unlock_ = success; } void EasyUnlockServiceRegular::OnSuspendDoneInternal() { lock_screen_last_shown_timestamp_ = base::TimeTicks::Now(); } void EasyUnlockServiceRegular::OnSyncStarted() { unlock_keys_before_sync_ = GetCryptAuthDeviceManager()->GetUnlockKeys(); } void EasyUnlockServiceRegular::OnSyncFinished( cryptauth::CryptAuthDeviceManager::SyncResult sync_result, cryptauth::CryptAuthDeviceManager::DeviceChangeResult device_change_result) { DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); if (sync_result == cryptauth::CryptAuthDeviceManager::SyncResult::FAILURE) return; std::set<std::string> public_keys_before_sync; for (const auto& device_info : unlock_keys_before_sync_) { public_keys_before_sync.insert(device_info.public_key()); } unlock_keys_before_sync_.clear(); std::vector<cryptauth::ExternalDeviceInfo> unlock_keys_after_sync = GetCryptAuthDeviceManager()->GetUnlockKeys(); std::set<std::string> public_keys_after_sync; for (const auto& device_info : unlock_keys_after_sync) { public_keys_after_sync.insert(device_info.public_key()); } ShowNotificationIfNewDevicePresent(public_keys_before_sync, public_keys_after_sync); LoadRemoteDevices(); } void EasyUnlockServiceRegular::OnNewDevicesSynced() { // This method copies EasyUnlockServiceRegular::OnSyncFinished(). // TODO(crbug.com/848956): Remove EasyUnlockServiceRegular::OnSyncFinished(). DCHECK(base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); std::set<std::string> public_keys_before_sync; if (is_waiting_for_initial_sync_) { is_waiting_for_initial_sync_ = false; // Without this, |public_keys_before_sync| would be incorrectly empty. remote_device_unlock_keys_before_sync_ = GetUnlockKeys(); } for (const auto& remote_device : remote_device_unlock_keys_before_sync_) { public_keys_before_sync.insert(remote_device.public_key()); } cryptauth::RemoteDeviceRefList remote_device_unlock_keys_after_sync = GetUnlockKeys(); std::set<std::string> public_keys_after_sync; for (const auto& remote_device : remote_device_unlock_keys_after_sync) { public_keys_after_sync.insert(remote_device.public_key()); } ShowNotificationIfNewDevicePresent(public_keys_before_sync, public_keys_after_sync); LoadRemoteDevices(); remote_device_unlock_keys_before_sync_ = remote_device_unlock_keys_after_sync; } void EasyUnlockServiceRegular::ShowNotificationIfNewDevicePresent( const std::set<std::string>& public_keys_before_sync, const std::set<std::string>& public_keys_after_sync) { if (public_keys_after_sync.empty()) ClearPermitAccess(); if (public_keys_before_sync == public_keys_after_sync) return; // Show the appropriate notification if an unlock key is first synced or if it // changes an existing key. // Note: We do not show a notification when EasyUnlock is disabled by sync nor // if EasyUnlock was enabled through the setup app. bool is_setup_fresh = short_lived_user_context_ && short_lived_user_context_->user_context(); if (!public_keys_after_sync.empty() && !is_setup_fresh) { if (public_keys_before_sync.empty()) { notification_controller_->ShowChromebookAddedNotification(); } else { shown_pairing_changed_notification_ = true; notification_controller_->ShowPairingChangeNotification(); } } } void EasyUnlockServiceRegular::OnForceSyncCompleted(bool success) { if (!success) PA_LOG(WARNING) << "Failed to force device sync."; } void EasyUnlockServiceRegular::OnScreenDidLock( proximity_auth::ScreenlockBridge::LockHandler::ScreenType screen_type) { will_unlock_using_easy_unlock_ = false; lock_screen_last_shown_timestamp_ = base::TimeTicks::Now(); } void EasyUnlockServiceRegular::OnScreenDidUnlock( proximity_auth::ScreenlockBridge::LockHandler::ScreenType screen_type) { // If we tried to load remote devices (e.g. after a sync or the // service was initialized) while the screen was locked, we can now // load the new remote devices. // // It's important to go through this code path even if unlocking the // login screen. Because when the service is initialized while the // user is signing in we need to load the remotes. Otherwise, the // first time the user locks the screen the feature won't work. if (deferring_device_load_) { PA_LOG(INFO) << "Loading deferred devices after screen unlock."; deferring_device_load_ = false; LoadRemoteDevices(); } // Do not process events for the login screen. if (screen_type != proximity_auth::ScreenlockBridge::LockHandler::LOCK_SCREEN) return; if (shown_pairing_changed_notification_) { shown_pairing_changed_notification_ = false; std::vector<cryptauth::ExternalDeviceInfo> unlock_keys = GetCryptAuthDeviceManager()->GetUnlockKeys(); if (!unlock_keys.empty()) { // TODO(tengs): Right now, we assume that there is only one possible // unlock key. We need to update this notification be more generic. notification_controller_->ShowPairingChangeAppliedNotification( unlock_keys[0].friendly_device_name()); } } // Only record metrics for users who have enabled the feature. if (IsEnabled()) { EasyUnlockAuthEvent event = will_unlock_using_easy_unlock_ ? EASY_UNLOCK_SUCCESS : GetPasswordAuthEvent(); RecordEasyUnlockScreenUnlockEvent(event); if (will_unlock_using_easy_unlock_) { RecordEasyUnlockScreenUnlockDuration(base::TimeTicks::Now() - lock_screen_last_shown_timestamp_); } } will_unlock_using_easy_unlock_ = false; } void EasyUnlockServiceRegular::OnFocusedUserChanged( const AccountId& account_id) { // Nothing to do. } void EasyUnlockServiceRegular::SetTurnOffFlowStatus(TurnOffFlowStatus status) { turn_off_flow_status_ = status; NotifyTurnOffOperationStatusChanged(); } void EasyUnlockServiceRegular::OnToggleEasyUnlockApiComplete( const cryptauth::ToggleEasyUnlockResponse& response) { DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); cryptauth_client_.reset(); OnTurnOffEasyUnlockSuccess(); } void EasyUnlockServiceRegular::OnToggleEasyUnlockApiFailed( const std::string& error_message) { DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); OnTurnOffEasyUnlockFailure(error_message); } void EasyUnlockServiceRegular::OnTurnOffEasyUnlockCompleted( const base::Optional<std::string>& error_code) { DCHECK(base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); if (error_code) OnTurnOffEasyUnlockFailure(*error_code); else OnTurnOffEasyUnlockSuccess(); } void EasyUnlockServiceRegular::OnTurnOffEasyUnlockSuccess() { PA_LOG(INFO) << "Successfully turned off Smart Lock."; LogToggleFeatureDisableResult(SmartLockResult::SUCCESS); if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { remote_device_unlock_keys_before_sync_ = GetUnlockKeys(); device_sync_client_->ForceSyncNow( base::BindOnce(&EasyUnlockServiceRegular::OnForceSyncCompleted, weak_ptr_factory_.GetWeakPtr())); } else { GetCryptAuthDeviceManager()->ForceSyncNow( cryptauth::InvocationReason::INVOCATION_REASON_FEATURE_TOGGLED); } EasyUnlockService::ResetLocalStateForUser(GetAccountId()); SetRemoteDevices(base::ListValue()); SetProximityAuthDevices(GetAccountId(), cryptauth::RemoteDeviceRefList(), base::nullopt /* local_device */); pref_manager_->SetIsEasyUnlockEnabled(false); SetTurnOffFlowStatus(IDLE); ResetScreenlockState(); registrar_.RemoveAll(); } void EasyUnlockServiceRegular::OnTurnOffEasyUnlockFailure( const std::string& error_message) { LOG(WARNING) << "Failed to turn off Smart Lock: " << error_message; LogToggleFeatureDisableResult(SmartLockResult::FAILURE); SetTurnOffFlowStatus(FAIL); } cryptauth::CryptAuthEnrollmentManager* EasyUnlockServiceRegular::GetCryptAuthEnrollmentManager() { DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); cryptauth::CryptAuthEnrollmentManager* manager = ChromeCryptAuthServiceFactory::GetInstance() ->GetForBrowserContext(profile()) ->GetCryptAuthEnrollmentManager(); DCHECK(manager); return manager; } cryptauth::CryptAuthDeviceManager* EasyUnlockServiceRegular::GetCryptAuthDeviceManager() { DCHECK(!base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)); cryptauth::CryptAuthDeviceManager* manager = ChromeCryptAuthServiceFactory::GetInstance() ->GetForBrowserContext(profile()) ->GetCryptAuthDeviceManager(); DCHECK(manager); return manager; } void EasyUnlockServiceRegular::RefreshCryptohomeKeysIfPossible() { // If the user reauthed on the settings page, then the UserContext will be // cached. if (short_lived_user_context_ && short_lived_user_context_->user_context()) { // We only sync the remote devices to cryptohome if the user has enabled // EasyUnlock on the login screen. base::ListValue empty_list; const base::ListValue* remote_devices_list = GetRemoteDevices(); if (!IsChromeOSLoginEnabled() || !remote_devices_list) remote_devices_list = &empty_list; UserSessionManager::GetInstance()->GetEasyUnlockKeyManager()->RefreshKeys( *short_lived_user_context_->user_context(), base::ListValue(remote_devices_list->GetList()), base::Bind(&EasyUnlockServiceRegular::SetHardlockAfterKeyOperation, weak_ptr_factory_.GetWeakPtr(), EasyUnlockScreenlockStateHandler::NO_HARDLOCK)); } else { CheckCryptohomeKeysAndMaybeHardlock(); } } cryptauth::RemoteDeviceRefList EasyUnlockServiceRegular::GetUnlockKeys() { cryptauth::RemoteDeviceRefList unlock_keys; for (const auto& remote_device : device_sync_client_->GetSyncedDevices()) { if (remote_device.unlock_key()) unlock_keys.push_back(remote_device); } return unlock_keys; } } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
26b97dc5bf3b409fc0266a556b94dbd771f7e2b1
869cefe6ea1acb40e347f5430278b1204984b565
/extras/include/boost/boost/mpl/aux_/msvc_eti_base.hpp
c3a766981ed9ef3ad7f1d2b0c221eded0cddc6b2
[ "BSL-1.0" ]
permissive
muschellij2/FSL6.0.0
c68ed91e8c2777fcf07d994d7ab288a75e448fd1
3c3dd651066ee189bc8c290f744ca48cb3d1f156
refs/heads/master
2020-04-27T01:04:04.915711
2019-03-05T14:57:48
2019-03-05T14:57:48
173,954,388
9
4
null
null
null
null
UTF-8
C++
false
false
1,763
hpp
#ifndef BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED #define BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: msvc_eti_base.hpp,v 1.1.1.2 2015/02/27 15:20:24 mwebster Exp $ // $Date: 2015/02/27 15:20:24 $ // $Revision: 1.1.1.2 $ #include <boost/mpl/aux_/is_msvc_eti_arg.hpp> #include <boost/mpl/aux_/config/eti.hpp> #include <boost/mpl/aux_/config/gcc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> namespace boost { namespace mpl { namespace aux { #if defined(BOOST_MPL_CFG_MSVC_70_ETI_BUG) template< bool > struct msvc_eti_base_impl { template< typename T > struct result_ : T { typedef T type; }; }; template<> struct msvc_eti_base_impl<true> { template< typename T > struct result_ { typedef result_ type; typedef result_ first; typedef result_ second; typedef result_ tag; enum { value = 0 }; }; }; template< typename T > struct msvc_eti_base : msvc_eti_base_impl< is_msvc_eti_arg<T>::value > ::template result_<T> { }; #else // !BOOST_MPL_CFG_MSVC_70_ETI_BUG template< typename T > struct msvc_eti_base : T { #if BOOST_WORKAROUND(BOOST_MPL_CFG_GCC, BOOST_TESTED_AT(0x0304)) msvc_eti_base(); #endif typedef T type; }; #endif template<> struct msvc_eti_base<int> { typedef msvc_eti_base type; typedef msvc_eti_base first; typedef msvc_eti_base second; typedef msvc_eti_base tag; enum { value = 0 }; }; }}} #endif // BOOST_MPL_AUX_MSVC_ETI_BASE_HPP_INCLUDED
[ "muschellij2@gmail.com" ]
muschellij2@gmail.com
5dc2391e034338c0c66c96c23286be6f710b6373
0d11203e6a143b2383b5baa8a9a2b3e48383c9b1
/DSA09013.cpp
5904611bb1f715924663548c2794d75e7975d573
[]
no_license
namnguyen215/CTDLGT
c36b8526b3af00ea2d4bd113efe378f95091f895
6e7e602940fb5c28b7af830f44f58443375b7666
refs/heads/main
2023-06-25T08:48:47.269848
2021-07-21T16:36:36
2021-07-21T16:36:36
360,927,428
2
1
null
null
null
null
UTF-8
C++
false
false
1,421
cpp
#include<bits/stdc++.h> using namespace std; bool chuaxet[1000]; vector<int> ke[1007]; int v,e,v1,v2; void init() { memset(chuaxet,true,sizeof(chuaxet)); for(int i=0;i<=v;i++) { ke[i].clear(); } } bool check() { for(int i=1;i<=v;i++) if(chuaxet[i]==true) return false; return true; } void bfs(int u,int e1,int e2) { queue<int> q; q.push(u); chuaxet[u]=false; while(!q.empty()) { int s=q.front(); q.pop(); for(int i=0;i<ke[s].size();i++) { if((s==e1 && ke[s][i]==e2) || (s==e2 && ke[s][i]==e1)) continue; if(chuaxet[ke[s][i]]) { chuaxet[ke[s][i]]=false; q.push(ke[s][i]); } } } } bool canhcau(int e1,int e2) { memset(chuaxet,true,sizeof(chuaxet)); bfs(1,e1,e2); if(check()) return false; return true; } int main() { int t;cin>>t; while(t--) { init(); cin>>v>>e; for(int i=0;i<e;i++) { cin>>v1>>v2; ke[v1].push_back(v2); ke[v2].push_back(v1); } for(int i=1;i<=v;i++) { for(int j=0;j<ke[i].size();j++) { if(i<ke[i][j] && canhcau(i,ke[i][j])) cout<<i<<" "<<ke[i][j]<<" "; } } cout<<endl; } }
[ "namnguyenphuong215@gmail.com" ]
namnguyenphuong215@gmail.com
8152a463860fefc8329ca739d8b5c4232a2964b6
1f013e822124dfe9b4611f1fe08675a23871566e
/home/mkalbarczyk/z1/kod.cpp
7933d43a94c35c9eea0f16a74714ca40f8187736
[]
no_license
dtraczewski/zpk2014
a1d9a26d25ff174561e3b20c8660901178d827a5
548970bc5a9a02215687cb143d2f3f44307ff252
refs/heads/master
2021-01-21T06:06:32.044028
2015-09-06T12:17:07
2015-09-06T12:17:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
#include <iostream> using namespace std; int main(){ char a; char b; cin>>a>>b; int wynik; int drugi; a=int(a)-48; switch(b){ case 'A': drugi = 10; break; case 'B': drugi = 11; break; case 'C': drugi = 12; break; case 'D': drugi = 13; break; case 'E': drugi = 14; break; case 'F': drugi = 15; break; default: drugi = int(b)-48; break; } wynik = 16*a+drugi; cout<<wynik<<endl<<char(wynik); }
[ "kalbarczykmagda@gmail.com" ]
kalbarczykmagda@gmail.com
977929e9d508af3dd2b864dc9265d022ca67a6ea
317f2542cd92aa527c2e17af5ef609887a298766
/tools/target_10_2_0_1155/qnx6/usr/include/bb/platform/bbm/Context.hpp
11e3bde2b8e188e0c695818667a1f3bea2f11ca9
[]
no_license
sborpo/bb10qnx
ec77f2a96546631dc38b8cc4680c78a1ee09b2a8
33a4b75a3f56806f804c7462d5803b8ab11080f4
refs/heads/master
2020-07-05T06:53:13.352611
2014-12-12T07:39:35
2014-12-12T07:39:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,103
hpp
/*! * * @copyright * Copyright Research In Motion Limited, 2012-2012 * Research In Motion Limited. All rights reserved. */ #ifndef BB_PLATFORM_BBM_CONTEXT_HPP #define BB_PLATFORM_BBM_CONTEXT_HPP #include <bb/platform/bbm/Global> #include <bb/platform/bbm/RegistrationState> #include <QObject> #include <QScopedPointer> #include <QUuid> namespace bb { namespace platform { namespace bbm { class ContextPrivate; /*! * @headerfile Context.hpp <bb/platform/bbm/Context> * * @brief Represents a class that has the necessary context for access to the BBM Social Platform. * * @details Creating a @c Context object initializes the BBM Social Platform for access. * Calling @c requestRegisterApplication() registers your app with the BBM Social Platform. * You can verify if your app has access to the BBM Social Platform by calling @c registrationAccessState(). * @c RegistrationState::Allowed is returned if registration is successful. Once successfully * registered, your app can use the BBM Social Platform APIs. * * @since BlackBerry 10.0.0 * * @xmlonly * <apigrouping group="App Integration/BBM"/> * <library name="bbplatformbbm"/> * @endxmlonly */ class BB_PLATFORM_BBM_EXPORT Context: public QObject { Q_OBJECT public: /*! * @brief Creates a new @c Context object for your app. * The context object provides access to the BBM Social Platform APIs. * * @param applicationUuid The UUID is a unique, 128-bit, 36-character identifier that you generate * for your app using a UUID generator. The UUID string must conform to the Microsoft 8-4-4-4-12 * format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). * Valid characters consist of hexadecimal values in the ranges 0 to 9 and a to f. * A registration dialog may appear in your app after you invoke this function. The dialog * indicates to the user that your app is connecting to BBM. The user must dismiss * the dialog once registration is complete. * * @param parent The @c QObject parent of this @c Context object. * @see @c QUuid * @since BlackBerry 10.0.0 */ explicit Context(const QUuid &applicationUuid = QUuid(), QObject *parent = 0); /*! * @brief Destroys this @c Context object. * @since BlackBerry 10.0.0 */ virtual ~Context(); /*! * @brief Requests registration of your app with the BBM Social Platform. * * @details <p>A progress registration dialog may appear in your * application after you invoke this function. The user can * cancel registration by dismissing the dialog. Once * registration is complete, a system toast may appear indicating to * the user that your application is now connected to BBM. If * registration does not complete successfully, a system dialog may * appear informing the user about the reason for failure.</p> * <p>If BBM is not set up when registration starts, the user may decide * to set up BBM. This action triggers registration to resume. * </p> The signal @c registrationStateUpdated is emitted as an * asynchronous response. * * @return true if sending the request succeeds, false otherwise. * @since BlackBerry 10.0.0 */ Q_SLOT bool requestRegisterApplication(); /*! * @brief Requests registration of your app with the BBM Social Platform. * * @details A UUID is a unique, 128-bit, 36-character identifier that you * generate for your app using a UUID (or GUID) generator. The UUID string must conform to * the Microsoft 8-4-4-4-12 format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). * Valid characters consist of hexadecimal values in the ranges 0 to 9 and a to f. * <p>Registration takes place in "silent" mode so that the registration progress * dialog does not appear to the user after you invoke this function. * Once registration is complete, a system toast appears to indicate to * the user that your application is now connected to BBM. If registration * does not complete successfully, no system dialog is displayed to inform * the user about the reason for failure.</p> * <p>If permission to connect to BBM is not set up when registration starts, * the user may decide to set up BBM. This action will cause registration to resume.</p> * * </p> The signal @c registrationStateUpdated is emitted as an * asynchronous response. * * @return true if sending the request succeeds, false otherwise. * @since BlackBerry 10.2.0 */ Q_SLOT bool requestRegisterApplicationSilent(); /*! * @brief Retrieves the registration state of your app. * @return The registration state, @c RegistrationState::Type. * @since BlackBerry 10.0.0 */ bb::platform::bbm::RegistrationState::Type registrationState() const; /*! * @brief Verifies whether the registration state of your app is @c RegistrationState::Allowed * @return true if the registration state is @c RegistrationState::Allowed, false otherwise. * @since BlackBerry 10.0.0 */ bool isAccessAllowed() const; /*! * @brief Retrieves the version of the BBM Social Platform. * @details The possible versions are: * 200 - the second release of the BBM Social Platform for * BlackBerry 10. Release date: June, 2013. * 100 - the first release of the BBM Social Platform for * BlackBerry 10. Release date: January, 2013. Also, the first * release of the BBM Social Platform for BlackBerry Device Software version * 5, BlackBerry 6, and BlackBerry 7. Release date: October, 2011. * * 120 - release for BlackBerry Device Software version 5, * BlackBerry 6, and BlackBerry 7. Release date: November, 2011. * * 130 - release for BlackBerry Device Software version 5, * BlackBerry 6, and BlackBerry 7. Release date: February, 2012. * You can use the version number to check whether your application is * compatible with this version of the BBM Social Platform. * * @return The curent platform version number. * @since BlackBerry 10.0.0 */ int platformVersion() const; /*! * @brief Determine if BBM is set up on the user's device. * @details Verifies whether the user has completed the set up of * BBM on their device by signing in with their BlackBerry ID * (Setup > BlackBerry Messenger). * * @return true if the BBM is setup, false otherwise. * @since BlackBerry 10.2.0 */ bool isBbmSetup() const; Q_SIGNALS: /*! @brief Emitted when your app's access to the BBM Social Platform is updated. * @details Access to the BBM Social Platform APIs, afforded by the @c Context object, becomes available * only after the registration access state changes to @c RegistrationState::AccessAllowed. * * @param state @c bb::platform::bbm::RegistrationState. * @since BlackBerry 10.0.0 */ void registrationStateUpdated(bb::platform::bbm::RegistrationState::Type state); private: QScopedPointer<ContextPrivate> d_ptr; Q_DECLARE_PRIVATE(Context) Q_DISABLE_COPY(Context) }; } } } #endif /* BB_PLATFORM_BBM_CONTEXT_HPP */
[ "dev@dclark.us" ]
dev@dclark.us
6a3fa5e4413353bb2312bcf760187e5677679c99
07ec6b72a5ff9a7c8c42f6f1213a75cb6ef2719a
/HDOJ/3713.cc
cb5e751c4578a23de5b2bbda003f6e8a09d568db
[]
no_license
cheuk-fung/Programming-Challenges
fbfbf833b19ff1063b0fca4b5d14d1e907264aa1
7c055fd2891b7edc865e7da8886d057a93fb41fe
refs/heads/master
2020-12-24T17:36:21.407367
2020-04-26T19:44:42
2020-04-27T17:13:09
1,443,793
1
1
null
null
null
null
UTF-8
C++
false
false
3,193
cc
/* * SRC: HDOJ 3713 * PROB: Double Maze * ALGO: BFS * DATE: Oct 16, 2011 * COMP: g++ * * Created by Leewings Ac */ #include <cstdio> #include <cstring> #include <string> using std::string; // const int dir[4][2] = { {0, -1}, {1, 0}, {0, 1}, {-1, 0} }; // const char way[4] = { 'L', 'D', 'R', 'U' }; const int dir[4][2] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} }; const char way[4] = { 'D', 'L', 'R', 'U' }; const int wall[4] = { 2, 1, 4, 8 }; int map_1[6][6], map_2[6][6]; struct Status { int x1, y1, x2, y2; int step; string route; bool operator ==(const Status &other) { return x1 == other.x1 && y1 == other.y1 && x2 == other.x2 && y2 == other.y2; } }; Status bfs_q[1000000], final; int vis[6][6][6][6]; void bfs() { memset(vis, 0, sizeof(vis)); Status *q_head = bfs_q, *q_tail = bfs_q; for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) { if (map_1[i][j] & 32) { q_tail->x1 = i; q_tail->y1 = j; } if (map_2[i][j] & 32) { q_tail->x2 = i; q_tail->y2 = j; } if (map_1[i][j] & 64) { final.x1 = i; final.y1 = j; } if (map_2[i][j] & 64) { final.x2 = i; final.y2 = j; } } if (*q_tail == final) { putchar(10); return ; } vis[q_tail->x1][q_tail->y1][q_tail->x2][q_tail->y2] = 1; q_tail->step = 0; q_tail->route = ""; q_tail++; while (q_head != q_tail) { Status curr = *q_head++; int x1 = curr.x1, y1 = curr.y1, x2 = curr.x2, y2 = curr.y2; for (int i = 0; i < 4; i++) { int xx1 = x1, yy1 = y1, xx2 = x2, yy2 = y2; if (!(map_1[x1][y1] & wall[i])) xx1 += dir[i][0], yy1 += dir[i][1]; if (!(map_2[x2][y2] & wall[i])) xx2 += dir[i][0], yy2 += dir[i][1]; if (!(0 <= xx1 && xx1 < 6)) continue; if (!(0 <= yy1 && yy1 < 6)) continue; if (!(0 <= xx2 && xx2 < 6)) continue; if (!(0 <= yy2 && yy2 < 6)) continue; if (!(map_1[xx1][yy1] & 16)) continue; if (!(map_2[xx2][yy2] & 16)) continue; if (vis[xx1][yy1][xx2][yy2]) continue; vis[xx1][yy1][xx2][yy2] = 1; q_tail->x1 = xx1; q_tail->y1 = yy1; q_tail->x2 = xx2; q_tail->y2 = yy2; q_tail->step = curr.step + 1; q_tail->route = curr.route + way[i]; if (*q_tail == final) { printf("%s\n", q_tail->route.c_str()); return ; } q_tail++; } } puts("-1"); } int main() { int n; scanf("%d", &n); for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) scanf("%d", &map_1[i][j]); for (int t = 1; t < n; t++) { for (int i = 0; i < 6; i++) for (int j = 0; j < 6; j++) scanf("%d", &map_2[i][j]); bfs(); memcpy(map_1, map_2, sizeof(map_1)); } return 0; }
[ "osideal@gmail.com" ]
osideal@gmail.com
8d010c7c4d02acc2a7dbe9112857fdb54951557b
ed21e5e773e8594055cfd04378e2ea48c68b7f33
/client/resource/Resource.cpp
9a58b5e0c9596e7c0c9632a4dad673f98ca604a4
[]
no_license
ysei/threed
86baaba40cd0f53760a732bde3bf051941012b52
68f2b2fa09dd80cae1280dbd0965e391e8ba42c1
refs/heads/master
2020-02-26T16:09:19.933935
2013-02-11T10:26:35
2013-02-11T10:26:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
cpp
#include <assert.h> #include <resource/Resource.h> #include <resource/ObjectResource.h> #include <resource/MeshResource.h> #include <resource/ShaderResource.h> #include <resource/TextureResource.h> #include <renderer/RenderResource.h> Resource::Resource(ResourceManager &m, const char *name, enum ResourceType type) : mRefCount(0), mType(type), mName(name), mResourceManager(m), m_RenderResource(0) { } Resource::~Resource() { } int Resource::AddRef() { return mRefCount++; } int Resource::RemoveRef() { if (--mRefCount == 0) { delete this; return 0; } return mRefCount; } Resource *Resource::LoadResource(ResourceManager &m, const char *name, enum ResourceType type) { Resource *r; switch (type) { case RT_OBJECT: r = new ObjectResource(m, name); break; case RT_MESH: r = new MeshResource(m, name); break; case RT_SHADER: r = new ShaderResource(m, name); break; case RT_TEXTURE: r = new TextureResource(m, name); break; default: assert(0); } // pull it from file/network/whatever if (r->LoadFromStorage() < 0) { delete r; assert(0); // for now crash return NULL; } // construct the render resource r->m_RenderResource = RenderResource::CreateRenderResource(r); return r; }
[ "geist@foobox.com" ]
geist@foobox.com
b1d56b2ab72c680c71a008ec6c740f3556033254
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Game/DummyClient/XDummyBot_LevelUp.cpp
e58399f1d35ff467d7ae719ae7a26464caee6186
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,260
cpp
#include "StdAfx.h" #include "XDummyBot_LevelUp.h" #include "XBirdDummyAgent.h" #include "XDummyMaster.h" #include "XDummyLazyCommandPoster.h" #include "XDummyCollision.h" XDummyBot_LevelUp::XDummyBot_LevelUp(XBirdDummyAgent* pAgent, XDummyAgentInfo* pAgentInfo) : XDummyBot(pAgent, pAgentInfo) { } XDummyBot_LevelUp::~XDummyBot_LevelUp(void) { } void XDummyBot_LevelUp::OnRun( float fDelta ) { } minet::MCommandResult XDummyBot_LevelUp::OnCommand( XBirdDummyAgent* pAgent, MCommand* pCommand ) { assert(NULL!=pAgent); assert(NULL!=pCommand); __super::OnCommand(pAgent, pCommand); XBirdClient* pClient = pAgent->GetClient(); assert(NULL!=pClient); switch(pCommand->GetID()) { case MC_CHAR_MYINFO: { TD_MYINFO vecTDMyInfo; if (pCommand->GetSingleBlob(vecTDMyInfo, 0)==false) return CR_FALSE; if(3 != vecTDMyInfo.nPlayerGrade) { XBIRDPOSTCMD2(pClient, MC_GM_SET_ME_REQ, MCommandParameterWideString(L"grade"), MCommandParameterWideString(L"3")); } if (50 != vecTDMyInfo.nLevel) { XBIRDPOSTCMD2(pClient, MC_GM_SET_ME_REQ, MCommandParameterWideString(L"level"), MCommandParameterWideString(L"50")); } pAgent->DelBot(this); break; } } return CR_FALSE; }
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
80abc530f6d830ef3865cef69a929ede1adacbcb
efec853c032df69be4fcd98554d1fa87b90c1c49
/scripts/symmapdisplay.cc
f61e2d949bcbc5a8fbf8854ddf52fbcb8a337042
[]
no_license
cameronc137/remoll_polar
c2723e7d15fd1b5ce34ba778e33aec58a8dd3bcb
13ec5be5991b8eee70230a783b5559a468f270dc
refs/heads/master
2021-01-16T22:22:23.426457
2015-08-28T21:10:18
2015-08-28T21:10:18
39,574,496
0
1
null
2015-07-23T15:21:58
2015-07-23T15:13:50
C++
UTF-8
C++
false
false
5,402
cc
#include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; void symmapdisplay() { // Graphics initialization // TCanvas *cBphi = new TCanvas("cBphi", "",491,189,700,502); cBphi->SetHighLightColor(2); cBphi->Range(-0.8421627,-0.9582822,0.8421627,0.9582822); TView *view = TView::CreateView(1); view->SetRange(-1,-1,-7.367216e-05,801,50,8.970953e-05); cBphi->SetFillColor(0); cBphi->SetBorderMode(0); cBphi->SetBorderSize(2); cBphi->SetTheta(19.17722); cBphi->SetPhi(-10.60345); cBphi->SetFrameBorderMode(0); TCanvas *cBr = new TCanvas("cBr", "",49,52,700,502); cBr->SetHighLightColor(2); cBr->Range(-0.8884543,-1.044525,0.8884543,1.044525); TView *view = TView::CreateView(1); view->SetRange(-1,-1,-0.243346,801,50,5.121616); cBr->SetFillColor(0); cBr->SetBorderMode(0); cBr->SetBorderSize(2); cBr->SetTheta(26.77215); cBr->SetPhi(-15.51724); cBr->SetFrameBorderMode(0); TCanvas *cBz = new TCanvas("cBz", "",401,189,700,502); cBz->SetHighLightColor(2); cBz->Range(-0.8697405,-0.9634467,0.8697405,0.9634467); TView *view = TView::CreateView(1); view->SetRange(-1,-1,0,801,50,8.834574); cBz->SetFillColor(0); cBz->SetBorderMode(0); cBz->SetBorderSize(2); cBz->SetTheta(18.79747); cBz->SetPhi(-13.44828); cBz->SetFrameBorderMode(0); TH2F *hBphi = new TH2F("hBphi","Phi field component",401,-401,400,24,-1,50); TH2F *hBr = new TH2F("hBr","R field component",401,-401,400,24,-1,50); TH2F *hBz = new TH2F("hBz","Z field component",401,-401,400,24,-1,50); // Fill the histograms // float par1, par2, par3, par4, par5, par6; ifstream infile; infile.open("/home/cameronc/gitdir/remoll_polar/Map.dat",ios::in ); if (!infile.is_open()) {cout<< "error, file not opened"<<endl; return 1;} float junk1,junk2,junk3; infile >> junk1 >> junk2 >> junk3; infile >> junk1 >> junk2 >> junk3; infile >> junk1 >> junk2 >> junk3; infile >> junk1 >> junk2; infile >> junk1; infile >> junk1; // R Phi Z B_r B_phi B_z while( infile >> par1 >> par2 >> par3 >> par4 >> par5 >> par6 ){ par1=(par1*500.0); par3=(par3*500.0)+201.8; if (par1==25){ par4=0; par5=0; par6=0; } cout<<par1<<"\t"<<par2<<"\t"<<par3<<"\t"<<par4<<"\t"<<par5<<"\t"<<par6<<endl; if (par2==180){ hBz->SetBinContent(hBz->GetBin((int)par3,(int)par1),par6); hBr->SetBinContent(hBr->GetBin((int)par3,(int)par1),par4); hBphi->SetBinContent(hBphi->GetBin((int)par3,(int)par1),par5); /* if ((par5 < 1e-4) && (par5 > -1e-4)){ hBphi->SetBinContent(hBphi->GetBin((int)par3,(int)par1),par5); } else { hBphi->SetBinContent(hBphi->GetBin((int)par3,(int)par1),0.00); } */ } } infile.close(); // Edit the axis of the plots and print them // // hBz->SetEntries(20852); hBz->SetStats(0); // hBr->SetEntries(20852); hBr->SetStats(0); // hBphi->SetEntries(20852); hBphi->SetStats(0); Int_t ci; ci = TColor::GetColor("#000099"); cBz->cd(); hBz->SetLineColor(ci); hBz->GetXaxis()->SetTitle(" z/mm"); hBz->GetXaxis()->SetLabelFont(42); hBz->GetXaxis()->SetLabelSize(0.035); hBz->GetXaxis()->SetTitleSize(0.035); hBz->GetXaxis()->SetTitleOffset(1.3); hBz->GetXaxis()->SetTitleFont(42); hBz->GetYaxis()->SetTitle(" r/mm"); hBz->GetYaxis()->SetLabelFont(42); hBz->GetYaxis()->SetLabelSize(0.035); hBz->GetYaxis()->SetTitleSize(0.035); hBz->GetYaxis()->SetTitleOffset(1.5); hBz->GetYaxis()->SetTitleFont(42); hBz->GetZaxis()->SetTitle(" B_{z}/T"); hBz->GetZaxis()->SetLabelFont(42); hBz->GetZaxis()->SetLabelSize(0.035); hBz->GetZaxis()->SetTitleSize(0.035); hBz->GetZaxis()->SetTitleFont(42); hBz->Draw("surf1"); cBz->Modified(); cBz->cd(); cBz->SetSelected(cBz); cBz->Print(".symMap.pdf","pdf"); cBr->cd(); hBr->SetLineColor(ci); hBr->GetXaxis()->SetTitle(" z/mm"); hBr->GetXaxis()->SetLabelFont(42); hBr->GetXaxis()->SetLabelSize(0.035); hBr->GetXaxis()->SetTitleSize(0.035); hBr->GetXaxis()->SetTitleOffset(1.3); hBr->GetXaxis()->SetTitleFont(42); hBr->GetYaxis()->SetTitle(" r/mm"); hBr->GetYaxis()->SetLabelFont(42); hBr->GetYaxis()->SetLabelSize(0.035); hBr->GetYaxis()->SetTitleSize(0.035); hBr->GetYaxis()->SetTitleOffset(1.5); hBr->GetYaxis()->SetTitleFont(42); hBr->GetZaxis()->SetTitle(" B_{r}/T"); hBr->GetZaxis()->SetLabelFont(42); hBr->GetZaxis()->SetLabelSize(0.035); hBr->GetZaxis()->SetTitleSize(0.035); hBr->GetZaxis()->SetTitleFont(42); hBr->Draw("surf1"); cBr->Modified(); cBr->cd(); cBr->SetSelected(cBr); cBr->Print(".symMap.pdf","pdf"); cBphi->cd(); hBphi->SetLineColor(ci); hBphi->GetXaxis()->SetTitle(" z/mm"); hBphi->GetXaxis()->SetLabelFont(42); hBphi->GetXaxis()->SetLabelSize(0.035); hBphi->GetXaxis()->SetTitleSize(0.035); hBphi->GetXaxis()->SetTitleOffset(1.3); hBphi->GetXaxis()->SetTitleFont(42); hBphi->GetYaxis()->SetTitle(" r/mm"); hBphi->GetYaxis()->SetLabelFont(42); hBphi->GetYaxis()->SetLabelSize(0.035); hBphi->GetYaxis()->SetTitleSize(0.035); hBphi->GetYaxis()->SetTitleOffset(1.5); hBphi->GetYaxis()->SetTitleFont(42); hBphi->GetZaxis()->SetTitle(" B_{phi}/T"); hBphi->GetZaxis()->SetLabelFont(42); hBphi->GetZaxis()->SetLabelSize(0.035); hBphi->GetZaxis()->SetTitleSize(0.035); hBphi->GetZaxis()->SetTitleFont(42); hBphi->Draw("surf1"); cBphi->Modified(); cBphi->cd(); cBphi->SetSelected(cBphi); cBphi->Print(".symMap.pdf","pdf"); return 0; }
[ "cameronc137@gmail.com" ]
cameronc137@gmail.com
4daf455724eadf71f7ffaefd5b465ff2b1d44f34
4f5d415bebc162328109421e700d23bb9f6ae284
/common/template_bfs.cpp
e578e883710675168ebb364764837f0fd07e6bd7
[]
no_license
lufovic77/AlgorithmStudy
2dc603a6dd6a85b4f180fd1ea6a7ef9f29d23da7
7ffebc9a39c5c84e9f46c31f7f43ee3f47e970b8
refs/heads/master
2021-07-23T21:59:56.846234
2021-06-24T13:20:36
2021-06-24T13:20:36
149,069,013
0
0
null
null
null
null
UTF-8
C++
false
false
300
cpp
#include <iostream> #include <cstdio> #include <cmath> #include <vector> #include <algorithm> #include <limits.h> #include <queue> #define FOR(i,n) for(int i=0;i<n;i++) #define FOR2(i,n) for(int i=1;i<=n;i++) using namespace std; int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, 1, 0, -1}; int main(){ }
[ "lufovic77@gmail.com" ]
lufovic77@gmail.com
622961b5df8362a6842382e934e07e08fd8cd735
679c83d35865be573b23c7929c9b1924005297cd
/Source.cpp
6182bc341a52b63633de93a7732f07ce91e7a595
[]
no_license
soulsama972/overlay
db0e0ee412b48d24cfc2e754fa0aad10caceed4a
233067e2f18d0cbbd5ff0be32758feee01e767ee
refs/heads/master
2022-02-17T20:52:40.380509
2019-10-02T17:01:43
2019-10-02T17:01:43
209,622,796
1
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
#include"Utill.hpp" #include"Hook.h" class Ni2 { public: void Init(); void ShutDown(); private: //listCount Nino2.exe+1280Ec8 uintptr_t listCount = 0; //heal Nino2.exe+11D9E20 //enitiyList heal //0x718 * enityListCOunt + 388 uintptr_t entityListHeal = 0; }; void Ni2::Init() { } void Ni2::ShutDown() { }
[ "michael77700@gmail.com" ]
michael77700@gmail.com
13ba3bbc1ffc76b0078b409938bbdf1cad9eec6d
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-quicksight/source/model/DescribeThemeRequest.cpp
62164497d6e7e614ceab6ab8a3b4fec9cfe54082
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
1,159
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/quicksight/model/DescribeThemeRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::QuickSight::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; DescribeThemeRequest::DescribeThemeRequest() : m_awsAccountIdHasBeenSet(false), m_themeIdHasBeenSet(false), m_versionNumber(0), m_versionNumberHasBeenSet(false), m_aliasNameHasBeenSet(false) { } Aws::String DescribeThemeRequest::SerializePayload() const { return {}; } void DescribeThemeRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_versionNumberHasBeenSet) { ss << m_versionNumber; uri.AddQueryStringParameter("version-number", ss.str()); ss.str(""); } if(m_aliasNameHasBeenSet) { ss << m_aliasName; uri.AddQueryStringParameter("alias-name", ss.str()); ss.str(""); } }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
6157505e46e579a588d13d3c2b12e5bb86818ae5
275fe6dd30c6584a219e66d5342bb2a9621efc71
/select/main.cpp
eba6879ae4c1ee2356902001ea00a3b78f7ed5c3
[]
no_license
heybeachboy/learing-linux-devp
7f119bce51dfdce6628043536d97f17b58d3d42e
612c9a39b232bcabf3f1e3d03c498dcd32aa15ab
refs/heads/master
2020-05-30T20:51:35.788833
2019-06-11T07:23:21
2019-06-11T07:23:21
189,957,839
0
0
null
null
null
null
UTF-8
C++
false
false
5,961
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/select.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <assert.h> #define IPADDR "127.0.0.1" #define PORT 8787 #define MAXLINE 1024 #define LISTENQ 5 #define SIZE 10 typedef struct server_context_st { int cli_cnt; /*客户端个数*/ int clifds[SIZE]; /*客户端的个数*/ fd_set allfds; /*句柄集合*/ int maxfd; /*句柄最大值*/ } server_context_st; static server_context_st *s_srv_ctx = NULL; /*=========================================================================== * ==========================================================================*/ static int create_server_proc(const char* ip,int port) { int fd; struct sockaddr_in servaddr; fd = socket(AF_INET, SOCK_STREAM,0); if (fd == -1) { fprintf(stderr, "create socket fail,erron:%d,reason:%s\n", errno, strerror(errno)); return -1; } /*一个端口释放后会等待两分钟之后才能再被使用,SO_REUSEADDR是让端口释放后立即就可以被再次使用。*/ int reuse = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) { return -1; } bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; inet_pton(AF_INET,ip,&servaddr.sin_addr); servaddr.sin_port = htons(port); if (bind(fd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1) { perror("bind error: "); return -1; } listen(fd,LISTENQ); return fd; } static int accept_client_proc(int srvfd) { struct sockaddr_in cliaddr; socklen_t cliaddrlen; cliaddrlen = sizeof(cliaddr); int clifd = -1; printf("accpet clint proc is called.\n"); ACCEPT: clifd = accept(srvfd,(struct sockaddr*)&cliaddr,&cliaddrlen); if (clifd == -1) { if (errno == EINTR) { goto ACCEPT; } else { fprintf(stderr, "accept fail,error:%s\n", strerror(errno)); return -1; } } fprintf(stdout, "accept a new client: %s:%d\n", inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port); //将新的连接描述符添加到数组中 int i = 0; for (i = 0; i < SIZE; i++) { if (s_srv_ctx->clifds[i] < 0) { s_srv_ctx->clifds[i] = clifd; s_srv_ctx->cli_cnt++; break; } } if (i == SIZE) { fprintf(stderr,"too many clients.\n"); return -1; } } static int handle_client_msg(int fd, char *buf) { assert(buf); printf("recv buf is :%s\n", buf); write(fd, buf, strlen(buf) +1); return 0; } static void recv_client_msg(fd_set *readfds) { int i = 0, n = 0; int clifd; char buf[MAXLINE] = {0}; for (i = 0;i <= s_srv_ctx->cli_cnt;i++) { clifd = s_srv_ctx->clifds[i]; if (clifd < 0) { continue; } /*判断客户端套接字是否有数据*/ if (FD_ISSET(clifd, readfds)) { //接收客户端发送的信息 n = read(clifd, buf, MAXLINE); if (n <= 0) { /*n==0表示读取完成,客户都关闭套接字*/ FD_CLR(clifd, &s_srv_ctx->allfds); close(clifd); s_srv_ctx->clifds[i] = -1; continue; } handle_client_msg(clifd, buf); } } } static void handle_client_proc(int srvfd) { int clifd = -1; int retval = 0; fd_set *readfds = &s_srv_ctx->allfds; struct timeval tv; int i = 0; while (1) { /*每次调用select前都要重新设置文件描述符和时间,因为事件发生后,文件描述符和时间都被内核修改啦*/ FD_ZERO(readfds); /*添加监听套接字*/ FD_SET(srvfd, readfds); s_srv_ctx->maxfd = srvfd; tv.tv_sec = 30; tv.tv_usec = 0; /*添加客户端套接字*/ for (i = 0; i < s_srv_ctx->cli_cnt; i++) { clifd = s_srv_ctx->clifds[i]; /*去除无效的客户端句柄*/ if (clifd != -1) { FD_SET(clifd, readfds); } s_srv_ctx->maxfd = (clifd > s_srv_ctx->maxfd ? clifd : s_srv_ctx->maxfd); } /*开始轮询接收处理服务端和客户端套接字*/ retval = select(s_srv_ctx->maxfd + 1, readfds, NULL, NULL, &tv); if (retval == -1) { fprintf(stderr, "select error:%s.\n", strerror(errno)); return; } if (retval == 0) { fprintf(stdout, "select is timeout.\n"); continue; } if (FD_ISSET(srvfd, readfds)) { /*监听客户端请求*/ accept_client_proc(srvfd); } else { /*接受处理客户端消息*/ recv_client_msg(readfds); } } } static void server_uninit() { if (s_srv_ctx) { free(s_srv_ctx); s_srv_ctx = NULL; } } static int server_init() { s_srv_ctx = (server_context_st *)malloc(sizeof(server_context_st)); if (s_srv_ctx == NULL) { return -1; } memset(s_srv_ctx, 0, sizeof(server_context_st)); int i = 0; for (;i < SIZE; i++) { s_srv_ctx->clifds[i] = -1; } return 0; } int main(int argc,char *argv[]) { int srvfd; /*初始化服务端context*/ if (server_init() < 0) { return -1; } /*创建服务,开始监听客户端请求*/ srvfd = create_server_proc(IPADDR, PORT); if (srvfd < 0) { fprintf(stderr, "socket create or bind fail.\n"); goto err; } /*开始接收并处理客户端请求*/ handle_client_proc(srvfd); server_uninit(); return 0; err: server_uninit(); return -1; }
[ "zhouletian1234@live.com" ]
zhouletian1234@live.com
366e0fa6eb1bc9ad91935ef765e77546f5035da6
632440c7875ef0ba22ce8b6ba122890b2e8648c1
/Renderer.hpp
de51a9f9baaf726ff88f572c0ca1378987ea6a75
[]
no_license
suny-poly-cs-club/DungeonCrawler
06e89a128821e48b47863f74874ef0ba5343c2de
ac371f86c9322c11fecb63440a88496b41866be4
refs/heads/master
2020-04-21T19:16:36.988037
2019-02-22T03:17:05
2019-02-22T03:17:05
169,800,735
1
2
null
2019-02-22T00:15:16
2019-02-08T21:22:26
C++
UTF-8
C++
false
false
229
hpp
#pragma once #include "Shader.hpp" #include <vector> typedef enum { STANDARD }SHADERS; class Renderer { public: Renderer(); ~Renderer(); void createProgram(); std::vector<Shader*> shaders; };
[ "joshm1238@gmail.com" ]
joshm1238@gmail.com
2faee54b48411b41cb9753c006c087f4ea758c1b
93becb0e207e95d75dbb05c92c08c07402bcc492
/atcoder/2020_1_12/f.cpp
d5d4c05c0dcdc5ab14dcc7959fc7d45a480140a0
[]
no_license
veqcc/atcoder
2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed
cc3b30a818ba2f90c4d29c74b4d2231e8bca1903
refs/heads/master
2023-04-14T21:39:29.705256
2023-04-10T02:31:49
2023-04-10T02:31:49
136,691,016
2
0
null
null
null
null
UTF-8
C++
false
false
2,040
cpp
#include <functional> #include <algorithm> #include <iostream> #include <iomanip> #include <cstring> #include <string> #include <vector> #include <random> #include <bitset> #include <queue> #include <cmath> #include <stack> #include <set> #include <map> typedef long long ll; using namespace std; const ll MOD = 1000000007LL; int main() { cin.sync_with_stdio(false); cin.tie(0); cout.tie(0); int n; cin >> n; vector <double> x(n), y(n); for (int i = 0; i < n; i++) cin >> x[i] >> y[i]; double l = 0, r = 1000; while (r - l > 1e-10) { double R = (l + r) / 2; bool ok = false; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { double distance = sqrt((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j])) / 2; if (R < distance) continue; double h = sqrt(R * R - distance * distance); double x_vector = y[j] - y[i]; double y_vector = x[i] - x[j]; double vector_length = sqrt(x_vector * x_vector + y_vector * y_vector); for (int dir = 1; dir > -2; dir -= 2) { double X = (x[i] + x[j]) / 2 + dir * x_vector * h / vector_length; double Y = (y[i] + y[j]) / 2 + dir * y_vector * h / vector_length; bool all_in = true; for (int k = 0; k < n; k++) { if ((X - x[k]) * (X - x[k]) + (Y - y[k]) * (Y - y[k]) > R * R + 1e-8) { all_in = false; break; } } if (all_in) { ok = true; break; } } if (ok) break; } if (ok) break; } if (ok) { r = R; } else { l = R; } } cout << fixed << setprecision(10) << l << "\n"; return 0; }
[ "kambe3141@gmail.com" ]
kambe3141@gmail.com
0f19b8249656b62ece298751e1e84345b7aca301
9dd3c0238b00cd6d1328739a53bfecdf36d02e42
/MiniSQL/MiniSQL/RecordManager.h
6e374ab6f54c605b457407ec6dcc2e677da60565
[]
no_license
MichaelSuen-thePointer/PtrMiniSQLxx
506f847214a218e639dff2ef424f181a29d0bd5a
f69a81ea02b9f63e3a0adf37d86ca8da9f905f0b
refs/heads/master
2021-01-17T17:08:49.299165
2016-06-25T13:09:43
2016-06-25T13:09:43
61,697,685
8
7
null
null
null
null
GB18030
C++
false
false
5,977
h
#pragma once #include "BufferManager.h" class RecordManager { public: class TableRecordList : Uncopyable { friend class RecordManager; friend class std::map<std::string, TableRecordList>; private: using Record = std::pair<uint32_t, uint16_t>; std::string _fileName; std::deque<Record> _records; std::set<Record> _freeRecords; uint16_t _entrySize; Record _nextPos; TableRecordList(const std::string& tableName, std::deque<Record>&& records, std::set<Record>&& freeRecords, uint16_t entrySize, Record nextPos) : _fileName(tableName + "_records") , _records(std::move(records)) , _freeRecords(std::move(freeRecords)) , _entrySize(entrySize) , _nextPos(nextPos) { } public: //构造函数 TableRecordList(TableRecordList&& other) : _fileName(std::move(other._fileName)) , _records(std::move(other._records)) , _freeRecords(std::move(other._freeRecords)) , _entrySize(other._entrySize) , _nextPos(other._nextPos) { } //移动构造 TableRecordList& operator=(TableRecordList&& other) { _fileName = std::move(other._fileName); _records = std::move(other._records); _freeRecords = std::move(other._freeRecords); _entrySize = other._entrySize; _nextPos = other._nextPos; return *this; } //获取record数 size_t size() const { return _records.size(); } //获取条目指针 BlockPtr operator[](size_t index) const { auto& pair = _records[index]; assert((int)pair.second * (int)_entrySize <= std::numeric_limits<uint16_t>::max()); return{BufferManager::instance().check_file_index(_fileName), 0, pair.first, static_cast<uint16_t>(pair.second * _entrySize)}; } //插入条目 BlockPtr insert(byte* buffer) { Record entry; if (_freeRecords.size()) { entry = *_freeRecords.begin(); _freeRecords.erase(_freeRecords.begin()); } else { entry = _nextPos; _nextPos += 1; if ((_nextPos.second + 1) * _entrySize >= BufferBlock::BlockSize) { if (_nextPos.first == std::numeric_limits<uint32_t>::max()) { throw InsuffcientSpace("not enough space for new record"); } _nextPos.first += 1; _nextPos.second = 0; } } auto& block = BufferManager::instance().find_or_alloc(_fileName, 0, entry.first); assert(entry.second * _entrySize + _entrySize < BufferBlock::BlockSize); memcpy(block.raw_ptr() + entry.second * _entrySize, buffer, _entrySize); block.notify_modification(); _records.push_back(entry); return{BufferManager::instance().check_file_index(_fileName), 0, entry.first, static_cast<uint16_t>(entry.second * _entrySize)}; } //删除条目 void erase(size_t i) { assert(i >= 0 && i < _records.size()); auto result = _freeRecords.insert(_records[i]); assert(result.second); _records.erase(_records.begin() + i); } //清空条目 void clear() { _freeRecords.insert(_records.begin(), _records.end()); _records.clear(); } }; const static char* const FileName; /*= "RecordManagerMeta";*/ const static int MaxRecordSize = BufferBlock::BlockSize; ~RecordManager(); private: std::map<std::string, TableRecordList> _tableInfos; RecordManager(); bool table_exists(const std::string& tableName) { return _tableInfos.find(tableName) != _tableInfos.end(); } public: //获取管理器实例 static RecordManager& instance() { static RecordManager instance; return instance; } //删除记录 void drop_record(const std::string& tableName) { _tableInfos.erase(tableName); } //查找表 TableRecordList& find_table(const std::string& tableName) { auto tableInfo = _tableInfos.find(tableName); if (tableInfo == _tableInfos.end()) { throw TableNotExist(tableName.c_str()); } return tableInfo->second; } //插入条目并返回文件指针 BlockPtr insert_entry(const std::string& tableName, byte* entry) { auto& table = find_table(tableName); return table.insert(entry); } //移除条目 void remove_entry(const std::string& tableName, size_t i) { auto& table = find_table(tableName); table.erase(i); } //获取表信息 TableRecordList& operator[](const std::string& tableName) { return find_table(tableName); } //新建表 TableRecordList& create_table(const std::string& tableName, uint16_t entrySize) { if (_tableInfos.size() > std::numeric_limits<uint16_t>::max()) { throw InsuffcientSpace("allows at most 65536 tables"); } if (table_exists(tableName)) { throw TableExist(tableName.c_str()); } auto place = _tableInfos.insert({tableName,TableRecordList{tableName, {}, {}, entrySize, {0,0}}}); return place.first->second; } //移除表 void remove_table(const std::string& tableName) { if (!table_exists(tableName)) { throw TableNotExist(tableName.c_str()); } _tableInfos.erase(tableName); } };
[ "crazy95sun@live.cn" ]
crazy95sun@live.cn
afea07fa985a3439649fff113c4defd0d3d769af
88999f52b8898fc6cbfc6dc63f4f8f6c41941a2a
/zxing/zxing/pdf417/detector/LinesSampler.cpp
39c12f5910768c3bbab0cfd463badf9a72bd835e
[]
no_license
ouyangmland/sscap
6e77b9932998cbac3996cab7fae7815d0753b7f8
6f3dce87aa3bb431287a8a7b6fa20dd261a356a1
refs/heads/master
2020-12-10T03:26:16.194510
2017-06-16T08:59:59
2017-06-16T08:59:59
95,564,487
0
2
null
2017-06-27T14:01:29
2017-06-27T14:01:29
null
UTF-8
C++
false
false
25,150
cpp
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*- /* * Copyright 2010, 2012 ZXing authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <map> #include <zxing/pdf417/detector/LinesSampler.h> #include <zxing/pdf417/decoder/BitMatrixParser.h> #include <zxing/NotFoundException.h> #include <zxing/common/Point.h> #include <algorithm> // vs12, std::min und std:max #include <cmath> using std::map; using std::vector; using std::min; using zxing::pdf417::detector::LinesSampler; using zxing::pdf417::decoder::BitMatrixParser; using zxing::Ref; using zxing::BitMatrix; using zxing::NotFoundException; using zxing::Point; // VC++ using zxing::Line; const int LinesSampler::MODULES_IN_SYMBOL = 17 ; const int LinesSampler::BARS_IN_SYMBOL = 8; const int LinesSampler::POSSIBLE_SYMBOLS= 2787; const int LinesSampler::BARCODE_START_OFFSET = 2; namespace { class VoteResult { private: bool indecisive; int vote; public: VoteResult() : indecisive(false), vote(0) {} bool isIndecisive() { return indecisive; } void setIndecisive(bool indecisive) { this->indecisive = indecisive; } int getVote() { return vote; } void setVote(int vote) { this->vote = vote; } }; VoteResult getValueWithMaxVotes(map<int, int>& votes) { VoteResult result; int maxVotes = 0; for (map<int, int>::iterator i = votes.begin(); i != votes.end(); i++) { if (i->second > maxVotes) { maxVotes = i->second; result.setVote(i->first); result.setIndecisive(false); } else if (i->second == maxVotes) { result.setIndecisive(true); } } return result; } } vector<float> LinesSampler::init_ratios_table() { // Pre-computes and outputs the symbol ratio table. vector<vector<float> > table (BitMatrixParser::SYMBOL_TABLE_LENGTH); for(int i=0; i < (int)table.size(); ++i) { table[i].resize(LinesSampler::BARS_IN_SYMBOL); } vector<float> RATIOS_TABLE (BitMatrixParser::SYMBOL_TABLE_LENGTH * LinesSampler::BARS_IN_SYMBOL); int x = 0; for (int i = 0; i < BitMatrixParser::SYMBOL_TABLE_LENGTH; i++) { int currentSymbol = BitMatrixParser::SYMBOL_TABLE[i]; int currentBit = currentSymbol & 0x1; for (int j = 0; j < BARS_IN_SYMBOL; j++) { float size = 0.0f; while ((currentSymbol & 0x1) == currentBit) { size += 1.0f; currentSymbol >>= 1; } currentBit = currentSymbol & 0x1; table[i][BARS_IN_SYMBOL - j - 1] = size / MODULES_IN_SYMBOL; } for (int j = 0; j < BARS_IN_SYMBOL; j++) { RATIOS_TABLE[x] = table[i][j]; x++; } } return RATIOS_TABLE; } const vector<float> LinesSampler::RATIOS_TABLE = init_ratios_table(); LinesSampler::LinesSampler(Ref<BitMatrix> linesMatrix, int dimension) : linesMatrix_(linesMatrix), dimension_(dimension) {} /** * Samples a grid from a lines matrix. * * @return the potentially decodable bit matrix. */ Ref<BitMatrix> LinesSampler::sample() { const int symbolsPerLine = dimension_ / MODULES_IN_SYMBOL; // XXX vector<float> symbolWidths; computeSymbolWidths(symbolWidths, symbolsPerLine, linesMatrix_); // XXX vector<vector<int> > codewords(linesMatrix_->getHeight()); vector<vector<int> > clusterNumbers(linesMatrix_->getHeight()); linesMatrixToCodewords(clusterNumbers, symbolsPerLine, symbolWidths, linesMatrix_, codewords); // XXX vector<vector<map<int, int> > > votes = distributeVotes(symbolsPerLine, codewords, clusterNumbers); // XXX vector<vector<int> > detectedCodeWords(votes.size()); for (int i = 0; i < (int)votes.size(); i++) { detectedCodeWords[i].resize(votes[i].size(), 0); for (int j = 0; j < (int)votes[i].size(); j++) { if (!votes[i][j].empty()) { detectedCodeWords[i][j] = getValueWithMaxVotes(votes[i][j]).getVote(); } } } // XXX vector<int> insertLinesAt = findMissingLines(symbolsPerLine, detectedCodeWords); // XXX int rowCount = decodeRowCount(symbolsPerLine, detectedCodeWords, insertLinesAt); detectedCodeWords.resize(rowCount); // XXX Ref<BitMatrix> grid(new BitMatrix(dimension_, detectedCodeWords.size())); codewordsToBitMatrix(detectedCodeWords, grid); return grid; } /** * @brief LinesSampler::codewordsToBitMatrix * @param codewords * @param matrix */ void LinesSampler::codewordsToBitMatrix(vector<vector<int> > &codewords, Ref<BitMatrix> &matrix) { for (int i = 0; i < (int)codewords.size(); i++) { for (int j = 0; j < (int)codewords[i].size(); j++) { int moduleOffset = j * MODULES_IN_SYMBOL; for (int k = 0; k < MODULES_IN_SYMBOL; k++) { if ((codewords[i][j] & (1 << (MODULES_IN_SYMBOL - k - 1))) > 0) { matrix->set(moduleOffset + k, i); } } } } } /** * @brief LinesSampler::calculateClusterNumber * @param codeword * @return */ int LinesSampler::calculateClusterNumber(int codeword) { if (codeword == 0) { return -1; } int barNumber = 0; bool blackBar = true; int clusterNumber = 0; for (int i = 0; i < MODULES_IN_SYMBOL; i++) { if ((codeword & (1 << i)) > 0) { if (!blackBar) { blackBar = true; barNumber++; } if (barNumber % 2 == 0) { clusterNumber++; } else { clusterNumber--; } } else { if (blackBar) { blackBar = false; } } } return (clusterNumber + 9) % 9; } //#define OUTPUT_SYMBOL_WIDTH 1 //#define OUTPUT_BAR_WIDTH 1 //#define OUTPUT_CW_STARTS 1 //#define OUTPUT_CLUSTER_NUMBERS 1 //#define OUTPUT_EC_LEVEL 1 void LinesSampler::computeSymbolWidths(vector<float> &symbolWidths, const int symbolsPerLine, Ref<BitMatrix> linesMatrix) { int symbolStart = 0; bool lastWasSymbolStart = true; const float symbolWidth = symbolsPerLine > 0 ? (float)linesMatrix->getWidth() / (float)symbolsPerLine : (float)linesMatrix->getWidth(); // Use the following property of PDF417 barcodes to detect symbols: // Every symbol starts with a black module and every symbol is 17 modules wide, // therefore there have to be columns in the line matrix that are completely composed of black pixels. vector<int> blackCount(linesMatrix->getWidth(), 0); for (int x = BARCODE_START_OFFSET; x < linesMatrix->getWidth(); x++) { for (int y = 0; y < linesMatrix->getHeight(); y++) { if (linesMatrix->get(x, y)) { blackCount[x]++; } } if (blackCount[x] == linesMatrix->getHeight()) { if (!lastWasSymbolStart) { float currentWidth = (float)(x - symbolStart); // Make sure we really found a symbol by asserting a minimal size of 75% of the expected symbol width. // This might break highly distorted barcodes, but fixes an issue with barcodes where there is a // full black column from top to bottom within a symbol. if (currentWidth > 0.75 * symbolWidth) { // The actual symbol width might be slightly bigger than the expected symbol width, // but if we are more than half an expected symbol width bigger, we assume that // we missed one or more symbols and assume that they were the expected symbol width. while (currentWidth > 1.5 * symbolWidth) { symbolWidths.push_back(symbolWidth); currentWidth -= symbolWidth; } symbolWidths.push_back(currentWidth); lastWasSymbolStart = true; symbolStart = x; } } } else { if (lastWasSymbolStart) { lastWasSymbolStart = false; } } } // The last symbol ends at the right edge of the matrix, where there usually is no black bar. float currentWidth = (float)(linesMatrix->getWidth() - symbolStart); while (currentWidth > 1.5 * symbolWidth) { symbolWidths.push_back(symbolWidth); currentWidth -= symbolWidth; } symbolWidths.push_back(currentWidth); #if PDF417_DIAG && OUTPUT_SYMBOL_WIDTH { cout << "symbols per line: " << symbolsPerLine << endl; cout << "symbol width (" << symbolWidths.size() << "): "; for (int i = 0; i < symbolWidths.size(); i++) { cout << symbolWidths[i] << ", "; } cout << endl; } #endif } void LinesSampler::linesMatrixToCodewords(vector<vector<int> >& clusterNumbers, const int symbolsPerLine, const vector<float>& symbolWidths, Ref<BitMatrix> linesMatrix, vector<vector<int> >& codewords) { for (int y = 0; y < linesMatrix->getHeight(); y++) { // Not sure if this is the right way to handle this but avoids an error: if (symbolsPerLine > (int)symbolWidths.size()) { throw NotFoundException("Inconsistent number of symbols in this line."); } // TODO: use symbolWidths.size() instead of symbolsPerLine to at least decode some codewords codewords[y].resize(symbolsPerLine, 0); clusterNumbers[y].resize(symbolsPerLine, -1); int line = y; vector<int> barWidths(1, 0); int barCount = 0; // Runlength encode the bars in the scanned linesMatrix. // We assume that the first bar is black, as determined by the PDF417 standard. bool isSetBar = true; // Filter small white bars at the beginning of the barcode. // Small white bars may occur due to small deviations in scan line sampling. barWidths[0] += BARCODE_START_OFFSET; for (int x = BARCODE_START_OFFSET; x < linesMatrix->getWidth(); x++) { if (linesMatrix->get(x, line)) { if (!isSetBar) { isSetBar = true; barCount++; barWidths.resize(barWidths.size() + 1); } } else { if (isSetBar) { isSetBar = false; barCount++; barWidths.resize(barWidths.size() + 1); } } barWidths[barCount]++; } // Don't forget the last bar. barCount++; barWidths.resize(barWidths.size() + 1); #if PDF417_DIAG && OUTPUT_BAR_WIDTH { for (int i = 0; i < barWidths.size(); i++) { cout << barWidths[i] << ", "; } cout << endl; } #endif ////////////////////////////////////////////////// // Find the symbols in the line by counting bar lengths until we reach symbolWidth. // We make sure, that the last bar of a symbol is always white, as determined by the PDF417 standard. // This helps to reduce the amount of errors done during the symbol recognition. // The symbolWidth usually is not constant over the width of the barcode. int cwWidth = 0; int cwCount = 0; vector<int> cwStarts(symbolsPerLine, 0); cwStarts[0] = 0; cwCount++; for (int i = 0; i < barCount && cwCount < symbolsPerLine; i++) { cwWidth += barWidths[i]; if ((float)cwWidth > symbolWidths[cwCount - 1]) { if ((i % 2) == 1) { // check if bar is white i++; } cwWidth = barWidths[i]; cwStarts[cwCount] = i; cwCount++; } } #if PDF417_DIAG && OUTPUT_CW_STARTS { for (int i = 0; i < cwStarts.size(); i++) { cout << cwStarts[i] << ", "; } cout << endl; } #endif /////////////////////////////////////////// vector<vector<float> > cwRatios(symbolsPerLine); // Distribute bar widths to modules of a codeword. for (int i = 0; i < symbolsPerLine; i++) { cwRatios[i].resize(BARS_IN_SYMBOL, 0.0f); const int cwStart = cwStarts[i]; const int cwEnd = (i == symbolsPerLine - 1) ? barCount : cwStarts[i + 1]; const int cwLength = cwEnd - cwStart; if (cwLength < 7 || cwLength > 9) { // We try to recover smybols with 7 or 9 bars and spaces with heuristics, but everything else is beyond repair. continue; } float cwWidth = 0; // For symbols with 9 bar length simply ignore the last bar. for (int j = 0; j < min(BARS_IN_SYMBOL, cwLength); ++j) { cwWidth += (float)barWidths[cwStart + j]; } // If there were only 7 bars and spaces detected use the following heuristic: // Assume the length of the symbol is symbolWidth and the last (unrecognized) bar uses all remaining space. if (cwLength == 7) { for (int j = 0; j < cwLength; ++j) { cwRatios[i][j] = (float)barWidths[cwStart + j] / symbolWidths[i]; } cwRatios[i][7] = (symbolWidths[i] - cwWidth) / symbolWidths[i]; } else { for (int j = 0; j < (int)cwRatios[i].size(); ++j) { cwRatios[i][j] = (float)barWidths[cwStart + j] / cwWidth; } } float bestMatchError = std::numeric_limits<float>::max(); int bestMatch = 0; // Search for the most possible codeword by comparing the ratios of bar size to symbol width. // The sum of the squared differences is used as similarity metric. // (Picture it as the square euclidian distance in the space of eight tuples where a tuple represents the bar ratios.) for (int j = 0; j < POSSIBLE_SYMBOLS; j++) { float error = 0.0f; for (int k = 0; k < BARS_IN_SYMBOL; k++) { float diff = RATIOS_TABLE[j * BARS_IN_SYMBOL + k] - cwRatios[i][k]; error += diff * diff; if (error >= bestMatchError) { break; } } if (error < bestMatchError) { bestMatchError = error; bestMatch = BitMatrixParser::SYMBOL_TABLE[j]; } } codewords[y][i] = bestMatch; clusterNumbers[y][i] = calculateClusterNumber(bestMatch); } } #if PDF417_DIAG && OUTPUT_CLUSTER_NUMBERS { for (int i = 0; i < clusterNumbers.size(); i++) { for (int j = 0; j < clusterNumbers[i].size(); j++) { cout << clusterNumbers[i][j] << ", "; } cout << endl; } } #endif #if PDF417_DIAG { Ref<BitMatrix> bits(new BitMatrix(symbolsPerLine * MODULES_IN_SYMBOL, codewords.size())); codewordsToBitMatrix(codewords, bits); static int __cnt__ = 0; stringstream ss; ss << "pdf417-detectedRaw" << __cnt__++ << ".png"; bits->writePng(ss.str().c_str(), 8, 16); } #endif } vector<vector<map<int, int> > > LinesSampler::distributeVotes(const int symbolsPerLine, const vector<vector<int> >& codewords, const vector<vector<int> >& clusterNumbers) { // Matrix of votes for codewords which are possible at this position. vector<vector<map<int, int> > > votes(1); votes[0].resize(symbolsPerLine); int currentRow = 0; map<int, int> clusterNumberVotes; int lastLineClusterNumber = -1; for (int y = 0; y < (int)codewords.size(); y++) { // Vote for the most probable cluster number for this row. clusterNumberVotes.clear(); for (int i = 0; i < (int)codewords[y].size(); i++) { if (clusterNumbers[y][i] != -1) { clusterNumberVotes[clusterNumbers[y][i]] = clusterNumberVotes[clusterNumbers[y][i]] + 1; } } // Ignore lines where no codeword could be read. if (!clusterNumberVotes.empty()) { VoteResult voteResult = getValueWithMaxVotes(clusterNumberVotes); bool lineClusterNumberIsIndecisive = voteResult.isIndecisive(); int lineClusterNumber = voteResult.getVote(); // If there are to few votes on the lines cluster number, we keep the old one. // This avoids switching lines because of damaged inter line readings, but // may cause problems for barcodes with four or less rows. if (lineClusterNumberIsIndecisive) { lineClusterNumber = lastLineClusterNumber; } if ((lineClusterNumber != ((lastLineClusterNumber + 3) % 9)) && (lastLineClusterNumber != -1)) { lineClusterNumber = lastLineClusterNumber; } // Ignore broken lines at the beginning of the barcode. if ((lineClusterNumber == 0 && lastLineClusterNumber == -1) || (lastLineClusterNumber != -1)) { if ((lineClusterNumber == ((lastLineClusterNumber + 3) % 9)) && (lastLineClusterNumber != -1)) { currentRow++; if ((int)votes.size() < currentRow + 1) { votes.resize(currentRow + 1); votes[currentRow].resize(symbolsPerLine); } } if ((lineClusterNumber == ((lastLineClusterNumber + 6) % 9)) && (lastLineClusterNumber != -1)) { currentRow += 2; if ((int)votes.size() < currentRow + 1) { votes.resize(currentRow + 1); votes[currentRow].resize(symbolsPerLine); } } for (int i = 0; i < (int)codewords[y].size(); i++) { if (clusterNumbers[y][i] != -1) { if (clusterNumbers[y][i] == lineClusterNumber) { votes[currentRow][i][codewords[y][i]] = votes[currentRow][i][codewords[y][i]] + 1; } else if (clusterNumbers[y][i] == ((lineClusterNumber + 3) % 9)) { if ((int)votes.size() < currentRow + 2) { votes.resize(currentRow + 2); votes[currentRow + 1].resize(symbolsPerLine); } votes[currentRow + 1][i][codewords[y][i]] = votes[currentRow + 1][i][codewords[y][i]] + 1; } else if ((clusterNumbers[y][i] == ((lineClusterNumber + 6) % 9)) && (currentRow > 0)) { votes[currentRow - 1][i][codewords[y][i]] = votes[currentRow - 1][i][codewords[y][i]] + 1; } } } lastLineClusterNumber = lineClusterNumber; } } } return votes; } vector<int> LinesSampler::findMissingLines(const int symbolsPerLine, vector<vector<int> > &detectedCodeWords) { vector<int> insertLinesAt; if (detectedCodeWords.size() > 1) { for (int i = 0; i < (int)detectedCodeWords.size() - 1; i++) { int clusterNumberRow = -1; for (int j = 0; j < (int)detectedCodeWords[i].size() && clusterNumberRow == -1; j++) { int clusterNumber = calculateClusterNumber(detectedCodeWords[i][j]); if (clusterNumber != -1) { clusterNumberRow = clusterNumber; } } if (i == 0) { // The first line must have the cluster number 0. Insert empty lines to match this. if (clusterNumberRow > 0) { insertLinesAt.push_back(0); if (clusterNumberRow > 3) { insertLinesAt.push_back(0); } } } int clusterNumberNextRow = -1; for (int j = 0; j < (int)detectedCodeWords[i + 1].size() && clusterNumberNextRow == -1; j++) { int clusterNumber = calculateClusterNumber(detectedCodeWords[i + 1][j]); if (clusterNumber != -1) { clusterNumberNextRow = clusterNumber; } } if ((clusterNumberRow + 3) % 9 != clusterNumberNextRow && clusterNumberRow != -1 && clusterNumberNextRow != -1) { // The cluster numbers are not consecutive. Insert an empty line between them. insertLinesAt.push_back(i + 1); if (clusterNumberRow == clusterNumberNextRow) { // There may be two lines missing. This is detected when two consecutive lines have the same cluster number. insertLinesAt.push_back(i + 1); } } } } for (int i = 0; i < (int)insertLinesAt.size(); i++) { detectedCodeWords.insert(detectedCodeWords.begin() + insertLinesAt[i] + i, vector<int>(symbolsPerLine, 0)); } return insertLinesAt; } int LinesSampler::decodeRowCount(const int symbolsPerLine, vector<vector<int> > &detectedCodeWords, vector<int> &insertLinesAt) { // Use the information in the first and last column to determin the number of rows and find more missing rows. // For missing rows insert blank space, so the error correction can try to fill them in. map<int, int> rowCountVotes; map<int, int> ecLevelVotes; map<int, int> rowNumberVotes; int lastRowNumber = -1; insertLinesAt.clear(); for (int i = 0; i + 2 < (int)detectedCodeWords.size(); i += 3) { rowNumberVotes.clear(); int firstCodewordDecodedLeft = -1; int secondCodewordDecodedLeft = -1; int thirdCodewordDecodedLeft = -1; int firstCodewordDecodedRight = -1; int secondCodewordDecodedRight = -1; int thirdCodewordDecodedRight = -1; if (detectedCodeWords[i][0] != 0) { firstCodewordDecodedLeft = BitMatrixParser::getCodeword(detectedCodeWords[i][0]); } if (detectedCodeWords[i + 1][0] != 0) { secondCodewordDecodedLeft = BitMatrixParser::getCodeword(detectedCodeWords[i + 1][0]); } if (detectedCodeWords[i + 2][0] != 0) { thirdCodewordDecodedLeft = BitMatrixParser::getCodeword(detectedCodeWords[i + 2][0]); } if (detectedCodeWords[i][detectedCodeWords[i].size() - 1] != 0) { firstCodewordDecodedRight = BitMatrixParser::getCodeword(detectedCodeWords[i][detectedCodeWords[i].size() - 1]); } if (detectedCodeWords[i + 1][detectedCodeWords[i + 1].size() - 1] != 0) { secondCodewordDecodedRight = BitMatrixParser::getCodeword(detectedCodeWords[i + 1][detectedCodeWords[i + 1].size() - 1]); } if (detectedCodeWords[i + 2][detectedCodeWords[i + 2].size() - 1] != 0) { thirdCodewordDecodedRight = BitMatrixParser::getCodeword(detectedCodeWords[i + 2][detectedCodeWords[i + 2].size() - 1]); } if (firstCodewordDecodedLeft != -1 && secondCodewordDecodedLeft != -1) { int leftRowCount = ((firstCodewordDecodedLeft % 30) * 3) + ((secondCodewordDecodedLeft % 30) % 3); int leftECLevel = (secondCodewordDecodedLeft % 30) / 3; rowCountVotes[leftRowCount] = rowCountVotes[leftRowCount] + 1; ecLevelVotes[leftECLevel] = ecLevelVotes[leftECLevel] + 1; } if (secondCodewordDecodedRight != -1 && thirdCodewordDecodedRight != -1) { int rightRowCount = ((secondCodewordDecodedRight % 30) * 3) + ((thirdCodewordDecodedRight % 30) % 3); int rightECLevel = (thirdCodewordDecodedRight % 30) / 3; rowCountVotes[rightRowCount] = rowCountVotes[rightRowCount] + 1; ecLevelVotes[rightECLevel] = ecLevelVotes[rightECLevel] + 1; } if (firstCodewordDecodedLeft != -1) { int rowNumber = firstCodewordDecodedLeft / 30; rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1; } if (secondCodewordDecodedLeft != -1) { int rowNumber = secondCodewordDecodedLeft / 30; rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1; } if (thirdCodewordDecodedLeft != -1) { int rowNumber = thirdCodewordDecodedLeft / 30; rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1; } if (firstCodewordDecodedRight != -1) { int rowNumber = firstCodewordDecodedRight / 30; rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1; } if (secondCodewordDecodedRight != -1) { int rowNumber = secondCodewordDecodedRight / 30; rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1; } if (thirdCodewordDecodedRight != -1) { int rowNumber = thirdCodewordDecodedRight / 30; rowNumberVotes[rowNumber] = rowNumberVotes[rowNumber] + 1; } int rowNumber = getValueWithMaxVotes(rowNumberVotes).getVote(); if (lastRowNumber + 1 < rowNumber) { for (int j = lastRowNumber + 1; j < rowNumber; j++) { insertLinesAt.push_back(i); insertLinesAt.push_back(i); insertLinesAt.push_back(i); } } lastRowNumber = rowNumber; } for (int i = 0; i < (int)insertLinesAt.size(); i++) { detectedCodeWords.insert(detectedCodeWords.begin() + insertLinesAt[i] + i, vector<int>(symbolsPerLine, 0)); } int rowCount = getValueWithMaxVotes(rowCountVotes).getVote(); // int ecLevel = getValueWithMaxVotes(ecLevelVotes); #if PDF417_DIAG && OUTPUT_EC_LEVEL { cout << "EC Level: " << ecLevel << " (" << ((1 << (ecLevel + 1)) - 2) << " EC Codewords)" << endl; } #endif rowCount += 1; return rowCount; } /** * Ends up being a bit faster than Math.round(). This merely rounds its * argument to the nearest int, where x.5 rounds up. */ int LinesSampler::round(float d) { return (int)(d + 0.5f); } Point LinesSampler::intersection(Line a, Line b) { float dxa = a.start.x - a.end.x; float dxb = b.start.x - b.end.x; float dya = a.start.y - a.end.y; float dyb = b.start.y - b.end.y; float p = a.start.x * a.end.y - a.start.y * a.end.x; float q = b.start.x * b.end.y - b.start.y * b.end.x; float denom = dxa * dyb - dya * dxb; if(abs(denom) < 1e-12) // Lines don't intersect (replaces "denom == 0") return Point(std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()); float x = (p * dxb - dxa * q) / denom; float y = (p * dyb - dya * q) / denom; return Point(x, y); }
[ "sockscap64@gmail.com" ]
sockscap64@gmail.com
712f4b3262fc6d4d392385c69d2ee54dcbf4058f
3b1388cfcea18ec095667b81a9700a4946aead1f
/Rook.h
05bee2939aa795d5c9e57f5f4df3f59bd7c305a7
[ "MIT" ]
permissive
tesfaye/15418FinalProject
e9fd7d0dcbea58479fec3a3570649d11662ce21a
9b4f7c0282c656dafeef05855730570fcc5766e1
refs/heads/master
2020-04-03T18:41:02.787875
2018-12-16T19:55:08
2018-12-16T19:55:08
155,493,164
0
0
null
null
null
null
UTF-8
C++
false
false
2,537
h
#include <string> #include <vector> #include "Piece.h" using namespace std; class Rook: public Piece { public: Rook(int player, int row, int col): Piece(player, row, col) { if (player) { this->piece = 'r'; this->value = -50; } else { this->piece = 'R'; this->value = 50; } }; Rook(int player, int row, int col, bool first): Piece(player, row, col) { if (player) { this->piece = 'r'; this->value = -50; } else { this->piece = 'R'; this->value = 50; } this->first = first; }; // creates a deepcopy of the Rook and returns it Rook *deepcopy() { return new Rook(this->player, this->row, this->col, this->first); }; vector<pair<int, int> > find_valid_moves(Piece **board) { Piece *temp; int row, col; int player = this->player; vector<pair<int, int> > coords; // up row = this->row; col = this->col; while (row > 0) { row--; temp = board[INDEX(row, col)]; if (temp != NULL) { if (temp->player != player) coords.push_back(make_pair(row, col)); break; } coords.push_back(make_pair(row, col)); } // down row = this->row; col = this->col; while (row < BOARD_DIM - 1) { row++; temp = board[INDEX(row, col)]; if (temp != NULL) { if (temp->player != player) coords.push_back(make_pair(row, col)); break; } coords.push_back(make_pair(row, col)); } // left row = this->row; col = this->col; while (col > 0) { col--; temp = board[INDEX(row, col)]; if (temp != NULL) { if (temp->player != player) coords.push_back(make_pair(row, col)); break; } coords.push_back(make_pair(row, col)); } // right row = this->row; col = this->col; while (col < BOARD_DIM - 1) { col++; temp = board[INDEX(row, col)]; if (temp != NULL) { if (temp->player != player) coords.push_back(make_pair(row, col)); break; } coords.push_back(make_pair(row, col)); } return coords; }; };
[ "jasonh1@andrew.cmu.edu" ]
jasonh1@andrew.cmu.edu
3f8747e0fb0caaaf35b7f89f2d5f1ce49d8c60c2
f4441767e1d39fc1bc05e09855c079204e4205cd
/Sources/System/ParserCsv.cpp
232f80f1592b5a9090103deb4d20dc9c78afc257
[]
no_license
Caerind/Arthropoda
56d31af4aa1ef20bb8eee24d8e3f86aaf018eade
6a7f43ca2dc9f1274229f5ea8fff09a9cdd7eb40
refs/heads/master
2021-06-15T15:56:15.116594
2017-04-24T21:00:24
2017-04-24T21:00:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
cpp
#include "ParserCsv.hpp" namespace oe { ParserCsv::ParserCsv(const U32 elementsPerLine) : mFilename("") , mElementsPerLine(elementsPerLine) { } ParserCsv::ParserCsv(const U32 elementsPerLine, const std::string& filename) : mFilename("") , mElementsPerLine(elementsPerLine) { loadFromFile(filename); } bool ParserCsv::loadFromFile(const std::string& filename) { IFile file(filename); if (file) { mFilename = filename; std::string line; while (file.read(line)) { std::stringstream ss(line); std::string value; while (std::getline(ss, value, ';')) { ss >> value; addValue(value); } } file.close(); return true; } return false; } bool ParserCsv::saveToFile(const std::string& filename) { OFile file((!filename.empty()) ? filename : mFilename); if (file) { for (U32 i = 0; i < mValues.size(); i++) { if (i != 0 && (i % mElementsPerLine) == 0) { file << '\n'; } file << mValues[i] << ';'; } file.close(); return true; } return false; } void ParserCsv::addValue(const std::string& value) { mValues.emplace_back(value); } void ParserCsv::setValue(U32 index, const std::string& value) { mValues[index] = value; } const std::string& ParserCsv::getValue(U32 index) const { return mValues[index]; } U32 ParserCsv::getSize() const { return mValues.size(); } U32 ParserCsv::getElementsPerLine() const { return mElementsPerLine; } const std::string& ParserCsv::getFilename() const { return mFilename; } } // namespace oe
[ "charles.mailly@free.fr" ]
charles.mailly@free.fr
9add55d58dd20f5a6f5956896db9d1bb981f17f9
4daa512f5005e2d0602db8ebc0f6fb2cbf30ef80
/src/system/physics.cpp
e50e391a04709e7c99e9b22c0b51bddda5f4eb01
[]
no_license
tgloverxi/Alpha-Go-Away
9454e5bc87e9d68419108f30928fe9dc94a72599
ceb614cf0b23225ab70addcdd519d6aed3996235
refs/heads/main
2023-06-04T19:43:42.467601
2021-06-16T21:58:53
2021-06-16T21:58:53
375,256,605
1
0
null
null
null
null
UTF-8
C++
false
false
12,820
cpp
// internal #include "physics.hpp" #include "logger/debug.hpp" namespace { vec2 get_bounding_box(const Position &position) { return {abs(position.scale.x), abs(position.scale.y)}; } bool satHelper(const entt::entity e1, const entt::entity e2) { // if(!(m_registry.has<BoundingBox>(e1) && m_registry.has<BoundingBox>(e2))) return false; BoundingBox bb1 = m_registry.get<BoundingBox>(e1); // bounding box for first entity BoundingBox bb2 = m_registry.get<BoundingBox>(e2); // bounding box for second entity if (bb1.vertices.size() <= 0 || bb2.vertices.size() <= 0) { // all unit entities should have a bounding box return false; } for (int i = 0; i < bb1.transformed_vertices.size(); i++) { auto current = bb1.transformed_vertices[i]; auto next = bb1.transformed_vertices[(i + 1) % bb1.transformed_vertices.size()]; auto edge = next - current; vec2 axis = vec2(-edge.y, edge.x); auto e1MaxProj = NULL; auto e2MaxProj = NULL; auto e1MinProj = NULL; auto e2MinProj = NULL; for (vec2 v : bb1.transformed_vertices) { // project entity 1's bb vertices onto the axis auto projection = dot(axis, v); if (e1MaxProj == NULL || projection > e1MaxProj) { e1MaxProj = projection; } if (e1MinProj == NULL || projection < e1MinProj) { e1MinProj = projection; } } for (vec2 v : bb2.transformed_vertices) { // project entity 2's bb vertices onto the axis auto projection = dot(axis, v); if (e2MaxProj == NULL || projection > e2MaxProj) { e2MaxProj = projection; } if (e2MinProj == NULL || projection < e2MinProj) { e2MinProj = projection; } } if (e1MaxProj < e2MinProj || e1MinProj > e2MaxProj) { return false; } } return true; } bool collides(const entt::entity e1, const entt::entity e2) { bool e1Check = satHelper(e1, e2); bool e2Check = satHelper(e2, e1); return (e1Check && e2Check); } void update_velocity_and_facing_dir(entt::entity entity_i, entt::entity entity_j) { auto &&[position_i, motion_i, property_i] = m_registry.get<Position, Motion, UnitProperty>(entity_i); auto &&[position_j, motion_j] = m_registry.get<Position, Motion>(entity_j); if (property_i.path.size()>0) { std::pair<int, int> nextStep = property_i.path[0]; auto next_tile_center = get_tile_center_from_index(ivec2(nextStep.first, nextStep.second)); if (glm::distance(next_tile_center, position_i.position)<1) { property_i.path.erase(property_i.path.begin()); } vec2 next_position = get_tile_center_from_index(ivec2(nextStep.first, nextStep.second)); motion_i.velocity = glm::normalize(next_position - position_i.position) * unit_speed; }else{ motion_i.velocity *= 0.f; } if (motion_i.velocity.x != 0) { position_i.scale.x = -1 * sign(motion_i.velocity.x) * abs(position_i.scale.x); } else if ((position_j.position - position_i.position).x > 0) { position_i.scale.x = -abs(position_i.scale.x); } else { position_i.scale.x = abs(position_i.scale.x); } } void set_transformed_bounding_box(entt::entity entity) { if (m_registry.has<BoundingBox, Position>(entity)) { auto&&[bb, position] = m_registry.get<BoundingBox, Position>(entity); Transform transform; transform.translate(position.position); transform.rotate(position.angle); transform.scale(position.scale); std::vector<vec2> temp_vector; for (int i = 0; i < bb.vertices.size(); i++) { auto transformed = transform.mat * vec3(bb.vertices[i].x, bb.vertices[i].y, 1.f); temp_vector.emplace_back(transformed.x, transformed.y); bb.transformed_vertices = temp_vector; } } } vec2 get_spos(std::vector<vec2> points, float t) { int p1 = (int)t + 1; int p2 = p1 + 1; int p3 = p2 + 1; int p0 = p1 - 1; float tt = pow(t, 2); float q0 = t * (t - 1.f) * (t - 1.f); float q1 = tt * (2.f * t - 3) + 1.0f; float q2 = -(tt * (2.f * t - 3)); float q3 = tt * (t - 1.f); float tx = (points[p0].x * q0 + points[p1].x * q1 + points[p2].x * q2 + points[p3].x * q3); float ty = (points[p0].y * q0 + points[p1].y * q1 + points[p2].y * q2 + points[p3].y * q3); return{ tx, ty }; } vec2 get_tangent(std::vector<vec2> points, float t) { int p1 = (int)t + 1; int p2 = p1 + 1; int p3 = p2 + 1; int p0 = p1 - 1; float tt = pow(t, 2); float q0 = 3 * tt - 4 * t + 1; float q1 = 6 * tt - 6 * t; float q2 = -6 * tt + 6 * t; float q3 = 3 * tt - 2 * t; float tx = (points[p0].x * q0 + points[p1].x * q1 + points[p2].x * q2 + points[p3].x * q3); float ty = (points[p0].y * q0 + points[p1].y * q1 + points[p2].y * q2 + points[p3].y * q3); return{ tx, ty }; } } bool is_out_of_boundary(entt::entity entity) { auto &&[position, motion] = m_registry.get<Position, Motion>(entity); if (position.position.y < map_y_min) { position.position.y = map_y_min; if (motion.velocity.y < 0) { motion.velocity.y = 0; } return true; } else if (position.position.y > map_y_max) { position.position.y = map_y_max; if (motion.velocity.y > 0) { motion.velocity.y = 0; } return true; } if (position.position.x < map_x_min) { position.position.x = map_x_min; if (motion.velocity.x < 0) { motion.velocity.x = 0; } return true; } else if (position.position.x > map_x_max) { position.position.x = map_x_max; if (motion.velocity.x > 0) { motion.velocity.x = 0; } return true; } return false; } void physics_update(float elapsed_ms) { if (DebugSystem::in_debug_mode) { for (auto&&[entity, boundingBox] :m_registry.view<BoundingBox>().each()) { if (m_registry.valid(entity)) { for (auto &vertices : boundingBox.transformed_vertices) { auto dotSize = vec2(5.f, 5.f); DebugSystem::createLine(vertices, dotSize); } } } } // for (auto &entity: m_registry.view<UnitProperty>()) { // auto &property = m_registry.get<UnitProperty>(entity); // std::cout << "test" << std::endl; // if (property.selected) { // // Mark the selected unit // auto& bb = m_registry.get<BoundingBox>(entity); // for (auto& vertices : bb.transformed_vertices) { // auto dotSize = vec2(5.f, 5.f); // std::cout << "draw" << std::endl; // DebugSystem::createLine(vertices, dotSize); // } // }else if(property.selected_release){ // //draw the moving trajectory // auto &motion= m_registry.get<Motion>(entity); // auto &position = m_registry.get<Position>(entity); // vec2 tri_pos = {(position.position.x-property.init_pos.x)/2+property.init_pos.x, (position.position.y-property.init_pos.y)/2+property.init_pos.y}; // float x1 = position.position.x-property.init_pos.x; // float y1 = position.position.y-property.init_pos.y; // // use dot product to calculate the angle // // vec2 v1 = normalize(vec2({x1, y1})); // // float angle = acos(dot(v1, {1.f, 0.f})); // if (y1 < 0.f) { // //clock wise // angle *= -1.f; // } // if (y1==0){ // // DebugSystem::createDirectTri(tri_pos,{x1/2,30},0.f); // std::cout << "tri" << std::endl; // } else if (x1==0){ // DebugSystem::createDirectTri(tri_pos,{30,y1/2},M_PI/2*y1/abs(y1)); // std::cout << "tri" << std::endl; // }else { // DebugSystem::createDirectTri(tri_pos, {abs((position.position.x-property.init_pos.x)/2),abs((position.position.y-property.init_pos.y)/2)},angle); // std::cout << "tri" << std::endl; // } // property.selected_release = false; // } // } float step_seconds = 1.0f * (elapsed_ms / 1000.f); for (auto&&[entity, motion, position, unit_property, bounding_box]: m_registry.view<Motion, Position, UnitProperty, BoundingBox>().each()) { if (m_registry.valid(unit_property.actualTarget) && m_registry.has<UnitProperty, Motion, Position, BoundingBox>(unit_property.actualTarget) ) { update_velocity_and_facing_dir(entity, unit_property.actualTarget); position.position += motion.velocity * step_seconds; } set_transformed_bounding_box(entity); is_out_of_boundary(entity); //basic health bar vec2 pos = {position.position.x, position.position.y - tile_size.y/2}; //vec2 scale = {unit_property.hp, 5}; float max_hp_bar_length = (tile_size.x-10); vec2 scale = {max_hp_bar_length/unit_property.maxhp * unit_property.hp, 5}; DebugSystem::createLine(vec2(pos.x+(scale.x-max_hp_bar_length)/2, pos.y), scale); } for (auto&&[entity, motion, position, projectile_property]: m_registry.view<Motion, Position, ProjectileProperty>().each()) { if (m_registry.valid(projectile_property.actualTarget)) { auto& target_position = m_registry.get<Position>(projectile_property.actualTarget); if(A_Star::spline){ position.position = get_spos(projectile_property.spoints, projectile_property.t); vec2 tangent = get_tangent(projectile_property.spoints, projectile_property.t); position.angle = atan2(tangent.y,tangent.x); projectile_property.t += 0.02f; }else{ vec2 dir = glm::normalize( target_position.position-position.position); position.angle = atan2(dir.y,dir.x); motion.velocity = glm::normalize(dir) * projectile_speed; position.position += motion.velocity * step_seconds; } set_transformed_bounding_box(entity); if(is_out_of_boundary(entity)){ m_registry.destroy(entity); } if(m_registry.valid(projectile_property.actualTarget) && m_registry.valid(entity) && collides(entity, projectile_property.actualTarget)){ auto& target_prop = m_registry.get<UnitProperty>(projectile_property.actualTarget); target_prop.hp -= projectile_property.damage; if(target_prop.hp<=0){m_registry.destroy(projectile_property.actualTarget);} m_registry.destroy(entity); } }else{ m_registry.destroy(entity); } } } void physics_update_keyframe(float elapsed_ms) { for (auto&& [entity, pos, keyframe] : m_registry.view<Position, KeyFrameMotion>().each()) { vec3 currFrame, nextFrame; unsigned int frame_index = keyframe.currFrame; int next_frame_index = (frame_index == keyframe.keyframes.size() - 1? -1 : frame_index + 1); currFrame = keyframe.keyframes[frame_index]; if (next_frame_index > 0) { // interpolate next position nextFrame = keyframe.keyframes[next_frame_index]; float diff_x = nextFrame.x - currFrame.x; float diff_y = nextFrame.y - currFrame.y; float diff_angle = nextFrame.z - currFrame.z; float time_passed = (keyframe.time_gap - keyframe.time_left)/keyframe.time_gap; if (keyframe.time_left <= 0) { keyframe.time_left = keyframe.time_gap; keyframe.currFrame = next_frame_index; continue; } pos.position.y = time_passed * diff_y + currFrame.y; pos.angle = time_passed * diff_angle + currFrame.z; keyframe.time_left -= elapsed_ms; } else { pos.angle = currFrame.z; pos.position = vec2(currFrame.x, currFrame.y); m_registry.remove<KeyFrameMotion>(entity); } } }
[ "tgloverxi0819@sina.com" ]
tgloverxi0819@sina.com
908a238aca9b876e7c432a966be9d113103fbd67
77b401eb0bc7b07672ca9968a367c58e00c13a5e
/dev_accesss/dev_accesss/include/sql_base.h
bdd5393408667a66305b1aa18c57dd103f6e9c18
[]
no_license
loongson-gz/dev_access
e5e93db7f345362c07bb391d6013bc0cb6c5f7f8
0f471caaa65c1a21f30371456b90ef2056161cc2
refs/heads/master
2021-08-18T01:43:13.371773
2018-09-10T02:21:15
2018-09-10T02:21:15
144,522,762
0
3
null
null
null
null
UTF-8
C++
false
false
259
h
#ifndef __SQL_BASE_H__ #define __SQL_BASE_H__ #include "dev_access_type.h" class SqlBase { public: SqlBase(); virtual ~SqlBase(); virtual int Start() = 0; virtual int Stop() = 0; virtual void SetEventCallback(EventMsgFn fn, void *pUser) {} }; #endif
[ "water0066@qq.com" ]
water0066@qq.com
fd52a54658b10d457d2476c61ae3c9dd935ad960
7a2425190626dd2e75dd6cbca9fe47727afbad42
/src/nstd/new/new.hpp
877523824ae37f5f3bbc455d50b6693948a23c84
[]
no_license
dietmarkuehl/kuhllib
fadd4073c9b09992479e92112ef34c367cb90fad
482ddc2b910870398a9a2bcaa0a77a145e081f78
refs/heads/main
2023-08-31T22:13:02.079530
2023-08-21T22:14:14
2023-08-21T22:14:14
3,148,966
71
7
null
2023-08-21T22:14:15
2012-01-10T21:49:09
C++
UTF-8
C++
false
false
2,040
hpp
// nstd/new/new.hpp -*-C++-*- // ---------------------------------------------------------------------------- // Copyright (C) 2017 Dietmar Kuehl http://www.dietmar-kuehl.de // // 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. // ---------------------------------------------------------------------------- #ifndef INCLUDED_NSTD_NEW_NEW #define INCLUDED_NSTD_NEW_NEW // ---------------------------------------------------------------------------- //-dk:TODO use own implementations! #include <new> // ---------------------------------------------------------------------------- #endif
[ "dietmar.kuehl@me.com" ]
dietmar.kuehl@me.com
d5e5ee25f1746641b41764cff007f0736c36ad13
30f8027f318e604e2c4ed579840d76f33e33368d
/ConsoleApplication0.2.cpp
3ab7796274b94887ff49d1358283fb18630a4a0d
[]
no_license
KOBOSP/large_scale_TSP
4e275eda8b8695e0f9a5ac964338aafcfa654a5e
afd893eceed71fe3f24904ea9a408caedcbef230
refs/heads/master
2023-01-30T14:19:43.237051
2020-12-17T14:04:40
2020-12-17T14:04:40
322,309,063
0
1
null
null
null
null
UTF-8
C++
false
false
17,609
cpp
#include "pch.h" #ifndef GLUT_DISABLE_ATEXIT_HACK #define GLUT_DISABLE_ATEXIT_HACK #endif #define GLEW_STATIC #include <GL/glew.h> #include <GL/wglew.h> #include <GL/freeglut.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> //for matrices #include <glm/gtc/type_ptr.hpp> #include <math.h> #include <algorithm> #include <set> #include<time.h> #include <vector> #include <cstring> #include <iostream> using namespace std; class Vector3D { public: float x; // the x value of this Vector3D float y; // the y value of this Vector3D float z; // the z value of this Vector3D float color = 1.0f; float eps = 1e-8; Vector3D() // Constructor to set x = y = z = 0 { x = 0; y = 0; z = 0; } Vector3D(float x, float y, float z) // Constructor that initializes this Vector3D to the intended values of x, y and z { this->x = x; this->y = y; this->z = z; } Vector3D& operator= (Vector3D v) // operator= sets values of v to this Vector3D. example: v1 = v2 means that values of v2 are set onto v1 { x = v.x; y = v.y; z = v.z; return *this; } Vector3D operator+ (Vector3D v) // operator+ is used to add two Vector3D's. operator+ returns a new Vector3D { return Vector3D(x + v.x, y + v.y, z + v.z); } Vector3D operator- (Vector3D v) // operator- is used to take difference of two Vector3D's. operator- returns a new Vector3D { return Vector3D(x - v.x, y - v.y, z - v.z); } Vector3D operator* (float value) // operator* is used to scale a Vector3D by a value. This value multiplies the Vector3D's x, y and z. { return Vector3D(x * value, y * value, z * value); } Vector3D operator/ (float value) // operator/ is used to scale a Vector3D by a value. This value divides the Vector3D's x, y and z. { return Vector3D(x / value, y / value, z / value); } Vector3D& operator+= (Vector3D v) // operator+= is used to add another Vector3D to this Vector3D. { x += v.x; y += v.y; z += v.z; return *this; } Vector3D& operator-= (Vector3D v) // operator-= is used to subtract another Vector3D from this Vector3D. { x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3D& operator*= (float value) // operator*= is used to scale this Vector3D by a value. { x *= value; y *= value; z *= value; return *this; } Vector3D& operator/= (float value) // operator/= is used to scale this Vector3D by a value. { x /= value; y /= value; z /= value; return *this; } bool operator == (Vector3D value) { if (fabs(x-value.x)<=eps && fabs(y - value.y)<=eps && fabs(z - value.z)<=eps)return true; return false; } Vector3D operator- () // operator- is used to set this Vector3D's x, y, and z to the negative of them. { return Vector3D(-x, -y, -z); } float Length() // length() returns the length of this Vector3D { return sqrtf(x * x + y * y + z * z); }; void Unitize() // unitize() normalizes this Vector3D that its direction remains the same but its length is 1. { float length = this->Length(); if (length == 0) return; x /= length; y /= length; z /= length; } Vector3D Unit() // unit() returns a new Vector3D. The returned value is a unitized version of this Vector3D. { float length = this->Length(); if (length == 0) return *this; return Vector3D(x / length, y / length, z / length); } }; float GetRandomFloat(float low, float up) { if (low > up) { swap(low, up); } float fResult = low + ((up - low) * rand()) / (RAND_MAX + 1); return fResult; } //视角参数 const float PI = acos(-1); float R = 10, hu = 0.0, du = 90, OriX = -1, OriY = -1; //du是视点和x轴的夹角,hu是视点和水平面的夹角,r是视点绕y轴的半径, float C = PI / 180.0; //弧度和角度转换参数 float ViewH = 0;//视点中心高度 int GRID_SIZE = 5; //地板砖边长的一半 int PathDisplayMode = 1; const int CityNum = 10; const int KCityNum = 10; const int K = 3; Vector3D City[CityNum]; Vector3D KCity[KCityNum]; vector<int>PreKc[K]; vector<int>NowKc[K]; float OriginLen, PermuLen, AnnealLen, AntcolonyLen, DPLen; float DP[1 << CityNum][CityNum], PreDP[CityNum][CityNum]; Vector3D Km[K]; int OriginOrder[CityNum]; int DPOrder[CityNum]; int PermuOrder[CityNum]; int AnnealOrder[CityNum]; int AntcolonyOrder[CityNum]; float CalPathDistance(int(&CityOrder)[CityNum]) { float tempLen = 0.0f; for (int i = 0; i < CityNum; i++) { tempLen += (City[CityOrder[i]] - City[CityOrder[(i + 1) % CityNum]]).Length(); } return tempLen; } void OriginShortest() { for (int i = 0; i < CityNum; i++) { OriginOrder[i] = i; } OriginLen = CalPathDistance(OriginOrder); printf("OriginShortest:%f ", OriginLen); for (int i = 0; i < CityNum; i++) { printf("%d ", OriginOrder[i]); } printf("\n"); } void PermutationShortest() { do { float tempLen = CalPathDistance(OriginOrder); if (tempLen < PermuLen) { PermuLen = tempLen; memcpy(PermuOrder, OriginOrder, sizeof(PermuOrder)); } } while (next_permutation(OriginOrder, OriginOrder + CityNum)); printf("PermutationShortest:%f ", PermuLen); for (int i = 0; i < CityNum; i++) { printf("%d ", PermuOrder[i]); } printf("\n"); } void Kmeans() { vector<int>tmp; for (int i = 0; i < K; ++i) tmp.push_back(i); random_shuffle(tmp.begin(), tmp.end()); for (int i = 0; i < K; ++i) Km[i] = KCity[tmp[i]]; while (true) { for (int i = 0; i < KCityNum; ++i) { int center = 0; float minDistance = 0x7fffffff; for (int j = 0; j < K; ++j) { float distance = sqrt((KCity[i].x - Km[j].x) * (KCity[i].x - Km[j].x) + (KCity[i].y - Km[j].y) * (KCity[i].y - Km[j].y) + (KCity[i].z - Km[j].z) * (KCity[i].z - Km[j].z)); if (distance < minDistance) { center = j; minDistance = distance; } } NowKc[center].push_back(i); } for (int i = 0; i < K; ++i) { float mx = 0, my = 0, mz = 0; for (int j = 0; j < NowKc[i].size(); ++j) { mx += KCity[NowKc[i][j]].x; my += KCity[NowKc[i][j]].y; mz += KCity[NowKc[i][j]].z; } Km[i].x = mx / NowKc[i].size(); Km[i].y = my / NowKc[i].size(); Km[i].z = mz / NowKc[i].size(); } int flag = 0; for (int i = 0; i < K; ++i) if (NowKc[i]!=PreKc[i]) { flag = 1; break; } if (!flag) break; for (int i = 0; i < K; ++i) swap(NowKc[i], PreKc[i]); } for (int i = 0; i < K; ++i) { printf("%d:", i); for (int j = 0; j < NowKc[i].size(); ++j) printf("%d ", NowKc[i][j]); printf("\n"); } } void DPShortest() { for (int i = 0; i < CityNum; ++i) for (int j = 0; j < CityNum; ++j) PreDP[i][j] = sqrt((City[i].x - City[j].x) * (City[i].x - City[j].x) + (City[i].y - City[j].y) * (City[i].y - City[j].y) + (City[i].z - City[j].z) * (City[i].z - City[j].z)); for (int i = 0; i < (1 << CityNum); ++i) for (int j = 0; j < CityNum; ++j) DP[i][j] = 1e10; DP[1][0] = 0; for (int i = 0; i < (1 << CityNum); ++i) for (int j = 0; j < CityNum; ++j) if(i>>j&1) for (int k = 0; k < CityNum; ++k) if ((i - (1 << j)) >> k & 1) { DP[i][j] = min(DP[i][j], DP[i - (1 << j)][k]+PreDP[k][j]); } for (int i = 0; i < CityNum; ++i) { if (DPLen > DP[(1 << CityNum) - 1][i]+PreDP[i][0]) { DPLen = DP[(1 << CityNum) - 1][i]+PreDP[i][0]; DPOrder[CityNum-1] = i; } } int BackPath = (1 << CityNum) - 1 - (1 << DPOrder[CityNum-1]); for (int i = CityNum - 2; i > 0; --i) { int len = 1e10; for (int j = CityNum; j > 0 ; --j) { if ((BackPath >> j) & 1 && len > DP[BackPath][j]+PreDP[j][DPOrder[i+1]]) { DPOrder[i] = j; len = DP[BackPath][j]+ PreDP[j][DPOrder[i + 1]]; } } BackPath = BackPath - (1 << DPOrder[i]); } printf("DPShortest:%f ", DPLen); for (int i = 0; i < CityNum; i++) { printf("%d ", DPOrder[i]); } printf("\n"); } void AnnealShortest() { float TperaNow = 1, TperaEnd = 10e-20, CoolRate = 0.99, MaxIter = CityNum*100; for (int i = 0; i < MaxIter; i++) { int ExcPosHe = (int)GetRandomFloat(1, CityNum); int ExcPosTa = (int)GetRandomFloat(1, CityNum); if (ExcPosHe > ExcPosTa) { swap(ExcPosHe , ExcPosTa); } float DeltaLen= (City[AnnealOrder[ExcPosHe-1]] - City[AnnealOrder[ExcPosTa]]).Length(); DeltaLen += (City[AnnealOrder[ExcPosHe]] - City[AnnealOrder[(ExcPosTa+1)%CityNum]]).Length(); DeltaLen -= (City[AnnealOrder[ExcPosHe - 1]] - City[AnnealOrder[ExcPosHe]]).Length(); DeltaLen -= (City[AnnealOrder[ExcPosTa]] - City[AnnealOrder[(ExcPosTa+1) % CityNum]]).Length(); if ((DeltaLen < 0)|| (exp(-1 * DeltaLen / TperaNow)>GetRandomFloat(0, 1))) { for (int i = ExcPosHe, j = ExcPosTa; i < j; i++, j--) { swap(AnnealOrder[i], AnnealOrder[j]); } AnnealLen += DeltaLen; } TperaEnd *= CoolRate; if (TperaNow < TperaEnd) { break; } } printf("AnnealShortest:%f ", AnnealLen); for (int i = 0; i < CityNum; i++) { printf("%d ", AnnealOrder[i]); } printf("\n"); } void AntcolonyShortest() { const int AntNum = CityNum*10,MaxIter= CityNum*10; float InformFact = 1.0f, RandFact = 1.0f, RandVola = 0.2f, perAntInformC = 10; int AntPath[AntNum][CityNum] = { 0 }, InformResi[CityNum][CityNum]; float AntPathLen[AntNum], AntPathLenMin = RAND_MAX * 1.0f; for (int i = 0; i < CityNum; i++) { for (int j = 0; j < CityNum; j++) { InformResi[i][j] = 1.5f; } } for (int i = 0; i < MaxIter; i++) { for (int j = 0; j < AntNum; j++) { vector<int> CityResi; for (int k = 0; k < CityNum; k++) { CityResi.push_back(k); } int CityNowIdx = (int)GetRandomFloat(0, CityNum); AntPath[j][0] = CityResi[CityNowIdx]; CityResi.erase(CityResi.begin() + CityNowIdx); for (int k = 0; k < CityNum-1; k++) { vector<float> CityResiPosib; float PosibSum = 0.0f; for (int m = 0; m < CityResi.size(); m++) { float tmpPosib = pow(InformResi[k][m], InformFact)*pow(1.0f / (City[AntPath[j][k]] - City[CityResi[m]]).Length(), RandFact); PosibSum += tmpPosib; CityResiPosib.push_back(tmpPosib); } float PosibRandGet = GetRandomFloat(0, PosibSum); PosibSum = 0.0f; for (int m = 0; m <CityResi.size(); m++) { PosibSum += CityResiPosib[m]; //printf("%f...%f\n", PosibSum, PosibRandGet); if ((PosibSum > PosibRandGet)||(m== CityResi.size()-1)) { AntPath[j][k + 1] = CityResi[m]; CityResi.erase(CityResi.begin() + m); break; } } } } for (int j = 0; j < AntNum; j++) { AntPathLen[j] = CalPathDistance(AntPath[j]); if (AntPathLen[j] < AntcolonyLen) { AntcolonyLen = AntPathLen[j]; memcpy(AntcolonyOrder, AntPath[j],sizeof(AntcolonyOrder)); } } for (int j = 0; j < CityNum; j++) { for (int k = 0; k < CityNum; k++) { InformResi[j][k] *= (1 - RandVola); } } for (int j = 0; j < AntNum; j++) { for (int k = 0; k < CityNum; k++) { InformResi[AntPath[j][k]][AntPath[j][(k + 1)%CityNum]] += (perAntInformC* (City[AntPath[j][k]] - City[AntPath[j][(k + 1) % CityNum]]).Length() / AntPathLen[j]); } } } printf("AntcolonyShortest:%f ", AntcolonyLen); for (int i = 0; i < CityNum; i++) { printf("%d ", AntcolonyOrder[i]); } printf("\n"); } void Init() { srand(time(0)); for (int i = 0; i < CityNum; i++) { City[i] = Vector3D(GetRandomFloat(-5.0f, 5.0f), GetRandomFloat(0.0f, 5.0f), GetRandomFloat(-5.0f, 5.0f)); printf("City%d %f %f %f\n", i, City[i].x, City[i].y, City[i].z); } for (int i = 0; i < KCityNum; i++) { KCity[i] = Vector3D(GetRandomFloat(-5.0f, 5.0f), GetRandomFloat(0.0f, 5.0f), GetRandomFloat(-5.0f, 5.0f)); } OriginShortest(); AntcolonyLen = RAND_MAX * 1.0f; DPLen = PermuLen = AnnealLen = OriginLen; memcpy(PermuOrder, OriginOrder, sizeof(OriginOrder)); memcpy(AnnealOrder, OriginOrder, sizeof(OriginOrder)); memcpy(AntcolonyOrder, OriginOrder, sizeof(OriginOrder)); Kmeans(); } void DrawGrid() //画地板 { glBegin(GL_LINES); glColor3f(0.5f, 0.5f, 0.5f); for (int i = -GRID_SIZE; i <= GRID_SIZE; i++) { glVertex3f((float)i, 0.0f, (float)-GRID_SIZE); glVertex3f((float)i, 0.0f, (float)GRID_SIZE); glVertex3f((float)-GRID_SIZE, 0.0f, (float)i); glVertex3f((float)GRID_SIZE, 0.0f, (float)i); //glVertex3f((float)GRID_SIZE, 0.0f, (float)i); //glVertex3f((float)GRID_SIZE, GRID_SIZE, (float)i); //glVertex3f((float)-GRID_SIZE, 0.0f, (float)i); //glVertex3f((float)-GRID_SIZE, GRID_SIZE, (float)i); //glVertex3f((float)i, 0.0f, (float)GRID_SIZE); //glVertex3f((float)i, GRID_SIZE, (float)GRID_SIZE); //glVertex3f((float)i, 0.0f, (float)-GRID_SIZE); //glVertex3f((float)i, GRID_SIZE, (float)-GRID_SIZE); } glEnd(); } void DrawCity() { glPointSize(5.0f); glBegin(GL_POINTS); /*for (int i = 0; i < CityNum; i++) { glColor3f(1.0f, 0.0f, 0.0f); if (i == 0 || i == CityNum-1) { glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(City[i].x, City[i].y, City[i].z); continue; } glVertex3f(City[i].x, City[i].y, City[i].z); }*/ for (int i = 0; i < K; ++i) { for (int j = 0; j < NowKc[i].size(); ++j) { glColor3f(KCity[NowKc[i][j]].color / K * (float)(i+1), KCity[NowKc[i][j]].color / K * (float)(i+1), KCity[NowKc[i][j]].color / K * (float)(i+1)); glVertex3f(KCity[NowKc[i][j]].x, KCity[NowKc[i][j]].y, KCity[NowKc[i][j]].z); } } glEnd(); } void DrawPath(int Mode) { glBegin(GL_LINE_STRIP); switch (Mode) { case 1://Origin glColor3f(0.0f, 1.0f, 0.0f); for (int i = 0; i < CityNum; i++) { glVertex3f(City[OriginOrder[i]].x, City[OriginOrder[i]].y, City[OriginOrder[i]].z); } glVertex3f(City[OriginOrder[0]].x, City[OriginOrder[0]].y, City[OriginOrder[0]].z); break; case 2://Permutation glColor3f(0.0f, 1.0f, 0.5f); for (int i = 0; i < CityNum; i++) { glVertex3f(City[PermuOrder[i]].x, City[PermuOrder[i]].y, City[PermuOrder[i]].z); } glVertex3f(City[PermuOrder[0]].x, City[PermuOrder[0]].y, City[PermuOrder[0]].z); break; case 3://Anneal glColor3f(0.0f, 1.0f, 1.0f); for (int i = 0; i < CityNum; i++) { glVertex3f(City[AnnealOrder[i]].x, City[AnnealOrder[i]].y, City[AnnealOrder[i]].z); } glVertex3f(City[AnnealOrder[0]].x, City[AnnealOrder[0]].y, City[AnnealOrder[0]].z); break; case 4://Antcolony glColor3f(0.5f, 1.0f, 0.0f); for (int i = 0; i < CityNum; i++) { glVertex3f(City[AntcolonyOrder[i]].x, City[AntcolonyOrder[i]].y, City[AntcolonyOrder[i]].z); } glVertex3f(City[AntcolonyOrder[0]].x, City[AntcolonyOrder[0]].y, City[AntcolonyOrder[0]].z); break; case 5://DP glColor3f(1.0f, 1.0f, 0.0f); for (int i = 0; i < CityNum; ++i) { glVertex3f(City[DPOrder[i]].x, City[DPOrder[i]].y, City[DPOrder[i]].z); } glVertex3f(City[DPOrder[0]].x, City[DPOrder[0]].y, City[DPOrder[0]].z); break; default: printf("No %d Mode\n", Mode); break; } glEnd(); } void renderScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //清除缓冲,GL_COLOR_BUFFER_BIT :颜色缓冲标志位 glLoadIdentity(); //重置当前矩阵为4*4的单位矩阵 gluLookAt(R * cos(C * du), R * cos(C * hu), R * sin(C * du), 0.0f, ViewH, 0.0, 0.0, 1.0, 0.0); //从视点看远点 DrawGrid(); DrawCity(); //DrawPath(PathDisplayMode); glutSwapBuffers(); //交换两个缓冲区指针 } void onMouseDown(int button, int state, int x, int y) { if (state == GLUT_DOWN) //记录鼠标按下位置 OriX = x, OriY = y; } void onMouseMove(int x, int y) //处理鼠标拖动 { du += (x - OriX); //鼠标在窗口x轴方向上的增量加到视点与x轴的夹角上,就可以左右转 hu += (y - OriY); //鼠标在窗口y轴方向上的改变加到视点y的坐标上,就可以上下转 if (hu > 180) hu = 180; if (hu < -180) hu = -180; OriX = x, OriY = y; //将此时的坐标作为旧值,为下一次计算增量做准备 } void onMouseWheel(int button, int dir, int x, int y)//处理滚轮事件 { dir > 0 ? R++ : R--; R == 0 ? R++ : R = R; } void onSpecialKeys(int key, int x, int y) { switch (key) { case GLUT_KEY_UP: ViewH++; break; case GLUT_KEY_DOWN: ViewH--; break; } } void onKeyBoards(unsigned char key, int x, int y) { switch (key) { case '0': GetRandomFloat(-5, 5); break; case '1': OriginShortest(); PathDisplayMode = 1; break; case '2': PermutationShortest(); PathDisplayMode = 2; break; case '3': AnnealShortest(); PathDisplayMode = 3; break; case '4': AntcolonyShortest(); PathDisplayMode = 4; break; case '5': DPShortest(); PathDisplayMode = 5; break; } } void reshape(int w, int h) { glViewport(0, 0, w, h); //截图;1、2为视口的左下角;3、4为视口的宽度和高度 glMatrixMode(GL_PROJECTION); //将当前矩阵指定为投影矩阵 glLoadIdentity(); gluPerspective(75.0, (float)w / h, 1.0, 1000.0); //1、视野在Y-Z平面的角度[0,180];2、投影平面宽度与高度的比率;3、近截剪面到视点的距离;4、远截剪面到视点的距离 glMatrixMode(GL_MODELVIEW); //对模型视景矩阵堆栈应用随后的矩阵操作. } int main(int argc, char* argv[]) { glutInit(&argc, argv); //初始化glut库 glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); //设置初始显示模式 glEnable(GL_DEPTH_TEST); glutInitWindowSize(1024, 1024); glutCreateWindow("Mass-Spring Model"); Init(); glutReshapeFunc(reshape); glutDisplayFunc(renderScene); glutIdleFunc(renderScene); //设置不断调用显示函数 glutMouseFunc(onMouseDown); glutMotionFunc(onMouseMove); glutMouseWheelFunc(onMouseWheel); glutSpecialFunc(onSpecialKeys); glutKeyboardFunc(onKeyBoards); glutMainLoop();//enters the GLUT event processing loop. return 0; }
[ "kobosptom@gmail.com" ]
kobosptom@gmail.com
769e5ca22314920b61fad1aa9e33627f70f4a3aa
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_SE_DinoSpawnEntriesCanyonCave_classes.hpp
73f2ee0b8987256b0f41478425721d373d1124c9
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
857
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_SE_DinoSpawnEntriesCanyonCave_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass SE_DinoSpawnEntriesCanyonCave.SE_DinoSpawnEntriesCanyonCave_C // 0x0000 (0x0050 - 0x0050) class USE_DinoSpawnEntriesCanyonCave_C : public UNPCSpawnEntriesContainer { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass SE_DinoSpawnEntriesCanyonCave.SE_DinoSpawnEntriesCanyonCave_C"); return ptr; } void ExecuteUbergraph_SE_DinoSpawnEntriesCanyonCave(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
fbc3381077c7a8c6f70e9a9cb7658d7a20d5aa89
48d5dbf4475448f5df6955f418d7c42468d2a165
/SDK/SoT_BP_Anim_Weapondealer_classes.hpp
656be338d1bc130b686cc92390528628a77a25c6
[]
no_license
Outshynd/SoT-SDK-1
80140ba84fe9f2cdfd9a402b868099df4e8b8619
8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4
refs/heads/master
2022-11-21T04:35:29.362290
2020-07-10T14:50:55
2020-07-10T14:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
727
hpp
#pragma once // Sea of Thieves (1.4.16) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_Anim_Weapondealer_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // AnimBlueprintGeneratedClass BP_Anim_Weapondealer.BP_Anim_Weapondealer_C // 0x0000 (0x1975 - 0x1975) class UBP_Anim_Weapondealer_C : public UBP_Anim_NPC_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("AnimBlueprintGeneratedClass BP_Anim_Weapondealer.BP_Anim_Weapondealer_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "53855178+Shat-sky@users.noreply.github.com" ]
53855178+Shat-sky@users.noreply.github.com
a0c94d799c8774af0c846272562aaaf35a55c8e8
b079b31239511c2aa5279697dcd88c8e3ccabbbb
/src/rwth-asr-0.5/src/Flf/GammaCorrection.cc
928bf92a68c8da28352cd1b2ba16139d214dbeb0
[]
no_license
kkromberg/SpeechRecognition
0fe3df4f206e7282b5d06f288e28366d4f146928
9f9f41c01b311b6c55f398ec07a6492a5b6e55b1
refs/heads/master
2021-01-13T05:49:31.147656
2017-01-26T11:32:07
2017-01-26T11:32:07
72,191,492
10
1
null
2016-11-15T22:21:24
2016-10-28T08:58:37
C++
UTF-8
C++
false
false
6,204
cc
// Copyright 2011 RWTH Aachen University. All rights reserved. // // Licensed under the RWTH ASR License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.hltpr.rwth-aachen.de/rwth-asr/rwth-asr-license.html // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Core/Application.hh> #include <Core/Parameter.hh> #include <GammaCorrection.hh> namespace Flf { // ------------------------------------------------------------------------- namespace { f64 gammaCorrectionFunc(const f64 x, const f64 gamma, const f64 brpt = 0.3) { if (x >= 1.0) return 1.0; //const f64 y = 1.0 - ::pow(1.0 - x, gamma); //return (y < 1e-12) ? 1e-12 : y; if (x > brpt) { const f64 m1brpt = 1.0 - brpt; const f64 y = ((1.0 - ::pow(1.0 - ((x - brpt) / m1brpt), gamma)) * m1brpt) + brpt; return (y < 1e-12) ? 1e-12 : y; } else { const f64 y = ::pow(x / brpt, gamma) * brpt; return (y < 1e-12) ? 1e-12 : y; } } } // namespace // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- void gammaCorrection(ConstConfusionNetworkRef cnRef, f64 gamma, bool normalize) { if (!cnRef || (gamma == 1.0)) return; if (!cnRef->isNormalized()) Core::Application::us()->criticalError("Confusion network pruning does only work for normalized CNs."); ConfusionNetwork &cn = const_cast<ConfusionNetwork&>(*cnRef); ScoreId posteriorId = cn.normalizedProperties->posteriorId; verify(posteriorId != Semiring::InvalidId); for (ConfusionNetwork::iterator itSlot = cn.begin(), endSlot = cn.end(); itSlot != endSlot; ++itSlot) { ConfusionNetwork::Slot &slot = *itSlot; Score sum = 0.0; for (ConfusionNetwork::Slot::iterator itArc = slot.begin(), endArc = slot.end(); itArc != endArc; ++itArc) { Score &score = (*itArc->scores)[posteriorId]; score = gammaCorrectionFunc(f64(score), gamma); sum += score; } if (normalize) { const Score norm = 1.0 / sum; for (ConfusionNetwork::Slot::iterator itArc = slot.begin(), endArc = slot.end(); itArc != endArc; ++itArc) { Score &score = (*itArc->scores)[posteriorId]; score *= norm; } } } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- void gammaCorrection(ConstPosteriorCnRef cnRef, f64 gamma, bool normalize) { if (!cnRef || (gamma == 1.0)) return; PosteriorCn &cn = const_cast<PosteriorCn&>(*cnRef); for (PosteriorCn::iterator itSlot = cn.begin(), endSlot = cn.end(); itSlot != endSlot; ++itSlot) { PosteriorCn::Slot &slot = *itSlot; Probability sum = 0.0; for (PosteriorCn::Slot::iterator itArc = slot.begin(), endArc = slot.end(); itArc != endArc; ++itArc) { Probability &score = itArc->score; score = gammaCorrectionFunc(f64(score), gamma); sum += score; } if (normalize) { const Probability norm = 1.0 / sum; for (PosteriorCn::Slot::iterator itArc = slot.begin(), endArc = slot.end(); itArc != endArc; ++itArc) { Probability &score = itArc->score; score *= norm; } } } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- class CnGammaCorrectionNode : public Node { typedef Node Precursor; public: static const Core::ParameterFloat paramGamma; static const Core::ParameterBool paramNormalize; protected: f64 gamma_; bool normalize_; public: CnGammaCorrectionNode(const std::string &name, const Core::Configuration &config) : Node(name, config) {} virtual ~CnGammaCorrectionNode() {} virtual void init(const std::vector<std::string> &arguments) { gamma_ = paramGamma(config); // verify(gamma_ > 0.0); if (gamma_ < 1e-6) gamma_ = 1e-6; normalize_ = paramNormalize(config); Core::Component::Message msg = log(); msg << "gamma=" << gamma_ << "\n"; if (normalize_) msg << "Re-normalize gamma corrected probability distribution\n"; } }; const Core::ParameterFloat CnGammaCorrectionNode::paramGamma( "gamma", "gamma", 1.0); const Core::ParameterBool CnGammaCorrectionNode::paramNormalize( "normalize", "normalize", true); class NormalizedCnGammaCorrectionNode : public CnGammaCorrectionNode { typedef CnGammaCorrectionNode Precursor; public: NormalizedCnGammaCorrectionNode(const std::string &name, const Core::Configuration &config) : Precursor(name, config) {} virtual ~NormalizedCnGammaCorrectionNode() {} virtual ConstConfusionNetworkRef sendCn(Port to) { verify(connected(to)); ConstConfusionNetworkRef cn = requestCn(to); if (cn) gammaCorrection(cn, gamma_); return cn; } }; NodeRef createNormalizedCnGammaCorrectionNode(const std::string &name, const Core::Configuration &config) { return NodeRef(new NormalizedCnGammaCorrectionNode(name, config)); } class PosteriorCnGammaCorrectionNode : public CnGammaCorrectionNode { typedef CnGammaCorrectionNode Precursor; public: PosteriorCnGammaCorrectionNode(const std::string &name, const Core::Configuration &config) : Precursor(name, config) {} virtual ~PosteriorCnGammaCorrectionNode() {} virtual ConstPosteriorCnRef sendPosteriorCn(Port to) { verify(connected(to)); ConstPosteriorCnRef cn = requestPosteriorCn(to); if (cn) gammaCorrection(cn, gamma_); return cn; } }; NodeRef createPosteriorCnGammaCorrectionNode(const std::string &name, const Core::Configuration &config) { return NodeRef(new PosteriorCnGammaCorrectionNode(name, config)); } // ------------------------------------------------------------------------- } // namespace Flf
[ "prak3@i6.informatik.rwth-aachen.de" ]
prak3@i6.informatik.rwth-aachen.de
b63da5fe873fa665a8c751875986779212601f94
4090aed9b69d1e355b40a6db6a138f34353197a0
/a1paper.cpp
dd86b26c074a97830acbf28a64d5a5e695254ea2
[]
no_license
HongyuHe/OJ
0ecb72c4a87ac8ac5dc90210be0fbd71c6843f64
f8713ed4e374fdbc783c7c683020a1c23f42b3ad
refs/heads/master
2020-03-31T17:14:30.991344
2018-10-10T01:17:27
2018-10-10T01:17:27
152,414,016
1
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
#include <iostream> #include <vector> #include <cmath> using namespace std; typedef long long ll; typedef long double ld; int main() { ll n; cin >> n; n--; vector<ll> v(n); for(auto& i : v) { cin >> i; } ld totalcost = 0; ll needed = 1; bool enough = false; ld longedge = pow(2.0, -3/4.0); ld shortedge = pow(2.0, -5/4.0); for(ll i = 0; i < v.size(); i++) { // Calculate cost here totalcost += needed * longedge; swap(shortedge, longedge); shortedge /= 2; // Calculate paper needed now needed *= 2; needed -= v[i]; // Check if we have enough paper if(needed <= 0) { enough = true; break; } } cout << fixed; cout.precision(9); if(enough) { cout << totalcost << endl; } else { cout << "impossible" << endl; } }
[ "mikepf97@gmail.com" ]
mikepf97@gmail.com
047595cd080269c134aabbc0c683b21ddbfa584f
cf56f8f1f71fe848eac264a354dc0122bda9e2f2
/trees/check_sum_tree.cpp
20ae8e8e196d1bfccb5c42e726dcfa17e1d53cfa
[]
no_license
sakshi018/Data-structures-
b38948c2e82f729b896aa71e392ae3a610bd9980
8245aec48dc6880e5f99f33067c696ded4104ab2
refs/heads/master
2020-05-18T09:00:38.226847
2016-01-23T17:21:46
2016-01-23T17:21:46
40,308,241
1
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
#include <iostream> using namespace std; struct node { node *left; node *right; int data; }; int checksumtree(node *root) { int node_left=0; int node_right = 0; if(root == NULL || (root->left==NULL && root->right==NULL)) return 1; else { if(root->left!=NULL) node_left=root->left->data; if(root->right!=NULL) node_right=root->right->data; if((root->data= node_left + node_right) && checksumtree(root->left) && checksumtree(root->right)) return 1; else return 0; } } node* newNode(int data) { node *nnode = new node; nnode->data = data; nnode->left = NULL; nnode->right = NULL; return nnode; } /* Driver program to test above function */ int main() { node *root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); if(checksumtree(root)) cout<<"The given tree satisfies the children sum property "; else cout<<"The given tree does not satisfy the children sum property "; return 0; }
[ "shaks018@gmail.com" ]
shaks018@gmail.com
b52ce09d3ff022d3d6b9ba8343663c622574f3aa
2cc63e61904c0b821b88687cbc7c20f4ffeb28cb
/2160 - Nome no Formulário.cpp
320ed0eaac705e5f3d7f61a383f38994822296a7
[]
no_license
lawrencesilva/URI
47557fbb007ccbfb00150d2cd503e8ab9bd0973a
1db51a14e7072099351e205abb691b191fb7d681
refs/heads/master
2020-03-24T02:08:58.630761
2018-07-26T11:12:00
2018-07-26T11:12:00
142,364,470
0
0
null
null
null
null
UTF-8
C++
false
false
322
cpp
#include <iostream> #include <cmath> #include <string> #include <iomanip> using namespace std; int main() { string nome; int contador; getline(cin, nome); for(contador = 0; nome [contador] != '\0'; contador++) { } if(contador > 80) cout << "NO" << endl; else cout << "YES" << endl; return 0; }
[ "lawrencedowow@hotmail.com" ]
lawrencedowow@hotmail.com
e4bc41f39b16241113b84c00bbea8ef06958f3a5
871bda8a9cdf206ea6d174066303c0c3220bb9cf
/various/code_sketches/lecture10-20/mine_tq.cpp
7336467e78b455c92fcd0522c45db67aee0cf3ac
[]
no_license
lapotolo/CompetitiveProgramming
d14b05064ae7961c80fb76b18006f68fe3264c4b
d99135f78dafd01190103a52c6e147ab6cf42a04
refs/heads/master
2021-06-15T21:30:44.575795
2019-10-23T21:04:56
2019-10-23T21:04:56
104,220,660
1
0
null
null
null
null
UTF-8
C++
false
false
3,439
cpp
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> #include <cmath> struct node { uint32_t value; std::vector<size_t> children; size_t index_flat; bool visited; }; struct flat_node { uint32_t value; size_t size; }; struct query { uint32_t val; size_t start; size_t end; size_t index; }; std::vector<node> test; std::vector<query> queries; std::unordered_map<uint32_t, uint32_t> map_cnt; std::unordered_map<uint32_t, uint32_t> map_res; uint32_t res[100001]; size_t sqn; size_t index_flat = 0; size_t build_all(node& n ,std::vector<flat_node>& tree) { if (n.visited) return 0; n.visited = true; tree.emplace_back(flat_node {n.value, 1}); flat_node& node = tree.back(); n.index_flat = index_flat; index_flat++; for (auto c : n.children) node.size += build_all(test[c], tree); return node.size; } void add_node(uint32_t val) { map_cnt[val]++; map_res[map_cnt[val]]++; } void remove_node(uint32_t val) { map_res[map_cnt[val]]--; map_cnt[val]--; } void solve(std::vector<flat_node> const& tree) { size_t last_start = 0; size_t last_stop = 0; for (auto q : queries) { size_t start = q.start; size_t stop = q.end; while (last_start < start) { //remove elements currently not included remove_node(tree[last_start].value); last_start++; } while (last_start > start) { //add elements previously not included add_node(tree[--last_start].value); } while (last_stop < stop) { //add elements previously not included add_node(tree[last_stop].value); last_stop++; } while (stop < last_stop) { //remove elements currently not included remove_node(tree[--last_stop].value); } res[q.index] = map_res[q.val]; } } int main() { std::ios_base::sync_with_stdio(false); std::size_t n, m, l, r; uint32_t val; std::cin >> n >> m; test.reserve(n); queries.reserve(m); sqn = (size_t) (std::sqrt(n) + 1); for (size_t i=0; i<n; ++i) { std::cin >> val; test.emplace_back(node {val, {}, 0, false}); } for (size_t i=1; i<n; ++i) { //n-1 lines std::cin >> l >> r; //l and r go from 1 to n --l; --r; test[l].children.push_back(r); test[r].children.push_back(l); } std::vector<flat_node> tree; tree.reserve(n); build_all(test[0], tree); for(int i = 0; i < tree.size(); ++i){ std::cout << "node= " << i+1 << " -> (color="<< tree[i].value << ", rootedtreesize=" << tree[i].size << ") \n"; } for (size_t i=0; i<m; ++i){ std::cin >> l >> val; //l goes from 1 to n --l; size_t start = test[l].index_flat; queries.emplace_back(query {val, start, start + tree[start].size, i}); } std::sort(queries.begin(), queries.end(), [](query const& a, query const& b) -> bool { if (a.start/sqn != b.start/sqn) return a.start/sqn < b.start/sqn; return (a.end < b.end); }); solve(tree); for (size_t j=0; j<m; ++j) std::cout << res[j] << "\n"; return 0; }
[ "lapotoloni@gmail.com" ]
lapotoloni@gmail.com
1bddcd57fccd2127d2cba048a740a599d1b77725
4f03a0ece8252f78ed946ea2b34f62726d6fc76a
/0063_字符串中第一个只出现一次的字符/main.cpp
b0889c1b311ec579ab8c79d18bc88c1c482df93f
[]
no_license
torresng/CodingSolutions
a3b404f7719dcc89396a13ca4ad56fbb1af325fe
57f4014b6fc28fb9f4b8f3166a2fe68390f03ba5
refs/heads/master
2020-06-12T17:39:05.904473
2020-04-27T03:42:55
2020-04-27T03:42:55
194,375,010
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
class Solution { public: char firstNotRepeatingChar(string s) { unordered_map<char, int> count; for (auto c : s) { count[c]++; } char res = '#'; for (auto c : s) { if (count[c] == 1) { res = c; break; } } return res; } };
[ "torresng2684cte@gmail.com" ]
torresng2684cte@gmail.com
55f825c78d07845b388499dede1bacc1e693ae05
96f8fb7fb764026ede7e927d8b4768b8b6f44abb
/01_Code/07_C++/07_C++/day02/10ref.cpp
7620153370f60fce313e1e286e4360948b1e3292
[]
no_license
isongbo/MyCode
a513beaa8f43bc751aab5217314615c728ba771e
eb2330b1dbae9032ba5ad8ccd65b68375219e451
refs/heads/master
2021-01-10T09:48:53.587674
2016-01-15T10:21:04
2016-01-15T10:21:04
49,700,737
2
1
null
null
null
null
UTF-8
C++
false
false
337
cpp
#include <iostream> using namespace std; int main(){ int var_i=9527; int& ri=var_i; cout << &var_i << endl; cout << &ri << endl; ri=9528; cout << var_i << endl; /* 为var_i 再起一个别名 */ int& rri=ri; rri=9529; cout << var_i << endl; int y=100; /* 把y的值赋值给rri 不是rri引用y */ rri=y; }
[ "syt-aini@126.com" ]
syt-aini@126.com
82b7c058c2e7cfbc8ac5c25c4902f367b3485bd4
97a4b1b863f488a943c9b6f7803ed23ecd1440ef
/alice_torso_module/src/alice_torso_module.cpp
29e3192030bf6a807bbe31b79853ca5aed5da3ad
[]
no_license
roscore/hsc_motion
2d28f645536900a59117843edc7892daef5dc517
d1e34793b068515b508d414877c01f337cc4cd72
refs/heads/main
2023-05-30T20:27:09.751136
2021-06-23T05:46:27
2021-06-23T05:46:27
379,492,714
0
0
null
null
null
null
UTF-8
C++
false
false
31,090
cpp
/* * alice_torso_module.cpp * * Created on: Aug 7, 2020 * Author: heroehs */ #include <stdio.h> #include <cmath> #include "alice_torso_module/alice_torso_module.h" using namespace alice; TorsoModule::TorsoModule() : control_cycle_msec_(8) { running_ = false; enable_ = false; gazebo_check = false; module_name_ = "torso_module"; control_mode_ = robotis_framework::PositionControl; readIDData(); // Dynamixel initialize //// if(alice_id_ == "3") { result_["head_yaw"] = new robotis_framework::DynamixelState(); // joint 13 result_["head_pitch"] = new robotis_framework::DynamixelState(); // joint 14 result_["waist_yaw"] = new robotis_framework::DynamixelState(); // joint 9 } else if(alice_id_ == "2") { result_["head_yaw"] = new robotis_framework::DynamixelState(); // joint 13 result_["head_pitch"] = new robotis_framework::DynamixelState(); // joint 14 } else if(alice_id_ == "1") { result_["head_yaw"] = new robotis_framework::DynamixelState(); // joint 13 result_["head_pitch"] = new robotis_framework::DynamixelState(); // joint 14 result_["waist_yaw"] = new robotis_framework::DynamixelState(); // joint 9 } else ROS_WARN("Unknown Alice ID!!!"); //init new_count_ = 1; is_moving_state = false; mode_ = 7; pre_mode_ = 7; search_phase = 0; /* motion */ // search_phase : 1 search_motion[0][0] = 0.523599; // Degree -> 30 search_motion[0][1] = 0.785398; // Degree -> 45 // search_phase : 2 search_motion[1][0] = 0.523599; // Degree -> 30 search_motion[1][1] = -0.785398; // Degree -> 45 // search_phase : 3 search_motion[2][0] = 0.523599; // Degree -> 20 search_motion[2][1] = 0.0; // search_phase : 4 search_motion[3][0] = 0.872665; // Degree -> 20 search_motion[3][1] = 0.0; // search_phase : 5 search_motion[4][0] = 0.872665; // Degree -> 20 search_motion[4][1] = 0.0; // search_phase : 6 search_motion[5][0] = 0.523599; // Degree -> 20 search_motion[5][1] = 0.0; motion_bias = 0.0349066; // Degree -> 2 max_limit_[0]=45; // 20 //max_limit_[1]=40; // 40 //max_limit_[2]=30; error_[0] = 0; error_[1] = 0; error_[2] = 0; min_p_gain[0] = 0.15; min_p_gain[1] = 0.15; min_p_gain[2] = 0.15; max_p_gain[0] = 0.3; max_p_gain[1] = 0.3; max_p_gain[2] = 0.2; // head pitch max_error_[0] = 0.872665; min_error_[0] = 0; // head yaw max_error_[1] = 0.698132; min_error_[1] = 0; // waist yaw max_error_[2] = 1.5708; min_error_[2] = 0; mapped_error_[0] = min_p_gain[0]; mapped_error_[1] = min_p_gain[1]; mapped_error_[2] = min_p_gain[2]; joint_name_to_id_.clear(); joint_id_to_name_.clear(); joint_name_to_curr_pose_.clear(); // Manual joint_id_to_rad_.clear(); // Tracking joint_name_to_goal_pose_.clear(); // Searching joint_name_to_ini_pose_state_.clear(); joint_name_to_ini_pose_goal_.clear(); //joint_name_to_check_.clear(); motion_phase_init = false; max_boxsize_ = 0; min_boxsize_ = 0; x_resolution = 1280; y_resolution = 720; x_origin = x_resolution/2; y_origin = y_resolution/2; roi_x_offset=0; roi_y_offset=0; roi_height=0; roi_width=0; y, pre_y, pre_x = 0; ts = 0.001; } TorsoModule::~TorsoModule() { queue_thread_.join(); } void TorsoModule::initialize(const int control_cycle_msec, robotis_framework::Robot *robot) { control_cycle_msec_ = control_cycle_msec; queue_thread_ = boost::thread(boost::bind(&TorsoModule::queueThread, this)); for (std::map<std::string, robotis_framework::Dynamixel*>::iterator it = robot->dxls_.begin(); it != robot->dxls_.end(); it++) { std::string joint_name = it->first; robotis_framework::Dynamixel* dxl_info = it->second; joint_name_to_id_[joint_name] = dxl_info->id_; joint_id_to_name_[dxl_info->id_] = joint_name; joint_id_to_rad_[dxl_info->id_] = 0; dxl_pidcontroller[joint_name] = new PIDController(); //for manual dxl_pidcontroller[joint_name]->PID_set_gains(0.12,0,0); } motion_trajectory[joint_id_to_name_[7]] = new alice::FifthOrderTrajectory(); motion_trajectory[joint_id_to_name_[8]] = new alice::FifthOrderTrajectory(); mov_time_state = 2.0; dxl_pidcontroller[joint_id_to_name_[7]]->PID_set_gains(0.25,0,0.00); //0.0015 dxl_pidcontroller[joint_id_to_name_[8]]->PID_set_gains(0.15,0,0.00); //202007 기준 0.1,0,0.00 + dxl_init.yaml 에서 P gain -> 2배로 증가시킴 if(alice_id_ == "3" || alice_id_ == "1") { dxl_pidcontroller[joint_id_to_name_[9]]->PID_set_gains(0.1,0,0); motion_trajectory[joint_id_to_name_[9]] = new alice::FifthOrderTrajectory(); } ROS_INFO("< ------- Initialize Module : Torso Module !! ------->"); } void TorsoModule::torsomodeCallback(const std_msgs::Int32::ConstPtr& msg) { ROS_INFO("=================================\n"); pre_mode_ = mode_; if(msg->data == 0) { mode_ = 0; if(pre_mode_ != 0) { new_count_ = 1; is_moving_state = false; ROS_INFO(" Auto Mode\n"); } } else if(msg->data == 1) { mode_ = 1; if(pre_mode_ != 1) { new_count_ = 1; is_moving_state = false; ROS_INFO(" Manual Mode\n"); } } else if(msg->data == 2) { mode_ = 2; if((pre_mode_ != 2) || (search_phase == 0)) { new_count_ = 1; search_phase = 1; is_moving_state = false; motion_phase_init = true; ROS_INFO(" Searching Mode\n"); } } else if(msg->data == 3) { mode_ = 3; if(pre_mode_ != 3) { new_count_ = 1; is_moving_state = false; ROS_INFO(" Tracking Mode\n"); } } else if(msg->data == 4) { mode_ = 4; new_count_ = 1; is_moving_state = false; ROS_INFO(" Scan Mode\n"); } else if(msg->data == 5) { mode_ = 5; if((pre_mode_ != 5) || (search_phase == 0)) { new_count_ = 1; search_phase = 5; is_moving_state = false; motion_phase_init = true; ROS_INFO(" Ball_check Mode\n"); } } else if(msg->data == 6) { mode_ = 6; if(pre_mode_ != 6) { new_count_ = 1; is_moving_state = false; ROS_INFO(" Torso Module :: STOP !!\n"); } } } void TorsoModule::manualMovingCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) { if(mode_ != 1) { return; } joint_id_to_rad_[7] = DEG2RAD_(msg->data[0]); joint_id_to_rad_[8] = DEG2RAD_(msg->data[1]); //ROS_INFO("joint_angle(7) : %f", joint_id_to_rad_[7]); //ROS_INFO("joint_angle(8) : %f", joint_id_to_rad_[8]); if(joint_id_to_rad_[7]>DEG2RAD_(50)) { joint_id_to_rad_[7]=DEG2RAD_(50); } else if(joint_id_to_rad_[7]<-DEG2RAD_(10)) { joint_id_to_rad_[7]=-DEG2RAD_(10); } if(joint_id_to_rad_[8]>DEG2RAD_(45)) { joint_id_to_rad_[8]=DEG2RAD_(45); } else if(joint_id_to_rad_[8]<-DEG2RAD_(45)) { joint_id_to_rad_[8]=-DEG2RAD_(45); } if(alice_id_ == "3") { if(joint_id_to_rad_[9]>DEG2RAD_(45)) { joint_id_to_rad_[9]=DEG2RAD_(45); } else if(joint_id_to_rad_[9]<-DEG2RAD_(45)) { joint_id_to_rad_[9]=-DEG2RAD_(45); } } //ROS_INFO("-----------------------------------\n"); //ROS_INFO("receive rad\n"); //ROS_INFO("ID 7 Value : %f \n", joint_id_to_rad_[7]); //ROS_INFO("ID 8 Value : %f \n", joint_id_to_rad_[8]); if(alice_id_ == "3" || alice_id_ == "1") { //ROS_INFO("ID 9 Value : %f \n", joint_id_to_rad_[9]); } is_moving_state=true; } int TorsoModule::error_calculate(int origin_point, int object_point) { return (object_point - origin_point); } void TorsoModule::desiredPoseHeadMsgCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) { is_moving_head_ = true; } void TorsoModule::detectedObjectsMsgCallback(const alice_msgs::FoundObjectArray::ConstPtr& msg) { bool inner_flag = false; double error_yaw; double error_pitch; if(mode_ == 3) inner_flag = true; // tracking if(!inner_flag) { return; } for(int i = 0; i < msg->length; i++) { if(!msg->data[i].name.compare("ball")) { current_x = msg->data[i].roi.x_offset + msg->data[i].roi.width/2; current_y = msg->data[i].roi.y_offset + msg->data[i].roi.height/2; ball_detected = 1; break; } } if(ball_detected) { // 추가한 부분 //x_origin = 640 - RAD2DEG_(joint_name_to_curr_pose_[joint_id_to_name_[8]]) * 9; // -45~45 || 21.3 -> 30 ~ -30 || 14.2 -> 30 ~ -30 || 14.2 //y_origin = 360 + RAD2DEG_(joint_name_to_curr_pose_[joint_id_to_name_[7]]) * 4; // -18~18 || 20 -> 80 ~ -10 || 20 -> 65 ~ -25 || 20 x_origin = 640; // Zed Cam's Resolution y_origin = 360; // Zed Cam's Resolution error_yaw = DEG2RAD_(error_calculate(x_origin,current_x)/14.2); error_pitch = DEG2RAD_(error_calculate(y_origin,current_y)/12); //ROS_INFO("current_x : %f\n", current_x); //ROS_INFO("current_y : %f\n", current_y); //ROS_INFO("curr_pos_y : %f\n", RAD2DEG_(joint_name_to_curr_pose_[joint_id_to_name_[8]]) * 14.2); //ROS_INFO("curr_pos_p : %f\n", RAD2DEG_(joint_name_to_curr_pose_[joint_id_to_name_[7]]) * 20); //ROS_INFO("x_origin : %d\n", x_origin); //ROS_INFO("y_origin : %d\n", y_origin); //ROS_INFO("error_yaw : %d\n", error_calculate(x_origin,current_x)); //ROS_INFO("error_pitch : %d\n", error_calculate(y_origin,current_y)); update_state = false; } else { error_yaw = 0; error_pitch = 0; update_state = false; } joint_id_to_rad_[8]=joint_name_to_curr_pose_[joint_id_to_name_[8]]-error_yaw; joint_id_to_rad_[7]=joint_name_to_curr_pose_[joint_id_to_name_[7]]+error_pitch; if(joint_id_to_rad_[7]>DEG2RAD_(-abs(joint_id_to_rad_[8])*0.44+60)) { joint_id_to_rad_[7]= -abs(joint_id_to_rad_[8])*0.44+60; } else if(joint_id_to_rad_[7]<-DEG2RAD_(10)) { joint_id_to_rad_[7]=-DEG2RAD_(10); } if(joint_id_to_rad_[8]>DEG2RAD_(45)) { joint_id_to_rad_[8]=DEG2RAD_(45); } else if(joint_id_to_rad_[8]<-DEG2RAD_(45)) { joint_id_to_rad_[8]=-DEG2RAD_(45); } //ROS_INFO("%f", joint_id_to_rad_[8]); is_moving_state=true; } void TorsoModule::environmentDetectorMsgCallback(const alice_msgs::FoundObjectArray::ConstPtr& msg) { /* int data_cnt = 0; for(int i = 0; i < msg->length; i++) { if(!msg->data[i].name.compare("goal")) { data_cnt ++; current_goal_x = msg->data[i].pos.x; current_goal_y = msg->data[i].pos.y; } if(!msg->data[i].name.compare("center")) { data_cnt ++; current_center_x = msg->data[i].pos.x; current_center_y = msg->data[i].pos.y; } } if(data_cnt == 2) { double theta_center = 0; double theta_goal = 0; double length_center = 0; double length_goal = 0; double sin_robot = 0; double cos_robot = 0; if(current_center_x != 0 && current_goal_x != 0) { theta_center = fabs(atan2(current_center_y,current_center_x)); theta_goal = fabs(atan2(current_goal_y, current_goal_x)); length_center = sqrt(pow(current_center_x,2) + pow(current_center_y,2)); length_goal = sqrt(pow(current_goal_x,2) + pow(current_goal_y,2)); sin_robot = (length_goal * sin(theta_center + theta_goal)) / 4.5; cos_robot = sqrt(1-pow(sin_robot,2)); current_robot_x = length_center*sin_robot; current_robot_y = length_center*cos_robot; int sign_x = 1; int sign_y = 1; if((current_goal_y - current_center_y) < 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) < 0) //case 1 { sign_x = 1; sign_y = 1; } else if((current_goal_y - current_center_y) < 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) > 0) { sign_x = -1; sign_y = 1; } else if((current_goal_y - current_center_y) > 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) > 0) { sign_x = -1; sign_y = -1; } else if((current_goal_y - current_center_y) > 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) < 0) { sign_x = 1; sign_y = -1; } current_robot_x = current_robot_x * sign_x; current_robot_y = current_robot_y * sign_y; if((current_goal_x - current_center_x) != 0) current_robot_theta = atan2((current_goal_y - current_center_y), (current_goal_x - current_goal_x)); else { if((current_goal_y - current_center_y) > 0) current_robot_theta = 90*DEGREE2RADIAN; else if((current_goal_y - current_center_y) < 0) current_robot_theta = 270*DEGREE2RADIAN; else current_robot_theta = 0; } } else { current_center_x = 0.01; current_goal_x = 0.01; theta_center = fabs(atan2(current_center_y,current_center_x)); theta_goal = fabs(atan2(current_goal_y, current_goal_x)); length_center = sqrt(pow(current_center_x,2) + pow(current_center_y,2)); length_goal = sqrt(pow(current_goal_x,2) + pow(current_goal_y,2)); sin_robot = (length_goal * sin(theta_center + theta_goal)) / 4.5; cos_robot = sqrt(1-pow(sin_robot,2)); current_robot_x = length_center*sin_robot; current_robot_y = length_center*cos_robot; int sign_x = 1; int sign_y = 1; if((current_goal_y - current_center_y) < 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) < 0) //case 1 { sign_x = 1; sign_y = 1; } else if((current_goal_y - current_center_y) < 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) > 0) { sign_x = -1; sign_y = 1; } else if((current_goal_y - current_center_y) > 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) > 0) { sign_x = -1; sign_y = -1; } else if((current_goal_y - current_center_y) > 0 && (pow(length_goal,2) - pow(length_center,2) - pow(4.5,2)) < 0) { sign_x = 1; sign_y = -1; } current_robot_x = current_robot_x * sign_x; current_robot_y = current_robot_y * sign_y; if((current_goal_x - current_center_x) != 0) current_robot_theta = atan2((current_goal_y - current_center_y), (current_goal_x - current_goal_x)); else { if((current_goal_y - current_center_y) > 0) current_robot_theta = 90*DEGREE2RADIAN; else if((current_goal_y - current_center_y) < 0) current_robot_theta = 270*DEGREE2RADIAN; else current_robot_theta = 0; } } } data_cnt = 0; robot_state_msg.x = current_robot_x; robot_state_msg.y = current_robot_y; robot_state_msg.z = current_robot_theta; robot_state_pub.publish(robot_state_msg); */ } void TorsoModule::headMovingMsgCallback(const diagnostic_msgs::KeyValue::ConstPtr& msg) { pre_mode_ = mode_; if(msg->key == "head_tracking") //head tracking { mode_ = 3; if(pre_mode_ != 3) { new_count_ = 1; is_moving_state = false; ROS_INFO(" Tracking Mode\n"); } } else if(msg->key == "head_searching") //head search { mode_ = 2; if((pre_mode_ != 2) || (search_phase == 0)) { new_count_ = 1; search_phase = 1; is_moving_state = false; motion_phase_init = true; ROS_INFO(" Searching Mode\n"); } } else if(msg->key == "head_ball_check") //head ball check { mode_ = 5; if((pre_mode_ != 5) || (search_phase == 0)) { new_count_ = 1; search_phase = 5; is_moving_state = false; motion_phase_init = true; ROS_INFO(" Ball_check Mode\n"); } } else if(msg->key == "head_stop") //head stop { mode_ = 6; if(pre_mode_ != 6) { new_count_ = 1; is_moving_state = false; ROS_INFO(" Torso Module :: STOP !!\n"); } } } //test void TorsoModule::ballTestMsgCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) { current_x = msg->data[0]; current_y = msg->data[1]; } void TorsoModule::scanCallback(const std_msgs::Bool::ConstPtr& msg) { } void TorsoModule::ballTestParamMsgCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) { } void TorsoModule::desiredPoseWaistMsgCallback(const std_msgs::Float64MultiArray::ConstPtr& msg) { // Test } void TorsoModule::walkingModuleStatusMsgCallback(const robotis_controller_msgs::StatusMsg::ConstPtr& msg) { } void TorsoModule::readIDData() { ros::NodeHandle nh; int alice_id_int = nh.param<int>("alice_userid",0); //ROS_INFO("Base id: %d",alice_id_int); std::stringstream alice_id_stream; alice_id_stream << alice_id_int; alice_id_ = alice_id_stream.str(); } void TorsoModule::queueThread() { ros::NodeHandle ros_node; ros::CallbackQueue callback_queue; ros_node.setCallbackQueue(&callback_queue); /* subscribe topics */ // for gui ros::Subscriber head_manual_sub = ros_node.subscribe("/heroehs/alice/torso_mode", 5, &TorsoModule::torsomodeCallback, this); ros::Subscriber manual_moving_sub = ros_node.subscribe("heroehs/alice/manual/torso_desired_point", 5 ,&TorsoModule::manualMovingCallback, this); head_moving_sub = ros_node.subscribe("/alice/head_command", 5, &TorsoModule::headMovingMsgCallback, this); scan_cmd_sub = ros_node.subscribe("/heroehs/alice/scan_cmd", 1, &TorsoModule::scanCallback, this); environment_detector_sub = ros_node.subscribe("/heroehs/environment_detector", 5, &TorsoModule::environmentDetectorMsgCallback, this); detected_objects_sub = ros_node.subscribe("/alice/vision/detected_objects", 5, &TorsoModule::detectedObjectsMsgCallback, this); // test desired pose head_test = ros_node.subscribe("/desired_pose_head", 5, &TorsoModule::desiredPoseHeadMsgCallback, this); waist_test = ros_node.subscribe("/desired_pose_waist", 5, &TorsoModule::desiredPoseWaistMsgCallback, this); //test ball //ball_test_sub = ros_node.subscribe("/ball_test", 5, &TorsoModule::ballTestMsgCallback, this); ball_param_sub = ros_node.subscribe("/ball_param", 5, &TorsoModule::ballTestParamMsgCallback, this); //walking status walking_module_status_sub = ros_node.subscribe("/heroehs/status", 10, &TorsoModule::walkingModuleStatusMsgCallback, this); /* publish topics */ scan_done_pub = ros_node.advertise<std_msgs::Bool>("/heroehs/alice/scan_done", 1); robot_state_pub = ros_node.advertise<geometry_msgs::Vector3>("/heroehs/alice/robot_state", 1); ros::WallDuration duration(control_cycle_msec_ / 1000.0); while(ros_node.ok()) callback_queue.callAvailable(duration); } bool TorsoModule::isRunning() { return running_; } void TorsoModule::process(std::map<std::string, robotis_framework::Dynamixel *> dxls, std::map<std::string, double> sensors) { if (enable_ == false) { return; } if(new_count_ == 1) { update_state = true; new_count_++; if(alice_id_ == "2") { for(int i=7; i<9;i++) { result_[joint_id_to_name_[i]]->goal_position_=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; joint_name_to_curr_pose_[joint_id_to_name_[i]]=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; joint_id_to_rad_[joint_name_to_id_[joint_id_to_name_[i]]]=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; } } else if(alice_id_ == "3") { for(int i=7; i<10;i++) { result_[joint_id_to_name_[i]]->goal_position_=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; joint_name_to_curr_pose_[joint_id_to_name_[i]]=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; joint_id_to_rad_[joint_name_to_id_[joint_id_to_name_[i]]]=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; } } } if(is_moving_state==true && mode_== 1) // manual mode { if(alice_id_ == "2") { for(int i=7; i<9;i++) { joint_name_to_curr_pose_[joint_id_to_name_[i]] = dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; // PID gain 변경 error_[i-7] = joint_id_to_rad_[i] - joint_name_to_curr_pose_[joint_id_to_name_[i]]; if(abs(error_[i-7]) < min_error_[i-7]) error_[i-7] = min_error_[i-7]; if(abs(error_[i-7]) > max_error_[i-7]) error_[i-7] = max_error_[i-7]; if(abs(error_[i-7]) > (max_error_[i-7] / 3)) mapped_error_[i-7] = max_p_gain[i-7] - (abs(error_[i-7]) / (max_error_[i-7] -min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) + min_p_gain[i-7]); else mapped_error_[i-7] = (abs(error_[i-7]) - min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) / (max_error_[i-7] - min_error_[i-7]) + min_p_gain[i-7]; //ROS_INFO("curr_pose : %f des_pos : %f error %f", joint_name_to_curr_pose_[joint_id_to_name_[i]], joint_id_to_rad_[i], error_[i-7]); //mapped_error_[i-7] = max_p_gain[i-7] - ((abs(error_[i-7]) - min_error_[i-7]) * (min_p_gain[i-7] - 0) / (max_error_[i-7] - min_error_[i-7]) + 0); mapped_error_[i-7] = max_p_gain[i-7] - (abs(error_[i-7]) / (max_error_[i-7] -min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) + min_p_gain[i-7]); if(mapped_error_[i-7] > max_p_gain[i-7]) mapped_error_[i-7] = max_p_gain[i-7]; if(mapped_error_[i-7] < min_p_gain[i-7]) mapped_error_[i-7] = min_p_gain[i-7]; //ROS_INFO("error: %f mapped_error: %f", abs(error_[0]), mapped_error_[0]); dxl_pidcontroller[joint_id_to_name_[i]]->PID_set_gains(mapped_error_[i-7],0,0.00); result_[joint_id_to_name_[i]]->goal_position_=joint_name_to_curr_pose_[joint_id_to_name_[i]] + dxl_pidcontroller[joint_id_to_name_[i]]->PID_process(joint_id_to_rad_[i],joint_name_to_curr_pose_[joint_id_to_name_[i]]); //printf("id: %d=> %f | ",i,result_[joint_id_to_name_[i]]->goal_position_); } //printf("\n"); } else if(alice_id_ == "3") { for(int i=7; i<9;i++) { joint_name_to_curr_pose_[joint_id_to_name_[i]] = dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; // PID gain 변경 error_[i-7] = joint_id_to_rad_[i] - joint_name_to_curr_pose_[joint_id_to_name_[i]]; if(abs(error_[i-7]) < min_error_[i-7]) error_[i-7] = min_error_[i-7]; if(abs(error_[i-7]) > max_error_[i-7]) error_[i-7] = max_error_[i-7]; if(abs(error_[i-7]) > (max_error_[i-7] / 3)) mapped_error_[i-7] = max_p_gain[i-7] - (abs(error_[i-7]) / (max_error_[i-7] -min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) + min_p_gain[i-7]); else mapped_error_[i-7] = (abs(error_[i-7]) - min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) / (max_error_[i-7] - min_error_[i-7]) + min_p_gain[i-7]; //ROS_INFO("curr_pose : %f des_pos : %f error %f", joint_name_to_curr_pose_[joint_id_to_name_[i]], joint_id_to_rad_[i], error_[i-7]); //mapped_error_[i-7] = max_p_gain[i-7] - ((abs(error_[i-7]) - min_error_[i-7]) * (min_p_gain[i-7] - 0) / (max_error_[i-7] - min_error_[i-7]) + 0); mapped_error_[i-7] = max_p_gain[i-7] - (abs(error_[i-7]) / (max_error_[i-7] -min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) + min_p_gain[i-7]); if(mapped_error_[i-7] > max_p_gain[i-7]) mapped_error_[i-7] = max_p_gain[i-7]; if(mapped_error_[i-7] < min_p_gain[i-7]) mapped_error_[i-7] = min_p_gain[i-7]; //ROS_INFO("error: %f mapped_error: %f", abs(error_[0]), mapped_error_[0]); dxl_pidcontroller[joint_id_to_name_[i]]->PID_set_gains(mapped_error_[i-7],0,0.00); result_[joint_id_to_name_[i]]->goal_position_=joint_name_to_curr_pose_[joint_id_to_name_[i]] + dxl_pidcontroller[joint_id_to_name_[i]]->PID_process(joint_id_to_rad_[i],joint_name_to_curr_pose_[joint_id_to_name_[i]]); //printf("id: %d=> %f | ",i,result_[joint_id_to_name_[i]]->goal_position_); } //printf("\n"); } } else if(is_moving_state==true && mode_== 3) // tracking mode { if(alice_id_ == "2") { for(int i=7; i<9;i++) { joint_name_to_curr_pose_[joint_id_to_name_[i]]=dxls[joint_id_to_name_[i]]->dxl_state_->present_position_; /* // PID gain 변경 error_[i-7] = joint_id_to_rad_[i] - joint_name_to_curr_pose_[joint_id_to_name_[i]]; if(abs(error_[i-7]) < min_error_[i-7]) error_[i-7] = min_error_[i-7]; if(abs(error_[i-7]) > max_error_[i-7]) error_[i-7] = max_error_[i-7]; if(abs(error_[i-7]) > (max_error_[i-7] / 3)) mapped_error_[i-7] = max_p_gain[i-7] - (abs(error_[i-7]) / (max_error_[i-7] -min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) + min_p_gain[i-7]); else mapped_error_[i-7] = (abs(error_[i-7]) - min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) / (max_error_[i-7] - min_error_[i-7]) + min_p_gain[i-7]; //ROS_INFO("curr_pose : %f des_pos : %f error %f", joint_name_to_curr_pose_[joint_id_to_name_[i]], joint_id_to_rad_[i], error_[i-7]); //mapped_error_[i-7] = max_p_gain[i-7] - ((abs(error_[i-7]) - min_error_[i-7]) * (min_p_gain[i-7] - 0) / (max_error_[i-7] - min_error_[i-7]) + 0); mapped_error_[i-7] = max_p_gain[i-7] - (abs(error_[i-7]) / (max_error_[i-7] -min_error_[i-7]) * (max_p_gain[i-7] - min_p_gain[i-7]) + min_p_gain[i-7]/2); if(mapped_error_[i-7] > max_p_gain[i-7]) mapped_error_[i-7] = max_p_gain[i-7]; if(mapped_error_[i-7] < min_p_gain[i-7]) mapped_error_[i-7] = min_p_gain[i-7]; //ROS_INFO("error: %f mapped_error: %f", abs(error_[0]), mapped_error_[0]); dxl_pidcontroller[joint_id_to_name_[i]]->PID_set_gains(mapped_error_[i-7],0,0.00); */ result_[joint_id_to_name_[i]]->goal_position_=joint_name_to_curr_pose_[joint_id_to_name_[i]] + dxl_pidcontroller[joint_id_to_name_[i]]->PID_process(joint_id_to_rad_[i],joint_name_to_curr_pose_[joint_id_to_name_[i]]); update_state = true; } } } else if(mode_== 2) // searching mode { if(is_moving_state) { //ROS_INFO("into moving state!!\n"); for(int i=7; i<9;i++) { result_[joint_id_to_name_[i]]->goal_position_= motion_trajectory[joint_id_to_name_[i]]->fifth_order_traj_gen(joint_name_to_ini_pose_state_[joint_id_to_name_[i]], joint_name_to_ini_pose_goal_[joint_id_to_name_[i]],0,0,0,0,0,mov_time_state); } } if(search_phase == 1) { if(motion_phase_init) { for(int dxl_id = 7; dxl_id < 9; dxl_id++) { joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]] = dxls[joint_id_to_name_[dxl_id]]->dxl_state_->present_position_; motion_trajectory[joint_id_to_name_[dxl_id]]->current_pose = joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]]; motion_trajectory[joint_id_to_name_[dxl_id]]->current_time = 0; joint_name_to_ini_pose_goal_[joint_id_to_name_[dxl_id]] = search_motion[search_phase - 1][dxl_id-7]; } motion_phase_init = false; is_moving_state = true; } if(abs(dxls[joint_id_to_name_[7]]->dxl_state_->present_position_ - search_motion[search_phase-1][0]) < motion_bias && abs(dxls[joint_id_to_name_[8]]->dxl_state_->present_position_ - search_motion[search_phase-1][1]) < motion_bias) { search_phase++; //mov_time_state = 2.0; is_moving_state = false; new_count_ = 1; motion_phase_init = true; } } else if(search_phase == 2) { if(motion_phase_init) { for(int dxl_id = 7; dxl_id < 9; dxl_id++) { joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]] = dxls[joint_id_to_name_[dxl_id]]->dxl_state_->present_position_; motion_trajectory[joint_id_to_name_[dxl_id]]->current_pose = joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]]; motion_trajectory[joint_id_to_name_[dxl_id]]->current_time = 0; joint_name_to_ini_pose_goal_[joint_id_to_name_[dxl_id]] = search_motion[search_phase - 1][dxl_id-7]; } motion_phase_init = false; is_moving_state = true; } if(abs(dxls[joint_id_to_name_[7]]->dxl_state_->present_position_ - search_motion[search_phase-1][0]) < motion_bias && abs(dxls[joint_id_to_name_[8]]->dxl_state_->present_position_ - search_motion[search_phase-1][1]) < motion_bias) { search_phase++; is_moving_state = false; new_count_ = 1; motion_phase_init = true; } } else if(search_phase == 3) { if(motion_phase_init) { for(int dxl_id = 7; dxl_id < 9; dxl_id++) { joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]] = dxls[joint_id_to_name_[dxl_id]]->dxl_state_->present_position_; motion_trajectory[joint_id_to_name_[dxl_id]]->current_pose = joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]]; motion_trajectory[joint_id_to_name_[dxl_id]]->current_time = 0; joint_name_to_ini_pose_goal_[joint_id_to_name_[dxl_id]] = search_motion[search_phase - 1][dxl_id-7]; } motion_phase_init = false; is_moving_state = true; } if(abs(dxls[joint_id_to_name_[7]]->dxl_state_->present_position_ - search_motion[search_phase-1][0]) < motion_bias && abs(dxls[joint_id_to_name_[8]]->dxl_state_->present_position_ - search_motion[search_phase-1][1]) < motion_bias) { search_phase = 0; is_moving_state = false; new_count_ = 1; motion_phase_init = true; pre_mode_ = 6; } } } else if(mode_ == 5) // ball_check mode { if(is_moving_state) { //ROS_INFO("into moving state!!\n"); for(int i=7; i<9;i++) { result_[joint_id_to_name_[i]]->goal_position_= motion_trajectory[joint_id_to_name_[i]]->fifth_order_traj_gen(joint_name_to_ini_pose_state_[joint_id_to_name_[i]], joint_name_to_ini_pose_goal_[joint_id_to_name_[i]],0,0,0,0,0,mov_time_state); } } if(search_phase == 5) { if(motion_phase_init) { for(int dxl_id = 7; dxl_id < 9; dxl_id++) { joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]] = dxls[joint_id_to_name_[dxl_id]]->dxl_state_->present_position_; motion_trajectory[joint_id_to_name_[dxl_id]]->current_pose = joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]]; motion_trajectory[joint_id_to_name_[dxl_id]]->current_time = 0; joint_name_to_ini_pose_goal_[joint_id_to_name_[dxl_id]] = search_motion[search_phase - 1][dxl_id-7]; } motion_phase_init = false; is_moving_state = true; } if(abs(dxls[joint_id_to_name_[7]]->dxl_state_->present_position_ - search_motion[search_phase-1][0]) < motion_bias && abs(dxls[joint_id_to_name_[8]]->dxl_state_->present_position_ - search_motion[search_phase-1][1]) < motion_bias) { search_phase++; is_moving_state = false; new_count_ = 1; motion_phase_init = true; } ROS_INFO("pre_pos : %f\n",dxls[joint_id_to_name_[7]]->dxl_state_->present_position_); ROS_INFO("search motion : %f\n",search_motion[search_phase-1][0]); ROS_INFO("gap : %f\n",abs(dxls[joint_id_to_name_[7]]->dxl_state_->present_position_ - search_motion[search_phase-1][0])); } else if(search_phase == 6) { if(motion_phase_init) { for(int dxl_id = 7; dxl_id < 9; dxl_id++) { joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]] = dxls[joint_id_to_name_[dxl_id]]->dxl_state_->present_position_; motion_trajectory[joint_id_to_name_[dxl_id]]->current_pose = joint_name_to_ini_pose_state_[joint_id_to_name_[dxl_id]]; motion_trajectory[joint_id_to_name_[dxl_id]]->current_time = 0; joint_name_to_ini_pose_goal_[joint_id_to_name_[dxl_id]] = search_motion[search_phase - 1][dxl_id-7]; } motion_phase_init = false; is_moving_state = true; } if(abs(dxls[joint_id_to_name_[7]]->dxl_state_->present_position_ - search_motion[search_phase-1][0]) < motion_bias && abs(dxls[joint_id_to_name_[8]]->dxl_state_->present_position_ - search_motion[search_phase-1][1]) < motion_bias) { search_phase = 0; is_moving_state = false; new_count_ = 1; motion_phase_init = true; pre_mode_ = 6; } } } else if(mode_ == 6) // stop { is_moving_state = false; } } double TorsoModule::LowpassFilter(double x) { f_cut = 25; w_cut = 2*PI*f_cut; tau = 1/w_cut; y = ( tau * pre_y + ts * x ) /(tau + ts) ; pre_x = x; pre_y = y; return y; } void TorsoModule::stop() { new_count_ = 1; return; }
[ "heroehsyona@gmail.com" ]
heroehsyona@gmail.com
bd4970ca63920284111188ae7b776e53ed89e0fa
3c4f86f7d74b388cb9197fba66728e9023b40e29
/UNIVERSIDAD/programacion/ejemplos/Utn/ejercicios_lab1_32_hasta_ matrices/EJER47.CPP
1caf9229da22cb8ba96adb6da9af137d58f7c22c
[]
no_license
andoporto/Programacion2014
a05058b8ec7e06e7f75c412f345dca234c67746b
2a1d860813c85b1c618a61c29833af2662636693
refs/heads/master
2021-01-23T21:39:08.697914
2015-02-16T23:17:48
2015-02-16T23:17:48
30,872,534
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <stdio.h> #include <conio.h> void main (void){ int a, b, c, d, e, n; clrscr(); printf("\n\n\n\t\t\tFecha de Pascua del 2003"); a = 2003 % 19; b = 2003 % 4; c = 2003 % 7; d = ( 19 * a + 24 ) % 30; e = ( 2 * b + 4 * c + 6 * d + 5 ) % 7; n = ( 22 + d + e ); if( n > 31 ) printf("\n\n\t\t\t%d de Abril", n - 31); else printf("\n\n\t\t\t%d de Marzo", n); getch(); }
[ "andoporto@gmail.com" ]
andoporto@gmail.com
76f651cb8362e77414e54b8fc1009b0325205e4e
2fe4e358b9b89f7a768bb6c02f43fb83630c5d73
/src/threadpool/Condition.cc
c8414cb974a06c94399e59002894fef6b2c8c36c
[]
no_license
mzLuo/spellCorrection
110d103f2a15613584cf497820901fb70ca1610e
d5b834ac48c528583ecca213005f7a843de448ab
refs/heads/master
2020-03-08T21:13:06.042020
2018-04-06T14:03:15
2018-04-06T14:03:15
128,402,274
3
0
null
null
null
null
UTF-8
C++
false
false
562
cc
/// /// @file Condition.cc /// @author lemon(haohb13@gmail.com) /// @date 2016-03-18 15:05:17 /// #include "Condition.h" #include "MutexLock.h" namespace wd { Condition::Condition(MutexLock & mutex) : _mutex(mutex) { pthread_cond_init(&_cond, NULL); } Condition::~Condition() { pthread_cond_destroy(&_cond); } void Condition::wait() { pthread_cond_wait(&_cond, _mutex.getMutexLockPtr()); } void Condition::notify() { pthread_cond_signal(&_cond); } void Condition::notifyAll() { pthread_cond_broadcast(&_cond); } }//end of namespace wd
[ "mzluo2866@163.com" ]
mzluo2866@163.com
c03e651389f3c792508497d1e4d5caab14d5c518
a15a859507d83a6fe292d13f6289cba72d829484
/model/uan-phy-real-newb.h
5caa1080ce1f45172a036906722d24d88e707707
[]
no_license
rustfree/NS3_UAN_FcMaca
a41344071387281a54a369815f4013636546ee4a
f27b1f2b6e005daa2ab1d6dd46048d604024e367
refs/heads/master
2023-02-25T10:58:26.702043
2021-01-18T12:50:45
2021-01-18T12:50:45
330,548,629
1
1
null
null
null
null
UTF-8
C++
false
false
10,905
h
/* ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ** uan-phy-real-new.h * ** Created on 2018/7/18 * ** Author:lch * ** For:connecting with real channel * ** ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * ~ * */ #ifndef UAN_PHY_REAL_NEW_H #define UAN_PHY_REAL_NEW_H #include "uan-phy.h" #include "ns3/traced-callback.h" #include "ns3/nstime.h" #include "ns3/device-energy-model.h" #include "ns3/random-variable-stream.h" #include "ns3/event-id.h" #include "ns3/system-thread.h" #include <list> //#include <cstring> namespace ns3 { /** * \ingroup uan */ void * ReceivePacket(void * arg); class UanPhyRealNewbPerGenDefault : public UanPhyPer { public: /** Constructor */ UanPhyRealNewbPerGenDefault (); /** Destructor */ virtual ~UanPhyRealNewbPerGenDefault (); static TypeId GetTypeId (void); virtual double CalcPer (Ptr<Packet> pkt, double sinrDb, UanTxMode mode); private: double m_thresh; //!< SINR threshold. }; // class UanPhyRealNewbPerGenDefault class UanPhyRealNewbPerUmodem : public UanPhyPer { public: /** Constructor */ UanPhyRealNewbPerUmodem (); /** Destructor */ virtual ~UanPhyRealNewbPerUmodem (); static TypeId GetTypeId (void); virtual double CalcPer (Ptr<Packet> pkt, double sinrDb, UanTxMode mode); private: double NChooseK (uint32_t n, uint32_t k); }; // class UanPhyRealNewbPerUmodem /** * \ingroup uan */ class UanPhyRealNewbCalcSinrDefault : public UanPhyCalcSinr { public: /** Constructor */ UanPhyRealNewbCalcSinrDefault (); /** Destructor */ virtual ~UanPhyRealNewbCalcSinrDefault (); /** * Register this type. * \return The TypeId. */ static TypeId GetTypeId (void); virtual double CalcSinrDb (Ptr<Packet> pkt, Time arrTime, double rxPowerDb, double ambNoiseDb, UanTxMode mode, UanPdp pdp, const UanTransducer::ArrivalList &arrivalList ) const; }; // class UanPhyRealNewbCalcSinrDefault /** * \ingroup uan */ class UanPhyRealNewbCalcSinrFhFsk : public UanPhyCalcSinr { public: /** Constructor */ UanPhyRealNewbCalcSinrFhFsk (); /** Destructor */ virtual ~UanPhyRealNewbCalcSinrFhFsk (); static TypeId GetTypeId (void); virtual double CalcSinrDb (Ptr<Packet> pkt, Time arrTime, double rxPowerDb, double ambNoiseDb, UanTxMode mode, UanPdp pdp, const UanTransducer::ArrivalList &arrivalList ) const; private: uint32_t m_hops; //!< Number of hops. }; // class UanPhyRealNewbCalcSinrFhFsk /** * \ingroup uan * * Generic PHY model. * * This is a generic PHY class. SINR and PER information * are controlled via attributes. By adapting the SINR * and PER models to a specific situation, this PHY should * be able to model a wide variety of networks. */ class UanPhyRealNewb : public UanPhy { public: /** Constructor */ UanPhyRealNewb (); /** Dummy destructor, see DoDispose */ virtual ~UanPhyRealNewb (); /** * Get the default transmission modes. * * \return The default mode list. */ static UanModesList GetDefaultModes (void); /** * Register this type. * \return The TypeId. */ static TypeId GetTypeId (void); // Inherited methods virtual void SetEnergyModelCallback (DeviceEnergyModel::ChangeStateCallback cb); virtual void EnergyDepletionHandler (void); virtual void EnergyRechargeHandler (void); virtual void SendPacket (Ptr<Packet> pkt, uint32_t modeNum); virtual void RegisterListener (UanPhyListener *listener); virtual void StartRxPacket (Ptr<Packet> pkt, double rxPowerDb, UanTxMode txMode, UanPdp pdp); virtual void SetReceiveOkCallback (RxOkCallback cb); virtual void SetReceiveErrorCallback (RxErrCallback cb); virtual bool IsStateSleep (void); virtual bool IsStateIdle (void); virtual bool IsStateBusy (void); virtual bool IsStateRx (void); virtual bool IsStateTx (void); virtual bool IsStateCcaBusy (void); virtual void SetRxGainDb (double gain); virtual void SetTxPowerDb (double txpwr); virtual void SetRxThresholdDb (double thresh); virtual void SetCcaThresholdDb (double thresh); virtual double GetRxGainDb (void); virtual double GetTxPowerDb (void); virtual double GetRxThresholdDb (void); virtual double GetCcaThresholdDb (void); virtual Ptr<UanChannel> GetChannel (void) const; virtual Ptr<UanNetDevice> GetDevice (void) const; virtual Ptr<UanTransducer> GetTransducer (void); virtual void SetChannel (Ptr<UanChannel> channel); virtual void SetDevice (Ptr<UanNetDevice> device); virtual void SetMac (Ptr<UanMac> mac); virtual void SetTransducer (Ptr<UanTransducer> trans); virtual void NotifyTransStartTx (Ptr<Packet> packet, double txPowerDb, UanTxMode txMode); virtual void NotifyIntChange (void); virtual uint32_t GetNModes (void); virtual UanTxMode GetMode (uint32_t n); virtual Ptr<Packet> GetPacketRx (void) const; virtual void Clear (void); virtual void SetSleepMode (bool sleep); int64_t AssignStreams (int64_t stream); /*new added*/ //void StartTX(Ptr<Packet> pkt); //void EndRX(void); //void EndTX(void); void StartRX(void); //void ReceivePacket(void ); // void TransmitPacket (Ptr<Packet> pkt); void ConnectModem(void); void Init(void);//数据初始化 void setModemIP(void);//设置mocdem的IP bool IsrStateRX(void); void setrStateIDLE(void); int readnFd(void); /*thread method*/ void sendDataThread_1f(void); void sendDataThread_5f(void); void recvDataThread(void); private: /** List of Phy Listeners. */ typedef std::list<UanPhyListener *> ListenerList; UanModesList m_modes; //!< List of modes supported by this PHY. State m_state,r_state; //!< Phy state. ListenerList m_listeners; //!< List of listeners. RxOkCallback m_recOkCb; //!< Callback for packets received without error. RxErrCallback m_recErrCb; //!< Callback for packets received with errors. Ptr<UanChannel> m_channel; //!< Attached channel. Ptr<UanTransducer> m_transducer; //!< Associated transducer. Ptr<UanNetDevice> m_device; //!< Device hosting this Phy. Ptr<UanMac> m_mac; //!< MAC layer. Ptr<UanPhyPer> m_per; //!< Error model. Ptr<UanPhyCalcSinr> m_sinr; //!< SINR calculator. double m_rxGainDb; //!< Receive gain. double m_txPwrDb; //!< Transmit power. double m_rxThreshDb; //!< Receive SINR threshold. double m_ccaThreshDb; //!< CCA busy threshold. Ptr<Packet> m_pktRx; //!< Received packet. Ptr<Packet> m_pktTx; //!< Sent packet. double m_minRxSinrDb; //!< Minimum receive SINR during packet reception. double m_rxRecvPwrDb; //!< Receiver power. Time m_pktRxArrTime; //!< Packet arrival time. UanPdp m_pktRxPdp; //!< Power delay profile of pakket. UanTxMode m_pktRxMode; //!< Packet transmission mode at receiver. bool m_cleared; //!< Flag when we've been cleared. EventId m_txEndEvent; //!< Tx event EventId m_rxEndEvent; //!< Rx event EventId m_callEndEvent; /* * *argument about the real machine * * */ /* //TX float txGain = 0.01; float transmitAmp = txGain * 32767; // int sampleRate = 96000; int frameNum = 5; int time = 0; //RX */ /*veriable about the socket*/ int nFd = 0; int nRet = 0; int nReadLen =0; int len_pktTx = 0; int len_pktRx = 0; /*veriable about the modem packet*/ int tcppacketlen = 1032; char * tcpsendbuffer = (char *)malloc(tcppacketlen); char * tcprecvbuffer = (char *)malloc(tcppacketlen); char * tempbuffer = (char *)malloc(tcppacketlen); char * recvbuffer = (char *)malloc(tcppacketlen); int framecnt; //帧号 int messageLen; //数据长度 int tuborItertime; //迭代次数 //rx float threshold = 0.1; float rxgain = 1; uint16_t gain = (uint16_t)(rxgain/2.5*65535); uint16_t correlateThreadShort = (uint16_t)(threshold*65535);;//? int sampleRate = 96000; uint16_t qpskNumChannel = 4; int frameNum = 1; //tx float txGain = 0.01; float transmitAmp = txGain * 32767; Ptr<SystemThread> recvthr,sendthr; //int MaxSize = 1024; //datasize允许的最大值 uint16_t dataSize = 1024; uint16_t packetSize = 1024; //max:1024,传到phy层的packet的大小,等于应用层的包大小+3,目前为测试状态 int dataPerFrame = 239; // int dataPerBag =1024; int sendBytesNum; int zeroBytesNum; int sendPackageNum; short serverPort=80; //端口号 uint32_t serverAddr=0; //??? const char * IpList[3]={"192.168.2.101","192.168.2.102","192.168.2.103"}; /** Provides uniform random variables. */ Ptr<UniformRandomVariable> m_pg; /** Energy model callback. */ DeviceEnergyModel::ChangeStateCallback m_energyCallback; /** A packet destined for this Phy was received without error. */ ns3::TracedCallback<Ptr<const Packet>, double, UanTxMode > m_rxOkLogger; /** A packet destined for this Phy was received with error. */ ns3::TracedCallback<Ptr<const Packet>, double, UanTxMode > m_rxErrLogger; /** A packet was sent from this Phy. */ ns3::TracedCallback<Ptr<const Packet>, double, UanTxMode > m_txLogger; double CalculateSinrDb (Ptr<Packet> pkt, Time arrTime, double rxPowerDb, UanTxMode mode, UanPdp pdp); double GetInterferenceDb (Ptr<Packet> pkt); double DbToKp (double db); double KpToDb (double kp); void RxEndEvent (Ptr<Packet> pkt, double rxPowerDb, UanTxMode txMode); /** Event to process end of packet transmission. */ void TxEndEvent (); void UpdatePowerConsumption (const State state); /** Call UanListener::NotifyRxStart on all listeners. */ void NotifyListenersRxStart (void); /** Call UanListener::NotifyRxEndOk on all listeners. */ void NotifyListenersRxGood (void); /** Call UanListener::NotifyRxEndError on all listeners. */ void NotifyListenersRxBad (void); /** Call UanListener::NotifyCcaStart on all listeners. */ void NotifyListenersCcaStart (void); /** Call UanListener::NotifyCcaEnd on all listeners. */ void NotifyListenersCcaEnd (void); void NotifyListenersTxStart (Time duration); protected: virtual void DoDispose (); }; // class UanPhyRealNewb } // namespace ns3 #endif /* UAN_PHY_REAL_H */
[ "luochaohui_lch@163.com" ]
luochaohui_lch@163.com
1f6a2a3b58c97768cd96882e79b4365e083660ad
3ea61f80e1e4b2113523624f0de88457b2669852
/src/pose_estimation/pose_estimation_halcon/src/Recognition_node.cpp
c60dee67825c75f281cc6da6899c9694ba5443d4
[]
no_license
rneerg/RoboVision3D
c4f8e05e91702a0df04eeb902771dad52588eb45
f0293ea5f1aaaf64d4530ac9f0f92a3583b55ef6
refs/heads/master
2020-04-18T16:03:55.217179
2014-09-04T11:55:03
2014-09-04T11:55:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,779
cpp
/******************************************************************************************************************** * * @file Recognition_node.cpp * @author Thomas Sølund (thso@teknologisk.dk) * @date 2013-04-23 * @version 1.0 * @brief ROS Node implementing Halcon surface based matching * *********************************************************************************************************************/ #include <ros/ros.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <pcl/conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/common/transforms.h> #include <pcl/filters/extract_indices.h> #include <sensor_msgs/PointCloud2.h> #include <ros/callback_queue.h> #include <visualization_msgs/MarkerArray.h> #include <visualization_msgs/Marker.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/filters/extract_indices.h> //Downsampling using the voxel grid approach #include <pcl/filters/voxel_grid.h> //Boost uuid #include <boost/uuid/uuid.hpp> // uuid class #include <boost/uuid/uuid_generators.hpp> // generators #include <boost/uuid/uuid_io.hpp> // streaming operators etc. #include <boost/lexical_cast.hpp> #include <pose_estimation_halcon/ModelCreationParameters.hpp> #include <pose_estimation_halcon/SurfaceModelCreator.h> #include <pose_estimation_halcon/SurfaceModelDetector.h> #include <pose_estimation_halcon/ModelCreators.hpp> #include <pose_estimation_halcon/ModelDetectors.hpp> #include <pose_estimation_halcon/Create3DObjectModel.h> #include <pose_estimation_halcon/PCDFileHandler.h> #include <pose_estimation_halcon/prepareEstimation.h> #include <pose_estimation_halcon/estimate.h> #include <robot_msgs/ResultPose.h> using namespace HalconCpp; namespace perception { class RecognitionCtrl { public: RecognitionCtrl(ros::NodeHandle nh); virtual ~RecognitionCtrl(); void startServices(); void InitParameters(); void setTopicSubscriber(); void setTopicPublisher(); void pointcloud_callback(const sensor_msgs::PointCloud2ConstPtr& cloud); void createMarker(int id, double x, double y, double z, double roll, double pitch, double yaw, double lengthX, double lengthY, double lengthZ ); /*ROS services */ bool prepareEstimation(pose_estimation_halcon::prepareEstimation::Request &req, pose_estimation_halcon::prepareEstimation::Response &res); bool estimate(pose_estimation_halcon::estimate::Request &req, pose_estimation_halcon::estimate::Response &res); private: ros::NodeHandle nh; // Create a map for name resolving std::map<std::string,boost::uuids::uuid> indexmap; // Create a map storing halcon model by uuid std::map<boost::uuids::uuid,HTuple> modelmap; //Primilary model container pcl::PointCloud<pcl::PointXYZ> pcl_model; std::string point_cloud_topic; std::string scene_cloud_path; std::string model_cloud_path; ros::ServiceServer sPrepareRecognition; ros::ServiceServer sFind3DModel; ros::Publisher visPub; ros::Publisher segResult; pcl::PointCloud<pcl::PointXYZRGB> *cloud; bool cloud_ready; HTuple halcon_model; bool removeTable(pcl::PointCloud<pcl::PointXYZ>::Ptr src, pcl::PointCloud<pcl::PointXYZ>::Ptr tar); }; } namespace perception { RecognitionCtrl::RecognitionCtrl(ros::NodeHandle _nh) { // TODO Auto-generated constructor stub nh = _nh; cloud = new pcl::PointCloud<pcl::PointXYZRGB>; cloud_ready = false; } RecognitionCtrl::~RecognitionCtrl() { // TODO Auto-generated destructor stub } void RecognitionCtrl::startServices() { sPrepareRecognition = nh.advertiseService("prepare", &perception::RecognitionCtrl::prepareEstimation,this); ROS_INFO("pose_estimation_halcon: Started service /pose_estimation_halcon/prepare."); sFind3DModel = nh.advertiseService("estimate", &perception::RecognitionCtrl::estimate,this); ROS_INFO("pose_estimation_halcon: Started service /pose_estimation_halcon/estimate."); } void RecognitionCtrl::InitParameters() { ROS_INFO("pose_estimation_halcon: Loading Node parameters"); // Load parameters from launch file nh.param<std::string>("point_cloud_topic", point_cloud_topic, ""); nh.param<std::string>("scene_cloud_path", scene_cloud_path, ""); nh.param<std::string>("model_cloud_path", model_cloud_path, ""); } void RecognitionCtrl::setTopicSubscriber() { ROS_INFO("pose_estimation_halcon: Subcribe to topics"); } void RecognitionCtrl::setTopicPublisher() { ROS_INFO("pose_estimation_halcon: Starting publishing service"); // visPub = nh.advertise<visualization_msgs::Marker>("objectMarker",0); std::string result = "result"; ROS_INFO_STREAM("Creating publisher \"" << nh.getNamespace() << "/" << result << "\"..."); visPub = nh.advertise<sensor_msgs::PointCloud2>(result,50); // Visualization publisher std::string topic = "segmented"; ROS_INFO_STREAM("Creating publisher \"" << nh.getNamespace() << "/" << topic << "\"..."); segResult = nh.advertise<sensor_msgs::PointCloud2>(topic, 50); } bool RecognitionCtrl::removeTable(pcl::PointCloud<pcl::PointXYZ>::Ptr src, pcl::PointCloud<pcl::PointXYZ>::Ptr tar) { //*********************************************************************// // Plane fitting /**********************************************************************/ pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<pcl::PointXYZ> seg; // Optional seg.setOptimizeCoefficients (true); // Mandatory seg.setModelType (pcl::SACMODEL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (0.01); seg.setInputCloud (src); seg.segment (*inliers, *coefficients); if (inliers->indices.size () == 0) { PCL_ERROR ("Could not estimate a planar model for the given dataset."); return false; } std::cerr << "Model coefficients: " << coefficients->values[0] << " " << coefficients->values[1] << " " << coefficients->values[2] << " " << coefficients->values[3] << std::endl; std::cerr << "Model inliers: " << inliers->indices.size () << std::endl; //*********************************************************************// // Extract Indices /**********************************************************************/ pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_n (new pcl::PointCloud<pcl::PointXYZ>); // Create the filtering object pcl::ExtractIndices<pcl::PointXYZ> extract; // Extract the inliers extract.setInputCloud (src); extract.setIndices(inliers); extract.setNegative (true); extract.filter (*cloud_n); std::cerr << "PointCloud representing the planar component: " << cloud_n->width * cloud_n->height << " data points." << std::endl; sensor_msgs::PointCloud2 segsvisuros; pcl::toROSMsg<pcl::PointXYZ>(*cloud_n, segsvisuros); segResult.publish(segsvisuros); pcl::copyPointCloud(*cloud_n,*tar); return true; } void RecognitionCtrl::createMarker(int id, double x, double y, double z, double roll, double pitch, double yaw, double lengthX, double lengthY, double lengthZ ) { visualization_msgs::Marker marker; marker.header.frame_id = "objectMarker"; marker.header.stamp = ros::Time(); marker.ns = nh.getNamespace(); marker.id = 0; marker.type = visualization_msgs::Marker::CUBE; marker.action = visualization_msgs::Marker::ADD; marker.pose.position.x = 1; marker.pose.position.y = 1; marker.pose.position.z = 1; marker.pose.orientation.x = 0.0; marker.pose.orientation.y = 0.0; marker.pose.orientation.z = 0.0; marker.pose.orientation.w = 1.0; marker.scale.x = lengthX; marker.scale.y = lengthY; marker.scale.z = lengthZ; marker.color.a = 1.0; marker.color.r = 0.0; marker.color.g = 1.0; marker.color.b = 0.0; //only if using a MESH_RESOURCE marker type: //marker.mesh_resource = "package://pr2_description/meshes/base_v0/base.dae"; visPub.publish(marker); } void RecognitionCtrl::pointcloud_callback(const sensor_msgs::PointCloud2ConstPtr& input) { ROS_INFO("DTI_3D_Recognition: Pointcloud_callback"); // Convert input message to pointcloud cloud_ready = false; pcl::fromROSMsg(*input, *cloud); cloud_ready = true; } bool RecognitionCtrl::prepareEstimation(pose_estimation_halcon::prepareEstimation::Request &req, pose_estimation_halcon::prepareEstimation::Response &res) { ROS_INFO("pose_estimation_halcon: Prepare pose estimation service called!!"); if(!req.model_name.empty()) { //Check if model already exist in map if(indexmap.find(req.model_name) == indexmap.end()) { // Create unique id boost::uuids::uuid uuid = boost::uuids::random_generator()(); std::cout << uuid << std::endl; // create a map for model name --> uuid indexmap.insert( std::make_pair(req.model_name,uuid)); //Create the object model from a point cloud Create3DObjectModel cadModelCreator; sensor_msgs::PointCloud2 m = req.model; pcl::PointCloud<pcl::PointXYZ> model; pcl::fromROSMsg(m, model); pcl_model = model; HTuple x,y,z; for (size_t i = 0; i < model.points.size (); ++i) { x.Append(HTuple(model.points[i].x)); y.Append(HTuple(model.points[i].y)); z.Append(HTuple(model.points[i].z)); } cadModelCreator.createModelFromPoints(x,y,z); // cadModelCreator.readModel(req.pcd_model_path); // ROS_INFO("pose_estimation_halcon: CAD model loaded from %s", req.pcd_model_path.c_str()); //HTuple Pose; //HTuple radius = 10; //HTuple minExtend = 20; //HTuple maxExtend = 20; //CreatePose(10,10,10,0,0,0,"Rp+T","gba","point",&Pose); //cadModelCreator.createBoxModel(Pose,HTuple(10),HTuple(10),HTuple(10)); //ROS_INFO("DTI_3D_Recognition: Synthetic cylinder model created!"); cadModelCreator.computeSurfaceNormals(); cadModelCreator.writeModel(req.surface_model_path, "obj"); HTuple objectModel3D = cadModelCreator.get3DObjectModel(); ROS_INFO("=============CAD Models contains: ================="); if(cadModelCreator.hasPoints() ){ ROS_INFO("\t%d Points", cadModelCreator.getNumberOfPoints()); } if(cadModelCreator.hasFaces()){ ROS_INFO("\t%d Faces", cadModelCreator.getNumberOfFaces()); } if(cadModelCreator.hasLines()){ ROS_INFO("\t%d Lines", cadModelCreator.getNumberOfLines()); } if(cadModelCreator.hasPointNormals()){ ROS_INFO("\tPoint normals"); } if(cadModelCreator.hasTriangles()){ ROS_INFO("\t%d Triangles", cadModelCreator.getNumberOfTriangles()); } ROS_INFO("==================================================="); //double min_x,min_y,min_z,max_x,max_y,max_z; //cadModelCreator.getBoundingBox(min_x, min_y, min_z, max_x, max_y, max_z); //std::cout << min_x <<" "<< min_y <<" "<< min_z <<" "<< max_x <<" "<< max_y <<" "<< max_z << std::endl; //Create the surface model using the objectModel SurfaceModelCreationParameters smcParams; smcParams.RelSamplingDistance = HTuple(req.RelSamplingDistance); //smcParams.feat_angle_resolution = smcParams.feat_step_size_rel = HTuple(req.RelSamplingDistance); smcParams.ObjectModel3D = objectModel3D; ROS_INFO("pose_estimation_halcon: Creating surface model"); SurfaceModelCreator smc; smc.setParameters(smcParams); smc.createModel(); ROS_INFO("pose_estimation_halcon: Saving surface model to %s", req.surface_model_path.c_str()); smc.saveModel(req.surface_model_path); halcon_model = smc.getSurfaceModel(); // Add Halcon model to map modelmap.insert(std::make_pair(uuid,smc.getSurfaceModel().Clone())); res.model_id = boost::lexical_cast<std::string>(uuid); res.isReady = true; }else{ ROS_WARN("%s model already exist as surface model!",req.model_name.c_str()); res.isReady = true; } }else { ROS_WARN("No Model name associated to the model. Please provide a name!"); res.isReady = false; } return true; } bool RecognitionCtrl::estimate(pose_estimation_halcon::estimate::Request &req, pose_estimation_halcon::estimate::Response &res) { ROS_INFO("pose_estimation_halcon: Pose estimation service called!!"); // Get a point cloud if(!point_cloud_topic.empty()){ sensor_msgs::PointCloud2::ConstPtr cloud = ros::topic::waitForMessage<sensor_msgs::PointCloud2>(point_cloud_topic, ros::Duration(5.0)); if(!cloud) { ROS_WARN("Retrieval of point cloud failed!"); return false; } pcl::PointCloud<pcl::PointXYZ> scene; pcl::PointCloud<pcl::PointXYZRGB> scene_rgb; pcl::fromROSMsg(*cloud, scene); pcl::fromROSMsg(*cloud, scene_rgb); ROS_INFO("pose_estimation_halcon: grabbing scene cloud with %d points!", (int)scene.points.size ()); //Downsample point cloud pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZ>); // Create the filtering object pcl::VoxelGrid<pcl::PointXYZ> sor; sor.setInputCloud (scene.makeShared()); sor.setLeafSize (req.leaf_size,req.leaf_size,req.leaf_size); sor.filter (*cloud_filtered); std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height << " data points (" << pcl::getFieldsList (*cloud_filtered) << ")." << std::endl; pcl::PointCloud<pcl::PointXYZ>::Ptr scene_without_plane (new pcl::PointCloud<pcl::PointXYZ>); if(req.table_top){ //Application is a table top application remove if(!removeTable(cloud_filtered,scene_without_plane)) return false; }else{ pcl::copyPointCloud(*cloud_filtered, *scene_without_plane); } HTuple x,y,z; for (size_t i = 0; i < scene_without_plane->points.size (); ++i) { //std::cout << pc->points[i].x << " " << std::endl; x.Append(HTuple(scene_without_plane->points[i].x)); y.Append(HTuple(scene_without_plane->points[i].y)); z.Append(HTuple(scene_without_plane->points[i].z)); } //Create the object model from the point cloud ROS_INFO("Creating Model of the scene!!"); Create3DObjectModel SearchModelCreator; SearchModelCreator.createModelFromPoints(x,y,z); SearchModelCreator.computeSurfaceNormals(); ROS_INFO("Number of points in scene: %d", SearchModelCreator.getNumberOfPoints()); HTuple scene_data = SearchModelCreator.get3DObjectModel(); ObjectModelFileFormat file; SearchModelCreator.writeModel("scene", file.obj); SurfaceModelDetectionParameters detectParams; detectParams.RelSamplingDistance = HTuple(req.RelSamplingDistance); detectParams.num_matches = 10; detectParams.KeyPointFraction = 0.5; detectParams.MinScore = 0.1; boost::uuids::uuid uuid = boost::lexical_cast<boost::uuids::uuid>(req.model_id); std::map<boost::uuids::uuid, HTuple>::iterator it = modelmap.find(uuid); // HTuple surface_model = halcon_model;//it->second; // std::cout << surface_model << std::endl; HTuple pose, score; SurfaceModelDetector detector; detector.setParameters(detectParams); ROS_INFO("model path: %s", req.surface_model_path.c_str()); //detector.setSurfaceModel(halcon_model); detector.loadModel(req.surface_model_path); ROS_INFO("Detecting 3D model!"); int instances = detector.detectModel(scene_data); if(instances > 0) { ROS_INFO("Found %d instances of the model in the scene!", instances); if(detector.getBestMatch(pose, score) == 1) { ROS_INFO("Apply transformation to model!"); HTuple HomMat; PoseToHomMat3d(pose,&HomMat); Eigen::Matrix4f t; t(0,0) = (double)HomMat[0]; t(0,1) = (double)HomMat[1]; t(0,2) = (double)HomMat[2]; t(0,3) = (double)HomMat[3]; t(1,0) = (double)HomMat[4]; t(1,1) = (double)HomMat[5]; t(1,2) = (double)HomMat[6]; t(1,3) = (double)HomMat[7]; t(2,0) = (double)HomMat[8]; t(2,1) = (double)HomMat[9]; t(2,2) = (double)HomMat[10]; t(2,3) = (double)HomMat[11]; t(3,0) = 0; t(3,1) = 0; t(3,2) = 0; t(3,3) = 1; pcl::PointCloud<pcl::PointXYZ>::Ptr aligned_model (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr result_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::transformPointCloud(pcl_model,*aligned_model, t); //*result_cloud += *aligned_model; pcl::copyPointCloud(*aligned_model,*result_cloud); //color model red for (size_t i = 0; i < result_cloud->points.size (); ++i) { result_cloud->points[i].r = 255; result_cloud->points[i].g = 0; result_cloud->points[i].b = 0; } //color scene blue for (size_t i = 0; i < scene_rgb.points.size (); ++i) { scene_rgb.points[i].r = 0; scene_rgb.points[i].g = 0; scene_rgb.points[i].b = 255; } *result_cloud += scene_rgb; sensor_msgs::PointCloud2 res_msg; pcl::toROSMsg<pcl::PointXYZRGB>(*result_cloud, res_msg); visPub.publish(res_msg); robot_msgs::ResultPose result; result.pose.x = pose[0]; result.pose.y = pose[1]; result.pose.z = pose[2]; result.pose.roll = pose[3]; result.pose.pitch = pose[4]; result.pose.yaw = pose[5]; result.status = true; result.confirmed = true; res.pose = result; res.isReady = true; } } }else{ ROS_ERROR("No scene topic name avaliable!! Please add in the parameter list!!"); res.isReady = false; } return true; } } /* namespace perception */ int main(int argc, char **argv) { ROS_INFO("*************************************************"); ROS_INFO("This node implements 3D pose estimation using "); ROS_INFO("Halcon surface based matching "); ROS_INFO("*************************************************"); ros::init(argc, argv, "pose_estimation_halcon"); ros::NodeHandle nh("~"); perception::RecognitionCtrl rc(nh); rc.InitParameters(); rc.setTopicSubscriber(); rc.setTopicPublisher(); rc.startServices(); ROS_INFO("pose_estimation_halcon node is running"); ros::spin(); return 0; }
[ "soelund@mail.dk" ]
soelund@mail.dk
68284117553b54188947eb45fcdd5b378e84d146
99a5907d52d23cbab9703a3818d93f8b80dedc9d
/week2_algorithmic_warmup/1_fibonachi_number.cpp
c3ce72deed98d467885f6bdc7c8a92de7f35d6ec
[]
no_license
Mr-SkyLark/Algorythmic_Toolbox
7e705b62dcd1998518b20958a8089a8a7ad5c062
fced2f74be28d1bcfa7274e8922c56f32c89682e
refs/heads/master
2021-05-18T13:52:19.539828
2020-04-22T09:49:07
2020-04-22T09:49:07
251,270,299
0
0
null
null
null
null
UTF-8
C++
false
false
566
cpp
//#define TESTS_ON #ifdef TESTS_ON #include "Test.hpp" #endif #include <iostream> #include <vector> #include <algorithm> long long fibonacci_fast(long long n) { if (n <= 1) return n; long long result = 1; long long preResult = 0; for(int i = 1; i < n; ++i) { preResult = preResult + result; std::swap(preResult, result); } return result; } int main() { #ifdef TESTS_ON Test test; test.test(); #else int n = 0; std::cin >> n; std::cout << fibonacci_fast(static_cast<long long>(n)) << '\n'; #endif return 0; }
[ "galdin.ilya.d@gmail.com" ]
galdin.ilya.d@gmail.com
1483d4ecd24e9e468ea5a9604bcbe97a9edef375
1ad59f12e827d1bd221b3d2800e2417d6a3a9293
/aten/src/ATen/core/TensorMethods.h
f3eb453554bbd6da0dd6916fcd26065994f80ad1
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
cjnolet/pytorch
97fb5e3a82f453caf7d009e5283d78e2a07850a0
a7b3197b2d4b63685629e903e95350eab143f976
refs/heads/master
2020-04-10T11:41:32.079146
2018-12-09T02:15:00
2018-12-09T02:17:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,337
h
#pragma once #include "ATen/core/Tensor.h" #include <c10/core/Scalar.h> #include <c10/macros/Macros.h> #include "ATen/core/SparseTensorRef.h" #include "ATen/core/Type.h" #include "c10/core/TensorOptions.h" namespace at { inline Tensor Tensor::toType(const Type & t, bool non_blocking) const { if(type() == t) return *this; return t.copy(*this, non_blocking); } inline Tensor Tensor::cpu() const { return toType(type().cpu()); } inline Tensor Tensor::cuda() const { return toType(type().cuda()); } inline Tensor Tensor::hip() const { return toType(type().hip()); } inline Tensor & Tensor::copy_(const Tensor & src, bool non_blocking) { return type().copy_(*this, src, non_blocking); } inline Tensor Tensor::toType(ScalarType t) const { return toType(type().toScalarType(t)); } inline Tensor Tensor::toBackend(Backend b) const { return toType(type().toBackend(b)); } inline TensorOptions Tensor::options() const { return TensorOptions().dtype(dtype()) .device(device()) .layout(layout()) .is_variable(is_variable()); } inline void Tensor::backward( c10::optional<Tensor> gradient, bool keep_graph, bool create_graph) { type().backward(*this, std::move(gradient), keep_graph, create_graph); } inline void Tensor::set_data(Tensor new_data) { type().set_data(*this, new_data); } // all static inline to allow for inlining of the non-dynamic part of dispatch inline Tensor Tensor::abs() const { return type().abs(*this); } inline Tensor & Tensor::abs_() { return type().abs_(*this); } inline Tensor Tensor::acos() const { return type().acos(*this); } inline Tensor & Tensor::acos_() { return type().acos_(*this); } inline Tensor Tensor::add(const Tensor & other, Scalar alpha) const { return type().add(*this, other, alpha); } inline Tensor & Tensor::add_(const Tensor & other, Scalar alpha) { return type().add_(*this, other, alpha); } inline Tensor Tensor::add(Scalar other, Scalar alpha) const { return type().add(*this, other, alpha); } inline Tensor & Tensor::add_(Scalar other, Scalar alpha) { return type().add_(*this, other, alpha); } inline Tensor Tensor::addmv(const Tensor & mat, const Tensor & vec, Scalar beta, Scalar alpha) const { return type().addmv(*this, mat, vec, beta, alpha); } inline Tensor & Tensor::addmv_(const Tensor & mat, const Tensor & vec, Scalar beta, Scalar alpha) { return type().addmv_(*this, mat, vec, beta, alpha); } inline Tensor Tensor::addr(const Tensor & vec1, const Tensor & vec2, Scalar beta, Scalar alpha) const { return type().addr(*this, vec1, vec2, beta, alpha); } inline Tensor & Tensor::addr_(const Tensor & vec1, const Tensor & vec2, Scalar beta, Scalar alpha) { return type().addr_(*this, vec1, vec2, beta, alpha); } inline Tensor Tensor::all(int64_t dim, bool keepdim) const { return type().all(*this, dim, keepdim); } inline bool Tensor::allclose(const Tensor & other, double rtol, double atol, bool equal_nan) const { return type().allclose(*this, other, rtol, atol, equal_nan); } inline Tensor Tensor::any(int64_t dim, bool keepdim) const { return type().any(*this, dim, keepdim); } inline Tensor Tensor::argmax(int64_t dim, bool keepdim) const { return type().argmax(*this, dim, keepdim); } inline Tensor Tensor::argmax() const { return type().argmax(*this); } inline Tensor Tensor::argmin(int64_t dim, bool keepdim) const { return type().argmin(*this, dim, keepdim); } inline Tensor Tensor::argmin() const { return type().argmin(*this); } inline Tensor Tensor::as_strided(IntList size, IntList stride) const { return type().as_strided(*this, size, stride); } inline Tensor & Tensor::as_strided_(IntList size, IntList stride) { return type().as_strided_(*this, size, stride); } inline Tensor Tensor::as_strided(IntList size, IntList stride, int64_t storage_offset) const { return type().as_strided(*this, size, stride, storage_offset); } inline Tensor & Tensor::as_strided_(IntList size, IntList stride, int64_t storage_offset) { return type().as_strided_(*this, size, stride, storage_offset); } inline Tensor Tensor::asin() const { return type().asin(*this); } inline Tensor & Tensor::asin_() { return type().asin_(*this); } inline Tensor Tensor::atan() const { return type().atan(*this); } inline Tensor & Tensor::atan_() { return type().atan_(*this); } inline Tensor Tensor::baddbmm(const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const { return type().baddbmm(*this, batch1, batch2, beta, alpha); } inline Tensor & Tensor::baddbmm_(const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) { return type().baddbmm_(*this, batch1, batch2, beta, alpha); } inline Tensor Tensor::bernoulli(Generator * generator) const { return type().bernoulli(*this, generator); } inline Tensor & Tensor::bernoulli_(const Tensor & p, Generator * generator) { return type().bernoulli_(*this, p, generator); } inline Tensor & Tensor::bernoulli_(double p, Generator * generator) { return type().bernoulli_(*this, p, generator); } inline Tensor Tensor::bernoulli(double p, Generator * generator) const { return type().bernoulli(*this, p, generator); } inline Tensor Tensor::bincount(const Tensor & weights, int64_t minlength) const { return type().bincount(*this, weights, minlength); } inline Tensor Tensor::bmm(const Tensor & mat2) const { return type().bmm(*this, mat2); } inline Tensor Tensor::ceil() const { return type().ceil(*this); } inline Tensor & Tensor::ceil_() { return type().ceil_(*this); } inline std::vector<Tensor> Tensor::chunk(int64_t chunks, int64_t dim) const { return type().chunk(*this, chunks, dim); } inline Tensor Tensor::clamp(c10::optional<Scalar> min, c10::optional<Scalar> max) const { return type().clamp(*this, min, max); } inline Tensor & Tensor::clamp_(c10::optional<Scalar> min, c10::optional<Scalar> max) { return type().clamp_(*this, min, max); } inline Tensor Tensor::clamp_max(Scalar max) const { return type().clamp_max(*this, max); } inline Tensor & Tensor::clamp_max_(Scalar max) { return type().clamp_max_(*this, max); } inline Tensor Tensor::clamp_min(Scalar min) const { return type().clamp_min(*this, min); } inline Tensor & Tensor::clamp_min_(Scalar min) { return type().clamp_min_(*this, min); } inline Tensor Tensor::contiguous() const { return type().contiguous(*this); } inline Tensor Tensor::cos() const { return type().cos(*this); } inline Tensor & Tensor::cos_() { return type().cos_(*this); } inline Tensor Tensor::cosh() const { return type().cosh(*this); } inline Tensor & Tensor::cosh_() { return type().cosh_(*this); } inline Tensor Tensor::cumsum(int64_t dim, ScalarType dtype) const { return type().cumsum(*this, dim, dtype); } inline Tensor Tensor::cumsum(int64_t dim) const { return type().cumsum(*this, dim); } inline Tensor Tensor::cumprod(int64_t dim, ScalarType dtype) const { return type().cumprod(*this, dim, dtype); } inline Tensor Tensor::cumprod(int64_t dim) const { return type().cumprod(*this, dim); } inline Tensor Tensor::det() const { return type().det(*this); } inline Tensor Tensor::diag_embed(int64_t offset, int64_t dim1, int64_t dim2) const { return type().diag_embed(*this, offset, dim1, dim2); } inline Tensor Tensor::diagflat(int64_t offset) const { return type().diagflat(*this, offset); } inline Tensor Tensor::diagonal(int64_t offset, int64_t dim1, int64_t dim2) const { return type().diagonal(*this, offset, dim1, dim2); } inline Tensor Tensor::div(const Tensor & other) const { return type().div(*this, other); } inline Tensor & Tensor::div_(const Tensor & other) { return type().div_(*this, other); } inline Tensor Tensor::div(Scalar other) const { return type().div(*this, other); } inline Tensor & Tensor::div_(Scalar other) { return type().div_(*this, other); } inline Tensor Tensor::dot(const Tensor & tensor) const { return type().dot(*this, tensor); } inline Tensor & Tensor::resize_(IntList size) { return type().resize_(*this, size); } inline Tensor Tensor::erf() const { return type().erf(*this); } inline Tensor & Tensor::erf_() { return type().erf_(*this); } inline Tensor Tensor::erfc() const { return type().erfc(*this); } inline Tensor & Tensor::erfc_() { return type().erfc_(*this); } inline Tensor Tensor::exp() const { return type().exp(*this); } inline Tensor & Tensor::exp_() { return type().exp_(*this); } inline Tensor Tensor::expm1() const { return type().expm1(*this); } inline Tensor & Tensor::expm1_() { return type().expm1_(*this); } inline Tensor Tensor::expand(IntList size, bool implicit) const { return type().expand(*this, size, implicit); } inline Tensor Tensor::expand_as(const Tensor & other) const { return type().expand_as(*this, other); } inline Tensor Tensor::flatten(int64_t start_dim, int64_t end_dim) const { return type().flatten(*this, start_dim, end_dim); } inline Tensor & Tensor::fill_(Scalar value) { return type().fill_(*this, value); } inline Tensor & Tensor::fill_(const Tensor & value) { return type().fill_(*this, value); } inline Tensor Tensor::floor() const { return type().floor(*this); } inline Tensor & Tensor::floor_() { return type().floor_(*this); } inline Tensor Tensor::ger(const Tensor & vec2) const { return type().ger(*this, vec2); } inline std::tuple<Tensor,Tensor> Tensor::gesv(const Tensor & A) const { return type().gesv(*this, A); } inline Tensor Tensor::fft(int64_t signal_ndim, bool normalized) const { return type().fft(*this, signal_ndim, normalized); } inline Tensor Tensor::ifft(int64_t signal_ndim, bool normalized) const { return type().ifft(*this, signal_ndim, normalized); } inline Tensor Tensor::rfft(int64_t signal_ndim, bool normalized, bool onesided) const { return type().rfft(*this, signal_ndim, normalized, onesided); } inline Tensor Tensor::irfft(int64_t signal_ndim, bool normalized, bool onesided, IntList signal_sizes) const { return type().irfft(*this, signal_ndim, normalized, onesided, signal_sizes); } inline Tensor Tensor::index(TensorList indices) const { return type().index(*this, indices); } inline Tensor & Tensor::index_copy_(int64_t dim, const Tensor & index, const Tensor & source) { return type().index_copy_(*this, dim, index, source); } inline Tensor Tensor::index_put(TensorList indices, const Tensor & values, bool accumulate) const { return type().index_put(*this, indices, values, accumulate); } inline Tensor & Tensor::index_put_(TensorList indices, const Tensor & values, bool accumulate) { return type().index_put_(*this, indices, values, accumulate); } inline Tensor Tensor::inverse() const { return type().inverse(*this); } inline Tensor Tensor::isclose(const Tensor & other, double rtol, double atol, bool equal_nan) const { return type().isclose(*this, other, rtol, atol, equal_nan); } inline bool Tensor::is_distributed() const { return type().is_distributed(*this); } inline bool Tensor::is_floating_point() const { return type().is_floating_point(*this); } inline bool Tensor::is_complex() const { return type().is_complex(*this); } inline bool Tensor::is_nonzero() const { return type().is_nonzero(*this); } inline bool Tensor::is_same_size(const Tensor & other) const { return type().is_same_size(*this, other); } inline bool Tensor::is_signed() const { return type().is_signed(*this); } inline std::tuple<Tensor,Tensor> Tensor::kthvalue(int64_t k, int64_t dim, bool keepdim) const { return type().kthvalue(*this, k, dim, keepdim); } inline Tensor Tensor::log() const { return type().log(*this); } inline Tensor & Tensor::log_() { return type().log_(*this); } inline Tensor Tensor::log10() const { return type().log10(*this); } inline Tensor & Tensor::log10_() { return type().log10_(*this); } inline Tensor Tensor::log1p() const { return type().log1p(*this); } inline Tensor & Tensor::log1p_() { return type().log1p_(*this); } inline Tensor Tensor::log2() const { return type().log2(*this); } inline Tensor & Tensor::log2_() { return type().log2_(*this); } inline Tensor Tensor::logdet() const { return type().logdet(*this); } inline Tensor Tensor::log_softmax(int64_t dim, ScalarType dtype) const { return type().log_softmax(*this, dim, dtype); } inline Tensor Tensor::log_softmax(int64_t dim) const { return type().log_softmax(*this, dim); } inline Tensor Tensor::logsumexp(int64_t dim, bool keepdim) const { return type().logsumexp(*this, dim, keepdim); } inline Tensor Tensor::matmul(const Tensor & other) const { return type().matmul(*this, other); } inline Tensor Tensor::matrix_power(int64_t n) const { return type().matrix_power(*this, n); } inline std::tuple<Tensor,Tensor> Tensor::max(int64_t dim, bool keepdim) const { return type().max(*this, dim, keepdim); } inline Tensor Tensor::max_values(int64_t dim, bool keepdim) const { return type().max_values(*this, dim, keepdim); } inline Tensor Tensor::mean(ScalarType dtype) const { return type().mean(*this, dtype); } inline Tensor Tensor::mean() const { return type().mean(*this); } inline Tensor Tensor::mean(IntList dim, bool keepdim, ScalarType dtype) const { return type().mean(*this, dim, keepdim, dtype); } inline Tensor Tensor::mean(IntList dim, bool keepdim) const { return type().mean(*this, dim, keepdim); } inline Tensor Tensor::mean(IntList dim, ScalarType dtype) const { return type().mean(*this, dim, dtype); } inline std::tuple<Tensor,Tensor> Tensor::median(int64_t dim, bool keepdim) const { return type().median(*this, dim, keepdim); } inline std::tuple<Tensor,Tensor> Tensor::min(int64_t dim, bool keepdim) const { return type().min(*this, dim, keepdim); } inline Tensor Tensor::min_values(int64_t dim, bool keepdim) const { return type().min_values(*this, dim, keepdim); } inline Tensor Tensor::mm(const Tensor & mat2) const { return type().mm(*this, mat2); } inline std::tuple<Tensor,Tensor> Tensor::mode(int64_t dim, bool keepdim) const { return type().mode(*this, dim, keepdim); } inline Tensor Tensor::mul(const Tensor & other) const { return type().mul(*this, other); } inline Tensor & Tensor::mul_(const Tensor & other) { return type().mul_(*this, other); } inline Tensor Tensor::mul(Scalar other) const { return type().mul(*this, other); } inline Tensor & Tensor::mul_(Scalar other) { return type().mul_(*this, other); } inline Tensor Tensor::mv(const Tensor & vec) const { return type().mv(*this, vec); } inline Tensor Tensor::mvlgamma(int64_t p) const { return type().mvlgamma(*this, p); } inline Tensor & Tensor::mvlgamma_(int64_t p) { return type().mvlgamma_(*this, p); } inline Tensor Tensor::narrow_copy(int64_t dim, int64_t start, int64_t length) const { return type().narrow_copy(*this, dim, start, length); } inline Tensor Tensor::narrow(int64_t dim, int64_t start, int64_t length) const { return type().narrow(*this, dim, start, length); } inline Tensor Tensor::permute(IntList dims) const { return type().permute(*this, dims); } inline Tensor Tensor::pin_memory() const { return type().pin_memory(*this); } inline Tensor Tensor::pinverse(double rcond) const { return type().pinverse(*this, rcond); } inline Tensor Tensor::repeat(IntList repeats) const { return type().repeat(*this, repeats); } inline Tensor Tensor::reshape(IntList shape) const { return type().reshape(*this, shape); } inline Tensor Tensor::reshape_as(const Tensor & other) const { return type().reshape_as(*this, other); } inline Tensor Tensor::round() const { return type().round(*this); } inline Tensor & Tensor::round_() { return type().round_(*this); } inline Tensor Tensor::relu() const { return type().relu(*this); } inline Tensor & Tensor::relu_() { return type().relu_(*this); } inline Tensor Tensor::prelu(const Tensor & weight) const { return type().prelu(*this, weight); } inline std::tuple<Tensor,Tensor> Tensor::prelu_backward(const Tensor & grad_output, const Tensor & weight) const { return type().prelu_backward(grad_output, *this, weight); } inline Tensor Tensor::hardshrink(Scalar lambd) const { return type().hardshrink(*this, lambd); } inline Tensor Tensor::hardshrink_backward(const Tensor & grad_out, Scalar lambd) const { return type().hardshrink_backward(grad_out, *this, lambd); } inline Tensor Tensor::rsqrt() const { return type().rsqrt(*this); } inline Tensor & Tensor::rsqrt_() { return type().rsqrt_(*this); } inline Tensor Tensor::select(int64_t dim, int64_t index) const { return type().select(*this, dim, index); } inline Tensor Tensor::sigmoid() const { return type().sigmoid(*this); } inline Tensor & Tensor::sigmoid_() { return type().sigmoid_(*this); } inline Tensor Tensor::sin() const { return type().sin(*this); } inline Tensor & Tensor::sin_() { return type().sin_(*this); } inline Tensor Tensor::sinh() const { return type().sinh(*this); } inline Tensor & Tensor::sinh_() { return type().sinh_(*this); } inline Tensor Tensor::detach() const { return type().detach(*this); } inline Tensor & Tensor::detach_() { return type().detach_(*this); } inline int64_t Tensor::size(int64_t dim) const { return type().size(*this, dim); } inline Tensor Tensor::slice(int64_t dim, int64_t start, int64_t end, int64_t step) const { return type().slice(*this, dim, start, end, step); } inline std::tuple<Tensor,Tensor> Tensor::slogdet() const { return type().slogdet(*this); } inline Tensor Tensor::smm(const Tensor & mat2) const { return type().smm(*this, mat2); } inline Tensor Tensor::softmax(int64_t dim, ScalarType dtype) const { return type().softmax(*this, dim, dtype); } inline Tensor Tensor::softmax(int64_t dim) const { return type().softmax(*this, dim); } inline std::vector<Tensor> Tensor::split(int64_t split_size, int64_t dim) const { return type().split(*this, split_size, dim); } inline std::vector<Tensor> Tensor::split_with_sizes(IntList split_sizes, int64_t dim) const { return type().split_with_sizes(*this, split_sizes, dim); } inline Tensor Tensor::squeeze() const { return type().squeeze(*this); } inline Tensor Tensor::squeeze(int64_t dim) const { return type().squeeze(*this, dim); } inline Tensor & Tensor::squeeze_() { return type().squeeze_(*this); } inline Tensor & Tensor::squeeze_(int64_t dim) { return type().squeeze_(*this, dim); } inline Tensor Tensor::sspaddmm(const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const { return type().sspaddmm(*this, mat1, mat2, beta, alpha); } inline Tensor Tensor::stft(int64_t n_fft, int64_t hop_length, int64_t win_length, const Tensor & window, bool normalized, bool onesided) const { return type().stft(*this, n_fft, hop_length, win_length, window, normalized, onesided); } inline int64_t Tensor::stride(int64_t dim) const { return type().stride(*this, dim); } inline Tensor Tensor::sum(ScalarType dtype) const { return type().sum(*this, dtype); } inline Tensor Tensor::sum() const { return type().sum(*this); } inline Tensor Tensor::sum(IntList dim, bool keepdim, ScalarType dtype) const { return type().sum(*this, dim, keepdim, dtype); } inline Tensor Tensor::sum(IntList dim, bool keepdim) const { return type().sum(*this, dim, keepdim); } inline Tensor Tensor::sum(IntList dim, ScalarType dtype) const { return type().sum(*this, dim, dtype); } inline Tensor Tensor::sqrt() const { return type().sqrt(*this); } inline Tensor & Tensor::sqrt_() { return type().sqrt_(*this); } inline Tensor Tensor::std(bool unbiased) const { return type().std(*this, unbiased); } inline Tensor Tensor::std(IntList dim, bool unbiased, bool keepdim) const { return type().std(*this, dim, unbiased, keepdim); } inline Tensor Tensor::prod(ScalarType dtype) const { return type().prod(*this, dtype); } inline Tensor Tensor::prod() const { return type().prod(*this); } inline Tensor Tensor::prod(int64_t dim, bool keepdim, ScalarType dtype) const { return type().prod(*this, dim, keepdim, dtype); } inline Tensor Tensor::prod(int64_t dim, bool keepdim) const { return type().prod(*this, dim, keepdim); } inline Tensor Tensor::prod(int64_t dim, ScalarType dtype) const { return type().prod(*this, dim, dtype); } inline Tensor Tensor::t() const { return type().t(*this); } inline Tensor & Tensor::t_() { return type().t_(*this); } inline Tensor Tensor::tan() const { return type().tan(*this); } inline Tensor & Tensor::tan_() { return type().tan_(*this); } inline Tensor Tensor::tanh() const { return type().tanh(*this); } inline Tensor & Tensor::tanh_() { return type().tanh_(*this); } inline Tensor Tensor::transpose(int64_t dim0, int64_t dim1) const { return type().transpose(*this, dim0, dim1); } inline Tensor & Tensor::transpose_(int64_t dim0, int64_t dim1) { return type().transpose_(*this, dim0, dim1); } inline Tensor Tensor::flip(IntList dims) const { return type().flip(*this, dims); } inline Tensor Tensor::roll(IntList shifts, IntList dims) const { return type().roll(*this, shifts, dims); } inline Tensor Tensor::rot90(int64_t k, IntList dims) const { return type().rot90(*this, k, dims); } inline Tensor Tensor::trunc() const { return type().trunc(*this); } inline Tensor & Tensor::trunc_() { return type().trunc_(*this); } inline Tensor Tensor::type_as(const Tensor & other) const { return type().type_as(*this, other); } inline Tensor Tensor::unsqueeze(int64_t dim) const { return type().unsqueeze(*this, dim); } inline Tensor & Tensor::unsqueeze_(int64_t dim) { return type().unsqueeze_(*this, dim); } inline Tensor Tensor::var(bool unbiased) const { return type().var(*this, unbiased); } inline Tensor Tensor::var(int64_t dim, bool unbiased, bool keepdim) const { return type().var(*this, dim, unbiased, keepdim); } inline Tensor Tensor::view_as(const Tensor & other) const { return type().view_as(*this, other); } inline Tensor Tensor::where(const Tensor & condition, const Tensor & other) const { return type().where(condition, *this, other); } inline Tensor Tensor::norm(Scalar p) const { return type().norm(*this, p); } inline Tensor Tensor::norm(Scalar p, int64_t dim, bool keepdim) const { return type().norm(*this, p, dim, keepdim); } inline Tensor Tensor::clone() const { return type().clone(*this); } inline Tensor & Tensor::resize_as_(const Tensor & the_template) { return type().resize_as_(*this, the_template); } inline Tensor Tensor::pow(Scalar exponent) const { return type().pow(*this, exponent); } inline Tensor & Tensor::zero_() { return type().zero_(*this); } inline Tensor Tensor::sub(const Tensor & other, Scalar alpha) const { return type().sub(*this, other, alpha); } inline Tensor & Tensor::sub_(const Tensor & other, Scalar alpha) { return type().sub_(*this, other, alpha); } inline Tensor Tensor::sub(Scalar other, Scalar alpha) const { return type().sub(*this, other, alpha); } inline Tensor & Tensor::sub_(Scalar other, Scalar alpha) { return type().sub_(*this, other, alpha); } inline Tensor Tensor::addmm(const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) const { return type().addmm(*this, mat1, mat2, beta, alpha); } inline Tensor & Tensor::addmm_(const Tensor & mat1, const Tensor & mat2, Scalar beta, Scalar alpha) { return type().addmm_(*this, mat1, mat2, beta, alpha); } inline Tensor & Tensor::sparse_resize_(IntList size, int64_t sparse_dim, int64_t dense_dim) { return type().sparse_resize_(*this, size, sparse_dim, dense_dim); } inline Tensor & Tensor::sparse_resize_and_clear_(IntList size, int64_t sparse_dim, int64_t dense_dim) { return type().sparse_resize_and_clear_(*this, size, sparse_dim, dense_dim); } inline Tensor Tensor::sparse_mask(SparseTensorRef mask) const { return type().sparse_mask(*this, mask); } inline Tensor Tensor::to_dense() const { return type().to_dense(*this); } inline int64_t Tensor::sparse_dim() const { return type().sparse_dim(*this); } inline int64_t Tensor::_dimI() const { return type()._dimI(*this); } inline int64_t Tensor::dense_dim() const { return type().dense_dim(*this); } inline int64_t Tensor::_dimV() const { return type()._dimV(*this); } inline int64_t Tensor::_nnz() const { return type()._nnz(*this); } inline Tensor Tensor::coalesce() const { return type().coalesce(*this); } inline bool Tensor::is_coalesced() const { return type().is_coalesced(*this); } inline Tensor Tensor::_indices() const { return type()._indices(*this); } inline Tensor Tensor::_values() const { return type()._values(*this); } inline Tensor & Tensor::_coalesced_(bool coalesced) { return type()._coalesced_(*this, coalesced); } inline Tensor Tensor::indices() const { return type().indices(*this); } inline Tensor Tensor::values() const { return type().values(*this); } inline int64_t Tensor::numel() const { return type().numel(*this); } inline std::vector<Tensor> Tensor::unbind(int64_t dim) const { return type().unbind(*this, dim); } inline Tensor Tensor::to_sparse(int64_t sparse_dim) const { return type().to_sparse(*this, sparse_dim); } inline Tensor Tensor::to_sparse() const { return type().to_sparse(*this); } inline Tensor Tensor::to(const TensorOptions & options, bool non_blocking, bool copy) const { return type().to(*this, options, non_blocking, copy); } inline Tensor Tensor::to(Device device, ScalarType dtype, bool non_blocking, bool copy) const { return type().to(*this, device, dtype, non_blocking, copy); } inline Tensor Tensor::to(ScalarType dtype, bool non_blocking, bool copy) const { return type().to(*this, dtype, non_blocking, copy); } inline Tensor Tensor::to(const Tensor & other, bool non_blocking, bool copy) const { return type().to(*this, other, non_blocking, copy); } inline Scalar Tensor::item() const { return type().item(*this); } inline void* Tensor::data_ptr() const { return type().data_ptr(*this); } inline Tensor & Tensor::set_(Storage source) { return type().set_(*this, source); } inline Tensor & Tensor::set_(Storage source, int64_t storage_offset, IntList size, IntList stride) { return type().set_(*this, source, storage_offset, size, stride); } inline Tensor & Tensor::set_(const Tensor & source) { return type().set_(*this, source); } inline Tensor & Tensor::set_() { return type().set_(*this); } inline bool Tensor::is_set_to(const Tensor & tensor) const { return type().is_set_to(*this, tensor); } inline Tensor & Tensor::masked_fill_(const Tensor & mask, Scalar value) { return type().masked_fill_(*this, mask, value); } inline Tensor & Tensor::masked_fill_(const Tensor & mask, const Tensor & value) { return type().masked_fill_(*this, mask, value); } inline Tensor & Tensor::masked_scatter_(const Tensor & mask, const Tensor & source) { return type().masked_scatter_(*this, mask, source); } inline Tensor Tensor::view(IntList size) const { return type().view(*this, size); } inline Tensor & Tensor::put_(const Tensor & index, const Tensor & source, bool accumulate) { return type().put_(*this, index, source, accumulate); } inline Tensor & Tensor::index_add_(int64_t dim, const Tensor & index, const Tensor & source) { return type().index_add_(*this, dim, index, source); } inline Tensor & Tensor::index_fill_(int64_t dim, const Tensor & index, Scalar value) { return type().index_fill_(*this, dim, index, value); } inline Tensor & Tensor::index_fill_(int64_t dim, const Tensor & index, const Tensor & value) { return type().index_fill_(*this, dim, index, value); } inline Tensor & Tensor::scatter_(int64_t dim, const Tensor & index, const Tensor & src) { return type().scatter_(*this, dim, index, src); } inline Tensor & Tensor::scatter_(int64_t dim, const Tensor & index, Scalar value) { return type().scatter_(*this, dim, index, value); } inline Tensor & Tensor::scatter_add_(int64_t dim, const Tensor & index, const Tensor & src) { return type().scatter_add_(*this, dim, index, src); } inline Tensor & Tensor::lt_(Scalar other) { return type().lt_(*this, other); } inline Tensor & Tensor::lt_(const Tensor & other) { return type().lt_(*this, other); } inline Tensor & Tensor::gt_(Scalar other) { return type().gt_(*this, other); } inline Tensor & Tensor::gt_(const Tensor & other) { return type().gt_(*this, other); } inline Tensor & Tensor::le_(Scalar other) { return type().le_(*this, other); } inline Tensor & Tensor::le_(const Tensor & other) { return type().le_(*this, other); } inline Tensor & Tensor::ge_(Scalar other) { return type().ge_(*this, other); } inline Tensor & Tensor::ge_(const Tensor & other) { return type().ge_(*this, other); } inline Tensor & Tensor::eq_(Scalar other) { return type().eq_(*this, other); } inline Tensor & Tensor::eq_(const Tensor & other) { return type().eq_(*this, other); } inline Tensor & Tensor::ne_(Scalar other) { return type().ne_(*this, other); } inline Tensor & Tensor::ne_(const Tensor & other) { return type().ne_(*this, other); } inline Tensor Tensor::__and__(Scalar other) const { return type().__and__(*this, other); } inline Tensor Tensor::__and__(const Tensor & other) const { return type().__and__(*this, other); } inline Tensor & Tensor::__iand__(Scalar other) { return type().__iand__(*this, other); } inline Tensor & Tensor::__iand__(const Tensor & other) { return type().__iand__(*this, other); } inline Tensor Tensor::__or__(Scalar other) const { return type().__or__(*this, other); } inline Tensor Tensor::__or__(const Tensor & other) const { return type().__or__(*this, other); } inline Tensor & Tensor::__ior__(Scalar other) { return type().__ior__(*this, other); } inline Tensor & Tensor::__ior__(const Tensor & other) { return type().__ior__(*this, other); } inline Tensor Tensor::__xor__(Scalar other) const { return type().__xor__(*this, other); } inline Tensor Tensor::__xor__(const Tensor & other) const { return type().__xor__(*this, other); } inline Tensor & Tensor::__ixor__(Scalar other) { return type().__ixor__(*this, other); } inline Tensor & Tensor::__ixor__(const Tensor & other) { return type().__ixor__(*this, other); } inline Tensor Tensor::__lshift__(Scalar other) const { return type().__lshift__(*this, other); } inline Tensor Tensor::__lshift__(const Tensor & other) const { return type().__lshift__(*this, other); } inline Tensor & Tensor::__ilshift__(Scalar other) { return type().__ilshift__(*this, other); } inline Tensor & Tensor::__ilshift__(const Tensor & other) { return type().__ilshift__(*this, other); } inline Tensor Tensor::__rshift__(Scalar other) const { return type().__rshift__(*this, other); } inline Tensor Tensor::__rshift__(const Tensor & other) const { return type().__rshift__(*this, other); } inline Tensor & Tensor::__irshift__(Scalar other) { return type().__irshift__(*this, other); } inline Tensor & Tensor::__irshift__(const Tensor & other) { return type().__irshift__(*this, other); } inline Tensor & Tensor::lgamma_() { return type().lgamma_(*this); } inline Tensor & Tensor::atan2_(const Tensor & other) { return type().atan2_(*this, other); } inline Tensor & Tensor::tril_(int64_t diagonal) { return type().tril_(*this, diagonal); } inline Tensor & Tensor::triu_(int64_t diagonal) { return type().triu_(*this, diagonal); } inline Tensor & Tensor::digamma_() { return type().digamma_(*this); } inline Tensor & Tensor::polygamma_(int64_t n) { return type().polygamma_(*this, n); } inline Tensor & Tensor::erfinv_() { return type().erfinv_(*this); } inline Tensor & Tensor::frac_() { return type().frac_(*this); } inline Tensor & Tensor::renorm_(Scalar p, int64_t dim, Scalar maxnorm) { return type().renorm_(*this, p, dim, maxnorm); } inline Tensor & Tensor::reciprocal_() { return type().reciprocal_(*this); } inline Tensor & Tensor::neg_() { return type().neg_(*this); } inline Tensor & Tensor::pow_(Scalar exponent) { return type().pow_(*this, exponent); } inline Tensor & Tensor::pow_(const Tensor & exponent) { return type().pow_(*this, exponent); } inline Tensor & Tensor::lerp_(const Tensor & end, Scalar weight) { return type().lerp_(*this, end, weight); } inline Tensor & Tensor::sign_() { return type().sign_(*this); } inline Tensor & Tensor::fmod_(Scalar other) { return type().fmod_(*this, other); } inline Tensor & Tensor::fmod_(const Tensor & other) { return type().fmod_(*this, other); } inline Tensor & Tensor::remainder_(Scalar other) { return type().remainder_(*this, other); } inline Tensor & Tensor::remainder_(const Tensor & other) { return type().remainder_(*this, other); } inline Tensor & Tensor::addbmm_(const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) { return type().addbmm_(*this, batch1, batch2, beta, alpha); } inline Tensor Tensor::addbmm(const Tensor & batch1, const Tensor & batch2, Scalar beta, Scalar alpha) const { return type().addbmm(*this, batch1, batch2, beta, alpha); } inline Tensor & Tensor::addcmul_(const Tensor & tensor1, const Tensor & tensor2, Scalar value) { return type().addcmul_(*this, tensor1, tensor2, value); } inline Tensor & Tensor::addcdiv_(const Tensor & tensor1, const Tensor & tensor2, Scalar value) { return type().addcdiv_(*this, tensor1, tensor2, value); } inline Tensor & Tensor::random_(int64_t from, int64_t to, Generator * generator) { return type().random_(*this, from, to, generator); } inline Tensor & Tensor::random_(int64_t to, Generator * generator) { return type().random_(*this, to, generator); } inline Tensor & Tensor::random_(Generator * generator) { return type().random_(*this, generator); } inline Tensor & Tensor::uniform_(double from, double to, Generator * generator) { return type().uniform_(*this, from, to, generator); } inline Tensor & Tensor::normal_(double mean, double std, Generator * generator) { return type().normal_(*this, mean, std, generator); } inline Tensor & Tensor::cauchy_(double median, double sigma, Generator * generator) { return type().cauchy_(*this, median, sigma, generator); } inline Tensor & Tensor::log_normal_(double mean, double std, Generator * generator) { return type().log_normal_(*this, mean, std, generator); } inline Tensor & Tensor::exponential_(double lambd, Generator * generator) { return type().exponential_(*this, lambd, generator); } inline Tensor & Tensor::geometric_(double p, Generator * generator) { return type().geometric_(*this, p, generator); } inline Tensor Tensor::diag(int64_t diagonal) const { return type().diag(*this, diagonal); } inline Tensor Tensor::cross(const Tensor & other, int64_t dim) const { return type().cross(*this, other, dim); } inline Tensor Tensor::triu(int64_t diagonal) const { return type().triu(*this, diagonal); } inline Tensor Tensor::tril(int64_t diagonal) const { return type().tril(*this, diagonal); } inline Tensor Tensor::trace() const { return type().trace(*this); } inline Tensor Tensor::ne(Scalar other) const { return type().ne(*this, other); } inline Tensor Tensor::ne(const Tensor & other) const { return type().ne(*this, other); } inline Tensor Tensor::eq(Scalar other) const { return type().eq(*this, other); } inline Tensor Tensor::eq(const Tensor & other) const { return type().eq(*this, other); } inline Tensor Tensor::ge(Scalar other) const { return type().ge(*this, other); } inline Tensor Tensor::ge(const Tensor & other) const { return type().ge(*this, other); } inline Tensor Tensor::le(Scalar other) const { return type().le(*this, other); } inline Tensor Tensor::le(const Tensor & other) const { return type().le(*this, other); } inline Tensor Tensor::gt(Scalar other) const { return type().gt(*this, other); } inline Tensor Tensor::gt(const Tensor & other) const { return type().gt(*this, other); } inline Tensor Tensor::lt(Scalar other) const { return type().lt(*this, other); } inline Tensor Tensor::lt(const Tensor & other) const { return type().lt(*this, other); } inline Tensor Tensor::take(const Tensor & index) const { return type().take(*this, index); } inline Tensor Tensor::index_select(int64_t dim, const Tensor & index) const { return type().index_select(*this, dim, index); } inline Tensor Tensor::masked_select(const Tensor & mask) const { return type().masked_select(*this, mask); } inline Tensor Tensor::nonzero() const { return type().nonzero(*this); } inline Tensor Tensor::gather(int64_t dim, const Tensor & index) const { return type().gather(*this, dim, index); } inline Tensor Tensor::addcmul(const Tensor & tensor1, const Tensor & tensor2, Scalar value) const { return type().addcmul(*this, tensor1, tensor2, value); } inline Tensor Tensor::addcdiv(const Tensor & tensor1, const Tensor & tensor2, Scalar value) const { return type().addcdiv(*this, tensor1, tensor2, value); } inline std::tuple<Tensor,Tensor> Tensor::gels(const Tensor & A) const { return type().gels(*this, A); } inline std::tuple<Tensor,Tensor> Tensor::trtrs(const Tensor & A, bool upper, bool transpose, bool unitriangular) const { return type().trtrs(*this, A, upper, transpose, unitriangular); } inline std::tuple<Tensor,Tensor> Tensor::symeig(bool eigenvectors, bool upper) const { return type().symeig(*this, eigenvectors, upper); } inline std::tuple<Tensor,Tensor> Tensor::eig(bool eigenvectors) const { return type().eig(*this, eigenvectors); } inline std::tuple<Tensor,Tensor,Tensor> Tensor::svd(bool some, bool compute_uv) const { return type().svd(*this, some, compute_uv); } inline Tensor Tensor::cholesky(bool upper) const { return type().cholesky(*this, upper); } inline Tensor Tensor::potrs(const Tensor & input2, bool upper) const { return type().potrs(*this, input2, upper); } inline Tensor Tensor::potri(bool upper) const { return type().potri(*this, upper); } inline std::tuple<Tensor,Tensor> Tensor::pstrf(bool upper, Scalar tol) const { return type().pstrf(*this, upper, tol); } inline std::tuple<Tensor,Tensor> Tensor::qr() const { return type().qr(*this); } inline std::tuple<Tensor,Tensor> Tensor::geqrf() const { return type().geqrf(*this); } inline Tensor Tensor::orgqr(const Tensor & input2) const { return type().orgqr(*this, input2); } inline Tensor Tensor::ormqr(const Tensor & input2, const Tensor & input3, bool left, bool transpose) const { return type().ormqr(*this, input2, input3, left, transpose); } inline std::tuple<Tensor,Tensor> Tensor::btrifact(bool pivot) const { return type().btrifact(*this, pivot); } inline std::tuple<Tensor,Tensor,Tensor> Tensor::btrifact_with_info(bool pivot) const { return type().btrifact_with_info(*this, pivot); } inline Tensor Tensor::btrisolve(const Tensor & LU_data, const Tensor & LU_pivots) const { return type().btrisolve(*this, LU_data, LU_pivots); } inline Tensor Tensor::multinomial(int64_t num_samples, bool replacement, Generator * generator) const { return type().multinomial(*this, num_samples, replacement, generator); } inline Tensor Tensor::lgamma() const { return type().lgamma(*this); } inline Tensor Tensor::digamma() const { return type().digamma(*this); } inline Tensor Tensor::polygamma(int64_t n) const { return type().polygamma(n, *this); } inline Tensor Tensor::erfinv() const { return type().erfinv(*this); } inline Tensor Tensor::frac() const { return type().frac(*this); } inline Tensor Tensor::dist(const Tensor & other, Scalar p) const { return type().dist(*this, other, p); } inline Tensor Tensor::reciprocal() const { return type().reciprocal(*this); } inline Tensor Tensor::neg() const { return type().neg(*this); } inline Tensor Tensor::atan2(const Tensor & other) const { return type().atan2(*this, other); } inline Tensor Tensor::lerp(const Tensor & end, Scalar weight) const { return type().lerp(*this, end, weight); } inline Tensor Tensor::histc(int64_t bins, Scalar min, Scalar max) const { return type().histc(*this, bins, min, max); } inline Tensor Tensor::sign() const { return type().sign(*this); } inline Tensor Tensor::fmod(Scalar other) const { return type().fmod(*this, other); } inline Tensor Tensor::fmod(const Tensor & other) const { return type().fmod(*this, other); } inline Tensor Tensor::remainder(Scalar other) const { return type().remainder(*this, other); } inline Tensor Tensor::remainder(const Tensor & other) const { return type().remainder(*this, other); } inline Tensor Tensor::min(const Tensor & other) const { return type().min(*this, other); } inline Tensor Tensor::min() const { return type().min(*this); } inline Tensor Tensor::max(const Tensor & other) const { return type().max(*this, other); } inline Tensor Tensor::max() const { return type().max(*this); } inline Tensor Tensor::median() const { return type().median(*this); } inline std::tuple<Tensor,Tensor> Tensor::sort(int64_t dim, bool descending) const { return type().sort(*this, dim, descending); } inline std::tuple<Tensor,Tensor> Tensor::topk(int64_t k, int64_t dim, bool largest, bool sorted) const { return type().topk(*this, k, dim, largest, sorted); } inline Tensor Tensor::all() const { return type().all(*this); } inline Tensor Tensor::any() const { return type().any(*this); } inline Tensor Tensor::renorm(Scalar p, int64_t dim, Scalar maxnorm) const { return type().renorm(*this, p, dim, maxnorm); } inline Tensor Tensor::unfold(int64_t dimension, int64_t size, int64_t step) const { return type().unfold(*this, dimension, size, step); } inline bool Tensor::equal(const Tensor & other) const { return type().equal(*this, other); } inline Tensor Tensor::pow(const Tensor & exponent) const { return type().pow(*this, exponent); } inline Tensor Tensor::alias() const { return type().alias(*this); } inline bool Tensor::is_variable() const noexcept { return impl_->is_variable(); } inline caffe2::TypeMeta Tensor::dtype() const noexcept { return impl_->dtype(); } inline Layout Tensor::layout() const noexcept { return impl_->layout(); } inline Device Tensor::device() const { return impl_->device(); } inline int64_t Tensor::get_device() const { // NB: this is not a native function to avoid dispatching overhead. return impl_->get_device(); } inline int64_t get_device(Tensor self) { return self.get_device(); } inline bool Tensor::is_cuda() const { // NB: this is not a native function to avoid dispatching overhead. return impl_->is_cuda(); } inline bool is_cuda(Tensor self) { return self.is_cuda(); } inline bool Tensor::is_hip() const { // NB: this is not a native function to avoid dispatching overhead. return impl_->is_hip(); } inline bool is_hip(Tensor self) { return self.is_hip(); } inline bool Tensor::is_sparse() const { // NB: this is not a native function to avoid dispatching overhead. return impl_->is_sparse(); } inline bool is_sparse(Tensor self) { return self.is_sparse(); } #define DEFINE_CAST(T, name, _) \ template <> \ inline T* Tensor::data() const { \ AT_CHECK( \ type().scalarType() == ScalarType::name, \ "expected scalar type ", \ #name, \ " but found ", \ c10::toString(type().scalarType())); \ return static_cast<T*>(this->data_ptr()); \ } AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_EXCEPT_COMPLEX_HALF(DEFINE_CAST) #undef DEFINE_CAST #define DEFINE_ITEM(T, name, _) \ template <> \ inline T Tensor::item() const { \ return item().to##name(); \ } AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_EXCEPT_COMPLEX_HALF(DEFINE_ITEM) #undef DEFINE_ITEM } //namespace at
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
f56f311b614b01cc709ec3c34a9adcb08d600755
d57acff08a839ba3c8adeaedf7b4b1843e7e39cf
/KDE/salut/main.cpp
337fa7413c511c45c39b73a826296eb52a5ad6f0
[ "MIT" ]
permissive
mhcrnl/2018Q1
3ba77bdcf62b1aedab2d20f87d82dc842b083380
2dfa39ba03c5c03973b4d9aeb068810a03e9dda9
refs/heads/master
2021-09-10T12:41:28.973710
2018-03-26T12:41:20
2018-03-26T12:41:20
115,506,780
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
#include <QApplication> #include "salut.h" int main(int argc, char** argv) { QApplication app(argc, argv); salut salut; salut.show(); return app.exec(); }
[ "mhcrnl@gmail.com" ]
mhcrnl@gmail.com
f170751050afd85aff0ca3e3c18e2f43a039b296
0ffc6574bb9c445daac18e9f194017ad8421bec1
/Coursera/C++Specialization/CourseraYellowBelt/FinalTask/test_runner.h
d6fe5b091d14df1683dc72066c4edcc403021044
[]
no_license
LeonidK1974/repo
d546ba9f23cc7aab1759b93cb74c3732a8729ed1
84d04e335f41eccb9fa0b09401f2a9b41a4ad816
refs/heads/master
2021-03-13T12:02:54.937223
2020-09-10T18:36:52
2020-09-10T18:36:52
246,679,395
0
0
null
2020-09-10T18:36:53
2020-03-11T21:02:17
C++
UTF-8
C++
false
false
1,741
h
#pragma once #include <iostream> #include <map> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <vector> using namespace std; template <class T> ostream& operator<<(ostream& os, const vector<T>& s) { os << "{"; bool first = true; for (const auto& x : s) { if (!first) { os << ", "; } first = false; os << x; } return os << "}"; } template <class T> ostream& operator<<(ostream& os, const set<T>& s) { os << "{"; bool first = true; for (const auto& x : s) { if (!first) { os << ", "; } first = false; os << x; } return os << "}"; } template <class K, class V> ostream& operator<<(ostream& os, const map<K, V>& m) { os << "{"; bool first = true; for (const auto& kv : m) { if (!first) { os << ", "; } first = false; os << kv.first << ": " << kv.second; } return os << "}"; } template <class T, class U> void AssertEqual(const T& t, const U& u, const string& hint = {}) { if (t != u) { ostringstream os; os << "Assertion failed: " << t << " != " << u; if (!hint.empty()) { os << " hint: " << hint; } throw runtime_error(os.str()); } } inline void Assert(bool b, const string& hint) { AssertEqual(b, true, hint); } class TestRunner { public: template <class TestFunc> void RunTest(TestFunc func, const string& test_name) { try { func(); cerr << test_name << " OK" << endl; } catch (exception& e) { ++fail_count; cerr << test_name << " fail: " << e.what() << endl; } catch (...) { ++fail_count; cerr << "Unknown exception caught" << endl; } } ~TestRunner() { if (fail_count > 0) { cerr << fail_count << " unit tests failed. Terminate" << endl; exit(1); } } private: int fail_count = 0; };
[ "leonid.i.kudryavtsev@gmail.com" ]
leonid.i.kudryavtsev@gmail.com
20b95e192fffa05f8d67d53c79911a4a22bf8b60
3f409e358ead9565dcbe1eedcc2eedbb939fe503
/contest/weekly-contest-156/problems/5208.minimum-moves-to-reach-target-with-rotations/5208.minimum-moves-to-reach-target-with-rotations.cpp
eae552de583cfb95bafce4131fa705c3cf390da2
[]
no_license
jimsoftyi/leetcode-cn
226be2d2a96dff31a7153a019909bea7aa48f78e
ac386bb287ef27ad84149718b6bc49704d072d17
refs/heads/master
2020-08-06T13:46:13.838553
2019-10-04T10:45:13
2019-10-04T10:45:13
212,997,092
1
0
null
2019-10-05T12:39:20
2019-10-05T12:39:20
null
UTF-8
C++
false
false
1,729
cpp
// 5208.minimum-moves-to-reach-target-with-rotations.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include <windows.h> #include <algorithm> #include <array> #include <map> #include <unordered_map> #include <unordered_set> #include <vector> #include <queue> #include <deque> #include <set> #include <stack> #include <list> #include <string> #include <random> #include <bitset> #include <sstream> #include "..\Common\Common.h" using namespace std; ////////////////////////////////////////////////////////////////////////// int minimumMoves(vector<vector<int>>& grid) { } int main() { double time = 0; LARGE_INTEGER nFreq; LARGE_INTEGER nBeginTime; LARGE_INTEGER nEndTime; QueryPerformanceFrequency(&nFreq); auto f_time_cout = [&]() { time = (double)(nEndTime.QuadPart - nBeginTime.QuadPart) / (double)nFreq.QuadPart; cout << "////////////////////////////////////////////////////////// time: " << time * 1000 << "ms" << endl; }; ////////////////////////////////////////////////////////////////////////// vector<vector<vector<int>>> TESTS; vector<int> ANSWERS; TESTS.push_back({ {0,0,0,0,0,1},{1,1,0,0,1,0},{0,0,0,0,1,1},{0,0,1,0,1,0},{0,1,1,0,0,0},{0,1,1,0,0,0} }); ANSWERS.push_back(11); TESTS.push_back({ {0,0,1,1,1,1},{0,0,0,0,1,1},{1,1,0,0,0,1},{1,1,1,0,0,1},{1,1,1,0,0,1},{1,1,1,0,0,0} }); ANSWERS.push_back(9); for (int i = 0; i < TESTS.size(); i++) { QueryPerformanceCounter(&nBeginTime); cout << endl << "/////////////////////////////" << endl; auto ans = minimumMoves(TESTS[i]); cout << checkAnswer<decltype(ans)>(ans, ANSWERS[i]) << endl; QueryPerformanceCounter(&nEndTime); f_time_cout(); } }
[ "ahjo_bb@hotmail.com" ]
ahjo_bb@hotmail.com
eddf66ad463f40088c4610f8f070c6dc61a095b7
d2249116413e870d8bf6cd133ae135bc52021208
/MFC CodeGuru/shell/appbar_project/TaskBar.h
b9564097bc2258151d246bba93fe26b5db10a14f
[]
no_license
Unknow-man/mfc-4
ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5
b58abf9eb4c6d90ef01b9f1203b174471293dfba
refs/heads/master
2023-02-17T18:22:09.276673
2021-01-20T07:46:14
2021-01-20T07:46:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,343
h
// TaskBar.h : main header file for the TASKBAR application // #if !defined(AFX_TASKBAR_H__9089251D_A8C8_11D1_B257_006097960BB7__INCLUDED_) #define AFX_TASKBAR_H__9089251D_A8C8_11D1_B257_006097960BB7__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CTaskBarApp: // See TaskBar.cpp for the implementation of this class // class CTaskBarApp : public CWinApp { public: CTaskBarApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTaskBarApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CTaskBarApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_TASKBAR_H__9089251D_A8C8_11D1_B257_006097960BB7__INCLUDED_)
[ "chenchao0632@163.com" ]
chenchao0632@163.com
05e7c911210c92e1e76a5d8a1f83a378b0312db5
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/content/browser/renderer_host/renderer_sandboxed_process_launcher_delegate.h
00038da2c15696b361aea1469ccf73307e44963e
[ "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
2,331
h
// 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. #ifndef CONTENT_BROWSER_RENDERER_HOST_RENDERER_SANDBOXED_PROCESS_LAUNCHER_DELEGATE_H_ #define CONTENT_BROWSER_RENDERER_HOST_RENDERER_SANDBOXED_PROCESS_LAUNCHER_DELEGATE_H_ #include "base/command_line.h" #include "build/build_config.h" #include "content/common/content_export.h" #include "content/public/common/sandboxed_process_launcher_delegate.h" #include "sandbox/policy/mojom/sandbox.mojom.h" namespace content { // NOTE: changes to this class need to be reviewed by the security team. class CONTENT_EXPORT RendererSandboxedProcessLauncherDelegate : public SandboxedProcessLauncherDelegate { public: RendererSandboxedProcessLauncherDelegate() = default; ~RendererSandboxedProcessLauncherDelegate() override = default; #if BUILDFLAG(USE_ZYGOTE) ZygoteCommunication* GetZygote() override; #endif // BUILDFLAG(USE_ZYGOTE) #if BUILDFLAG(IS_MAC) bool EnableCpuSecurityMitigations() override; #endif // BUILDFLAG(IS_MAC) // sandbox::policy::SandboxDelegate: sandbox::mojom::Sandbox GetSandboxType() override; }; #if BUILDFLAG(IS_WIN) // NOTE: changes to this class need to be reviewed by the security team. class CONTENT_EXPORT RendererSandboxedProcessLauncherDelegateWin : public RendererSandboxedProcessLauncherDelegate { public: RendererSandboxedProcessLauncherDelegateWin(const base::CommandLine& cmd_line, bool is_pdf_renderer, bool is_jit_disabled); // sandbox::policy::SandboxDelegate: std::string GetSandboxTag() override; bool InitializeConfig(sandbox::TargetConfig* config) override; void PostSpawnTarget(base::ProcessHandle process) override; bool CetCompatible() override; bool AllowWindowsFontsDir() override; // SandboxedProcessLauncherDelegate: bool ShouldUseUntrustedMojoInvitation() override; private: const bool renderer_code_integrity_enabled_; const bool renderer_app_container_disabled_; const bool is_pdf_renderer_ = false; bool dynamic_code_can_be_disabled_ = false; }; #endif // BUILDFLAG(IS_WIN) } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_RENDERER_SANDBOXED_PROCESS_LAUNCHER_DELEGATE_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
854692bde6ce9191a259f6b442c3fb1f924cdc72
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/range/adaptor/tokenized.hpp
96485f1c9210c14130903288434aa1b6fd7f3c9a
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:a69b381ac8b5615e1e63fe05250b259f37a624f89bc2fd2f6cd2317e02b15ebe size 4710
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
709ff7db98a22c914138d061a60ec45ae2ec4da1
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+ctrlisb-[fr-rf]-addr-ctrl.c.cbmc_out.cpp
d8144bf5f17d5fb1fa45e5b985223868540c6e56
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
60,255
cpp
// 0:vars:4 // 6:atom_1_X4_1:1 // 4:atom_1_X0_1:1 // 5:atom_1_X2_0:1 // 7:atom_1_X8_0:1 // 8:thr0:1 // 9:thr1:1 // 10:thr2:1 #define ADDRSIZE 11 #define NPROC 4 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; int r0= 0; char creg_r0; int r1= 0; char creg_r1; int r2= 0; char creg_r2; int r3= 0; char creg_r3; int r4= 0; char creg_r4; int r5= 0; char creg_r5; int r6= 0; char creg_r6; int r7= 0; char creg_r7; int r8= 0; char creg_r8; int r9= 0; char creg_r9; int r10= 0; char creg_r10; int r11= 0; char creg_r11; int r12= 0; char creg_r12; int r13= 0; char creg_r13; int r14= 0; char creg_r14; int r15= 0; char creg_r15; int r16= 0; char creg_r16; int r17= 0; char creg_r17; int r18= 0; char creg_r18; int r19= 0; char creg_r19; int r20= 0; char creg_r20; int r21= 0; char creg_r21; int r22= 0; char creg_r22; int r23= 0; char creg_r23; int r24= 0; char creg_r24; int r25= 0; char creg_r25; char old_cctrl= 0; char old_cr= 0; char old_cdy= 0; char old_cw= 0; char new_creg= 0; buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; buff(0,8) = 0; pw(0,8) = 0; cr(0,8) = 0; iw(0,8) = 0; cw(0,8) = 0; cx(0,8) = 0; is(0,8) = 0; cs(0,8) = 0; crmax(0,8) = 0; buff(0,9) = 0; pw(0,9) = 0; cr(0,9) = 0; iw(0,9) = 0; cw(0,9) = 0; cx(0,9) = 0; is(0,9) = 0; cs(0,9) = 0; crmax(0,9) = 0; buff(0,10) = 0; pw(0,10) = 0; cr(0,10) = 0; iw(0,10) = 0; cw(0,10) = 0; cx(0,10) = 0; is(0,10) = 0; cs(0,10) = 0; crmax(0,10) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; buff(1,8) = 0; pw(1,8) = 0; cr(1,8) = 0; iw(1,8) = 0; cw(1,8) = 0; cx(1,8) = 0; is(1,8) = 0; cs(1,8) = 0; crmax(1,8) = 0; buff(1,9) = 0; pw(1,9) = 0; cr(1,9) = 0; iw(1,9) = 0; cw(1,9) = 0; cx(1,9) = 0; is(1,9) = 0; cs(1,9) = 0; crmax(1,9) = 0; buff(1,10) = 0; pw(1,10) = 0; cr(1,10) = 0; iw(1,10) = 0; cw(1,10) = 0; cx(1,10) = 0; is(1,10) = 0; cs(1,10) = 0; crmax(1,10) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; buff(2,8) = 0; pw(2,8) = 0; cr(2,8) = 0; iw(2,8) = 0; cw(2,8) = 0; cx(2,8) = 0; is(2,8) = 0; cs(2,8) = 0; crmax(2,8) = 0; buff(2,9) = 0; pw(2,9) = 0; cr(2,9) = 0; iw(2,9) = 0; cw(2,9) = 0; cx(2,9) = 0; is(2,9) = 0; cs(2,9) = 0; crmax(2,9) = 0; buff(2,10) = 0; pw(2,10) = 0; cr(2,10) = 0; iw(2,10) = 0; cw(2,10) = 0; cx(2,10) = 0; is(2,10) = 0; cs(2,10) = 0; crmax(2,10) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; buff(3,6) = 0; pw(3,6) = 0; cr(3,6) = 0; iw(3,6) = 0; cw(3,6) = 0; cx(3,6) = 0; is(3,6) = 0; cs(3,6) = 0; crmax(3,6) = 0; buff(3,7) = 0; pw(3,7) = 0; cr(3,7) = 0; iw(3,7) = 0; cw(3,7) = 0; cx(3,7) = 0; is(3,7) = 0; cs(3,7) = 0; crmax(3,7) = 0; buff(3,8) = 0; pw(3,8) = 0; cr(3,8) = 0; iw(3,8) = 0; cw(3,8) = 0; cx(3,8) = 0; is(3,8) = 0; cs(3,8) = 0; crmax(3,8) = 0; buff(3,9) = 0; pw(3,9) = 0; cr(3,9) = 0; iw(3,9) = 0; cw(3,9) = 0; cx(3,9) = 0; is(3,9) = 0; cs(3,9) = 0; crmax(3,9) = 0; buff(3,10) = 0; pw(3,10) = 0; cr(3,10) = 0; iw(3,10) = 0; cw(3,10) = 0; cx(3,10) = 0; is(3,10) = 0; cs(3,10) = 0; crmax(3,10) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(0+3,0) = 0; mem(6+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(7+0,0) = 0; mem(8+0,0) = 0; mem(9+0,0) = 0; mem(10+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; co(8,0) = 0; delta(8,0) = -1; co(9,0) = 0; delta(9,0) = -1; co(10,0) = 0; delta(10,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !39, metadata !DIExpression()), !dbg !48 // br label %label_1, !dbg !49 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !47), !dbg !50 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !51 // call void @llvm.dbg.value(metadata i64 1, metadata !43, metadata !DIExpression()), !dbg !51 // store atomic i64 1, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !52 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 1; mem(0,cw(1,0)) = 1; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !53 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,0+3)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cw(1,7+0)); ASSUME(cdy[1] >= cw(1,8+0)); ASSUME(cdy[1] >= cw(1,9+0)); ASSUME(cdy[1] >= cw(1,10+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,0+3)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(cdy[1] >= cr(1,7+0)); ASSUME(cdy[1] >= cr(1,8+0)); ASSUME(cdy[1] >= cr(1,9+0)); ASSUME(cdy[1] >= cr(1,10+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !44, metadata !DIExpression()), !dbg !54 // call void @llvm.dbg.value(metadata i64 1, metadata !46, metadata !DIExpression()), !dbg !54 // store atomic i64 1, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !55 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !56 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !59, metadata !DIExpression()), !dbg !101 // br label %label_2, !dbg !83 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !98), !dbg !103 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !62, metadata !DIExpression()), !dbg !104 // %0 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !86 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !64, metadata !DIExpression()), !dbg !104 // %conv = trunc i64 %0 to i32, !dbg !87 // call void @llvm.dbg.value(metadata i32 %conv, metadata !60, metadata !DIExpression()), !dbg !101 // %tobool = icmp ne i32 %conv, 0, !dbg !88 // br i1 %tobool, label %if.then, label %if.else, !dbg !90 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg_r0); ASSUME(cctrl[2] >= 0); if((r0!=0)) { goto T2BLOCK2; } else { goto T2BLOCK3; } T2BLOCK2: // br label %lbl_LC00, !dbg !91 goto T2BLOCK4; T2BLOCK3: // br label %lbl_LC00, !dbg !92 goto T2BLOCK4; T2BLOCK4: // call void @llvm.dbg.label(metadata !99), !dbg !112 // call void (...) @isb(), !dbg !94 // isb: Guess cisb[2] = get_rng(0,NCONTEXT-1); // Check ASSUME(cisb[2] >= cdy[2]); ASSUME(cisb[2] >= cctrl[2]); ASSUME(cisb[2] >= caddr[2]); ASSUME(creturn[2] >= cisb[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !66, metadata !DIExpression()), !dbg !114 // %1 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !96 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r1 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r1 = buff(2,0+2*1); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r1 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !68, metadata !DIExpression()), !dbg !114 // %conv4 = trunc i64 %1 to i32, !dbg !97 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !65, metadata !DIExpression()), !dbg !101 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !70, metadata !DIExpression()), !dbg !117 // %2 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !99 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r2 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r2 = buff(2,0+2*1); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r2 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %2, metadata !72, metadata !DIExpression()), !dbg !117 // %conv8 = trunc i64 %2 to i32, !dbg !100 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !69, metadata !DIExpression()), !dbg !101 // %xor = xor i32 %conv8, %conv8, !dbg !101 creg_r3 = max(creg_r2,creg_r2); ASSUME(active[creg_r3] == 2); r3 = r2 ^ r2; // call void @llvm.dbg.value(metadata i32 %xor, metadata !73, metadata !DIExpression()), !dbg !101 // %add = add nsw i32 3, %xor, !dbg !102 creg_r4 = max(0,creg_r3); ASSUME(active[creg_r4] == 2); r4 = 3 + r3; // %idxprom = sext i32 %add to i64, !dbg !102 // %arrayidx = getelementptr inbounds [4 x i64], [4 x i64]* @vars, i64 0, i64 %idxprom, !dbg !102 r5 = 0+r4*1; ASSUME(creg_r5 >= 0); ASSUME(creg_r5 >= creg_r4); ASSUME(active[creg_r5] == 2); // call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !75, metadata !DIExpression()), !dbg !122 // %3 = load atomic i64, i64* %arrayidx monotonic, align 8, !dbg !102 // LD: Guess old_cr = cr(2,r5); cr(2,r5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,r5)] == 2); ASSUME(cr(2,r5) >= iw(2,r5)); ASSUME(cr(2,r5) >= creg_r5); ASSUME(cr(2,r5) >= cdy[2]); ASSUME(cr(2,r5) >= cisb[2]); ASSUME(cr(2,r5) >= cdl[2]); ASSUME(cr(2,r5) >= cl[2]); // Update creg_r6 = cr(2,r5); crmax(2,r5) = max(crmax(2,r5),cr(2,r5)); caddr[2] = max(caddr[2],creg_r5); if(cr(2,r5) < cw(2,r5)) { r6 = buff(2,r5); } else { if(pw(2,r5) != co(r5,cr(2,r5))) { ASSUME(cr(2,r5) >= old_cr); } pw(2,r5) = co(r5,cr(2,r5)); r6 = mem(r5,cr(2,r5)); } ASSUME(creturn[2] >= cr(2,r5)); // call void @llvm.dbg.value(metadata i64 %3, metadata !77, metadata !DIExpression()), !dbg !122 // %conv12 = trunc i64 %3 to i32, !dbg !104 // call void @llvm.dbg.value(metadata i32 %conv12, metadata !74, metadata !DIExpression()), !dbg !101 // %tobool13 = icmp ne i32 %conv12, 0, !dbg !105 // br i1 %tobool13, label %if.then14, label %if.else15, !dbg !107 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg_r6); ASSUME(cctrl[2] >= 0); if((r6!=0)) { goto T2BLOCK5; } else { goto T2BLOCK6; } T2BLOCK5: // br label %lbl_LC01, !dbg !108 goto T2BLOCK7; T2BLOCK6: // br label %lbl_LC01, !dbg !109 goto T2BLOCK7; T2BLOCK7: // call void @llvm.dbg.label(metadata !100), !dbg !129 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !79, metadata !DIExpression()), !dbg !130 // %4 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !112 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r7 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r7 = buff(2,0); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r7 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %4, metadata !81, metadata !DIExpression()), !dbg !130 // %conv19 = trunc i64 %4 to i32, !dbg !113 // call void @llvm.dbg.value(metadata i32 %conv19, metadata !78, metadata !DIExpression()), !dbg !101 // %cmp = icmp eq i32 %conv, 1, !dbg !114 // %conv20 = zext i1 %cmp to i32, !dbg !114 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !82, metadata !DIExpression()), !dbg !101 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !83, metadata !DIExpression()), !dbg !134 // %5 = zext i32 %conv20 to i64 // call void @llvm.dbg.value(metadata i64 %5, metadata !85, metadata !DIExpression()), !dbg !134 // store atomic i64 %5, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !116 // ST: Guess iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,4); cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,4)] == 2); ASSUME(active[cw(2,4)] == 2); ASSUME(sforbid(4,cw(2,4))== 0); ASSUME(iw(2,4) >= max(creg_r0,0)); ASSUME(iw(2,4) >= 0); ASSUME(cw(2,4) >= iw(2,4)); ASSUME(cw(2,4) >= old_cw); ASSUME(cw(2,4) >= cr(2,4)); ASSUME(cw(2,4) >= cl[2]); ASSUME(cw(2,4) >= cisb[2]); ASSUME(cw(2,4) >= cdy[2]); ASSUME(cw(2,4) >= cdl[2]); ASSUME(cw(2,4) >= cds[2]); ASSUME(cw(2,4) >= cctrl[2]); ASSUME(cw(2,4) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,4) = (r0==1); mem(4,cw(2,4)) = (r0==1); co(4,cw(2,4))+=1; delta(4,cw(2,4)) = -1; ASSUME(creturn[2] >= cw(2,4)); // %cmp22 = icmp eq i32 %conv4, 0, !dbg !117 // %conv23 = zext i1 %cmp22 to i32, !dbg !117 // call void @llvm.dbg.value(metadata i32 %conv23, metadata !86, metadata !DIExpression()), !dbg !101 // call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !87, metadata !DIExpression()), !dbg !137 // %6 = zext i32 %conv23 to i64 // call void @llvm.dbg.value(metadata i64 %6, metadata !89, metadata !DIExpression()), !dbg !137 // store atomic i64 %6, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !119 // ST: Guess iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,5); cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,5)] == 2); ASSUME(active[cw(2,5)] == 2); ASSUME(sforbid(5,cw(2,5))== 0); ASSUME(iw(2,5) >= max(creg_r1,0)); ASSUME(iw(2,5) >= 0); ASSUME(cw(2,5) >= iw(2,5)); ASSUME(cw(2,5) >= old_cw); ASSUME(cw(2,5) >= cr(2,5)); ASSUME(cw(2,5) >= cl[2]); ASSUME(cw(2,5) >= cisb[2]); ASSUME(cw(2,5) >= cdy[2]); ASSUME(cw(2,5) >= cdl[2]); ASSUME(cw(2,5) >= cds[2]); ASSUME(cw(2,5) >= cctrl[2]); ASSUME(cw(2,5) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,5) = (r1==0); mem(5,cw(2,5)) = (r1==0); co(5,cw(2,5))+=1; delta(5,cw(2,5)) = -1; ASSUME(creturn[2] >= cw(2,5)); // %cmp27 = icmp eq i32 %conv8, 1, !dbg !120 // %conv28 = zext i1 %cmp27 to i32, !dbg !120 // call void @llvm.dbg.value(metadata i32 %conv28, metadata !90, metadata !DIExpression()), !dbg !101 // call void @llvm.dbg.value(metadata i64* @atom_1_X4_1, metadata !91, metadata !DIExpression()), !dbg !140 // %7 = zext i32 %conv28 to i64 // call void @llvm.dbg.value(metadata i64 %7, metadata !93, metadata !DIExpression()), !dbg !140 // store atomic i64 %7, i64* @atom_1_X4_1 seq_cst, align 8, !dbg !122 // ST: Guess iw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,6); cw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,6)] == 2); ASSUME(active[cw(2,6)] == 2); ASSUME(sforbid(6,cw(2,6))== 0); ASSUME(iw(2,6) >= max(creg_r2,0)); ASSUME(iw(2,6) >= 0); ASSUME(cw(2,6) >= iw(2,6)); ASSUME(cw(2,6) >= old_cw); ASSUME(cw(2,6) >= cr(2,6)); ASSUME(cw(2,6) >= cl[2]); ASSUME(cw(2,6) >= cisb[2]); ASSUME(cw(2,6) >= cdy[2]); ASSUME(cw(2,6) >= cdl[2]); ASSUME(cw(2,6) >= cds[2]); ASSUME(cw(2,6) >= cctrl[2]); ASSUME(cw(2,6) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,6) = (r2==1); mem(6,cw(2,6)) = (r2==1); co(6,cw(2,6))+=1; delta(6,cw(2,6)) = -1; ASSUME(creturn[2] >= cw(2,6)); // %cmp32 = icmp eq i32 %conv19, 0, !dbg !123 // %conv33 = zext i1 %cmp32 to i32, !dbg !123 // call void @llvm.dbg.value(metadata i32 %conv33, metadata !94, metadata !DIExpression()), !dbg !101 // call void @llvm.dbg.value(metadata i64* @atom_1_X8_0, metadata !95, metadata !DIExpression()), !dbg !143 // %8 = zext i32 %conv33 to i64 // call void @llvm.dbg.value(metadata i64 %8, metadata !97, metadata !DIExpression()), !dbg !143 // store atomic i64 %8, i64* @atom_1_X8_0 seq_cst, align 8, !dbg !125 // ST: Guess iw(2,7) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,7); cw(2,7) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,7)] == 2); ASSUME(active[cw(2,7)] == 2); ASSUME(sforbid(7,cw(2,7))== 0); ASSUME(iw(2,7) >= max(creg_r7,0)); ASSUME(iw(2,7) >= 0); ASSUME(cw(2,7) >= iw(2,7)); ASSUME(cw(2,7) >= old_cw); ASSUME(cw(2,7) >= cr(2,7)); ASSUME(cw(2,7) >= cl[2]); ASSUME(cw(2,7) >= cisb[2]); ASSUME(cw(2,7) >= cdy[2]); ASSUME(cw(2,7) >= cdl[2]); ASSUME(cw(2,7) >= cds[2]); ASSUME(cw(2,7) >= cctrl[2]); ASSUME(cw(2,7) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,7) = (r7==0); mem(7,cw(2,7)) = (r7==0); co(7,cw(2,7))+=1; delta(7,cw(2,7)) = -1; ASSUME(creturn[2] >= cw(2,7)); // ret i8* null, !dbg !126 ret_thread_2 = (- 1); // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !148, metadata !DIExpression()), !dbg !153 // br label %label_3, !dbg !46 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !152), !dbg !155 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !149, metadata !DIExpression()), !dbg !156 // call void @llvm.dbg.value(metadata i64 1, metadata !151, metadata !DIExpression()), !dbg !156 // store atomic i64 1, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !49 // ST: Guess iw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,0+2*1); cw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,0+2*1)] == 3); ASSUME(active[cw(3,0+2*1)] == 3); ASSUME(sforbid(0+2*1,cw(3,0+2*1))== 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(cw(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cw(3,0+2*1) >= old_cw); ASSUME(cw(3,0+2*1) >= cr(3,0+2*1)); ASSUME(cw(3,0+2*1) >= cl[3]); ASSUME(cw(3,0+2*1) >= cisb[3]); ASSUME(cw(3,0+2*1) >= cdy[3]); ASSUME(cw(3,0+2*1) >= cdl[3]); ASSUME(cw(3,0+2*1) >= cds[3]); ASSUME(cw(3,0+2*1) >= cctrl[3]); ASSUME(cw(3,0+2*1) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,0+2*1) = 1; mem(0+2*1,cw(3,0+2*1)) = 1; co(0+2*1,cw(3,0+2*1))+=1; delta(0+2*1,cw(3,0+2*1)) = -1; ASSUME(creturn[3] >= cw(3,0+2*1)); // ret i8* null, !dbg !50 ret_thread_3 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !166, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i8** %argv, metadata !167, metadata !DIExpression()), !dbg !235 // %0 = bitcast i64* %thr0 to i8*, !dbg !114 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !114 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !168, metadata !DIExpression()), !dbg !237 // %1 = bitcast i64* %thr1 to i8*, !dbg !116 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !116 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !172, metadata !DIExpression()), !dbg !239 // %2 = bitcast i64* %thr2 to i8*, !dbg !118 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !118 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !173, metadata !DIExpression()), !dbg !241 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3), metadata !174, metadata !DIExpression()), !dbg !242 // call void @llvm.dbg.value(metadata i64 0, metadata !176, metadata !DIExpression()), !dbg !242 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 3) monotonic, align 8, !dbg !121 // ST: Guess iw(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+3*1); cw(0,0+3*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+3*1)] == 0); ASSUME(active[cw(0,0+3*1)] == 0); ASSUME(sforbid(0+3*1,cw(0,0+3*1))== 0); ASSUME(iw(0,0+3*1) >= 0); ASSUME(iw(0,0+3*1) >= 0); ASSUME(cw(0,0+3*1) >= iw(0,0+3*1)); ASSUME(cw(0,0+3*1) >= old_cw); ASSUME(cw(0,0+3*1) >= cr(0,0+3*1)); ASSUME(cw(0,0+3*1) >= cl[0]); ASSUME(cw(0,0+3*1) >= cisb[0]); ASSUME(cw(0,0+3*1) >= cdy[0]); ASSUME(cw(0,0+3*1) >= cdl[0]); ASSUME(cw(0,0+3*1) >= cds[0]); ASSUME(cw(0,0+3*1) >= cctrl[0]); ASSUME(cw(0,0+3*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+3*1) = 0; mem(0+3*1,cw(0,0+3*1)) = 0; co(0+3*1,cw(0,0+3*1))+=1; delta(0+3*1,cw(0,0+3*1)) = -1; ASSUME(creturn[0] >= cw(0,0+3*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !177, metadata !DIExpression()), !dbg !244 // call void @llvm.dbg.value(metadata i64 0, metadata !179, metadata !DIExpression()), !dbg !244 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !123 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !180, metadata !DIExpression()), !dbg !246 // call void @llvm.dbg.value(metadata i64 0, metadata !182, metadata !DIExpression()), !dbg !246 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !125 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !183, metadata !DIExpression()), !dbg !248 // call void @llvm.dbg.value(metadata i64 0, metadata !185, metadata !DIExpression()), !dbg !248 // store atomic i64 0, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !127 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !186, metadata !DIExpression()), !dbg !250 // call void @llvm.dbg.value(metadata i64 0, metadata !188, metadata !DIExpression()), !dbg !250 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !129 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !189, metadata !DIExpression()), !dbg !252 // call void @llvm.dbg.value(metadata i64 0, metadata !191, metadata !DIExpression()), !dbg !252 // store atomic i64 0, i64* @atom_1_X2_0 monotonic, align 8, !dbg !131 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // call void @llvm.dbg.value(metadata i64* @atom_1_X4_1, metadata !192, metadata !DIExpression()), !dbg !254 // call void @llvm.dbg.value(metadata i64 0, metadata !194, metadata !DIExpression()), !dbg !254 // store atomic i64 0, i64* @atom_1_X4_1 monotonic, align 8, !dbg !133 // ST: Guess iw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,6); cw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,6)] == 0); ASSUME(active[cw(0,6)] == 0); ASSUME(sforbid(6,cw(0,6))== 0); ASSUME(iw(0,6) >= 0); ASSUME(iw(0,6) >= 0); ASSUME(cw(0,6) >= iw(0,6)); ASSUME(cw(0,6) >= old_cw); ASSUME(cw(0,6) >= cr(0,6)); ASSUME(cw(0,6) >= cl[0]); ASSUME(cw(0,6) >= cisb[0]); ASSUME(cw(0,6) >= cdy[0]); ASSUME(cw(0,6) >= cdl[0]); ASSUME(cw(0,6) >= cds[0]); ASSUME(cw(0,6) >= cctrl[0]); ASSUME(cw(0,6) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,6) = 0; mem(6,cw(0,6)) = 0; co(6,cw(0,6))+=1; delta(6,cw(0,6)) = -1; ASSUME(creturn[0] >= cw(0,6)); // call void @llvm.dbg.value(metadata i64* @atom_1_X8_0, metadata !195, metadata !DIExpression()), !dbg !256 // call void @llvm.dbg.value(metadata i64 0, metadata !197, metadata !DIExpression()), !dbg !256 // store atomic i64 0, i64* @atom_1_X8_0 monotonic, align 8, !dbg !135 // ST: Guess iw(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,7); cw(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,7)] == 0); ASSUME(active[cw(0,7)] == 0); ASSUME(sforbid(7,cw(0,7))== 0); ASSUME(iw(0,7) >= 0); ASSUME(iw(0,7) >= 0); ASSUME(cw(0,7) >= iw(0,7)); ASSUME(cw(0,7) >= old_cw); ASSUME(cw(0,7) >= cr(0,7)); ASSUME(cw(0,7) >= cl[0]); ASSUME(cw(0,7) >= cisb[0]); ASSUME(cw(0,7) >= cdy[0]); ASSUME(cw(0,7) >= cdl[0]); ASSUME(cw(0,7) >= cds[0]); ASSUME(cw(0,7) >= cctrl[0]); ASSUME(cw(0,7) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,7) = 0; mem(7,cw(0,7)) = 0; co(7,cw(0,7))+=1; delta(7,cw(0,7)) = -1; ASSUME(creturn[0] >= cw(0,7)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !136 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cw(0,10+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(cdy[0] >= cr(0,10+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call15 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !137 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cw(0,10+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(cdy[0] >= cr(0,10+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call16 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !138 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cw(0,10+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(cdy[0] >= cr(0,10+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !139, !tbaa !140 // LD: Guess old_cr = cr(0,8); cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,8)] == 0); ASSUME(cr(0,8) >= iw(0,8)); ASSUME(cr(0,8) >= 0); ASSUME(cr(0,8) >= cdy[0]); ASSUME(cr(0,8) >= cisb[0]); ASSUME(cr(0,8) >= cdl[0]); ASSUME(cr(0,8) >= cl[0]); // Update creg_r9 = cr(0,8); crmax(0,8) = max(crmax(0,8),cr(0,8)); caddr[0] = max(caddr[0],0); if(cr(0,8) < cw(0,8)) { r9 = buff(0,8); } else { if(pw(0,8) != co(8,cr(0,8))) { ASSUME(cr(0,8) >= old_cr); } pw(0,8) = co(8,cr(0,8)); r9 = mem(8,cr(0,8)); } ASSUME(creturn[0] >= cr(0,8)); // %call17 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !144 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cw(0,10+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(cdy[0] >= cr(0,10+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !145, !tbaa !140 // LD: Guess old_cr = cr(0,9); cr(0,9) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,9)] == 0); ASSUME(cr(0,9) >= iw(0,9)); ASSUME(cr(0,9) >= 0); ASSUME(cr(0,9) >= cdy[0]); ASSUME(cr(0,9) >= cisb[0]); ASSUME(cr(0,9) >= cdl[0]); ASSUME(cr(0,9) >= cl[0]); // Update creg_r10 = cr(0,9); crmax(0,9) = max(crmax(0,9),cr(0,9)); caddr[0] = max(caddr[0],0); if(cr(0,9) < cw(0,9)) { r10 = buff(0,9); } else { if(pw(0,9) != co(9,cr(0,9))) { ASSUME(cr(0,9) >= old_cr); } pw(0,9) = co(9,cr(0,9)); r10 = mem(9,cr(0,9)); } ASSUME(creturn[0] >= cr(0,9)); // %call18 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !146 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cw(0,10+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(cdy[0] >= cr(0,10+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !147, !tbaa !140 // LD: Guess old_cr = cr(0,10); cr(0,10) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,10)] == 0); ASSUME(cr(0,10) >= iw(0,10)); ASSUME(cr(0,10) >= 0); ASSUME(cr(0,10) >= cdy[0]); ASSUME(cr(0,10) >= cisb[0]); ASSUME(cr(0,10) >= cdl[0]); ASSUME(cr(0,10) >= cl[0]); // Update creg_r11 = cr(0,10); crmax(0,10) = max(crmax(0,10),cr(0,10)); caddr[0] = max(caddr[0],0); if(cr(0,10) < cw(0,10)) { r11 = buff(0,10); } else { if(pw(0,10) != co(10,cr(0,10))) { ASSUME(cr(0,10) >= old_cr); } pw(0,10) = co(10,cr(0,10)); r11 = mem(10,cr(0,10)); } ASSUME(creturn[0] >= cr(0,10)); // %call19 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !148 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,0+3)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cw(0,10+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,0+3)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(cdy[0] >= cr(0,10+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0), metadata !199, metadata !DIExpression()), !dbg !271 // %6 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !150 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r12 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r12 = buff(0,0); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r12 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %6, metadata !201, metadata !DIExpression()), !dbg !271 // %conv = trunc i64 %6 to i32, !dbg !151 // call void @llvm.dbg.value(metadata i32 %conv, metadata !198, metadata !DIExpression()), !dbg !235 // %cmp = icmp eq i32 %conv, 1, !dbg !152 // %conv20 = zext i1 %cmp to i32, !dbg !152 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !202, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1), metadata !204, metadata !DIExpression()), !dbg !275 // %7 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !154 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r13 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r13 = buff(0,0+1*1); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r13 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %7, metadata !206, metadata !DIExpression()), !dbg !275 // %conv24 = trunc i64 %7 to i32, !dbg !155 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !203, metadata !DIExpression()), !dbg !235 // %cmp25 = icmp eq i32 %conv24, 1, !dbg !156 // %conv26 = zext i1 %cmp25 to i32, !dbg !156 // call void @llvm.dbg.value(metadata i32 %conv26, metadata !207, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2), metadata !209, metadata !DIExpression()), !dbg !279 // %8 = load atomic i64, i64* getelementptr inbounds ([4 x i64], [4 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !158 // LD: Guess old_cr = cr(0,0+2*1); cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+2*1)] == 0); ASSUME(cr(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cr(0,0+2*1) >= 0); ASSUME(cr(0,0+2*1) >= cdy[0]); ASSUME(cr(0,0+2*1) >= cisb[0]); ASSUME(cr(0,0+2*1) >= cdl[0]); ASSUME(cr(0,0+2*1) >= cl[0]); // Update creg_r14 = cr(0,0+2*1); crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+2*1) < cw(0,0+2*1)) { r14 = buff(0,0+2*1); } else { if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) { ASSUME(cr(0,0+2*1) >= old_cr); } pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1)); r14 = mem(0+2*1,cr(0,0+2*1)); } ASSUME(creturn[0] >= cr(0,0+2*1)); // call void @llvm.dbg.value(metadata i64 %8, metadata !211, metadata !DIExpression()), !dbg !279 // %conv30 = trunc i64 %8 to i32, !dbg !159 // call void @llvm.dbg.value(metadata i32 %conv30, metadata !208, metadata !DIExpression()), !dbg !235 // %cmp31 = icmp eq i32 %conv30, 1, !dbg !160 // %conv32 = zext i1 %cmp31 to i32, !dbg !160 // call void @llvm.dbg.value(metadata i32 %conv32, metadata !212, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !214, metadata !DIExpression()), !dbg !283 // %9 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !162 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r15 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r15 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r15 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %9, metadata !216, metadata !DIExpression()), !dbg !283 // %conv36 = trunc i64 %9 to i32, !dbg !163 // call void @llvm.dbg.value(metadata i32 %conv36, metadata !213, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i64* @atom_1_X2_0, metadata !218, metadata !DIExpression()), !dbg !286 // %10 = load atomic i64, i64* @atom_1_X2_0 seq_cst, align 8, !dbg !165 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r16 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r16 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r16 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i64 %10, metadata !220, metadata !DIExpression()), !dbg !286 // %conv40 = trunc i64 %10 to i32, !dbg !166 // call void @llvm.dbg.value(metadata i32 %conv40, metadata !217, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i64* @atom_1_X4_1, metadata !222, metadata !DIExpression()), !dbg !289 // %11 = load atomic i64, i64* @atom_1_X4_1 seq_cst, align 8, !dbg !168 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r17 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r17 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r17 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // call void @llvm.dbg.value(metadata i64 %11, metadata !224, metadata !DIExpression()), !dbg !289 // %conv44 = trunc i64 %11 to i32, !dbg !169 // call void @llvm.dbg.value(metadata i32 %conv44, metadata !221, metadata !DIExpression()), !dbg !235 // call void @llvm.dbg.value(metadata i64* @atom_1_X8_0, metadata !226, metadata !DIExpression()), !dbg !292 // %12 = load atomic i64, i64* @atom_1_X8_0 seq_cst, align 8, !dbg !171 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r18 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r18 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r18 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // call void @llvm.dbg.value(metadata i64 %12, metadata !228, metadata !DIExpression()), !dbg !292 // %conv48 = trunc i64 %12 to i32, !dbg !172 // call void @llvm.dbg.value(metadata i32 %conv48, metadata !225, metadata !DIExpression()), !dbg !235 // %and = and i32 %conv44, %conv48, !dbg !173 creg_r19 = max(creg_r17,creg_r18); ASSUME(active[creg_r19] == 0); r19 = r17 & r18; // call void @llvm.dbg.value(metadata i32 %and, metadata !229, metadata !DIExpression()), !dbg !235 // %and49 = and i32 %conv40, %and, !dbg !174 creg_r20 = max(creg_r16,creg_r19); ASSUME(active[creg_r20] == 0); r20 = r16 & r19; // call void @llvm.dbg.value(metadata i32 %and49, metadata !230, metadata !DIExpression()), !dbg !235 // %and50 = and i32 %conv36, %and49, !dbg !175 creg_r21 = max(creg_r15,creg_r20); ASSUME(active[creg_r21] == 0); r21 = r15 & r20; // call void @llvm.dbg.value(metadata i32 %and50, metadata !231, metadata !DIExpression()), !dbg !235 // %and51 = and i32 %conv32, %and50, !dbg !176 creg_r22 = max(max(creg_r14,0),creg_r21); ASSUME(active[creg_r22] == 0); r22 = (r14==1) & r21; // call void @llvm.dbg.value(metadata i32 %and51, metadata !232, metadata !DIExpression()), !dbg !235 // %and52 = and i32 %conv26, %and51, !dbg !177 creg_r23 = max(max(creg_r13,0),creg_r22); ASSUME(active[creg_r23] == 0); r23 = (r13==1) & r22; // call void @llvm.dbg.value(metadata i32 %and52, metadata !233, metadata !DIExpression()), !dbg !235 // %and53 = and i32 %conv20, %and52, !dbg !178 creg_r24 = max(max(creg_r12,0),creg_r23); ASSUME(active[creg_r24] == 0); r24 = (r12==1) & r23; // call void @llvm.dbg.value(metadata i32 %and53, metadata !234, metadata !DIExpression()), !dbg !235 // %cmp54 = icmp eq i32 %and53, 1, !dbg !179 // br i1 %cmp54, label %if.then, label %if.end, !dbg !181 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r24); ASSUME(cctrl[0] >= 0); if((r24==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([120 x i8], [120 x i8]* @.str.1, i64 0, i64 0), i32 noundef 96, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !182 // unreachable, !dbg !182 r25 = 1; T0BLOCK2: // %13 = bitcast i64* %thr2 to i8*, !dbg !185 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !185 // %14 = bitcast i64* %thr1 to i8*, !dbg !185 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %14) #7, !dbg !185 // %15 = bitcast i64* %thr0 to i8*, !dbg !185 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %15) #7, !dbg !185 // ret i32 0, !dbg !186 ret_thread_0 = 0; ASSERT(r25== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
81b59b16b116c5147f13644360d847506e83fee6
07a787d756dff1dd611cda747239ff734b0fca43
/DICTIONARYBST/BinaryTree.h
a8b1e057284691d677199f1be449052e0bdd5eff
[]
no_license
Evan-Swanson/CPSC-223
4f9a1ba8fc1c588bd297009e34911256b3bef8b6
bc172810be0edc3c9ee39fd7fe2a8ccca47409c7
refs/heads/master
2020-04-13T17:26:51.072899
2018-12-28T00:38:40
2018-12-28T00:38:40
163,348,502
0
0
null
null
null
null
UTF-8
C++
false
false
3,827
h
//file BinaryTree.h //Evan Swanson, Ryan Schoenlein // 3/5/18 // Specification of ADT Binary Tree // Data object: A binary tree T that is either empty or // in the form of r // / \ // TL TR // where TL and TR are binary trees // Operations: (a scaled-down version) // create, destroy, copy, operator=, // traversals (preorder, inorder, postorder) // Contract: Assumes the this class can access private data members of class Node. // Those data members are: Item item, Node* leftptr, Node* rightptr. // There is a constructor that allows caller to give item, left and right ptrs. #ifndef BINARYTREE_H #define BINARYTREE_H #include "TreeNode.h" #include "Exception.h" #include <iostream> using namespace std; class BinaryTree { public: //creates an empty binary tree //post: object is an empty binary tree //usage: BinaryTree zags; BinaryTree(); //creates a new binary tree that is a copy of an existing tree //post object is a copy of rightHandSideTree //throws an exception if there is not enough room in the heap for // an copied tree //usage: BinaryTree zags (bulldog); BinaryTree(const BinaryTree& rightHandSideTree) throw (Exception); //releases the memory of a binary tree //pre: object exists //post: memory for the object has been released. object theoretically does not exist // but in practice, it is empty. ~BinaryTree(); // ******************** member functions ******************************************** //pre: binary tree object exists // ********************************************************************************** //checks for an empty tree //post: returns true if the object is empty; else returns false //usage: if (tree.isEmpty()) bool isEmpty() const; //copies one tree to another //pre: rhstree is an assigned tree. //post: object is a copy of rightHandSideTree //throws an exception if there is not enough room in the heap for // an copied tree //usage: atree = btree = ctree; BinaryTree& operator=(const BinaryTree& rightHandSideTree) throw (Exception); //prints the tree to look like a computer science tree //post: outputs the tree as in the example below // // bar // foo // geeU // root -> queue // stack // list // array //nodes at the same level are indented the same. //Viewer must rotate head 90 degrees in order to look like a cs tree //usage: tree.prettyDisplay(); void prettyDisplay(); // *************** on the following traversals //uses: operator<< from class Item //post: prints the objects in the tree in order specified //usage: tree.preorderTraverse(); //similarly for the other traversals // ***************************************************** void preorderTraverse (); void inorderTraverse(ostream& output); void postorderTraverse(); //makes a full binary tree of height 2 //pre input is either cin or an open file //post: object is a full binary tree of height 2 //throws an exception if there is not enough room in the // heap to make the tree //usage: tree.makeTreeOne(); void makeTreeOne(istream& input) throw (Exception); //makes a complete binary tree of height 3 //pre input is either cin or an open file //post: object is a complete binary tree of height 3 //throws an exception if there is not enough room in the // heap to make the tree //usage: tree.makeTreeTwo() void makeTreeTwo(istream& input) throw (Exception); protected: TreeNode* root; }; #endif
[ "44790747+Evan-Swanson@users.noreply.github.com" ]
44790747+Evan-Swanson@users.noreply.github.com
e7d6b6533a9c515982c85e30c07156c9f9d3dc59
3e0b214f030b16e48f30dd18fcd08c98284930d7
/examples/demo-module-UT/demoModuleTests.cpp
a841d3c88eff98e84f4212b2ed97d56030ffb828
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
zeroSDN/ZMF
d56def1aa65b6a287aefcbdecf8e46e68fef99d4
a2262a77891b9c6b34d33dc6ff1b9734175fdcce
refs/heads/master
2020-04-11T01:20:51.196452
2015-11-12T09:38:36
2015-11-12T09:38:36
41,360,398
0
1
null
null
null
null
UTF-8
C++
false
false
339
cpp
// // Created by zsdn on 6/25/15. // #include "demoModuleTests.h" demoModuleTests::demoModuleTests() { } void demoModuleTests::testMethod1() { CPPUNIT_ASSERT(true); } void demoModuleTests::testMethod2() { CPPUNIT_ASSERT(true); } void demoModuleTests::testMethod3() { CPPUNIT_ASSERT_EQUAL(i,5); CPPUNIT_ASSERT(true); }
[ "public@jonas-grunert.de" ]
public@jonas-grunert.de
b1ab5cdf0e0b50fd897a5eadc2ef102a9474c45d
277698e0fa6c846f1209adbd840afab8aea6d7b5
/code/EditInPlace.h
78a31773e4c14d9e36573857ec913b460274611a
[ "MIT" ]
permissive
omerdagan84/neomem
ad67dba738efced735f614029d7c237f574ecbbe
7d2f782bb37f1ab0ac6580d00672e114605afab7
refs/heads/master
2021-01-20T19:45:32.004246
2014-04-12T13:09:20
2014-04-12T13:09:20
22,289,594
2
0
null
null
null
null
MacCentralEurope
C++
false
false
2,748
h
// CEditInPlace // This is an extension of the edit control which is used to edit values in the // Contents View and Properties View. // Adapted from various CodeGuru articles. //----------------------------------------------------------------------------------------------------------------- // Like the built in edit control for the first column, our edit control also sends the LVN_ENDLABELEDIT // notification when the edit is completed. If this notification message isnít already being handled, // add a handler so that any changes made with the edit control can be accepted. // We need to subclass the CEdit class to provide for our special requirement. // The main requirements placed on this class is that // It should send the LVN_ENDLABELEDIT message when edit is complete // It should expand to accommodate the text // It should destroy itself when the edit is complete // The edit should be terminated when the user presses the Escape or the Enter key or // when the edit control loses focus. // The reason I caught some events in the KeyDown, some in the KeyUp, and some in the OnChar, // had to do with how the application behaved. If I would have caught the VK_PRIOR or VK_NEXT // in the OnKeyDown, I would get several calls depending on how long the button was pressed. // This is very annoying. If you don't believe me, move the code, add several items to the list and // try it (it isn't pretty). // I also caught the ESC key so that I could cancel an edit. The return key is being used to end an edit // and when it is on the last record, it insert a new one. Just don't forget to override the // OnGetDlgCode() so that you can get the arrow keys and tabs. #pragma once #include "ListCtrlEx.h" class CEditInPlace : public CEdit { // Construction public: CEditInPlace(CListCtrlEx* plvw, int iItem, int iSubItem, CString sInitText); virtual ~CEditInPlace(); // Operations public: // Attributes public: private: CListCtrlEx* m_plvw; int m_iItem; int m_iSubItem; CString m_sInitText; BOOL m_bEscape; // To indicate whether ESC key was pressed // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CEditInPlace) public: virtual BOOL PreTranslateMessage(MSG* pMsg); //}}AFX_VIRTUAL UINT OnGetDlgCode(); // Implementation protected: // Generated message map functions //{{AFX_MSG(CEditInPlace) afx_msg void OnKillFocus(CWnd* pNewWnd); afx_msg void OnNcDestroy(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ "bburns@3bad96a7-2d8f-4f48-a7ae-748201937164" ]
bburns@3bad96a7-2d8f-4f48-a7ae-748201937164
5f50a63613c44d39694d7a26f8ba7029935a4c9d
0dff71fc1ba6c8f38a1cb9006a8a224138551cc9
/CircleIn3D.h
ef0ecf75a454a0c6a26e46272e21c5d564d6121b
[]
no_license
hidex7777/fsof005
ea1ead2483f3d0bb83101995006f9634293f6936
490e7eb0b6fbe440285e0f11c721fadd9f752c6a
refs/heads/master
2021-08-31T06:35:14.901623
2017-12-20T15:23:08
2017-12-20T15:23:08
114,789,517
0
0
null
null
null
null
UTF-8
C++
false
false
362
h
#pragma once #include "ofMain.h" class CircleIn3D { public: CircleIn3D(ofVec3f center, ofColor color, float r, float theta); ~CircleIn3D() {}; void update(float add); void draw(); vector<ofVec3f> getDots(); private: ofVec3f mycenter; float myradius; vector<ofVec3f> mydots; ofColor mycolor; float theta; int dotalp; int linealp; };
[ "hidex7777@gmail.com" ]
hidex7777@gmail.com
893745ea0bf7dbcba47e7166d35b4b2401612618
9c2e00697c4904d031f80b08c449f63aa7031d10
/Seminar/Week11 - Strings/solutions/task07.cpp
fefdf216719be1afc4be596fdb933855a9a9e7cb
[]
no_license
fmi-lab/up-kn-2020-group-4
6e2d753c84a0613b540537ef35f14bbdf52315ea
f75169a224e1f2e8dec76644f4e1341622bfeb94
refs/heads/master
2023-02-27T07:30:27.540323
2021-02-03T08:03:40
2021-02-03T08:03:40
300,292,730
9
4
null
null
null
null
UTF-8
C++
false
false
1,458
cpp
#include <iostream> #include <cstring> using namespace std; bool isLetter(char symbol) { return symbol >= 'A' && symbol <= 'z'; } void resize(char* &str, size_t& size) { char* oldStr = str; str = new char[size*2]; for (int i = 0; i < size; i++) { str[i] = oldStr[i]; } size *= 2; delete[] oldStr; } char* insertText(bool isText) { size_t size = 2, counter = 0; char* text = new char [size]{}; char symbol; cin.get(symbol); while (symbol != '\n' && (isText || symbol != ' ')) { if (counter >= size - 1) { resize(text, size); } text[counter++] = symbol; cin.get(symbol); } text[counter] = '\0'; return text; } void removeWord(char* text, char* word) { int textLen = strlen(text); int wordLen = strlen(word); for (int i = 0; i < textLen; i++) { if (strncmp(word, text + i, wordLen) == 0) { for (int j = i; j < textLen - wordLen; j++){ text[j] = text[j + wordLen]; } textLen -= wordLen; } } text[textLen] = '\0'; } void printStr(char* str) { for (int i = 0; i < strlen(str); i++) { cout << str[i]; } } int main() { cout << "Insert text: " << endl; char* text = insertText(true); cout << "Insert word: " << endl; char* word = insertText(false); removeWord(text, word); printStr(text); return 0; }
[ "cvetilinna@gmail.com" ]
cvetilinna@gmail.com
de7b52f8682426c56a90ef4bcc3ce2343ecf78f7
e600605b2c67b4c0dbc93ed9b5492b9fc607b0f3
/ShapeInheritance/Circle.h
c9084f8ecc531b1ff1c26be98b0d0ce7f4022207
[]
no_license
neilpirch/CSIS223_Assign06_ShapeInheritance
334b52d856ea87689fb9fb5592fa2b2d37504cca
7cdbadbbf6cc55f4fbdc9670a200c4e58cc7643f
refs/heads/master
2021-08-28T16:13:49.562936
2017-12-12T17:39:31
2017-12-12T17:39:31
114,020,447
0
0
null
null
null
null
UTF-8
C++
false
false
320
h
#pragma once #include "Shape.h" class Circle : public Shape { const double PI = 3.1416; public: Circle(); Circle(int newX, int newY, int newRadius); int getRadius() const; void setRadius(int newRadius); void display() const; double getArea() const; double getPerimeter() const; private: int radius; };
[ "neil.pirch@gmail.com" ]
neil.pirch@gmail.com
0e3c7d411b785e63e62a8c2494707ce2e1e3ad11
2f78e134c5b55c816fa8ee939f54bde4918696a5
/code/game/anonymouscomponent.cpp
728cdaa5bb0c9d522035f080e57f86524ed97185
[]
no_license
narayanr7/HeavenlySword
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
a255b26020933e2336f024558fefcdddb48038b2
refs/heads/master
2022-08-23T01:32:46.029376
2020-05-26T04:45:56
2020-05-26T04:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,489
cpp
#include "anonymouscomponent.h" CAnonymousEntComponent::CAnonymousEntComponent() :m_name("") { // nothing } CAnonymousEntComponent::CAnonymousEntComponent(const ntstd::String& name) :m_name(name) { // nothing } CAnonymousEntComponent::~CAnonymousEntComponent() { // nothing } CAnonymousEntComponentMap::CAnonymousEntComponentMap() { // nothing } CAnonymousEntComponentMap::~CAnonymousEntComponentMap() { // nothing } bool CAnonymousEntComponentMap::Add(CAnonymousEntComponent* aec) { ntAssert(aec->HasName()); if(Find(aec->GetName())) { user_warn_msg(( "CAnonymousEntComponent %s allready exists." , aec->GetName().c_str() )); return false; } else { m_container.insert(Container::value_type(aec->GetName().c_str(),aec)); return true; } } bool CAnonymousEntComponentMap::Remove( CAnonymousEntComponent* pobComp ) { ntAssert( pobComp ); return Remove( pobComp->GetName().c_str() ); } bool CAnonymousEntComponentMap::Remove(const char* pcCompName ) { ntAssert( pcCompName ); Container::iterator it = m_container.find( pcCompName ); if( it != m_container.end() ) { m_container.erase( it ); return true; } return false; } // return 0 is not found CAnonymousEntComponent* CAnonymousEntComponentMap::Find(const ntstd::String& name) const { //m_finder.m_pAec->m_name = name; if (!m_container.empty()) { Container::const_iterator it = m_container.find(name.c_str()); if(it != m_container.end()) { return it->second; } } return 0; }
[ "hopefullyidontgetbanned735@gmail.com" ]
hopefullyidontgetbanned735@gmail.com
7e66d4d274ad483996947ef8d3d62dd5918e75a6
f37d8d2dcdf3b3f1aabb09e7b5f69ddbe4a75c09
/t3d-graphics-engine-master/T3D/T3D/WinGLApplication.cpp
597dd8ad6fc4d28d4dfdbfd73c59d8aa5d1185f4
[]
no_license
Ken-na/RoboPirates
8d4f568f0a66c1ba61592a69a239ca0e97e275c4
dd8af05e4e4eb8dfc1cd32fbe994b52902de38d0
refs/heads/master
2023-03-02T09:38:34.898547
2021-02-01T10:18:29
2021-02-01T10:18:29
334,792,779
0
0
null
null
null
null
UTF-8
C++
false
false
4,899
cpp
// ========================================================================================= // KXG363 - Advanced Games Programming, 2012 // ========================================================================================= // // Author: Robert Ollington // // winglapplication.h // // t3d application for windows and OpenGL #include <windows.h> #include <gl/glew.h> #include <GL/GL.h> #include <GL/GLU.h> #include <sdl\SDL_ttf.h> #include "WinGLApplication.h" #include "GLRenderer.h" #include "Transform.h" #include "GameObject.h" #include "Mesh.h" #include "Vector3.h" #include "Input.h" #include "PerfLogTask.h" #include "DiagMessageTask.h" #include "SoundManager.h" // stdin, stdout, and stderr are defined differently in Visual Studio 2015 // This is required to give backward combatibility with the version of SDL being used. FILE _iob[] = { *stdin, *stdout, *stderr }; extern "C" FILE * __cdecl __iob_func(void) { return _iob; } namespace T3D { WinGLApplication::WinGLApplication(void) { surf = NULL; running = false; renderer = new GLRenderer(); root = new Transform(NULL,"Root"); } WinGLApplication::~WinGLApplication(void) { delete root; root = NULL; delete renderer; renderer = NULL; } bool WinGLApplication::init(){ cout << "init\n"; if(SDL_Init(SDL_INIT_EVERYTHING) < 0) { return false; } //Initialize SDL_mixer soundManager->init(); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2); if((surf = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_HWSURFACE | SDL_GL_DOUBLEBUFFER | SDL_OPENGL)) == NULL) { return false; } glewInit(); glClearColor(0, 0, 0, 0); glClearDepth(1.0f); glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); // Initialize SDL_ttf library if (TTF_Init() != 0) { std::cout << "TTF_Init() Failed: " << TTF_GetError() << endl; SDL_Quit(); exit(1); } SDL_WM_GrabInput(SDL_GRAB_ON); SDL_ShowCursor(SDL_DISABLE); std::cout<<glGetString(GL_VERSION)<<"\n"; return true; } int WinGLApplication::run(void){ if(init() == false) { return -1; } running = true; SDL_Event sdlEvent; lastFrame = SDL_GetTicks()/1000.0f; while(running) { soundManager->update(); float thisFrame = SDL_GetTicks()/1000.0f; dt = thisFrame-lastFrame; lastFrame = thisFrame; Input::onMouseMotion(0,0); while(SDL_PollEvent(&sdlEvent)) { handleEvent(&sdlEvent); } updateTasks(); updateComponents(root); renderer->prerender(); renderer->render(root); renderer->postrender(); } quit(); return 0; } void WinGLApplication::quit(void){ SDL_Quit(); } void WinGLApplication::handleEvent(SDL_Event *e){ switch (e->type) { case SDL_QUIT: running = false; break; case SDL_KEYDOWN: Input::onKeyDown(e->key.keysym.sym); if (Input::keyDown[KEY_ESCAPE]) running = false; if (Input::keyDown[KEY_F1]) renderer->toggleWireframe(); if (Input::keyDown[KEY_F2]) renderer->toggleAxes(); if (Input::keyDown[KEY_F3]) renderer->toggleGrid(); if (Input::keyDown[KEY_F4]) renderer->togglePoints(); if (Input::keyDown[KEY_F9]) { int line = 0; addTask(new DiagMessageTask(this, "ESCAPE quit", 2, 600-(line++*20), true, 5.0)); addTask(new DiagMessageTask(this, "F1 wireframe", 2, 600-(line++*20), true, 5.0)); addTask(new DiagMessageTask(this, "F2 axes", 2, 600-(line++*20), true, 5.0)); addTask(new DiagMessageTask(this, "F3 grid", 2, 600 - (line++ * 20), true, 5.0)); addTask(new DiagMessageTask(this, "F4 points", 2, 600 - (line++ * 20), true, 5.0)); addTask(new DiagMessageTask(this, "F9 show help", 2, 600-(line++*20), true, 5.0)); addTask(new DiagMessageTask(this, "F10 show stats", 2, 600-(line++*20), true, 5.0)); } if (Input::keyDown[KEY_F10]) { // find log task PerfLogTask *task = (PerfLogTask *)findTask("PerfLogTask"); if (task) { // toggle on screen diagnostics task->setDiagDisplay(!task->getDiagDisplay()); } } break; case SDL_KEYUP: Input::onKeyUp(e->key.keysym.sym); break; case SDL_MOUSEMOTION: Input::onMouseMotion((e->motion).xrel,(e->motion).yrel); break; } } }
[ "43331896+Ken-na@users.noreply.github.com" ]
43331896+Ken-na@users.noreply.github.com
993ff7814a05e80a4adebf59b372cdadf32d9621
934dd917999f277eb2b99ae138e4020b2da0bce9
/f24/f24.ino
9f35a8b5c681fa9e2d0432a978610137b8be5f5c
[]
no_license
LukJA/f24-team-firefly-2017
5691ecc8b6a4042e0a66c012432ec5109db84c04
de7b33a7417248c0f699502b680c140c9388962d
refs/heads/master
2021-01-23T04:58:50.117902
2017-04-19T18:17:43
2017-04-19T18:17:43
86,259,686
0
0
null
null
null
null
UTF-8
C++
false
false
6,716
ino
#include <OneWire.h> #include <Metro.h> #include <SD.h> #include <SPI.h> // ------------------------------------------- // F24 team firefly main ECU control // OLED dash on SERIAL3 (7,8) // Accel on WIRE2 (3,4) // telem on SPI0 (9-12) // define pins // OUT ---- #define OLEDSer Serial3 #define ignitOut 23 #define buzzOut 22 #define hornOut 21 #define DAC0 A21 #define DAC1 A22 // IN ---- #define battVoltTIn 19 #define battVoltLIn 18 #define battAmpsAIn 17 // shunt #define motorPI 29 #define dAxlePI 30 #define tempsIn 28 #define ignitIn 26 #define masterIn 25 #define resetIn 24 #define hornIn 27 #define throttleIn 20 #define Toffset 2048 // throttle bottom out // variables // -- global // photo interupt set volatile int motorRpm, axlespeedKPH = 0; // shunted // toggle switchs volatile bool master = 0; volatile bool ignition = 0; volatile bool horn = 0; // ds18b20 set volatile int batTemp, motTemp, escTemp = 0; // stored as shunt // battery stats volatile float batVoltLower, batVoltTotal = 125; // stored as true volatile int batCurrent = 0; // shunted to whole number // throttle volatile int throttle = 0; String warning = " "; String warningCleared = " "; // -- system elapsedMillis sinceBoot; // intervals Metro X1millis = Metro(1); // Instantiate an instance Metro X10millis = Metro(10); // Instantiate an instance Metro X100millis = Metro(100); // Instantiate an instance Metro X500millis = Metro(500); // Instantiate an instance // black box SD init File BlackBox; volatile bool SDEN = 0; // Teensy 3.5 & 3.6 on-board: BUILTIN_SDCARD const int chipSelect = BUILTIN_SDCARD; // temp sense OneWire ds18b20(tempsIn); //create instance byte addr[8]; byte data[12]; const byte t1Addr[8] = {0x28, 0x2B, 0x8A, 0x63, 0x08, 0x00, 0x00, 0x1B}; //motor const byte t2Addr[8] = {0x28, 0x34, 0xF6, 0x64, 0x08, 0x00, 0x00, 0xAE}; //esc const byte t3Addr[8] = {0x28, 0xFE, 0x0A, 0x64, 0x08, 0x00, 0x00, 0x79}; //bat #include <MCP3008.h> //define pin connections #define CS_PIN 12 #define CLOCK_PIN 9 #define MOSI_PIN 11 #define MISO_PIN 10 MCP3008 adc(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN); void setup() { // prevent interupting setup noInterrupts(); Serial.begin(9600); // debug serial // led pinMode(13, OUTPUT); digitalWrite(13, HIGH); // set outputs pinMode(ignitOut, OUTPUT); pinMode(buzzOut, OUTPUT); pinMode(hornOut, OUTPUT); // PhotoInterupts handler attachment // all methods are handled in "photoInter.c" pinMode(motorPI, INPUT); attachInterrupt(motorPI, motorPhotoI, RISING); pinMode(dAxlePI, INPUT); attachInterrupt(dAxlePI, dAxlePhotoI, RISING); // UI interupts // methods handled in UI pinMode(ignitIn, INPUT_PULLDOWN); attachInterrupt(ignitIn, ignitionISR, CHANGE); pinMode(masterIn, INPUT_PULLDOWN); attachInterrupt(masterIn, masterISR, CHANGE); pinMode(resetIn, INPUT_PULLDOWN); //attachInterrupt(resetIn, rsetISR, CHANGE); pinMode(hornIn, INPUT_PULLDOWN); attachInterrupt(hornIn, hornISR, CHANGE); // Enable 13bit ADC pinMode(throttleIn, INPUT_PULLDOWN); pinMode(battVoltTIn, INPUT); pinMode(battVoltLIn, INPUT); //analogReadResolution(13); // Enable 12bit DAC pinMode(DAC1, OUTPUT); pinMode(DAC0, OUTPUT); analogWriteResolution(12); // Write 1V to DAC1 (1-4v) analogWrite(DAC1, 1241); // 1V // Setup OLED Serial Display OLEDSer.begin(115200); // begin serial control of OLED // Setup Temperature Sensors (request a convert and set settings) //tempsBegin(); delay(100); // allow first conversion // activate interupts interrupts(); } void loop() { // runs a certain routine every X milliseconds through metro library //every 1 - //every 10 - read and write throttle, ignition //every 100 - send data to oled, //every 500 - read temps + request next, motor current, motor voltage into vars, update boot time, check warnings digitalWrite(13, HIGH); // status is GO if (!master){ ignition = 0; // deactive motor controls throttle = 0; Serial.println(master); // notify debug digitalWrite(13, LOW); // turn of status led delay(200); //wait a bit to give OLED time to catch-up OLEDSer.println("M"); // system disbaled if master is deactivated // Disable interupts??? reset wont work... } while(!master){ // wait until switch is flicked, handled in interupt } if (X1millis.check()){ // nothing yet - may remove } if (X10millis.check()){ // read throttle (13bit) throttle = (analogRead(throttleIn)); Serial.println(throttle); throttle = map(throttle, 30, 300, 0, 4096); analogWrite(DAC0, throttle); // write throttle, its 13bit and output is 12 so shift over one //write ignition if (ignition){ digitalWrite(ignitOut, HIGH); } else{ digitalWrite(ignitOut, LOW); } } if (X100millis.check()){ // send OLED data - in OLED.ino // RPM SPEED V1 V2 AT W#(/10) T1 T2 T3 IG THROT(128) WARN(4) // eg 1337 33 125 126 20 24 26 27 28 1 100 HELP // convert warning char warn[10]; warning.toCharArray(warn, 10); //OLEDData(1337, 33, 125, 126, 20, 24, 26, 27, 28, 1, 100, "HELP"); int draw = map(throttle, 0, 4096, 0, 128); OLEDData(motorRpm, axlespeedKPH, 127, 126, batCurrent, batCurrent*batVoltTotal/10, batTemp, motTemp, escTemp, ignition, draw, warn); //reset the alarm digitalWrite(buzzOut, LOW); } if (X500millis.check()){ sinceBoot = millis(); // update boot time Serial.println(sinceBoot); // voltages + warning batVoltLower = (adc.readadc(0) * 3.3 * 5) / 1023; // divider is 1/5 ref is 3.3 batVoltTotal = (adc.readadc(1) * 3.3 * 11) / 1023; // divider is 1/11 ref is 3.3 //Serial.print(batVoltLower); //Serial.print(batVoltTotal); /* if ((batVoltLower < 10.6 || batVoltTotal-batVoltLower < 10.6) && (warningCleared != "VOLT")){ // set the warning digitalWrite(buzzOut, HIGH); warning = "VOLT"; }*/ // current -- 0.00075 ohm resistor I = v/r // calculates current in A and shunts it to int batCurrent = (int)(adc.readadc(battAmpsAIn) / 1024 * 3.3 /0.00075); /* if ((batCurrent > 50) && (warningCleared != "AMPS")){ // set the warning digitalWrite(buzzOut, HIGH); warning = "AMPS"; }*/ // temps //tempsRead(); // read current (auto updates vars) //tempsRequest(); // request a set for the next loop round /* if ((batTemp > 40 || motTemp > 60 || escTemp > 60) && (warningCleared != "TEMP")){ // set the warning digitalWrite(buzzOut, HIGH); warning = "TEMP"; }*/ } }
[ "lukejandrews@hotmail.co.uk" ]
lukejandrews@hotmail.co.uk
d8a92eaf27150259336d00f1dea9f7077aa86dd0
3acafaea6ada570668aeea4e076110aba8724bb5
/cxxlib/test/test_Signal.cpp
b492bef8a55cece16db18388355c0406cf248574
[]
no_license
frankyueh/cxxlib
4ca1698d3847ca86204122550b8d1b2e5f520aac
d5d508eae79a53d6a73207ea5cea4afaffb736cd
refs/heads/master
2020-05-27T00:31:43.736151
2015-09-23T06:47:54
2015-09-23T06:47:54
41,167,531
0
0
null
null
null
null
UTF-8
C++
false
false
9,577
cpp
#include "Thread.h" #include "EventSignal.h" #include "Mutex.h" #include "gtest/gtest.h" #include "gtest_utilities.h" using namespace cxxlib; /* // Signal_Test //----------------------------------------------------------------------------- class Signal_Test : public ::testing::Test { public: static const unsigned int THREAD_NUMBER = 7; // at least 2 static const unsigned int REPEAT_TIMES = 3; // at least 1 protected: virtual void SetUp() { } virtual void TearDown() { } private: }; #define SIGNAL_TEST_ROUTINE(SignalType, ThreadCase, _stShared_) \ SignalTestRoutine<SignalType, ThreadCase> _cSignalTestRoutine_; \ ThreadCase *_acThread_ = _cSignalTestRoutine_.m_acThread; \ SignalSharedRes<SignalType>& _stShared_ = _cSignalTestRoutine_.m_stShared; #define SIGNAL_THREAD_ROUTINE(SignalType, _cMutex_, _cSignal_, _nSharedCount_, _nCounter_) \ \ Mutex& _cMutex_ = pstShared->cMutex; \ SignalType& _cSignal_ = pstShared->cSignal; \ \ volatile unsigned int& _nSharedCount_ = pstShared->nSharedCount; \ volatile unsigned int& _nCounter_ = pstShared->anCounter[_nSharedCount_]; \ \ _cMutex_.Lock(); \ const unsigned int _nThreadNum_ = _nSharedCount_++; \ _cMutex_.Unlock(); template<class SignalType> struct SignalSharedRes { SignalSharedRes() : cMutex(Mutex::NONRECURSIVE) {} Mutex cMutex; SignalType cSignal; volatile unsigned int nSharedCount; volatile unsigned int anCounter[Signal_Test::THREAD_NUMBER]; EventSignal cHold; }; template<class SignalType, class ThreadCase> class SignalTestRoutine { public: ThreadCase m_acThread[Signal_Test::THREAD_NUMBER]; SignalSharedRes<SignalType> m_stShared; SignalTestRoutine() { m_stShared.nSharedCount = 0; GUTIL_FOREACH_ASSERT_LIMIT( u, Signal_Test::THREAD_NUMBER, { m_stShared.anCounter[u] = 0; m_acThread[u].pstShared = &m_stShared; EXPECT_TRUE(m_acThread[u].Start()); }, Guarded cGuarded(m_stShared.cMutex), u + 1 == m_stShared.nSharedCount, GUTIL_MAX_WAITING_MS); m_stShared.cMutex.Lock(); m_stShared.nSharedCount = 0; m_stShared.cMutex.Unlock(); } ~SignalTestRoutine() { GUTIL_FOREACH_ASSERT_LIMIT( u, Signal_Test::THREAD_NUMBER, NULL, Guarded cGuarded(m_stShared.cMutex), !m_acThread[u].IsRunning(), GUTIL_MAX_WAITING_MS); } }; template<class SignalType> class ThreadCaseBase : public Thread { public: SignalSharedRes<SignalType> *pstShared; }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // CondSetResetTest class CondSetResetTest_Thread : public ThreadCaseBase<CondSignal> { void Run() { SIGNAL_THREAD_ROUTINE(CondSignal, cMutex, cSignal, nSharedCount, nCounter); EXPECT_FALSE(cSignal.IsSet()); EXPECT_FALSE(cSignal.Wait(0)); cMutex.Lock(); nCounter = 1; cMutex.Unlock(); do { EXPECT_TRUE(cSignal.Wait()); cMutex.Lock(); ++nSharedCount; ++nCounter; cMutex.Unlock(); pstShared->cHold.Wait(); } while (nCounter <= Signal_Test::REPEAT_TIMES); } }; TEST_F(Signal_Test, CondSetResetTest) { SIGNAL_TEST_ROUTINE(CondSignal, CondSetResetTest_Thread, stShared); GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, NULL, Guarded cGuarded(stShared.cMutex), 1 == stShared.anCounter[u], GUTIL_MAX_WAITING_MS); for (unsigned int n = 0 ; n < REPEAT_TIMES ; n++) { GTM_THREAD_SLEEPWAIT(); stShared.cHold.Reset(); GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, stShared.cSignal.Set(), Guarded cGuarded(stShared.cMutex), THREAD_NUMBER * n + u + 1 == stShared.nSharedCount, GUTIL_MAX_WAITING_MS); stShared.cHold.Set(false); GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, NULL, Guarded cGuarded(stShared.cMutex), n + 2 == stShared.anCounter[u], GUTIL_MAX_WAITING_MS); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // CondIsSetAndWaitTest class CondIsSetAndWaitTest_Thread : public ThreadCaseBase<CondSignal> { void Run() { SIGNAL_THREAD_ROUTINE(CondSignal, cMutex, cSignal, nSharedCount, nCounter); do { if (cSignal.IsSet()) { if (cSignal.Wait(0)) { cMutex.Lock(); ++nSharedCount; ++nCounter; cMutex.Unlock(); } } else { GTM_THREAD_YIELD(); } } while (nCounter < Signal_Test::REPEAT_TIMES); } }; TEST_F(Signal_Test, CondIsSetAndWaitTest) { SIGNAL_TEST_ROUTINE(CondSignal, CondIsSetAndWaitTest_Thread, stShared); unsigned int nSetCount = 0; GTM_WAIT_UNTIL( { if (nSetCount < THREAD_NUMBER * REPEAT_TIMES && !stShared.cSignal.IsSet()) { ++nSetCount; stShared.cSignal.Set(); } else { GTM_THREAD_YIELD(); } } Guarded cGuarded(stShared.cMutex), THREAD_NUMBER * REPEAT_TIMES == stShared.nSharedCount, GUTIL_MAX_WAITING_MS); for (unsigned int n = 0 ; n < THREAD_NUMBER ; ++n) EXPECT_EQ(+REPEAT_TIMES, stShared.anCounter[n]); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // EventManualReset class EventManualReset_Thread : public ThreadCaseBase<EventSignal> { void Run() { SIGNAL_THREAD_ROUTINE(EventSignal, cMutex, cSignal, nSharedCount, nCounter); EXPECT_FALSE(cSignal.IsSet()); EXPECT_FALSE(cSignal.Wait(0)); cMutex.Lock(); nCounter = 1; cMutex.Unlock(); do { EXPECT_TRUE(cSignal.Wait()); EXPECT_TRUE(cSignal.IsSet()); EXPECT_TRUE(cSignal.Wait()); cMutex.Lock(); ++nSharedCount; ++nCounter; cMutex.Unlock(); pstShared->cHold.Wait(); } while (nCounter <= Signal_Test::REPEAT_TIMES); } }; TEST_F(Signal_Test, EventManualReset) { SIGNAL_TEST_ROUTINE(EventSignal, EventManualReset_Thread, stShared); GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, NULL, Guarded cGuarded(stShared.cMutex), 1 == stShared.anCounter[u], GUTIL_MAX_WAITING_MS); for (unsigned int n = 0 ; n < REPEAT_TIMES ; n++) { GTM_THREAD_SLEEPWAIT(); stShared.cHold.Reset(); stShared.cSignal.Set(false); GTM_WAIT_UNTIL( Guarded cGuarded(stShared.cMutex), THREAD_NUMBER * (n + 1) == stShared.nSharedCount, GUTIL_MAX_WAITING_MS); stShared.cSignal.Reset(); stShared.cHold.Set(false); GTM_THREAD_SLEEPWAIT(); // prevent thread starvation from the code below... GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, NULL, Guarded cGuarded(stShared.cMutex), n + 2 == stShared.anCounter[u], GUTIL_MAX_WAITING_MS); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // EventAutoResetTest class EventAutoResetTest_Thread : public ThreadCaseBase<EventSignal> { void Run() { SIGNAL_THREAD_ROUTINE(EventSignal, cMutex, cSignal, nSharedCount, nCounter); EXPECT_FALSE(cSignal.IsSet()); EXPECT_FALSE(cSignal.Wait(0)); cMutex.Lock(); nCounter = 1; cMutex.Unlock(); do { EXPECT_FALSE(cSignal.IsSet()); EXPECT_TRUE(cSignal.Wait()); cMutex.Lock(); ++nCounter; cMutex.Unlock(); } while (nCounter <= Signal_Test::REPEAT_TIMES); } }; TEST_F(Signal_Test, EventAutoResetTest) { SIGNAL_TEST_ROUTINE(EventSignal, EventAutoResetTest_Thread, stShared); GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, NULL, Guarded cGuarded(stShared.cMutex), 1 == stShared.anCounter[u], GUTIL_MAX_WAITING_MS); GTM_THREAD_SLEEPWAIT(); for (unsigned int n = 0 ; n < REPEAT_TIMES ; n++) { GTM_THREAD_SLEEPWAIT(); stShared.cSignal.Set(true); GTM_THREAD_SLEEPWAIT(); // prevent thread starvation from the code below... GUTIL_FOREACH_ASSERT_LIMIT( u, THREAD_NUMBER, NULL, Guarded cGuarded(stShared.cMutex), n + 2 == stShared.anCounter[u], GUTIL_MAX_WAITING_MS); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // WaitTimeTest TEST_F(Signal_Test, WaitTimeTest) { CondSignal cCondObject; EventSignal cEventObject; GUTIL_EXPECT_EXECTIME( EXPECT_FALSE(cCondObject.Wait(GUTIL_AVG_MEASURE_MS)), GUTIL_AVG_MEASURE_MS, GUTIL_MEASURE_ERR_RANGE ); GUTIL_EXPECT_EXECTIME( { EXPECT_FALSE(cEventObject.IsSet()); EXPECT_FALSE(cEventObject.Wait(GUTIL_AVG_MEASURE_MS)); }, GUTIL_AVG_MEASURE_MS, GUTIL_MEASURE_ERR_RANGE ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // StateControlTest TEST_F(Signal_Test, StateControlTest) { CondSignal cCondSignal; EXPECT_FALSE(cCondSignal.IsSet()); EXPECT_FALSE(cCondSignal.IsSet()); EXPECT_FALSE(cCondSignal.IsSet()); cCondSignal.Set(); EXPECT_TRUE(cCondSignal.IsSet()); EXPECT_TRUE(cCondSignal.IsSet()); EXPECT_TRUE(cCondSignal.IsSet()); EXPECT_TRUE(cCondSignal.Wait(0)); EXPECT_FALSE(cCondSignal.Wait(0)); EXPECT_FALSE(cCondSignal.IsSet()); EXPECT_FALSE(cCondSignal.IsSet()); EXPECT_FALSE(cCondSignal.IsSet()); EventSignal cEventSignal; EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); cEventSignal.Set(false); EXPECT_TRUE(cEventSignal.IsSet()); EXPECT_TRUE(cEventSignal.IsSet()); EXPECT_TRUE(cEventSignal.IsSet()); EXPECT_TRUE(cEventSignal.Wait(1)); EXPECT_TRUE(cEventSignal.Wait(1)); cEventSignal.Reset(); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); cEventSignal.Set(true); EXPECT_FALSE(cEventSignal.Wait(0)); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); cEventSignal.Reset(); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); EXPECT_FALSE(cEventSignal.IsSet()); } */
[ "yueh.frank@gmail.com" ]
yueh.frank@gmail.com
faf29b654edc0b31d30eaa263252f574b83dc9e4
3e38a461d1b02cb3eed7fe41328b5f501e33aebe
/4lab/4lab_2/Levenshtein.cpp
c0315a4cc630d8c5e2a031c0103f892b01d9a0ef
[]
no_license
Vokamrecom/-MathProga
41ee341b0cd5f7654ab792c0965b4782ad79e9b4
ce5833cfac18c9b65712f53e0d4987a24a4e338b
refs/heads/master
2021-04-26T23:01:51.371097
2018-05-28T11:25:33
2018-05-28T11:25:33
123,917,350
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,795
cpp
#include "stdafx.h" #include <iomanip> #include <algorithm> #include "Levenshtein.h" #define DD(i,j) d[(i)*(ly+1)+(j)] int min3(int x1, int x2, int x3) { return std::min(std::min(x1, x2), x3); //минимальное из трех } int levenshtein(int lx, const char x[], int ly, const char y[]) //длина слова х, слово длиной lx //длина слова y, слово длиной ly { int *d = new int[(lx + 1)*(ly + 1)]; for (int i = 0; i <= lx; i++) DD(i, 0) = i; //длина строки х=i (кол-во символов в слове x), а DD возвращ. саму строку for (int j = 0; j <= ly; j++) DD(0, j) = j; //длина строки y=j for (int i = 1; i <= lx; i++) for (int j = 1; j <= ly; j++) { DD(i, j) = min3(DD(i - 1, j) + 1, DD(i, j - 1) + 1, DD(i - 1, j - 1) + (x[i - 1] == y[j - 1] ? 0 : 1)); } return DD(lx, ly); //возвращает длину слова и строки } int levenshtein_r( //рекурсия int lx, const char x[], int ly, const char y[] ) { int rc = 0; //результат, дистанция if (lx == 0) rc = ly; //елси длина x=0, то дистанция = длине слова y else if (ly == 0) rc = lx; else if (lx == 1 && ly == 1 && x[0] == y[0]) rc = 0; //если длина x = длина y = 1 и первые буквы совапали, дистанция = 0 else if (lx == 1 && ly == 1 && x[0] != y[0]) rc = 1; //если длина x = длина y = 1 и первые буквы не совапали, дистанция = 1 else rc = min3( levenshtein_r(lx - 1, x, ly, y) + 1, levenshtein_r(lx, x, ly - 1, y) + 1, levenshtein_r(lx - 1, x, ly - 1, y) + (x[lx - 1] == y[ly - 1] ? 0 : 1) ); return rc; };
[ "ermakovkiril@gmail.com" ]
ermakovkiril@gmail.com
89ffd828f81acf95765c137b0fe3bb7fd8bbf8fe
93becb0e207e95d75dbb05c92c08c07402bcc492
/atcoder/2019_7_27_技術室奥/b.cpp
1bcaf48dea04fad22515aba7924be900d47f76ae
[]
no_license
veqcc/atcoder
2c5f12e12704ca8eace9e2e1ec46a354f1ec71ed
cc3b30a818ba2f90c4d29c74b4d2231e8bca1903
refs/heads/master
2023-04-14T21:39:29.705256
2023-04-10T02:31:49
2023-04-10T02:31:49
136,691,016
2
0
null
null
null
null
UTF-8
C++
false
false
671
cpp
#include <functional> #include <algorithm> #include <iostream> #include <iomanip> #include <cstring> #include <string> #include <vector> #include <random> #include <bitset> #include <queue> #include <cmath> #include <stack> #include <set> #include <map> typedef long long ll; using namespace std; const ll MOD = 1000000007LL; int main() { cin.sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, k; cin >> n >> k; int idx = -1; int mx = 0; for (int i = 1; i <= n; i++) { int a; cin >> a; if (a < k && a > mx) { mx = a; idx = i; } } cout << idx << "\n"; return 0; }
[ "kambe3141@gmail.com" ]
kambe3141@gmail.com
aa18aa2d31bb0b445c7544bac7316b75cb9f6fb0
ee5f4030fd7c72a34c49717d4bd08334f19403b3
/ScriptEmbedder/src/scriptembedderbuilder.cc
32c14ae491189fc2da6a25c5df263033e41581c9
[ "MIT" ]
permissive
PerttuP/ScriptEmbedder
ade2cc464ac98059a13ebe810688953166b83e4b
98f39da5f176af830aa0310023afdcc4c61f3e0d
refs/heads/master
2021-01-01T05:27:29.933906
2016-06-06T20:27:57
2016-06-06T20:27:57
59,598,333
0
0
null
null
null
null
UTF-8
C++
false
false
438
cc
/** * @file * @brief Implements the ScriptEmbedderBuilder class defined in scripembedderbuilder.hh. * @author Perttu Paarlahti 2016. */ #include "scriptembedderbuilder.hh" #include "serialscriptembedder.hh" namespace ScriptEmbedderNS { ScriptEmbedder*ScriptEmbedderBuilder::createSerialEmbedder(const Configuration& conf) { Q_ASSERT(conf.isValid()); return new SerialScriptEmbedder(conf); } }// namespace ScriptEmbedderNS
[ "perttu.paarlahti@gmail.com" ]
perttu.paarlahti@gmail.com
7bfff978bc134495f00a5311e97fc4aad106e7ef
d9bf27e750b24652aa89029f85ce90f75e98b395
/yukicoder/182.cpp
8927b5a45f8212c1b77884bd399027289d5e761c
[]
no_license
r2en/Competitive_Programming
09bd2074ba73081fdb044c38db87568d2b918a4a
dc7f06fcfcfd302c568324337c50e3b7eb1495ab
refs/heads/master
2021-06-13T18:04:55.350268
2017-04-25T10:11:51
2017-04-25T10:11:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
#include <iostream> #include <map> using namespace std; int main(){ int N; cin >> N; int cnt = 0; int mmax = 0; int *m; m = new int[N]; for(int i = 0; i < N; ++i){ int a = 0; cin >> a; m[a]++; mmax = max(a,mmax); } for(int i = 0; i <= mmax; ++i){ if(m[i]==1){ cnt++; } } cout << cnt << endl; delete[] m; return 0; }
[ "s12161te@gmail.com" ]
s12161te@gmail.com
3261827c90edf8feb74dd42e8185bd36386138a3
f23fea7b41150cc5037ddf86cd7a83a4a225b68b
/SDK/BP_ipg_costume_reapers_01_Desc_classes.h
781f5b58e7a6d797af023bcb7e68955cf70478c8
[]
no_license
zH4x/SoT-SDK-2.2.0.1
36e1cf7f23ece6e6b45e5885f01ec7e9cd50625e
f2464e2e733637b9fa0075cde6adb5ed2be8cdbd
refs/heads/main
2023-06-06T04:21:06.057614
2021-06-27T22:12:34
2021-06-27T22:12:34
380,845,087
0
0
null
null
null
null
UTF-8
C++
false
false
789
h
#pragma once // Name: SoT, Version: 2.2.0b /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_ipg_costume_reapers_01_Desc.BP_ipg_costume_reapers_01_Desc_C // 0x0000 (FullSize[0x00E8] - InheritedSize[0x00E8]) class UBP_ipg_costume_reapers_01_Desc_C : public UCostumeDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_ipg_costume_reapers_01_Desc.BP_ipg_costume_reapers_01_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
ebaacc31272be31988d0aa35ce35ad7c466a6a69
9402c9f35b6d895c3b6f7ddcfc87241e6b9145d8
/Codechef/JulyLT14/test.cpp
02f5037fb63ac844d60030eea6be9b945f8e423f
[]
no_license
siddharth94/competitive
586d42679558dcd1dcca3457c2ca7be089cbda30
ecda01521a7a9908225771d9374d5c18fa646515
refs/heads/master
2021-07-06T05:27:13.395384
2017-09-29T10:16:20
2017-09-29T10:16:20
105,229,373
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include <bits/stdc++.h> using namespace std; #define F(i,n) for(int i=0;i<n;i++) #define FE(i,n) for(int i=0;i<=n;i++) #define FR(i,n) for(int i=n;i>0;i--) #define FRE(i,n) for(int i=n;i>=0;i--) #define LL long long #define gc getchar_unlocked void get(int &x) { register int c = gc(); x = 0; int neg = 0; for(;((c<48 || c>57) && c != '-');c = gc()); if(c=='-') {neg=1;c=gc();} for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} if(neg) x=-x; } int main() { bool mark[10005]={}; F(i,10005) cout << mark[i] << endl; return 0; }
[ "siddharthgg52@gmail.com" ]
siddharthgg52@gmail.com
4e7d2537804ce834944509f09d9d94885a920e4e
80325ad653c6bb7b66f8bf6bfef232db867ad3fb
/2018/MultiDirectionalList/MultiDirectionalList/MultiDirectionalList.cpp
601ed4963bb0068eeceafff2545ea55bf742b955
[]
no_license
gmc1322/FreeTime
e2e5a1c23ef55f5325f57bb57ddbcfe0d10c088c
ac86cba38a54a0dda9797df061d1080cd84add29
refs/heads/master
2020-04-16T16:23:46.830821
2019-01-15T00:24:04
2019-01-15T00:24:04
165,735,010
0
0
null
null
null
null
UTF-8
C++
false
false
51,381
cpp
#include "MultiDirectionalList.h" #include <iostream> #include <algorithm> using namespace MDLSpace; Direction::Direction( const std::vector< float > &DirectionValues ) noexcept : Angles{ DirectionValues } { } Direction::Direction( std::vector< float > &&DirectionValues ) noexcept : Angles{ std::move( DirectionValues ) } { } bool Direction::operator<( const Direction &Rhs ) const noexcept { size_t i = 0; for( auto Iter : Angles ) { const float &Compair = Rhs.Angles[ i ]; if( Iter < Compair ) { return true; } if( Compair < Iter ) { return false; } ++i; } return false; } int Direction::Calc( const std::vector< size_t > &DimSizes ) const ExceptDebug { int Return = 0; size_t j = 0; size_t Mult = 1; for( auto AngleIter = Angles.cbegin(), AngleEnd = Angles.cend(); AngleIter != AngleEnd; ++AngleIter, ++j ) { Mult *= DimSizes[ j ]; Return += static_cast< int >( *AngleIter / 90 * Mult ); } return Return; // NamedRVO } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr::DirectionPtr( const Direction &Dir, Directions *NextPtr ) noexcept : Dir{ Dir }, NextPtr( NextPtr ) { } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr::DirectionPtr( const DirectionPtr &Copy ) noexcept : Dir{ Copy.Dir }, NextPtr( nullptr ) { } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr::DirectionPtr( DirectionPtr &&Move ) noexcept : Dir{ Move.Dir }, NextPtr( Move.NextPtr ) { Move.NextPtr = nullptr; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr & MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr::operator=( const DirectionPtr &Copy ) noexcept { Dir = Copy.Dir; return *this; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr & MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr::operator=( DirectionPtr &&Move ) noexcept { Dir = std::move( Move.Dir ); return *this; } template< typename ListType, size_t DirectionCount > bool MultiDirectionalList< ListType, DirectionCount >::Directions::DirectionPtr::operator<( const DirectionPtr &Rhs ) const noexcept { return Dir < Rhs.Dir; } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >:: Directions::Directions( const ListType &Data, const std::initializer_list< DirectionPtr > &Directions ) ExceptDebug : Data{ Data }, DirectionArray{ Directions } { AssertDebug( Directions.size() != DirectionCount, NotEnoughDirectionInitializers{ Directions.size() } ); std::sort( DirectionArray.begin(), DirectionArray.end() ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::Directions( const ListType &Data, const std::vector< DirectionPtr > &Directions ) ExceptDebug : Data{ Data }, DirectionArray{ Directions } { AssertDebug( Directions.size() != DirectionCount, NotEnoughDirectionInitializers{ Directions.size() } ); std::sort( DirectionArray.begin(), DirectionArray.end() ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::Directions( ListType &&Data, std::vector< DirectionPtr > &&Directions ) ExceptDebug : Data{ std::move( Data ) }, DirectionArray{ std::move( Directions ) } { AssertDebug( Directions.size() != DirectionCount, NotEnoughDirectionInitializers{ Directions.size() } ); std::sort( DirectionArray.begin(), DirectionArray.end() ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::Directions( const ListType &Data, const DirInitType &Directions ) noexcept : Data{ Data } { for( size_t i = 0; i < DirectionCount; ++i ) { DirectionArray[ i ] = DirectionPtr{ Directions[ i ].Dir }; } std::sort( DirectionArray.begin(), DirectionArray.end() ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::Directions( ListType &&Data, const DirInitType &Directions ) noexcept : Data{ std::move( Data ) } { for( size_t i = 0; i < DirectionCount; ++i ) { DirectionArray[ i ] = DirectionPtr{ Directions[ i ].Dir }; } std::sort( DirectionArray.begin(), DirectionArray.end() ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Directions::Directions( ListType &&Data, DirInitType &&Directions ) noexcept : Data{ std::move( Data ) }, DirectionArray( std::move( Directions ) ) { std::sort( DirectionArray.begin(), DirectionArray.end() ); } template< typename ListType, size_t DirectionCount> MultiDirectionalList< ListType, DirectionCount >::Directions::Directions( Directions &&Dir ) noexcept : Data{ std::move( Dir.Data ) }, DirectionArray{ std::move( Dir.DirectionArray ) } { } template< typename ListType, size_t DirectionCount > void MultiDirectionalList< ListType, DirectionCount >::Directions::operator=( Directions &&Dir ) noexcept { Data = std::move( Dir.Data ); DirectionArray = std::move( Dir.DirectionArray ); } template< typename ListType, size_t DirectionCount > size_t MultiDirectionalList< ListType, DirectionCount >::Directions::Find( const std::vector< float > &Direction_ ) noexcept { const DirectionPtr Compair{ Direction{ Direction_ } }; const DirectionPtr *Start = DirectionArray.begin(); return static_cast< DirectionPtr * >( std::bsearch( &Compair, Start, DirectionCount, sizeof( DirectionArray[ 0 ] ), []( const void *Lhs, const void *Rhs )->int { const DirectionPtr *LhsPtr = static_cast< const DirectionPtr * >( Lhs ); const DirectionPtr *RhsPtr = static_cast< const DirectionPtr * >( Rhs ); return *LhsPtr < *RhsPtr ? -1 : ( *RhsPtr < *LhsPtr ? 1 : 0 ); } ) ) - Start; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >:: Directions::CouldNotFind::CouldNotFind( const std::vector< float > &Angles ) noexcept { std::cerr << "Could not find the angles: "; auto End = Angles.end(); --End; for( auto Iter = Angles.begin(); Iter != End; ++Iter ) { std::cerr << *Iter << ", "; } std::cerr << " and " << *End << std::endl; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Iterator::Iterator( const std::vector< size_t > &DimensionSizes, Directions *Begin ) noexcept : DimensionSizes( DimensionSizes ), Iter( Begin ) { } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Iterator::Iterator( const Iterator &Rhs ) noexcept : DimensionSizes{ Rhs.DimensionSizes }, Iter( Rhs.Iter ) { } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Iterator::Iterator( Iterator &&Rhs ) noexcept : DimensionSizes{ std::move( Rhs.DimensionSizes ) }, Iter( Rhs.Iter ) { } template< typename ListType, size_t DirectionCount > ListType & MultiDirectionalList< ListType, DirectionCount >::Iterator::operator*() const noexcept { return Iter->Data; } template< typename ListType, size_t DirectionCount > ListType * MultiDirectionalList< ListType, DirectionCount >::Iterator::operator->() const noexcept { return &( Iter->Data ); } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator & MultiDirectionalList< ListType, DirectionCount >::Iterator::operator++() noexcept { Iter = Iter->Next.NextPtr; return *this; } template< typename ListType, size_t DirectionCount > bool MultiDirectionalList< ListType, DirectionCount >::Iterator::operator!=( const Iterator &Rhs ) const noexcept { return Iter != Rhs.Iter; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator & MultiDirectionalList< ListType, DirectionCount >::Iterator::operator=( const Iterator &Rhs ) noexcept { Iter = Rhs.Iter; return *this; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator & MultiDirectionalList< ListType, DirectionCount >::Iterator::operator=( Iterator &&Rhs ) noexcept { Iter = Rhs.Iter; return *this; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator & MultiDirectionalList< ListType, DirectionCount >::Iterator::Move( size_t Index ) ExceptDebug { size_t DirIndex = DirectionCount - 1; const StaticArray< typename Directions::DirectionPtr, DirectionCount > &Array = Iter->DirectionArray; Direction Dir = Array[ DirIndex ].Dir; const Direction Zero{ std::vector< float >( DimensionSizes.size() ) }; while( Zero < Dir ) { const size_t End = static_cast< size_t >( std::abs( Dir.Calc( DimensionSizes ) ) ); while( End <= Index ) { Iter = Iter->DirectionArray[ DirIndex ].NextPtr; if( !Iter ) { break; } Index -= End; } if( Index ) { Dir = Array[ --DirIndex ].Dir; } else { return *this; } } for( size_t i = 0; i < Index; ++i ) { Iter = Iter->Next.NextPtr; AssertDebug( !Iter, ( MovedTooFar{ Index, false } ) ); } return *this; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator & MultiDirectionalList< ListType, DirectionCount >::Iterator::MoveBack( size_t Index ) ExceptDebug { size_t DirIndex = 0; const StaticArray< typename Directions::DirectionPtr, DirectionCount > &Array = Iter->DirectionArray; Direction Dir = Array[ DirIndex ].Dir; DebugElse( const Direction Zero{ std::vector< float >( DimensionSizes.size() ) }; while( Dir < Zero ), for( ; ; ) ) { const size_t End = static_cast< size_t >( std::abs( Dir.Calc( DimensionSizes ) ) ); while( End <= Index ) { Iter = Iter->DirectionArray[ DirIndex ].NextPtr; if( !Iter ) { break; } Index -= End; } if( Index ) { Dir = Array[ ++DirIndex ].Dir; } else { return *this; } } DebugOnly( throw( UnableToMove( Index, DimensionSizes[ 0 ] ) ) ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Iterator::MovedTooFar::MovedTooFar( size_t Index, bool Back ) noexcept { if( Back ) { std::cerr << "You tried to move the Iterator back " << Index << " nodes, but there is no node there!" << std::endl; } else { std::cerr << "You tried to move the Iterator forward " << Index << " nodes, but there is no node there!" << std::endl; } } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Iterator::UnableToMove::UnableToMove( size_t Index, size_t DimSize ) noexcept { std::cerr << "The Iterator is unable to move back " << Index << " spaces with the available directions!" << std::endl; std::cerr << "This can be fixed by including the direction: { -" << 1.0f / DimSize * 90 << "f, 0 }" << std::endl; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator & MultiDirectionalList< ListType, DirectionCount >::Iterator::Move( const Direction &Dir, size_t Count ) ExceptDebug { const size_t Index = Iter->Find( Dir.Angles ); for( size_t i = 0; i < Count; ++i ) { Iter = Iter->DirectionArray[ Index ].NextPtr; AssertDebug( !Iter, ( MultiDirectionalList< ListType, DirectionCount >::MovedTooFar{ Dir, Count } ) ); } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::ConstIterator::ConstIterator( const std::vector< size_t > &DimensionSizes, Directions *Begin ) noexcept : Iterator( DimensionSizes, Begin ) { } template< typename ListType, size_t DirectionCount > const ListType & MultiDirectionalList< ListType, DirectionCount >::ConstIterator::operator*() const noexcept { return static_cast< Iterator *const >( this )->operator*(); } template< typename ListType, size_t DirectionCount > const ListType * MultiDirectionalList< ListType, DirectionCount >::ConstIterator::operator->() const noexcept { return static_cast< Iterator *const >( this )->operator->(); } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::ConstIterator & MultiDirectionalList< ListType, DirectionCount >::ConstIterator::Move( const Direction &Dir, size_t Count ) ExceptDebug { static_cast< Iterator *const >( this )->Move( Dir, Count ); return *this; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::ConstIterator & MultiDirectionalList< ListType, DirectionCount >::ConstIterator::Move( size_t Index ) ExceptDebug { static_cast< Iterator *const >( this )->Move( Index ); return *this; } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::MultiDirectionalList( const ListType &Data, const DirInitType &Directions_, const std::vector< size_t > &DimensionCounts ) ExceptDebug : DimensionSizes{ DimensionCounts }, DirectionsMemory( DimensionSizes, Data, Directions_ ), DirectionalHead( DirectionsMemory.GetTop() ), Size( 1 ) { AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionSizes.size(),( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionSizes.size() } ) ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::MultiDirectionalList( ListType &&Data, DirInitType &&Directions_, std::vector< size_t > &&DimensionCounts ) ExceptDebug : DimensionSizes{ std::move( DimensionCounts ) }, DirectionsMemory( DimensionSizes, std::move( Data ), std::move( Directions_ ) ), DirectionalHead( DirectionsMemory.GetTop() ), Size( 1 ) { AssertDebug( DirectionsMemory.GetTop()->DirectionArray[ 0 ].Dir.Angles.size() != DimensionSizes.size(), ( DirectionSizeError{ DirectionsMemory.GetTop()->DirectionArray[ 0 ].Dir.Angles.size(), DimensionSizes.size() } ) ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::MultiDirectionalList( const DataInitType &Data, const DirInitType &Directions_, const std::vector< size_t > &DimensionCounts ) ExceptDebug : DimensionSizes{ DimensionCounts }, DirectionsMemory( Data.size(), *( Data.begin() ), Directions_ ), DirectionalHead( DirectionsMemory.GetTop() ), Size( 1 ) { AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionSizes.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionSizes.size() } ) ); Directions *Iter = DirectionalHead; for( auto DataIter = Data.begin(), EndIter = Data.end(); ++DataIter != EndIter; ) { Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ *DataIter, DirectionalHead->DirectionArray } ); Iter = Iter->Next.NextPtr; ++Size; } ValidateIterators(); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::MultiDirectionalList( DataInitType &&Data, DirInitType &&Directions_, std::vector< size_t > &&DimensionCounts ) ExceptDebug : DimensionSizes{ std::move( DimensionCounts ) }, DirectionsMemory( Data.size(), std::move( *( Data.begin() ) ), std::move( Directions_ ) ), DirectionalHead( DirectionsMemory.GetTop() ), Size( 1 ) { AssertDebug( DirectionsMemory.GetTop()->DirectionArray[ 0 ].Dir.Angles.size() != DimensionSizes.size(), ( DirectionSizeError{ DirectionsMemory.GetTop()->DirectionArray[ 0 ].Dir.Angles.size(), DimensionSizes.size() } ) ); Directions *Iter = DirectionalHead; for( auto DataIter = Data.begin(), EndIter = Data.end(); ++DataIter != EndIter; ) { Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *DataIter ), DirectionalHead->DirectionArray } ); Iter = Iter->Next.NextPtr; ++Size; } ValidateIterators(); } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator MultiDirectionalList< ListType, DirectionCount >::Move( const Direction &Dir, size_t Count ) ExceptDebug { Directions *ReturnPtr = DirectionalHead; const size_t Index = ReturnPtr->Find( Dir.Angles ); for( size_t i = 0; i < Count; ++i ) { ReturnPtr = ReturnPtr->DirectionArray[ Index ].NextPtr; AssertDebug( !ReturnPtr, ( MovedTooFar{ Dir, Count } ) ); } return Iterator{ DimensionSizes, ReturnPtr }; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator MultiDirectionalList< ListType, DirectionCount >::Move( size_t Index ) ExceptDebug { Iterator Return{ DimensionSizes, MoveTo( DirectionalHead, Index ) }; return Return; // NamedRVO } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::ConstIterator MultiDirectionalList< ListType, DirectionCount >::Move( const Direction &Dir, size_t Count ) const ExceptDebug { Directions *ReturnPtr = DirectionalHead; const size_t Index = ReturnPtr->Find( Dir.Angles ); for( size_t i = 0; i < Count; ++i ) { ReturnPtr = ReturnPtr->DirectionArray[ Index ].NextPtr; AssertDebug( !ReturnPtr, ( MovedTooFar{ Dir, Count } ) ); } return ConstIterator{ DimensionSizes, ReturnPtr }; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::ConstIterator MultiDirectionalList< ListType, DirectionCount >::Move( size_t Index ) const ExceptDebug { ConstIterator Return{ DimensionSizes, MoveTo( DirectionalHead, Index ) }; return Return; // NamedRVO } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushBack( const ListType &Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ Size - 1, Size } ) ); MoveTo( DirectionalHead, Size - 1 )->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ Data, DirectionalHead->DirectionArray } ); ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushBack( ListType &&Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ Size - 1, Size } ) ); MoveTo( DirectionalHead, Size - 1 )->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( Data ), DirectionalHead->DirectionArray } ); ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushBack( const DataInitType &Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ Size - 1, Size } ) ); Directions *Iter = MoveTo( DirectionalHead, Size - 1 ); for( auto VecIter : Data ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ VecIter, DirectionalHead->DirectionArray } ); ++Size; } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushBack( DataInitType &&Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ Size - 1, Size } ) ); Directions *Iter = MoveTo( DirectionalHead, Size - 1 ); for( auto Begin = Data.begin(), End = Data.end(); Begin != End; ++Begin, ++Size ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), DirectionalHead->DirectionArray } ); } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushBack( const DataInitType &Data, const DirInitType &Directions_, const std::vector< size_t > &DimensionCounts ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ Size - 1, Size } ) ); AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); DimensionSizes = DimensionCounts; Directions *Iter = MoveTo( DirectionalHead, Size - 1 ); for( auto VecIter : Data ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ VecIter, Directions_ } ); ++Size; } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushBack( DataInitType &&Data, DirInitType &&Directions_, std::vector< size_t > &&DimensionCounts ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ Size - 1, Size } ) ); AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); DimensionSizes = std::move( DimensionCounts ); Directions *Iter = MoveTo( DirectionalHead, Size - 1 ); auto End = Data.end(); --End; for( auto Begin = Data.begin() ; Begin != End; ++Begin, ++Size ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), Directions_ } ); } Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *End ), std::move( Directions_ ) } ); return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( const ListType &Data, const DirInitType &Directions_, const std::vector< size_t > &DimensionCounts ) ExceptDebug { AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); DimensionSizes = DimensionCounts; if( !DirectionalHead ) { DirectionalHead = DirectionsMemory = std::make_pair( DimensionSizes, Directions{ Data, Directions_ } ); } else { Directions *Temp = DirectionalHead; DirectionalHead = DirectionsMemory.SetBlock( Directions{ Data, Directions_ } ); DirectionalHead->Next.NextPtr = Temp; } ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( ListType &&Data, DirInitType &&Directions_, std::vector< size_t > &&DimensionCounts ) ExceptDebug { AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); DimensionSizes = std::move( DimensionCounts ); if( !DirectionalHead ) { DirectionalHead = DirectionsMemory = std::make_pair( DimensionSizes, Directions{ std::move( Data ), std::move( Directions_ ) } ); } else { Directions *Temp = DirectionalHead; DirectionalHead = DirectionsMemory.SetBlock( Directions{ std::move( Data ), std::move( Directions_ ) } ); DirectionalHead->Next.NextPtr = Temp; } ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( const DataInitType &Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, Size } ) ); Directions *Temp = DirectionalHead; Directions* *Iter = &DirectionalHead; for( auto Begin = Data.rbegin(), End = Data.rend(); Begin != End; ++Begin ) { ( *Iter ) = DirectionsMemory.SetBlock( Directions{ *Begin, Temp->DirectionArray } ); Iter = &( ( *Iter )->Next.NextPtr ); ++Size; } ( *Iter )->Next.NextPtr = Temp; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( DataInitType &&Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, Size } ) ); Directions *Temp = DirectionalHead; Directions* *Iter = &DirectionalHead; for( auto Begin = Data.rbegin(), End = Data.rend(); Begin != End; ++Begin ) { ( *Iter ) = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), Temp->DirectionArray } ); Iter = &( ( *Iter )->Next.NextPtr ); ++Size; } ( *Iter )->Next.NextPtr = Temp; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( const DataInitType &Data, const DirInitType &Directions_, const std::vector< size_t > &DimensionCounts ) ExceptDebug { AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); DimensionSizes = DimensionCounts; if( !DirectionalHead ) { DirectionalHead = DirectionsMemory = std::make_pair( Data.size(), Directions{ std::move( *( Data.begin() ) ), std::move( Directions_ ) } ); Directions *Iter = DirectionalHead; for( auto Begin = Data.rbegin(), End = Data.rend(); ++Begin != End; ) { Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ *Begin, Directions_ } ); Iter = Iter->Next.NextPtr; ++Size; } } else { Directions *Temp = DirectionalHead; Directions* *Iter = &DirectionalHead; for( auto Begin = Data.rbegin(), End = Data.rend(); Begin != End; ++Begin ) { ( *Iter ) = DirectionsMemory.SetBlock( Directions{ *Begin, Directions_ } ); Iter = &( ( *Iter )->Next.NextPtr ); ++Size; } ( *Iter )->Next.NextPtr = Temp; } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( DataInitType &&Data, DirInitType &&Directions_, std::vector< size_t > &&DimensionCounts ) ExceptDebug { AssertDebug( Directions_[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions_[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); DimensionSizes = DimensionCounts; if( !DirectionalHead ) { DirectionalHead = DirectionsMemory = std::make_pair( Data.size(), Directions{ std::move( *( Data.begin() ) ), Directions_ } ); Directions *Iter = DirectionalHead; auto End = Data.rend(); --End; for( auto Begin = Data.rbegin(); ++Begin != End; ) { Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), Directions_ } ); Iter = Iter->Next.NextPtr; ++Size; } Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *End ), std::move( Directions_ ) } ); ++Size; } else { Directions *Temp = DirectionalHead; Directions* *Iter = &DirectionalHead; auto End = Data.rend(); --End; for( auto Begin = Data.rbegin(); Begin != End; ++Begin ) { ( *Iter ) = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), Directions_ } ); Iter = &( ( *Iter )->Next.NextPtr ); ++Size; } ( *Iter ) = DirectionsMemory.SetBlock( Directions{ std::move( *End ), std::move( Directions_ ) } ); ( *Iter )->Next.NextPtr = Temp; ++Size; } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( const ListType &Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, Size } ) ); Directions *Temp = DirectionalHead; DirectionalHead = DirectionsMemory.SetBlock( Directions{ Data, DirectionalHead->DirectionArray } ); DirectionalHead->Next.NextPtr = Temp; ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PushFront( ListType &&Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, Size } ) ); Directions *Temp = DirectionalHead; DirectionalHead = DirectionsMemory.SetBlock( Directions{ std::move( Data ), DirectionalHead->DirectionArray } ); DirectionalHead->Next.NextPtr = Temp; ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertAfter( const ListType &Data, size_t Index ) ExceptDebug { Directions *Temp = MoveTo( DirectionalHead, Index ); Directions *NextTemp = Temp->Next.NextPtr; Temp->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ Data, DirectionalHead->DirectionArray } ); Temp->Next.NextPtr = NextTemp; ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertAfter( ListType &&Data, size_t Index ) ExceptDebug { Directions *Temp = MoveTo( DirectionalHead, Index ); Directions *NextTemp = Temp->Next.NextPtr; Temp->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( Data ), DirectionalHead->DirectionArray } ); Temp->Next.NextPtr->Next.NextPtr = NextTemp; ++Size; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertAfter( const DataInitType &Data, size_t Index ) ExceptDebug { Directions *Iter = MoveTo( DirectionalHead, Index ); Directions *Temp = Iter->Next.NextPtr; for( auto VecIter : Data ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ VecIter, DirectionalHead->DirectionArray } ); ++Size; } Iter->Next.NextPtr = Temp; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertAfter( DataInitType &&Data, size_t Index ) ExceptDebug { Directions *Iter = MoveTo( DirectionalHead, Index ); Directions *Temp = Iter->Next.NextPtr; for( auto Begin = Data.begin(), End = Data.end(); Begin != End; ++Begin ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), DirectionalHead->DirectionArray } ); ++Size; } Iter->Next.NextPtr = Temp; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertBefore( const ListType &Data, size_t Index ) ExceptDebug { return InsertAfter( Data, Index - 1 ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertBefore( ListType &&Data, size_t Index ) ExceptDebug { return InsertAfter( std::move( Data ), Index - 1 ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertBefore( const DataInitType &Data, size_t Index ) ExceptDebug { Directions *Iter = MoveTo( DirectionalHead, Index ); Directions *Temp = Iter->Next.NextPtr; for( auto Begin = Data.rbegin(), End = Data.rend(); Begin != End; ++Begin ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ *Begin, DirectionalHead->DirectionArray } ); ++Size; } Iter->Next.NextPtr = Temp; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::InsertBefore( DataInitType &&Data, size_t Index ) ExceptDebug { Directions *Iter = MoveTo( DirectionalHead, Index ); Directions *Temp = Iter->Next.NextPtr; for( auto Begin = Data.rbegin(), End = Data.rend(); Begin != End; ++Begin ) { Iter = Iter->Next.NextPtr = DirectionsMemory.SetBlock( Directions{ std::move( *Begin ), DirectionalHead->DirectionArray } ); ++Size; } Iter->Next.NextPtr = Temp; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PopFront() ExceptDebug { DirectionalHead = DirectionalHead->Next.NextPtr; DirectionsMemory.Erase( 0 ); --Size; InvalidateIterators(); return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::PopBack() ExceptDebug { return Erase( Size - 1 ); } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::Erase( size_t Index ) ExceptDebug { Directions *PrevTemp = MoveTo( DirectionalHead, Index - 1 ); PrevTemp->Next.NextPtr = PrevTemp->Next.NextPtr->Next.NextPtr; DirectionsMemory.Erase( Index ); --Size; InvalidateIterators(); return *this; } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Iterator MultiDirectionalList< ListType, DirectionCount >::begin() noexcept { return Iterator{ DimensionSizes, DirectionalHead }; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::ConstIterator MultiDirectionalList< ListType, DirectionCount >::begin() const noexcept { return ConstIterator{ DirectionalHead }; } template< typename ListType, size_t DirectionCount > const typename MultiDirectionalList< ListType, DirectionCount >::ConstIterator MultiDirectionalList< ListType, DirectionCount >::end() const noexcept { return ConstIterator{ DimensionSizes }; } template< typename ListType, size_t DirectionCount > size_t MultiDirectionalList< ListType, DirectionCount >::GetSize() const noexcept { return Size; } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::ValidateIterators() noexcept { for( size_t i = 0; i < DirectionCount; ++i ) { const typename Directions::DirectionPtr &DirIter = DirectionalHead->DirectionArray[ i ]; Directions *Iter = DirectionalHead; const int End = DirIter.Dir.Calc( DimensionSizes ); Iter = MoveTo( Iter, std::abs( End ) ); Directions *Start = DirectionalHead; if( End > 0 ) { while( Iter ) { Start->DirectionArray[ i ].NextPtr = Iter; Start = Start->Next.NextPtr; Iter = Iter->Next.NextPtr; } } else { while( Iter ) { Iter->DirectionArray[ i ].NextPtr = Start; Start = Start->Next.NextPtr; Iter = Iter->Next.NextPtr; } } } return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::SetDimensions( const DirInitType &Directions, const std::vector< size_t > &DimensionCounts ) ExceptDebug { AssertDebug( Directions[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, 0 } ) ); DimensionSizes = DimensionCounts; DirectionalHead->DirectionArray = Directions; std::sort( DirectionalHead->DirectionArray.begin(), DirectionalHead->DirectionArray.end() ); ValidateIterators(); return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::SetDimensions( DirInitType &&Directions, std::vector< size_t > &&DimensionCounts ) ExceptDebug { AssertDebug( Directions[ 0 ].Dir.Angles.size() != DimensionCounts.size(), ( DirectionSizeError{ Directions[ 0 ].Dir.Angles.size(), DimensionCounts.size() } ) ); AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, 0 } ) ); DimensionSizes = std::move( DimensionCounts ); DirectionalHead->DirectionArray = std::move( Directions ); std::sort( DirectionalHead->DirectionArray.begin(), DirectionalHead->DirectionArray.end() ); ValidateIterators(); return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::Resize( size_t Count, const ListType &Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, Size } ) ); if( Count ) { DirectionsMemory = std::make_pair( Count, Directions{ Data, DirectionalHead->DirectionArray } ); Directions* *Iter = &DirectionalHead; for( size_t i = 0; i < Count; ++i ) { ( *Iter ) = DirectionsMemory.GetBlock( i ); Iter = &( ( *Iter )->Next.NextPtr ); } } else { DirectionsMemory.Reset(); DirectionalHead = nullptr; } Size = Count; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::Resize( size_t Count, ListType &&Data ) ExceptDebug { AssertDebug( !DirectionalHead, ( MovedTooFar{ 0, Size } ) ); if( Count ) { DirectionsMemory = std::make_pair( Count, Directions{ std::move( Data ), DirectionalHead->DirectionArray } ); Directions* *Iter = &DirectionalHead; for( size_t i = 0; i < Count; ++i ) { ( *Iter ) = DirectionsMemory.GetBlock( i ); Iter = &( ( *Iter )->Next.NextPtr ); } } else { DirectionsMemory.Reset(); DirectionalHead = nullptr; } Size = Count; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::Resize( size_t Count, const ListType &Data, const DirInitType &Directions_ ) ExceptDebug { if( Count ) { DirectionsMemory = std::make_pair( Count, Directions{ Data, Directions_ } ); Directions* *Iter = &DirectionalHead; for( size_t i = 0; i < Count; ++i ) { ( *Iter ) = DirectionsMemory.GetBlock( i ); Iter = &( ( *Iter )->Next.NextPtr ); } } else { DirectionsMemory.Reset(); DirectionalHead = nullptr; } Size = Count; return *this; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount > & MultiDirectionalList< ListType, DirectionCount >::Resize( size_t Count, ListType &&Data, DirInitType &&Directions_ ) ExceptDebug { if( Count ) { DirectionsMemory = std::make_pair( Count, Directions{ std::move( Data ), std::move( Directions_ ) } ); Directions* *Iter = &DirectionalHead; for( size_t i = 0; i < Count; ++i ) { ( *Iter ) = DirectionsMemory.GetBlock( i ); Iter = &( ( *Iter )->Next.NextPtr ); } } else { DirectionsMemory.Reset(); DirectionalHead = nullptr; } Size = Count; return *this; } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >:: NotEnoughDirectionInitializers::NotEnoughDirectionInitializers( size_t Count ) noexcept { std::cerr << "You tried to initialize the list with " << Count << " directions, but it requires " << DirectionCount << std::endl; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::MovedTooFar::MovedTooFar( const Direction &Dir, size_t Count ) noexcept { std::cerr << "You tried to move at the angles: "; for( auto Iter : Dir.Angles ) { std::cerr << Iter << ", "; } std::cerr << Count << " times, but the list does not have a node there!" << std::endl; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::MovedTooFar::MovedTooFar( size_t Index, size_t Size ) noexcept { std::cerr << "You tried to move to index: " << Index << ", but the list only has " << Size << " nodes!" << std::endl; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::DirectionSizeError::DirectionSizeError( size_t DirSize, size_t ListSize ) noexcept { std::cerr << "The amount of dimensions in the direction struct is diffrent from the amount in the list: "; std::cerr << DirSize << " for the direction struct, vs: " << ListSize << " for the list!" << std::endl; } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Memory::Memory( size_t BlockSize, const ListType &Data, const DirInitType &Directions_ ) noexcept : BlockSize( BlockSize ), CurrentIndex( 1 ), MemoryBlocks{ new Directions[ BlockSize ]() } { *( MemoryBlocks[ 0 ] ) = Directions{ Data, Directions_ }; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Memory::Memory( size_t BlockSize, ListType &&Data, DirInitType &&Directions_ ) noexcept : BlockSize( BlockSize ), CurrentIndex( 1 ), MemoryBlocks{ new Directions[ BlockSize ]() } { *( MemoryBlocks[ 0 ] ) = Directions{ std::move( Data ), std::move( Directions_ ) }; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Memory::Memory( const std::vector< size_t > &BlockSizes, const ListType &Data, const DirInitType &Directions_ ) noexcept : BlockSize( 1 ), CurrentIndex( 1 ) { for( auto Iter : BlockSizes ) { BlockSize *= Iter; } MemoryBlocks.push_back( new Directions[ BlockSize ]() ); *( MemoryBlocks[ 0 ] ) = Directions{ Data, Directions_ }; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Memory::Memory( const std::vector< size_t > &BlockSizes, ListType &&Data, DirInitType &&Directions_ ) noexcept : BlockSize( 1 ), CurrentIndex( 1 ) { for( auto Iter : BlockSizes ) { BlockSize *= Iter; } MemoryBlocks.push_back( new Directions[ BlockSize ]() ); *( MemoryBlocks[ 0 ] ) = Directions{ std::move( Data ), std::move( Directions_ ) }; } template< typename ListType, size_t DirectionCount > MultiDirectionalList< ListType, DirectionCount >::Memory::~Memory() noexcept { EmptyBlocks.clear(); for( auto Iter : MemoryBlocks ) { delete [] Iter; } MemoryBlocks.clear(); } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions * MultiDirectionalList< ListType, DirectionCount >::Memory::operator=( std::pair< size_t, Directions > &&DataCount ) noexcept { BlockSize = DataCount.first; CurrentIndex = 1; EmptyBlocks.clear(); for( auto Iter : MemoryBlocks ) { delete[] Iter; } MemoryBlocks.clear(); MemoryBlocks.push_back( new Directions[ BlockSize ]() ); MemoryBlocks[ 0 ][ 0 ] = Directions{ std::move( DataCount.second ) }; return MemoryBlocks[ 0 ]; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions * MultiDirectionalList< ListType, DirectionCount >::Memory::operator=( std::pair< std::vector< size_t >, Directions > &&DataCount ) noexcept { BlockSize = 1; for( auto Iter : DataCount.first ) { BlockSize *= Iter; } CurrentIndex = 1; EmptyBlocks.clear(); for( auto Iter : MemoryBlocks ) { delete[] Iter; } MemoryBlocks.clear(); MemoryBlocks.push_back( new Directions[ BlockSize ]() ); MemoryBlocks[ 0 ][ 0 ] = Directions{ std::move( DataCount.second ) }; return MemoryBlocks[ 0 ]; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions * MultiDirectionalList< ListType, DirectionCount >::Memory::GetTop() noexcept { return MemoryBlocks[ 0 ]; } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions * MultiDirectionalList< ListType, DirectionCount >::Memory::GetBlock( size_t Index ) noexcept { return MemoryBlocks[ Index / BlockSize ] + ( Index % BlockSize ); } template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions * MultiDirectionalList< ListType, DirectionCount >::Memory::SetBlock( Directions &&Dir ) noexcept { if( EmptyBlocks.empty() ) { const size_t Index = CurrentIndex / BlockSize; const size_t MemSize = MemoryBlocks.size(); if( Index < MemSize ) { Directions *const Return = MemoryBlocks[ Index ] + ( CurrentIndex % BlockSize ); *Return = std::move( Dir ); ++CurrentIndex; return Return; } ++CurrentIndex; Directions *const Return = new Directions[ BlockSize ]() ; MemoryBlocks.push_back( Return ); Return[ 0 ] = std::move( Dir ); return Return; } const auto Iter = EmptyBlocks.cbegin(); Directions *const Return = GetBlock( *Iter ); EmptyBlocks.erase( Iter ); *Return = std::move( Dir ); return Return; } template< typename ListType, size_t DirectionCount > void MultiDirectionalList< ListType, DirectionCount >::Memory::Erase( size_t Index ) noexcept { if( Index == CurrentIndex ) { --CurrentIndex; return; } const auto End = EmptyBlocks.cend(); while( EmptyBlocks.find( Index ) != End ) { ++Index; } EmptyBlocks.emplace( Index ); } template <typename ListType, size_t DirectionCount> void MultiDirectionalList<ListType, DirectionCount>::Memory::Reset() noexcept { BlockSize = 0; CurrentIndex = 0; EmptyBlocks.clear(); for( auto Iter : MemoryBlocks ) { delete[] Iter; } MemoryBlocks.clear(); } /////////////////////////////////////////////////////////////////////////////// template< typename ListType, size_t DirectionCount > typename MultiDirectionalList< ListType, DirectionCount >::Directions * MultiDirectionalList< ListType, DirectionCount >::MoveTo( Directions *Start, size_t EndIndex ) const ExceptDebug { AssertDebug( EndIndex > Size, ( MovedTooFar{ EndIndex, Size } ) ); size_t DirIndex = DirectionCount - 1; Direction Dir = DirectionalHead->DirectionArray[ DirIndex ].Dir; const Direction Zero{ std::vector< float >( DimensionSizes.size() ) }; while( Zero < Dir ) { const size_t End = static_cast< size_t >( std::abs( Dir.Calc( DimensionSizes ) ) ); while( End <= EndIndex ) { Directions *Temp = Start->DirectionArray[ DirIndex ].NextPtr; if( !Temp ) { break; } Start = Temp; EndIndex -= End; } if( EndIndex ) { Dir = DirectionalHead->DirectionArray[ --DirIndex ].Dir; } else { return Start; } } for( size_t i = 0; i < EndIndex; ++i ) { Start = Start->Next.NextPtr; } return Start; } template< typename ListType, size_t DirectionCount > void MultiDirectionalList< ListType, DirectionCount >::InvalidateIterators() noexcept { Directions *Iter = DirectionalHead; for( size_t i = 0; i < Size; ++i ) { for( size_t j = 0; j < DirectionCount; ++j ) { Iter->DirectionArray[ j ].NextPtr = nullptr; } Iter = Iter->Next.NextPtr; } }
[ "gmc1322@users.noreply.github.com" ]
gmc1322@users.noreply.github.com