blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
1b950d20260ecdb1d7cdf745f0c2eb72dd3e8818
af0b2d96ba888f591b67dc69b3814af6a3573d42
/blue_shield/blue_shield.ino
d901c7d369d8f1aed091e08cef5e9f508c718faa
[]
no_license
Ketupat-Development-Studios/lumos-switch
e1474525b563156d31f509fdf2374250445e7cae
6af7ddfa040cf9ef5d8c02627f9191203b25635e
refs/heads/master
2021-06-28T15:39:05.434570
2020-08-15T12:11:26
2020-08-15T12:11:26
123,659,475
0
0
null
null
null
null
UTF-8
C++
false
false
4,191
ino
#include<SoftwareSerial.h> #include<Servo.h> SoftwareSerial BTserial(3, 2); Servo actuator; char c = ' '; char blueIn = ' '; boolean readingData = false; boolean open_state = true; //int upPin = 4; //int downPin = 2; int upVal, downVal; int upArm = 0; int downArm = 120; int restArm = 50; int state = 999; int moving = 0; int move_delay = 150; int indicator = 0; int indicator_delay = 100; int touch_switch = 0; int touch_switch_delay = 50; int pairing = 0; int pairing_delay = 50; //PINS declaration INPUT int blueRX = 3; //PINS declaration OUTPUT int blueTX = 2; int blueEN = 5; int servoCtl = 8; int touchSensor = 10; int ind2 = 11; int ind1 = 12; void setup() { Serial.begin(9600); Serial.println("Arduino is ready"); BTserial.begin(38400); pinMode(blueRX, INPUT); pinMode(blueTX, OUTPUT); pinMode(blueEN, OUTPUT); pinMode(touchSensor, OUTPUT); pinMode(ind2, OUTPUT); pinMode(ind1, OUTPUT); pinMode(9, INPUT_PULLUP); actuator.attach(servoCtl); //Base States digitalWrite(ind1, LOW); digitalWrite(ind2, HIGH); digitalWrite(touchSensor, HIGH); digitalWrite(blueTX, LOW); digitalWrite(blueEN, LOW); } void loop() { if (readingData && indicator <= 0) { indicator = 0; readingData = false; } else if (indicator > 0) { indicator--; } else { readingData = false; } //Keep reading from HC-05 and send to arduino serial monitor if (BTserial.available()) { c = BTserial.read(); blueIn = c; Serial.write(c); readingData = true; indicator = indicator_delay; } //Keep reading from arduino serial monitor and send to HC-05 if (Serial.available()) { c = Serial.read(); BTserial.write(c); } upVal = HIGH; downVal = HIGH; int tmp = digitalRead(9); // Serial.write("GATE: "); // Serial.write(tmp==LOW?"LOW":"HIGH"); // Serial.write("\n"); if (touch_switch <= 0) { if (tmp==LOW) { if (open_state == true) { BTserial.write("C\n"); BTserial.flush(); Serial.write("Circuit Closed\n"); touch_switch = touch_switch_delay; } open_state = false; } else { if (open_state == false) { BTserial.write("O\n"); BTserial.flush(); Serial.write("Circuit Open\n"); touch_switch = touch_switch_delay; } open_state = true; } } else { touch_switch--; if (touch_switch%25 == 0) { Serial.write("--> Cooldown: "); Serial.print(touch_switch); Serial.write("\n"); } } if (pairing > 0) pairing--; if (readingData) digitalWrite(ind1, HIGH); else digitalWrite(ind1, LOW); //Hook on bluetooth control --> U (up) D (down) if (blueIn == 'U') upVal = LOW; else if (blueIn == 'D') downVal = LOW; else if (blueIn == 'T') { if (pairing <= 0) { digitalWrite(ind1, LOW); digitalWrite(ind2, LOW); delay(120); for (int i=0;i<5;i++) { digitalWrite(ind2, HIGH); delay(120); digitalWrite(ind2, LOW); delay(120); } for (int i=0;i<3;i++) { digitalWrite(ind1, HIGH); delay(250); digitalWrite(ind1, LOW); delay(250); } delay(1000); pairing = pairing_delay; } } // Serial.write("UP: "); // Serial.write(upVal==LOW?"LOW":"HIGH"); // Serial.write(" | DOWN: "); // Serial.write(downVal==LOW?"LOW":"HIGH"); // Serial.write("\n"); if (moving > 0) { moving--; digitalWrite(ind2, LOW); } else { if (upVal == HIGH && downVal == HIGH) { //Resting if (state != 0) { actuator.write(restArm); state = 0; moving = move_delay; } else digitalWrite(ind2, HIGH); } else { if (downVal == LOW) { if (state != -1) { actuator.write(downArm); Serial.write("DOWN\n"); state = -1; moving = move_delay; } else digitalWrite(ind2, HIGH); } else if (upVal == LOW) { if (state != 1) { actuator.write(upArm); Serial.write("UP\n"); state = 1; moving = move_delay; } else digitalWrite(ind2, HIGH); } } } delay(5); }
[ "devyaoyh@gmail.com" ]
devyaoyh@gmail.com
28379d3c2bfb8ad80babf8ad0c30f944a5ab42ac
460455e7990de7257aa223a58e73069f3ef7ff43
/src/server/scripts/Kalimdor/CavernsOfTime/DarkPortal/instance_dark_portal.cpp
6a131594483f1bef460cc1a3df9e373f8063d751
[]
no_license
Shkipper/wmane
2ce69adea1eedf866921c857cbc5bd1bc6d037f0
2da37e1e758f17b61efb6aae8fa7343b234f3dcd
refs/heads/master
2020-04-24T19:51:51.897587
2019-02-25T06:14:18
2019-02-25T06:14:18
172,225,859
0
0
null
2019-02-23T14:49:31
2019-02-23T14:49:31
null
UTF-8
C++
false
false
11,104
cpp
/* * Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Instance_Dark_Portal SD%Complete: 50 SDComment: Quest support: 9836, 10297. Currently in progress. SDCategory: Caverns of Time, The Dark Portal EndScriptData */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "dark_portal.h" #define MAX_ENCOUNTER 2 #define C_MEDIVH 15608 #define C_TIME_RIFT 17838 #define SPELL_RIFT_CHANNEL 31387 #define RIFT_BOSS 1 inline uint32 RandRiftBoss() { return ((rand()%2) ? C_RKEEP : C_RLORD); } float PortalLocation[4][4]= { {-2041.06f, 7042.08f, 29.99f, 1.30f}, {-1968.18f, 7042.11f, 21.93f, 2.12f}, {-1885.82f, 7107.36f, 22.32f, 3.07f}, {-1928.11f, 7175.95f, 22.11f, 3.44f} }; struct Wave { uint32 PortalBoss; //protector of current portal uint32 NextPortalTime; //time to next portal, or 0 if portal boss need to be killed }; static Wave RiftWaves[]= { {RIFT_BOSS, 0}, {C_DEJA, 120000}, {RIFT_BOSS, 0}, {C_TEMPO, 140000}, {RIFT_BOSS, 0}, {C_AEONUS, 0} }; class instance_dark_portal : public InstanceMapScript { public: instance_dark_portal() : InstanceMapScript("instance_dark_portal", 269) { } InstanceScript* GetInstanceScript(InstanceMap* map) const { return new instance_dark_portal_InstanceMapScript(map); } struct instance_dark_portal_InstanceMapScript : public InstanceScript { instance_dark_portal_InstanceMapScript(Map* map) : InstanceScript(map) { } uint32 m_auiEncounter[MAX_ENCOUNTER]; uint32 mRiftPortalCount; uint32 mShieldPercent; uint8 mRiftWaveCount; uint8 mRiftWaveId; uint32 NextPortal_Timer; uint64 MedivhGUID; uint8 CurrentRiftId; void Initialize() { MedivhGUID = 0; Clear(); } void Clear() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); mRiftPortalCount = 0; mShieldPercent = 100; mRiftWaveCount = 0; mRiftWaveId = 0; CurrentRiftId = 0; NextPortal_Timer = 0; } void InitWorldState(bool Enable = true) { DoUpdateWorldState(WORLD_STATE_BM, Enable ? 1 : 0); DoUpdateWorldState(WORLD_STATE_BM_SHIELD, 100); DoUpdateWorldState(WORLD_STATE_BM_RIFT, 0); } bool IsEncounterInProgress() const { if (const_cast<instance_dark_portal_InstanceMapScript*>(this)->GetData(TYPE_MEDIVH) == IN_PROGRESS) return true; return false; } void OnPlayerEnter(Player* player) { if (GetData(TYPE_MEDIVH) == IN_PROGRESS) return; player->SendUpdateWorldState(WORLD_STATE_BM, 0); } void OnCreatureCreate(Creature* creature) { if (creature->GetEntry() == C_MEDIVH) MedivhGUID = creature->GetGUID(); } //what other conditions to check? bool CanProgressEvent() { if (instance->GetPlayers().isEmpty()) return false; return true; } uint8 GetRiftWaveId() { switch (mRiftPortalCount) { case 6: mRiftWaveId = 2; return 1; case 12: mRiftWaveId = 4; return 3; case 18: return 5; default: return mRiftWaveId; } } void SetData(uint32 type, uint32 data) { switch (type) { case TYPE_MEDIVH: if (data == SPECIAL && m_auiEncounter[0] == IN_PROGRESS) { --mShieldPercent; DoUpdateWorldState(WORLD_STATE_BM_SHIELD, mShieldPercent); if (!mShieldPercent) { if (Creature* pMedivh = instance->GetCreature(MedivhGUID)) { if (pMedivh->IsAlive()) { pMedivh->DealDamage(pMedivh, pMedivh->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); m_auiEncounter[0] = FAIL; m_auiEncounter[1] = NOT_STARTED; } } } } else { if (data == IN_PROGRESS) { TC_LOG_DEBUG("scripts", "Instance Dark Portal: Starting event."); InitWorldState(); m_auiEncounter[1] = IN_PROGRESS; NextPortal_Timer = 15000; } if (data == DONE) { //this may be completed further out in the post-event TC_LOG_DEBUG("scripts", "Instance Dark Portal: Event completed."); Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) { for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if (Player* player = itr->GetSource()) { if (player->GetQuestStatus(QUEST_OPENING_PORTAL) == QUEST_STATUS_INCOMPLETE) player->AreaExploredOrEventHappens(QUEST_OPENING_PORTAL); if (player->GetQuestStatus(QUEST_MASTER_TOUCH) == QUEST_STATUS_INCOMPLETE) player->AreaExploredOrEventHappens(QUEST_MASTER_TOUCH); } } } } m_auiEncounter[0] = data; } break; case TYPE_RIFT: if (data == SPECIAL) { if (mRiftPortalCount != 6 && mRiftPortalCount != 12 && mRiftPortalCount != 18) NextPortal_Timer = 5000; } else m_auiEncounter[1] = data; break; } } uint32 GetData(uint32 type) { switch (type) { case TYPE_MEDIVH: return m_auiEncounter[0]; case TYPE_RIFT: return m_auiEncounter[1]; case DATA_PORTAL_COUNT: return mRiftPortalCount; case DATA_SHIELD: return mShieldPercent; } return 0; } uint64 GetData64(uint32 data) { if (data == DATA_MEDIVH) return MedivhGUID; return 0; } Creature* SummonedPortalBoss(Creature* me) { uint32 entry = RiftWaves[GetRiftWaveId()].PortalBoss; if (entry == RIFT_BOSS) entry = RandRiftBoss(); TC_LOG_DEBUG("scripts", "Instance Dark Portal: Summoning rift boss entry %u.", entry); Position pos; me->GetRandomNearPosition(pos, 10.0f); //normalize Z-level if we can, if rift is not at ground level. pos.m_positionZ = std::max(me->GetMap()->GetHeight(pos.m_positionX, pos.m_positionY, MAX_HEIGHT), me->GetMap()->GetWaterLevel(pos.m_positionX, pos.m_positionY)); if (Creature* summon = me->SummonCreature(entry, pos, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000)) return summon; TC_LOG_DEBUG("scripts", "Instance Dark Portal: What just happened there? No boss, no loot, no fun..."); return NULL; } void DoSpawnPortal() { if (Creature* pMedivh = instance->GetCreature(MedivhGUID)) { uint8 tmp = urand(0, 2); if (tmp >= CurrentRiftId) ++tmp; TC_LOG_DEBUG("scripts", "Instance Dark Portal: Creating Time Rift at locationId %i (old locationId was %u).", tmp, CurrentRiftId); CurrentRiftId = tmp; Creature* temp = pMedivh->SummonCreature(C_TIME_RIFT, PortalLocation[tmp][0], PortalLocation[tmp][1], PortalLocation[tmp][2], PortalLocation[tmp][3], TEMPSUMMON_CORPSE_DESPAWN, 0); if (temp) { temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); temp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Creature* pBoss = SummonedPortalBoss(temp)) { if (pBoss->GetEntry() == C_AEONUS) pBoss->AddThreat(pMedivh, 0.0f); else { pBoss->AddThreat(temp, 0.0f); temp->CastSpell(pBoss, SPELL_RIFT_CHANNEL, false); } } } } } void Update(uint32 diff) { if (m_auiEncounter[1] != IN_PROGRESS) return; //add delay timer? if (!CanProgressEvent()) { Clear(); return; } if (NextPortal_Timer) { if (NextPortal_Timer <= diff) { ++mRiftPortalCount; DoUpdateWorldState(WORLD_STATE_BM_RIFT, mRiftPortalCount); DoSpawnPortal(); NextPortal_Timer = RiftWaves[GetRiftWaveId()].NextPortalTime; } else NextPortal_Timer -= diff; } } }; }; void AddSC_instance_dark_portal() { new instance_dark_portal(); }
[ "felianther15@gmail.com" ]
felianther15@gmail.com
e3a3fefd05f18e0fa221f3dc444500e79b07d275
4c81d5546aa29fb33d8b8d9a7470a4fd69284cc0
/protocolBuffer/protocolBuffer_org/protobuf-2.6.1/out/BuyClubList_Request.pb.cc
3c132648b81d88cefbcc15d2f2ab0a13055edea4
[ "LicenseRef-scancode-protobuf" ]
permissive
zzfeed/tools
6836c81579a4d02055b12735aa6bde185ecab930
f43215105e71802afa95b78423011ebaf6c532e8
refs/heads/master
2021-09-21T09:56:15.773978
2018-08-24T06:09:40
2018-08-24T06:09:40
null
0
0
null
null
null
null
UTF-8
C++
false
true
16,365
cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BuyClubList_Request.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "BuyClubList_Request.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> // @@protoc_insertion_point(includes) namespace quote { void protobuf_ShutdownFile_BuyClubList_5fRequest_2eproto() { delete BuyClubList_Request::default_instance_; } #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER void protobuf_AddDesc_BuyClubList_5fRequest_2eproto_impl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #else void protobuf_AddDesc_BuyClubList_5fRequest_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; #endif BuyClubList_Request::default_instance_ = new BuyClubList_Request(); BuyClubList_Request::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_BuyClubList_5fRequest_2eproto); } #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_BuyClubList_5fRequest_2eproto_once_); void protobuf_AddDesc_BuyClubList_5fRequest_2eproto() { ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_BuyClubList_5fRequest_2eproto_once_, &protobuf_AddDesc_BuyClubList_5fRequest_2eproto_impl); } #else // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_BuyClubList_5fRequest_2eproto { StaticDescriptorInitializer_BuyClubList_5fRequest_2eproto() { protobuf_AddDesc_BuyClubList_5fRequest_2eproto(); } } static_descriptor_initializer_BuyClubList_5fRequest_2eproto_; #endif // =================================================================== #ifndef _MSC_VER const int BuyClubList_Request::kClassTypeFieldNumber; const int BuyClubList_Request::kReqFieldsFieldNumber; const int BuyClubList_Request::kSortFieldFieldNumber; const int BuyClubList_Request::kSortOrderFieldNumber; const int BuyClubList_Request::kReqBeginFieldNumber; const int BuyClubList_Request::kReqSizeFieldNumber; const int BuyClubList_Request::kReqFlagFieldNumber; const int BuyClubList_Request::kUserIdFieldNumber; #endif // !_MSC_VER BuyClubList_Request::BuyClubList_Request() : ::google::protobuf::MessageLite() { SharedCtor(); // @@protoc_insertion_point(constructor:quote.BuyClubList_Request) } void BuyClubList_Request::InitAsDefaultInstance() { } BuyClubList_Request::BuyClubList_Request(const BuyClubList_Request& from) : ::google::protobuf::MessageLite() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:quote.BuyClubList_Request) } void BuyClubList_Request::SharedCtor() { _cached_size_ = 0; class_type_ = 0; sort_field_ = 0; sort_order_ = false; req_begin_ = 0u; req_size_ = 0u; req_flag_ = 0u; user_id_ = GOOGLE_ULONGLONG(0); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } BuyClubList_Request::~BuyClubList_Request() { // @@protoc_insertion_point(destructor:quote.BuyClubList_Request) SharedDtor(); } void BuyClubList_Request::SharedDtor() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER if (this != &default_instance()) { #else if (this != default_instance_) { #endif } } void BuyClubList_Request::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const BuyClubList_Request& BuyClubList_Request::default_instance() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER protobuf_AddDesc_BuyClubList_5fRequest_2eproto(); #else if (default_instance_ == NULL) protobuf_AddDesc_BuyClubList_5fRequest_2eproto(); #endif return *default_instance_; } BuyClubList_Request* BuyClubList_Request::default_instance_ = NULL; BuyClubList_Request* BuyClubList_Request::New() const { return new BuyClubList_Request; } void BuyClubList_Request::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<BuyClubList_Request*>(16)->f) - \ reinterpret_cast<char*>(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) if (_has_bits_[0 / 32] & 253) { ZR_(class_type_, user_id_); } #undef OFFSET_OF_FIELD_ #undef ZR_ req_fields_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->clear(); } bool BuyClubList_Request::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; ::google::protobuf::io::StringOutputStream unknown_fields_string( mutable_unknown_fields()); ::google::protobuf::io::CodedOutputStream unknown_fields_stream( &unknown_fields_string); // @@protoc_insertion_point(parse_start:quote.BuyClubList_Request) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 class_type = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &class_type_))); set_has_class_type(); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_req_fields; break; } // repeated int32 req_fields = 2 [packed = true]; case 2: { if (tag == 18) { parse_req_fields: DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_req_fields()))); } else if (tag == 16) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 1, 18, input, this->mutable_req_fields()))); } else { goto handle_unusual; } if (input->ExpectTag(24)) goto parse_sort_field; break; } // required int32 sort_field = 3; case 3: { if (tag == 24) { parse_sort_field: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &sort_field_))); set_has_sort_field(); } else { goto handle_unusual; } if (input->ExpectTag(32)) goto parse_sort_order; break; } // required bool sort_order = 4; case 4: { if (tag == 32) { parse_sort_order: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &sort_order_))); set_has_sort_order(); } else { goto handle_unusual; } if (input->ExpectTag(40)) goto parse_req_begin; break; } // required uint32 req_begin = 5; case 5: { if (tag == 40) { parse_req_begin: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &req_begin_))); set_has_req_begin(); } else { goto handle_unusual; } if (input->ExpectTag(48)) goto parse_req_size; break; } // required uint32 req_size = 6; case 6: { if (tag == 48) { parse_req_size: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &req_size_))); set_has_req_size(); } else { goto handle_unusual; } if (input->ExpectTag(56)) goto parse_req_flag; break; } // optional uint32 req_flag = 7; case 7: { if (tag == 56) { parse_req_flag: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &req_flag_))); set_has_req_flag(); } else { goto handle_unusual; } if (input->ExpectTag(64)) goto parse_user_id; break; } // optional uint64 user_id = 8 [default = 0]; case 8: { if (tag == 64) { parse_user_id: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( input, &user_id_))); set_has_user_id(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField( input, tag, &unknown_fields_stream)); break; } } } success: // @@protoc_insertion_point(parse_success:quote.BuyClubList_Request) return true; failure: // @@protoc_insertion_point(parse_failure:quote.BuyClubList_Request) return false; #undef DO_ } void BuyClubList_Request::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:quote.BuyClubList_Request) // required int32 class_type = 1; if (has_class_type()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->class_type(), output); } // repeated int32 req_fields = 2 [packed = true]; if (this->req_fields_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_req_fields_cached_byte_size_); } for (int i = 0; i < this->req_fields_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( this->req_fields(i), output); } // required int32 sort_field = 3; if (has_sort_field()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->sort_field(), output); } // required bool sort_order = 4; if (has_sort_order()) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->sort_order(), output); } // required uint32 req_begin = 5; if (has_req_begin()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->req_begin(), output); } // required uint32 req_size = 6; if (has_req_size()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->req_size(), output); } // optional uint32 req_flag = 7; if (has_req_flag()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(7, this->req_flag(), output); } // optional uint64 user_id = 8 [default = 0]; if (has_user_id()) { ::google::protobuf::internal::WireFormatLite::WriteUInt64(8, this->user_id(), output); } output->WriteRaw(unknown_fields().data(), unknown_fields().size()); // @@protoc_insertion_point(serialize_end:quote.BuyClubList_Request) } int BuyClubList_Request::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required int32 class_type = 1; if (has_class_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->class_type()); } // required int32 sort_field = 3; if (has_sort_field()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->sort_field()); } // required bool sort_order = 4; if (has_sort_order()) { total_size += 1 + 1; } // required uint32 req_begin = 5; if (has_req_begin()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->req_begin()); } // required uint32 req_size = 6; if (has_req_size()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->req_size()); } // optional uint32 req_flag = 7; if (has_req_flag()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->req_flag()); } // optional uint64 user_id = 8 [default = 0]; if (has_user_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt64Size( this->user_id()); } } // repeated int32 req_fields = 2 [packed = true]; { int data_size = 0; for (int i = 0; i < this->req_fields_size(); i++) { data_size += ::google::protobuf::internal::WireFormatLite:: Int32Size(this->req_fields(i)); } if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _req_fields_cached_byte_size_ = data_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } total_size += unknown_fields().size(); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void BuyClubList_Request::CheckTypeAndMergeFrom( const ::google::protobuf::MessageLite& from) { MergeFrom(*::google::protobuf::down_cast<const BuyClubList_Request*>(&from)); } void BuyClubList_Request::MergeFrom(const BuyClubList_Request& from) { GOOGLE_CHECK_NE(&from, this); req_fields_.MergeFrom(from.req_fields_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_class_type()) { set_class_type(from.class_type()); } if (from.has_sort_field()) { set_sort_field(from.sort_field()); } if (from.has_sort_order()) { set_sort_order(from.sort_order()); } if (from.has_req_begin()) { set_req_begin(from.req_begin()); } if (from.has_req_size()) { set_req_size(from.req_size()); } if (from.has_req_flag()) { set_req_flag(from.req_flag()); } if (from.has_user_id()) { set_user_id(from.user_id()); } } mutable_unknown_fields()->append(from.unknown_fields()); } void BuyClubList_Request::CopyFrom(const BuyClubList_Request& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool BuyClubList_Request::IsInitialized() const { if ((_has_bits_[0] & 0x0000003d) != 0x0000003d) return false; return true; } void BuyClubList_Request::Swap(BuyClubList_Request* other) { if (other != this) { std::swap(class_type_, other->class_type_); req_fields_.Swap(&other->req_fields_); std::swap(sort_field_, other->sort_field_); std::swap(sort_order_, other->sort_order_); std::swap(req_begin_, other->req_begin_); std::swap(req_size_, other->req_size_); std::swap(req_flag_, other->req_flag_); std::swap(user_id_, other->user_id_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.swap(other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::std::string BuyClubList_Request::GetTypeName() const { return "quote.BuyClubList_Request"; } // @@protoc_insertion_point(namespace_scope) } // namespace quote // @@protoc_insertion_point(global_scope)
[ "xie123888" ]
xie123888
a819f06d17146b82f70650b918cd1ad1cc722da9
4a5f47f4da5356b87c789d15dd83188929791cbc
/src/rpc/rawtransaction.cpp
a422b1c57a65e4a5e7259190b576c8d8bc0e5d4e
[ "MIT" ]
permissive
TMRO2020/UkkeyCoin
e7a5cad8c530311364c47b9aaa0a1f3f0e9db005
77aa24be0831b5350d6892d32ff679d9459046a6
refs/heads/master
2022-01-12T03:39:55.812200
2019-03-19T21:41:00
2019-03-19T21:41:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
46,178
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "chain.h" #include "coins.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "keystore.h" #include "validation.h" #include "merkleblock.h" #include "net.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" #include "script/standard.h" #include "txmempool.h" #include "uint256.h" #include "utilstrencodings.h" #include "instantx.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include "evo/specialtx.h" #include "evo/providertx.h" #include "evo/cbtx.h" #include "llmq/quorums_commitment.h" #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey))); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); UniValue a(UniValue::VARR); BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) { uint256 txid = tx.GetHash(); entry.push_back(Pair("txid", txid.GetHex())); entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION))); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("type", tx.nType)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); UniValue vin(UniValue::VARR); BOOST_FOREACH(const CTxIn& txin, tx.vin) { UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); UniValue o(UniValue::VOBJ); o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true))); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); // Add address and value info if spentindex enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n); if (GetSpentIndex(spentKey, spentInfo)) { in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis))); in.push_back(Pair("valueSat", spentInfo.satoshis)); if (spentInfo.addressType == 1) { in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString())); } else if (spentInfo.addressType == 2) { in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString())); } } } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("valueSat", txout.nValue)); out.push_back(Pair("n", (int64_t)i)); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(txout.scriptPubKey, o, true); out.push_back(Pair("scriptPubKey", o)); // Add spent information if spentindex is enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txid, i); if (GetSpentIndex(spentKey, spentInfo)) { out.push_back(Pair("spentTxId", spentInfo.txid.GetHex())); out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex)); out.push_back(Pair("spentHeight", spentInfo.blockHeight)); } vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (!tx.vExtraPayload.empty()) { entry.push_back(Pair("extraPayloadSize", (int)tx.vExtraPayload.size())); entry.push_back(Pair("extraPayload", HexStr(tx.vExtraPayload))); } if (tx.nType == TRANSACTION_PROVIDER_REGISTER) { CProRegTx proTx; if (GetTxPayload(tx, proTx)) { UniValue obj; proTx.ToJson(obj); entry.push_back(Pair("proRegTx", obj)); } } else if (tx.nType == TRANSACTION_PROVIDER_UPDATE_SERVICE) { CProUpServTx proTx; if (GetTxPayload(tx, proTx)) { UniValue obj; proTx.ToJson(obj); entry.push_back(Pair("proUpServTx", obj)); } } else if (tx.nType == TRANSACTION_PROVIDER_UPDATE_REGISTRAR) { CProUpRegTx proTx; if (GetTxPayload(tx, proTx)) { UniValue obj; proTx.ToJson(obj); entry.push_back(Pair("proUpRegTx", obj)); } } else if (tx.nType == TRANSACTION_PROVIDER_UPDATE_REVOKE) { CProUpRevTx proTx; if (GetTxPayload(tx, proTx)) { UniValue obj; proTx.ToJson(obj); entry.push_back(Pair("proUpRevTx", obj)); } } else if (tx.nType == TRANSACTION_COINBASE) { CCbTx cbTx; if (GetTxPayload(tx, cbTx)) { UniValue obj; cbTx.ToJson(obj); entry.push_back(Pair("cbTx", obj)); } } else if (tx.nType == TRANSACTION_QUORUM_COMMITMENT) { llmq::CFinalCommitmentTxPayload qcTx; if (GetTxPayload(tx, qcTx)) { UniValue obj; qcTx.ToJson(obj); entry.push_back(Pair("qcTx", obj)); } } if (!hashBlock.IsNull()) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { entry.push_back(Pair("height", pindex->nHeight)); entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight)); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } else { entry.push_back(Pair("height", -1)); entry.push_back(Pair("confirmations", 0)); } } } bool fLocked = instantsend.IsLockedInstantSendTransaction(txid); entry.push_back(Pair("instantlock", fLocked)); } UniValue getrawtransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "getrawtransaction \"txid\" ( verbose )\n" "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n" "enabled, it also works for blockchain transactions.\n" "DEPRECATED: for now, it also works for transactions with unspent outputs.\n" "\nReturn the raw transaction data.\n" "\nIf verbose is 'true', returns an Object with information about 'txid'.\n" "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n" "\nResult (if verbose is not set or set to false):\n" "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" "\nResult (if verbose is set to true):\n" "{\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"address\" (string) ukkey address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n" " \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"instantlock\" : true|false, (bool) Current transaction lock state\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" true") + HelpExampleRpc("getrawtransaction", "\"mytxid\", true") ); LOCK(cs_main); uint256 hash = ParseHashV(request.params[0], "parameter 1"); // Accept either a bool (true) or a num (>=1) to indicate verbose output. bool fVerbose = false; if (request.params.size() > 1) { if (request.params[1].isNum()) { if (request.params[1].get_int() != 0) { fVerbose = true; } } else if(request.params[1].isBool()) { if(request.params[1].isTrue()) { fVerbose = true; } } else { throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be a boolean."); } } CTransactionRef tx; uint256 hashBlock; if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? "No such mempool or blockchain transaction" : "No such mempool transaction. Use -txindex to enable blockchain transaction queries") + ". Use gettransaction for wallet transactions."); std::string strHex = EncodeHexTx(*tx); if (!fVerbose) return strHex; UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", strHex)); TxToJSON(*tx, hashBlock, result); return result; } UniValue gettxoutproof(const JSONRPCRequest& request) { if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2)) throw std::runtime_error( "gettxoutproof [\"txid\",...] ( blockhash )\n" "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n" "\nNOTE: By default this function only works sometimes. This is when there is an\n" "unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option or\n" "specify the block in which the transaction is included manually (by blockhash).\n" "\nArguments:\n" "1. \"txids\" (string) A json array of txids to filter\n" " [\n" " \"txid\" (string) A transaction hash\n" " ,...\n" " ]\n" "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n" "\nResult:\n" "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n" "\nExamples:\n" + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'") + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"") + HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"") ); std::set<uint256> setTxids; uint256 oneTxid; UniValue txids = request.params[0].get_array(); for (unsigned int idx = 0; idx < txids.size(); idx++) { const UniValue& txid = txids[idx]; if (txid.get_str().length() != 64 || !IsHex(txid.get_str())) throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str()); uint256 hash(uint256S(txid.get_str())); if (setTxids.count(hash)) throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str()); setTxids.insert(hash); oneTxid = hash; } LOCK(cs_main); CBlockIndex* pblockindex = NULL; uint256 hashBlock; if (request.params.size() > 1) { hashBlock = uint256S(request.params[1].get_str()); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hashBlock]; } else { const Coin& coin = AccessByTxid(*pcoinsTip, oneTxid); if (!coin.IsSpent() && coin.nHeight > 0 && coin.nHeight <= chainActive.Height()) { pblockindex = chainActive[coin.nHeight]; } } if (pblockindex == NULL) { CTransactionRef tx; if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); pblockindex = mapBlockIndex[hashBlock]; } CBlock block; if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); unsigned int ntxFound = 0; for (const auto& tx : block.vtx) if (setTxids.count(tx->GetHash())) ntxFound++; if (ntxFound != setTxids.size()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block"); CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock mb(block, setTxids); ssMB << mb; std::string strHex = HexStr(ssMB.begin(), ssMB.end()); return strHex; } UniValue verifytxoutproof(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "verifytxoutproof \"proof\"\n" "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n" "and throwing an RPC error if the block is not in our best chain\n" "\nArguments:\n" "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n" "\nResult:\n" "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n" "\nExamples:\n" + HelpExampleCli("verifytxoutproof", "\"proof\"") + HelpExampleRpc("gettxoutproof", "\"proof\"") ); CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock merkleBlock; ssMB >> merkleBlock; UniValue res(UniValue::VARR); std::vector<uint256> vMatch; std::vector<unsigned int> vIndex; if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) return res; LOCK(cs_main); if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()])) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); BOOST_FOREACH(const uint256& hash, vMatch) res.push_back(hash.GetHex()); return res; } UniValue createrawtransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw std::runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n" "\nCreate a transaction spending the given inputs and creating new outputs.\n" "Outputs can be addresses or data.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n" "\nArguments:\n" "1. \"inputs\" (array, required) A json array of json objects\n" " [\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n, (numeric, required) The output number\n" " \"sequence\":n (numeric, optional) The sequence number\n" " } \n" " ,...\n" " ]\n" "2. \"outputs\" (object, required) a json object with outputs\n" " {\n" " \"address\": x.xxx, (numeric or string, required) The key is the ukkey address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n" " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n" " ,...\n" " }\n" "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" "\nExamples:\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true); if (request.params[0].isNull() || request.params[1].isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null"); UniValue inputs = request.params[0].get_array(); UniValue sendTo = request.params[1].get_obj(); CMutableTransaction rawTx; if (request.params.size() > 2 && !request.params[2].isNull()) { int64_t nLockTime = request.params[2].get_int64(); if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); rawTx.nLockTime = nLockTime; } for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; const UniValue& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const UniValue& vout_v = find_value(o, "vout"); if (!vout_v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max()); // set the sequence number if passed in the parameters object const UniValue& sequenceObj = find_value(o, "sequence"); if (sequenceObj.isNum()) { int64_t seqNr64 = sequenceObj.get_int64(); if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range"); else nSequence = (uint32_t)seqNr64; } CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence); rawTx.vin.push_back(in); } std::set<CBitcoinAddress> setAddress; std::vector<std::string> addrList = sendTo.getKeys(); BOOST_FOREACH(const std::string& name_, addrList) { if (name_ == "data") { std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data"); CTxOut out(0, CScript() << OP_RETURN << data); rawTx.vout.push_back(out); } else { CBitcoinAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Ukkey address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } } return EncodeHexTx(rawTx); } UniValue decoderawtransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "decoderawtransaction \"hexstring\"\n" "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The transaction hex string\n" "\nResult:\n" "{\n" " \"txid\" : \"id\", (string) The transaction id\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" " \"type\" : n, (numeric) The type\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) The output number\n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwG\" (string) Ukkey address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n" " \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n" "}\n" "\nExamples:\n" + HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\"") ); LOCK(cs_main); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)); CMutableTransaction mtx; if (!DecodeHexTx(mtx, request.params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); UniValue result(UniValue::VOBJ); TxToJSON(CTransaction(std::move(mtx)), uint256(), result); return result; } UniValue decodescript(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "decodescript \"hexstring\"\n" "\nDecode a hex-encoded script.\n" "\nArguments:\n" "1. \"hexstring\" (string) the hex encoded script\n" "\nResult:\n" "{\n" " \"asm\":\"asm\", (string) Script public key\n" " \"hex\":\"hex\", (string) hex encoded public key\n" " \"type\":\"type\", (string) The output type\n" " \"reqSigs\": n, (numeric) The required signatures\n" " \"addresses\": [ (json array of string)\n" " \"address\" (string) ukkey address\n" " ,...\n" " ],\n" " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n" "}\n" "\nExamples:\n" + HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\"") ); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)); UniValue r(UniValue::VOBJ); CScript script; if (request.params[0].get_str().size() > 0){ std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); UniValue type; type = find_value(r, "type"); if (type.isStr() && type.get_str() != "scripthash") { // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH, // don't return the address for a P2SH of the P2SH. r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString())); } return r; } /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", txin.prevout.hash.ToString())); entry.push_back(Pair("vout", (uint64_t)txin.prevout.n)); entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); entry.push_back(Pair("sequence", (uint64_t)txin.nSequence)); entry.push_back(Pair("error", strMessage)); vErrorsRet.push_back(entry); } UniValue signrawtransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) throw std::runtime_error( "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n" "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n" "The third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" #ifdef ENABLE_WALLET + HelpRequiringPassphrase() + "\n" #endif "\nArguments:\n" "1. \"hexstring\" (string, required) The transaction hex string\n" "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n" " [ (json array of json objects, or 'null' if none provided)\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n, (numeric, required) The output number\n" " \"scriptPubKey\": \"hex\", (string, required) script key\n" " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n" " }\n" " ,...\n" " ]\n" "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n" " [ (json array of strings, or 'null' if none provided)\n" " \"privatekey\" (string) private key in base58-encoding\n" " ,...\n" " ]\n" "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\"\n" "\nResult:\n" "{\n" " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n" " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n" " {\n" " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n" " \"vout\" : n, (numeric) The index of the output to spent and used as input\n" " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n" " \"sequence\" : n, (numeric) Script sequence number\n" " \"error\" : \"text\" (string) Verification or signing error related to the input\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\"") ); #ifdef ENABLE_WALLET LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL); #else LOCK(cs_main); #endif RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true); std::vector<unsigned char> txData(ParseHexV(request.params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); std::vector<CMutableTransaction> txVariants; while (!ssData.empty()) { try { CMutableTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (const std::exception&) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CMutableTransaction mergedTx(txVariants[0]); // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache &viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) { view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail. } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (request.params.size() > 2 && !request.params[2].isNull()) { fGivenKeys = true; UniValue keys = request.params[2].get_array(); for (unsigned int idx = 0; idx < keys.size(); idx++) { UniValue k = keys[idx]; CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); tempKeystore.AddKey(key); } } #ifdef ENABLE_WALLET else if (pwalletMain) EnsureWalletIsUnlocked(); #endif // Add previous txouts given in the RPC call: if (request.params.size() > 1 && !request.params[1].isNull()) { UniValue prevTxs = request.params[1].get_array(); for (unsigned int idx = 0; idx < prevTxs.size(); idx++) { const UniValue& p = prevTxs[idx]; if (!p.isObject()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); UniValue prevOut = p.get_obj(); RPCTypeCheckObj(prevOut, { {"txid", UniValueType(UniValue::VSTR)}, {"vout", UniValueType(UniValue::VNUM)}, {"scriptPubKey", UniValueType(UniValue::VSTR)}, }); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); COutPoint out(txid, nOut); std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { const Coin& coin = view.AccessCoin(out); if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) { std::string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = 0; newcoin.nHeight = 1; view.AddCoin(out, std::move(newcoin), true); } // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheckObj(prevOut, { {"txid", UniValueType(UniValue::VSTR)}, {"vout", UniValueType(UniValue::VNUM)}, {"scriptPubKey", UniValueType(UniValue::VSTR)}, {"redeemScript", UniValueType(UniValue::VSTR)}, }); UniValue v = find_value(prevOut, "redeemScript"); if (!v.isNull()) { std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } #ifdef ENABLE_WALLET const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); #else const CKeyStore& keystore = tempKeystore; #endif int nHashType = SIGHASH_ALL; if (request.params.size() > 3 && !request.params[3].isNull()) { static std::map<std::string, int> mapSigHashValues = boost::assign::map_list_of (std::string("ALL"), int(SIGHASH_ALL)) (std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (std::string("NONE"), int(SIGHASH_NONE)) (std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (std::string("SINGLE"), int(SIGHASH_SINGLE)) (std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; std::string strHashType = request.params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Script verification errors UniValue vErrors(UniValue::VARR); // Use CTransaction for the constant parts of the // transaction to avoid rehashing. const CTransaction txConst(mergedTx); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const Coin& coin = view.AccessCoin(txin.prevout); if (coin.IsSpent()) { TxInErrorToJSON(txin, vErrors, "Input not found or already spent"); continue; } const CScript& prevPubKey = coin.out.scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CMutableTransaction& txv, txVariants) { if (txv.vin.size() > i) { txin.scriptSig = CombineSignatures(prevPubKey, txConst, i, txin.scriptSig, txv.vin[i].scriptSig); } } ScriptError serror = SCRIPT_ERR_OK; if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i), &serror)) { TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror)); } } bool fComplete = vErrors.empty(); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(mergedTx))); result.push_back(Pair("complete", fComplete)); if (!vErrors.empty()) { result.push_back(Pair("errors", vErrors)); } return result; } UniValue sendrawtransaction(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) throw std::runtime_error( "sendrawtransaction \"hexstring\" ( allowhighfees instantsend bypasslimits)\n" "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n" "\nAlso see createrawtransaction and signrawtransaction calls.\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n" "2. allowhighfees (boolean, optional, default=false) Allow high fees\n" "3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n" "4. bypasslimits (boolean, optional, default=false) Bypass transaction policy limits\n" "\nResult:\n" "\"hex\" (string) The transaction hash in hex\n" "\nExamples:\n" "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\"") ); LOCK(cs_main); RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL)); // parse hex string from parameter CMutableTransaction mtx; if (!DecodeHexTx(mtx, request.params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); CTransactionRef tx(MakeTransactionRef(std::move(mtx))); const uint256& hashTx = tx->GetHash(); CAmount nMaxRawTxFee = maxTxFee; if (request.params.size() > 1 && request.params[1].get_bool()) nMaxRawTxFee = 0; bool fInstantSend = false; if (request.params.size() > 2) fInstantSend = request.params[2].get_bool(); bool fBypassLimits = false; if (request.params.size() > 3) fBypassLimits = request.params[3].get_bool(); CCoinsViewCache &view = *pcoinsTip; bool fHaveChain = false; for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) { const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o)); fHaveChain = !existingCoin.IsSpent(); } bool fHaveMempool = mempool.exists(hashTx); if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets if (fInstantSend && !instantsend.ProcessTxLockRequest(*tx, *g_connman)) { throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info"); } CValidationState state; bool fMissingInputs; if (!AcceptToMemoryPool(mempool, state, std::move(tx), !fBypassLimits, &fMissingInputs, false, nMaxRawTxFee)) { if (state.IsInvalid()) { throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); } else { if (fMissingInputs) { throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs"); } throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason()); } } } else if (fHaveChain) { throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain"); } if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); g_connman->RelayTransaction(*tx); return hashTx.GetHex(); } static const CRPCCommand commands[] = { // category name actor (function) okSafeMode // --------------------- ------------------------ ----------------------- ---------- { "rawtransactions", "getrawtransaction", &getrawtransaction, true, {"txid","verbose"} }, { "rawtransactions", "createrawtransaction", &createrawtransaction, true, {"inputs","outputs","locktime"} }, { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true, {"hexstring"} }, { "rawtransactions", "decodescript", &decodescript, true, {"hexstring"} }, { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false, {"hexstring","allowhighfees","instantsend","bypasslimits"} }, { "rawtransactions", "signrawtransaction", &signrawtransaction, false, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */ { "blockchain", "gettxoutproof", &gettxoutproof, true, {"txids", "blockhash"} }, { "blockchain", "verifytxoutproof", &verifytxoutproof, true, {"proof"} }, }; void RegisterRawTransactionRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
[ "osaru3@saruyamax.com" ]
osaru3@saruyamax.com
c7443a72fb684d60064a22afe970a823fb316bf7
7dd05848e173a624177427f66a1ef7786e94db58
/extern/lua-5.4.2/src/linit.cc
3dd960b5b2efc64d4368769dd07d8857af7e33fb
[ "MIT" ]
permissive
stjordanis/rd-eztraits
6606ca7b63e088b4b045da4ac040125c39a43763
5e549edef7a4a39e03747b375a85d8262d0d8431
refs/heads/master
2023-07-13T12:24:03.974345
2021-08-18T10:53:10
2021-08-18T10:53:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,705
cc
/* ** $Id: linit.c $ ** Initialization of libraries for lua.c and other clients ** See Copyright Notice in lua.h */ #define linit_c #define LUA_LIB /* ** If you embed Lua in your program and need to open the standard ** libraries, call luaL_openlibs in your program. If you need a ** different set of libraries, copy this file to your project and edit ** it to suit your needs. ** ** You can also *preload* libraries, so that a later 'require' can ** open the library, which is already linked to the application. ** For that, do the following code: ** ** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); ** lua_pushcfunction(L, luaopen_modname); ** lua_setfield(L, -2, modname); ** lua_pop(L, 1); // remove PRELOAD table */ #include "extern/lua-5.4.2/src/lprefix.h" #include <stddef.h> #include "extern/lua-5.4.2/src/lua.h" #include "extern/lua-5.4.2/src/lualib.h" #include "extern/lua-5.4.2/src/lauxlib.h" /* ** these libs are loaded by lua.c and are readily available to any Lua ** program */ static const luaL_Reg loadedlibs[] = { {LUA_GNAME, luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, {LUA_IOLIBNAME, luaopen_io}, {LUA_OSLIBNAME, luaopen_os}, {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_UTF8LIBNAME, luaopen_utf8}, {LUA_DBLIBNAME, luaopen_debug}, {NULL, NULL} }; LUALIB_API void luaL_openlibs (lua_State *L) { const luaL_Reg *lib; /* "require" functions from 'loadedlibs' and set results to global table */ for (lib = loadedlibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } }
[ "manfred.grabherr@imbim.uu.se" ]
manfred.grabherr@imbim.uu.se
57fec50d11f2df8706f891a0e21c9df4c564569a
64ed6f392c2c43c359d0aab24c6ec84b14fb7487
/SharedPtr.h
a4e21003618a431fa0c46c823b1eac82bcd31b95
[]
no_license
rushing-w/DataStruct
e655a8583b77526a823158271f72ac07b7527e65
afb77f2eb20b2cbd440f6a1511a66b305a568c0b
refs/heads/master
2021-01-20T07:21:14.679406
2017-05-03T05:22:43
2017-05-03T05:22:43
83,885,978
2
0
null
null
null
null
GB18030
C++
false
false
2,927
h
#pragma once #include<iostream> using namespace std; //由于上面的指针存在各种各样的问题,只能适用于特定的场合,所以我们需要实现一种比较通用的, //在这里,实现了SharedPtr,即引用计数的深拷贝 template<class T> class SharedPtr { public: SharedPtr(T* ptr = NULL) : _ptr(ptr) { _count = new int(1); } SharedPtr(SharedPtr<T>& sp) : _ptr(sp._ptr) { (*sp._count)++; _count = sp._count; } SharedPtr<T>& operator=(SharedPtr<T>& sp) { if (_ptr != sp._ptr) { _ptr = sp._ptr; if (*sp._count == 1) { (*sp._count)++; _count = sp._count; } else { (*sp._count)++; (*_count)--; _count = sp._count; } } return *this; } ~SharedPtr() { if (_ptr && --(*_count) == 0) { delete _ptr; delete _count; } _ptr = NULL; _count = NULL; } T operator*() { if (_ptr) return *_ptr; return 0; } T* operator->() { return _ptr; } private: T* _ptr; int* _count; }; void TestSharedPtr() { SharedPtr<int> sp1(new int(3)); SharedPtr<int> sp2(sp1); SharedPtr<int> sp3; SharedPtr<int> sp4(sp3); sp4 = sp1; } //虽然这种引用计数版本的简化版智能指针SharedPtr解决了释放空间时的问题,但是还存在不少问题 //1、存在线程安全问题 //2、循环引用问题-->当我们使用双向链表时,p1的next指向p2,p2的prev指向p1,这时p1和p2的_count值都为2,因为 //都有两个指针指向了一块空间,所以删除时,需要将其中一个的_count--,但是另外一个还在使用这一块空间,所以总是存在 //两个指针指向这块空间,所以直接删除是删除不了的 //---------->>>所以,在boost库中引入了weak_ptr来打破循环引用(weak_ptr不增加引用计数),weak_ptr是一种 //不控制的所指向对象生存期的智能指针,它指向由一个shared_ptr管理的对象。将一个weak_ptr绑定到一个shared_ptr //上,不会改变shared_ptr的引用计数。即存在循环引用时将weak_ptr的_count++,不去处理shared_ptr的_count。 //一旦最后一个指向对象的shared_ptr被销毁的话,对象就会被释放,即使weak_ptr有指向的对象,对象也还是会被释放 。 //3、定置删除器--->需要包含boost库,所以这里就贴一下代码(vs里面似乎没有这个库) //#include <boost/shared_ptr.hpp> //using namespace boost; //// 定置的删除器仿函数 //class FClose //{ //public : // void operator () (void* ptr) // { // cout << "fclose" << endl; // fclose((FILE *)ptr); // } //}; // //class Free //{ //public : // void operator () (void* ptr) // { // cout << "free" << endl; // free(ptr); // } //}; //void Test() //{ // // 定制删除器 // shared_ptr<FILE> p1(fopen("test.txt", "w"), FClose()); // // 定制删除器和分配器 // shared_ptr<int> p2((int *)malloc(sizeof(int)), Free(), allocator<int>()); //}
[ "1030104052@qq.com" ]
1030104052@qq.com
e2c98e4a9ff836be45f3c3440060f3657a812522
06c742cf2cb5568925e24a3f8090347efcf59b0f
/Beam_DX11_3D_ENGINE/Code/Source/Rendering/Material.cpp
ed1761ff68d72a400712a890fbd2e2cf0b74d7ff
[]
no_license
BeamPoints/Beam_Dev_3D_Engine
b71b65b158c12f87fbd365728736b876b7a268a3
3d6295834e90775bc70716d46d2dd1c3ee0229de
refs/heads/master
2020-04-23T00:00:34.108045
2019-02-22T15:08:49
2019-02-22T15:08:49
170,762,265
0
0
null
null
null
null
UTF-8
C++
false
false
961
cpp
#include "../../Include/Rendering/Material.h" bool CMaterial::LoadShader(std::string const & aFilename, std::vector<char>& aByteCode) { std::ifstream file; file.open(aFilename, std::ios::binary); bool const ok = not (file.eof() or file.fail()); if (ok) { file.seekg(0, std::ios_base::end); std::streampos fileSize = file.tellg(); aByteCode.resize(fileSize); file.seekg(0, std::ios_base::beg); file.read(aByteCode.data(), fileSize); } return ok; } std::vector<D3D11_INPUT_ELEMENT_DESC> const CMaterial::MaterialInfo::sVertexLayout = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R32G32B32_FLOAT, 2, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 3, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } };
[ "beampoints@gmail.com" ]
beampoints@gmail.com
11028e22090336c8de6d4c497e0bebb28063b5c3
5f790869382ac6a2c7e0ae913ccbfdb60508c694
/Level 2/Math/Rearrange Array.cpp
2c2c13bb006eb9ac6707e076fd51f102fd0cb47d
[]
no_license
rohithmone27/InterviewBit
4e702a62d4f8ff88ca89ebc3012ecbab86aacb03
cbf65c69159d0a552b53b8e61bc94c76c85582e1
refs/heads/master
2022-11-28T23:22:30.520518
2020-08-09T16:45:08
2020-08-09T16:45:08
285,234,911
6
0
null
null
null
null
UTF-8
C++
false
false
187
cpp
void Solution::arrange(vector<int> &A) { int n=A.size(); for(int i=0;i<n;i++){ A[i] += (A[A[i]]%n) *n; } for(int i=0;i<n;i++){ A[i] /= n; } }
[ "noreply@github.com" ]
rohithmone27.noreply@github.com
1bf936e157d31bca7fb049e14d8e5a2d98ece116
ee9c5d0ca8f5b0884827f808fd74289f5f8fc5f2
/problems/BOJ/BOJ1626.cpp
272d5b73e2e8d9d8f9ae4db9b797efb405a95a44
[]
no_license
caoash/competitive-programming
a1f69a03da5ea6eae463c6ae521a55bf32011752
f98d8d547d25811a26cf28316fbeb76477b6c63f
refs/heads/master
2022-05-26T12:51:37.952057
2021-10-10T22:01:03
2021-10-10T22:01:03
162,861,707
21
1
null
null
null
null
UTF-8
C++
false
false
5,944
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using vl = vector<ll>; #define pb push_back #define rsz resize #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() using pi = pair<int,int>; #define f first #define s second #define mp make_pair const int MX = 50005; const int MOD = (int) (1e9 + 7); const ll INF = (ll) 1e18; namespace output { void pr(int x) { cout << x; } void pr(long x) { cout << x; } void pr(ll x) { cout << x; } void pr(unsigned x) { cout << x; } void pr(unsigned long x) { cout << x; } void pr(unsigned long long x) { cout << x; } void pr(float x) { cout << x; } void pr(double x) { cout << x; } void pr(long double x) { cout << x; } void pr(char x) { cout << x; } void pr(const char * x) { cout << x; } void pr(const string & x) { cout << x; } void pr(bool x) { pr(x ? "true" : "false"); } template < class T1, class T2 > void pr(const pair < T1, T2 > & x); template < class T > void pr(const T & x); template < class T, class...Ts > void pr(const T & t, const Ts & ...ts) { pr(t); pr(ts...); } template < class T1, class T2 > void pr(const pair < T1, T2 > & x) { pr("{", x.f, ", ", x.s, "}"); } template < class T > void pr(const T & x) { pr("{"); // const iterator needed for vector<bool> bool fst = 1; for (const auto & a: x) pr(!fst ? ", " : "", a), fst = 0; pr("}"); } void ps() { pr("\n"); } // print w/ spaces template < class T, class...Ts > void ps(const T & t, const Ts & ...ts) { pr(t); if (sizeof...(ts)) pr(" "); ps(ts...); } void pc() { cout << "]" << endl; } // debug w/ commas template < class T, class...Ts > void pc(const T & t, const Ts & ...ts) { pr(t); if (sizeof...(ts)) pr(", "); pc(ts...); } #define dbg(x...) pr("[", #x, "] = ["), pc(x); } #ifdef LOCAL using namespace output; #endif template < int SZ > struct LCA { int depth[SZ]; int p[SZ][33]; int pmx[SZ][33]; int smx[SZ][33]; vector<pi> adj[SZ]; void addEdge(int u, int v, int w) { adj[u].push_back(mp(v, w)); adj[v].push_back(mp(u, w)); } void dfs(int v, int par) { for (pi to : adj[v]) { if (to.f != par) { p[to.f][0] = v; pmx[to.f][0] = to.s; depth[to.f] = depth[v] + 1; dfs(to.f, v); } } } void precomp() { for (int i = 0; i < SZ; i++) { for (int j = 0; j < 32; j++) { p[i][j] = -1; pmx[i][j] = -1; smx[i][j] = -1; } } p[0][0] = 0; pmx[0][0] = 0; dfs(0, -1); for (int j = 1; j < 32; j++) { for (int i = 0; i < SZ; i++) { if (p[i][j - 1] == -1) { p[i][j] = -1; pmx[i][j] = -1; } else { p[i][j] = p[p[i][j - 1]][j - 1]; pmx[i][j] = max(pmx[i][j - 1], pmx[p[i][j - 1]][j - 1]); smx[i][j] = max(smx[i][j - 1], smx[p[i][j - 1]][j - 1]); if (pmx[i][j - 1] != pmx[p[i][j - 1]][j - 1]) { smx[i][j] = max(smx[i][j], min(pmx[i][j - 1], pmx[p[i][j - 1]][j - 1])); } } } } } int query(int a, int b) { if (depth[a] > depth[b]) { swap(a, b); } int lift = depth[b] - depth[a]; int ans = 0; for (int j = 31; j >= 0; j--) { if (lift & (1 << j)) { ans = max(ans, pmx[b][j]); b = p[b][j]; } } for (int j = 31; j >= 0; j--) { if (p[a][j] != p[b][j]) { ans = max(ans, pmx[a][j]); ans = max(ans, pmx[b][j]); a = p[a][j]; b = p[b][j]; } } return (a == b) ? ans : max(ans, max(pmx[a][0], pmx[b][0])); } int query2(int a, int b, int best) { int ans = 0; auto chk = [&] (int i, int j) { if (pmx[i][j] == best) { ans = max(ans, smx[i][j]); } else { ans = max(ans, pmx[i][j]); } }; if (depth[a] > depth[b]) { swap(a, b); } int lift = depth[b] - depth[a]; for (int j = 31; j >= 0; j--) { if (lift & (1 << j)) { chk(b, j); b = p[b][j]; } } for (int j = 31; j >= 0; j--) { if (p[a][j] != p[b][j]) { chk(a, j); chk(b, j); a = p[a][j]; b = p[b][j]; } } if (a != b) { chk(a, 0); chk(b, 0); } return ans; } }; template < int SZ > struct DSU { int p[SZ], sz[SZ]; void init() { for (int i = 0; i < SZ; i++) { p[i] = i; sz[i] = 1; } } int find(int x) { return p[x] = (p[x] == x ? x : find(p[x])); } void merge(int u, int v) { int a = find(u); int b = find(v); if (a != b) { if (sz[a] < sz[b]) { swap(a, b); } p[b] = a; sz[a] += sz[b]; } } }; vector<pair<int, pi>> edges; vector<pair<int, pi>> bad; DSU<MX> dsu; LCA<MX> lca; int main(){ ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int u, v, w; cin >> u >> v >> w; u--, v--; edges.pb(mp(w, mp(u, v))); } dsu.init(); sort(all(edges)); ll cost = 0; int num = 0; for (auto x : edges) { if (dsu.find(x.s.f) != dsu.find(x.s.s)) { // dbg(x.s.f, x.s.s); dsu.merge(x.s.f, x.s.s); lca.addEdge(x.s.f, x.s.s, x.f); ++num; cost += x.f; } else { bad.pb(x); } } if (num != n - 1) { cout << -1 << '\n'; return 0; } lca.precomp(); ll ans = INF; for (auto x : bad) { int curr = lca.query(x.s.f, x.s.s); if (curr == x.f) { curr = lca.query2(x.s.f, x.s.s, curr); } ans = min(ans, cost - curr + x.f); } cout << (ans == INF ? -1 : ans) << '\n'; }
[ "caoash@gmail.com" ]
caoash@gmail.com
25071a0ded9f81060f559feee155a61b7753d78e
4c6af24752eda9fc0dec55f198530d447a8494af
/HW_1/task6/task6/task6.cpp
5c22f90c791a2b3f342e11a3379412884c149fe0
[]
no_license
vlad24/FIRST-SEMESTER
45feff9d6ffc165d82956593b855f6944af137f7
72d2a6d6ea7d53922a924f00c4182c52508ebbb4
refs/heads/master
2020-04-15T20:47:39.805095
2013-02-17T18:57:09
2013-02-17T18:57:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
814
cpp
//#include "stdafx.h" #include "iostream" using namespace std; int slen(char c[]) { int u = 0; while (c[u] != '\0') { u++; } return u; } int main() { char mainstring[100] = {}; char substring[100] = {}; cout << "Enter the main string : " ; cin >> mainstring; cout << "Enter the sub string : " ; cin >> substring; int lengthmain = slen(mainstring); int lengthsub = slen(substring); int amount = 0; int indicator = 0; for (int j = 0; j <= lengthmain - lengthsub; j++ ) { indicator = 0; for (int k = 0; k <= lengthsub; k++ ) { if (mainstring[j + k] == substring[k]) { if ((k == lengthsub - 1) && (indicator == 0)) amount ++; } else { indicator =- 1; } } } cout << "Amount of occurences = " << amount ; int time = 0; cin >> time; return 0; }
[ "vlad.pavlov24@gmail.com" ]
vlad.pavlov24@gmail.com
28bc78033dfa9a3b5291f1011132178e9af86e93
5e2e27daacfddfe119015736fcc6e9a864d66c49
/GameEngine/Graphics/FrustumCalc.cpp
f3e4d4875d8d0e6c78eb75f677056e41f9e4fa38
[]
no_license
mdubovoy/Animation_System
17ddc22740962209e7edbd8ea85bec108499f3e2
b356d0ea6812e0548336bc4813662463e786de93
refs/heads/master
2021-01-22T11:41:13.637727
2014-09-22T14:01:20
2014-09-22T14:01:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,987
cpp
#include "FrustumCalc.h" #include "Camera.h" extern Camera* pCamera; // only used if we want this object to have its own ModelView for debug #define COLLISION_DEMO 0 // 1 - keys set up to move cube for collision demo, 0 - keys set up to move camera FrustumCalc::FrustumCalc() { lightColor = Vect(1.0f, 0.0f, 0.0f, 0.0f); // boundingRadius set inside each GraphicObject's transform } void FrustumCalc::updateSphere(const Matrix& World, Vect& center) { // get 3 more vectors on sphere besides the center // we want to know our center and radiuss Vect Px = center + this->boundingRadius * Vect(1, 0, 0); Vect Py = center + this->boundingRadius * Vect(0, 1, 0); Vect Pz = center + this->boundingRadius * Vect(0, 0, 1); // transform vectors by multiplying by localToVector, just like object itself Vect transPx = Px * World; Vect transPy = Py * World; Vect transPz = Pz * World; Vect transCenter = center * World; //Check // our new transformed center center = transCenter; // calculate max distance, using transformed vects, this will be new bounding radius for object float distX = (transPx - center).mag(); float distY = (transPy - center).mag(); float distZ = (transPz - center).mag(); // figure out the max distance, set to DistX first float maxDist = this->maxBoundingObjectDistance(distX, distY, distZ); // our new bounding radius this->boundingRadius = maxDist; #if COLLISION_DEMO //********Bounding Object's own ModelView for DEBUG only - used to draw sphere********** this->center = Vect(0.0f, 0.0f, 0.0f); // For Collision Demo only static float angle_x = 0.0f; angle_x += 0.15f; Matrix Scale(SCALE, 1.0f, 1.0f, 1.0f); Matrix RotX(ROT_X, angle_x); Matrix Trans(TRANS, -2.0f, 0.0f, 0.0f); this->World = Scale * Trans; // not using ROT this->center *= this->World; this->ModelView = this->World * pCamera->getViewMatrix(); #else #endif } float FrustumCalc::maxBoundingObjectDistance(const float distX, const float distY, const float distZ) const { float maxDist = distX; // if Z is greater than Y, then only compare DistX with DistZ if(distZ >= distY) { if(distX < distZ) maxDist = distZ; } // otherwise only compare DistX with DistY else if(distY > distZ) { if(distX < distY) maxDist = distY; } return maxDist; } bool FrustumCalc::insideFrustum(const Vect& center, const Camera* const camera) { bool inside; // get frustum's corner points Vect camNearBottomLeft; Vect camFarTopRight; camera->getNearBottomLeft(camNearBottomLeft); camera->getFarTopRight(camFarTopRight); // get normal from each plane Vect camFrontNorm; Vect camBackNorm; Vect camRightNorm; Vect camLeftNorm; Vect camTopNorm; Vect camBottomNorm; camera->getFrontNorm(camFrontNorm); camera->getBackNorm(camBackNorm); camera->getRightNorm(camRightNorm); camera->getLeftNorm(camLeftNorm); camera->getTopNorm(camTopNorm); camera->getBottomNorm(camBottomNorm); float distLeft = (center - camNearBottomLeft).dot(camLeftNorm); float distFront = (center - camNearBottomLeft).dot(camFrontNorm); float distBottom = (center - camNearBottomLeft).dot(camBottomNorm); float distRight = (center - camFarTopRight).dot(camRightNorm); float distBack = (center - camFarTopRight).dot(camBackNorm); float distTop = (center - camFarTopRight).dot(camTopNorm); // set to true only if culling tests pass if(distLeft < this->boundingRadius && distFront < this->boundingRadius && distBottom < this->boundingRadius && distRight < this->boundingRadius && distBack < this->boundingRadius && distTop < this->boundingRadius) { inside = true; } else inside = false; return inside; } bool FrustumCalc::insideCollisionDemoCube(const Cube* const model) { bool inside; float distLeft = (this->center - model->nearBottomLeft).dot(model->leftNorm); float distFront = (this->center - model->nearBottomLeft).dot(model->frontNorm); float distBottom = (this->center - model->nearBottomLeft).dot(model->bottomNorm); float distRight = (this->center - model->farTopRight).dot(model->rightNorm); float distBack = (this->center - model->farTopRight).dot(model->backNorm); float distTop = (this->center - model->farTopRight).dot(model->topNorm); // set to true only if culling tests pass if(distLeft < this->boundingRadius && distFront < this->boundingRadius && distBottom < this->boundingRadius && distRight < this->boundingRadius && distBack < this->boundingRadius && distTop < this->boundingRadius) { inside = true; } else inside = false; return inside; }
[ "michel.dubovoy@gmail.com" ]
michel.dubovoy@gmail.com
ebef6d955ce85c26db137504d85b30c34ef224e7
c3b4b1441a6ee5a7b6c48e4f9f0649fe14d881b3
/ClusterSKSolver/source/SKLoader.cpp
af473b8672d278d57f54f605dff2aad617909c4d
[]
no_license
antsuabon/ClusterSKSolver
c50b4452530e46c7b137f9e1360290f9c67f7c6b
42dfaa84c6890c6a55e7bac6c7c2961fa98979cf
refs/heads/master
2023-06-04T10:44:19.759862
2021-06-27T20:22:03
2021-06-27T20:22:03
349,968,214
0
0
null
null
null
null
UTF-8
C++
false
false
1,750
cpp
#include "../header/SKLoader.h" using namespace std; vector<string> tokenize(string s, string del = " ") { vector<string> res; int start = 0; int end = s.find(del); while (end != -1) { res.push_back(s.substr(start, end - start)); start = end + del.size(); end = s.find(del, start); } res.push_back(s.substr(start, end - start)); return res; } void loadSudoku(string path, int **sudokuArray, map<vector<pair<int, int>>, int> *blocks, int *n, int *regionX, int *regionY) { ifstream infile(path); string line; string state = ""; vector<vector<int>> initialState; while (std::getline(infile, line)) { if (!line.empty()) { if (line.find("r") != string::npos) { state = "r"; } else if (line.find("b") != string::npos) { state = "b"; } else if (state == "r") { vector<string> tokens = tokenize(line, "x"); (*regionX) = stoi(tokens[0]); (*regionY) = stoi(tokens[1]); } else if (state == "b") { vector<string> tokens1 = tokenize(line, "->"); vector<pair<int, int>> positions; vector<string> tokens2 = tokenize(tokens1[0], "|"); for (string &var2 : tokens2) { vector<string> tokens3 = tokenize(var2, ","); positions.push_back({stoi(tokens3[0]), stoi(tokens3[1])}); } blocks->insert({positions, stoi(tokens1[1])}); } else { vector<int> row; vector<string> tokens = tokenize(line, ","); for (string &var : tokens) { row.push_back(stoi(var)); } initialState.push_back(row); } } } (*n) = initialState.size(); (*sudokuArray) = new int[(*n) * (*n)]; for (size_t i = 0; i < (*n); i++) { for (size_t j = 0; j < (*n); j++) { (*sudokuArray)[i * (*n) + j] = initialState[i][j]; } } }
[ "antsuabon@alum.us.es" ]
antsuabon@alum.us.es
60f9420dc7a126df23acd2a3d1eccf4c2ec70e33
35ef95e579c011d2e62c498fe4346aaf0db16006
/Project6 126.cpp
d60f4c8f9f1107d9ad19126e0f03ee4d5713c09d
[]
no_license
weifengshi/CS200
f3931267232daf05ad9df31d052e7a0db0af8816
1e4e3b0cb5fdd497f1794d194210d8a85459094b
refs/heads/master
2018-12-18T17:24:38.684609
2018-09-14T17:58:01
2018-09-14T17:58:01
79,519,356
0
0
null
2018-09-14T17:57:10
2017-01-20T02:58:07
C++
UTF-8
C++
false
false
592
cpp
#include<iostream> using namespace std; int main() { float a, b; cout << "Enter a:"; cin >> a; cout << "Enter b:"; cin >> b; int number; cout << endl << "What kind of operation?(1)Add,(2)Subtract,(3)Multiply,(4)Divide" << endl; cout << "Choice:"; cin >> number; switch (number) { case 1: cout << a + b << endl; break; case 2: cout << a - b << endl; break; case 3: cout << a * b << endl; break; case 4: cout << a / b << endl; break; default: cout << "Invalid choice" << endl; } int x; cin >> x; return 0; }
[ "noreply@github.com" ]
weifengshi.noreply@github.com
7e7ee7e400491d8def14209c22d725af2e09833d
f1b5f30436d91a3331cca7fb927e68fad4066b6f
/HX711Serial/HX711Serial.ino
54e84b53e697dfc3d0ac0378381b82bb9e70140d
[]
no_license
woodif/HX-711
1a9da33d28c9baa4a6732b117255bbd9ee46dc36
5d4a84491e27eee49a42790c92adc9791dd8a9ea
refs/heads/master
2016-09-02T04:49:48.756846
2015-05-16T10:21:01
2015-05-16T10:21:01
35,719,265
0
0
null
null
null
null
UTF-8
C++
false
false
1,699
ino
#include "HX711.h" #include <SoftwareSerial.h> #include <Wire.h> //#include <LiquidCrystal_I2C.h> // HX711.DOUT - pin #A1 // HX711.PD_SCK - pin #A0 //LiquidCrystal_I2C lcd(0x27, 16, 2); HX711 scale(A1, A0); // parameter "gain" is ommited; the default value 128 is used by the library //SoftwareSerial mySerial(10, 9); // RX, TX static float buf ; static float raw ; void setup() { Serial.begin(115200); Serial.println("HX711 Demo"); Serial.println("Before setting up the scale:"); Serial.print("read: \t\t"); Serial.println(scale.read()); // print a raw reading from the ADC /////////////////////////////////////////////////////////////// // lcd.begin(); // lcd.print("Term Project"); // lcd.setCursor(0, 1); // lcd.print("Weight Sensor"); // delay(3000); // Serial.begin(57600); // mySerial.begin(9600); } void loop() { raw = (scale.read() - 8625100.00f) / 41850.11091f; raw -= 26.35; raw *= 2.049335863f; // buf = buf + 0.9f*(raw - buf); //// buf -= 0 ; // buf *= -1 ; Serial.print("real reading:\t"); Serial.print(scale.read()); Serial.print("\t| one reading:\t"); Serial.println(raw); // Serial.print("\t| average:\t"); // Serial.println(buf,1); } /////////////////////////////////////////////////////// // if (buf >= 1){ //// lcd.begin(); //// lcd.print("Weight Unit Kg."); //// lcd.setCursor(0, 1); //// lcd.print(buf,1); //delay(10); // } // else { //// lcd.begin(); //// lcd.print("Weight Sensor"); //// lcd.setCursor(0, 1); //// lcd.print("By Elec. RMUTL"); // } // ////if (mySerial.available()) //// Serial.write(mySerial.read()); //// if (Serial.available()) // mySerial.print(buf,1); //delay(100); //}
[ "sarawoot_202@hotmail.com" ]
sarawoot_202@hotmail.com
5be9054993f9ddc91df121b7adabbedc3b46eba0
0897a99cad19fdbc4b5a65571bc148aa28086726
/include/OutOfCore/BlockwiseImage.hpp
b0673216913a9f30ed17d95ffeecb0f79af4fd2c
[]
no_license
sg47/Out_Of_Core_Module
10c39c03cc85d448e280591333d402cbed87a96a
d1d907df47a508b8a05473deb7f977b32d80be00
refs/heads/master
2021-01-22T15:23:10.524661
2012-09-12T12:14:35
2012-09-12T12:14:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,225
hpp
#ifndef _BLOCKWISE_IMAGE_HPP #define _BLOCKWISE_IMAGE_HPP #include "BlockwiseImage.h" #include "IndexMethod.hpp" #include <boost/assert.hpp> #include <boost/lexical_cast.hpp> #include <string> #include <fstream> #include <strstream> #ifdef SAVE_MINI_IMAGE /*---------------------------------------------*/ /* opencv part */ #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #ifdef NDEBUG #pragma comment(lib, "opencv_highgui240.lib") #pragma comment(lib, "opencv_core240.lib") #pragma comment(lib, "opencv_imgproc240.lib") #else #pragma comment(lib, "opencv_highgui240d.lib") #pragma comment(lib, "opencv_core240d.lib") #pragma comment(lib, "opencv_imgproc240d.lib") #endif /*---------------------------------------------*/ #endif template<typename T, unsigned memory_usage> BlockwiseImage<T, memory_usage>::BlockwiseImage(int rows, int cols, int mini_rows, int mini_cols, boost::shared_ptr<IndexMethodInterface> method) : GiantImageInterface(method ? method : (boost::shared_ptr<IndexMethodInterface>(new ZOrderIndex(rows, cols)))) { init(rows, cols); set_minimal_resolution(rows, cols, mini_rows, mini_cols); } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::reset() { init(0, 0); return true; } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::init(int rows, int cols) { BOOST_ASSERT(rows >= 0 && cols >= 0); /* ensure index_method is valid */ BOOST_ASSERT(index_method.use_count() != 0); img_size.rows = rows; img_size.cols = cols; img_container.resize(index_method->get_max_index() + 1); return true; } template<typename T, unsigned memory_usage> void BlockwiseImage<T, memory_usage>::set_minimal_resolution(int rows, int cols, int mini_rows, int mini_cols) { BOOST_ASSERT(m_mini_rows >= 0 && m_mini_cols >= 0 && rows >= mini_rows && cols >= mini_cols); /* ensure the mini_rows and mini_cols not zero to insure the correctness of the division */ if(mini_rows == 0) mini_rows = 1; if(mini_cols == 0) mini_cols = 1; size_t level_row = rows / mini_rows, level_col = cols / mini_cols; level_row = get_least_order_number(level_row); level_col = get_least_order_number(level_col); /* ensure the smallest image (the max scale level) is not less than mini_rows or mini_cols which user specified */ m_max_level = (level_row < level_col) ? level_row : level_col; /* recalculate the mini_rows and mini_cols */ m_mini_rows = std::ceil((double)(rows) / (1 << m_max_level)); m_mini_cols = std::ceil((double)(cols) / (1 << m_max_level)); } template<typename T, unsigned memory_usage> BlockwiseImage<T, memory_usage>::~BlockwiseImage() { img_container.clear(); } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::set_pixels(int start_row, int start_col, int rows, int cols, const std::vector<T> &data) { if(start_row < 0 || start_col < 0 || start_row > (get_image_rows()-1) || start_col > (get_image_cols()-1) || rows <= 0 || cols <= 0 || (start_row+rows) > get_image_rows() || (start_col+cols) > get_image_cols()) { std::cerr << "BlockwiseImage::set_pixels error : Invalid parameter" << std::endl; return false; } if(data.size() < (rows*cols)) return false; size_t count = 0; for(IndexMethodInterface::RowMajorIndexType row = 0; row < rows; ++row) { IndexMethodInterface::IndexType row_result = index_method->get_row_result(start_row+row); for(IndexMethodInterface::RowMajorIndexType col = 0; col < cols; ++col) { img_container[index_method->get_index_by_row_result(row_result, start_col+col)] = data[count++]; } } return true; } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::get_pixels(int start_row, int start_col, int rows, int cols, std::vector<T> &data) const { if(start_row < 0 || start_col < 0 || start_row > (get_image_rows()-1) || start_col > (get_image_cols()-1) || rows <= 0 || cols <= 0 || (start_row+rows) > get_image_rows() || (start_col+cols) > get_image_cols()) { std::cerr << "BlockwiseImage::get_pixels error : Invalid parameter" << std::endl; return false; } data.resize(rows*cols); static const ContainerType &c_img_container = img_container; size_t count = 0; for(IndexMethodInterface::RowMajorIndexType row = 0; row < rows; ++row) { IndexMethodInterface::IndexType row_result = index_method->get_row_result(start_row+row); for(IndexMethodInterface::RowMajorIndexType col = 0; col < cols; ++col) { data[count++] = c_img_container[index_method->get_index_by_row_result(row_result, start_col+col)]; } } return true; } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::set_pixels(int start_row, int start_col, int rows, int cols, const T clear_value) { if(start_row < 0 || start_col < 0 || start_row > (get_image_rows()-1) || start_col > (get_image_cols()-1) || rows <= 0 || cols <= 0 || (start_row+rows) > get_image_rows() || (start_col+cols) > get_image_cols()) { std::cerr << "BlockwiseImage::set_pixels error : Invalid parameter" << std::endl; return false; } for(IndexMethodInterface::RowMajorIndexType row = 0; row < rows; ++row) { IndexMethodInterface::IndexType row_result = index_method->get_row_result(start_row+row); for(IndexMethodInterface::RowMajorIndexType col = 0; col < cols; ++col) { img_container[index_method->get_index_by_row_result(row_result, start_col+col)] = clear_value; } } return true; } template<typename T, unsigned memory_usage> const T& BlockwiseImage<T, memory_usage>::operator()(int row, int col) const { BOOST_ASSERT(0 <= row && row < img_size.rows && 0 <= col && col < img_size.cols); static const ContainerType &c_img_container = img_container; return c_img_container[index_method->get_index(row, col)]; } template<typename T, unsigned memory_usage> T& BlockwiseImage<T, memory_usage>::operator()(int row, int col) { BOOST_ASSERT(0 <= row && row < img_size.rows && 0 <= col && col < img_size.cols); return img_container[index_method->get_index(row, col)]; } template<typename T, unsigned memory_usage> const T& BlockwiseImage<T, memory_usage>::get_pixel(int row, int col) const { return this->operator() (row, col); } template<typename T, unsigned memory_usage> T& BlockwiseImage<T, memory_usage>::get_pixel(int row, int col) { return this->operator() (row, col); } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::write_image_head_file(const char* file_name) { namespace bf = boost::filesystem; using namespace std; try { bf::path file_path(file_name); if(bf::is_directory(file_path)) { cerr << "file name should be a normal file" << endl; return false; } if(bf::extension(file_path) != ".bigimage") { cerr << "extension should be bigimage" << endl; return false; } if(!bf::exists(file_path.parent_path())) bf::create_directories(file_path.parent_path()); } catch(bf::filesystem_error &err) { cerr << err.what() << endl; return false; } ofstream fout(file_name, ios::out); if(!fout.is_open()) { cerr << "create " << file_name << " failure" << endl; return false; } /* the head file info */ fout << "type=" << "BlockwiseImage" << endl; fout << "rows=" << img_size.rows << endl; fout << "cols=" << img_size.cols << endl; fout << "filenodesize=" << file_node_size << endl; fout << "filenodeshiftnum=" << file_node_shift_num << endl; fout << "indexmethod=" << index_method->get_index_method_name() << endl; fout << "minirows=" << m_mini_rows << endl; fout << "minicols=" << m_mini_cols << endl; fout.close(); return true; } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::write_image(const char* file_name) { using namespace std; namespace bf = boost::filesystem; try { if(!write_image_head_file(file_name)) return false; bf::path file_path = file_name; bf::path data_path = (file_path.parent_path() / file_path.stem()).make_preferred(); if(bf::exists(data_path)) { bf::remove_all(data_path); cout << "[Warning] : " << data_path << " is existing, and the original directory will be removed" << endl; } /* block wise image only has one level : means the full size level */ data_path /= bf::path("level_0"); if(!bf::create_directories(data_path)) { cerr << "create directory " << data_path << "failure" << endl; return false; } /* because just read the image data, so just const reference to read for some kind of optimization */ static const ContainerType &c_img_container = img_container; int64 file_number = std::ceil((double)(c_img_container.size()) / file_node_size); T *temp_file_data = new T[file_node_size]; /* first write the full one file context */ int64 start_index = 0, file_loop = 0; for(; file_loop < file_number - 1; ++file_loop) { std::ostrstream strstream; strstream << data_path.generic_string() << "/" << file_loop << '\0'; ofstream file_out(strstream.str(), ios::out | ios::binary); if(!file_out.is_open()) { cerr << "create " << strstream.str() << " failure" << endl; return false; } start_index = (int64)(file_loop) << file_node_shift_num; for(int64 i = 0; i < file_node_size; ++i) { temp_file_data[i] = c_img_container[start_index + i]; } file_out.write(reinterpret_cast<const char*>(temp_file_data), sizeof(T)*file_node_size); file_out.close(); } /* write the last file till the end of the container(maybe not full) */ start_index = (int64)(file_loop) << file_node_shift_num; std::ostrstream strstream; strstream << data_path.generic_string() << "/" << file_loop << '\0'; ofstream file_out(strstream.str(), ios::out | ios::binary); if(!file_out.is_open()) { cerr << "create " << strstream.str() << " failure" << endl; return false; } int64 last_file_size = c_img_container.size() - start_index; for(int64 i = 0; i < last_file_size; ++i) { temp_file_data[i] = c_img_container[start_index + i]; } file_out.write(reinterpret_cast<const char*>(temp_file_data), sizeof(T)*last_file_size); file_out.close(); delete []temp_file_data; if(!save_mini_image(file_name)) return false; } catch(bf::filesystem_error &err) { cerr << err.what() << endl; return false; } return true; } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::write_image(const std::string &file_name) { return write_image(file_name.c_str()); } template<typename T, unsigned memory_usage> const T& BlockwiseImage<T, memory_usage>::at(IndexMethodInterface::IndexType index) const { BOOST_ASSERT(index < img_container.size()); static const ContainerType &c_img_container = img_container; return c_img_container[index]; } template<typename T, unsigned memory_usage> T& BlockwiseImage<T, memory_usage>::at(IndexMethodInterface::IndexType index) { BOOST_ASSERT(index < img_container.size()); return img_container[index]; } template<typename T, unsigned memory_usage> bool BlockwiseImage<T, memory_usage>::save_mini_image(const char *file_name) { #ifdef SAVE_MINI_IMAGE const ContainerType &c_img_container = img_container; /* total_size is the total cell size of the minimum size image * delta_count is the delta size when access the minimum size image data in * the whole size img_container */ IndexMethodInterface::IndexType total_size, file_cell_size, delta_count; total_size = c_img_container.size(); file_cell_size = total_size >> (2*m_max_level); delta_count = 1 << (2*m_max_level); std::vector<T> img_data(m_mini_rows*m_mini_cols); std::vector<T> img_zorder_data(file_cell_size); /* get the hierarchical image first */ for(IndexMethodInterface::IndexType i = 0, count = 0; i < file_cell_size; ++i, count += delta_count) { img_zorder_data[i] = c_img_container[count]; } /* convert it to the row-major format */ for(size_t row = 0; row < m_mini_rows; ++row) { IndexMethodInterface::IndexType row_result = index_method->get_row_result(row); for(size_t col = 0; col < m_mini_cols; ++col) { img_data[row*m_mini_cols+col] = img_zorder_data[index_method->get_index_by_row_result(row_result, col)]; } } boost::filesystem::path file_path = file_name; std::string mini_image_name = (file_path.parent_path() / (file_path.stem().generic_string() + ".jpg")).generic_string(); /* save the image into opencv format */ cv::Mat result_image(m_mini_rows, m_mini_cols, CV_8UC3, img_data.data()); /* convert the RGB format to opencv BGR format */ cv::cvtColor(result_image, result_image, CV_RGB2BGR); cv::imwrite(mini_image_name.c_str(), result_image); #endif return true; } /* deprecated function */ //boost::shared_ptr<BlockwiseImage<T, memory_usage> > BlockwiseImage<T, memory_usage>::load_image(const char *file_name) //{ // typedef boost::shared_ptr<BlockwiseImage<T, memory_usage> > PtrType; // PtrType dst_image(new BlockwiseImage<T, memory_usage> (0, 0)); // PtrType null_image; // // if(!dst_image->load_image_head_file(file_name)) return null_image; // // bf::path file_path(file_name); // bf::path data_path = (file_path.parent_path() / file_path.stem()).make_preferred(); // data_path /= "level_0"; // if(!bf::exists(data_path)) { // cerr << "image data missing" << endl; // return null_image; // } // // /* get the new value, then init for using */ // dst_image->init(dst_image->get_image_rows(), dst_image->get_image_cols()); // // ContainerType &img_container = dst_image->img_container; // int64 file_number = std::ceil((double)(img_container.size()) / dst_image->file_node_size); // // int64 start_index = 0, file_loop = 0; // int64 file_node_shift_num = dst_image->file_node_shift_num; // int64 file_node_size = dst_image->file_node_size; // // /* first read the full context files */ // for(; file_loop < file_number - 1; ++file_loop) { // std::ostrstream strstream; // strstream << data_path.generic_string() << "/" << file_loop << '\0'; // if(!bf::exists(bf::path(strstream.str()))) { // cerr << "image data missing" << endl; // return null_image; // } // // /* now read the existing data file */ // ifstream file_in(strstream.str(), ios::out | ios::binary); // if(!file_in.is_open()) { // cerr << "open" << strstream.str() << " failure" << endl; // return null_image; // } // // start_index = (int64)(file_loop) << file_node_shift_num; // for(int64 i = 0; i < file_node_size; ++i) { // file_in.read(reinterpret_cast<char*>(&img_container[start_index + i]), sizeof(T)); // } // file_in.close(); // } // // /* now read the last file */ // start_index = (int64)(file_loop) << file_node_shift_num; // std::ostrstream strstream; // strstream << data_path.generic_string() << "/" << file_loop << '\0'; // if(!bf::exists(bf::path(strstream.str()))) { // cerr << "image data missing" << endl; // return null_image; // } // ifstream file_in(strstream.str(), ios::out | ios::binary); // if(!file_in.is_open()) { // cerr << "open" << strstream.str() << " failure" << endl; // return null_image; // } // for(int64 last_index = start_index; last_index < img_container.size(); ++last_index) { // file_in.read(reinterpret_cast<char*>(&img_container[last_index]), sizeof(T)); // } // file_in.close(); // // return dst_image; //} #endif
[ "whiledoing@sina.com" ]
whiledoing@sina.com
e0f7e41260c6cd1a26d716ac9777ced1f1fb5730
0dc20516079aaae4756d28e67db7cae9c0d33708
/jxy/jxy_src/jxysvr/thirdparty/breakpad/src/processor/stackwalker_amd64.cc
06f4b98e0dbfc023bdc52acb4fed29b7a47a5064
[ "BSD-3-Clause" ]
permissive
psymicgit/dummy
149365d586f0d4083a7a5719ad7c7268e7dc4bc3
483f2d410f353ae4c42abdfe4c606ed542186053
refs/heads/master
2020-12-24T07:48:56.132871
2017-08-05T07:20:18
2017-08-05T07:20:18
32,851,013
3
8
null
null
null
null
UTF-8
C++
false
false
10,221
cc
// Copyright (c) 2010 Google 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: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // stackwalker_amd64.cc: amd64-specific stackwalker. // // See stackwalker_amd64.h for documentation. // // Author: Mark Mentovai, Ted Mielczarek #include "google_breakpad/processor/call_stack.h" #include "google_breakpad/processor/memory_region.h" #include "google_breakpad/processor/source_line_resolver_interface.h" #include "google_breakpad/processor/stack_frame_cpu.h" #include "processor/cfi_frame_info.h" #include "processor/logging.h" #include "processor/scoped_ptr.h" #include "processor/stackwalker_amd64.h" namespace google_breakpad { const StackwalkerAMD64::CFIWalker::RegisterSet StackwalkerAMD64::cfi_register_map_[] = { // It may seem like $rip and $rsp are callee-saves, because the callee is // responsible for having them restored upon return. But the callee_saves // flags here really means that the walker should assume they're // unchanged if the CFI doesn't mention them --- clearly wrong for $rip // and $rsp. { "$rax", NULL, false, StackFrameAMD64::CONTEXT_VALID_RAX, &MDRawContextAMD64::rax }, { "$rdx", NULL, false, StackFrameAMD64::CONTEXT_VALID_RDX, &MDRawContextAMD64::rdx }, { "$rcx", NULL, false, StackFrameAMD64::CONTEXT_VALID_RCX, &MDRawContextAMD64::rcx }, { "$rbx", NULL, true, StackFrameAMD64::CONTEXT_VALID_RBX, &MDRawContextAMD64::rbx }, { "$rsi", NULL, false, StackFrameAMD64::CONTEXT_VALID_RSI, &MDRawContextAMD64::rsi }, { "$rdi", NULL, false, StackFrameAMD64::CONTEXT_VALID_RDI, &MDRawContextAMD64::rdi }, { "$rbp", NULL, true, StackFrameAMD64::CONTEXT_VALID_RBP, &MDRawContextAMD64::rbp }, { "$rsp", ".cfa", false, StackFrameAMD64::CONTEXT_VALID_RSP, &MDRawContextAMD64::rsp }, { "$r8", NULL, false, StackFrameAMD64::CONTEXT_VALID_R8, &MDRawContextAMD64::r8 }, { "$r9", NULL, false, StackFrameAMD64::CONTEXT_VALID_R9, &MDRawContextAMD64::r9 }, { "$r10", NULL, false, StackFrameAMD64::CONTEXT_VALID_R10, &MDRawContextAMD64::r10 }, { "$r11", NULL, false, StackFrameAMD64::CONTEXT_VALID_R11, &MDRawContextAMD64::r11 }, { "$r12", NULL, true, StackFrameAMD64::CONTEXT_VALID_R12, &MDRawContextAMD64::r12 }, { "$r13", NULL, true, StackFrameAMD64::CONTEXT_VALID_R13, &MDRawContextAMD64::r13 }, { "$r14", NULL, true, StackFrameAMD64::CONTEXT_VALID_R14, &MDRawContextAMD64::r14 }, { "$r15", NULL, true, StackFrameAMD64::CONTEXT_VALID_R15, &MDRawContextAMD64::r15 }, { "$rip", ".ra", false, StackFrameAMD64::CONTEXT_VALID_RIP, &MDRawContextAMD64::rip }, }; StackwalkerAMD64::StackwalkerAMD64(const SystemInfo* system_info, const MDRawContextAMD64* context, MemoryRegion* memory, const CodeModules* modules, StackFrameSymbolizer* resolver_helper) : Stackwalker(system_info, memory, modules, resolver_helper), context_(context), cfi_walker_(cfi_register_map_, (sizeof(cfi_register_map_) / sizeof(cfi_register_map_[0]))) { } StackFrame* StackwalkerAMD64::GetContextFrame() { if (!context_) { BPLOG(ERROR) << "Can't get context frame without context"; return NULL; } StackFrameAMD64* frame = new StackFrameAMD64(); // The instruction pointer is stored directly in a register, so pull it // straight out of the CPU context structure. frame->context = *context_; frame->context_validity = StackFrameAMD64::CONTEXT_VALID_ALL; frame->trust = StackFrame::FRAME_TRUST_CONTEXT; frame->instruction = frame->context.rip; return frame; } StackFrameAMD64* StackwalkerAMD64::GetCallerByCFIFrameInfo( const vector<StackFrame*> &frames, CFIFrameInfo* cfi_frame_info) { StackFrameAMD64* last_frame = static_cast<StackFrameAMD64*>(frames.back()); scoped_ptr<StackFrameAMD64> frame(new StackFrameAMD64()); if (!cfi_walker_ .FindCallerRegisters(*memory_, *cfi_frame_info, last_frame->context, last_frame->context_validity, &frame->context, &frame->context_validity)) return NULL; // Make sure we recovered all the essentials. static const int essentials = (StackFrameAMD64::CONTEXT_VALID_RIP | StackFrameAMD64::CONTEXT_VALID_RSP); if ((frame->context_validity & essentials) != essentials) return NULL; frame->trust = StackFrame::FRAME_TRUST_CFI; return frame.release(); } StackFrameAMD64* StackwalkerAMD64::GetCallerByStackScan( const vector<StackFrame*> &frames) { StackFrameAMD64* last_frame = static_cast<StackFrameAMD64*>(frames.back()); u_int64_t last_rsp = last_frame->context.rsp; u_int64_t caller_rip_address, caller_rip; if (!ScanForReturnAddress(last_rsp, &caller_rip_address, &caller_rip)) { // No plausible return address was found. return NULL; } // Create a new stack frame (ownership will be transferred to the caller) // and fill it in. StackFrameAMD64* frame = new StackFrameAMD64(); frame->trust = StackFrame::FRAME_TRUST_SCAN; frame->context = last_frame->context; frame->context.rip = caller_rip; // The caller's %rsp is directly underneath the return address pushed by // the call. frame->context.rsp = caller_rip_address + 8; frame->context_validity = StackFrameAMD64::CONTEXT_VALID_RIP | StackFrameAMD64::CONTEXT_VALID_RSP; // Other unwinders give up if they don't have an %rbp value, so see if we // can pass some plausible value on. if (last_frame->context_validity & StackFrameAMD64::CONTEXT_VALID_RBP) { // Functions typically push their caller's %rbp immediately upon entry, // and then set %rbp to point to that. So if the callee's %rbp is // pointing to the first word below the alleged return address, presume // that the caller's %rbp is saved there. if (caller_rip_address - 8 == last_frame->context.rbp) { u_int64_t caller_rbp = 0; if (memory_->GetMemoryAtAddress(last_frame->context.rbp, &caller_rbp) && caller_rbp > caller_rip_address) { frame->context.rbp = caller_rbp; frame->context_validity |= StackFrameAMD64::CONTEXT_VALID_RBP; } } else if (last_frame->context.rbp >= caller_rip_address + 8) { // If the callee's %rbp is plausible as a value for the caller's // %rbp, presume that the callee left it unchanged. frame->context.rbp = last_frame->context.rbp; frame->context_validity |= StackFrameAMD64::CONTEXT_VALID_RBP; } } return frame; } StackFrame* StackwalkerAMD64::GetCallerFrame(const CallStack* stack) { if (!memory_ || !stack) { BPLOG(ERROR) << "Can't get caller frame without memory or stack"; return NULL; } const vector<StackFrame*> &frames = *stack->frames(); StackFrameAMD64* last_frame = static_cast<StackFrameAMD64*>(frames.back()); scoped_ptr<StackFrameAMD64> new_frame; // If we have DWARF CFI information, use it. scoped_ptr<CFIFrameInfo> cfi_frame_info( frame_symbolizer_->FindCFIFrameInfo(last_frame)); if (cfi_frame_info.get()) new_frame.reset(GetCallerByCFIFrameInfo(frames, cfi_frame_info.get())); // If CFI failed, or there wasn't CFI available, fall back // to stack scanning. if (!new_frame.get()) { new_frame.reset(GetCallerByStackScan(frames)); } // If nothing worked, tell the caller. if (!new_frame.get()) return NULL; // Treat an instruction address of 0 as end-of-stack. if (new_frame->context.rip == 0) return NULL; // If the new stack pointer is at a lower address than the old, then // that's clearly incorrect. Treat this as end-of-stack to enforce // progress and avoid infinite loops. if (new_frame->context.rsp <= last_frame->context.rsp) return NULL; // new_frame->context.rip is the return address, which is one instruction // past the CALL that caused us to arrive at the callee. Set // new_frame->instruction to one less than that. This won't reference the // beginning of the CALL instruction, but it's guaranteed to be within // the CALL, which is sufficient to get the source line information to // match up with the line that contains a function call. Callers that // require the exact return address value may access the context.rip // field of StackFrameAMD64. new_frame->instruction = new_frame->context.rip - 1; return new_frame.release(); } } // namespace google_breakpad
[ "wuzili1234@gmail.com" ]
wuzili1234@gmail.com
071179dcc13fa3cc32aa68486eaed86d12070d4c
abbcbf44964d4557cfcab0fe1056bdcca4e7e60a
/VectorList/src/WordMap.cpp
063f7b812628b5e8dad177bf1d679291e3bdfb38
[]
no_license
charit93/Data-Structures-CMPE-180-92
b4fdc6cda32330b7d199d1b7f52dcf9517fbcdc8
8937f71a1e6df21a4e66c18702f5404591c1155a
refs/heads/master
2020-03-11T12:11:10.374829
2018-09-04T18:31:58
2018-09-04T18:31:58
129,990,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,357
cpp
#include <map> #include <string> #include<iostream> #include "WordMap.h" using namespace std; WordMap::WordMap() {} WordMap::~WordMap() {} map<string, Word>& WordMap::get_data() { return data; } int WordMap::get_count(const string text) const { /***** Complete this function. *****/ map<string, Word>::const_iterator it = data.find(text); return it != data.end() ? (it->second).get_count() : -1; } void WordMap::insert(const string text) { /***** Complete this function. *****/ steady_clock::time_point start = steady_clock::now(); // start timer map<string, Word>::iterator it = data.find(text); // word in the map if (it == data.end()) // Entering the word { data[text] = Word(text); } else { (it->second).increment_count(); // increment word count } steady_clock::time_point end = steady_clock::now(); // count end time increment_elapsed_time(start,end); // total elapsed time } map<string, Word>::iterator WordMap::search(const string text) { /***** Complete this function. *****/ steady_clock::time_point start = steady_clock().now(); // start timer map<string, Word>::iterator it=data.find(text); // word in the map steady_clock::time_point end_time = steady_clock().now(); // count end time increment_elapsed_time(start,end_time); // total elapsed time return it; } int WordMap::size(){ return data.size(); }
[ "charitupadhyay@gmail.com" ]
charitupadhyay@gmail.com
6130b31e7e0ec9ae51a0c5e9d6e4b1a22320039d
02b715831737eb94df84910677f6917aa04fa312
/EIN-SOF/DOMASNO/DOMASNO C++/OBLIK/troDimenzionalni.cpp
38b9fa535221b9cd5524d2c86d62d31fe3906053
[]
no_license
DoozyX/EIN-SOF
05b433e178fbda6fb63e0d61387684158913de1d
5de0bd42906f9878557d489b617824fe80c4b23b
refs/heads/master
2021-01-01T18:25:14.240394
2017-11-18T12:54:16
2017-11-18T12:54:16
98,330,930
0
0
null
null
null
null
UTF-8
C++
false
false
609
cpp
//programa troDimenzionalni.cpp //deviniranje na metodi #include <iostream> using std::cout; #include "troDimenzionalni.h" TroDimenzionalni::TroDimenzionalni(double x,double y,double z):DvoDimenzionalni(x,y) { h=z; } double TroDimenzionalni::presmetajPlostina() { double pom,pom1; pom=DvoDimenzionalni::presmetajPlostina(); pom1=2*pom+getA()*2*h+getB()*2*h; return pom1; } double TroDimenzionalni::presmetajVolumen() { double pom; pom=DvoDimenzionalni::presmetajPlostina()*h; return pom; } void TroDimenzionalni::print() { DvoDimenzionalni::print(); cout<<"Visinata e: "<<h<<"\n"; }
[ "slobodan.kletnikov@gmail.com" ]
slobodan.kletnikov@gmail.com
472034a1fe62ab43a454a0ffc33e33345712f17f
0ede806372e66372edabd130593e6660c222f21f
/hw6/ref.cpp
33f67d40600b338569e69b32147d9cb28241f471
[]
no_license
elijahverdoorn/SD-Spring-15
ee47022dbe30a595efe649fcfd19a52406aedb10
7b9afb05d874dc939ecd686905754c5dd54a5d81
refs/heads/master
2016-09-05T17:03:05.423101
2015-09-15T15:16:43
2015-09-15T15:16:43
34,302,490
1
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
#include <iostream> using namespace std; void f1(int& x) { x++; } main() { int x = 2; cout << x << endl; f1(x); cout << x << endl; return 0; }
[ "elijahverdoorn@gmail.com" ]
elijahverdoorn@gmail.com
225f35c55c3268891fa6a2f2b03b9e6fb1257ca4
148db5d8bc334989e589726f969a9a51f823a8ef
/frontends/parsers/p4/p4AnnotationLexer.hpp
7814b046486c6ed9998c3717aca4d14613895183
[ "Apache-2.0" ]
permissive
P4-Research/p4c
95bc225e80cb512cc419c15ad728c1e87c26e424
e1b2239cd8249d9069c4125ccb95683975cd3c99
refs/heads/master
2021-06-25T01:28:29.268496
2020-12-16T00:57:02
2020-12-16T00:57:02
179,700,661
6
2
Apache-2.0
2020-02-20T12:29:07
2019-04-05T14:47:06
C++
UTF-8
C++
false
false
2,245
hpp
#ifndef FRONTENDS_P4_P4ANNOTATIONLEXER_H_ #define FRONTENDS_P4_P4ANNOTATIONLEXER_H_ #include "frontends/parsers/p4/abstractP4Lexer.hpp" #include "frontends/parsers/p4/p4parser.hpp" namespace P4 { class P4AnnotationLexer : public AbstractP4Lexer { public: enum Type { // Lists EXPRESSION_LIST = P4Parser::token_type::TOK_START_EXPRESSION_LIST, KV_LIST = P4Parser::token_type::TOK_START_KV_LIST, INTEGER_LIST = P4Parser::token_type::TOK_START_INTEGER_LIST, INTEGER_OR_STRING_LITERAL_LIST = P4Parser::token_type::TOK_START_INTEGER_OR_STRING_LITERAL_LIST, STRING_LITERAL_LIST = P4Parser::token_type::TOK_START_STRING_LITERAL_LIST, // Singletons EXPRESSION = P4Parser::token_type::TOK_START_EXPRESSION, INTEGER = P4Parser::token_type::TOK_START_INTEGER, INTEGER_OR_STRING_LITERAL = P4Parser::token_type::TOK_START_INTEGER_OR_STRING_LITERAL, STRING_LITERAL = P4Parser::token_type::TOK_START_STRING_LITERAL, // Pairs EXPRESSION_PAIR = P4Parser::token_type::TOK_START_EXPRESSION_PAIR, INTEGER_PAIR = P4Parser::token_type::TOK_START_INTEGER_PAIR, STRING_LITERAL_PAIR = P4Parser::token_type::TOK_START_STRING_LITERAL_PAIR, // Triples EXPRESSION_TRIPLE = P4Parser::token_type::TOK_START_EXPRESSION_TRIPLE, INTEGER_TRIPLE = P4Parser::token_type::TOK_START_INTEGER_TRIPLE, STRING_LITERAL_TRIPLE = P4Parser::token_type::TOK_START_STRING_LITERAL_TRIPLE, // P4Runtime annotations P4RT_TRANSLATION_ANNOTATION = P4Parser::token_type::TOK_START_P4RT_TRANSLATION_ANNOTATION, }; private: Type type; const IR::Vector<IR::AnnotationToken>& body; bool needStart; IR::Vector<IR::AnnotationToken>::const_iterator it; const Util::SourceInfo& srcInfo; public: P4AnnotationLexer(Type type, const Util::SourceInfo& srcInfo, const IR::Vector<IR::AnnotationToken>& body) : type(type), body(body), needStart(true), it(this->body.begin()), srcInfo(srcInfo) { } Token yylex(P4::P4ParserDriver& driver); }; } // namespace P4 #endif /* FRONTENDS_P4_P4ANNOTATIONLEXER_H_ */
[ "noreply@github.com" ]
P4-Research.noreply@github.com
d6c3b8ca64db853e8a526ca38aa0e3336dc7678c
438e7e41206157a38e4318450a91e4cc1a5af564
/TP3/Ej3/main.cpp
e42e3d089f1c59814ae057e1f1a5a93e8fe476d5
[]
no_license
gtessi/PDI2014-FICH
f793d8af457a673432ff3c79d1056122de550a00
dd9d4e2df2ff70a711a5cf747875abc3134f1e8b
refs/heads/master
2020-03-27T05:51:19.198022
2018-08-25T02:51:25
2018-08-25T02:51:25
146,057,455
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,377
cpp
#include <iostream> #include "CImg.h" using namespace cimg_library; using namespace std; // Cuenta la cantidad de unos en el patron unsigned int cuentaUnos(unsigned int n,double patron[]){ unsigned int total=0; unsigned int n2=n*n; for(unsigned int i=0;i<n2;i++) if(patron[i]==1.0) total++; // Devuelve la cantidad de unos en el patron return total; } // Acota el rango CImg<float> clipping(CImg<float> img){ CImg<float> salida(img); // Aplica el clipping cimg_forXY(salida,i,j){ if (salida(i,j)>255) salida(i,j)=255; else if(salida(i,j)<0) salida(i,j)=0; } // Devuelve la imagen acotada return salida; } // Devuelve una imagen convolucionada con una matriz de NxN, a partir de un patron CImg<float> obtenerFiltro(CImg<unsigned char> img,unsigned int n,double patron[],bool acotar=false){ CImg<float> mascara(n,n), salida; // Construye la mascara a partir del patron cimg_forXY(mascara,i,j){ mascara(i,j)=patron[i+j*n]; } // Aplica el factor de escala a la imagen unsigned int factor_escala=cuentaUnos(n,patron); mascara/=factor_escala; // Convolucion entre la imagen y la mascara salida=img.get_convolve(mascara); // Acota el rango (clipping) if(acotar) salida=clipping(salida); // Normaliza salida.normalize(0,255); // Devuelve la imagen filtrada return salida; } CImg<float> gaussian_mask(unsigned int n,float sigma){ CImg<float> mascara(n,n), matriz_covarianza(2,2); // ??? // Vector color const char color[]={1}; // Crea la matriz de covarianza matriz_covarianza(0,0)=sigma; matriz_covarianza(1,1)=sigma; // Calcula la distribucion gaussiana mascara.draw_gaussian(n/2,n/2,matriz_covarianza,color); // Normaliza mascara.normalize(0,255); // Devuelve la mascara return mascara; } int main(int argc, char** argv) { // Carga la imagen en filename const char* filename = cimg_option("-i","hubble.tif","Image file\n"); CImg<unsigned char> hubble(filename); // Item 1 // Filtrado promedio CImg<float> filtrado_promedio, mascara_gaussiana, gaussiana; // Patrones double patron3[]={ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; double patron5[]={ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; double patron32[]={ 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0 }; //filtrado_promedio=obtenerFiltro(hubble,3,patron3,false); filtrado_promedio=obtenerFiltro(hubble,5,patron5,false); //filtrado_promedio=obtenerFiltro(hubble,3,patron32,false); filtrado_promedio.display(); // Aplica la mascara gaussiana // Mas tamaño, mas borroso // El desvio no afecta mucho cuando el tamaño es pequeño mascara_gaussiana=gaussian_mask(11,3); gaussiana=hubble.get_convolve(mascara_gaussiana); gaussiana/=gaussiana.sum(); gaussiana.display(); // Item 2 // Deteccion de objetos de mayor tamaño aplicando un filtrado promedio filtrado_promedio.threshold(150); filtrado_promedio.display(); // No aparecen objetos con el filtrado gaussiano aplicado, hay que revisar // los parametros y verificar si aparecen los objetos grandes cout<<"*********************************************************"<<endl<<endl; return 0; }
[ "noreply@github.com" ]
gtessi.noreply@github.com
9bb2695c911ba2c39b5ab4b73de7d9ff066d43f7
7e00a527a91a4bd2a60c7f1f0ae339730daa7ad1
/src/Statistics.cpp
c5470a7351ab753d606a98975d7272c7a0b3416e
[]
no_license
tzavellas/ObserverPattern
4a12a99c8c2a0b2abc4f5f01580bc9dda699fc40
6d95db6c89812062500ff62ccd6ff918d51835c9
refs/heads/master
2023-01-20T18:42:08.244843
2020-11-29T17:16:22
2020-11-29T17:16:22
316,933,637
0
0
null
null
null
null
UTF-8
C++
false
false
738
cpp
#include "Statistics.hpp" #include <algorithm> Statistics::Statistics(const float& value) : m_MinValue{value}, m_MaxValue{value}, m_ValueSum{value}, m_Count{ (value != 0.0) ? 1u : 0u} { // nothing to do } void Statistics::update(const float& newValue) { if (m_Count > 0) { m_MinValue = std::min(m_MinValue, newValue); m_MaxValue = std::max(m_MaxValue, newValue); } else { m_MinValue = newValue; m_MaxValue = newValue; } m_ValueSum += newValue; m_Count++; } float Statistics::getMin() const { return m_MinValue; } float Statistics::getMax() const { return m_MaxValue; } float Statistics::getAverage() const { return m_ValueSum/m_Count; }
[ "tzavellas@gmail.com" ]
tzavellas@gmail.com
faee043efffcd28847ea5d433bdd91e6452d1edb
0233477eeb6d785b816ee017cf670e2830bdd209
/SDK/SoT_BP_ipg_hair_05_Desc_classes.hpp
d63a95a7ae7acdde9d10a31695bf281f88394ce5
[]
no_license
compy-art/SoT-SDK
a568d346de3771734d72463fc9ad159c1e1ad41f
6eb86840a2147c657dcd7cff9af58b382e72c82a
refs/heads/master
2020-04-17T02:33:02.207435
2019-01-13T20:55:42
2019-01-13T20:55:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
702
hpp
#pragma once // Sea of Thieves (1.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_ipg_hair_05_Desc_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_ipg_hair_05_Desc.BP_ipg_hair_05_Desc_C // 0x0000 (0x00E0 - 0x00E0) class UBP_ipg_hair_05_Desc_C : public UClothingDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>("BlueprintGeneratedClass BP_ipg_hair_05_Desc.BP_ipg_hair_05_Desc_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
f960a225f0bf911fb98ca368ad195675a34051e5
152c8ed80987ac2de10fe03fe6af283f1430d0be
/Classes/Tool.h
75c5a069c124c72439d35fc22543b2ad190ade63
[]
no_license
aababy/Begins_New
2bae369a90f4d4e9f5bba1d2f3669a0eef22d4c5
9c3e09c5d38667c2fdc35f4ccf2aa3bbfd7ea627
refs/heads/master
2021-01-01T15:55:15.575484
2014-12-22T03:58:00
2014-12-22T03:58:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
851
h
#pragma once #include "IncludeForHeader.h" #include "ui/UICheckBox.h" Button * initButton(int iTag, Widget* root, Widget::ccWidgetTouchCallback callback); ImageView * initImageView(int iTag, Widget* root); CheckBox * initCheckBox(int iTag, Widget* root, const CheckBox::ccCheckBoxCallback& callback); Layout * initRoot(const std::string& filename, Layer *layer); Layout * initRootForCell(const std::string& filename, Layer *layer); Layout * initLayout(int iTag, Widget* root, Widget::ccWidgetTouchCallback callback); string itostr(int i); string getString(char *sz); Button* initUIButton(int tag, SEL_TouchEvent selector, Layout* root, Ref* target); Time getCurrentTime(); Time str2MTime(const string &str); Time str2MTimeForDB(const string &str); string getShowTime(Time &mtime); int cycleNum(bool bAdd, int iCount, int *idx);
[ "jumpchess@163.com" ]
jumpchess@163.com
a903ab1beccc7bef5a1dab90c14efc18e0a35495
a712987d2ef30425eda8af84b3132d25d27da46a
/src/network/client.h
fb13e1d122192f9deaaf09f3302c1b39171c774f
[ "MIT" ]
permissive
ziloka/cpptris
ee85210b951285c5f8b37b0b78edcda6300a2ce6
281c478add5a8b2c048754f1264c4b70311c4864
refs/heads/master
2023-03-19T05:50:35.786618
2018-10-30T13:06:02
2018-10-30T13:06:02
532,646,997
1
0
null
2022-09-04T20:11:35
2022-09-04T20:11:34
null
UTF-8
C++
false
false
1,174
h
#ifndef CLIENT_H #define CLIENT_H #include <string> #include <SFML/Network.hpp> #include "../piece.h" class Client { private: sf::TcpSocket socket; bool connected = false; std::string address; char username[25]; int id; std::string * users = new std::string[4]; int userWorlds[4][10*20]; int addBlockCount = 0; int blockSender = 0; float userPiecePosition[4][2]; int userPiece[4][4*4]; bool gameOver[4]; bool gameStarted = false; bool gameFinished = false; int gameWinner = 0; void connect(); void send(sf::Packet packet); public: Client(std::string name, std::string address); void resetState(); void updateState(int (&world)[10][20]); void updatePieceState(Piece* piece); void sendGameOver(); void sendBlock(); bool isConnected(); std::string getName(int i); bool isGameStarted(); int* getUserWorld(int usr); float * getPiecePosition(int usr); int * getPiece(int usr); bool getGameOver(int usr); bool isGameFinished(); int getGameWinner(); bool addBlock(); string getBlockSender(); int getId(); }; #endif //CLIENT_H
[ "me@evgiz.net" ]
me@evgiz.net
ff30ab1177f96472963069ec3d2efaef5b5b6bd1
091afb7001e86146209397ea362da70ffd63a916
/inst/include/boost/simd/constant/include/constants/five.hpp
a1ad45fe0bd224bc95be40398253f8f19297a570
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
254
hpp
#ifndef BOOST_SIMD_CONSTANT_INCLUDE_CONSTANTS_FIVE_HPP_INCLUDED #define BOOST_SIMD_CONSTANT_INCLUDE_CONSTANTS_FIVE_HPP_INCLUDED #include <boost/simd/constant/constants/five.hpp> #include <boost/simd/constant/constants/simd/vmx/altivec/five.hpp> #endif
[ "kevinushey@gmail.com" ]
kevinushey@gmail.com
e63ed43c36b42ab2c0fdbe663d81de565f6a568d
ee5d08a8b806b9a5c3452664b9ec6c8776b8225e
/recording/src/irobot_create/nodes/odometry_rosbag.cpp
49651c905fccd794964b8fc71422984303fe4ca6
[ "BSD-3-Clause" ]
permissive
sbrodeur/CREATE-dataset
cff764617883f9186c607482f61cf85c4d4007e6
473e0555e81516139b6e70362ca0025af100158b
refs/heads/master
2021-05-05T02:25:24.459839
2018-01-31T20:41:50
2018-01-31T20:41:50
119,738,964
0
0
null
null
null
null
UTF-8
C++
false
false
10,428
cpp
/****************************************************************************** * * Copyright (c) 2016, Simon Brodeur * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the NECOTIS research group nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <rosbag/bag.h> #include <rosbag/view.h> #include <iostream> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/exact_time.h> #include <message_filters/sync_policies/approximate_time.h> #include <message_filters/time_synchronizer.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/JointState.h> #include <nav_msgs/Odometry.h> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> #include <tf2_msgs/TFMessage.h> using namespace std; #define AXLE_LEN 0.258 #define WHEEL_DIAMETER 0.078 // NOTE: adapted from http://wiki.ros.org/rosbag/Cookbook /** * Inherits from message_filters::SimpleFilter<M> * to use protected signalMessage function */ template <class M> class BagSubscriber : public message_filters::SimpleFilter<M> { public: void newMessage(const boost::shared_ptr<M const> &msg) { message_filters::SimpleFilter<M>::signalMessage(msg); } }; class OdometryRosbag { typedef sensor_msgs::Imu ImuMsg; typedef sensor_msgs::JointState JointMsg; typedef BagSubscriber<ImuMsg> ImuSubscriber; typedef BagSubscriber<JointMsg> JointSubscriber; typedef message_filters::sync_policies::ApproximateTime<ImuMsg, JointMsg> SyncPolicy; typedef message_filters::Synchronizer<SyncPolicy> Synchronizer; public: OdometryRosbag(rosbag::Bag* bag, const std::string& output_odom_topic, const bool& publish_tf): initialized_(false){ bag_ = bag; nb_msg_generated_ = 0; nb_tf_msg_generated_ = 0; output_odom_topic_ = output_odom_topic; publish_tf_ = publish_tf; // Set frame_id's const std::string str_base_baselink("base_link"); tf_odom_.header.frame_id = "odom"; tf_odom_.child_frame_id = str_base_baselink; odom_msg_.header.frame_id = "odom"; odom_msg_.child_frame_id = str_base_baselink; // Set up fake subscribers to capture Imu and MagneticField messages imu_sub_.reset(new ImuSubscriber()); joint_sub_.reset(new JointSubscriber()); sync_.reset(new Synchronizer( SyncPolicy(50), *imu_sub_, *joint_sub_)); sync_->registerCallback(boost::bind(&OdometryRosbag::imuJointCallback, this, _1, _2)); } virtual ~OdometryRosbag(){ // TODO: fix the following error at termination: // terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::lock_error> >' // what(): boost: mutex lock failed in pthread_mutex_lock: Invalid argument // Aborted // // see: https://github.com/ros/ros_comm/issues/318 // http://answers.ros.org/question/143756/rostimer-leads-to-boostlock_error-at-process-cleanup/ imu_sub_.reset(); joint_sub_.reset(); sync_.reset(); } void addImuMessage(sensor_msgs::Imu::ConstPtr imu){ imu_sub_->newMessage(imu); } void addJointMessage(sensor_msgs::JointState::ConstPtr joint){ joint_sub_->newMessage(joint); } private: rosbag::Bag* bag_; std::string output_odom_topic_; nav_msgs::Odometry odom_msg_; geometry_msgs::TransformStamped tf_odom_; bool initialized_; ros::Time last_time_; bool publish_tf_; int nb_msg_generated_; int nb_tf_msg_generated_; double x_; double y_; double lastLeftWheelDist_; double lastRightWheelDist_; boost::shared_ptr<Synchronizer> sync_; boost::shared_ptr<ImuSubscriber> imu_sub_; boost::shared_ptr<JointSubscriber> joint_sub_; // **** member functions void imuJointCallback(const ImuMsg::ConstPtr& imu_msg, const JointMsg::ConstPtr& joint_state_msg){ ros::Time time = imu_msg->header.stamp; double wheelRadius = WHEEL_DIAMETER / 2.0; double leftWheelDist = joint_state_msg->position[0] * wheelRadius; double rightWheelDist = joint_state_msg->position[1] * wheelRadius; if (!initialized_){ x_ = 0.0; y_ = 0.0; lastLeftWheelDist_ = leftWheelDist; lastRightWheelDist_ = rightWheelDist; last_time_ = time; initialized_ = true; } double deltaLeftWheelDist = leftWheelDist - lastLeftWheelDist_; double deltaRightWheelDist = rightWheelDist - lastRightWheelDist_; // NOTE: assume we are moving straight (true if dt is small enough) double roll, pitch, yaw; tf::Quaternion q; quaternionMsgToTF(imu_msg->orientation, q); tf::Matrix3x3 m(q); m.getRPY(roll, pitch, yaw); double deltaDist = (deltaLeftWheelDist + deltaRightWheelDist) / 2.0; x_ += deltaDist * cos(yaw); y_ += deltaDist * sin(yaw); // Populate position info // NOTE: propagate timestamp from the message odom_msg_.header.stamp = time; odom_msg_.pose.pose.position.x = x_; odom_msg_.pose.pose.position.y = y_; odom_msg_.pose.pose.orientation = imu_msg->orientation; // Populate velocity info (in the frame of the robot) double velocitiyForward = (joint_state_msg->velocity[0] + joint_state_msg->velocity[1]) * wheelRadius / 2.0; odom_msg_.twist.twist.linear.x = velocitiyForward; odom_msg_.twist.twist.linear.y = 0.0; odom_msg_.twist.twist.angular = imu_msg->angular_velocity; if (publish_tf_){ // NOTE: propagate timestamp from the message tf_odom_.header.stamp = time; tf_odom_.transform.translation.x = x_; tf_odom_.transform.translation.y = y_; tf_odom_.transform.rotation = imu_msg->orientation; // Write tf message to rosbag //tf::tfMessage tf_msg; tf2_msgs::TFMessage tf_msg; tf_msg.transforms.push_back(tf_odom_); bag_->write("/tf", tf_odom_.header.stamp, tf_msg); nb_tf_msg_generated_++; if (nb_tf_msg_generated_ % 1000 == 0){ printf("Number of tf messages generated: %d \n", nb_tf_msg_generated_); } } // Write msg in rosbag here bag_->write(output_odom_topic_, odom_msg_.header.stamp, odom_msg_); nb_msg_generated_++; if (nb_msg_generated_ % 1000 == 0){ printf("Number of odometry messages generated: %d \n", nb_msg_generated_); } last_time_ = time; lastLeftWheelDist_ = leftWheelDist; lastRightWheelDist_ = rightWheelDist; } }; int main(int argc, char **argv){ ros::Time::init(); std::string input_rosbag = "input.bag"; std::string output_rosbag = "output.bag"; std::string output_odom_topic = "/irobot_create/odom"; std::string input_imu_topic = "/imu/data"; std::string input_joint_topic = "/irobot_create/joints"; bool publish_tf = false; namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "describe arguments") ("output,o", po::value(&output_rosbag), "set output rosbag file") ("input,i", po::value(&input_rosbag), "set input rosbag file") ("output-odom-topic,d", po::value(&output_odom_topic), "set topic of the output Odometry messages") ("input-imu-topic,m", po::value(&input_imu_topic), "set topic of the input Imu messages") ("input-joint-topic,j", po::value(&input_joint_topic), "set topic of the input JointState messages") ("publish-tf,t", po::bool_switch(&publish_tf), "set to publish tf messages"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } rosbag::Bag output(output_rosbag, rosbag::bagmode::Write); rosbag::Bag input(input_rosbag, rosbag::bagmode::Read); OdometryRosbag odometry(&output, output_odom_topic, publish_tf); int nb_imu_msg_processed = 0; int nb_joint_msg_processed = 0; int nb_total_msg_processed = 0; rosbag::View view(input); BOOST_FOREACH(rosbag::MessageInstance const m, view) { // Detect Imu messages from the given topic if (m.getTopic() == input_imu_topic || ("/" + m.getTopic() == input_imu_topic)) { sensor_msgs::Imu::ConstPtr imu = m.instantiate<sensor_msgs::Imu>(); if (imu != NULL){ odometry.addImuMessage(imu); nb_imu_msg_processed++; } } // Detect JointState messages from the given topic if (m.getTopic() == input_joint_topic || ("/" + m.getTopic() == input_joint_topic)) { sensor_msgs::JointState::ConstPtr mag = m.instantiate<sensor_msgs::JointState>(); if (mag != NULL){ odometry.addJointMessage(mag); nb_joint_msg_processed++; } } if (m.getTopic() != output_odom_topic){ // Write every message to output bag output.write(m.getTopic(), m.getTime(), m, m.getConnectionHeader()); nb_total_msg_processed++; } if (nb_total_msg_processed % 1000 == 0){ printf("Number of imu messages processed: %d (total %d)\n", nb_imu_msg_processed, nb_total_msg_processed); printf("Number of joint messages processed: %d (total %d)\n", nb_joint_msg_processed, nb_total_msg_processed); } } output.close(); input.close(); return 0; }
[ "Simon Brodeur@USherbrooke.ca" ]
Simon Brodeur@USherbrooke.ca
f6dbc7835f49e3975e7d47d4ff8d4df76bb2d393
490ec0d2c4d0ae5d54095c71e90d99bbc87049b8
/ECE551-cpp/mp_miniproject/My_project/source/parsing.cpp
f069043794810b4bcd7630229a24fde35f4e4d7b
[ "MIT" ]
permissive
sicongzhao/cht_Duke_courses
b8c1f03c2fda05b5e73552e6bdb7f3c323810620
d889e85e677f419c67c12e78143f3e8143457944
refs/heads/master
2022-01-06T23:18:36.962017
2019-06-12T20:33:33
2019-06-12T20:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,592
cpp
#define MAXFLAG 1 #define MINFLAG -1 #include "parsing.h" #include "helpers.h" /************************************************* Function: parsing Description: to wrap-up the parsers for each step Calls: Called By: numeric.cpp/main Input: 1.read-in file content 2.mapped-function pairs 3.all valid commands. Return: void Others: *************************************************/ std::string check_command(std::string &input, const std::vector<std::string> &command_list) { unsigned i = 0; std::string::iterator it = input.begin(); std::string::iterator it_first = it; while(i < command_list.size()) { if(input.find(command_list[i]) != std::string::npos) { // to check if there is something like "abcdefinexyz and eliminate it" std::string temp_define_string = get_next_valid_str(it); // remove spaces delete_spaces_and_tabs_on_head_and_tail(temp_define_string); if(temp_define_string.compare(command_list[i]) != 0) { std::stringstream err_msg1; err_msg1 << "Error: In input: >> " << input << " << have strange " << command_list[i] << "!"; throw err_msg1.str(); } std::cout << "Try to define input: >> " << input << " <<." << std::endl; input.erase(it_first, it); return command_list[i]; } i++; } if(i == command_list.size()) { std::stringstream err_msg2; err_msg2 << "Error: In input: >> " << input << " << command not found!" << std::endl; throw err_msg2.str(); } return NULL; } void parsing(const std::string &input, std::map<std::string, function*> &function_map, const std::vector<std::string> &command_list) { std::string temp_compare; std::string temp_input; temp_input = input; try { temp_compare = check_command(temp_input, command_list); } catch(std::string err_msg) { std::cerr << err_msg << std::endl; return; } std::cout << "Command is: >> " << temp_compare << " <<." << std::endl; if(!temp_compare.compare(0, 6, "define")) { parsing_define(temp_input, function_map); } else if(!temp_compare.compare(0, 8, "evaluate")) { parsing_eval(temp_input, function_map); } else if(!temp_compare.compare(0, 6, "numint")) { parsing_numint(temp_input, function_map); } else if(!temp_compare.compare(0, 5, "mcint")) { parsing_mcint(temp_input, function_map); } else if(!temp_compare.compare(0, 3, "max")) { parsing_gradient(temp_input, function_map, MAXFLAG); } else if(!temp_compare.compare(0, 3, "min")) { parsing_gradient(temp_input, function_map, MINFLAG); } else { std::cerr << "Unknown command: can only take in 6 pre-defined types of commands." << std::endl; } }
[ "cht@bupt.edu.cn" ]
cht@bupt.edu.cn
74c55dfce4be27254ac35cafceb951c9708346f8
f99c0194278639456604ebf76443b65bf1c6ed04
/paymentchannel/include/paymentchannel/Commitment.hpp
e1d7c563cfe490394a46f0cc2b700c4d871b15fa
[]
no_license
RdeWilde/JoyStream
e4ed42ff61af1f348cb49469caa8e30ccf3f8a52
95c2b6fc50251fbe4730b19d47c18bec86e18bf4
refs/heads/master
2021-06-11T20:26:46.682624
2016-05-10T08:27:05
2016-05-10T08:27:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,636
hpp
/** * Copyright (C) JoyStream - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Bedeho Mender <bedeho.mender@gmail.com>, August 15 2015 */ #ifndef PAYMENTCHANNEL_COMMITMENT_HPP #define PAYMENTCHANNEL_COMMITMENT_HPP #include <common/PublicKey.hpp> namespace Coin { class P2SHScriptPubKey; class MultisigScriptPubKey; class TxOut; } class Commitment { public: // Default constructor Commitment(); // Constructor based on members Commitment(int64_t value, const Coin::PublicKey & firstPk, const Coin::PublicKey & secondPk); // Copy constructor Commitment(const Commitment& o); // Assignement operator Commitment & operator=(const Commitment & o); // p2sh 2of2 multisig scriptPubKey controlling contract output Coin::P2SHScriptPubKey contractOutputScriptPubKey() const; // Generates contract output Coin::TxOut contractOutput() const; // 2o2 multisig scriptpubkey Coin::MultisigScriptPubKey redeemScript() const; // Getters and setters int64_t value() const; void setValue(int64_t value); Coin::PublicKey firstPk() const; void setFirstPk(const Coin::PublicKey & firstPk); Coin::PublicKey secondPk() const; void setSecondPk(const Coin::PublicKey & secondPk); private: // Funds allocated to output int64_t _value; // First public key controlling multisig output Coin::PublicKey _firstPk; // Second public key controlling multisig output Coin::PublicKey _secondPk; }; #endif // PAYMENTCHANNEL_COMMITMENT_HPP
[ "bedeho.mender@gmail.com" ]
bedeho.mender@gmail.com
f3f67e5db33e87b03b0ce3aa1ba033ffa5db70bc
90efdfa1f56e2082283e510c7aa9a77ceab8ce18
/template/src/TemplateGame.h
8c426edcee6f05323707188d4f260324a400fbe1
[]
no_license
aurodev/GPlay3D
451e2863d6ac3222762672d358eecd494d9cc272
ad6b88dd22688e2b6e6e2fa02779daa0b5545592
refs/heads/master
2020-07-13T04:28:30.234238
2018-06-26T06:48:20
2018-06-26T06:48:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
877
h
#ifndef TemplateGame_H_ #define TemplateGame_H_ #include "gplay3d.h" using namespace gameplay; /** * Main game class. */ class TemplateGame: public Game { public: /** * Constructor. */ TemplateGame(); /** * @see Game::keyEvent */ void keyEvent(Keyboard::KeyEvent evt, int key); /** * @see Game::touchEvent */ void touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex); protected: /** * @see Game::initialize */ void initialize(); /** * @see Game::finalize */ void finalize(); /** * @see Game::update */ void update(float elapsedTime); /** * @see Game::render */ void render(float elapsedTime); private: /** * Draws the scene each frame. */ bool drawScene(Node* node); Scene* _scene; }; #endif
[ "fredakilla@gmail.com" ]
fredakilla@gmail.com
9ce6b3907dcfec4a8f95f860990c41218de9b1e2
7f940f1a54ab400d98d0291248427114acada9ee
/concepts/threads/futures.cpp
9791c67166ebc5f8496a150451b958ad77788c3c
[]
no_license
anirudhaps/Cplusplus
7d01e5deb1e0d4dda37257cd8831f3a89f7049b5
ac180ffe894a39443d6bb6438fda9ff308701e00
refs/heads/master
2022-09-29T04:30:40.181243
2022-09-13T16:51:02
2022-09-13T16:51:02
86,616,344
0
0
null
null
null
null
UTF-8
C++
false
false
2,108
cpp
#include <future> #include <iostream> // needed for using 300ms as arg in sleep_for using namespace std::chrono_literals; // This is the task/callable that will be executed in a separate thread int operation(int count) { int sum{}; for (int i = 0; i < count; ++i) { sum += i; std::cout << '.'; std::this_thread::sleep_for(300ms); } std::cout << "\n"; // This sum is the shared state between this thread and main thread and this // will be available in the std::future as result when this task returns. return sum; } int main() { // Because the callable operation returns an int, the template type arg in the // std::future<> should be int. Here, 10 will be the argument passed to // operation(). // It seems the std::async is by default using std::launch::async as lanch // policy. We can explicitly mention it as shown below: // std::future<int> result = std::async(std::launch::async, operation, 10); // To run operation() synchronously, use deferred launch policy. In this case, // operation() task will be executed when main thread tries to get the shared // state. i.e. when result.get() is invoked. This is as good as calling // operation() directly in place of result.get(). std::future<int> result = std::async(std::launch::deferred, operation, 10); // std::future<int> result = std::async(operation, 10); std::this_thread::sleep_for(1s); std::cout << "Main thread continues...\n"; if (result.valid()) { // The shared state will become available via this get() call and until this // become available, this get() call will block the main thread. // Important note: once you call get() on the future, the shared state is // destroyed and you cannot get it again. Also, the future (result here) // becomes invalid. The .valid() call is used to check if a future is valid // or not. If it is valid, then only we ar calling the get() it to get the // shared state. auto sum = result.get(); std::cout << "Sum from future: " << sum << "\n"; } return 0; }
[ "ps.anirudha@gmail.com" ]
ps.anirudha@gmail.com
34434c5c2c810bf1e750d30effd2a03e6ae7328b
d297a725b3d28ce67796552ddc7341b8793151b0
/stereo_disparity/main.cpp
bd7e88a3c99d5d426f001a2fcaa3b84d52e06787
[]
no_license
andrey-golubev/opencl-sandbox
d76a4f4391258ec302f72ae0b5ba0335de5b66ab
ef23dec4876c2365f92ce4896d7fc389ad7128b7
refs/heads/master
2020-12-19T19:02:15.420906
2020-04-15T11:11:04
2020-04-15T11:11:04
235,823,367
1
0
null
null
null
null
UTF-8
C++
false
false
3,727
cpp
#include <cstdint> #include <iostream> #include <map> #include <random> #include <opencv2/highgui.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include "common/utils.hpp" #include "stereo_disparity_cpp_inl.hpp" #include "stereo_disparity_cpp_opt_inl.hpp" #include "stereo_disparity_ocl_inl.hpp" namespace { void print_usage(const char* program_name) { PRINTLN("Usage: " + std::string(program_name) + " IMAGE_LEFT IMAGE_RIGHT [ALGO_VERSION] [MAX_DISPARITY]\n" + " ALGO_VERSION:\n 0 - C++ basic\n 1 - C++ optimized\n 2 - OpenCL"); } template<typename CharT, typename Traits = std::char_traits<CharT>> std::vector<std::basic_string<CharT>> split(const std::basic_string<CharT>& src, CharT delimiter) { std::vector<std::basic_string<CharT>> dst; std::basic_istringstream<CharT> ss_src(src); std::basic_string<CharT> tmp; while (std::getline(ss_src, tmp, delimiter)) { dst.push_back(tmp); } return dst; } enum AlgoType { CPP_BASIC = 0, CPP_OPT = 1, OCL = 2, }; std::string algo2str(int t) { switch (t) { case CPP_BASIC: return "C++ basic"; case CPP_OPT: return "C++ optimized"; case OCL: return "OpenCL"; default: throw std::runtime_error("Unknown algorithm version"); } } } // namespace // debug controls #define SHOW_WINDOW 0 #define RESIZE 0 int main(int argc, char* argv[]) { if (argc < 3 || argc > 5) { print_usage(argv[0]); return 1; } // read input image cv::Mat bgr_left = cv::imread(argv[1]); cv::Mat bgr_right = cv::imread(argv[2]); int algo_version = 0; int max_disparity = 50; // read disparity from user input if specified if (argc > 3) { if (argc >= 4) { algo_version = std::stoi(argv[3]); } if (argc == 5) { max_disparity = std::stoi(argv[4]); } } // convert to grayscale cv::Mat left; cv::Mat right; cv::cvtColor(bgr_left, left, cv::COLOR_BGR2GRAY); cv::cvtColor(bgr_right, right, cv::COLOR_BGR2GRAY); #if RESIZE const auto input_size = left.size(); constexpr double scale = 0.5; auto size = cv::Size(input_size.width * scale, input_size.height * scale); cv::resize(left, left, size); cv::resize(right, right, size); #endif // find disparity cv::Mat map; std::uint64_t musec = 0; std::size_t iters = 1; PRINTLN("Running " + algo2str(algo_version) + " version"); switch (algo_version) { case CPP_BASIC: { musec = measure( iters, [&]() { map = stereo_cpp_base::stereo_compute_disparity(left, right, max_disparity); }, false); break; } case CPP_OPT: { musec = measure( iters, [&]() { map = stereo_cpp_opt::stereo_compute_disparity(left, right, max_disparity); }, false); break; } case OCL: { musec = measure( iters, [&]() { map = stereo_ocl_base::stereo_compute_disparity(left, right, max_disparity); }, false); break; } default: throw std::runtime_error("Unknown algorithm version"); } OUT << "Total time: " << (double(musec) / 1000 / 1000) << " sec" << std::endl; OUT << "Avg time: " << (double(musec) / iters) / 1000 / 1000 << " sec" << std::endl; #if SHOW_WINDOW // show disparity map cv::String win_name("Disparity Map"); cv::namedWindow(win_name, cv::WINDOW_NORMAL | cv::WINDOW_KEEPRATIO); cv::resizeWindow(win_name, cv::Size(640 * 2, 480 * 2)); cv::imshow(win_name, map); while (cv::waitKey(1) != 27) { }; #endif return 0; }
[ "andpgolubev@gmail.com" ]
andpgolubev@gmail.com
dff29843ca798cef5c05755a5ffe7bf01763b79b
0509e367ee369133f0c57f2cbd6cb6fd959da1d5
/chapter7/rei7.3_1.cpp
da2190f58aff74d78efa2500b01187864305d86f
[]
no_license
Hiroaki-K4/cpp_learn
5a1e6916d504027c18c64a16c353ee72429ed383
69d38f317f9c144b4e092361936d61b62d3bed3b
refs/heads/main
2023-02-25T12:40:56.497944
2021-01-30T13:27:00
2021-01-30T13:27:00
317,693,373
0
0
null
null
null
null
UTF-8
C++
false
false
551
cpp
#include <iostream> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> using namespace std; class base { public: base() { cout << "baseクラスのコンストラクタ呼び出し" << endl; } ~base() { cout << "baseクラスのデストラクタ呼び出し" << endl; } }; class derived : public base { public: derived() { cout << "derivedクラスのコンストラクタ呼び出し" << endl; } ~derived() { cout << "derivedクラスのデストラクタ呼び出し" << endl; } }; int main() { derived o; return 0; }
[ "49no19@gmail.com" ]
49no19@gmail.com
4145b1d07620be6a4bf337206b5c03f9d5bc4913
84257c31661e43bc54de8ea33128cd4967ecf08f
/ppc_85xx/usr/include/c++/4.2.2/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.h
421ce0e9b7be5f9b275a3097407a7fcf48d98d97
[]
no_license
nateurope/eldk
9c334a64d1231364980cbd7bd021d269d7058240
8895f914d192b83ab204ca9e62b61c3ce30bb212
refs/heads/master
2022-11-15T01:29:01.991476
2020-07-10T14:31:34
2020-07-10T14:31:34
278,655,691
0
0
null
null
null
null
UTF-8
C++
false
false
1,232
h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_javax_crypto_sasl_crammd5_CramMD5AuthInfoProvider__ #define __gnu_javax_crypto_sasl_crammd5_CramMD5AuthInfoProvider__ #pragma interface #include <java/lang/Object.h> extern "Java" { namespace gnu { namespace javax { namespace crypto { namespace sasl { namespace crammd5 { class CramMD5AuthInfoProvider; class PasswordFile; } } } } } } class gnu::javax::crypto::sasl::crammd5::CramMD5AuthInfoProvider : public ::java::lang::Object { public: virtual void activate (::java::util::Map *); virtual void passivate (); virtual jboolean contains (::java::lang::String *); virtual ::java::util::Map *lookup (::java::util::Map *); virtual void update (::java::util::Map *); virtual ::java::util::Map *getConfiguration (::java::lang::String *); CramMD5AuthInfoProvider (); private: ::gnu::javax::crypto::sasl::crammd5::PasswordFile * __attribute__((aligned(__alignof__( ::java::lang::Object )))) passwordFile; public: static ::java::lang::Class class$; }; #endif /* __gnu_javax_crypto_sasl_crammd5_CramMD5AuthInfoProvider__ */
[ "Andre.Mueller@nateurope.com" ]
Andre.Mueller@nateurope.com
cc6c6bada59d68862902f283830b12380c63e91c
c36761457f62066159fdb4409f7787ee0d9b43b0
/IrisLangLibrary/src/IrisLangLibrary.cpp
73bf266b4a2a4eabeacb92ded1ad5956700e3c4f
[ "Apache-2.0" ]
permissive
RedFog/Iris-Language
d8ee855da6a748cb7a5753bc56a68b5834ce18a1
cde174f3e17b9747b7876487bfa4ab81fcfc5952
refs/heads/master
2020-04-06T06:41:21.242453
2016-03-14T16:41:55
2016-03-14T16:51:08
54,444,300
1
0
null
2016-03-22T04:08:27
2016-03-22T04:08:26
null
GB18030
C++
false
false
12,959
cpp
// IrisLangLibrary.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" #include "IrisLangLibrary.h" #include "IrisDevelopUtil.h" #include "IrisInterpreter/IrisStructure/IrisClass.h" #include "IrisInterpreter/IrisStructure/IrisModule.h" #include "IrisInterpreter.h" #include "IrisInterpreter/IrisNativeClasses/IrisInteger.h" #include "IrisInterpreter/IrisNativeClasses/IrisFloat.h" #include "IrisInterpreter/IrisNativeClasses/IrisString.h" #include "IrisInterpreter/IrisNativeClasses/IrisUniqueString.h" #include "IrisInterpreter/IrisNativeModules/IrisGC.H" #include "IrisFatalErrorHandler.h" #include <string> using namespace std; IrisDev_FatalErrorMessageFunction g_pfFatalErrorMessageFunction = nullptr; IrisDev_ExitConditionFunction g_pfExitConditionFunction = nullptr; IRISLANGLIBRARY_API bool IrisDev_CheckClass(const IrisValue & ivValue, const char* strClassName) { auto pClass = ((IrisValue&)ivValue).GetIrisObject()->GetClass(); auto& strName = pClass->GetInternClass()->GetClassName(); return strName == strClassName; } IRISLANGLIBRARY_API void IrisDev_GroanIrregularWithString(const char* strIrregularString) { IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); IrisValue ivValue = IrisDev_CreateStringInstanceByInstantValue(strIrregularString); pInterpreter->RegistIrregular(ivValue); } IRISLANGLIBRARY_API int IrisDev_GetInt(const IrisValue & ivValue) { return IrisInteger::GetIntData((IrisValue&)ivValue); } IRISLANGLIBRARY_API double IrisDev_GetFloat(const IrisValue & ivValue) { return IrisFloat::GetFloatData((IrisValue&)ivValue); } IRISLANGLIBRARY_API const char* IrisDev_GetString(const IrisValue & ivValue) { if (IrisDev_CheckClass(ivValue, "String")) { return IrisString::GetString((IrisValue&)ivValue).c_str(); } else { return IrisUniqueString::GetString((IrisValue&)ivValue).c_str(); } } IRISLANGLIBRARY_API IrisValue IrisDev_CallMethod(const IrisValue & ivObj, IIrisValues * pParameters, const char* strMethodName) { return static_cast<IrisObject*>(((IrisValue&)ivObj).GetIrisObject())->CallInstanceFunction(strMethodName, nullptr, pParameters, CallerSide::Outside); } IRISLANGLIBRARY_API IIrisClass * IrisDev_GetClass(const char* strClassPathName) { return IrisInterpreter::CurrentInterpreter()->GetIrisClass(strClassPathName)->GetExternClass(); } IRISLANGLIBRARY_API IIrisModule * IrisDev_GetModule(const char * strClassPathName) { return IrisInterpreter::CurrentInterpreter()->GetIrisModule(strClassPathName)->GetExternModule(); } IRISLANGLIBRARY_API IIrisInterface * IrisDev_GetInterface(const char * strClassPathName) { return IrisInterpreter::CurrentInterpreter()->GetIrisInterface(strClassPathName)->GetExternInterface(); } IRISLANGLIBRARY_API const IrisValue & IrisDev_Nil() { return IrisInterpreter::CurrentInterpreter()->Nil(); } IRISLANGLIBRARY_API const IrisValue & IrisDev_False() { return IrisInterpreter::CurrentInterpreter()->False(); } IRISLANGLIBRARY_API const IrisValue & IrisDev_True() { return IrisInterpreter::CurrentInterpreter()->True(); } IRISLANGLIBRARY_API bool IrisDev_RegistClass(const char * szPath, IIrisClass * pClass) { return IrisInterpreter::CurrentInterpreter()->RegistClass(szPath, pClass); } IRISLANGLIBRARY_API bool IrisDev_RegistModule(const char * szPath, IIrisModule * pModule) { return IrisInterpreter::CurrentInterpreter()->RegistModule(szPath, pModule); } IRISLANGLIBRARY_API bool IrisDev_RegistInterface(const char * szPath, IIrisInterface * pInterface) { return IrisInterpreter::CurrentInterpreter()->RegistInterface(szPath, pInterface); } IRISLANGLIBRARY_API void IrisDev_AddInstanceMethod(IIrisClass * pClass, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter) { pClass->GetInternClass()->AddInstanceMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter)); } IRISLANGLIBRARY_API void IrisDev_AddClassMethod(IIrisClass * pClass, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter) { pClass->GetInternClass()->AddClassMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter)); } IRISLANGLIBRARY_API void IrisDev_AddInstanceMethod(IIrisModule * pModule, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter) { pModule->GetInternModule()->AddInstanceMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter)); } IRISLANGLIBRARY_API void IrisDev_AddClassMethod(IIrisModule * pModule, const char * szMethodName, IrisNativeFunction pfFunction, size_t nParamCount, bool bIsWithVariableParameter) { pModule->GetInternModule()->AddClassMethod(new IrisMethod(szMethodName, pfFunction, nParamCount, bIsWithVariableParameter)); } IRISLANGLIBRARY_API void IrisDev_AddGetter(IIrisClass * pClass, const char * szInstanceVariableName, IrisNativeFunction pfFunction) { pClass->GetInternClass()->AddGetter(szInstanceVariableName, pfFunction); } IRISLANGLIBRARY_API void IrisDev_AddSetter(IIrisClass* pClass, const char * szInstanceVariableName, IrisNativeFunction pfFunction) { pClass->GetInternClass()->AddSetter(szInstanceVariableName, pfFunction); } IRISLANGLIBRARY_API void IrisDev_AddConstance(IIrisClass * pClass, const char * szConstanceName, const IrisValue & ivValue) { pClass->GetInternClass()->AddConstance(szConstanceName, ivValue); } IRISLANGLIBRARY_API void IrisDev_AddConstance(IIrisModule * pModule, const char * szConstanceName, const IrisValue & ivValue) { pModule->GetInternModule()->AddConstance(szConstanceName, ivValue); } IRISLANGLIBRARY_API void IrisDev_AddClassVariable(IIrisClass * pClass, const char * szVariableName, const IrisValue & ivValue) { pClass->GetInternClass()->AddClassVariable(szVariableName, ivValue); } IRISLANGLIBRARY_API void IrisDev_AddClassVariable(IIrisModule * pClass, const char * szVariableName, const IrisValue & ivValue) { pClass->GetInternModule()->AddClassVariable(szVariableName, ivValue); } IRISLANGLIBRARY_API void IrisDev_AddModule(IIrisClass * pClass, IIrisModule * pTargetModule) { pClass->GetInternClass()->AddModule(pTargetModule->GetInternModule()); } IRISLANGLIBRARY_API void IrisDev_AddModule(IIrisModule * pModule, IIrisModule * pTargetModule) { pModule->GetInternModule()->AddModule(pTargetModule->GetInternModule()); } IRISLANGLIBRARY_API IrisValue IrisDev_CreateNormalInstance(IIrisClass * pClass, IIrisValues * ivsParams, IIrisContextEnvironment * pContexEnvironment) { return pClass->GetInternClass()->CreateInstance(ivsParams, pContexEnvironment); } IRISLANGLIBRARY_API IrisValue IrisDev_CreateStringInstanceByInstantValue(const char * szString) { auto pClass = IrisDev_GetClass("String"); IrisValue ivValue; IrisObject* pObject = new IrisObject(); pObject->SetClass(pClass); IrisStringTag* pString = new IrisStringTag(szString); pObject->SetNativeObject(pString); ivValue.SetIrisObject(pObject); IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject())); IrisGC::CurrentGC()->Start(); // 将新对象保存到堆里 IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue); return ivValue; } IRISLANGLIBRARY_API IrisValue IrisDev_CreateFloatInstanceByInstantValue(double dFloat) { auto pClass = IrisDev_GetClass("Float"); IrisValue ivValue; IrisObject* pObject = new IrisObject(); pObject->SetClass(pClass); IrisFloatTag* pFloat = new IrisFloatTag(dFloat); pObject->SetNativeObject(pFloat); ivValue.SetIrisObject(pObject); IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject())); IrisGC::CurrentGC()->Start(); // 将新对象保存到堆里 IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue); return ivValue; } IRISLANGLIBRARY_API IrisValue IrisDev_CreateIntegerInstanceByInstantValue(int nInteger) { auto pClass = IrisDev_GetClass("Integer"); IrisValue ivValue; IrisObject* pObject = new IrisObject(); pObject->SetClass(pClass); IrisIntegerTag* pInteger = new IrisIntegerTag(nInteger); pObject->SetNativeObject(pInteger); ivValue.SetIrisObject(pObject); IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject())); IrisGC::CurrentGC()->Start(); // 将新对象保存到堆里 IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue); return ivValue; } IRISLANGLIBRARY_API IrisValue IrisDev_CreateUniqueStringInstanceByUniqueIndex(size_t nIndex) { IrisValue ivValue; bool bResult = false; ivValue = IrisUniqueString::GetUniqueString(nIndex, bResult); if (bResult) { return ivValue; } auto pClass = IrisDev_GetClass("UniqueString"); IrisObject* pObject = new IrisObject(); pObject->SetClass(pClass); pObject->SetPermanent(true); IrisUniqueStringTag* pString = new IrisUniqueStringTag(IrisCompiler::CurrentCompiler()->GetUniqueString(nIndex, IrisCompiler::CurrentCompiler()->GetCurrentFileIndex())); pObject->SetNativeObject(pString); ivValue.SetIrisObject(pObject); IrisGC::CurrentGC()->AddSize(sizeof(IrisObject) + pObject->GetClass()->GetTrustteeSize(pObject->GetNativeObject())); IrisGC::CurrentGC()->Start(); // 将新对象保存到堆里 IrisInterpreter::CurrentInterpreter()->AddNewInstanceToHeap(ivValue); IrisUniqueString::AddUniqueString(nIndex, ivValue); return ivValue; } IRISLANGLIBRARY_API void IrisDev_SetObjectInstanceVariable(IrisValue & ivObj, char * szInstanceVariableName, const IrisValue & ivValue) { bool bResult = false; auto& ivResult = ivObj.GetIrisObject()->GetInstanceValue(szInstanceVariableName, bResult); if (bResult) { ((IrisValue&)ivResult).SetIrisObject(ivResult.GetIrisObject()); } else { ivObj.GetIrisObject()->AddInstanceValue(szInstanceVariableName, ivValue); } } IRISLANGLIBRARY_API IrisValue IrisDev_GetObjectInstanceVariable(IrisValue & ivObj, char * szInstanceVariableName) { bool bResult = false; auto& ivResult = ivObj.GetIrisObject()->GetInstanceValue(szInstanceVariableName, bResult); return ivResult; } IRISLANGLIBRARY_API bool IrisDev_IrregularHappened() { return IrisInterpreter::CurrentInterpreter()->IrregularHappened(); } IRISLANGLIBRARY_API bool IrisDev_FatalErrorHappened() { return IrisInterpreter::CurrentInterpreter()->FatalErrorHappened(); } void _InternFatalErrorMessageFunction(const string& pMessage) { g_pfFatalErrorMessageFunction((char*)pMessage.c_str()); } bool _InternExitConditionFunction() { return g_pfExitConditionFunction() ? true : false; } IRISLANGLIBRARY_API bool IR_Initialize(PIrisInitializeStruct pInitializeStruct) { IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); g_pfExitConditionFunction = pInitializeStruct->m_pfExitConditionFunction; g_pfFatalErrorMessageFunction = pInitializeStruct->m_pfFatalErrorMessageFunction; IrisFatalErrorHandler::CurrentFatalHandler()->SetFatalErrorMessageFuncton(_InternFatalErrorMessageFunction); pInterpreter->SetExitConditionFunction(_InternExitConditionFunction); return true; } IRISLANGLIBRARY_API bool IR_Run() { IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); pInterpreter->SetCompiler(pCompiler); // Run IrisGC::CurrentGC()->SetGCFlag(false); if (!pInterpreter->Initialize()) { return false; } IrisGC::CurrentGC()->ResetNextThreshold(); IrisGC::CurrentGC()->SetGCFlag(true); if (!pInterpreter->Run()) { return false; } return true; } IRISLANGLIBRARY_API bool IR_ShutDown() { IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); return pInterpreter->ShutDown(); } IRISLANGLIBRARY_API bool IR_LoadScriptFromPath(char * pScriptFilePath) { string strOrgFileName(pScriptFilePath); string strDestFileName; auto nPos = strOrgFileName.find_last_of("."); if (nPos != std::string::npos) { strDestFileName.assign(strOrgFileName, 0, nPos); } strDestFileName += ".irc"; IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); pCompiler->LoadScript(pScriptFilePath); bool bCompileResult = pCompiler->Generate(); if (!bCompileResult) { remove(strDestFileName.c_str()); } return bCompileResult; } IRISLANGLIBRARY_API bool IR_LoadScriptFromVirtualPathAndText(char* pPath, char * pScriptText) { string strDestFileName(pPath); strDestFileName += ".irc"; IrisCompiler* pCompiler = IrisCompiler::CurrentCompiler(); pCompiler->LoadScriptFromVirtualPathAndText(pPath, pScriptText); bool bCompileResult = pCompiler->Generate(); if (!bCompileResult) { remove(strDestFileName.c_str()); } return bCompileResult; } IRISLANGLIBRARY_API bool IR_LoadExtention(char * pExtentionPath) { IrisInterpreter* pInterpreter = IrisInterpreter::CurrentInterpreter(); return pInterpreter->LoadExtension(pExtentionPath); }
[ "a1026121287@hotmail.com" ]
a1026121287@hotmail.com
ff3e009725d61538b5c086dcbaa1e6fd7436e790
8a50a32e7d34df7b6430919bcdd7b971d3baac64
/v0.1.1/WPJInputUtil.cpp
fd723e353b82587003e7022c551484de778355ba
[]
no_license
woudX/WPJ
6f0ea0705f38245c9741e7cbde5846b3b2758519
ec670b8d1f2d42b2723e1463a50a00b887b4a80e
refs/heads/master
2016-09-16T02:05:34.377895
2014-08-14T05:08:24
2014-08-14T05:08:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,659
cpp
#include "WPJInputUtil.h" USING_NS_WPJ WPJInputUtil *WPJInputUtil::m_pInst = 0; WPJInputUtil::WPJInputUtil():m_bFirst(true) { memset(m_arKeyPressed, 0, sizeof(m_arKeyPressed)); } WPJInputUtil *WPJInputUtil::GetSharedInst() { if (m_pInst == 0) m_pInst = new WPJInputUtil(); return m_pInst; } WPJInputUtil *WPJInputUtil::RegistDisplay(ALLEGRO_DISPLAY *pDisplay) { m_pDisplay = pDisplay; return this; } WPJInputUtil *WPJInputUtil::UnregistDisplay() { m_pDisplay = NULL; return this; } bool WPJInputUtil::Init() { int bRet; // init input hardware driver bRet = al_is_keyboard_installed() && al_is_mouse_installed(); // init event_queue m_pEventQueue = al_create_event_queue(); if (bRet && m_pEventQueue) { al_register_event_source(m_pEventQueue, al_get_keyboard_event_source()); al_register_event_source(m_pEventQueue, al_get_mouse_event_source()); al_register_event_source(m_pEventQueue, al_get_display_event_source(m_pDisplay)); } return bRet; } int WPJInputUtil::PeekEvent(ALLEGRO_EVENT &e) { return al_wait_for_event_timed(m_pEventQueue, &e, 0.001f); } void WPJInputUtil::AnalysisEvent(ALLEGRO_EVENT &e) { // key pressed if (e.type == ALLEGRO_EVENT_KEY_DOWN) m_arKeyPressed[e.keyboard.keycode] = true; else if (e.type == ALLEGRO_EVENT_KEY_UP) m_arKeyPressed[e.keyboard.keycode] = false; // event trigged if (e.type == ALLEGRO_EVENT_KEY_DOWN || e.type == ALLEGRO_EVENT_KEY_UP || e.type == ALLEGRO_EVENT_KEY_CHAR) { ALLEGRO_EVENT copyE = e; WPJEvent *pEvent = new WPJEvent(copyE, e.type); m_lTriggedEvents.push_back(pEvent); } } bool WPJInputUtil::IsKeyPressed(int keyID) { if (keyID < MAX_INPUT_SIZE) return m_arKeyPressed[keyID]; else { //WPJLOG("[%s] There is no keyID = %ud, please change MAX_INPUT_SIZE\n", _D_NOW_TIME__, keyID); ASSERT(false); return false; } } WPJEvent *WPJInputUtil::NextTriggedEvent() { WPJEvent *bRet = NULL; if (m_lTriggedEvents.size() > 0) { if (m_bFirst) { m_itNextEvent = m_lTriggedEvents.begin(); m_bFirst = false; } else m_itNextEvent++; if (m_itNextEvent != m_lTriggedEvents.end()) bRet = pp(m_itNextEvent); } return bRet; } void WPJInputUtil::ClearAllTriggedEvents() { foreach_in_list_auto(WPJEvent*, itor, m_lTriggedEvents) ptr_safe_del(pp(itor)); m_lTriggedEvents.clear(); m_bFirst = true; } WPJInputUtil::~WPJInputUtil() { ClearAllTriggedEvents(); if (al_is_keyboard_installed()) al_unregister_event_source(m_pEventQueue, al_get_keyboard_event_source()); if (al_is_mouse_installed()) al_unregister_event_source(m_pEventQueue, al_get_mouse_event_source()); al_destroy_event_queue(m_pEventQueue); }
[ "jccgls001@126.com" ]
jccgls001@126.com
98f112694db50d0b6bb92e14aa129b47d7288b8f
0ac892aa91ed29c5910df727903b2a71c29b1a0c
/src/UIState/SetTempSetPoint.h
03d159d439439395ed41dffcb0730f70cecac59b
[ "MIT" ]
permissive
thomca/TankController
68da356a33040cbeeba1b027401865f77ec415c3
d1e4db579b3e0ddf90ec423ee4bee8f2bf9c7836
refs/heads/main
2023-04-19T06:19:21.442528
2021-05-12T04:52:44
2021-05-12T04:52:44
366,751,414
0
0
MIT
2021-05-12T14:50:53
2021-05-12T14:50:53
null
UTF-8
C++
false
false
493
h
/** * SetTempSetPoint.h * * Set the target Temperature */ #pragma once #include "NumberCollectorState.h" class SetTempSetPoint : public NumCollectorState { public: SetTempSetPoint(TankControllerLib* tc) : NumCollectorState(tc) { } const char* name() { return "SetTempSetPoint"; } float getCurrentValue() { return 0.0; } int getCurrentValuePrecision() { return 2; } const char* prompt() { return "Set Temperature "; }; void setValue(double value); };
[ "noreply@github.com" ]
thomca.noreply@github.com
94c275be25e47904c3b285a44648a78255fa4bec
1e58f86db88d590ce63110c885c52305d67f8136
/Common/messagelistdelegate.cpp
f89d1da790a13889ea4f96f582f611267dba6d32
[]
no_license
urielyan/F270
32a9b87780b6b0bbbd8e072ca4305cd38dc975c1
c3d1eceead895ded12166eeb6748df111f46ef2d
refs/heads/master
2021-01-10T02:06:40.335370
2016-03-02T03:23:02
2016-03-02T03:23:02
52,927,128
1
1
null
null
null
null
UTF-8
C++
false
false
3,475
cpp
/********************************************************************* * Copyright(c) 2014, 大豪信息技术有限公司上海研发部 * * All Rights reserved * * 文件名称:MessageListDelegate.cpp * 概 要:信息显示接口的代理 * * 当前版本:V1.0.0 * 作 者:葛 海 浪 * 完成日期:2016-2-22 * * 修改版本: * 修改说明: * 修改作者: * ********************************************************************/ #include "messagelistdelegate.h" #include <QPainter> MessageListDelegate::MessageListDelegate(QObject *parent) : QAbstractItemDelegate(parent) { } void MessageListDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { painter->save(); painter->setRenderHint(QPainter::Antialiasing); QRect sequnceRect, messageRect; doLayout(option, sequnceRect, messageRect); drawBackGround(painter, option, index); drawSequnceRect(painter, option, index, sequnceRect); drawMessageRect(painter, option, index, messageRect); painter->restore(); } QSize MessageListDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const { return option.rect.size(); } bool MessageListDelegate::helpEvent(QHelpEvent */*event*/, QAbstractItemView */*view*/, const QStyleOptionViewItem &/*option*/, const QModelIndex &/*index*/) { return false; } void MessageListDelegate::doLayout(const QStyleOptionViewItem &option, QRect &sequnceRect, QRect &messageRect) const { /** draw Message Sequnce Rect **/ sequnceRect = option.rect; sequnceRect.setWidth(option.rect.width() / 9); sequnceRect.moveLeft(option.rect.left()); /** draw Message Information Rect **/ messageRect = option.rect; messageRect.moveLeft(option.rect.left()); } void MessageListDelegate::drawBackGround(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { painter->save(); /** draw background **/ QRect rect = option.rect; painter->setPen(QColor(202, 201, 200)); if(index.data(MousePressRole).toBool()) { // 鼠标下押状态 painter->setBrush(QBrush(QColor(179, 231, 255))); } else { if((index.data(MouseClickedRole).toBool())) { // 鼠标单击状态 painter->setBrush(QBrush(QColor(220, 244, 255))); } else { // 默认状态 painter->setBrush(QBrush(QColor(248, 248, 248))); } } painter->drawRoundedRect(rect, 0, 0); /** draw over **/ painter->restore(); } void MessageListDelegate::drawSequnceRect(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index, const QRect &rect) const { painter->save(); int pixSize = rect.height() * 0.25; QFont font = option.font; QTextOption txtAlign(Qt::AlignHCenter | Qt::AlignTop); font.setPixelSize(pixSize); painter->setFont(font); painter->drawText(rect, index.data(SequnceRole).toString(), txtAlign); painter->restore(); } void MessageListDelegate::drawMessageRect(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index, const QRect &rect) const { painter->save(); int pixSize = rect.height() * 0.35; QFont font = option.font; QTextOption txtAlign(Qt::AlignCenter); font.setPixelSize(pixSize); painter->setFont(font); painter->drawText(rect, index.data(MessageRole).toString(), txtAlign); painter->restore(); }
[ "urielyan@sina.com" ]
urielyan@sina.com
b612e83cb0cee3bbb91e018abc60dc12dc4dc46d
e66d115b1b53b5be0cc6a6a2233ffdb4c22096e0
/Ogitor/qtOgitor/include/settingsdialog.hxx
2ac8c73c4b40f0229225f7eb6c0d325d0ad95ffa
[ "MIT" ]
permissive
lockie/HiveGame
565a6f46b214f7df345c25c0bc05ee5bd6699ece
bb1aa12561f1dfd956d78a53bfb7a746e119692a
refs/heads/master
2021-06-11T20:56:21.872049
2016-12-18T11:28:33
2016-12-18T11:28:33
1,229,308
4
1
null
null
null
null
UTF-8
C++
false
false
2,850
hxx
/*///////////////////////////////////////////////////////////////////////////////// /// An /// ___ ____ ___ _____ ___ ____ /// / _ \ / ___|_ _|_ _/ _ \| _ \ /// | | | | | _ | | | || | | | |_) | /// | |_| | |_| || | | || |_| | _ < /// \___/ \____|___| |_| \___/|_| \_\ /// File /// /// Copyright (c) 2008-2011 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team // /// The MIT License /// /// 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 SETTINGSDIALOG_HXX #define SETTINGSDIALOG_HXX #include <QtGui/QDialog> #include <QtGui/QWidget> #include "OgitorsPrerequisites.h" #include "ui_settingsdialog.h" #include "colourpicker.hxx" class SettingsDialog : public QDialog, public Ui::settingsdialog { Q_OBJECT public: SettingsDialog(QWidget *parent, Ogitors::PROJECTOPTIONS *options); virtual ~SettingsDialog(); void addResourceLocation(int loctype, QString path); public Q_SLOTS: void onAccept(); void browse(); void onAddDirectory(); void onAddDirectoryRecursive(); void onAddArchive(); void onRemoveEntry(); private: Ogitors::PROJECTOPTIONS *mOptions; std::vector<int> mResourceFileTypes; ColourPickerWidget *mSelRectColourWidget; ColourPickerWidget *mSelColourWidget; ColourPickerWidget *mHighlightColourWidget; ColourPickerWidget *mSelectHighlightColourWidget; ColourPickerWidget *mGridColourWidget; bool eventFilter ( QObject * watched, QEvent * e ); // Drag-and drop functions void dragEnterEvent(QDragEnterEvent * e); void dropEvent(QDropEvent * e); static QStringList getFilenames(const QMimeData * data); }; #endif // SETTINGSDIALOG_HXX
[ "fake0mail0@gmail.com" ]
fake0mail0@gmail.com
f2709ed6b1b5a63738c24e1b6950c1054029c676
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/compiler/xla/service/gpu/for_thunk.cc
7ccfcf3bd6363e6a66b4b3e05f1a0a47a689b5bb
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
2,461
cc
/* Copyright 2017 The TensorFlow 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 "tensorflow/compiler/xla/service/gpu/for_thunk.h" #include "absl/memory/memory.h" #include "tensorflow/compiler/xla/service/gpu/hlo_execution_profiler.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { ForThunk::ForThunk(const int64 loop_limit, std::unique_ptr<ThunkSequence> body_thunk_sequence, const HloInstruction* hlo) : Thunk(Kind::kWhile, hlo), loop_limit_(loop_limit), body_thunk_sequence_(absl::make_unique<SequentialThunk>( // Pass nullptr as the HloInstruction* to the body_thunk_sequence_ // constructor because this SequentialThunk is logically "part of" // this ForThunk, and shouldn't be profiled separately from it. std::move(*body_thunk_sequence), nullptr)) {} Status ForThunk::Initialize(const GpuExecutable& executable, se::StreamExecutor* executor) { TF_RETURN_IF_ERROR(body_thunk_sequence_->Initialize(executable, executor)); return Status::OK(); } Status ForThunk::ExecuteOnStream(const ExecuteParams& params) { VLOG(2) << "Executing ForThunk with " << loop_limit_ << " iters for " << (hlo_instruction() ? hlo_instruction()->ToString() : "<null>"); auto op_profiler = params.profiler->MakeScopedInstructionProfiler(hlo_instruction()); for (int64 i = 0; i < loop_limit_; ++i) { params.profiler->StartHloComputation(); // Invoke loop body thunk sequence. TF_RETURN_IF_ERROR(body_thunk_sequence_->ExecuteOnStream(params)); params.profiler->FinishHloComputation(hlo_instruction()->while_body()); } return Status::OK(); } } // namespace gpu } // namespace xla
[ "v-grniki@microsoft.com" ]
v-grniki@microsoft.com
254872aa8a3e03462daf9808b8e7877450570e1a
c36c51b605873e674efdf1a9c2198be2b24ba1cc
/Source/Core/EventSpecification.cpp
6b29242ae5c401f0aeba409ace5a0ac95e293e62
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
aquawicket2/RmlUi
5454c673af3b307f9d079495b0515894f71b4893
264d3630f435855aa67b4db1e081c3a727713c1c
refs/heads/master
2021-04-23T04:58:12.383232
2020-03-28T16:33:59
2020-03-28T16:33:59
249,899,751
4
0
MIT
2020-03-25T06:03:25
2020-03-25T06:03:25
null
UTF-8
C++
false
false
8,399
cpp
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * 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 "EventSpecification.h" #include "../../Include/RmlUi/Core/ID.h" namespace Rml { namespace Core { // An EventId is an index into the specifications vector. static std::vector<EventSpecification> specifications = { { EventId::Invalid, "invalid", false, false, DefaultActionPhase::None } }; // Reverse lookup map from event type to id. static UnorderedMap<String, EventId> type_lookup; namespace EventSpecificationInterface { void Initialize() { // Must be specified in the same order as in EventId specifications = { // id type interruptible bubbles default_action {EventId::Invalid , "invalid" , false , false , DefaultActionPhase::None}, {EventId::Mousedown , "mousedown" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Mousescroll , "mousescroll" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Mouseover , "mouseover" , true , true , DefaultActionPhase::Target}, {EventId::Mouseout , "mouseout" , true , true , DefaultActionPhase::Target}, {EventId::Focus , "focus" , false , false , DefaultActionPhase::Target}, {EventId::Blur , "blur" , false , false , DefaultActionPhase::Target}, {EventId::Keydown , "keydown" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Keyup , "keyup" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Textinput , "textinput" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Mouseup , "mouseup" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Click , "click" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Dblclick , "dblclick" , true , true , DefaultActionPhase::TargetAndBubble}, {EventId::Load , "load" , false , false , DefaultActionPhase::None}, {EventId::Unload , "unload" , false , false , DefaultActionPhase::None}, {EventId::Show , "show" , false , false , DefaultActionPhase::None}, {EventId::Hide , "hide" , false , false , DefaultActionPhase::None}, {EventId::Mousemove , "mousemove" , true , true , DefaultActionPhase::None}, {EventId::Dragmove , "dragmove" , true , true , DefaultActionPhase::None}, {EventId::Drag , "drag" , false , true , DefaultActionPhase::Target}, {EventId::Dragstart , "dragstart" , false , true , DefaultActionPhase::Target}, {EventId::Dragover , "dragover" , true , true , DefaultActionPhase::None}, {EventId::Dragdrop , "dragdrop" , true , true , DefaultActionPhase::None}, {EventId::Dragout , "dragout" , true , true , DefaultActionPhase::None}, {EventId::Dragend , "dragend" , true , true , DefaultActionPhase::None}, {EventId::Handledrag , "handledrag" , false , true , DefaultActionPhase::None}, {EventId::Resize , "resize" , false , false , DefaultActionPhase::None}, {EventId::Scroll , "scroll" , false , true , DefaultActionPhase::None}, {EventId::Animationend , "animationend" , false , true , DefaultActionPhase::None}, {EventId::Transitionend , "transitionend" , false , true , DefaultActionPhase::None}, {EventId::Change , "change" , false , true , DefaultActionPhase::None}, {EventId::Submit , "submit" , true , true , DefaultActionPhase::None}, {EventId::Tabchange , "tabchange" , false , true , DefaultActionPhase::None}, {EventId::Columnadd , "columnadd" , false , true , DefaultActionPhase::None}, {EventId::Rowadd , "rowadd" , false , true , DefaultActionPhase::None}, {EventId::Rowchange , "rowchange" , false , true , DefaultActionPhase::None}, {EventId::Rowremove , "rowremove" , false , true , DefaultActionPhase::None}, {EventId::Rowupdate , "rowupdate" , false , true , DefaultActionPhase::None}, }; type_lookup.clear(); type_lookup.reserve(specifications.size()); for (auto& specification : specifications) type_lookup.emplace(specification.type, specification.id); #ifdef RMLUI_DEBUG // Verify that all event ids are specified RMLUI_ASSERT((int)specifications.size() == (int)EventId::NumDefinedIds); for (int i = 0; i < (int)specifications.size(); i++) { // Verify correct order RMLUI_ASSERT(i == (int)specifications[i].id); } #endif } static EventSpecification& GetMutable(EventId id) { size_t i = static_cast<size_t>(id); if (i < specifications.size()) return specifications[i]; return specifications[0]; } // Get event specification for the given type. // If not found: Inserts a new entry with given values. static EventSpecification& GetOrInsert(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase) { auto it = type_lookup.find(event_type); if (it != type_lookup.end()) return GetMutable(it->second); const size_t new_id_num = specifications.size(); if (new_id_num >= size_t(EventId::MaxNumIds)) { Log::Message(Log::LT_ERROR, "Error while registering event type '%s': Maximum number of allowed events exceeded.", event_type.c_str()); RMLUI_ERROR; return specifications.front(); } // No specification found for this name, insert a new entry with default values EventId new_id = static_cast<EventId>(new_id_num); specifications.push_back(EventSpecification{ new_id, event_type, interruptible, bubbles, default_action_phase }); type_lookup.emplace(event_type, new_id); return specifications.back(); } const EventSpecification& Get(EventId id) { return GetMutable(id); } const EventSpecification& GetOrInsert(const String& event_type) { // Default values for new event types defined as follows: constexpr bool interruptible = true; constexpr bool bubbles = true; constexpr DefaultActionPhase default_action_phase = DefaultActionPhase::None; return GetOrInsert(event_type, interruptible, bubbles, default_action_phase); } EventId GetIdOrInsert(const String& event_type) { auto it = type_lookup.find(event_type); if (it != type_lookup.end()) return it->second; return GetOrInsert(event_type).id; } EventId InsertOrReplaceCustom(const String& event_type, bool interruptible, bool bubbles, DefaultActionPhase default_action_phase) { const size_t size_before = specifications.size(); EventSpecification& specification = GetOrInsert(event_type, interruptible, bubbles, default_action_phase); bool got_existing_entry = (size_before == specifications.size()); // If we found an existing entry of same type, replace it, but only if it is a custom event id. if (got_existing_entry && (int)specification.id >= (int)EventId::FirstCustomId) { specification.interruptible = interruptible; specification.bubbles = bubbles; specification.default_action_phase = default_action_phase; } return specification.id; } } } }
[ "michael.ragazzon@gmail.com" ]
michael.ragazzon@gmail.com
83afdfeb36d03188fe3cea71448daf1c01be4e75
7f8648727d44a04cf98fa3cf80ac010acbe43474
/Feld.h
83b13637dc3ba321c4e9a516c7df761053fd348b
[]
no_license
christiannoubi/Feld-WS15
5b2cbd2bb647a1a541fb2109888c4f3056f5715b
9f25b6ec3b512b28908c799f46134e6f58f98b55
refs/heads/master
2020-04-15T03:00:34.844152
2019-01-06T18:08:16
2019-01-06T18:08:16
164,332,356
0
0
null
null
null
null
UTF-8
C++
false
false
610
h
#include <iostream> struct Feld { // Destruktor: virtual ~Feld () {} // Liefert die Länge des Felds zurück: virtual int laenge() const = 0; // Klammeroperator für nicht-konstante Objekte: virtual double &operator [] (int a) = 0; // Klammeroperator für konstante Objekte: virtual double &operator [] (int a) const = 0; }; // Feld auf den Ausgabestrom ausgeben: std::ostream& operator << (std::ostream& os, Feld& feld) { os << "["; for(int i=0; i<feld.laenge(); i++) { os << " " << feld [i]; } os << " ]"; return os; }
[ "noubichristian@yahoo.fr" ]
noubichristian@yahoo.fr
30116a9b6a93560dc800be72d83edd550df89b1c
5bc237a4755d1d17218343d95eb95594b8fadb3d
/application/test/test_application.cpp
912e3e75ce6fe8fe2bd99a1257cb76974d86b053
[]
no_license
duynii/btproject
557b85d14fd47de6acca8f4e05c9c38b22075ac5
7f87305e3e2dd524a5bd85ded76241d9eb7d0a17
refs/heads/master
2020-06-20T21:00:39.995727
2016-11-27T11:33:26
2016-11-27T11:33:26
74,821,652
0
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
#include <limits> #include <gtest/gtest.h> #include <comma/application/command_line_options.h> #include <comma/application/signal_flag.h> /// Some dummy tests to test linking TEST( application, dj_algorithm ) { EXPECT_TRUE( 1 == 1 ); EXPECT_FALSE( 1 != 1 ); EXPECT_EQ( 5, 5 ); // TODO: definitely more tests! }
[ "duynii@gmail.com" ]
duynii@gmail.com
a2461e5474c1dcabd9641913ae4ebf7dd534f3e6
85f6241123446541443cfd33045cbbfe63365295
/unit_tests/test.cpp
b1ca962b232cabaa3ad11ff897487433049cdc68
[]
no_license
sharonen/RateLimitingRequestsModule
3df01ea97693d7ff7090c906415dfd7fbff26f18
cf1991cae24c7fc7ca6b1132af492e4dd1524898
refs/heads/master
2020-03-29T11:03:14.582647
2018-09-30T06:07:52
2018-09-30T06:07:52
149,833,728
0
0
null
null
null
null
UTF-8
C++
false
false
3,308
cpp
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "../src/lib/requests_handler/requests_handler.hpp" #include "../src/lib/requests_handler/response.hpp" TEST_CASE("Checking the limit of requests") { GIVEN("a Requests Handle"){ auto pRequestsHandler = new RequestsHadler(100, 60); THEN("the requests limits is as expected") REQUIRE(pRequestsHandler->requests_limit()== 100); } } TEST_CASE("Checking getter and setter methods of requests limits") { GIVEN("a Requests Handle"){ auto pRequestsHandler = new RequestsHadler(100, 60); WHEN("setting a new value requests_limit"){ pRequestsHandler->requests_limit(200); THEN("the new requests limits is as expected"){ REQUIRE(pRequestsHandler->requests_limit() == 200); } } } } TEST_CASE("Checking getter and setter methods of timer_rate_in_sec") { GIVEN("a Requests Handle"){ auto pRequestsHandler = new RequestsHadler(100, 60); WHEN("setting a new value timer_rate_in_sec"){ pRequestsHandler->timer_rate_in_sec(10); THEN("the new requests limits is as expected"){ REQUIRE(pRequestsHandler->timer_rate_in_sec() == 10); } } } } TEST_CASE("checking the limit of requests") { GIVEN("a Requests Handle"){ Response reps; std::string url = "www.google.com"; RequestsHadler* pRequestsHandler = new RequestsHadler(5, 60); REQUIRE(pRequestsHandler->requests_limit() == 5); WHEN("sending 6 HTTP requests"){ for(int i = 0; i < 5; i++){ reps = pRequestsHandler->handleNewRequest(url); REQUIRE(reps.code == ErrorCode::ok); } reps = pRequestsHandler->handleNewRequest(url); THEN("the method returns an error code too many requests (HTTP error code 429)"){ REQUIRE(reps.code == ErrorCode::TooManyRequests); } } } } TEST_CASE("checking the update requests limit") { GIVEN("a Requests Handle"){ Response reps; std::string url = "www.google.com"; RequestsHadler* pRequestsHandler = new RequestsHadler(10, 2); REQUIRE(pRequestsHandler->current_requests_limit() == 10); for(int i = 0; i < 5; i++){ reps = pRequestsHandler->handleNewRequest(url); REQUIRE(reps.code == ErrorCode::ok); } REQUIRE(pRequestsHandler->current_requests_limit()== 5); WHEN("calling updateRequestsLimit"){ boost::asio::io_service io_s; boost::asio::deadline_timer timer(io_s); pRequestsHandler->updateRequestsLimit(&timer); THEN("the current requests limit is restart"){ REQUIRE(pRequestsHandler->current_requests_limit()== 10); } } } } TEST_CASE("checking the url requests ") { GIVEN("a Requests Handle"){ Response reps; RequestsHadler* pRequestsHandler = new RequestsHadler(10, 2); REQUIRE(pRequestsHandler->current_requests_limit()== 10); WHEN("requesting a correct URL request"){ std::string url = "www.google.com"; reps = pRequestsHandler->handleNewRequest(url); THEN("the method returns okay (HTTP code 200)"){ REQUIRE(reps.code == ErrorCode::ok); } } WHEN("requesting a worng URL request"){ std::string url = "www.no_such_url_fot_testing.com"; reps = pRequestsHandler->handleNewRequest(url); THEN("the method returns an error code bad request (HTTP error code 400)"){ REQUIRE(reps.code == ErrorCode::BadRequest); } } } }
[ "sharonronen@sharons-air.lan" ]
sharonronen@sharons-air.lan
560ec2df631e868708dbc2dcc4e636d06505f510
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/chrome/browser/notifications/fullscreen_notification_blocker.h
f8d6107fd88f7910d68af8e26ad296d88e3455aa
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,531
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_NOTIFICATIONS_FULLSCREEN_NOTIFICATION_BLOCKER_H_ #define CHROME_BROWSER_NOTIFICATIONS_FULLSCREEN_NOTIFICATION_BLOCKER_H_ #include "base/macros.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "ui/message_center/notification_blocker.h" // A notification blocker which checks the fullscreen state. class FullscreenNotificationBlocker : public message_center::NotificationBlocker, public content::NotificationObserver { public: explicit FullscreenNotificationBlocker( message_center::MessageCenter* message_center); ~FullscreenNotificationBlocker() override; bool is_fullscreen_mode() const { return is_fullscreen_mode_; } // message_center::NotificationBlocker overrides: void CheckState() override; bool ShouldShowNotificationAsPopup( const message_center::Notification& notification) const override; private: // content::NotificationObserver override. void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; bool is_fullscreen_mode_; content::NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(FullscreenNotificationBlocker); }; #endif // CHROME_BROWSER_NOTIFICATIONS_FULLSCREEN_NOTIFICATION_BLOCKER_H_
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
0e8c7105810471c8d3209efebd54856edbc91ee3
b155f6ba313cfd5c02441ac3d639fff2273daae0
/Source/Server.cpp
dc2b94643b2083d75e78e54de976ed710f6c67f8
[]
no_license
numver8638/EndTermProjectV2
86128fc6111ca42965054710b02b83983107f780
5e4ca89fef54cd545b1b20ee08b551ecb5b1fd01
refs/heads/master
2023-03-22T01:26:06.558307
2021-03-18T08:14:44
2021-03-18T08:14:44
348,604,277
1
0
null
null
null
null
UTF-8
C++
false
false
11,855
cpp
#include "Server.h" #include <algorithm> #include <cassert> #include <ctime> #include <cstdlib> #include <iostream> #include "ConnectionState.h" #include "PacketStream.h" #include "Socket.h" #include "Thread.h" #define MIN_WIDTH (0) #define MAX_WIDTH (10) #define MIN_HEIGHT (0) #define MAX_HEIGHT (10) #define BUFFER_HEIGHT (4) // 클라이언트와 통신하는 스레드. 클라이언트 당 하나씩 생성됨. class ClientThread : public Thread { private: Socket m_socket; PacketStream m_stream; std::string m_username; ConnectionState m_state = ConnectionState::Login; bool m_connected = true; std::vector<Block> m_blocks; Block m_currentBlock; int m_maxHeight; // 타이머 정보 DWORD m_ticks; DWORD m_tickCount; DWORD m_tickBase; void Disconnect() { m_connected = false; m_socket.Close(); } // 현재 블럭 상태에서 주어진 위치로 블럭을 이동 할 수 있는지 판단하는 메서드. bool CanMove(const Position& pos, const BlockData& data) { std::vector<bool> plane(MAX_WIDTH * MAX_HEIGHT); // 현재 쌓인 블록을 기준으로 bool vector 생성. auto it = m_blocks.begin(); const auto end = --m_blocks.end(); // 마지막 블럭은 현재 블럭(움직이고 있는 블럭)으로 취급함. while (it != end) { auto& b = *(it++); const auto& pos = b.GetPosition(); for (const auto& p : b.GetData().Data) { if ((pos.Y + p.first.Y) >= 0) { plane[(pos.Y + p.first.Y) * MAX_WIDTH + (pos.X + p.first.X)] = true; } } } // 위에서 생성한 bool vector와 현재 블럭이 겹치는지 판단. auto collide = false; for (const auto& p : data.Data) { // 블럭이 위에서 내려오는 경우 일부가 잘릴수도 있음. // 그런 예외 상황을 고려해서 Y가 0 이상인 부분만 판단. if ((pos.Y + p.first.Y) >= 0) { collide |= plane[(pos.Y + p.first.Y) * MAX_WIDTH + (pos.X + p.first.X)]; } } // 충돌하지 않는다면 옮길 수 있고, 아니라면 옮길 수 없음. return !collide; } void SendCreateBlock() { // Send random block auto block = Block::GenerateRandomBlock(); // 블럭이 X축 밖으로 넘어가지 않는 범위에서 랜덤으로 X 위치를 결정함. auto pos = Position(rand() % (MAX_WIDTH - block.GetData().Width), 0); // 블럭의 위치를 설정. block.SetAbsolutePosition(pos); // 클라이언트에게 전송. m_stream.SendEvent(CreateBlockEvent(block.GetKind(), block.GetDirection(), block.GetPosition())); // 서버에 저장. m_blocks.push_back(block); } void CheckBlocks() { auto overflow = false; std::vector<bool> plane(MAX_WIDTH * MAX_HEIGHT); // 현재 쌓인 블록을 기준으로 bool vector 생성. auto it = m_blocks.begin(); const auto end = --m_blocks.end(); // 마지막 블럭은 현재 블럭(움직이고 있는 블럭)으로 취급함. while (it != end) { auto& b = *(it++); const auto& pos = b.GetPosition(); for (const auto& p : b.GetData().Data) { // 블럭이 XY 범위를 넘어간다면 게임 실패 조건 성립. // Y == 0인 경우 블럭이 천장에 닿은 경우이므로 이 경우도 게임 실패. if ((pos.Y + p.first.Y) > 0) { plane[(pos.Y + p.first.Y) * MAX_WIDTH + (pos.X + p.first.X)] = true; } else { overflow = true; } } } // 실패 조건 판별 // 블럭이 최고 높이에 도달하거나 초과함. if (overflow) { m_state = ConnectionState::GameOver; m_stream.SendEvent(GameOverEvent("Block overflow.")); } // 성공 조건 판별 // 구성면이 모두 블럭으로 참. auto succeed = true; for (auto i = (MAX_WIDTH * (MAX_HEIGHT - m_maxHeight)); i < (MAX_WIDTH * MAX_HEIGHT); i++) { succeed &= plane[i]; } if (succeed) { m_state = ConnectionState::GameOver; m_stream.SendEvent(GameOverEvent("You won!")); } } void MoveBlock(Key key) { auto& block = m_blocks.back(); // 복사본 하나 생성. auto pos = block.GetPosition(); auto delta = Position(); auto direction = block.GetDirection(); // 사용자 키 입력에 따라 블럭 변화 처리. switch (key) { case Key::Right: delta.X = 1; break; case Key::Left: delta.X = -1; break; case Key::Down: delta.Y = 1; break; case Key::Space: direction = (direction == BlockDirection::Horizontal) ? BlockDirection::Vertical : BlockDirection::Horizontal; break; default: return; } // 위에서 위치 데이터 반영한 새로운 블록 데이터 가져옴. auto& data = Block::GetData(block.GetKind(), direction); pos += delta; // 블록이 X 범위 밖으로 나가는 경우 위치 보정. if (pos.X < 0) { pos.X = 0; } if ((pos.X + data.Width) > MAX_WIDTH) { pos.X = MAX_WIDTH - data.Width; } if (pos.Y >= MAX_HEIGHT) { pos.Y = MAX_HEIGHT - 1; } // 옮길 위치가 이동 가능할 경우 현재 데이터에 반영하고 이벤트 전송. if (CanMove(pos, data)) { block.SetAbsolutePosition(pos); block.SetDirection(direction); MoveBlockEvent e(direction, pos); m_stream.SendEvent(e); std::printf("[thread %d] User pressed %d key. Move block to (%d,%d).\n", GetThreadID(), static_cast<int>(key), pos.X, pos.Y); } else if (delta.Y > 0) { // 움직일 수 없는 상태서 y 변위가 있을경우 바닥에 도달한 것으로 간주. // 새로운 블럭을 생성함. std::printf("[thread %d] Reached to the base(%d,%d). Create next block.\n", GetThreadID(), pos.X, pos.Y); SendCreateBlock(); } else { // 블럭을 움직 일 수 없음(디버깅용 메세지) std::printf("[thread %d] Cannot move block to (%d, %d). Ignore it.\n", GetThreadID(), pos.X, pos.Y); } // 현재 블록 상태 점검. CheckBlocks(); } // 타이머 이벤트. 사용자가 지정한 주기가 되면 이벤트가 발생함. void OnTimer() { // 현재 게임 상태에 따라 다르게 행동. switch (m_state) { // 게임 초기화 단계 case ConnectionState::GameInit: { int width = 0; int height = 0; // 현재까지의 블럭들을 순회하면서 최고 높이와 현재 폭을 계산함. for (const auto& block : m_blocks) { const auto& data = block.GetData(); width += data.Width; height = max(height, data.Height); } if (width == MAX_WIDTH) { // Building initial state complete. // Switch to GameStart state. m_maxHeight = height; m_state = ConnectionState::GameStart; m_stream.SendEvent(GameStartEvent()); SendCreateBlock(); } else { // 적합한 블럭을 생성할 때 까지 반복. while (true) { auto block = Block::GenerateRandomBlock(true); // 현재 남은 공간에 적합한 블럭인지 확인하고 // 적합한 경우 블럭 위치를 설정하고 블럭 생성 이벤트를 전송. if (block.GetData().Width <= (MAX_WIDTH - width)) { block.SetAbsolutePosition(Position(width, MAX_HEIGHT - 1)); m_blocks.push_back(block); m_stream.SendEvent(CreateBlockEvent(block.GetKind(), block.GetDirection(), block.GetPosition())); break; } } } break; } // 게임 시작 단계. case ConnectionState::GameStart: MoveBlock(Key::Down); break; default: // Ignore it. break; } } void OnKeyPress(const KeyPressEvent* event) { // 게임 시작 단계에서만 사용자 입력을 처리함. if (m_state != ConnectionState::GameStart) { std::printf("[thread %d] User pressed key but not in GameStart state. Ignore it.\n", GetThreadID()); } else { MoveBlock(event->GetKey()); } } void OnLogin(const LoginEvent* event) { // 로그인 상태서 로그인 이벤트 발생시 연결 해제(오류로 취급). if (m_state != ConnectionState::Login) { std::printf("[thread %d] User sent LoginEvent while logged in.\n", GetThreadID()); ServerDisconnectEvent event("you're already logged in."); m_stream.SendEvent(event); Disconnect(); } else { // 로그인 성공. 게임 초기화 단계로 넘어 감. std::printf("[thread %d] User %s logged in. (speed: %d)\n", GetThreadID(), event->GetName().c_str(), event->GetSpeed()); m_username = event->GetName(); m_tickBase = event->GetSpeed(); m_state = ConnectionState::GameInit; GameInitEvent event; m_stream.SendEvent(event); } } void OnClientDisconnect(const ClientDisconnectEvent* event) { // 클라이언트에서 연결 종료. 서버도 연결 종료함. std::printf("[thread %d] User disconnected. cause: %s\n", GetThreadID(), event->GetCuase().c_str()); Disconnect(); } public: ClientThread(Server& server, Socket socket) : m_socket(std::move(socket)), m_stream(m_socket) {} int Run() { assert(m_socket.IsConnected()); // Set random seed. srand(time(NULL)); m_tickCount = GetTickCount(); DWORD deltaSum = 0; while (m_connected) { auto current = GetTickCount(); auto delta = (current - m_tickCount); m_ticks += delta; deltaSum += delta; m_tickCount = current; // 정해진 주기에 도달하면 타이머 이벤트 호출. if (deltaSum > m_tickBase) { deltaSum = 0; OnTimer(); } // 이벤트가 들어 온 경우 이벤트 처리. if (m_socket.HasAcceptRequest()) { Event* event = nullptr; auto status = m_stream.ReceiveEvent(event); if (status == SocketStatus::Success) { // 클라이언트가 보낸 이벤트의 수신에 성공했다면 // 수신된 이벤트에 따라 이벤트 처리 코드 호출. switch (event->GetEventID()) { case EventID::KeyPress: OnKeyPress(static_cast<const KeyPressEvent*>(event)); break; case EventID::Login: OnLogin(static_cast<const LoginEvent*>(event)); break; case EventID::ClientDisconnect: OnClientDisconnect(static_cast<const ClientDisconnectEvent*>(event)); break; default: std::printf("[thread %d] user %s: Not-to-be-sent packet %d is received from client. Ignore it.\n", GetThreadID(), m_username.c_str(), static_cast<int>(event->GetEventID())); break; } delete event; } else { // 수신 실패. 연결 종료. std::printf("[thread %d] Connection error: %s\n", GetThreadID(), Socket::StatusToString(status)); Disconnect(); } } } return 0; } }; int Server::Start() { Socket listenSocket; std::string ip; unsigned short port; char buffer[16 + 1]; std::cout << "Server IP (default: localhost): "; std::cin.getline(buffer, sizeof(buffer)); if (buffer[0] != '\0') { ip.assign(buffer); } else { ip = "127.0.0.1"; } std::cout << "Server Port (default: 50000): "; std::cin.getline(buffer, sizeof(buffer)); if (buffer[0] != '\0') { port = std::atoi(buffer); } else { port = 50000; } auto status = listenSocket.Bind(ip.c_str(), port); if (status != SocketStatus::Success) { std::cout << "Socket error: " << Socket::StatusToString(status) << std::endl; return 0; } std::cout << "Created server on " << ip << ":" << port << std::endl; const auto searchFunction = [this](Thread* thread) -> bool { return !thread->IsRunning(); }; while (true) { // 클라이언트 접속 요청이 있으면 수락. if (listenSocket.HasAcceptRequest()) { auto thread = new ClientThread(*this, listenSocket.Accept()); m_threads.emplace(thread); thread->Start(); } // 종료된 스레드가 있으면 자원 정리. auto it = std::find_if(m_threads.begin(), m_threads.end(), searchFunction); while (it != m_threads.end()) { Thread* thread = *it; std::cout << "Removing terminated thread " << thread->GetThreadID() << std::endl; thread->Wait(); delete thread; it = m_threads.erase(it); it = std::find_if(it, m_threads.end(), searchFunction); } } return 0; }
[ "numver8638@naver.com" ]
numver8638@naver.com
693f0e9f11914c5ef612b791f053362cad11fa97
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/chrome/browser/android/offline_pages/offline_page_tab_helper.h
22ff4a148d1db2f201c57e451d954748580ddd62
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
4,589
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINE_PAGE_TAB_HELPER_H_ #define CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINE_PAGE_TAB_HELPER_H_ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/offline_pages/offline_page_types.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "url/gurl.h" namespace content { class WebContents; } namespace offline_pages { struct OfflinePageItem; // Per-tab class to manage switch between online version and offline version. class OfflinePageTabHelper : public content::WebContentsObserver, public content::WebContentsUserData<OfflinePageTabHelper> { public: // Delegate that is used to better handle external dependencies. // Default implementation is in .cc file, while tests provide an override. class Delegate { public: virtual ~Delegate() {} virtual bool GetTabId(content::WebContents* web_contents, std::string* tab_id) const = 0; }; // This enum is used for UMA reporting. It contains all possible outcomes of // redirect intent and result. Generally one of these outcomes will happen. // The fringe errors (like no OfflinePageModel, etc.) are not reported due // to their low probability. // NOTE: because this is used for UMA reporting, these values should not be // changed or reused; new values should be ended immediately before the MAX // value. Make sure to update the histogram enum // (OfflinePagesRedirectResult in histograms.xml) accordingly. // Public for testing. enum class RedirectResult { REDIRECTED_ON_DISCONNECTED_NETWORK = 0, PAGE_NOT_FOUND_ON_DISCONNECTED_NETWORK = 1, REDIRECTED_ON_FLAKY_NETWORK = 2, PAGE_NOT_FOUND_ON_FLAKY_NETWORK = 3, IGNORED_FLAKY_NETWORK_FORWARD_BACK = 4, REDIRECTED_ON_CONNECTED_NETWORK = 5, NO_TAB_ID = 6, SHOW_NET_ERROR_PAGE = 7, REDIRECT_LOOP_OFFLINE = 8, REDIRECT_LOOP_ONLINE = 9, REDIRECT_RESULT_MAX, }; ~OfflinePageTabHelper() override; const OfflinePageItem* offline_page() { return offline_page_.get(); } private: friend class content::WebContentsUserData<OfflinePageTabHelper>; friend class OfflinePageTabHelperTest; FRIEND_TEST_ALL_PREFIXES(OfflinePageTabHelperTest, NewNavigationCancelsPendingRedirects); explicit OfflinePageTabHelper(content::WebContents* web_contents); void SetDelegateForTesting(std::unique_ptr<Delegate> delegate); // Overridden from content::WebContentsObserver: void DidStartNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; void RedirectToOnline(const GURL& from_url, const OfflinePageItem* offline_page); // 3 step redirection to the offline page. First getting all the pages, then // selecting appropriate page to redirect to and finally attempting to // redirect to that offline page, and caching metadata of that page locally. // RedirectResult is accumulated along the codepath to reflect the overall // result of redirection - and be reported to UMA at the end. void GetPagesForRedirectToOffline(RedirectResult result, const GURL& online_url); void SelectBestPageForRedirectToOffline( RedirectResult result, const GURL& online_url, const MultipleOfflinePageItemResult& pages); void TryRedirectToOffline(RedirectResult result, const GURL& from_url, const OfflinePageItem& offline_page); void Redirect(const GURL& from_url, const GURL& to_url); // Returns true if a given URL is in redirect chain already. bool IsInRedirectLoop(const GURL& to_url) const; void ReportRedirectResultUMA(RedirectResult result); // Iff the tab we are associated with is redirected to an offline page, // |offline_page_| will be non-null. This can be used to synchronously ask // about the offline state of the current web contents. std::unique_ptr<OfflinePageItem> offline_page_; std::unique_ptr<Delegate> delegate_; base::WeakPtrFactory<OfflinePageTabHelper> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(OfflinePageTabHelper); }; } // namespace offline_pages #endif // CHROME_BROWSER_ANDROID_OFFLINE_PAGES_OFFLINE_PAGE_TAB_HELPER_H_
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
a5b4e57d6c8a0949442398ae6a22e7f669684ecb
3324b70597e57ac9f3ccaff859aff40852a513c6
/classwork/ParticleField/src/testApp.cpp
52f666e428d5dcc1d56038d919fa299595e5c7db
[]
no_license
oherterich/algo2013-owenherterich
0cc8aaa93318d026f627188fd6ba4e1f2cc23c16
0988b2dd821b44fca7216b4ec1eab365836dc381
refs/heads/master
2021-01-21T05:05:47.571780
2013-12-16T21:29:20
2013-12-16T21:29:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ myField.setup( ofGetWindowWidth(), ofGetWindowHeight(), 20 ); ofBackground(0); for (int i = 0; i < 500; i++) { addParticle(); } } //-------------------------------------------------------------- void testApp::update(){ for( int i = 0; i < particleList.size(); i++ ) { particleList[i].applyForce( myField.getForceAtPosition( particleList[i].pos ) * 0.005 ); particleList[i].update(); } myField.update(); } //-------------------------------------------------------------- void testApp::draw(){ for( int i = 0; i < particleList.size(); i++ ) { particleList[i].draw(); } myField.draw(); } void testApp::addParticle() { Particle tmp; tmp.pos = ofVec2f( ofRandomWidth(), ofRandomHeight() ); particleList.push_back( tmp ); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if( key == '1'){ myField.setRandom( 20.0 ); }else if( key == '2' ){ myField.setPerlin(); } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ if( button == OF_MOUSE_BUTTON_1 ){ // myField.addRepelForce(x, y, 100, 2.0); myField.addCircularForce(x, y, 300, 2.0); }else{ myField.addAttractForce(x, y, 100, 2.0); } } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ mouseDragged(x, y, button); } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
[ "oherterich@gmail.com" ]
oherterich@gmail.com
0ce5ae63add551a2a5577117f1bb8a8456d623ad
db5bba94cf3eae6f1a16b1e780aa36f4b8c3c2da
/r-kvstore/src/model/TagResourcesRequest.cc
28901f02465ddba3b3aec598bb42e2db93c363f9
[ "Apache-2.0" ]
permissive
chaomengnan/aliyun-openapi-cpp-sdk
42eb87a6119c25fd2d2d070a757b614a5526357e
bb7d12ae9db27f2d1b3ba7736549924ec8d9ef85
refs/heads/master
2020-07-25T00:15:29.526225
2019-09-12T15:34:29
2019-09-12T15:34:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,433
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/r-kvstore/model/TagResourcesRequest.h> using AlibabaCloud::R_kvstore::Model::TagResourcesRequest; TagResourcesRequest::TagResourcesRequest() : RpcServiceRequest("r-kvstore", "2015-01-01", "TagResources") {} TagResourcesRequest::~TagResourcesRequest() {} long TagResourcesRequest::getResourceOwnerId()const { return resourceOwnerId_; } void TagResourcesRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setCoreParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::vector<std::string> TagResourcesRequest::getResourceId()const { return resourceId_; } void TagResourcesRequest::setResourceId(const std::vector<std::string>& resourceId) { resourceId_ = resourceId; for(int i = 0; i!= resourceId.size(); i++) setCoreParameter("ResourceId."+ std::to_string(i), resourceId.at(i)); } std::string TagResourcesRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void TagResourcesRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setCoreParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string TagResourcesRequest::getRegionId()const { return regionId_; } void TagResourcesRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setCoreParameter("RegionId", regionId); } std::string TagResourcesRequest::getOwnerAccount()const { return ownerAccount_; } void TagResourcesRequest::setOwnerAccount(const std::string& ownerAccount) { ownerAccount_ = ownerAccount; setCoreParameter("OwnerAccount", ownerAccount); } std::vector<TagResourcesRequest::Tag> TagResourcesRequest::getTag()const { return tag_; } void TagResourcesRequest::setTag(const std::vector<Tag>& tag) { tag_ = tag; int i = 0; for(int i = 0; i!= tag.size(); i++) { auto obj = tag.at(i); std::string str ="Tag."+ std::to_string(i); setCoreParameter(str + ".Value", obj.value); setCoreParameter(str + ".Key", obj.key); } } long TagResourcesRequest::getOwnerId()const { return ownerId_; } void TagResourcesRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setCoreParameter("OwnerId", std::to_string(ownerId)); } std::string TagResourcesRequest::getResourceType()const { return resourceType_; } void TagResourcesRequest::setResourceType(const std::string& resourceType) { resourceType_ = resourceType; setCoreParameter("ResourceType", resourceType); } std::string TagResourcesRequest::getAccessKeyId()const { return accessKeyId_; } void TagResourcesRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setCoreParameter("AccessKeyId", accessKeyId); }
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
1cc2ce02d3e6fce501dbac598270bceade3bc7ab
0a30b9871858064844f4644121ac423244a95bb4
/EngineModeController.h
e0f5f2788c068bd9bccbd2a698d06b7dbbff3f6e
[ "Apache-2.0" ]
permissive
elsewhat/gtav-mod-battlechess
045a44b8171880ce325147a20b9a43343f57a1ca
76c5fef1337e45dc13b6447354ffe96a1099b22b
refs/heads/master
2021-06-23T14:18:45.506241
2017-09-05T20:45:50
2017-09-05T20:45:50
98,060,054
1
0
null
null
null
null
UTF-8
C++
false
false
292
h
#pragma once #include "inc\types.h" #include "ChessBoard.h" #include <vector> class EngineModeController { public: virtual void onEnterMode(ChessBoard* chessBoard)=0; virtual void onExitMode(ChessBoard* chessBoard)=0 ; virtual bool actionOnTick(DWORD tick, ChessBoard* chessBoard)=0; };
[ "dagfinn.parnas@gmail.com" ]
dagfinn.parnas@gmail.com
0516cf09ee4a486f2fc1d8da1201d376de9fe140
9989ec29859d067f0ec4c7b82e6255e227bd4b54
/atcoder.jp/abc_170/abc170_e.cpp
525e2763dc443538d56e5785de61e486d9043214
[]
no_license
hikko624/prog_contest
8fa8b0e36e4272b6ad56d6506577c13f9a11c9de
34350e2d298deb52c99680d72345ca44ab6f8849
refs/heads/master
2022-09-10T20:43:28.046873
2022-08-26T13:59:29
2022-08-26T13:59:29
217,740,540
0
0
null
null
null
null
UTF-8
C++
false
false
11
cpp
// abc170_e
[ "hikko624@gmail.com" ]
hikko624@gmail.com
274e1aaa64ddecdd8f6c38163ae2d4cc81f13e4d
ad1ce910ab5d9382a87bebd2480f73ecca4c37a5
/examples/bvp1d/simple3.cpp
0981c86ae15c616589ecf90dc1309d7c8dafb5c6
[ "MIT" ]
permissive
grenkin/joker-fdm
33fee3fff4aa948bd4ba82c7016227a84b3cc5d8
21d60479ca0dd7f2deb0d8ce000f79a7c53f3202
refs/heads/master
2020-04-09T04:14:21.820983
2018-09-21T02:04:35
2018-09-21T02:04:35
68,077,571
4
0
null
2016-10-14T21:30:28
2016-09-13T05:35:13
Matlab
UTF-8
C++
false
false
1,499
cpp
/* A simple linear problem in 1D -u''(x) = -2 on (0, 1) u(0) = 0, u'(1) + 2 * (u(1) - 2) = 0 Exact solution: u(x) = x ^ 2 */ #include <iostream> #include <vector> #include <cmath> #include <joker-fdm/bvp1d.h> using namespace std; double zero(double x) { return 0; } double gfun(double x) { return -2; } double exact(double x) { return x * x; } int main() { double L0 = 1; int K0 = 10; double rms_old; for (int test = 0; test <= 5; ++test) { vector<double> L(1); L[0] = L0; vector<int> K(1); K[0] = K0; Grid1D grid(L, K); Data1D data(1, grid); data.a[0][0] = 1; data.b[0][0] = INFINITY; data.w[0][0] = 0; data.b[0][1] = 2; data.w[0][1] = 4; data.f[0][0][0] = data.df[0][0][0] = zero; vector<GridFunction1D> sol(1); sol[0].set_grid(grid); for (int n = 0; n <= K0; ++n) { data.g[0](0, n) = gfun(grid.coord(0, n)); sol[0](0, n) = 0; } Parameters1D param; param.max_Newton_iterations = 1; SolveBVP1D(data, param, sol); double rms = 0; for (int n = 0; n <= K0; ++n) rms += pow(sol[0](0, n) - exact(grid.coord(0, n)), 2); rms = sqrt(rms / (K0 + 1)); cout << "h = " << grid.h[0] << endl; cout << "rms = " << rms << endl; if (test > 0) cout << "rms_old / rms = " << rms_old / rms << "\n\n"; rms_old = rms; K0 *= 2; } return 0; }
[ "glebgrenkin@gmail.com" ]
glebgrenkin@gmail.com
b0912f4e8a3aacb729fc3de5de3cbde661b38994
4ad2ec9e00f59c0e47d0de95110775a8a987cec2
/_HackerCup/2016/Round 1/Boomerang Tournament/Help/Brute/main.cpp
4b7b3efa2e975b229cfada78325791aa96021800
[]
no_license
atatomir/work
2f13cfd328e00275672e077bba1e84328fccf42f
e8444d2e48325476cfbf0d4cfe5a5aa1efbedce9
refs/heads/master
2021-01-23T10:03:44.821372
2021-01-17T18:07:15
2021-01-17T18:07:15
33,084,680
2
1
null
2015-08-02T20:16:02
2015-03-29T18:54:24
C++
UTF-8
C++
false
false
1,764
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <cmath> #include <queue> using namespace std; #define mp make_pair #define pb push_back #define maxN 20 int t, test, n, i, j; int better[maxN][maxN]; int ans[maxN][2]; int perm[maxN]; int point[maxN]; queue<int> Q; int main() { freopen("input.in","r",stdin); freopen("output.ok","w",stdout); scanf("%d", &t); for (test = 1; test <= t; test++) { scanf("%d", &n); for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) scanf("%d", &better[i][j]); if (n == 16) continue; for (i = 1; i <= n; i++) { ans[i][0] = 20; ans[i][1] = 0; } for (i = 1; i <= n; i++) perm[i] = i; do { while (!Q.empty()) Q.pop(); for (i = 1; i <= n; i++) { Q.push(perm[i]); point[i] = n / 2; } for (i = 1; i < n; i++) { int id1 = Q.front(); Q.pop(); int id2 = Q.front(); Q.pop(); if (better[id1][id2]) { point[id1] >>= 1; Q.push(id1); } else { point[id2] >>= 1; Q.push(id2); } } for (i = 1; i <= n; i++) { ans[i][0] = min(ans[i][0], point[i] + 1); ans[i][1] = max(ans[i][1], point[i] + 1); } } while (next_permutation(perm + 1, perm + n + 1)); printf("Case #%d: \n", test); for (i = 1; i <= n; i++) printf("%d %d\n", ans[i][0], ans[i][1]); printf("\n"); } return 0; }
[ "atatomir5@gmail.com" ]
atatomir5@gmail.com
316c527c9f8d2af83225cea89bb4422a61b2e6a5
33e1799b6f320f2ab17f41f39492aeaf60bcf969
/AgileFontSet/CEditImpl.h
55b36ce35eb82dddb5748804754b9e774a39e500
[]
no_license
patton88/AgileFontSet
feac17fb84e906e02db822ce14d71ddf37ba5358
da0e26865f76bd053fc23896ab4abd1247b6ac54
refs/heads/master
2020-08-15T11:38:50.691081
2019-10-16T02:25:28
2019-10-16T02:25:28
215,334,815
3
2
null
null
null
null
UTF-8
C++
false
false
1,323
h
// CEditImpl.h // ////////////////////////////////////////////////////////////////////////// #if !defined(AFX_CEditImpl_H__C84_E69_d49_i41_t05_I29_00007733__INCLUDED_) #define AFX_CEditImpl_H__C84_E69_d49_i41_t05_I29_00007733__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // CEditImpl - CWindowImpl-derived class that implements a button. We need a // class like this to do subclassing or DDX. class CEditImpl : public CWindowImpl<CEditImpl, CEdit> { public: CEditImpl(); virtual ~CEditImpl(); void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE); BEGIN_MSG_MAP(CEditImpl) MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseMessage) MSG_WM_MOUSEHOVER(OnMouseHover) MSG_WM_MOUSELEAVE(OnMouseLeave) END_MSG_MAP() LRESULT OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); void OnMouseHover(WPARAM wParam, CPoint point); void OnMouseLeave(); private: CToolTipCtrl m_toolTip; BOOL m_bHovering; void InitToolTip(); }; #endif // !defined(AFX_CEditImpl_H__C84_E69_d49_i41_t05_I29_00007733__INCLUDED_) ////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line.
[ "name2017@163.com" ]
name2017@163.com
0f12f0b2ad3525184b1198a04bd6f3755c3cc9ba
c0caed81b5b3e1498cbca4c1627513c456908e38
/src/core/pose/rna/BaseStack.cc
e32f15496a78bb46fbe35584ba5a8772b4387636
[]
no_license
malaifa/source
5b34ac0a4e7777265b291fc824da8837ecc3ee84
fc0af245885de0fb82e0a1144422796a6674aeae
refs/heads/master
2021-01-19T22:10:22.942155
2017-04-19T14:13:07
2017-04-19T14:13:07
88,761,668
0
2
null
null
null
null
UTF-8
C++
false
false
3,059
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file core/pose/rna/BaseStack.cc /// @brief /// @details /// @author Rhiju Das, rhiju@stanford.edu #include <core/pose/rna/BaseStack.hh> #include <basic/Tracer.hh> static basic::Tracer TR( "core.pose.rna.BaseStack" ); #ifdef SERIALIZATION // Utility serialization headers #include <utility/serialization/serialization.hh> // Cereal headers #include <cereal/types/polymorphic.hpp> #endif // SERIALIZATION namespace core { namespace pose { namespace rna { /////////////////////////////////////////////////////////////////// BaseStack::BaseStack(): res1_( 0 ), res2_( 0 ), orientation_( ANY_BASE_DOUBLET_ORIENTATION ), which_side_( ANY_BASE_STACK_SIDE ) { } /////////////////////////////////////////////////////////////////// bool operator < ( BaseStack const & lhs, BaseStack const & rhs ){ //There must be a more elegant way to do this... if ( lhs.res1_ < rhs.res1_ ) { return true; } else if ( lhs.res1_ == rhs.res1_ ) { if ( lhs.res2_ < rhs.res2_ ) { return true; } else if ( lhs.res2_ == rhs.res2_ ) { if ( lhs.orientation_ < rhs.orientation_ ) { return true; } else if ( lhs.orientation_ == rhs.orientation_ ) { return ( lhs.which_side_ < rhs.which_side_ ); } } } return false; } /////////////////////////////////////////////////////////////////// std::ostream & operator << ( std::ostream & out, BaseStack const & s ) { out << s.res1_ << " " << s.res2_ << " " << get_full_orientation_from_num( s.orientation_ ) << " " << get_full_side_from_num( s.which_side_ ); return out; } } //rna } //pose } //core #ifdef SERIALIZATION /// @brief Automatically generated serialization method template< class Archive > void core::pose::rna::BaseStack::save( Archive & arc ) const { arc( CEREAL_NVP( res1_ ) ); // Size arc( CEREAL_NVP( res2_ ) ); // Size arc( CEREAL_NVP( orientation_ ) ); // enum core::chemical::rna::BaseDoubletOrientation arc( CEREAL_NVP( which_side_ ) ); // enum core::chemical::rna::BaseStackWhichSide } /// @brief Automatically generated deserialization method template< class Archive > void core::pose::rna::BaseStack::load( Archive & arc ) { arc( res1_ ); // Size arc( res2_ ); // Size arc( orientation_ ); // enum core::chemical::rna::BaseDoubletOrientation arc( which_side_ ); // enum core::chemical::rna::BaseStackWhichSide } SAVE_AND_LOAD_SERIALIZABLE( core::pose::rna::BaseStack ); CEREAL_REGISTER_TYPE( core::pose::rna::BaseStack ) CEREAL_REGISTER_DYNAMIC_INIT( core_pose_rna_BaseStack ) #endif // SERIALIZATION
[ "malaifa@yahoo.com" ]
malaifa@yahoo.com
05ac0ff5e12159682345386089de99a1129b2f05
e9025d80026f7d00e0fd69e0ee7e0f97533bd630
/400/round494/C.cpp
a6ae38014c679ad27cb8d0d4606ce2d4d3c9f31a
[]
no_license
rishup132/Codeforces-Solutions
66170b368d851b7076c03f42c9463a2342bac5df
671d16b0beec519b99fc79058ab9035c6f956670
refs/heads/master
2020-04-12T04:32:10.451666
2019-03-22T14:04:31
2019-03-22T14:04:31
162,298,347
0
0
null
null
null
null
UTF-8
C++
false
false
569
cpp
#include <bits/stdc++.h> #define ll long long #define mod 1000000007 using namespace std; int a[100010]; int main() { int n,k; cin >> n >> k; a[0] = 0; for(int i=1;i<=n;i++) cin >> a[i]; for(int i=1;i<=n;i++) a[i] += a[i-1]; double ans = 0; while(k <= n) { for(int i=0;i<=n-k;i++) { double temp = a[k+i] - a[i]; temp = temp/k; if(ans < temp) ans = temp; } k++; } cout << setprecision(15) << ans << endl; }
[ "rishupgupta132@gmail.com" ]
rishupgupta132@gmail.com
b3f9484513d7ec0aa13ff5bb8df6608c8804429e
def39f068050b234df9f6909d4277f96b740f11c
/E-olimp/1287. Tennis competitions .cpp
9c83eb1c033c9119a8fc356f951dd46b8d979f90
[]
no_license
azecoder/Problem-Solving
41a9a4302c48c8de59412ab9175b253df99f1f28
a920b7bac59830c7b798127f6eed0e2ab31a5fa2
refs/heads/master
2023-02-10T09:47:48.322849
2021-01-05T14:14:09
2021-01-05T14:14:09
157,236,604
5
1
null
null
null
null
UTF-8
C++
false
false
188
cpp
#include <stdio.h> #include <stdlib.h> unsigned long long a,b,s; int main(int argc, char *argv[]) { scanf("%llu %llu", &a,&b); s=a*b; printf("%llu\n", s); return 0; }
[ "tabriz.haji@gmail.com" ]
tabriz.haji@gmail.com
141658ca8d66785c12266583b5887e68e82be27d
410e45283cf691f932b07c5fdf18d8d8ac9b57c3
/chrome/browser/chromeos/policy/status_uploader_unittest.cc
a314bb8cc899b4ad25348722d273d25a7f2643ce
[ "BSD-3-Clause" ]
permissive
yanhuashengdian/chrome_browser
f52a7f533a6b8417e19b85f765f43ea63307a1fb
972d284a9ffa4b794f659f5acc4116087704394c
refs/heads/master
2022-12-21T03:43:07.108853
2019-04-29T14:20:05
2019-04-29T14:20:05
184,068,841
0
2
BSD-3-Clause
2022-12-17T17:35:55
2019-04-29T12:40:27
null
UTF-8
C++
false
false
15,487
cc
// Copyright (c) 2015 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/policy/status_uploader.h" #include <utility> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/run_loop.h" #include "base/test/test_simple_task_runner.h" #include "base/time/time.h" #include "chrome/browser/chromeos/policy/device_local_account.h" #include "chrome/browser/chromeos/policy/status_collector/device_status_collector.h" #include "chrome/browser/chromeos/settings/scoped_testing_cros_settings.h" #include "chrome/browser/chromeos/settings/stub_cros_settings_provider.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/settings/cros_settings_names.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "components/policy/core/common/cloud/mock_device_management_service.h" #include "components/prefs/testing_pref_service.h" #include "components/session_manager/core/session_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "net/url_request/url_request_context_getter.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/user_activity/user_activity_detector.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/platform/platform_event_source.h" #include "ui/events/platform_event.h" using ::testing::_; using ::testing::Invoke; using ::testing::Return; using ::testing::SaveArg; using ::testing::WithArgs; namespace em = enterprise_management; namespace { constexpr base::TimeDelta kDefaultStatusUploadDelay = base::TimeDelta::FromHours(1); constexpr base::TimeDelta kMinImmediateUploadInterval = base::TimeDelta::FromSeconds(10); // Using a DeviceStatusCollector to have a concrete StatusCollector, but the // exact type doesn't really matter, as it is being mocked. class MockDeviceStatusCollector : public policy::DeviceStatusCollector { public: explicit MockDeviceStatusCollector(PrefService* local_state) : DeviceStatusCollector( local_state, nullptr, policy::DeviceStatusCollector::VolumeInfoFetcher(), policy::DeviceStatusCollector::CPUStatisticsFetcher(), policy::DeviceStatusCollector::CPUTempFetcher(), policy::DeviceStatusCollector::AndroidStatusFetcher(), policy::DeviceStatusCollector::TpmStatusFetcher(), policy::DeviceStatusCollector::EMMCLifetimeFetcher(), base::TimeDelta(), /* Day starts at midnight */ true /* is_enterprise_device */) {} MOCK_METHOD1(GetStatusAsync, void(const policy::StatusCollectorCallback&)); MOCK_METHOD0(OnSubmittedSuccessfully, void()); // Explicit mock implementation declared here, since gmock::Invoke can't // handle returning non-moveable types like scoped_ptr. std::unique_ptr<policy::DeviceLocalAccount> GetAutoLaunchedKioskSessionInfo() override { return std::make_unique<policy::DeviceLocalAccount>( policy::DeviceLocalAccount::TYPE_KIOSK_APP, "account_id", "app_id", "update_url"); } }; } // namespace namespace policy { class StatusUploaderTest : public testing::Test { public: StatusUploaderTest() : task_runner_(new base::TestSimpleTaskRunner()) { DeviceStatusCollector::RegisterPrefs(prefs_.registry()); } void SetUp() override { // Required for policy::DeviceStatusCollector chromeos::DBusThreadManager::Initialize(); chromeos::CryptohomeClient::InitializeFake(); chromeos::PowerManagerClient::InitializeFake(); client_.SetDMToken("dm_token"); collector_.reset(new MockDeviceStatusCollector(&prefs_)); // Keep a pointer to the mock collector because collector_ gets cleared // when it is passed to the StatusUploader constructor. collector_ptr_ = collector_.get(); } void TearDown() override { content::RunAllTasksUntilIdle(); chromeos::PowerManagerClient::Shutdown(); chromeos::CryptohomeClient::Shutdown(); chromeos::DBusThreadManager::Shutdown(); } // Given a pending task to upload status, runs the task and returns the // callback waiting to get device status / session status. The status upload // task will be blocked until the test code calls that callback. StatusCollectorCallback CollectStatusCallback() { // Running the task should pass a callback into // GetStatusAsync. We'll grab this callback. EXPECT_TRUE(task_runner_->HasPendingTask()); StatusCollectorCallback status_callback; EXPECT_CALL(*collector_ptr_, GetStatusAsync) .WillOnce(SaveArg<0>(&status_callback)); task_runner_->RunPendingTasks(); testing::Mock::VerifyAndClearExpectations(&device_management_service_); return status_callback; } // Given a pending task to upload status, mocks out a server response. void RunPendingUploadTaskAndCheckNext(const StatusUploader& uploader, base::TimeDelta expected_delay, bool upload_success) { StatusCollectorCallback status_callback = CollectStatusCallback(); // Running the status collected callback should trigger // CloudPolicyClient::UploadDeviceStatus. CloudPolicyClient::StatusCallback callback; EXPECT_CALL(client_, UploadDeviceStatus).WillOnce(SaveArg<3>(&callback)); // Send some "valid" (read: non-nullptr) device/session data to the // callback in order to simulate valid status data. StatusCollectorParams status_params; status_callback.Run(std::move(status_params)); testing::Mock::VerifyAndClearExpectations(&device_management_service_); // Make sure no status upload is queued up yet (since an upload is in // progress). EXPECT_FALSE(task_runner_->HasPendingTask()); // StatusUpdater is only supposed to tell DeviceStatusCollector to clear its // caches if the status upload succeeded. EXPECT_CALL(*collector_ptr_, OnSubmittedSuccessfully()) .Times(upload_success ? 1 : 0); // Now invoke the response. callback.Run(upload_success); // Now that the previous request was satisfied, a task to do the next // upload should be queued. EXPECT_EQ(1U, task_runner_->NumPendingTasks()); CheckPendingTaskDelay(uploader, expected_delay, task_runner_->NextPendingTaskDelay()); } void CheckPendingTaskDelay(const StatusUploader& uploader, base::TimeDelta expected_delay, base::TimeDelta task_delay) { // The next task should be scheduled sometime between |last_upload| + // |expected_delay| and |now| + |expected_delay|. base::Time now = base::Time::NowFromSystemTime(); base::Time next_task = now + task_delay; EXPECT_LE(next_task, now + expected_delay); EXPECT_GE(next_task, uploader.last_upload() + expected_delay); } std::unique_ptr<StatusUploader> CreateStatusUploader() { return std::make_unique<StatusUploader>(&client_, std::move(collector_), task_runner_, kDefaultStatusUploadDelay); } content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<base::TestSimpleTaskRunner> task_runner_; chromeos::ScopedTestingCrosSettings scoped_testing_cros_settings_; std::unique_ptr<MockDeviceStatusCollector> collector_; MockDeviceStatusCollector* collector_ptr_; ui::UserActivityDetector detector_; MockCloudPolicyClient client_; MockDeviceManagementService device_management_service_; TestingPrefServiceSimple prefs_; // This property is required to instantiate the session manager, a singleton // which is used by the device status collector. session_manager::SessionManager session_manager_; }; TEST_F(StatusUploaderTest, BasicTest) { EXPECT_FALSE(task_runner_->HasPendingTask()); auto uploader = CreateStatusUploader(); EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // On startup, first update should happen in 1 minute. EXPECT_EQ(base::TimeDelta::FromMinutes(1), task_runner_->NextPendingTaskDelay()); } TEST_F(StatusUploaderTest, DifferentFrequencyAtStart) { const base::TimeDelta new_delay = kDefaultStatusUploadDelay * 2; scoped_testing_cros_settings_.device_settings()->SetInteger( chromeos::kReportUploadFrequency, new_delay.InMilliseconds()); EXPECT_FALSE(task_runner_->HasPendingTask()); auto uploader = CreateStatusUploader(); ASSERT_EQ(1U, task_runner_->NumPendingTasks()); // On startup, first update should happen in 1 minute. EXPECT_EQ(base::TimeDelta::FromMinutes(1), task_runner_->NextPendingTaskDelay()); // Second update should use the delay specified in settings. RunPendingUploadTaskAndCheckNext(*uploader, new_delay, true /* upload_success */); } TEST_F(StatusUploaderTest, ResetTimerAfterStatusCollection) { auto uploader = CreateStatusUploader(); RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay, true /* upload_success */); // Handle this response also, and ensure new task is queued. RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay, true /* upload_success */); // Now that the previous request was satisfied, a task to do the next // upload should be queued again. EXPECT_EQ(1U, task_runner_->NumPendingTasks()); } TEST_F(StatusUploaderTest, ResetTimerAfterFailedStatusCollection) { auto uploader = CreateStatusUploader(); // Running the queued task should pass a callback into // GetStatusAsync. We'll grab this callback and send nullptrs // to it in order to simulate failure to get status. EXPECT_EQ(1U, task_runner_->NumPendingTasks()); StatusCollectorCallback status_callback; EXPECT_CALL(*collector_ptr_, GetStatusAsync) .WillOnce(SaveArg<0>(&status_callback)); task_runner_->RunPendingTasks(); testing::Mock::VerifyAndClearExpectations(&device_management_service_); // Running the callback should trigger StatusUploader::OnStatusReceived, which // in turn should recognize the failure to get status and queue another status // upload. StatusCollectorParams status_params; status_params.device_status.reset(); status_params.session_status.reset(); status_params.child_status.reset(); status_callback.Run(std::move(status_params)); EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // Check the delay of the queued upload CheckPendingTaskDelay(*uploader, kDefaultStatusUploadDelay, task_runner_->NextPendingTaskDelay()); } TEST_F(StatusUploaderTest, ResetTimerAfterUploadError) { auto uploader = CreateStatusUploader(); // Simulate upload error RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay, false /* upload_success */); // Now that the previous request was satisfied, a task to do the next // upload should be queued again. EXPECT_EQ(1U, task_runner_->NumPendingTasks()); } TEST_F(StatusUploaderTest, ResetTimerAfterUnregisteredClient) { auto uploader = CreateStatusUploader(); client_.SetDMToken(""); EXPECT_FALSE(client_.is_registered()); StatusCollectorCallback status_callback = CollectStatusCallback(); // Make sure no status upload is queued up yet (since an upload is in // progress). EXPECT_FALSE(task_runner_->HasPendingTask()); // StatusUploader should not try to upload using an unregistered client EXPECT_CALL(client_, UploadDeviceStatus).Times(0); StatusCollectorParams status_params; status_callback.Run(std::move(status_params)); // A task to try again should be queued. ASSERT_EQ(1U, task_runner_->NumPendingTasks()); CheckPendingTaskDelay(*uploader, kDefaultStatusUploadDelay, task_runner_->NextPendingTaskDelay()); } TEST_F(StatusUploaderTest, ChangeFrequency) { auto uploader = CreateStatusUploader(); // Change the frequency. The new frequency should be reflected in the timing // used for the next callback. const base::TimeDelta new_delay = kDefaultStatusUploadDelay * 2; scoped_testing_cros_settings_.device_settings()->SetInteger( chromeos::kReportUploadFrequency, new_delay.InMilliseconds()); RunPendingUploadTaskAndCheckNext(*uploader, new_delay, true /* upload_success */); } TEST_F(StatusUploaderTest, NoUploadAfterUserInput) { auto uploader = CreateStatusUploader(); // Should allow data upload before there is user input. EXPECT_TRUE(uploader->IsSessionDataUploadAllowed()); // Now mock user input, and no session data should be allowed. ui::MouseEvent e(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), 0, 0); const ui::PlatformEvent& native_event = &e; ui::UserActivityDetector::Get()->DidProcessEvent(native_event); EXPECT_FALSE(uploader->IsSessionDataUploadAllowed()); } TEST_F(StatusUploaderTest, NoUploadAfterVideoCapture) { auto uploader = CreateStatusUploader(); // Should allow data upload before there is video capture. EXPECT_TRUE(uploader->IsSessionDataUploadAllowed()); // Now mock video capture, and no session data should be allowed. MediaCaptureDevicesDispatcher::GetInstance()->OnMediaRequestStateChanged( 0, 0, 0, GURL("http://www.google.com"), blink::MEDIA_DEVICE_VIDEO_CAPTURE, content::MEDIA_REQUEST_STATE_OPENING); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(uploader->IsSessionDataUploadAllowed()); } TEST_F(StatusUploaderTest, ScheduleImmediateStatusUpload) { EXPECT_FALSE(task_runner_->HasPendingTask()); auto uploader = CreateStatusUploader(); EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // On startup, first update should happen in 1 minute. EXPECT_EQ(base::TimeDelta::FromMinutes(1), task_runner_->NextPendingTaskDelay()); // Schedule an immediate status upload. uploader->ScheduleNextStatusUploadImmediately(); EXPECT_EQ(2U, task_runner_->NumPendingTasks()); CheckPendingTaskDelay(*uploader, base::TimeDelta(), task_runner_->FinalPendingTaskDelay()); } TEST_F(StatusUploaderTest, ScheduleImmediateStatusUploadConsecutively) { EXPECT_FALSE(task_runner_->HasPendingTask()); auto uploader = CreateStatusUploader(); EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // On startup, first update should happen in 1 minute. EXPECT_EQ(base::TimeDelta::FromMinutes(1), task_runner_->NextPendingTaskDelay()); // Schedule an immediate status upload and run it. uploader->ScheduleNextStatusUploadImmediately(); RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay, true /* upload_success */); // Schedule the next one and check that it was scheduled after // kMinImmediateUploadInterval of the last upload. uploader->ScheduleNextStatusUploadImmediately(); EXPECT_EQ(2U, task_runner_->NumPendingTasks()); CheckPendingTaskDelay(*uploader, kMinImmediateUploadInterval, task_runner_->FinalPendingTaskDelay()); } } // namespace policy
[ "279687673@qq.com" ]
279687673@qq.com
4a208e8573be0e7e3756e974dce9e91e6aad8806
5e5d31a6fb5b5601e4ca0ed7f464ca6d796a761f
/test/core/xds/xds_channel_stack_modifier_test.cc
e50bf38ac14b47b04efa031d1bb4653ecd81114f
[ "Apache-2.0", "BSD-3-Clause", "MPL-2.0" ]
permissive
nicolasnoble/grpc
9a48fc3a325a8f0756faeab3bf4d2b6a4d776802
f36e84f093e7bf3cc7bab48a1e07a1a77b6b87c8
refs/heads/master
2022-06-24T03:12:37.104839
2022-05-04T21:41:56
2022-05-04T21:41:56
31,379,436
2
2
Apache-2.0
2022-05-20T19:28:00
2015-02-26T17:32:10
C++
UTF-8
C++
false
false
6,272
cc
// // // Copyright 2021 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #include "src/core/ext/xds/xds_channel_stack_modifier.h" #include <gtest/gtest.h> #include <grpcpp/opencensus.h> #include "src/core/lib/channel/channel_stack_builder_impl.h" #include "src/core/lib/config/core_configuration.h" #include "src/core/lib/surface/channel_init.h" #include "src/core/lib/transport/transport_impl.h" #include "test/core/util/test_config.h" namespace grpc_core { namespace testing { namespace { // Test that XdsChannelStackModifier can be safely copied to channel args // and destroyed TEST(XdsChannelStackModifierTest, CopyChannelArgs) { grpc_init(); auto channel_stack_modifier = MakeRefCounted<XdsChannelStackModifier>( std::vector<const grpc_channel_filter*>{}); grpc_arg arg = channel_stack_modifier->MakeChannelArg(); grpc_channel_args* args = grpc_channel_args_copy_and_add(nullptr, &arg, 1); EXPECT_EQ(channel_stack_modifier, XdsChannelStackModifier::GetFromChannelArgs(*args)); grpc_channel_args_destroy(args); grpc_shutdown(); } // Test compare on channel args with the same XdsChannelStackModifier TEST(XdsChannelStackModifierTest, ChannelArgsCompare) { grpc_init(); auto channel_stack_modifier = MakeRefCounted<XdsChannelStackModifier>( std::vector<const grpc_channel_filter*>{}); grpc_arg arg = channel_stack_modifier->MakeChannelArg(); grpc_channel_args* args = grpc_channel_args_copy_and_add(nullptr, &arg, 1); grpc_channel_args* new_args = grpc_channel_args_copy(args); EXPECT_EQ(XdsChannelStackModifier::GetFromChannelArgs(*new_args), XdsChannelStackModifier::GetFromChannelArgs(*args)); grpc_channel_args_destroy(args); grpc_channel_args_destroy(new_args); grpc_shutdown(); } constexpr char kTestFilter1[] = "test_filter_1"; constexpr char kTestFilter2[] = "test_filter_2"; // Test filters insertion TEST(XdsChannelStackModifierTest, XdsHttpFiltersInsertion) { CoreConfiguration::Reset(); grpc_init(); // Add 2 test filters to XdsChannelStackModifier const grpc_channel_filter test_filter_1 = { nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, kTestFilter1}; const grpc_channel_filter test_filter_2 = { nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, kTestFilter2}; auto channel_stack_modifier = MakeRefCounted<XdsChannelStackModifier>( std::vector<const grpc_channel_filter*>{&test_filter_1, &test_filter_2}); grpc_arg arg = channel_stack_modifier->MakeChannelArg(); // Create a phony ChannelStackBuilder object grpc_channel_args* args = grpc_channel_args_copy_and_add(nullptr, &arg, 1); ChannelStackBuilderImpl builder("test", GRPC_SERVER_CHANNEL); builder.SetChannelArgs(ChannelArgs::FromC(args)); grpc_channel_args_destroy(args); grpc_transport_vtable fake_transport_vtable; memset(&fake_transport_vtable, 0, sizeof(grpc_transport_vtable)); fake_transport_vtable.name = "fake"; grpc_transport fake_transport = {&fake_transport_vtable}; builder.SetTransport(&fake_transport); // Construct channel stack and verify that the test filters were successfully // added ASSERT_TRUE(CoreConfiguration::Get().channel_init().CreateStack(&builder)); std::vector<std::string> filters; for (const auto& entry : *builder.mutable_stack()) { filters.push_back(entry->name); } filters.resize(3); EXPECT_EQ(filters, std::vector<std::string>({"server", kTestFilter1, kTestFilter2})); grpc_shutdown(); } // Test filters insertion with OpenCensus plugin registered TEST(XdsChannelStackModifierTest, XdsHttpFiltersInsertionAfterCensus) { CoreConfiguration::Reset(); grpc::RegisterOpenCensusPlugin(); grpc_init(); // Add 2 test filters to XdsChannelStackModifier const grpc_channel_filter test_filter_1 = { nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, kTestFilter1}; const grpc_channel_filter test_filter_2 = { nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr, nullptr, kTestFilter2}; auto channel_stack_modifier = MakeRefCounted<XdsChannelStackModifier>( std::vector<const grpc_channel_filter*>{&test_filter_1, &test_filter_2}); grpc_arg arg = channel_stack_modifier->MakeChannelArg(); // Create a phony ChannelStackBuilder object grpc_channel_args* args = grpc_channel_args_copy_and_add(nullptr, &arg, 1); ChannelStackBuilderImpl builder("test", GRPC_SERVER_CHANNEL); builder.SetChannelArgs(ChannelArgs::FromC(args)); grpc_channel_args_destroy(args); grpc_transport_vtable fake_transport_vtable; memset(&fake_transport_vtable, 0, sizeof(grpc_transport_vtable)); fake_transport_vtable.name = "fake"; grpc_transport fake_transport = {&fake_transport_vtable}; builder.SetTransport(&fake_transport); // Construct channel stack and verify that the test filters were successfully // added after the census filter ASSERT_TRUE(CoreConfiguration::Get().channel_init().CreateStack(&builder)); std::vector<std::string> filters; for (const auto& entry : *builder.mutable_stack()) { filters.push_back(entry->name); } filters.resize(4); EXPECT_EQ(filters, std::vector<std::string>({"server", "opencensus_server", kTestFilter1, kTestFilter2})); grpc_shutdown(); } } // namespace } // namespace testing } // namespace grpc_core int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); grpc::testing::TestEnvironment env(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
[ "noreply@github.com" ]
nicolasnoble.noreply@github.com
79c99df916e7fbed2f50cbbf9cedc2380dc55b02
a565193016f9b08ff3131420bd8e4571827fa969
/b4-hack/fb/core/RelocArray.h
4f8213460531ae686fbba7e604b1ae0027c2906d
[]
no_license
APPLlCATLON/bf4-booster
f257fd11af7fbf6ac19eac7b7b46e531f9d5bd8f
ddcfad778ecd4b01f3cd2ca40ea6c9aaf63922e4
refs/heads/master
2020-05-29T10:10:24.455441
2013-12-07T16:11:27
2013-12-07T16:11:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
459
h
#ifndef __RELOCARRAY_H__ #define __RELOCARRAY_H__ #include "../../fb2_classes.h" #include "../../fb2_offsets.h" #include <Windows.h> namespace fb { template< class T > class RelocArray { public: unsigned int size() { return m_count; } T at( int idx ) { return *( T* )( ( DWORD )m_data + ( idx * sizeof( T ) ) ); } T operator [] ( int idx ) { return at( idx ); } private: unsigned int m_count; T* m_data; }; }; #endif
[ "karl@skomski.com" ]
karl@skomski.com
ff83a831f93208e5ba592676e880cb44c9a529a0
968ad92cc0b69ec1fb0225f8c6912443e63cc260
/algorithms/implementation/ManasaAndStones.cpp
3fb64267a842b61f4fc0f1b089264729d8a2842e
[]
no_license
duonghdo/hackerrank
ba4c529ae08d58a23daca751c92d605ca69acfea
0299a2d30b8083f2ec7a5636ae8584e948c77e03
refs/heads/master
2021-01-10T20:09:49.396319
2015-11-23T05:14:32
2015-11-23T05:14:32
40,314,113
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
#include <iostream> using namespace std; int main(){ int t; cin >> t; while(t--){ int n, a, b; cin >> n >> a >> b; for(int i = 0; i < n; i++){ if(a == b) { cout << a*(n-i-1); break; } else if(a > b) cout << (i*a + (n-i-1)*b) << " "; else cout << (i*b + (n-i-1)*a) << " "; } cout << endl; } return 0; }
[ "duonghdo@users.noreply.github.com" ]
duonghdo@users.noreply.github.com
bddc2cb7c0d402edbb1e62b3e7e50e9c6f97bb17
92756269d7ba6a7c0a57ba8fcc1fd5f17cfba88f
/source/dialog_createtask.cpp
baae82be57eca827bb8fc6532bc289c96f0808d0
[]
no_license
kapiten79/timecontrol
1a2ee54986029dd21e7109ad7aa3c90d2d2b4755
59b70fb99e105f8f7552b046dfbec003080e528f
refs/heads/master
2020-04-05T15:44:05.397613
2018-11-10T12:51:32
2018-11-10T12:51:32
156,981,274
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
#include "dialog_createtask.h" #include "ui_dialog_createtask.h" Dialog_createTask::Dialog_createTask(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog_createTask) { ui->setupUi(this); ui->lineEdit->setFocus(); } Dialog_createTask::~Dialog_createTask() { delete ui; } /* Инициализируем параметры окна */ void Dialog_createTask::init_windowParams() { qDebug() << "Функция Dialog_createTask::init_windowParams() запустилась"; this->open(); ui->label->setText(labelText); qDebug() << labelText; } /* Нажатие кнопки OK в диалоге */ void Dialog_createTask::on_buttonBox_accepted() { emit nameEntered(ui->lineEdit->text()); ui->lineEdit->clear(); }
[ "mihon79@inbox.ru" ]
mihon79@inbox.ru
52fbda7db6da184f367d5eb886d598805f740838
f89e7d3912e37dd46bb1f9ca4f955864c91a3ae9
/client/Views/Panel.h
f97f2dd824b8990ddc33c08d0a5aeca3f90a2901
[]
no_license
hilgenberg/amoc
5eb78bd233e2b9fc806831fe23100488c29b27cb
99df710a12e623c9c80206f91fb3331d3d88ac3c
refs/heads/master
2023-02-17T17:28:05.085161
2023-02-12T14:27:50
2023-02-12T14:27:50
82,281,215
3
0
null
null
null
null
UTF-8
C++
false
false
1,837
h
#pragma once #include <ncurses.h> #include "../../playlist.h" #include "../Util/Rect.h" #include "View.h" enum menu_request { REQ_UP, REQ_DOWN, REQ_XUP, REQ_XDOWN, REQ_SCROLL_UP, REQ_SCROLL_DOWN, REQ_PGUP, REQ_PGDOWN, REQ_TOP, REQ_BOTTOM, REQ_COLLAPSE // collapse multi-selection to a single selection }; class Interface; //--------------------------------------------------------------- // Panel draws the playlist views and handles selection, current // song mark and various events. Closely related to FrameView. //--------------------------------------------------------------- struct Panel : public View { // c'tor gets called before the interface is running! Panel(Interface &iface, plist &items) : iface(iface), items(items) , top(0), sel(-1), xsel(0), mark(-1) , layout{.c0 = -1 } {} void set_active(bool a) { active = a; } void draw() const override; // no frame, draws just the inside void update_layout() { layout.c0 = -1; } void move_selection(menu_request req); bool handle_click(int x, int y, bool dbl) override; bool mark_path(const str &f); // or unmark if not found void mark_item(int i, bool take_sel = true); // this and mark_path take the selection along if sel==mark bool select_path(const str &f); // leave selection as is if not found void select_item(int i); bool item_visible (int i) const { return i >= top && i < top + bounds.h; }; Interface &iface; plist &items; Rect bounds; bool active; mutable int top; // first visible item mutable int sel, mark; // selected and marked items, -1 if none mutable int xsel; // if != 0: multi-sel from sel to sel+xsel (both inclusive) mutable struct{ int c0,c1,c2,cn; bool hide_artist, hide_album; bool too_small; bool readtags; int prefix_len; #ifndef NDEBUG int rows; #endif } layout; };
[ "th@zoon.cc" ]
th@zoon.cc
1ce209b337816ebf2a7cc25df40b85131d197e94
81f2b85a9542b8fd365b44d0caa39f2fb6f8e122
/GPE/unfinish/24731 Roads in the North.cpp
9f93b16e2fac99998531750c44a2d1117009b25e
[]
no_license
setsal/coding
c66aa55e43805240c95e1c4f330f08b0fb0df7ba
7ee094b8b680107efe88a0abb3aba5c18d148665
refs/heads/master
2023-08-26T20:03:03.723747
2021-09-24T18:04:14
2021-09-24T18:04:14
298,565,963
3
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
/* Problem: 24731: Roads in the North subs: 247, ACs: 53, AcceptRate: 21.46, onsite: 16, access: 2213 Link: https://gpe3.acm-icpc.tw/showproblemtab.php?probid=24731&cid=5 */
[ "contact@setsal.dev" ]
contact@setsal.dev
b4054b86edb917dff88bb1e08663ea78b8b0bb66
5dc4ea36514927efd678638e2095a4e8e32c0386
/NPSVisor/tools/svLabelMaker/source/svmRule.cpp
5e5452adf90dcc5c2620d4e9faf0cbce0e46e60d
[ "Unlicense" ]
permissive
NPaolini/NPS_OpenSource
732173afe958f9549af13bc39b15de79e5d6470c
0c7da066b02b57ce282a1903a3901a563d04a28f
refs/heads/main
2023-03-15T09:34:19.674662
2021-03-13T13:22:00
2021-03-13T13:22:00
342,852,203
0
0
null
null
null
null
UTF-8
C++
false
false
6,771
cpp
//------------------ svmRule.cpp ---------------------------- //----------------------------------------------------------- #include "precHeader.h" //----------------------------------------------------------- #include "svmRule.h" #include "common.h" //----------------------------------------------------------- //----------------------------------------------------------- void mdcCustom::clear() { if(mdc) { SetBkMode(mdc, oldMode); SetBkColor(mdc, oldBkg); SetTextColor(mdc, oldColor); SetTextAlign(mdc, oldAlign); SelectObject(mdc, oldPen); SelectObject(mdc, oldBmp); SetGraphicsMode(mdc, GM_COMPATIBLE); DeleteDC(mdc); DeleteObject(hBmpTmp); DeleteObject(bkg); mdc = 0; } } //----------------------------------------------------------- HDC mdcCustom::getMdc(PWin* owner, HDC hdc) { PRect r; GetClientRect(*owner, r); if(!mdc && r.Width()) { mdc = CreateCompatibleDC(hdc); SetGraphicsMode(mdc, GM_ADVANCED); hBmpTmp = CreateCompatibleBitmap(hdc, r.Width(), r.Height()); oldBmp = SelectObject(mdc, hBmpTmp); oldPen = SelectObject(mdc, pen); oldAlign = SetTextAlign(mdc, TA_BOTTOM | TA_CENTER); oldColor = SetTextColor(mdc, RGB(0, 0, 220)); oldBkg = SetBkColor(mdc, cBkg); oldMode = SetBkMode(mdc, OPAQUE); bkg = CreateSolidBrush(cBkg); } if(mdc) FillRect(mdc, r, bkg); return mdc; } //----------------------------------------------------------- bool PRule::create() { if(!baseClass::create()) return false; return true; } //----------------------------------------------------------- void PRule::setStartLg(long start) { if(start != Start) { Start = start; InvalidateRect(*this, 0, 0); } } //----------------------------------------------------------- void PRule::setStartPx(long start) { HDC hdc = GetDC(*this); SetMapMode(hdc, MM_LOMETRIC); POINT pt = { start, 0 }; DPtoLP(hdc, &pt, 1); SetMapMode(hdc, MM_TEXT); ReleaseDC(*this, hdc); setStartLg(pt.x); } //----------------------------------------------------------- void PRule::setZoom(svmManZoom::zoomX zoom, bool force) { if(Zoom != zoom || force) { Zoom = zoom; InvalidateRect(*this, 0, 0); } } //----------------------------------------------------------- LRESULT PRule::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_ERASEBKGND: return 1; case WM_SIZE: Mdc.clear(); break; case WM_PAINT: do { PAINTSTRUCT Paint; HDC hdc = BeginPaint(hwnd, &Paint); if(!hdc) { EndPaint(*this, &Paint); return 0; } HDC mdc = Mdc.getMdc(this, hdc); if(mdc) { SetMapMode(mdc, MM_LOMETRIC); XFORM xForm; FLOAT z = 1; svmManZoom mZ; mZ.setCurrZoom(Zoom); xForm.eM11 = 1; xForm.eM22 = 1; if(isHorz) { mZ.calcToScreenH(z); xForm.eM11 = z; } else { mZ.calcToScreenV(z); xForm.eM22 = z; } xForm.eM12 = (FLOAT) 0.0; xForm.eM21 = (FLOAT) 0.0; xForm.eDx = (FLOAT) 0.0; xForm.eDy = (FLOAT) 0.0; SetWorldTransform(mdc, &xForm); evPaint(mdc); xForm.eM11 = (FLOAT) 1.0; xForm.eM22 = (FLOAT) 1.0; SetWorldTransform(mdc, &xForm); SetMapMode(mdc, MM_TEXT); PRect rect2(Paint.rcPaint); BitBlt(hdc, rect2.left, rect2.top, rect2.Width(), rect2.Height(), mdc, rect2.left, rect2.top, SRCCOPY); } EndPaint(hwnd, &Paint); } while(false); return 0; } return baseClass::windowProc(hwnd, message, wParam, lParam); } //----------------------------------------------------------- void PRule::getWindowClass(WNDCLASS& wcl) { baseClass::getWindowClass(wcl); wcl.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); } //----------------------------------------------------------- //----------------------------------------------------------- #define DEF_STEP 100 #define VERT_ANGLE 2700 //----------------------------------------------------------- #define ADD_POINT(buff, v) \ wsprintf(buff, _T("%d.%02d"), (v) / 100, (v) % 100) //----------------------------------------------------------- void PRuleX::evPaint(HDC hdc) { PRect r; GetClientRect(*this, r); DPtoLP(hdc, (LPPOINT)(LPRECT)r, 2); int h = r.Height(); LONG step = DEF_STEP; LONG start = Start % DEF_STEP; int start2 = Start - start; int end = r.Width() + start; for(int i = -start; i < end; i += step) { MoveToEx(hdc, i, 0, 0); LineTo(hdc, i, h); } h /= 2; for(int i = step / 2 - start; i < end; i += step) { MoveToEx(hdc, i, 0, 0); LineTo(hdc, i, h); } TCHAR buff[64]; HFONT fnt = D_FONT_ORIENT(h, 0, 0, 0, _T("arial")); HGDIOBJ oldF = SelectObject(hdc, fnt); h *= 2; if(Zoom > svmManZoom::zOne) { for(int i = -start; i < end; i += step, start2 += DEF_STEP) { ADD_POINT(buff, start2); ExtTextOut(hdc, i, h, 0 , 0, buff, _tcslen(buff), 0); } } else { step *= 2; int i = -start; if(!((start2 / DEF_STEP) & 1)) { start2 += DEF_STEP; i += step / 2; } for(; i < end; i += step, start2 += DEF_STEP * 2) { ADD_POINT(buff, start2); ExtTextOut(hdc, i, h, 0 , 0, buff, _tcslen(buff), 0); } } DeleteObject(SelectObject(hdc, oldF)); } //----------------------------------------------------------- void PRuleY::evPaint(HDC hdc) { PRect r; GetClientRect(*this, r); DPtoLP(hdc, (LPPOINT)(LPRECT)r, 2); int w = r.Width(); LONG step = DEF_STEP; LONG start = Start % DEF_STEP; int start2 = Start - start; int end = r.Height() - start; for(int i = start; i > end; i -= step) { MoveToEx(hdc, 0, i, 0); LineTo(hdc, w, i); } w /= 2; for(int i = start + step / 2; i > end; i -= step) { MoveToEx(hdc, 0, i, 0); LineTo(hdc, w, i); } TCHAR buff[64]; HFONT fnt = D_FONT_ORIENT(w, 0, VERT_ANGLE, 0, _T("arial")); HGDIOBJ oldF = SelectObject(hdc, fnt); w *= 2; if(Zoom > svmManZoom::zOne) { for(int i = start; i > end; i -= step, start2 += DEF_STEP) { ADD_POINT(buff, start2); ExtTextOut(hdc, r.Width(), i, 0 , 0, buff, _tcslen(buff), 0); } } else { step *= 2; int i = start; if(!((start2 / DEF_STEP) & 1)) { start2 += DEF_STEP; i -= step / 2; } for(; i > end; i -= step, start2 += DEF_STEP * 2) { ADD_POINT(buff, start2); ExtTextOut(hdc, r.Width(), i, 0 , 0, buff, _tcslen(buff), 0); } } DeleteObject(SelectObject(hdc, oldF)); } //-----------------------------------------------------------
[ "npaolini@ennepisoft.it" ]
npaolini@ennepisoft.it
95e8f23afb2022613157722e2da03a844b8d8be8
61b07e8d14f85800d6fad641a77ef8bbef8d3859
/gameStats.cpp
188082eab9b5bac626461fbc8db710a00011fe9c
[]
no_license
Jared-Adamson/CSE_C_Cpp_LISP_Prolog_Programs
d9fc85dac95abf0447f2d1538fbf329a387cd3b4
194236b8944e65f5850a1fd0addacc0b2a6e36b7
refs/heads/master
2021-06-20T20:59:51.948456
2017-08-11T06:32:57
2017-08-11T06:32:57
23,534,774
0
0
null
null
null
null
UTF-8
C++
false
false
870
cpp
//Jared Adamson //C++ Practice from Beginning C++ Book // Demonstrates declaring and initializing variables #include <iostream> using namespace std; int main() { int score; double distance; char playAgain; bool shieldsUp; short lives, aliensKilled; score = 0; distance = 1200.76; playAgain = 'y'; shieldsUp = true; lives = 3; aliensKilled = 10; double engineTemp = 6572.89; cout << "\nscore: " << score << endl; cout << "distance: " << distance << endl; cout << "playAgain: " << playAgain << endl; cout << "lives: " << lives << endl; cout << "aliensKilled: "<< aliensKilled << endl; cout << "engineTemp: " << engineTemp << endl; int fuel; cout << "\nHow much fuel? "; cin >> fuel; cout << "fuel: " << fuel << endl; typedef unsigned short int ushort; ushort bonus = 10; cout << "\nbonus: " << bonus << endl; return 0; }
[ "jared.d.adamson@gmail.com" ]
jared.d.adamson@gmail.com
bf43aace070e60aa68f575550d8ddd30201b3f6e
247a1bc8595079a22c18786b52f84bd9ba84f3c8
/Cpp/318.maximum-product-of-word-lengths.cpp
22da8ee207db90f7de14b4e26caf7bc19ffa15fc
[ "MIT" ]
permissive
zszyellow/leetcode
cad541a3c34b243031417ea2ac0c77f63e511516
2ef6be04c3008068f8116bf28d70586e613a48c2
refs/heads/master
2021-07-15T23:37:37.414560
2021-02-14T05:56:00
2021-02-14T05:56:00
26,573,267
1
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
class Solution { public: int maxProduct(vector<string>& words) { int n = words.size(), mask = 0, res = 0; vector<int> masks; for (string word : words) { mask = 0; for (char c : word) mask |= (1 << (c-'a')); masks.push_back(mask); } for (int i = 0; i < n-1; ++ i) { for (int j = i+1; j < n; ++ j) { if ((masks[i] & masks[j]) == 0) res = max(res, static_cast<int>(words[i].size()*words[j].size())); } } return res; } };
[ "zszyellow@hotmail.com" ]
zszyellow@hotmail.com
968cea15579707fd3874d05cf991217afbf6f06c
9c2de8d42ba3f23b0b6d74a2518e6834f98251d2
/src/server/MinecraftChunk.cpp
3b8b100623ae19092315d9fb35f5f486600c8169
[]
no_license
tntguy12355/MinecraftPlaysPortal
c96025e660ed6861119d70f4431414697d41e757
ddb491bcc508de65ad6647ef9f1aadabfee69cd4
refs/heads/master
2023-03-17T09:59:06.715233
2021-02-24T02:11:30
2021-02-24T02:11:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,807
cpp
#include "MinecraftChunk.hpp" #include "common.hpp" namespace MCP { Chunk::Chunk(int x, int z) : x(x) , z(z) { } void Chunk::SetBlockID(int x, int y, int z, short id) { sections[(int)floor(y / 16.0)].SetBlockID(x, y % 16, z, id); } short Chunk::GetBlockID(int x, int y, int z) { return sections[(int)floor(y / 16.0)].GetBlockID(x, y % 16, z); } uint32_t Chunk::GetPrimaryBitMask() { uint32_t mask = 0; for (int i = 15; i >= 0; i--) { mask = mask << 1; if (sections[i].GetBlockCount() > 0)mask += 1; } return mask; } int Chunk::GetSentSectionsCount() { int count = 0; for (int i = 0; i < 16; i++) { if (sections[i].GetBlockCount() > 0)count++; } return count; } void ChunkSection::SetBlockID(int x, int y, int z, short id) { assert(x < 16 && y < 16 && z < 16 && x >= 0 && y>=0 && z>=0); short prevID = GetBlockID(x, y, z); blocks[x][y][z] = id; if (prevID == 0 && id != 0)blockCount++; if (prevID != 0 && id == 0)blockCount--; } short ChunkSection::GetBlockID(int x, int y, int z) { if (x >= 16 || y >= 16 || z >= 16 || x<0 || y<0 || z<0) return 0; else return blocks[x][y][z]; } void ChunkWorld::SetBlockID(int x, int y, int z, short id) { int chunkX = (int)floor(x / 16.0); int chunkZ = (int)floor(z / 16.0); Chunk * c = GetChunk(chunkX, chunkZ); //if there's no chunk, create one if (c == nullptr && id > 0) { c = new Chunk(chunkX, chunkZ); chunks.push_back(c); } if (c == nullptr) return; int blockX = x - chunkX * 16; int blockZ = z - chunkZ * 16; c->SetBlockID(blockX, y, blockZ, id); // if cleaned up whole chunk, remove it from list if (c->GetSentSectionsCount() == 0) { for (auto it = chunks.begin(); it != chunks.end(); it++) { if ((*it)->x == chunkX && (*it)->z == chunkZ) { chunks.erase(it); break; } } } } short ChunkWorld::GetBlockID(int x, int y, int z) { int chunkX = (int)floor(x / 16.0); int chunkZ = (int)floor(z / 16.0); Chunk * c = GetChunk(chunkX, chunkZ); if (c != nullptr) { return c->GetBlockID(x % 16, y, z % 16); } return 0; } Chunk* ChunkWorld::GetChunk(int chunkX, int chunkZ) { for (Chunk* chunk : chunks) { if (chunk->x == chunkX && chunk->z == chunkZ) { return chunk; } } return nullptr; } ChunkPacket::ChunkPacket(Chunk* c) : Packet(0x20) { WriteInt(c->x); // chunk X coords WriteInt(c->z); // chunk Z coords bool fullChunk = true; WriteByte(fullChunk ? 1 : 0); // full chunk bool WriteVarInt(c->GetPrimaryBitMask()); // primary bit mask (what chunks will be sent) WriteInt(0x0A000000); // heightmap NBT list. not needed for what I do, so I send empty compound if (fullChunk) { // biome array of 4x4x4 sections WriteVarInt(1024); for (int i = 0; i < 1024; i++) { WriteVarInt(c->biomeArray[i]); } } // size of upcoming data (one chunk section is 8192 + 2 + 1 + 2) WriteVarInt(c->GetSentSectionsCount() * 8197); // writing every chunk section for (int i = 0; i < 16; i++) { ChunkSection& cs = c->sections[i]; if (cs.GetBlockCount() == 0)continue; WriteShort(cs.GetBlockCount()); // block count WriteByte(15); // bits per block, using max bytes for direct pallete (15 for 1.16 smh) WriteVarInt(1024); // count of longs that will be sent for (int y = 0; y < 16; y++) for (int z = 0; z < 16; z++) for (int x = 0; x < 16; x += 4) { uint64_t data = 0; for (int b = 3; b >= 0; b--) { data = data << 15; data += cs.GetBlockID(x + b, y, z); } WriteLong(data); } } // block entities. i don't need them, so simply sending empty array WriteVarInt(0); } FullBrightLightChunkPacket::FullBrightLightChunkPacket(Chunk* c) : Packet(0x23) { WriteVarInt(c->x); // Chunk X WriteVarInt(c->z); // Chunk Y WriteByte(1); // trust edges? uint32_t lightMask = c->GetPrimaryBitMask() << 1; /* WriteVarInt(lightMask); // sky light mask WriteVarInt(lightMask); // block light mask WriteVarInt(lightMask ^ 0b111111111111111111); // empty sky light mask WriteVarInt(lightMask ^ 0b111111111111111111); // empty block light mask int sectionCount = c->GetSentSectionsCount(); */ //sending full bright for ALL of sections WriteVarInt(0b111111111111111111); // sky light mask WriteVarInt(0b111111111111111111); // block light mask WriteVarInt(0); // empty sky light mask WriteVarInt(0); // empty block light mask int sectionCount = 18; // sky light for (int i = 0; i < sectionCount; i++) { WriteVarInt(2048); for (int i = 0; i < 256; i++) { WriteLong(0xFFFFFFFFFFFFFFFF); } } //block light for (int i = 0; i < sectionCount; i++) { WriteVarInt(2048); for (int i = 0; i < 256; i++) { WriteLong(0xFFFFFFFFFFFFFFFF); } } } }
[ "krzyht@gmail.com" ]
krzyht@gmail.com
db94bb32b8525227287a97c3c28611ebab6a734b
8743445edc75a4116892f070ce3d1546bf5f607b
/cppcache/test/LoggingTest.cpp
240d0970e1ee109b5c8710d2f852796b98654ba7
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown" ]
permissive
apache/geode-native
d2ef8d21c62a6ab494bd6be9b20545f699340348
049309470cd01ddcb256cc2c0f60ed0aa3a4caf2
refs/heads/develop
2023-08-19T03:01:18.421251
2022-10-03T12:52:42
2022-10-03T12:52:42
80,904,111
53
77
Apache-2.0
2023-08-19T01:26:43
2017-02-04T08:00:06
C++
UTF-8
C++
false
false
26,585
cpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 <string> #include <util/Log.hpp> #include <boost/filesystem.hpp> #include <boost/regex.hpp> #include <gtest/gtest.h> #include <geode/AuthenticatedView.hpp> #include <geode/Cache.hpp> #include <geode/PoolManager.hpp> #include <geode/RegionFactory.hpp> #include <geode/RegionShortcut.hpp> using apache::geode::client::CacheClosedException; using apache::geode::client::CacheFactory; using apache::geode::client::LogLevel; using apache::geode::client::RegionShortcut; namespace { const auto __1K__ = 1024; const auto __4K__ = 4 * __1K__; const auto __1M__ = (__1K__ * __1K__); const auto __1G__ = (__1K__ * __1K__ * __1K__); const auto LENGTH_OF_BANNER = 16; const char* __1KStringLiteral = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; auto testFileNames = {"LoggingTest.log", "geode-native.log"}; class LoggingTest : public testing::Test { void scrubTestLogFiles() { for (auto name : testFileNames) { // Close logger, just in case apache::geode::client::Log::close(); if (boost::filesystem::exists(name)) { boost::filesystem::remove(name); } std::map<int32_t, boost::filesystem::path> rolledFiles; LoggingTest::findRolledFiles(boost::filesystem::current_path().string(), name, rolledFiles); for (auto& item : rolledFiles) { boost::filesystem::remove(item.second); } } } void SetUp() override { scrubTestLogFiles(); } void TearDown() override { scrubTestLogFiles(); } public: static void writeRolledLogFile(const boost::filesystem::path& logdir, const char* filename, int32_t rollIndex) { auto baseName = boost::filesystem::path(filename).stem().string(); auto rolledPath = logdir / boost::filesystem::path(baseName + "-" + std::to_string(rollIndex) + ".log"); auto rolledFile = fopen(rolledPath.string().c_str(), "w"); fwrite("Test", 1, 4, rolledFile); fclose(rolledFile); } static int numOfLinesInFile(const char* fname) { char line[2048]; int ln_cnt = 0; FILE* fp = fopen(fname, "r"); if (fp == nullptr) { return 0; } while (!!(fgets(line, sizeof line, fp))) { ++ln_cnt; } if (!feof(fp)) { fclose(fp); return -2; } fclose(fp); return ln_cnt; } static int expected(LogLevel level) { int expected = static_cast<int>(level); if (level >= LogLevel::Default) { expected--; } return expected; } static int expectedWithBanner(LogLevel level) { int expected = LoggingTest::expected(level); if (level != LogLevel::None) { expected += LENGTH_OF_BANNER; } return expected; } static void verifyLineCountAtLevel(LogLevel level) { for (auto logFilename : testFileNames) { apache::geode::client::Log::init(level, logFilename); LOGERROR("Error Message"); LOGWARN("Warning Message"); LOGINFO("Info Message"); LOGCONFIG("Config Message"); LOGFINE("Fine Message"); LOGFINER("Finer Message"); LOGFINEST("Finest Message"); LOGDEBUG("Debug Message"); int lines = LoggingTest::numOfLinesInFile(logFilename); ASSERT_TRUE(lines == LoggingTest::expectedWithBanner(level)); apache::geode::client::Log::close(); boost::filesystem::remove(logFilename); } } static void findRolledFiles( const std::string& logFilePath, const boost::filesystem::path& filename, std::map<int32_t, boost::filesystem::path>& rolledFiles) { const auto basePath = boost::filesystem::absolute(boost::filesystem::path(logFilePath)) / filename; const auto filterstring = basePath.stem().string() + "-(\\d+)\\.log$"; const boost::regex my_filter(filterstring); rolledFiles.clear(); boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator i( basePath.parent_path().string()); i != end_itr; ++i) { if (boost::filesystem::is_regular_file(i->status())) { std::string rootFilename = i->path().filename().string(); boost::regex testPattern(filterstring); boost::match_results<std::string::const_iterator> testMatches; if (boost::regex_search( std::string::const_iterator(rootFilename.begin()), rootFilename.cend(), testMatches, testPattern)) { auto index = std::atoi( std::string(testMatches[1].first, testMatches[1].second).c_str()); rolledFiles[index] = i->path(); } } } } static size_t calculateUsedDiskSpace(const std::string& logFilePath) { std::map<int32_t, boost::filesystem::path> rolledLogFiles{}; findRolledFiles(boost::filesystem::current_path().string(), boost::filesystem::path(logFilePath), rolledLogFiles); auto usedSpace = boost::filesystem::file_size(logFilePath); for (auto const& item : rolledLogFiles) { usedSpace += boost::filesystem::file_size(item.second); } return usedSpace; } void verifyDiskSpaceNotLeakedForFile(const char* filename) { const int NUMBER_OF_ITERATIONS = 4 * __1K__; const int DISK_SPACE_LIMIT = 2 * __1M__; std::string logfileName = filename ? filename : "geode-native.log"; // Start/stop logger several times, make sure it's picking up any/all // existing logs in its disk space calculations. for (auto j = 0; j < 5; j++) { ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, logfileName, 1, 2)); for (auto i = 0; i < NUMBER_OF_ITERATIONS; i++) { LOGDEBUG(__1KStringLiteral); } apache::geode::client::Log::close(); // Original file should still be around ASSERT_TRUE(boost::filesystem::exists(logfileName)); // We wrote 4x the log file limit, and 2x the disk space limit, so // there should be one 'rolled' file. Its name should be of the form // <base>-n.log, where n is some reasonable number. auto usedSpace = calculateUsedDiskSpace(logfileName); ASSERT_TRUE(usedSpace < DISK_SPACE_LIMIT); } } }; /** * Verify we can initialize the logger with any combination of level, * filename, file size limit, and disk space limit */ TEST_F(LoggingTest, logInit) { for (auto logFilename : testFileNames) { // Check all valid levels ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::None, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Error, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Warning, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Info, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Default, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Fine, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Finer, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Finest, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, logFilename, 1, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::All, logFilename, 1, 4)); apache::geode::client::Log::close(); // Specify a disk space limit smaller than the file size limit ASSERT_THROW( apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, logFilename, __1K__, 4), apache::geode::client::IllegalArgumentException); // Specify a file size limit above max allowed ASSERT_THROW( apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, logFilename, __1G__), apache::geode::client::IllegalArgumentException); // Specify a disk space limit above max allowed ASSERT_THROW( apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, logFilename, 1, __1G__), apache::geode::client::IllegalArgumentException); // Init twice without closing ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::All, logFilename, 1, 4)); ASSERT_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::All, logFilename, 1, 4), apache::geode::client::IllegalStateException); apache::geode::client::Log::close(); } // Init with valid filename ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, "LoggingTest.log")); apache::geode::client::Log::close(); // Init with legal filename with (), #, and space ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, "LoggingTest (#).log")); apache::geode::client::Log::close(); boost::filesystem::remove("LoggingTest (#).log"); // Init with invalid filename ASSERT_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, "#?$?%.log"), apache::geode::client::IllegalArgumentException); // Specify disk or file limit without a filename ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, nullptr, 4)); apache::geode::client::Log::close(); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, nullptr, 0, 4)); apache::geode::client::Log::close(); } TEST_F(LoggingTest, logToFileAtEachLevel) { for (auto logFilename : testFileNames) { ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, logFilename)); LOGDEBUG("This is a debug string"); LOGDEBUG("This is a formatted debug string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_FALSE(boost::filesystem::exists(logFilename)); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Finest, logFilename)); LOGFINEST("This is a 'finest' string"); LOGFINEST("This is a formatted 'finest' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Finer, logFilename)); LOGFINER("This is a 'finer' string"); LOGFINER("This is a formatted 'finer' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Fine, logFilename)); LOGFINE("This is a 'fine' string"); LOGFINE("This is a formatted 'fine' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Config, logFilename)); LOGCONFIG("This is a 'config' string"); LOGCONFIG("This is a formatted 'config' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Info, logFilename)); LOGINFO("This is a 'finer' string"); LOGINFO("This is a formatted 'finer' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Warning, logFilename)); LOGWARN("This is a 'warning' string"); LOGWARN("This is a formatted 'warning' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Error, logFilename)); LOGERROR("This is a 'error' string"); LOGERROR("This is a formatted 'error' string (%d)", __1K__); apache::geode::client::Log::close(); ASSERT_TRUE(boost::filesystem::exists(logFilename)); ASSERT_TRUE(boost::filesystem::file_size(logFilename) > 0); boost::filesystem::remove(logFilename); } } TEST_F(LoggingTest, verifyFileSizeLimit) { for (auto logFilename : testFileNames) { ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, logFilename, 1, 5)); for (auto i = 0; i < 4 * __1K__; i++) { LOGDEBUG(__1KStringLiteral); } apache::geode::client::Log::close(); // Original file should still be around ASSERT_TRUE(boost::filesystem::exists(logFilename)); // Check for 'rolled' log files. With a 1MB file size limit and each logged // string having a length of 1K chars, we should have at least one less // rolled log file than the number of strings logged, i.e. 3 rolled files // for 4K strings in this case. spdlog rolled files look like // <<basename>>.<<#>>.<<extension>>, so for LoggingTest.log we should find // LoggingTest.1.log, LoggingTest.2.log, etc. auto base = boost::filesystem::path(logFilename).stem(); auto ext = boost::filesystem::path(logFilename).extension(); // File size limit is treated as a "soft" limit. If the last message in the // log puts the file size over the limit, the file is rolled and the message // is preserved intact, rather than truncated or split across files. We'll // assume the file size never exceeds 110% of the specified limit. auto adjustedFileSizeLimit = static_cast<uint32_t>(static_cast<uint64_t>(__1M__) * 11 / 10); for (auto i = 0; i < 4; i++) { auto rolledLogFileName = base.string() + "-" + std::to_string(i) + ext.string(); ASSERT_TRUE(boost::filesystem::exists(rolledLogFileName)); ASSERT_TRUE(adjustedFileSizeLimit > boost::filesystem::file_size(rolledLogFileName)); } } } TEST_F(LoggingTest, verifyDiskSpaceLimit) { for (auto logFilename : testFileNames) { const int NUMBER_OF_ITERATIONS = 4 * __1K__; const int DISK_SPACE_LIMIT = 2 * __1M__; ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, logFilename, 1, 2)); for (auto i = 0; i < NUMBER_OF_ITERATIONS; i++) { LOGDEBUG(__1KStringLiteral); } apache::geode::client::Log::close(); // Original file should still be around ASSERT_TRUE(boost::filesystem::exists(logFilename)); auto size = boost::filesystem::file_size(logFilename); auto numRolledFilesFound = 0; auto base = boost::filesystem::path(logFilename).stem(); auto ext = boost::filesystem::path(logFilename).extension(); // We wrote 4x the log file limit, and 2x the disk space limit, so // there should be one 'rolled' file. Its name should be of the form // <base>-n.log, where n is some reasonable number. std::map<int32_t, boost::filesystem::path> rolledFiles; LoggingTest::findRolledFiles(boost::filesystem::current_path().string(), logFilename, rolledFiles); ASSERT_TRUE(rolledFiles.size() == 1); auto rolledFile = rolledFiles.begin()->second; size += boost::filesystem::file_size(rolledFile); ASSERT_TRUE(size <= DISK_SPACE_LIMIT); } } TEST_F(LoggingTest, verifyWithExistingRolledFile) { for (auto logFilename : testFileNames) { LoggingTest::writeRolledLogFile(boost::filesystem::current_path(), logFilename, 11); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, logFilename, 1, 5)); for (auto i = 0; i < 2 * __1K__; i++) { LOGDEBUG(__1KStringLiteral); } apache::geode::client::Log::close(); // Original file should still be around ASSERT_TRUE(boost::filesystem::exists(logFilename)); // Check for 'rolled' log files. With a 1MB file size limit and each logged // string having a length of 1K chars, we should have at least one less // rolled log file than the number of strings logged, i.e. 3 rolled files // for 4K strings in this case. spdlog rolled files look like // <<basename>>.<<#>>.<<extension>>, so for LoggingTest.log we should find // LoggingTest.1.log, LoggingTest.2.log, etc. auto base = boost::filesystem::path(logFilename).stem(); auto ext = boost::filesystem::path(logFilename).extension(); // File size limit is treated as a "soft" limit. If the last message in the // log puts the file size over the limit, the file is rolled and the message // is preserved intact, rather than truncated or split across files. We'll // assume the file size never exceeds 110% of the specified limit. auto adjustedFileSizeLimit = static_cast<uint32_t>(static_cast<uint64_t>(__1M__) * 11 / 10); auto rolledLogFileName = base.string() + "-" + std::to_string(12) + ext.string(); ASSERT_TRUE(boost::filesystem::exists(rolledLogFileName)); ASSERT_TRUE(adjustedFileSizeLimit > boost::filesystem::file_size(rolledLogFileName)); } } void verifyWithPath(const boost::filesystem::path& path, int32_t fileSizeLimit, int64_t diskSpaceLimit) { for (auto logFilename : testFileNames) { auto relativePath = path / boost::filesystem::path(logFilename); ASSERT_NO_THROW(apache::geode::client::Log::init( apache::geode::client::LogLevel::Debug, relativePath.string(), fileSizeLimit, diskSpaceLimit)); for (auto i = 0; i < ((3 * fileSizeLimit) / 2) * __1K__; i++) { LOGDEBUG(__1KStringLiteral); } apache::geode::client::Log::close(); // Original file should still be around ASSERT_TRUE(boost::filesystem::exists(relativePath)); // Check for 'rolled' log files. With a 1MB file size limit and each logged // string having a length of 1K chars, we should have at least one less // rolled log file than the number of strings logged, i.e. 3 rolled files // for 4K strings in this case. spdlog rolled files look like // <<basename>>.<<#>>.<<extension>>, so for LoggingTest.log we should find // LoggingTest.1.log, LoggingTest.2.log, etc. auto base = boost::filesystem::path(relativePath).stem(); auto ext = boost::filesystem::path(relativePath).extension(); // File size limit is treated as a "soft" limit. If the last message in the // log puts the file size over the limit, the file is rolled and the message // is preserved intact, rather than truncated or split across files. We'll // assume the file size never exceeds 110% of the specified limit. auto adjustedFileSizeLimit = static_cast<uint32_t>( static_cast<uint64_t>(__1M__ * fileSizeLimit) * 11 / 10); auto rolledLogFileName = relativePath.parent_path() / boost::filesystem::path(base.string() + "-" + std::to_string(0) + ext.string()); if (fileSizeLimit == diskSpaceLimit) { // If the limits are equal, we should *never* roll logs, just delete the // current file and start over ASSERT_FALSE(boost::filesystem::exists(rolledLogFileName)); } else { ASSERT_TRUE(boost::filesystem::exists(rolledLogFileName)); ASSERT_TRUE(adjustedFileSizeLimit > boost::filesystem::file_size(rolledLogFileName)); } ASSERT_TRUE(adjustedFileSizeLimit > boost::filesystem::file_size(relativePath)); } } TEST_F(LoggingTest, verifyWithRelativePathFromCWD) { auto relativePath = boost::filesystem::path("foo/bar"); verifyWithPath(relativePath, 1, 5); boost::filesystem::remove_all(boost::filesystem::path("foo")); } TEST_F(LoggingTest, verifyWithAbsolutePath) { auto absolutePath = boost::filesystem::absolute(boost::filesystem::path("foo/bar")); verifyWithPath(absolutePath, 1, 5); boost::filesystem::remove_all(boost::filesystem::path("foo")); } TEST_F(LoggingTest, setLimitsEqualAndRoll) { verifyWithPath(boost::filesystem::path(), 1, 1); } // Logger is supposed to tack the '.log' extension on any file that doesn't // already have it. TEST_F(LoggingTest, verifyExtension) { apache::geode::client::Log::init(LogLevel::All, "foo"); LOGINFO("..."); apache::geode::client::Log::close(); ASSERT_TRUE(LoggingTest::numOfLinesInFile("foo.log") > 0); boost::filesystem::remove("foo.log"); apache::geode::client::Log::init(LogLevel::All, "foo.txt"); LOGINFO("..."); apache::geode::client::Log::close(); ASSERT_TRUE(LoggingTest::numOfLinesInFile("foo.txt.log") > 0); boost::filesystem::remove("foo.txt.log"); } // Old version of logger didn't distinguish between rolled log file and // filename containing '-', so would crash in an atoi() call if you used // '-' in your log file name. TEST_F(LoggingTest, verifyFilenameWithDash) { apache::geode::client::Log::init(LogLevel::All, "foo-bar.log"); LOGINFO("..."); apache::geode::client::Log::close(); ASSERT_TRUE(LoggingTest::numOfLinesInFile("foo-bar.log") > 0); boost::filesystem::remove("foo-bar.log"); } TEST_F(LoggingTest, countLinesAllLevels) { for (LogLevel level : { LogLevel::Error, LogLevel::Warning, LogLevel::Info, LogLevel::Default, LogLevel::Config, LogLevel::Fine, LogLevel::Finer, LogLevel::Finest, LogLevel::Debug, }) { for (auto logFilename : testFileNames) { apache::geode::client::Log::init(level, logFilename); LOGERROR("Error Message"); LOGWARN("Warning Message"); LOGINFO("Info Message"); LOGCONFIG("Config Message"); LOGFINE("Fine Message"); LOGFINER("Finer Message"); LOGFINEST("Finest Message"); LOGDEBUG("Debug Message"); int lines = LoggingTest::numOfLinesInFile(logFilename); ASSERT_TRUE(lines == LoggingTest::expectedWithBanner(level)); apache::geode::client::Log::close(); boost::filesystem::remove(logFilename); } } } TEST_F(LoggingTest, countLinesConfigOnwards) { verifyLineCountAtLevel(LogLevel::Config); } TEST_F(LoggingTest, countLinesInfoOnwards) { verifyLineCountAtLevel(LogLevel::Info); } TEST_F(LoggingTest, countLinesWarningOnwards) { verifyLineCountAtLevel(LogLevel::Warning); } TEST_F(LoggingTest, countLinesErrorOnly) { verifyLineCountAtLevel(LogLevel::Error); } TEST_F(LoggingTest, countLinesNone) { verifyLineCountAtLevel(LogLevel::None); } TEST_F(LoggingTest, verifyDiskSpaceNotLeaked) { for (auto logFilename : testFileNames) { verifyDiskSpaceNotLeakedForFile(logFilename); } } TEST_F(LoggingTest, verifyDiskSpaceNotLeakedWithDefaultLogName) { verifyDiskSpaceNotLeakedForFile(nullptr); } } // namespace
[ "noreply@github.com" ]
apache.noreply@github.com
b0fdf157c0aebdbc5888342df6adcf2e3a19304c
8cf32b4cbca07bd39341e1d0a29428e420b492a6
/contracts/libc++/upstream/test/std/input.output/iostreams.base/ios/iostate.flags/rdstate.pass.cpp
d4f885c14781ac6b456bb4e69e32d8a056d2eb41
[ "NCSA", "MIT" ]
permissive
cubetrain/CubeTrain
e1cd516d5dbca77082258948d3c7fc70ebd50fdc
b930a3e88e941225c2c54219267f743c790e388f
refs/heads/master
2020-04-11T23:00:50.245442
2018-12-17T16:07:16
2018-12-17T16:07:16
156,970,178
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <ios> // template <class charT, class traits> class basic_ios // iostate rdstate() const; #include <ios> #include <cassert> int main() { std::ios ios(0); assert(ios.rdstate() == std::ios::badbit); ios.setstate(std::ios::failbit); assert(ios.rdstate() == (std::ios::failbit | std::ios::badbit)); }
[ "1848@shanchain.com" ]
1848@shanchain.com
c9a4d5f6adbec5514fb4b6eda62be58baef32bf5
91971732033d69414cb6acdcf471c2862483679c
/testsuites/posix-torture/src/main.cpp
3fd676b4e98ef704f4dd1c96ef941cbc7faba55b
[ "MIT" ]
permissive
managarm/managarm
d94e5bab607e36df458213984876fafc4575b184
f274d8d531f7f083284c0681ac065db1e467256f
refs/heads/master
2023-09-04T08:07:06.523632
2023-08-29T22:26:04
2023-08-29T22:26:04
63,081,862
1,261
87
MIT
2023-08-29T22:26:06
2016-07-11T15:57:53
C++
UTF-8
C++
false
false
576
cpp
#include <iostream> #include <vector> #include "testsuite.hpp" std::vector<abstract_test_case *> &test_case_ptrs() { static std::vector<abstract_test_case *> singleton; return singleton; } void abstract_test_case::register_case(abstract_test_case *tcp) { test_case_ptrs().push_back(tcp); } int main() { for(int s = 10; s < 24; s++) { int n = 1 << s; for(abstract_test_case *tcp : test_case_ptrs()) { std::cout << "posix-torture: Running " << tcp->name() << " for " << n << " iterations" << std::endl; for(int i = 0; i < n; i++) tcp->run(); } } }
[ "alexander.vandergrinten@gmail.com" ]
alexander.vandergrinten@gmail.com
beccbb920a33861bacd54ff8556732498e626123
5f8b6595ffefffca3c0152ed62af62bde398b348
/linked list imple.cpp
3c5ea496173fb3ff80e39bc9aeb6a2217f82dd9e
[]
no_license
hemilrajpura/Programs---DSA
7e132a07e5b203fb02ae7ae94cf4718aff11dfb7
854aa24ddaabc4889c4f919ac74caffc45f51729
refs/heads/main
2023-06-14T02:41:01.767773
2021-07-07T16:56:55
2021-07-07T16:56:55
383,867,983
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include<iostream> using namespace std; struct Node{ int data; struct Node * next; }; void printLL(struct Node * poi){ cout<<endl<<endl<<"Printing Linked List.."<<endl; while(poi != NULL){ cout<<endl<<poi -> data<<endl; poi = poi->next; } } int main(){ struct Node * head; struct Node * second; struct Node * third; head = (struct Node *) malloc(sizeof(struct Node)); second = (struct Node *) malloc(sizeof(struct Node)); third = (struct Node *) malloc(sizeof(struct Node)); //linking head -> data = 5; head -> next = second; second -> data = 10; second -> next = third; third -> data = 15; third -> next = NULL; printLL(head); //printing the first data //cout<<endl<<head->data<<endl; return 0; }
[ "noreply@github.com" ]
hemilrajpura.noreply@github.com
3728ef2b301031fb593765e57e86ea904dcb6e6d
b5c3a12b20977873209c881b8e0c9fb5bd717a18
/Energia/Main-code/FINALLY.ino
38774db74f79f686059d14b309f90286d59f979a
[]
no_license
AhmedRamadanElamir/Agrisource-Data
f417bf2516d01233a9f4dc6c87cdae92d7c73de4
e540fdc99c809d1fc9335e663026242eb81fcd73
refs/heads/master
2021-01-22T15:42:26.857169
2016-09-24T05:54:52
2016-09-24T05:54:52
63,517,170
1
3
null
null
null
null
UTF-8
C++
false
false
2,062
ino
#include <Energia.h> #include "BMP180.h" #include <Wire.h> //#include <OPT3001.h> #include <Time.h> //#include <flow.h> #include "DHT11.h" int temperature, pressure; #define soil PB_5 //pin used for Soil sensor int get_soil() { int soilData; soilData = analogRead(soil); return soilData; } void setup() { Serial.begin(9600); Serial1.begin(9600); pinMode(soil,INPUT); } String get_data() // this function cocatinate all the sensors readings together { String data = "val1&"; readSensor(temperature, pressure); data.conact(temperature); data.concat("&val2="); data.conact(pressure); data.concat("&val3="); data.concat(get_Hum()); data.concat("&val4="); data.concat(get_soil()); delay(1000); } void loop(){ Serial1.println("AT+CFUN=1"); //activate full phone functionality delay(200); Serial1.println("AT+COPS=0"); //choose automatic operator selection delay(200); Serial1.println("AT+CREG=0"); //network registeration delay(200); Serial1.println("AT+CGATT=1"); //gprs registeration delay(200); Serial1.println("AT+CGDCONT=1,\"IP\",\"MobinilWeb\""); //setup PDP context delay(200); Serial1.println("AT+CGACT=1,1"); //activate PDP context delay(200); Serial1.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); //setup connection type delay(200); Serial1.println("AT+SAPBR=3,1,\"APN\",\"MobinilWeb\""); //setup APN delay(200); Serial1.println("AT+SAPBR=1,1"); //use APN delay(200); Serial1.println("AT+HTTPINIT"); //initialise http session delay(200); Serial1.println("AT+HTTPPARA=\"CID\",1"); //APN id 1 delay(200); String data = "AT+HTTPPARA=\"URL\",\"agrisourcedata.com/sensors/modem.php?FID=13&SID=1&"; data.concat(get_data()); data.concat("\""); Serial1.println(data); //web address to send data to delay(1000); Serial1.println("AT+HTTPACTION=0"); //Get request delay(10000); Serial1.println("AT+HTTPREAD"); //read data delay(1000); Serial1.println("AT+HTTPTERM"); //terminate http session delay(1000); }
[ "noreply@github.com" ]
AhmedRamadanElamir.noreply@github.com
9fb5bae0cf5ad74501e6d0e01598e2c2df3d3f3e
fec81bfe0453c5646e00c5d69874a71c579a103d
/blazetest/src/mathtest/operations/dmatdmatsub/H3x3aH3x3a.cpp
808f88efad273b5656af23ae078c1f11660ba3f1
[ "BSD-3-Clause" ]
permissive
parsa/blaze
801b0f619a53f8c07454b80d0a665ac0a3cf561d
6ce2d5d8951e9b367aad87cc55ac835b054b5964
refs/heads/master
2022-09-19T15:46:44.108364
2022-07-30T04:47:03
2022-07-30T04:47:03
105,918,096
52
7
null
null
null
null
UTF-8
C++
false
false
3,712
cpp
//================================================================================================= /*! // \file src/mathtest/operations/dmatdmatsub/H3x3aH3x3a.cpp // \brief Source file for the H3x3aH3x3a dense matrix/dense matrix subtraction math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/HermitianMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/dmatdmatsub/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'H3x3aH3x3a'..." << std::endl; using blazetest::mathtest::ScalarA; try { // Matrix type definitions using H3x3a = blaze::HermitianMatrix< blaze::StaticMatrix<ScalarA,3UL,3UL> >; // Creator type definitions using CH3x3a = blazetest::Creator<H3x3a>; // Running the tests RUN_DMATDMATSUB_OPERATION_TEST( CH3x3a(), CH3x3a() ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix subtraction:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
e209e6f7af7092e7c67ad07e88f8093a8c0308cc
8a100a50efe9df71962b2552bd9b75300958b1fe
/Transmitters/Old Version/X_CTRL_STM32F10x/ElsCtrl_v1.6/USER/GUI/Page_Calibration.cpp
553af4cc00139ecd9089934b3256414374fcef93
[ "MIT" ]
permissive
yu1741588584/X-CTRL
156d608a02a9953de3a92e1d0a0abc62ece74350
9d93a49688fd8526253c9c9119479d04fab8371b
refs/heads/master
2022-12-27T22:29:31.691813
2022-04-30T03:49:20
2022-04-30T03:49:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,604
cpp
#include "FileGroup.h" #include "GUI_Private.h" #include "DigitalFilter.h" static MillisTaskManager mtm_Calibration(3); static FilterAverage<int> dfJSL_Y_ADC(13); void Task_JoystickCab() { int16_t ADC_LY = dfJSL_Y_ADC.getNext(JSL_Y_ADC); if(ADC_LY > JS_L.Ymax)JS_L.Ymax = ADC_LY; if(ADC_LY < JS_L.Ymin)JS_L.Ymin = ADC_LY; } void Task_ShowJoystickStatus() { screen.setCursor(StatusBarPos + 5, 14); screen.printf("Max:%4d",JS_L.Ymax); screen.setCursor(StatusBarPos + 5, 22); screen.printf("Min:%4d",JS_L.Ymin); } static void Setup() { screen.setCursor(StatusBarPos + 5, 5); screen.print("Calibrating..."); BuzzTone(1000, 200); uint32_t LY_sum = 0.0; uint32_t cnt = 0; for(cnt = 0; cnt < 1000; cnt++) { LY_sum += dfJSL_Y_ADC.getNext(JSL_Y_ADC); delay(1); } JS_L.Ymid = LY_sum / (cnt + 1); JS_L.Ymax = ADC_MaxValue / 2 + 200, JS_L.Ymin = ADC_MaxValue / 2 - 200; mtm_Calibration.TaskRegister(0, Task_JoystickCab, 10); mtm_Calibration.TaskRegister(1, Task_ShowJoystickStatus, 50); } static void Loop() { mtm_Calibration.Running(millis()); } static void Exit() { EEPROM_Handle(EEPROM_Chs::SaveData); ClearPage(); BuzzTone(500, 200); } static void ButtonLongPressEvent() { page.PageChangeTo(PAGE_CtrlInfo); } void PageRegister_Calibration(uint8_t ThisPage) { page.PageRegister_Basic(ThisPage, Setup, Loop, Exit); // page.PageRegister_Event(ThisPage, EVENT_ButtonPress, ButtonPressEvent); page.PageRegister_Event(ThisPage, EVENT_ButtonLongPress, ButtonLongPressEvent); }
[ "1290176185@qq.com" ]
1290176185@qq.com
54cbedb45180544c9fde1e565d673fe841bb5554
2cb681e118e3f1e4b2b141372ae1c6914599b835
/codechef/tweed1.cpp
721d371889e62defd221f1109e959b64d47c9d3b
[]
no_license
jatinarora2702/Competitive-Coding
1ad978a91122c920c839483e46812b5fb70a246e
a77f5d4f1737ca4e408ccf706128ba90ed664286
refs/heads/master
2021-01-11T20:11:34.791960
2020-12-31T00:21:06
2020-12-31T00:21:06
79,060,813
0
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
#include <bits/stdc++.h> #define N 55 using namespace std; int a[N]; char s[20]; int main() { int t, n, i, f, ke, ko, ch, win, waste; scanf("%d", &t); while(t--) { scanf("%d %s", &n, s); ke = ko = 0; for(i = 0 ; i < n ; i++) { scanf("%d", &a[i]); } if(strcmp(s, "Dee") == 0){ f = 0; } else{ f = 1; } if(n == 1 && a[0] % 2 == 0 && f == 0) win = 0; else win = 1; if(win == 0) { printf("Dee\n"); } else { printf("Dum\n"); } } return 0; }
[ "jatinarora2702@gmail.com" ]
jatinarora2702@gmail.com
13ab318356caf6c24c6fdc6d56d14530c345abc7
9b6763581388237af03d9bbf378955901a77a1dc
/Graduate_CLIMBGUYS/cpp&h/steelblock.h
e5f40d01a7370da718483cf6d9ffd4f4242fa3f6
[]
no_license
Nishin3614/ClimbBuys
e2623ecfef3cbe8f5b00b6963da8c823291b0a79
09c967dc36b59d32be44174e34a74daf02c1e48b
refs/heads/master
2023-02-25T06:46:07.896211
2021-01-29T00:19:08
2021-01-29T00:19:08
303,862,684
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,590
h
// ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // // 鋼鉄ブロック処理 [steelblock.h] // Author : KOKI NISHIYAMA // // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #ifndef _STEELBLOCK_H_ #define _STEELBLOCK_H_ // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // インクルードファイル // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #include "baseblock.h" // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // 前方宣言 // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // 構造体 // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // クラス // ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- class CSteelblock : public CBaseblock { public: /* 列挙型 */ /* 構造体 */ /* 関数 */ // コンストラクタ CSteelblock(); // デストラクタ virtual ~CSteelblock(); // 初期化処理 virtual void Init(void); // 更新処理 virtual void Uninit(void); // 更新処理 virtual void Update(void); // 描画処理 virtual void Draw(void); // 当たった後の処理 // nObjType : 相手オブジェクトタイプ // pScene : 相手のシーン情報 virtual void Scene_MyCollision( int const &nObjType = 0, // オブジェクトタイプ CScene * pScene = NULL // 相手のシーン情報 ); // 相手に当てられた後の処理 // nObjType : 相手オブジェクトタイプ // pScene : 相手のシーン情報 virtual void Scene_OpponentCollision( int const &nObjType = 0, // オブジェクトタイプ CScene * pScene = NULL // 相手のシーン情報 ); // 自分から当たらなかった後の処理 // nObjType : 相手オブジェクトタイプ // pScene : 相手のシーン情報 virtual void Scene_NoMyCollision( int const &nObjType = 0, // オブジェクトタイプ CScene * pScene = NULL // 相手のシーン情報 ) {}; // 相手に当てられなかった後の処理 // nObjType : 相手オブジェクトタイプ // pScene : 相手のシーン情報 virtual void Scene_NoOpponentCollision( int const &nObjType = 0, // オブジェクトタイプ CScene * pScene = NULL // 相手のシーン情報 ) {}; // 当たった後の判定 // Obj : オブジェタイプ // pScene : シーン情報 void HitCollision( COLLISIONDIRECTION const &Direct, // 前後左右上下 CScene::OBJ const & Obj, // オブジェタイプ CScene * pScene = NULL // シーン情報 ); // 鋼鉄ブロック全ソースの読み込み static HRESULT Load(void); // 鋼鉄ブロック全ソースの開放 static void UnLoad(void); // 作成(シーン管理) // pos : 位置 // nModelId : モデル番号 // pCol : 色情報 // layer : レイヤー static CSteelblock * Create( int const & nModelId, // モデル番号 GRID const & Grid, // 行列高さ番号 D3DXCOLOR * pCol, // 色情報 float const & fGravity, // 重力 CScene::LAYER const & layer = CScene::LAYER_3DBLOCK // レイヤー ); // 作成(個人管理) // pos : 位置 // nModelId : モデル番号 // pCol : 色情報 static CSteelblock * Create_Self( int const & nModelId, // モデル番号 GRID const & Grid, // 行列高さ番号 D3DXCOLOR * pCol // 色情報 ); // unique_ptr作成(個人管理unique) // ※戻り値はstd::moveで受け取る // pos : 位置 // nModelId : モデル番号 // pCol : 色情報 static std::unique_ptr<CSteelblock> Creat_Unique( int const & nModelId, // モデル番号 GRID const & Grid, // 行列高さ番号 D3DXCOLOR * pCol // 色情報 ); #ifdef _DEBUG // デバッグ処理 virtual void Debug(void); #endif // _DEBUG protected: /* 関数 */ // 設定 // private: /* 関数 */ /* 変数 */ }; #endif
[ "nishin369714@gmail.com" ]
nishin369714@gmail.com
a5cd8305d0f9db37b01d8e239b735ee612ddf207
19eb33d5832970b726e36e5f13a4d07914f9df14
/Controls/trip.h
32c2cd717a88de196f8d47d20e4da7cd340e0ca0
[]
no_license
Clackgot/Airport-source-code
ad3f90bbe58df82c50c0b39dda2a3044887a28ca
0b3dd142104134c2d1eebf647fb9c1c43f46bec1
refs/heads/master
2021-05-18T10:57:17.134800
2020-03-30T06:42:28
2020-03-30T06:42:28
251,218,626
0
0
null
null
null
null
UTF-8
C++
false
false
484
h
#ifndef TRIP_H #define TRIP_H #include <QString> #include <QDateTime> class Trip { public: int id; QString name; QDateTime time; int company; int direction; int status; int terminal; int airplane; QString title; public: Trip(int id, QString name, QDateTime time, int company, int direction, int status, int terminal, int airplane, QString title); Trip(); }; #endif // TRIP_H
[ "noreply@github.com" ]
Clackgot.noreply@github.com
a517a1aa3a15310a16c4f5b1f18272027c0565a2
bc4f297919596f3af1b0af9b8c0433c4a0e7ca74
/D_Alice_Bob_and_Candies.cpp
57f5bea601e394022dbe5339d512cc2391e29d2d
[]
no_license
fahadkhaanz/Competitive-Programming
34d92ec73c0b4aba5a2a18c68f998a92a57dc57e
bc3d4206d6749055d67e7b291acd230a31a4e5bc
refs/heads/master
2023-08-02T05:26:03.594439
2021-09-26T08:44:15
2021-09-26T08:44:15
291,102,479
0
0
null
null
null
null
UTF-8
C++
false
false
2,964
cpp
//git pull --rebase origin master #include<bits/stdc++.h> using namespace std; #define gc getchar_unlocked #define fo(i,n) for(int i=0;i<n;i++) #define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1) #define ll long long #define si(x) scanf("%d",&x) #define sl(x) scanf("%lld",&x) #define ss(s) scanf("%s",s) #define pi(x) printf("%d\n",x) #define pl(x) printf("%lld\n",x) #define ps(s) printf("%s\n",s) #define deb(x) cout << #x << "=" << x << endl #define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl #define pb push_back #define mp make_pair #define F first #define S second #define all(x) x.begin(), x.end() #define clr(x) memset(x, 0, sizeof(x)) #define sortall(x) sort(all(x)) #define tr(it, a) for(auto it = a.begin(); it != a.end(); it++) #define PI 3.1415926535897932384626 #define wi(t) int t;cin>>t;while(t--) typedef pair<int, int> pii; typedef pair<ll, ll> pl; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pl> vpl; typedef vector<vi> vvi; typedef vector<vl> vvl; mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count()); int rng(int lim) { uniform_int_distribution<int> uid(0,lim-1); return uid(rang); } int mpow(int base, int exp); void ipgraph(int n, int m); void dfs(int u, int par); const int mod = 1000000007; const int N = 3e5, M = N; //======================= vi g[N]; int a[N]; ll int gcd(ll int a, ll int b) { if (b == 0) return a; return gcd(b, a % b); } int tc=1; void solve() { ll int n; cin>>n; vl ar(n); fo(i,n) cin>>ar[i]; ll int al=0,bob=0,mo=0,all=0,bo=0; int i=0,j=n-1; while(i<=j) { al=0; int c=0; while(al<=bob) { if(i>j) break; al=al+ar[i++]; if(c==0) mo++; c++; } all+=al; c=0; bob=0; while(bob<=al) { if(i>j) break; bob+=ar[j--]; if(c==0) mo++; c++; } bo+=bob; } cout<<mo<<" "<<all<<" "<<bo<<"\n"; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); wi(t) { solve(); } return 0; } int mpow(int base, int exp) { base %= mod; int result = 1; while (exp > 0) { if (exp & 1) result = ((ll)result * base) % mod; base = ((ll)base * base) % mod; exp >>= 1; } return result; } void ipgraph(int n, int m){ int i, u, v; while(m--){ cin>>u>>v; u--, v--; g[u].pb(v); g[v].pb(u); } } void dfs(int u, int par){ for(int v:g[u]){ if (v == par) continue; dfs(v, u); } }
[ "fk0881889@gmail.com" ]
fk0881889@gmail.com
acdfb00002eb165983feeea630761ea5ac283697
9638a88e0e59707e741c413b6ede69dfa8e95f63
/main34_fehlerfrei/ConnectFour.h
19759fb510eff85bbb2be53263a86c13766dfd37
[]
no_license
Fibs2000/Table_stabil_2015
f641a922fb70d27196e3827a2f0029c97f4b1d44
3c1b42f458a5041e9541fae1a9800485d9615d63
refs/heads/master
2021-01-10T17:19:12.017704
2015-11-10T15:46:03
2015-11-10T15:46:03
45,922,170
0
0
null
null
null
null
UTF-8
C++
false
false
469
h
#ifndef ConnectFour_h #define ConnectFour_h #include "Game.h" class ConnectFour : public Game{ public: ConnectFour(NESController *controller, Adafruit_WS2801 *strip, RGBmatrixPanel *matrix); ~ConnectFour(); void newGame(); void run(); void resume(); private: void updateDisplay(); void redrawBoard(); int dropPos; byte curPlayer; byte winner; Point winPos[4]; long winTime; int dropHeight; byte droppedPieces[7][6]; const static int xOffset; }; #endif
[ "michel.fibs@gmail.com" ]
michel.fibs@gmail.com
43099c1f91000fd5a9dcc175b86bfb1dd5640a14
0014fb5ce4aa3a6f460128bb646a3c3cfe81eb9e
/testdata/8/2/src/node6.cpp
0cb52d2026c4a56e3862b81582d8116e08f5bd37
[]
no_license
yps158/randomGraph
c1fa9c531b11bb935d112d1c9e510b5c02921df2
68f9e2e5b0bed1f04095642ee6924a68c0768f0c
refs/heads/master
2021-09-05T05:32:45.210171
2018-01-24T11:23:06
2018-01-24T11:23:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include "unistd.h" #include <sstream> #include <random> std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<> d(0.029935, 0.005); class Node6{ public: Node6(){ sub_0_6_flag = 0; sub_0_6 = n.subscribe("topic_0_6", 1, &Node6::middlemanCallback0,this); pub_6_7 = n.advertise<std_msgs::String>("topic_6_7", 1); } void middlemanCallback0(const std_msgs::String::ConstPtr& msg){ if( true){ usleep(d(gen)*1000000); ROS_INFO("I'm node6 last from node0, intercepted: [%s]", msg->data.c_str()); pub_6_7.publish(msg); } else{ ROS_INFO("I'm node6, from node0 intercepted: [%s]", msg->data.c_str()); sub_0_6_flag = 1; } } private: ros::NodeHandle n; ros::Publisher pub_6_7; int sub_0_6_flag; ros::Subscriber sub_0_6; }; int main(int argc, char **argv){ ros::init(argc, argv, "node6"); Node6 node6; ros::spin(); return 0; }
[ "sasaki@thinkingreed.co.jp" ]
sasaki@thinkingreed.co.jp
ca588cda8d0a10ac6126b003cd39120cc9ddb0ff
32c0040dbb00970af34bf437c96d66d58e201ee0
/Include/TheEngine/filesystem/file.h
34b066d7e797efd6c835bfb6e53d7288f8b16e92
[]
no_license
Exh/synqera_engine
da456860c59d82fa0ef451a8332a9216516618bc
31a39f952fe47d15de0819e007b287a38ae966fd
refs/heads/master
2021-04-06T20:08:34.495983
2016-02-16T13:14:52
2016-02-16T13:14:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
487
h
#ifndef _THE_FILE_ #define _THE_FILE_ #include "TheEngine/common.h" enum ChunkType { SURFACE = 0, VERTEX, BONES, BONE_ANIMATION_HEADER, BONE_ANIMATION_CURVE }; struct ChunkHeader { ChunkType type; int32_t offset; int32_t size; int32_t dummyData[4]; }; class TheFile { std::vector<ChunkHeader> headers; public: TheFile(the::filesystem::stream &stream); ~TheFile(){} std::vector<ChunkHeader> getHeaders(ChunkType type); ChunkHeader getHeader(ChunkType type); }; #endif
[ "kirill.shabordin@dev.zodiac.tv" ]
kirill.shabordin@dev.zodiac.tv
34811ed5e6a8a80d025a6274f8c7236e0477e0e0
c8a6040af5a8a5dd8f89bbabde1d00519ef1ea62
/android_webview/browser/aw_feature_list.cc
c37a0351a0410ed368469da1180a27f32c8ebd12
[ "BSD-3-Clause" ]
permissive
imdark/chromium
a02c7f42444bd2f0619cfdeaf2c79a48baf9534f
088d11844c64d6477e49e31036a621a92853cc53
refs/heads/master
2023-01-16T10:34:55.745660
2019-04-02T03:21:05
2019-04-02T03:21:05
161,010,625
0
0
NOASSERTION
2018-12-09T06:15:31
2018-12-09T06:15:30
null
UTF-8
C++
false
false
2,355
cc
// Copyright 2018 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 "android_webview/browser/aw_feature_list.h" #include <string> #include "base/android/jni_string.h" #include "base/feature_list.h" #include "base/macros.h" #include "base/stl_util.h" #include "jni/AwFeatureList_jni.h" using base::android::ConvertJavaStringToUTF8; using base::android::JavaParamRef; namespace android_webview { namespace { // Array of features exposed through the Java ChromeFeatureList API. Entries in // this array may either refer to features defined in the header of this file or // in other locations in the code base (e.g. content/, components/, etc). const base::Feature* kFeaturesExposedToJava[] = { &features::kWebViewConnectionlessSafeBrowsing, &features::kWebViewPageStartedOnCommit, }; const base::Feature* FindFeatureExposedToJava(const std::string& feature_name) { for (size_t i = 0; i < base::size(kFeaturesExposedToJava); ++i) { if (kFeaturesExposedToJava[i]->name == feature_name) return kFeaturesExposedToJava[i]; } NOTREACHED() << "Queried feature cannot be found in AwFeatureList: " << feature_name; return nullptr; } } // namespace namespace features { // Alphabetical: // Use the SafeBrowsingApiHandler which uses the connectionless GMS APIs. This // Feature is checked and used in downstream internal code. const base::Feature kWebViewConnectionlessSafeBrowsing{ "WebViewConnectionlessSafeBrowsing", base::FEATURE_DISABLED_BY_DEFAULT}; // Kill switch for feature to call onPageFinished for browser-initiated // navigations when the navigation commits. const base::Feature kWebViewPageStartedOnCommit{ "WebViewPageStartedOnCommit", base::FEATURE_DISABLED_BY_DEFAULT}; // Whether the application package name is logged in UMA. const base::Feature kWebViewUmaLogAppPackageName{ "WebViewUmaLogAppPackageName", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace features static jboolean JNI_AwFeatureList_IsEnabled( JNIEnv* env, const JavaParamRef<jstring>& jfeature_name) { const base::Feature* feature = FindFeatureExposedToJava(ConvertJavaStringToUTF8(env, jfeature_name)); return base::FeatureList::IsEnabled(*feature); } } // namespace android_webview
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
91189d9b9a3ea29b5dcbcaa7aa6e87cf19956524
e4f347154205d12124a07f660f5965cc6abc1fc3
/src/Calque/LayerStack.hpp
71c6439a62bbaf4778ea52c38e78f2299ad8edee
[]
no_license
jonike/FriendPaint
45fb89103b95520e808bc2bf146a52b1338dfbb2
2adb49452c2a6734714cd607ab7161fb521c7b37
refs/heads/master
2021-06-14T18:20:38.346275
2017-01-22T22:01:13
2017-01-22T22:01:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
509
hpp
#ifndef DEF_LAYERSTACK #define DEF_LAYERSTACK #include <iostream> #include <string> #include <vector> #include "Layer.hpp" class LayerStack { public: LayerStack(); void createLayer(sf::Uint32 index, sf::String name); void moveLayer(Uint32 index, Uint32 delta); void renameLayer(sf::Uint32 index, sf::String new_name); void deleteLayer(sf::Uint32 index); void mergeDownLayer(sf::Uint32 index); private: std::vector<Layer*> list; }; #endif
[ "yoanlecoq.io@gmail.com" ]
yoanlecoq.io@gmail.com
2ca8e56518f1acabeeeb2895b339c1090d3d98bf
4f052287d727d37a56559517267c51555025a7f2
/mortage_calculation/main.cpp
82c3ce1494d30052cd235c7e262ca1013b4dfea2
[]
no_license
davidjie1949/linux_os_coding
2c87bce089450151514e24cba13f32db1625b498
8ecda327acbb02967b31e99d28fb8ac96de8f3d7
refs/heads/master
2023-03-04T07:01:05.065943
2021-02-17T05:20:36
2021-02-17T05:20:36
329,320,752
0
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
#include <iostream> #include "mortage.h" using namespace std; int main(){ mortage jieYang(2020, 0.02375, 600000, 0.2); cout << jieYang.getYear() << endl; cout << jieYang.getDownPayment() << endl; cout << jieYang.getInterestRate() << endl; cout << jieYang.loan_amount() << endl; cout << jieYang.total_interest_paid() << endl; return 0; }
[ "jieyng@umich.edu" ]
jieyng@umich.edu
31d8057c61aad58272afcb781fc29698c298738a
cd2f5e7775dbca9eec9f0fcd88a4635a2d2b0414
/components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate_unittest.cc
2d119daf57463250b8cc64b8446fc6426762fa12
[ "BSD-3-Clause" ]
permissive
ghj1040110333/chromium-1
8462ba0ca940fe3f4284d66036fb41f83cb7065e
374d3a7593027eb6b26bf290e387e7de1fa9612a
refs/heads/master
2023-03-02T22:22:29.564010
2018-02-11T09:21:22
2018-02-11T09:21:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
95,911
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 "components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <map> #include <string> #include <utility> #include "base/command_line.h" #include "base/files/file_util.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/metrics/field_trial.h" #include "base/numerics/safe_conversions.h" #include "base/optional.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/safe_sprintf.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" #include "base/test/mock_entropy_provider.h" #include "base/test/scoped_feature_list.h" #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_test_utils.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_data.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_metrics.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_request_options.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_features.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_server.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h" #include "components/data_reduction_proxy/core/common/lofi_decider.h" #include "components/data_reduction_proxy/proto/client_config.pb.h" #include "components/previews/core/previews_decider.h" #include "components/previews/core/previews_experiments.h" #include "components/previews/core/previews_features.h" #include "net/base/host_port_pair.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/base/proxy_server.h" #include "net/http/http_request_headers.h" #include "net/http/http_response_headers.h" #include "net/http/http_util.h" #include "net/nqe/effective_connection_type.h" #include "net/nqe/network_quality_estimator_test_util.h" #include "net/proxy_resolution/proxy_config.h" #include "net/proxy_resolution/proxy_info.h" #include "net/proxy_resolution/proxy_retry_info.h" #include "net/proxy_resolution/proxy_service.h" #include "net/socket/socket_test_util.h" #include "net/test/cert_test_util.h" #include "net/test/gtest_util.h" #include "net/test/test_data_directory.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_job_factory_impl.h" #include "net/url_request/url_request_status.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace data_reduction_proxy { namespace { using TestNetworkDelegate = net::NetworkDelegateImpl; const char kOtherProxy[] = "testproxy:17"; const char kTestURL[] = "http://www.google.com/"; const char kSecureTestURL[] = "https://www.google.com/"; const char kReceivedValidOCLHistogramName[] = "Net.HttpContentLengthWithValidOCL"; const char kOriginalValidOCLHistogramName[] = "Net.HttpOriginalContentLengthWithValidOCL"; const char kDifferenceValidOCLHistogramName[] = "Net.HttpContentLengthDifferenceWithValidOCL"; // HTTP original content length const char kOriginalInsecureDirectHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.Direct"; const char kOriginalInsecureViaDRPHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.ViaDRP"; const char kOriginalInsecureBypassedHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.BypassedDRP"; const char kOriginalInsecureOtherHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.Other"; // HTTP video original content length const char kOriginalVideoInsecureDirectHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.Direct.Video"; const char kOriginalVideoInsecureViaDRPHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.ViaDRP.Video"; const char kOriginalVideoInsecureBypassedHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.BypassedDRP.Video"; const char kOriginalVideoInsecureOtherHistogramName[] = "Net.HttpOriginalContentLengthV2.Http.Other.Video"; // HTTPS original content length const char kOriginalSecureDirectHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.Direct"; const char kOriginalSecureViaDRPHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.ViaDRP"; const char kOriginalSecureBypassedHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.BypassedDRP"; const char kOriginalSecureOtherHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.Other"; // HTTPS video original content length const char kOriginalVideoSecureDirectHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.Direct.Video"; const char kOriginalVideoSecureViaDRPHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.ViaDRP.Video"; const char kOriginalVideoSecureBypassedHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.BypassedDRP.Video"; const char kOriginalVideoSecureOtherHistogramName[] = "Net.HttpOriginalContentLengthV2.Https.Other.Video"; // Lo-Fi histograms. const char kReceivedValidOCLLoFiOnHistogramName[] = "Net.HttpContentLengthWithValidOCL.LoFiOn"; const char kOriginalValidOCLLoFiOnHistogramName[] = "Net.HttpOriginalContentLengthWithValidOCL.LoFiOn"; const char kDifferenceValidOCLLoFiOnHistogramName[] = "Net.HttpContentLengthDifferenceWithValidOCL.LoFiOn"; const char kReceivedHistogramName[] = "Net.HttpContentLength"; const char kReceivedInsecureDirectHistogramName[] = "Net.HttpContentLengthV2.Http.Direct"; const char kReceivedInsecureViaDRPHistogramName[] = "Net.HttpContentLengthV2.Http.ViaDRP"; const char kReceivedInsecureBypassedHistogramName[] = "Net.HttpContentLengthV2.Http.BypassedDRP"; const char kReceivedInsecureOtherHistogramName[] = "Net.HttpContentLengthV2.Http.Other"; const char kReceivedSecureDirectHistogramName[] = "Net.HttpContentLengthV2.Https.Direct"; const char kReceivedSecureViaDRPHistogramName[] = "Net.HttpContentLengthV2.Https.ViaDRP"; const char kReceivedSecureBypassedHistogramName[] = "Net.HttpContentLengthV2.Https.BypassedDRP"; const char kReceivedSecureOtherHistogramName[] = "Net.HttpContentLengthV2.Https.Other"; const char kReceivedVideoInsecureDirectHistogramName[] = "Net.HttpContentLengthV2.Http.Direct.Video"; const char kReceivedVideoInsecureViaDRPHistogramName[] = "Net.HttpContentLengthV2.Http.ViaDRP.Video"; const char kReceivedVideoInsecureBypassedHistogramName[] = "Net.HttpContentLengthV2.Http.BypassedDRP.Video"; const char kReceivedVideoInsecureOtherHistogramName[] = "Net.HttpContentLengthV2.Http.Other.Video"; const char kReceivedVideoSecureDirectHistogramName[] = "Net.HttpContentLengthV2.Https.Direct.Video"; const char kReceivedVideoSecureViaDRPHistogramName[] = "Net.HttpContentLengthV2.Https.ViaDRP.Video"; const char kReceivedVideoSecureBypassedHistogramName[] = "Net.HttpContentLengthV2.Https.BypassedDRP.Video"; const char kReceivedVideoSecureOtherHistogramName[] = "Net.HttpContentLengthV2.Https.Other.Video"; const char kOriginalHistogramName[] = "Net.HttpOriginalContentLength"; const char kDifferenceHistogramName[] = "Net.HttpContentLengthDifference"; const char kFreshnessLifetimeHistogramName[] = "Net.HttpContentFreshnessLifetime"; const char kCacheableHistogramName[] = "Net.HttpContentLengthCacheable"; const char kCacheable4HoursHistogramName[] = "Net.HttpContentLengthCacheable4Hours"; const char kCacheable24HoursHistogramName[] = "Net.HttpContentLengthCacheable24Hours"; const int64_t kResponseContentLength = 100; const int64_t kOriginalContentLength = 200; #if defined(OS_ANDROID) const Client kClient = Client::CHROME_ANDROID; #elif defined(OS_IOS) const Client kClient = Client::CHROME_IOS; #elif defined(OS_MACOSX) const Client kClient = Client::CHROME_MAC; #elif defined(OS_CHROMEOS) const Client kClient = Client::CHROME_CHROMEOS; #elif defined(OS_LINUX) const Client kClient = Client::CHROME_LINUX; #elif defined(OS_WIN) const Client kClient = Client::CHROME_WINDOWS; #elif defined(OS_FREEBSD) const Client kClient = Client::CHROME_FREEBSD; #elif defined(OS_OPENBSD) const Client kClient = Client::CHROME_OPENBSD; #elif defined(OS_SOLARIS) const Client kClient = Client::CHROME_SOLARIS; #elif defined(OS_QNX) const Client kClient = Client::CHROME_QNX; #else const Client kClient = Client::UNKNOWN; #endif class TestLoFiDecider : public LoFiDecider { public: TestLoFiDecider() : should_be_client_lofi_(false), should_be_client_lofi_auto_reload_(false), should_request_lofi_resource_(false), ignore_is_using_data_reduction_proxy_check_(false) {} ~TestLoFiDecider() override {} bool IsUsingLoFi(const net::URLRequest& request) const override { return should_request_lofi_resource_; } void SetIsUsingLoFi(bool should_request_lofi_resource) { should_request_lofi_resource_ = should_request_lofi_resource; } void SetIsUsingClientLoFi(bool should_be_client_lofi) { should_be_client_lofi_ = should_be_client_lofi; } void SetIsClientLoFiAutoReload(bool should_be_client_lofi_auto_reload) { should_be_client_lofi_auto_reload_ = should_be_client_lofi_auto_reload; } void MaybeSetAcceptTransformHeader( const net::URLRequest& request, net::HttpRequestHeaders* headers) const override { if (should_request_lofi_resource_) { headers->SetHeader(chrome_proxy_accept_transform_header(), empty_image_directive()); } } bool IsSlowPagePreviewRequested( const net::HttpRequestHeaders& headers) const override { std::string header_value; if (headers.GetHeader(chrome_proxy_accept_transform_header(), &header_value)) { return header_value == empty_image_directive() || header_value == lite_page_directive(); } return false; } bool IsLitePagePreviewRequested( const net::HttpRequestHeaders& headers) const override { std::string header_value; if (headers.GetHeader(chrome_proxy_accept_transform_header(), &header_value)) { return header_value == lite_page_directive(); } return false; } void MaybeApplyAMPPreview( net::URLRequest* request, GURL* new_url, previews::PreviewsDecider* previews_decider) const override { return; } void RemoveAcceptTransformHeader( net::HttpRequestHeaders* headers) const override { if (ignore_is_using_data_reduction_proxy_check_) return; headers->RemoveHeader(chrome_proxy_accept_transform_header()); } bool ShouldRecordLoFiUMA(const net::URLRequest& request) const override { return should_request_lofi_resource_; } bool IsClientLoFiImageRequest(const net::URLRequest& request) const override { return should_be_client_lofi_; } bool IsClientLoFiAutoReloadRequest( const net::URLRequest& request) const override { return should_be_client_lofi_auto_reload_; } void ignore_is_using_data_reduction_proxy_check() { ignore_is_using_data_reduction_proxy_check_ = true; } private: bool should_be_client_lofi_; bool should_be_client_lofi_auto_reload_; bool should_request_lofi_resource_; bool ignore_is_using_data_reduction_proxy_check_; }; class TestLoFiUIService : public LoFiUIService { public: TestLoFiUIService() : on_lofi_response_(false) {} ~TestLoFiUIService() override {} bool DidNotifyLoFiResponse() const { return on_lofi_response_; } void OnLoFiReponseReceived(const net::URLRequest& request) override { on_lofi_response_ = true; } void ClearResponse() { on_lofi_response_ = false; } private: bool on_lofi_response_; }; class TestPreviewsDecider : public previews::PreviewsDecider { public: TestPreviewsDecider() {} ~TestPreviewsDecider() override {} // previews::PreviewsDecider: bool ShouldAllowPreviewAtECT( const net::URLRequest& request, previews::PreviewsType type, net::EffectiveConnectionType effective_connection_type_threshold, const std::vector<std::string>& host_blacklist_from_server) const override { return true; } // Same as ShouldAllowPreviewAtECT, but uses the previews default // EffectiveConnectionType and no blacklisted hosts from the server. bool ShouldAllowPreview(const net::URLRequest& request, previews::PreviewsType type) const override { return true; } }; enum ProxyTestConfig { USE_SECURE_PROXY, USE_INSECURE_PROXY, BYPASS_PROXY }; class DataReductionProxyNetworkDelegateTest : public testing::Test { public: DataReductionProxyNetworkDelegateTest() : lofi_decider_(nullptr), lofi_ui_service_(nullptr), ssl_socket_data_provider_(net::ASYNC, net::OK) { ssl_socket_data_provider_.next_proto = net::kProtoHTTP11; ssl_socket_data_provider_.ssl_info.cert = net::ImportCertFromFile( net::GetTestCertsDirectory(), "unittest.selfsigned.der"); } void Init(ProxyTestConfig proxy_config, bool enable_brotli_globally) { net::ProxyServer proxy_server; switch (proxy_config) { case BYPASS_PROXY: proxy_server = net::ProxyServer::Direct(); break; case USE_SECURE_PROXY: proxy_server = net::ProxyServer::FromURI( "https://origin.net:443", net::ProxyServer::SCHEME_HTTPS); break; case USE_INSECURE_PROXY: proxy_server = net::ProxyServer::FromURI("http://origin.net:80", net::ProxyServer::SCHEME_HTTP); break; } context_.reset(new net::TestURLRequestContext(true)); context_storage_.reset(new net::URLRequestContextStorage(context_.get())); proxy_resolution_service_ = net::ProxyResolutionService::CreateFixedFromPacResult( proxy_server.ToPacString()); context_->set_proxy_resolution_service(proxy_resolution_service_.get()); context_->set_network_quality_estimator(&test_network_quality_estimator_); mock_socket_factory_.reset(new net::MockClientSocketFactory()); DataReductionProxyTestContext::Builder builder; builder = builder.WithClient(kClient) .WithMockClientSocketFactory(mock_socket_factory_.get()) .WithURLRequestContext(context_.get()); if (proxy_config != BYPASS_PROXY) { builder = builder.WithProxiesForHttp({DataReductionProxyServer( proxy_server, ProxyServer::UNSPECIFIED_TYPE)}); } test_context_ = builder.Build(); context_->set_client_socket_factory(mock_socket_factory_.get()); test_context_->AttachToURLRequestContext(context_storage_.get()); std::unique_ptr<TestLoFiDecider> lofi_decider(new TestLoFiDecider()); lofi_decider_ = lofi_decider.get(); test_context_->io_data()->set_lofi_decider(std::move(lofi_decider)); std::unique_ptr<TestLoFiUIService> lofi_ui_service(new TestLoFiUIService()); lofi_ui_service_ = lofi_ui_service.get(); test_context_->io_data()->set_lofi_ui_service(std::move(lofi_ui_service)); context_->set_enable_brotli(enable_brotli_globally); context_->Init(); test_context_->DisableWarmupURLFetch(); test_context_->EnableDataReductionProxyWithSecureProxyCheckSuccess(); } // Build the sockets by adding appropriate mock data for // |effective_connection_types.size()| number of requests. Data for // chrome-Proxy-ect header is added to the mock data if |expect_ect_header| // is true. |reads_list|, |mock_writes| and |writes_list| should be empty, and // are owned by the caller. void BuildSocket(const std::string& response_headers, const std::string& response_body, bool expect_ect_header, const std::vector<net::EffectiveConnectionType>& effective_connection_types, std::vector<net::MockRead>* reads_list, std::vector<std::string>* mock_writes, std::vector<net::MockWrite>* writes_list) { EXPECT_LT(0u, effective_connection_types.size()); EXPECT_TRUE(reads_list->empty()); EXPECT_TRUE(mock_writes->empty()); EXPECT_TRUE(writes_list->empty()); for (size_t i = 0; i < effective_connection_types.size(); ++i) { reads_list->push_back(net::MockRead(response_headers.c_str())); reads_list->push_back(net::MockRead(response_body.c_str())); } reads_list->push_back(net::MockRead(net::SYNCHRONOUS, net::OK)); std::string prefix = std::string("GET ") .append(kTestURL) .append(" HTTP/1.1\r\n") .append("Host: ") .append(GURL(kTestURL).host()) .append( "\r\n" "Proxy-Connection: keep-alive\r\n" "User-Agent:\r\n" "Accept-Encoding: gzip, deflate\r\n" "Accept-Language: en-us,fr\r\n"); if (io_data()->test_request_options()->GetHeaderValueForTesting().empty()) { // Force regeneration of Chrome-Proxy header. io_data()->test_request_options()->SetSecureSession("123"); } EXPECT_FALSE( io_data()->test_request_options()->GetHeaderValueForTesting().empty()); std::string suffix = std::string("Chrome-Proxy: ") + io_data()->test_request_options()->GetHeaderValueForTesting() + std::string("\r\n\r\n"); mock_socket_factory_->AddSSLSocketDataProvider(&ssl_socket_data_provider_); for (net::EffectiveConnectionType effective_connection_type : effective_connection_types) { std::string ect_header; if (expect_ect_header) { ect_header = "chrome-proxy-ect: " + std::string(net::GetNameForEffectiveConnectionType( effective_connection_type)) + "\r\n"; } std::string mock_write = prefix + ect_header + suffix; mock_writes->push_back(mock_write); writes_list->push_back(net::MockWrite(mock_writes->back().c_str())); } EXPECT_FALSE(socket_); socket_ = std::make_unique<net::StaticSocketDataProvider>( reads_list->data(), reads_list->size(), writes_list->data(), writes_list->size()); mock_socket_factory_->AddSocketDataProvider(socket_.get()); } static void VerifyHeaders(bool expected_data_reduction_proxy_used, bool expected_lofi_used, const net::HttpRequestHeaders& headers) { EXPECT_EQ(expected_data_reduction_proxy_used, headers.HasHeader(chrome_proxy_header())); std::string header_value; headers.GetHeader(chrome_proxy_accept_transform_header(), &header_value); EXPECT_EQ(expected_data_reduction_proxy_used && expected_lofi_used, header_value.find("empty-image") != std::string::npos); } void VerifyDidNotifyLoFiResponse(bool lofi_response) const { EXPECT_EQ(lofi_response, lofi_ui_service_->DidNotifyLoFiResponse()); } void ClearLoFiUIService() { lofi_ui_service_->ClearResponse(); } void VerifyDataReductionProxyData(const net::URLRequest& request, bool data_reduction_proxy_used, bool lofi_used) { DataReductionProxyData* data = DataReductionProxyData::GetData(request); if (!data_reduction_proxy_used) { EXPECT_FALSE(data); } else { EXPECT_TRUE(data->used_data_reduction_proxy()); EXPECT_EQ(lofi_used, data->lofi_requested()); } } // Each line in |response_headers| should end with "\r\n" and not '\0', and // the last line should have a second "\r\n". // An empty |response_headers| is allowed. It works by making this look like // an HTTP/0.9 response, since HTTP/0.9 responses don't have headers. std::unique_ptr<net::URLRequest> FetchURLRequest( const GURL& url, net::HttpRequestHeaders* request_headers, const std::string& response_headers, int64_t response_content_length, int load_flags) { const std::string response_body( base::checked_cast<size_t>(response_content_length), ' '); net::MockRead reads[] = {net::MockRead(response_headers.c_str()), net::MockRead(response_body.c_str()), net::MockRead(net::SYNCHRONOUS, net::OK)}; net::StaticSocketDataProvider socket(reads, arraysize(reads), nullptr, 0); mock_socket_factory_->AddSocketDataProvider(&socket); net::TestDelegate delegate; std::unique_ptr<net::URLRequest> request = context_->CreateRequest( url, net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); if (request_headers) request->SetExtraRequestHeaders(*request_headers); request->SetLoadFlags(request->load_flags() | load_flags); request->Start(); base::RunLoop().RunUntilIdle(); return request; } // Reads brotli encoded content to |encoded_brotli_buffer_|. void ReadBrotliFile() { // Get the path of data directory. const size_t kDefaultBufferSize = 4096; base::FilePath data_dir; PathService::Get(base::DIR_SOURCE_ROOT, &data_dir); data_dir = data_dir.AppendASCII("net"); data_dir = data_dir.AppendASCII("data"); data_dir = data_dir.AppendASCII("filter_unittests"); // Read data from the encoded file into buffer. base::FilePath encoded_file_path; encoded_file_path = data_dir.AppendASCII("google.br"); ASSERT_TRUE( base::ReadFileToString(encoded_file_path, &encoded_brotli_buffer_)); ASSERT_GE(kDefaultBufferSize, encoded_brotli_buffer_.size()); } // Fetches a single URL request, verifies the correctness of Accept-Encoding // header, and verifies that the response is cached only if |expect_cached| // is set to true. Each line in |response_headers| should end with "\r\n" and // not '\0', and the last line should have a second "\r\n". An empty // |response_headers| is allowed. It works by making this look like an // HTTP/0.9 response, since HTTP/0.9 responses don't have headers. void FetchURLRequestAndVerifyBrotli(net::HttpRequestHeaders* request_headers, const std::string& response_headers, bool expect_cached, bool expect_brotli) { test_network_quality_estimator()->set_effective_connection_type( net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN); GURL url(kTestURL); int response_body_size = 140; std::string response_body; if (expect_brotli && !expect_cached) { response_body = encoded_brotli_buffer_; response_body_size = response_body.size(); } else { response_body = std::string(base::checked_cast<size_t>(response_body_size), ' '); } mock_socket_factory_->AddSSLSocketDataProvider(&ssl_socket_data_provider_); net::MockRead reads[] = {net::MockRead(response_headers.c_str()), net::MockRead(response_body.c_str()), net::MockRead(net::SYNCHRONOUS, net::OK)}; if (io_data()->test_request_options()->GetHeaderValueForTesting().empty()) { // Force regeneration of Chrome-Proxy header. io_data()->test_request_options()->SetSecureSession("123"); } EXPECT_FALSE( io_data()->test_request_options()->GetHeaderValueForTesting().empty()); std::string host = GURL(kTestURL).host(); std::string prefix_headers = std::string("GET ") .append(kTestURL) .append( " HTTP/1.1\r\n" "Host: ") .append(host) .append( "\r\n" "Proxy-Connection: keep-alive\r\n" "User-Agent:\r\n"); std::string accept_language_header("Accept-Language: en-us,fr\r\n"); std::string ect_header = "chrome-proxy-ect: " + std::string(net::GetNameForEffectiveConnectionType( net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN)) + "\r\n"; // Brotli is included in accept-encoding header only if the request went // to the network (i.e., it was not a cached response), and if data // reduction ptroxy network delegate added Brotli to the header. std::string accept_encoding_header = expect_brotli && !expect_cached ? "Accept-Encoding: gzip, deflate, br\r\n" : "Accept-Encoding: gzip, deflate\r\n"; std::string suffix_headers = std::string("Chrome-Proxy: ") + io_data()->test_request_options()->GetHeaderValueForTesting() + std::string("\r\n\r\n"); std::string mock_write = prefix_headers + accept_language_header + ect_header + accept_encoding_header + suffix_headers; if (expect_cached || !expect_brotli) { // Order of headers is different if the headers were modified by data // reduction proxy network delegate. mock_write = prefix_headers + accept_encoding_header + accept_language_header + ect_header + suffix_headers; } net::MockWrite writes[] = {net::MockWrite(mock_write.c_str())}; net::StaticSocketDataProvider socket(reads, arraysize(reads), writes, arraysize(writes)); mock_socket_factory_->AddSocketDataProvider(&socket); net::TestDelegate delegate; std::unique_ptr<net::URLRequest> request = context_->CreateRequest( url, net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); if (request_headers) request->SetExtraRequestHeaders(*request_headers); request->Start(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0, request->status().ToNetError()); if (!expect_cached) { EXPECT_EQ(response_body_size, request->received_response_content_length()); EXPECT_NE(0, request->GetTotalSentBytes()); EXPECT_NE(0, request->GetTotalReceivedBytes()); EXPECT_FALSE(request->was_cached()); VerifyBrotliPresent(request.get(), expect_brotli); } else { EXPECT_TRUE(request->was_cached()); std::string content_encoding_value; request->GetResponseHeaderByName("Content-Encoding", &content_encoding_value); EXPECT_EQ(expect_brotli, content_encoding_value == "br"); } } void VerifyBrotliPresent(net::URLRequest* request, bool expect_brotli) { net::HttpRequestHeaders request_headers_sent; EXPECT_TRUE(request->GetFullRequestHeaders(&request_headers_sent)); std::string accept_encoding_value; EXPECT_TRUE(request_headers_sent.GetHeader("Accept-Encoding", &accept_encoding_value)); EXPECT_NE(std::string::npos, accept_encoding_value.find("gzip")); std::string content_encoding_value; request->GetResponseHeaderByName("Content-Encoding", &content_encoding_value); if (expect_brotli) { // Brotli should be the last entry in the Accept-Encoding header. EXPECT_EQ(accept_encoding_value.length() - 2, accept_encoding_value.find("br")); EXPECT_EQ("br", content_encoding_value); } else { EXPECT_EQ(std::string::npos, accept_encoding_value.find("br")); } } void FetchURLRequestAndVerifyPageIdDirective(base::Optional<uint64_t> page_id, bool redirect_once) { std::string response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=1200\r\n" "Vary: accept-encoding\r\n\r\n"; GURL url(kTestURL); int response_body_size = 140; std::string response_body = std::string(base::checked_cast<size_t>(response_body_size), ' '); mock_socket_factory_->AddSSLSocketDataProvider(&ssl_socket_data_provider_); net::MockRead redirect_reads[] = { net::MockRead("HTTP/1.1 302 Redirect\r\n"), net::MockRead("Location: http://www.google.com/\r\n"), net::MockRead("Content-Length: 0\r\n\r\n"), net::MockRead(net::SYNCHRONOUS, net::OK), net::MockRead(response_headers.c_str()), net::MockRead(response_body.c_str()), net::MockRead(net::SYNCHRONOUS, net::OK)}; net::MockRead reads[] = {net::MockRead(response_headers.c_str()), net::MockRead(response_body.c_str()), net::MockRead(net::SYNCHRONOUS, net::OK)}; EXPECT_FALSE( io_data()->test_request_options()->GetHeaderValueForTesting().empty()); std::string page_id_value; if (page_id) { char page_id_buffer[17]; if (base::strings::SafeSPrintf(page_id_buffer, "%x", page_id.value()) > 0) { page_id_value = std::string("pid=") + page_id_buffer; } } std::string mock_write = "GET http://www.google.com/ HTTP/1.1\r\nHost: " "www.google.com\r\nProxy-Connection: " "keep-alive\r\nUser-Agent:\r\nAccept-Encoding: gzip, " "deflate\r\nAccept-Language: en-us,fr\r\n" "chrome-proxy-ect: 4G\r\n" "Chrome-Proxy: " + io_data()->test_request_options()->GetHeaderValueForTesting() + (page_id_value.empty() ? "" : (", " + page_id_value)) + "\r\n\r\n"; net::MockWrite redirect_writes[] = {net::MockWrite(mock_write.c_str()), net::MockWrite(mock_write.c_str())}; net::MockWrite writes[] = {net::MockWrite(mock_write.c_str())}; std::unique_ptr<net::StaticSocketDataProvider> socket; if (!redirect_once) { socket = std::make_unique<net::StaticSocketDataProvider>( reads, arraysize(reads), writes, arraysize(writes)); } else { socket = std::make_unique<net::StaticSocketDataProvider>( redirect_reads, arraysize(redirect_reads), redirect_writes, arraysize(redirect_writes)); } mock_socket_factory_->AddSocketDataProvider(socket.get()); net::TestDelegate delegate; std::unique_ptr<net::URLRequest> request = context_->CreateRequest( url, net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); if (!page_id_value.empty()) { request->SetLoadFlags(request->load_flags() | net::LOAD_MAIN_FRAME_DEPRECATED); } request->Start(); base::RunLoop().RunUntilIdle(); } // Fetches a request while the effective connection type is set to // |effective_connection_type|. Verifies that the request headers include the // chrome-proxy-ect header only if |expect_ect_header| is true. The response // must be served from the cache if |expect_cached| is true. void FetchURLRequestAndVerifyECTHeader( net::EffectiveConnectionType effective_connection_type, bool expect_ect_header, bool expect_cached) { test_network_quality_estimator()->set_effective_connection_type( effective_connection_type); net::TestDelegate delegate; std::unique_ptr<net::URLRequest> request = context_->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); request->Start(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(140, request->received_response_content_length()); EXPECT_EQ(expect_cached, request->was_cached()); EXPECT_EQ(expect_cached, request->GetTotalSentBytes() == 0); EXPECT_EQ(expect_cached, request->GetTotalReceivedBytes() == 0); net::HttpRequestHeaders sent_request_headers; EXPECT_NE(expect_cached, request->GetFullRequestHeaders(&sent_request_headers)); if (expect_cached) { // Request headers are missing. Return since there is nothing left to // check. return; } // Verify that chrome-proxy-ect header is present in the request headers // only if |expect_ect_header| is true. std::string ect_value; EXPECT_EQ(expect_ect_header, sent_request_headers.GetHeader( chrome_proxy_ect_header(), &ect_value)); if (!expect_ect_header) return; EXPECT_EQ(net::GetNameForEffectiveConnectionType(effective_connection_type), ect_value); } void DelegateStageDone(int result) {} void NotifyNetworkDelegate(net::URLRequest* request, const net::ProxyInfo& data_reduction_proxy_info, const net::ProxyRetryInfoMap& proxy_retry_info, net::HttpRequestHeaders* headers) { network_delegate()->NotifyBeforeURLRequest( request, base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), nullptr); network_delegate()->NotifyBeforeStartTransaction( request, base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), headers); network_delegate()->NotifyBeforeSendHeaders( request, data_reduction_proxy_info, proxy_retry_info, headers); } net::MockClientSocketFactory* mock_socket_factory() { return mock_socket_factory_.get(); } net::TestURLRequestContext* context() { return context_.get(); } net::NetworkDelegate* network_delegate() const { return context_->network_delegate(); } TestDataReductionProxyParams* params() const { return test_context_->config()->test_params(); } TestDataReductionProxyConfig* config() const { return test_context_->config(); } TestDataReductionProxyIOData* io_data() const { return test_context_->io_data(); } TestLoFiDecider* lofi_decider() const { return lofi_decider_; } net::TestNetworkQualityEstimator* test_network_quality_estimator() { return &test_network_quality_estimator_; } net::SSLSocketDataProvider* ssl_socket_data_provider() { return &ssl_socket_data_provider_; } private: base::MessageLoopForIO message_loop_; std::unique_ptr<net::MockClientSocketFactory> mock_socket_factory_; std::unique_ptr<net::ProxyResolutionService> proxy_resolution_service_; std::unique_ptr<net::TestURLRequestContext> context_; std::unique_ptr<net::URLRequestContextStorage> context_storage_; TestLoFiDecider* lofi_decider_; TestLoFiUIService* lofi_ui_service_; std::unique_ptr<DataReductionProxyTestContext> test_context_; net::TestNetworkQualityEstimator test_network_quality_estimator_; net::SSLSocketDataProvider ssl_socket_data_provider_; std::unique_ptr<net::StaticSocketDataProvider> socket_; // Encoded Brotli content read from a file. May be empty. std::string encoded_brotli_buffer_; }; TEST_F(DataReductionProxyNetworkDelegateTest, AuthenticationTest) { Init(USE_INSECURE_PROXY, false); std::unique_ptr<net::URLRequest> fake_request( FetchURLRequest(GURL(kTestURL), nullptr, std::string(), 0, 0)); net::ProxyInfo data_reduction_proxy_info; net::ProxyRetryInfoMap proxy_retry_info; std::string data_reduction_proxy; data_reduction_proxy_info.UseProxyServer( params()->proxies_for_http().front().proxy_server()); net::HttpRequestHeaders headers; // Call network delegate methods to ensure that appropriate chrome proxy // headers get added/removed. network_delegate()->NotifyBeforeStartTransaction( fake_request.get(), base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), &headers); network_delegate()->NotifyBeforeSendHeaders(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); EXPECT_TRUE(headers.HasHeader(chrome_proxy_header())); std::string header_value; headers.GetHeader(chrome_proxy_header(), &header_value); EXPECT_TRUE(header_value.find("ps=") != std::string::npos); EXPECT_TRUE(header_value.find("sid=") != std::string::npos); } TEST_F(DataReductionProxyNetworkDelegateTest, LoFiTransitions) { Init(USE_INSECURE_PROXY, false); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {previews::features::kPreviews, features::kDataReductionProxyDecidesTransform}, {}); // Enable Lo-Fi. bool is_data_reduction_proxy_enabled[] = {false, true}; for (size_t i = 0; i < arraysize(is_data_reduction_proxy_enabled); ++i) { net::ProxyInfo data_reduction_proxy_info; std::string proxy; if (is_data_reduction_proxy_enabled[i]) { data_reduction_proxy_info.UseProxyServer( params()->proxies_for_http().front().proxy_server()); } else { base::TrimString(kOtherProxy, "/", &proxy); data_reduction_proxy_info.UseNamedProxy(proxy); } // Needed as a parameter, but functionality is not tested. TestPreviewsDecider test_previews_decider; { // Main frame loaded. Lo-Fi should be used. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; net::TestDelegate delegate; std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); fake_request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); lofi_decider()->SetIsUsingLoFi(config()->ShouldAcceptServerPreview( *fake_request.get(), test_previews_decider)); NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); VerifyHeaders(is_data_reduction_proxy_enabled[i], true, headers); VerifyDataReductionProxyData( *fake_request, is_data_reduction_proxy_enabled[i], config()->ShouldAcceptServerPreview(*fake_request.get(), test_previews_decider)); } { // Lo-Fi is already off. Lo-Fi should not be used. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; net::TestDelegate delegate; std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); lofi_decider()->SetIsUsingLoFi(false); NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); VerifyHeaders(is_data_reduction_proxy_enabled[i], false, headers); VerifyDataReductionProxyData(*fake_request, is_data_reduction_proxy_enabled[i], false); } { // Lo-Fi is already on. Lo-Fi should be used. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; net::TestDelegate delegate; std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); lofi_decider()->SetIsUsingLoFi(true); NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); VerifyHeaders(is_data_reduction_proxy_enabled[i], true, headers); VerifyDataReductionProxyData(*fake_request, is_data_reduction_proxy_enabled[i], true); } { // Main frame request with Lo-Fi off. Lo-Fi should not be used. // State of Lo-Fi should persist until next page load. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; net::TestDelegate delegate; std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); fake_request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); lofi_decider()->SetIsUsingLoFi(false); NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); VerifyHeaders(is_data_reduction_proxy_enabled[i], false, headers); VerifyDataReductionProxyData(*fake_request, is_data_reduction_proxy_enabled[i], false); } { // Lo-Fi is off. Lo-Fi is still not used. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; net::TestDelegate delegate; std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); lofi_decider()->SetIsUsingLoFi(false); NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); VerifyHeaders(is_data_reduction_proxy_enabled[i], false, headers); VerifyDataReductionProxyData(*fake_request, is_data_reduction_proxy_enabled[i], false); } { // Main frame request. Lo-Fi should be used. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; net::TestDelegate delegate; std::unique_ptr<net::URLRequest> fake_request = context()->CreateRequest( GURL(kTestURL), net::IDLE, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS); fake_request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); lofi_decider()->SetIsUsingLoFi(config()->ShouldAcceptServerPreview( *fake_request.get(), test_previews_decider)); NotifyNetworkDelegate(fake_request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); VerifyDataReductionProxyData( *fake_request, is_data_reduction_proxy_enabled[i], config()->ShouldAcceptServerPreview(*fake_request.get(), test_previews_decider)); } } } TEST_F(DataReductionProxyNetworkDelegateTest, RequestDataConfigurations) { Init(USE_INSECURE_PROXY, false); const struct { bool lofi_on; bool used_data_reduction_proxy; bool main_frame; } tests[] = { // Lo-Fi off. Main Frame Request. {false, true, true}, // Data reduction proxy not used. Main Frame Request. {false, false, true}, // Data reduction proxy not used, Lo-Fi should not be used. Main Frame // Request. {true, false, true}, // Lo-Fi on. Main Frame Request. {true, true, true}, // Lo-Fi off. Not a Main Frame Request. {false, true, false}, // Data reduction proxy not used. Not a Main Frame Request. {false, false, false}, // Data reduction proxy not used, Lo-Fi should not be used. Not a Main // Frame Request. {true, false, false}, // Lo-Fi on. Not a Main Frame Request. {true, true, false}, }; for (const auto& test : tests) { net::ProxyInfo data_reduction_proxy_info; if (test.used_data_reduction_proxy) { data_reduction_proxy_info.UseProxyServer( params()->proxies_for_http().front().proxy_server()); } else { data_reduction_proxy_info.UseNamedProxy("port.of.other.proxy"); } // Main frame loaded. Lo-Fi should be used. net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; test_network_quality_estimator()->set_effective_connection_type( net::EFFECTIVE_CONNECTION_TYPE_OFFLINE); std::unique_ptr<net::URLRequest> request = context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); request->SetLoadFlags(test.main_frame ? net::LOAD_MAIN_FRAME_DEPRECATED : 0); lofi_decider()->SetIsUsingLoFi(test.lofi_on); io_data()->request_options()->SetSecureSession("fake-session"); // Call network delegate methods to ensure that appropriate chrome proxy // headers get added/removed. network_delegate()->NotifyBeforeStartTransaction( request.get(), base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), &headers); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); DataReductionProxyData* data = DataReductionProxyData::GetData(*request.get()); if (!test.used_data_reduction_proxy) { EXPECT_FALSE(data); } else { EXPECT_TRUE(data); EXPECT_EQ(test.main_frame ? net::EFFECTIVE_CONNECTION_TYPE_OFFLINE : net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN, data->effective_connection_type()); EXPECT_TRUE(data->used_data_reduction_proxy()); EXPECT_EQ(test.main_frame ? GURL(kTestURL) : GURL(), data->request_url()); EXPECT_EQ(test.main_frame ? "fake-session" : "", data->session_key()); EXPECT_EQ(test.lofi_on, data->lofi_requested()); } } } TEST_F(DataReductionProxyNetworkDelegateTest, RequestDataHoldbackConfigurations) { Init(USE_INSECURE_PROXY, false); const struct { bool data_reduction_proxy_enabled; bool used_direct; } tests[] = { { false, true, }, { false, false, }, { true, false, }, { true, true, }, }; test_network_quality_estimator()->set_effective_connection_type( net::EFFECTIVE_CONNECTION_TYPE_4G); base::FieldTrialList field_trial_list(nullptr); ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial( "DataCompressionProxyHoldback", "Enabled")); for (const auto& test : tests) { net::ProxyInfo data_reduction_proxy_info; if (test.used_direct) data_reduction_proxy_info.UseDirect(); else data_reduction_proxy_info.UseNamedProxy("some.other.proxy"); config()->UpdateConfigForTesting(test.data_reduction_proxy_enabled, true, true); std::unique_ptr<net::URLRequest> request = context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); request->set_method("GET"); io_data()->request_options()->SetSecureSession("fake-session"); net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); DataReductionProxyData* data = DataReductionProxyData::GetData(*request.get()); if (!test.data_reduction_proxy_enabled || !test.used_direct) { EXPECT_FALSE(data); } else { EXPECT_TRUE(data); EXPECT_TRUE(data->used_data_reduction_proxy()); EXPECT_EQ("fake-session", data->session_key()); EXPECT_EQ(GURL(kTestURL), data->request_url()); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_4G, data->effective_connection_type()); EXPECT_TRUE(data->page_id()); } } } TEST_F(DataReductionProxyNetworkDelegateTest, RedirectRequestDataCleared) { Init(USE_INSECURE_PROXY, false); net::ProxyInfo data_reduction_proxy_info; data_reduction_proxy_info.UseProxyServer( params()->proxies_for_http().front().proxy_server()); // Main frame loaded. Lo-Fi should be used. net::HttpRequestHeaders headers_original; net::ProxyRetryInfoMap proxy_retry_info; test_network_quality_estimator()->set_effective_connection_type( net::EFFECTIVE_CONNECTION_TYPE_OFFLINE); std::unique_ptr<net::URLRequest> request = context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); lofi_decider()->SetIsUsingLoFi(true); io_data()->request_options()->SetSecureSession("fake-session"); // Call network delegate methods to ensure that appropriate chrome proxy // headers get added/removed. network_delegate()->NotifyBeforeStartTransaction( request.get(), base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), &headers_original); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers_original); DataReductionProxyData* data = DataReductionProxyData::GetData(*request.get()); EXPECT_TRUE(data); EXPECT_EQ(net::EFFECTIVE_CONNECTION_TYPE_OFFLINE, data->effective_connection_type()); EXPECT_TRUE(data->used_data_reduction_proxy()); EXPECT_EQ(GURL(kTestURL), data->request_url()); EXPECT_EQ("fake-session", data->session_key()); EXPECT_TRUE(data->lofi_requested()); data_reduction_proxy_info.UseNamedProxy("port.of.other.proxy"); // Simulate a redirect even though the same URL is used. Should clear // DataReductionProxyData. network_delegate()->NotifyBeforeRedirect(request.get(), GURL(kTestURL)); data = DataReductionProxyData::GetData(*request.get()); EXPECT_FALSE(data && data->used_data_reduction_proxy()); // Call NotifyBeforeSendHeaders again with different proxy info to check that // new data isn't added. Use a new set of headers since the redirected HTTP // jobs do not reuse headers from the previous jobs. Also, call network // delegate methods to ensure that appropriate chrome proxy headers get // added/removed. net::HttpRequestHeaders headers_redirect; network_delegate()->NotifyBeforeStartTransaction( request.get(), base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), &headers_redirect); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers_redirect); data = DataReductionProxyData::GetData(*request.get()); EXPECT_FALSE(data); } TEST_F(DataReductionProxyNetworkDelegateTest, NetHistograms) { Init(USE_INSECURE_PROXY, false); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitWithFeatures( {previews::features::kPreviews, features::kDataReductionProxyDecidesTransform}, {}); base::HistogramTester histogram_tester; std::string response_headers = "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: " + base::Int64ToString(kOriginalContentLength) + "\r\n\r\n"; std::unique_ptr<net::URLRequest> fake_request(FetchURLRequest( GURL(kTestURL), nullptr, response_headers, kResponseContentLength, 0)); fake_request->SetLoadFlags(fake_request->load_flags() | net::LOAD_MAIN_FRAME_DEPRECATED); base::TimeDelta freshness_lifetime = fake_request->response_info().headers->GetFreshnessLifetimes( fake_request->response_info().response_time).freshness; histogram_tester.ExpectUniqueSample(kReceivedValidOCLHistogramName, kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kOriginalValidOCLHistogramName, kOriginalContentLength, 1); histogram_tester.ExpectUniqueSample(kOriginalInsecureViaDRPHistogramName, kOriginalContentLength, 1); histogram_tester.ExpectUniqueSample( kDifferenceValidOCLHistogramName, kOriginalContentLength - kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kReceivedHistogramName, kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kReceivedInsecureViaDRPHistogramName, kResponseContentLength, 1); histogram_tester.ExpectTotalCount(kReceivedInsecureDirectHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedSecureDirectHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoInsecureViaDRPHistogramName, 0); histogram_tester.ExpectUniqueSample(kReceivedInsecureViaDRPHistogramName, kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kOriginalHistogramName, kOriginalContentLength, 1); histogram_tester.ExpectUniqueSample( kDifferenceHistogramName, kOriginalContentLength - kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kFreshnessLifetimeHistogramName, freshness_lifetime.InSeconds(), 1); histogram_tester.ExpectUniqueSample(kCacheableHistogramName, kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kCacheable4HoursHistogramName, kResponseContentLength, 1); histogram_tester.ExpectUniqueSample(kCacheable24HoursHistogramName, kResponseContentLength, 1); // Check Lo-Fi histograms. const struct { bool lofi_enabled; int expected_count; } tests[] = { { // Lo-Fi disabled. false, 0, }, { // Lo-Fi enabled so should populate Lo-Fi content length histogram. true, 1, }, }; for (size_t i = 0; i < arraysize(tests); ++i) { base::test::ScopedFeatureList scoped_feature_list; if (tests[i].lofi_enabled) { scoped_feature_list.InitAndEnableFeature( features::kDataReductionProxyDecidesTransform); } else { scoped_feature_list.InitAndDisableFeature( features::kDataReductionProxyDecidesTransform); } // Needed as a parameter, but functionality is not tested. TestPreviewsDecider test_previews_decider; lofi_decider()->SetIsUsingLoFi(config()->ShouldAcceptServerPreview( *fake_request.get(), test_previews_decider)); fake_request = (FetchURLRequest(GURL(kTestURL), nullptr, response_headers, kResponseContentLength, 0)); fake_request->SetLoadFlags(fake_request->load_flags() | net::LOAD_MAIN_FRAME_DEPRECATED); // Histograms are accumulative, so get the sum of all the tests so far. int expected_count = 0; for (size_t j = 0; j <= i; ++j) expected_count += tests[j].expected_count; if (expected_count == 0) { histogram_tester.ExpectTotalCount(kReceivedValidOCLLoFiOnHistogramName, expected_count); histogram_tester.ExpectTotalCount(kOriginalValidOCLLoFiOnHistogramName, expected_count); histogram_tester.ExpectTotalCount(kDifferenceValidOCLLoFiOnHistogramName, expected_count); } else { histogram_tester.ExpectUniqueSample(kReceivedValidOCLLoFiOnHistogramName, kResponseContentLength, expected_count); histogram_tester.ExpectUniqueSample(kOriginalValidOCLLoFiOnHistogramName, kOriginalContentLength, expected_count); histogram_tester.ExpectUniqueSample( kDifferenceValidOCLLoFiOnHistogramName, kOriginalContentLength - kResponseContentLength, expected_count); } } } TEST_F(DataReductionProxyNetworkDelegateTest, NetVideoHistograms) { Init(USE_INSECURE_PROXY, false); base::HistogramTester histogram_tester; // Check video std::string video_response_headers = "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Content-Type: video/mp4\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: " + base::Int64ToString(kOriginalContentLength) + "\r\n\r\n"; FetchURLRequest(GURL(kTestURL), nullptr, video_response_headers, kResponseContentLength, 0); histogram_tester.ExpectUniqueSample(kReceivedInsecureViaDRPHistogramName, kResponseContentLength, 1); histogram_tester.ExpectTotalCount(kReceivedInsecureDirectHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedInsecureBypassedHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedInsecureOtherHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedSecureViaDRPHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedSecureDirectHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedSecureBypassedHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedSecureOtherHistogramName, 0); histogram_tester.ExpectUniqueSample(kReceivedVideoInsecureViaDRPHistogramName, kResponseContentLength, 1); histogram_tester.ExpectTotalCount(kReceivedVideoInsecureDirectHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoInsecureBypassedHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoInsecureOtherHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoSecureViaDRPHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoSecureDirectHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoSecureBypassedHistogramName, 0); histogram_tester.ExpectTotalCount(kReceivedVideoSecureOtherHistogramName, 0); } struct ExpectedHistogram { const std::string name; int64_t value; }; bool operator<(const ExpectedHistogram& hist1, const ExpectedHistogram& hist2) { return hist1.name < hist2.name; } TEST_F(DataReductionProxyNetworkDelegateTest, DetailedNetHistograms) { // List of all the histograms we're concerned with. // Each test case can define interesting histograms from this list. // Any histogram not called out in an invidual test will have an expected // count of 0 samples. const std::set<std::string> all_new_net_histograms{ // HTTP received content length kReceivedInsecureDirectHistogramName, kReceivedInsecureViaDRPHistogramName, kReceivedInsecureBypassedHistogramName, kReceivedInsecureOtherHistogramName, // HTTP video received content length kReceivedVideoInsecureDirectHistogramName, kReceivedVideoInsecureViaDRPHistogramName, kReceivedVideoInsecureBypassedHistogramName, kReceivedVideoInsecureOtherHistogramName, // HTTPS received content length kReceivedSecureDirectHistogramName, kReceivedSecureViaDRPHistogramName, kReceivedSecureBypassedHistogramName, kReceivedSecureOtherHistogramName, // HTTPS video received content length kReceivedVideoSecureDirectHistogramName, kReceivedVideoSecureViaDRPHistogramName, kReceivedVideoSecureBypassedHistogramName, kReceivedVideoSecureOtherHistogramName, // HTTP Original content length kOriginalInsecureDirectHistogramName, kOriginalInsecureViaDRPHistogramName, kOriginalInsecureBypassedHistogramName, kOriginalInsecureOtherHistogramName, // HTTP video Original content length kOriginalVideoInsecureDirectHistogramName, kOriginalVideoInsecureViaDRPHistogramName, kOriginalVideoInsecureBypassedHistogramName, kOriginalVideoInsecureOtherHistogramName, // HTTPS Original content length kOriginalSecureDirectHistogramName, kOriginalSecureViaDRPHistogramName, kOriginalSecureBypassedHistogramName, kOriginalSecureOtherHistogramName, // HTTPS video Original content length kOriginalVideoSecureDirectHistogramName, kOriginalVideoSecureViaDRPHistogramName, kOriginalVideoSecureBypassedHistogramName, kOriginalVideoSecureOtherHistogramName, }; const struct { const std::string name; bool is_video; bool is_https; ProxyTestConfig proxy_config; int64_t original_content_length; int64_t content_length; // Any histogram listed in all_new_net_histograms but not here should have // no samples. const std::set<ExpectedHistogram> expected_histograms; } tests[] = { {"HTTP nonvideo request via DRP", false, false, USE_INSECURE_PROXY, kOriginalContentLength, kResponseContentLength, { {kReceivedInsecureViaDRPHistogramName, kResponseContentLength}, {kOriginalInsecureViaDRPHistogramName, kOriginalContentLength}, }}, {"HTTP video request via DRP", true, false, USE_INSECURE_PROXY, kOriginalContentLength, kResponseContentLength, { {kReceivedInsecureViaDRPHistogramName, kResponseContentLength}, {kOriginalInsecureViaDRPHistogramName, kOriginalContentLength}, {kReceivedVideoInsecureViaDRPHistogramName, kResponseContentLength}, {kOriginalVideoInsecureViaDRPHistogramName, kOriginalContentLength}, }}, {"DRP not configured for http", false, false, BYPASS_PROXY, kOriginalContentLength, kResponseContentLength, { {kReceivedInsecureDirectHistogramName, kResponseContentLength}, {kOriginalInsecureDirectHistogramName, kResponseContentLength}, }}, {"DRP not configured for http video", true, false, BYPASS_PROXY, kOriginalContentLength, kResponseContentLength, { {kReceivedInsecureDirectHistogramName, kResponseContentLength}, {kOriginalInsecureDirectHistogramName, kResponseContentLength}, {kReceivedVideoInsecureDirectHistogramName, kResponseContentLength}, {kOriginalVideoInsecureDirectHistogramName, kResponseContentLength}, }}, {"nonvideo over https", false, true, BYPASS_PROXY, kOriginalContentLength, kResponseContentLength, { {kReceivedSecureDirectHistogramName, kResponseContentLength}, {kOriginalSecureDirectHistogramName, kResponseContentLength}, }}, {"video over https", true, true, BYPASS_PROXY, kOriginalContentLength, kResponseContentLength, { {kReceivedSecureDirectHistogramName, kResponseContentLength}, {kOriginalSecureDirectHistogramName, kResponseContentLength}, {kReceivedVideoSecureDirectHistogramName, kResponseContentLength}, {kOriginalVideoSecureDirectHistogramName, kResponseContentLength}, }}, }; for (const auto& test : tests) { LOG(INFO) << "NetHistograms: " << test.name; Init(test.proxy_config, false); base::HistogramTester histogram_tester; GURL test_url = GURL(kTestURL); if (test.is_https) { test_url = GURL(kSecureTestURL); mock_socket_factory()->AddSSLSocketDataProvider( ssl_socket_data_provider()); } std::string via_header = ""; std::string ocl_header = ""; if (test.proxy_config == USE_INSECURE_PROXY) { via_header = "Via: 1.1 Chrome-Compression-Proxy\r\n"; ocl_header = "x-original-content-length: " + base::Int64ToString(kOriginalContentLength) + "\r\n"; } if (test.is_video) { // Check video std::string video_response_headers = "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Content-Type: video/mp4\r\n" + via_header + ocl_header + "\r\n"; FetchURLRequest(test_url, nullptr, video_response_headers, kResponseContentLength, 0); } else { // Check https std::string response_headers = "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" + via_header + ocl_header + "\r\n\r\n"; FetchURLRequest(test_url, nullptr, response_headers, kResponseContentLength, 0); } for (const auto& histogram : all_new_net_histograms) { auto expected_it = test.expected_histograms.find({histogram, 0}); if (expected_it == test.expected_histograms.end()) { histogram_tester.ExpectTotalCount(histogram, 0); } else { histogram_tester.ExpectUniqueSample(expected_it->name, expected_it->value, 1); } } } } TEST_F(DataReductionProxyNetworkDelegateTest, NonServerLoFiResponseDoesNotTriggerInfobar) { Init(USE_INSECURE_PROXY, false); ClearLoFiUIService(); lofi_decider()->SetIsUsingClientLoFi(false); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n\r\n"; auto request = FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0); EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lofi_received()); VerifyDidNotifyLoFiResponse(false); } TEST_F(DataReductionProxyNetworkDelegateTest, ServerLoFiResponseDoesTriggerInfobar) { Init(USE_INSECURE_PROXY, false); ClearLoFiUIService(); lofi_decider()->SetIsUsingClientLoFi(false); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Chrome-Proxy-Content-Transform: empty-image\r\n\r\n"; auto request = FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0); EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lofi_received()); VerifyDidNotifyLoFiResponse(true); } TEST_F(DataReductionProxyNetworkDelegateTest, NonClientLoFiResponseDoesNotTriggerInfobar) { Init(USE_INSECURE_PROXY, false); ClearLoFiUIService(); lofi_decider()->SetIsUsingClientLoFi(false); FetchURLRequest(GURL(kTestURL), nullptr, "HTTP/1.1 206 Partial Content\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Content-Range: bytes 0-139/2048\r\n\r\n", 140, 0); VerifyDidNotifyLoFiResponse(false); } TEST_F(DataReductionProxyNetworkDelegateTest, ClientLoFiCompleteResponseDoesNotTriggerInfobar) { Init(USE_INSECURE_PROXY, false); const char* const test_response_headers[] = { "HTTP/1.1 200 OK\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n\r\n", "HTTP/1.1 204 No Content\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n\r\n", "HTTP/1.1 404 Not Found\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n\r\n", "HTTP/1.1 206 Partial Content\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Content-Range: bytes 0-139/140\r\n\r\n", }; for (const char* headers : test_response_headers) { ClearLoFiUIService(); lofi_decider()->SetIsUsingClientLoFi(true); FetchURLRequest(GURL(kTestURL), nullptr, headers, 140, 0); VerifyDidNotifyLoFiResponse(false); } } TEST_F(DataReductionProxyNetworkDelegateTest, ClientLoFiPartialRangeDoesTriggerInfobar) { Init(USE_INSECURE_PROXY, false); const char* const test_response_headers[] = { "HTTP/1.1 206 Partial Content\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Content-Range: bytes 0-139/2048\r\n\r\n", "HTTP/1.1 206 Partial Content\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Content-Range: bytes 5-144/145\r\n\r\n", }; for (const char* headers : test_response_headers) { ClearLoFiUIService(); lofi_decider()->SetIsUsingClientLoFi(true); FetchURLRequest(GURL(kTestURL), nullptr, headers, 140, 0); VerifyDidNotifyLoFiResponse(true); } } TEST_F(DataReductionProxyNetworkDelegateTest, TestLoFiTransformationTypeHistogram) { const std::string regular_response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=0\r\n" "Vary: accept-encoding\r\n\r\n"; Init(USE_INSECURE_PROXY, false); const char kLoFiTransformationTypeHistogram[] = "DataReductionProxy.LoFi.TransformationType"; base::HistogramTester histogram_tester; net::HttpRequestHeaders request_headers; request_headers.SetHeader("chrome-proxy-accept-transform", "lite-page"); lofi_decider()->ignore_is_using_data_reduction_proxy_check(); FetchURLRequest(GURL(kTestURL), &request_headers, regular_response_headers, 140, 0); histogram_tester.ExpectBucketCount(kLoFiTransformationTypeHistogram, NO_TRANSFORMATION_LITE_PAGE_REQUESTED, 1); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Chrome-Proxy-Content-Transform: lite-page\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n"; response_headers += "\r\n"; auto request = FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0); EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lite_page_received()); histogram_tester.ExpectBucketCount(kLoFiTransformationTypeHistogram, LITE_PAGE, 1); } // Test that Brotli is not added to the accept-encoding header when it is // disabled globally. TEST_F(DataReductionProxyNetworkDelegateTest, BrotliAdvertisement_BrotliDisabled) { Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); ReadBrotliFile(); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=1200\r\n" "Vary: accept-encoding\r\n"; response_headers += "\r\n"; // Use secure sockets when fetching the request since Brotli is only enabled // for secure connections. FetchURLRequestAndVerifyBrotli(nullptr, response_headers, false, false); } // Test that Brotli is not added to the accept-encoding header when the request // is fetched from an insecure proxy. TEST_F(DataReductionProxyNetworkDelegateTest, BrotliAdvertisementInsecureProxy) { Init(USE_INSECURE_PROXY, true /* enable_brotli_globally */); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=1200\r\n" "Vary: accept-encoding\r\n"; response_headers += "\r\n"; // Use secure sockets when fetching the request since Brotli is only enabled // for secure connections. std::unique_ptr<net::URLRequest> request( FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0)); EXPECT_EQ(140, request->received_response_content_length()); EXPECT_NE(0, request->GetTotalSentBytes()); EXPECT_NE(0, request->GetTotalReceivedBytes()); EXPECT_FALSE(request->was_cached()); // Brotli should be added to Accept Encoding header only if secure proxy is in VerifyBrotliPresent(request.get(), false); } // Test that Brotli is not added to the accept-encoding header when it is // disabled via data reduction proxy field trial. TEST_F(DataReductionProxyNetworkDelegateTest, BrotliAdvertisementDisabledViaFieldTrial) { Init(USE_SECURE_PROXY, true /* enable_brotli_globally */); base::FieldTrialList field_trial_list(nullptr); ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial( "DataReductionProxyBrotliAcceptEncoding", "Disabled")); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=1200\r\n" "Vary: accept-encoding\r\n"; response_headers += "\r\n"; FetchURLRequestAndVerifyBrotli(nullptr, response_headers, false, false); FetchURLRequestAndVerifyBrotli(nullptr, response_headers, true, false); } // Test that Brotli is correctly added to the accept-encoding header when it is // enabled globally. TEST_F(DataReductionProxyNetworkDelegateTest, BrotliAdvertisement) { Init(USE_SECURE_PROXY, true /* enable_brotli_globally */); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=1200\r\n" "Content-Encoding: br\r\n" "Vary: accept-encoding\r\n"; response_headers += "\r\n"; FetchURLRequestAndVerifyBrotli(nullptr, response_headers, false, true); FetchURLRequestAndVerifyBrotli(nullptr, response_headers, true, true); } TEST_F(DataReductionProxyNetworkDelegateTest, IncrementingMainFramePageId) { // This is unaffacted by brotil and insecure proxy. Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); io_data()->request_options()->SetSecureSession("new-session"); uint64_t page_id = io_data()->request_options()->GeneratePageId(); FetchURLRequestAndVerifyPageIdDirective(++page_id, false); FetchURLRequestAndVerifyPageIdDirective(++page_id, false); FetchURLRequestAndVerifyPageIdDirective(++page_id, false); } TEST_F(DataReductionProxyNetworkDelegateTest, ResetSessionResetsId) { // This is unaffacted by brotil and insecure proxy. Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); io_data()->request_options()->SetSecureSession("new-session"); uint64_t page_id = io_data()->request_options()->GeneratePageId(); FetchURLRequestAndVerifyPageIdDirective(++page_id, false); io_data()->request_options()->SetSecureSession("new-session-2"); page_id = io_data()->request_options()->GeneratePageId(); FetchURLRequestAndVerifyPageIdDirective(++page_id, false); } TEST_F(DataReductionProxyNetworkDelegateTest, SubResourceNoPageId) { // This is unaffacted by brotil and insecure proxy. Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); io_data()->request_options()->SetSecureSession("new-session"); FetchURLRequestAndVerifyPageIdDirective(base::Optional<uint64_t>(), false); } TEST_F(DataReductionProxyNetworkDelegateTest, RedirectSharePid) { // This is unaffacted by brotil and insecure proxy. Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); io_data()->request_options()->SetSecureSession("new-session"); uint64_t page_id = io_data()->request_options()->GeneratePageId(); FetchURLRequestAndVerifyPageIdDirective(++page_id, true); } TEST_F(DataReductionProxyNetworkDelegateTest, SessionChangeResetsPageIDOnRedirect) { // This test calls directly into network delegate as it is difficult to mock // state changing in between redirects within an URLRequest's lifetime. // This is unaffacted by brotil and insecure proxy. Init(USE_INSECURE_PROXY, false /* enable_brotli_globally */); net::ProxyInfo data_reduction_proxy_info; data_reduction_proxy_info.UseProxyServer( params()->proxies_for_http().front().proxy_server()); std::unique_ptr<net::URLRequest> request = context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); io_data()->request_options()->SetSecureSession("fake-session"); uint64_t page_id = io_data()->request_options()->GeneratePageId(); net::HttpRequestHeaders headers; net::ProxyRetryInfoMap proxy_retry_info; // Send a request and verify the page ID is 1. network_delegate()->NotifyBeforeStartTransaction( request.get(), base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), &headers); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); DataReductionProxyData* data = DataReductionProxyData::GetData(*request.get()); EXPECT_TRUE(data_reduction_proxy_info.is_http()); EXPECT_EQ(++page_id, data->page_id().value()); // Send a second request and verify the page ID incremements. request = context()->CreateRequest(GURL(kTestURL), net::RequestPriority::IDLE, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS); request->SetLoadFlags(net::LOAD_MAIN_FRAME_DEPRECATED); network_delegate()->NotifyBeforeStartTransaction( request.get(), base::Bind(&DataReductionProxyNetworkDelegateTest::DelegateStageDone, base::Unretained(this)), &headers); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); data = DataReductionProxyData::GetData(*request.get()); EXPECT_EQ(++page_id, data->page_id().value()); // Verify that redirects are the same page ID. network_delegate()->NotifyBeforeRedirect(request.get(), GURL(kTestURL)); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); data = DataReductionProxyData::GetData(*request.get()); EXPECT_EQ(page_id, data->page_id().value()); network_delegate()->NotifyBeforeRedirect(request.get(), GURL(kTestURL)); io_data()->request_options()->SetSecureSession("new-session"); page_id = io_data()->request_options()->GeneratePageId(); network_delegate()->NotifyBeforeSendHeaders( request.get(), data_reduction_proxy_info, proxy_retry_info, &headers); data = DataReductionProxyData::GetData(*request.get()); EXPECT_EQ(++page_id, data->page_id().value()); } // Test that effective connection type is correctly added to the request // headers when it is enabled using field trial. The server is varying on the // effective connection type (ECT). TEST_F(DataReductionProxyNetworkDelegateTest, ECTHeaderEnabledWithVary) { Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Cache-Control: max-age=1200\r\n" "Vary: chrome-proxy-ect\r\n" "x-original-content-length: 200\r\n\r\n"; int response_body_size = 140; std::string response_body(base::checked_cast<size_t>(response_body_size), ' '); std::vector<net::MockRead> reads_list; std::vector<std::string> mock_writes; std::vector<net::MockWrite> writes_list; std::vector<net::EffectiveConnectionType> effective_connection_types; effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G); effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_2G); BuildSocket(response_headers, response_body, true, effective_connection_types, &reads_list, &mock_writes, &writes_list); // Add 2 socket providers since 2 requests in this test are fetched from the // network. FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, false); // When the ECT is set to the same value, fetching the same resource should // result in a cache hit. FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, true); // When the ECT is set to a different value, the response should not be // served from the cache. FetchURLRequestAndVerifyECTHeader(effective_connection_types[1], true, false); } // Test that effective connection type is correctly added to the request // headers when it is enabled using field trial. The server is not varying on // the effective connection type (ECT). TEST_F(DataReductionProxyNetworkDelegateTest, ECTHeaderEnabledWithoutVary) { Init(USE_SECURE_PROXY, false /* enable_brotli_globally */); std::string response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "Cache-Control: max-age=1200\r\n" "x-original-content-length: 200\r\n\r\n"; int response_body_size = 140; std::string response_body(base::checked_cast<size_t>(response_body_size), ' '); std::vector<net::MockRead> reads_list; std::vector<std::string> mock_writes; std::vector<net::MockWrite> writes_list; std::vector<net::EffectiveConnectionType> effective_connection_types; effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_SLOW_2G); effective_connection_types.push_back(net::EFFECTIVE_CONNECTION_TYPE_2G); BuildSocket(response_headers, response_body, true, effective_connection_types, &reads_list, &mock_writes, &writes_list); // Add 1 socket provider since 1 request in this test is fetched from the // network. FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, false); // When the ECT is set to the same value, fetching the same resource should // result in a cache hit. FetchURLRequestAndVerifyECTHeader(effective_connection_types[0], true, true); // When the ECT is set to a different value, the response should still be // served from the cache. FetchURLRequestAndVerifyECTHeader(effective_connection_types[1], true, true); } class DataReductionProxyNetworkDelegateClientLoFiTest : public testing::Test { public: DataReductionProxyNetworkDelegateClientLoFiTest() : baseline_savings_(0) {} ~DataReductionProxyNetworkDelegateClientLoFiTest() override; void Reset() { drp_test_context_.reset(); mock_socket_factory_.reset(); context_storage_.reset(); context_.reset(new net::TestURLRequestContext(true)); context_storage_.reset(new net::URLRequestContextStorage(context_.get())); mock_socket_factory_.reset(new net::MockClientSocketFactory()); context_->set_client_socket_factory(mock_socket_factory_.get()); drp_test_context_ = DataReductionProxyTestContext::Builder() .WithURLRequestContext(context_.get()) .WithMockClientSocketFactory(mock_socket_factory_.get()) .Build(); drp_test_context_->AttachToURLRequestContext(context_storage_.get()); context_->Init(); base::RunLoop().RunUntilIdle(); baseline_savings_ = drp_test_context()->settings()->GetTotalHttpContentLengthSaved(); } void SetUpLoFiDecider(bool is_client_lofi_image, bool is_client_lofi_auto_reload) const { std::unique_ptr<TestLoFiDecider> lofi_decider(new TestLoFiDecider()); lofi_decider->SetIsUsingClientLoFi(is_client_lofi_image); lofi_decider->SetIsClientLoFiAutoReload(is_client_lofi_auto_reload); drp_test_context_->io_data()->set_lofi_decider( std::unique_ptr<LoFiDecider>(std::move(lofi_decider))); } int64_t GetSavings() const { return drp_test_context()->settings()->GetTotalHttpContentLengthSaved() - baseline_savings_; } net::TestURLRequestContext* context() const { return context_.get(); } net::MockClientSocketFactory* mock_socket_factory() const { return mock_socket_factory_.get(); } DataReductionProxyTestContext* drp_test_context() const { return drp_test_context_.get(); } private: base::MessageLoopForIO loop; std::unique_ptr<net::TestURLRequestContext> context_; std::unique_ptr<net::URLRequestContextStorage> context_storage_; std::unique_ptr<net::MockClientSocketFactory> mock_socket_factory_; std::unique_ptr<DataReductionProxyTestContext> drp_test_context_; int64_t baseline_savings_; }; DataReductionProxyNetworkDelegateClientLoFiTest:: ~DataReductionProxyNetworkDelegateClientLoFiTest() {} TEST_F(DataReductionProxyNetworkDelegateClientLoFiTest, DataSavingsNonDRP) { const char kSimple200ResponseHeaders[] = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n\r\n"; const struct { const char* headers; size_t response_length; bool is_client_lofi_image; bool is_client_lofi_auto_reload; int64_t expected_savings; } tests[] = { // 200 responses shouldn't see any savings. {kSimple200ResponseHeaders, 140, false, false, 0}, {kSimple200ResponseHeaders, 140, true, false, 0}, // Client Lo-Fi Auto-reload responses should see negative savings. {kSimple200ResponseHeaders, 140, false, true, -(static_cast<int64_t>(sizeof(kSimple200ResponseHeaders) - 1) + 140)}, {kSimple200ResponseHeaders, 140, true, true, -(static_cast<int64_t>(sizeof(kSimple200ResponseHeaders) - 1) + 140)}, // A range response that doesn't use Client Lo-Fi shouldn't see any // savings. {"HTTP/1.1 206 Partial Content\r\n" "Content-Range: bytes 0-2047/10000\r\n" "Content-Length: 2048\r\n\r\n", 2048, false, false, 0}, // A Client Lo-Fi range response should see savings based on the // Content-Range header. {"HTTP/1.1 206 Partial Content\r\n" "Content-Range: bytes 0-2047/10000\r\n" "Content-Length: 2048\r\n\r\n", 2048, true, false, 10000 - 2048}, // A Client Lo-Fi range response should see savings based on the // Content-Range header, which in this case is 0 savings because the range // response contained the entire resource. {"HTTP/1.1 206 Partial Content\r\n" "Content-Range: bytes 0-999/1000\r\n" "Content-Length: 1000\r\n\r\n", 1000, true, false, 0}, // Client Lo-Fi range responses that don't have a Content-Range with the // full resource length shouldn't see any savings. {"HTTP/1.1 206 Partial Content\r\n" "Content-Length: 2048\r\n\r\n", 2048, true, false, 0}, {"HTTP/1.1 206 Partial Content\r\n" "Content-Range: bytes 0-2047/*\r\n" "Content-Length: 2048\r\n\r\n", 2048, true, false, 0}, {"HTTP/1.1 206 Partial Content\r\n" "Content-Range: invalid_content_range\r\n" "Content-Length: 2048\r\n\r\n", 2048, true, false, 0}, }; for (const auto& test : tests) { Reset(); SetUpLoFiDecider(test.is_client_lofi_image, test.is_client_lofi_auto_reload); std::string response_body(test.response_length, 'a'); net::MockRead reads[] = {net::MockRead(test.headers), net::MockRead(response_body.c_str()), net::MockRead(net::ASYNC, net::OK)}; net::StaticSocketDataProvider socket(reads, arraysize(reads), nullptr, 0); mock_socket_factory()->AddSocketDataProvider(&socket); net::TestDelegate test_delegate; std::unique_ptr<net::URLRequest> request = context()->CreateRequest( GURL("http://example.com"), net::RequestPriority::IDLE, &test_delegate, TRAFFIC_ANNOTATION_FOR_TESTS); request->Start(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(test.expected_savings, GetSavings()) << (&test - tests); } } TEST_F(DataReductionProxyNetworkDelegateClientLoFiTest, DataSavingsThroughDRP) { Reset(); drp_test_context()->DisableWarmupURLFetch(); drp_test_context()->EnableDataReductionProxyWithSecureProxyCheckSuccess(); SetUpLoFiDecider(true, false); const char kHeaders[] = "HTTP/1.1 206 Partial Content\r\n" "Content-Range: bytes 0-2047/10000\r\n" "Content-Length: 2048\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "X-Original-Content-Length: 3000\r\n\r\n"; std::string response_body(2048, 'a'); net::MockRead reads[] = {net::MockRead(kHeaders), net::MockRead(response_body.c_str()), net::MockRead(net::ASYNC, net::OK)}; net::StaticSocketDataProvider socket(reads, arraysize(reads), nullptr, 0); mock_socket_factory()->AddSocketDataProvider(&socket); net::TestDelegate test_delegate; std::unique_ptr<net::URLRequest> request = context()->CreateRequest( GURL("http://example.com"), net::RequestPriority::IDLE, &test_delegate, TRAFFIC_ANNOTATION_FOR_TESTS); request->Start(); base::RunLoop().RunUntilIdle(); // Since the Data Reduction Proxy is enabled, the length of the raw headers // should be used in the estimated original size. The X-OCL should be ignored. EXPECT_EQ(static_cast<int64_t>(net::HttpUtil::AssembleRawHeaders( kHeaders, sizeof(kHeaders) - 1) .size() + 10000 - request->GetTotalReceivedBytes()), GetSavings()); } TEST_F(DataReductionProxyNetworkDelegateTest, TestAcceptTransformHistogram) { Init(USE_INSECURE_PROXY, false); base::HistogramTester histogram_tester; const std::string regular_response_headers = "HTTP/1.1 200 OK\r\n" "Content-Length: 140\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "Cache-Control: max-age=0\r\n" "Vary: accept-encoding\r\n\r\n"; const char kResponseHeadersWithCPCTFormat[] = "HTTP/1.1 200 OK\r\n" "Chrome-Proxy-Content-Transform: %s\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "\r\n"; // Verify lite page request. net::HttpRequestHeaders request_headers; request_headers.SetHeader("chrome-proxy-accept-transform", "lite-page"); FetchURLRequest(GURL(kTestURL), &request_headers, regular_response_headers, 140, 0); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 1); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 0 /* LITE_PAGE_REQUESTED */, 1); // Check legacy histogram too: histogram_tester.ExpectBucketCount( "DataReductionProxy.LoFi.TransformationType", NO_TRANSFORMATION_LITE_PAGE_REQUESTED, 1); // Verify empty image request. request_headers.SetHeader("chrome-proxy-accept-transform", "empty-image"); FetchURLRequest(GURL(kTestURL), &request_headers, regular_response_headers, 140, 0); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 2); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 3 /* EMPTY_IMAGE_REQUESTED */, 1); // Verify lite page response. auto request = FetchURLRequest( GURL(kTestURL), nullptr, base::StringPrintf(kResponseHeadersWithCPCTFormat, "lite-page"), 140, 0); EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lite_page_received()); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 3); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 1 /* LITE_PAGE_TRANSFORM_RECEIVED */, 1); // Check legacy histogram too: histogram_tester.ExpectBucketCount( "DataReductionProxy.LoFi.TransformationType", LITE_PAGE, 1); // Verify page policy response. std::string response_headers = "HTTP/1.1 200 OK\r\n" "Chrome-Proxy: page-policies=empty-image\r\n" "Date: Wed, 28 Nov 2007 09:40:09 GMT\r\n" "Expires: Mon, 24 Nov 2014 12:45:26 GMT\r\n" "Via: 1.1 Chrome-Compression-Proxy\r\n" "x-original-content-length: 200\r\n" "\r\n"; request = FetchURLRequest(GURL(kTestURL), nullptr, response_headers, 140, 0); EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lite_page_received()); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 4); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 2 /* EMPTY_IMAGE_POLICY_DIRECTIVE_RECEIVED */, 1); // Verify empty image response. request = FetchURLRequest( GURL(kTestURL), nullptr, base::StringPrintf(kResponseHeadersWithCPCTFormat, "empty-image"), 140, 0); EXPECT_TRUE(DataReductionProxyData::GetData(*request)->lofi_received()); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 5); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 4 /* EMPTY_IMAGE_TRANSFORM_RECEIVED */, 1); // Verify compressed-video request. request_headers.SetHeader("chrome-proxy-accept-transform", "compressed-video"); FetchURLRequest(GURL(kTestURL), &request_headers, std::string(), 140, 0); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 6); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 5 /* COMPRESSED_VIDEO_REQUESTED */, 1); // Verify compressed-video response. request = FetchURLRequest( GURL(kTestURL), nullptr, base::StringPrintf(kResponseHeadersWithCPCTFormat, "compressed-video"), 140, 0); EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lofi_received()); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 7); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 8 /* COMPRESSED_VIDEO_RECEIVED */, 1); // Verify response with an unknown CPAT value. request = FetchURLRequest(GURL(kTestURL), nullptr, base::StringPrintf(kResponseHeadersWithCPCTFormat, "this-is-a-fake-transform"), 140, 0); EXPECT_FALSE(DataReductionProxyData::GetData(*request)->lofi_received()); histogram_tester.ExpectTotalCount( "DataReductionProxy.Protocol.AcceptTransform", 8); histogram_tester.ExpectBucketCount( "DataReductionProxy.Protocol.AcceptTransform", 9 /* UNKNOWN_TRANSFORM_RECEIVED */, 1); } } // namespace } // namespace data_reduction_proxy
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
23dced3024fe2c5634abc346c57f1482d74f014d
f746c798d1bef7d665c07b1923bf35d03ad408d4
/lib/poppler/qt4/src/poppler-qt4.h
1b5afb2ef63dbe08b6f6703b8ef792803bb51c1b
[ "GPL-1.0-or-later", "GPL-2.0-only", "GPL-3.0-only", "LGPL-2.0-or-later", "MIT" ]
permissive
istex/popplonode
cd51a2c582759869bc025558f3f06d864506e8c3
1637685667757df6e54077fa93b60d5d1f7fbc8a
refs/heads/master
2023-01-08T00:12:20.923850
2019-11-04T10:41:10
2019-11-04T10:41:10
101,175,171
4
1
MIT
2022-12-30T17:48:06
2017-08-23T12:00:08
C++
UTF-8
C++
false
false
53,311
h
/* poppler-qt.h: qt interface to poppler * Copyright (C) 2005, Net Integration Technologies, Inc. * Copyright (C) 2005, 2007, Brad Hards <bradh@frogmouth.net> * Copyright (C) 2005-2012, 2014, 2015, Albert Astals Cid <aacid@kde.org> * Copyright (C) 2005, Stefan Kebekus <stefan.kebekus@math.uni-koeln.de> * Copyright (C) 2006-2011, Pino Toscano <pino@kde.org> * Copyright (C) 2009 Shawn Rutledge <shawn.t.rutledge@gmail.com> * Copyright (C) 2010 Suzuki Toshiya <mpsuzuki@hiroshima-u.ac.jp> * Copyright (C) 2010 Matthias Fauconneau <matthias.fauconneau@gmail.com> * Copyright (C) 2011 Andreas Hartmetz <ahartmetz@gmail.com> * Copyright (C) 2011 Glad Deschrijver <glad.deschrijver@gmail.com> * Copyright (C) 2012, Guillermo A. Amaral B. <gamaral@kde.org> * Copyright (C) 2012, Fabio D'Urso <fabiodurso@hotmail.it> * Copyright (C) 2012, Tobias Koenig <tobias.koenig@kdab.com> * Copyright (C) 2012, 2014, 2015 Adam Reichold <adamreichold@myopera.com> * Copyright (C) 2012, 2013 Thomas Freitag <Thomas.Freitag@alfa.de> * Copyright (C) 2016 Jakub Alba <jakubalba@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __POPPLER_QT_H__ #define __POPPLER_QT_H__ #include "poppler-annotation.h" #include "poppler-link.h" #include "poppler-optcontent.h" #include "poppler-page-transition.h" #include <QtCore/QByteArray> #include <QtCore/QDateTime> #include <QtCore/QSet> #include <QtXml/QDomDocument> #include "poppler-export.h" class EmbFile; class Sound; class AnnotMovie; /** The %Poppler Qt4 binding. */ namespace Poppler { class Document; class DocumentData; class PageData; class FormField; class TextBoxData; class PDFConverter; class PSConverter; /** Debug/error function. This function type is used for debugging & error output; the first parameter is the actual message, the second is the unaltered closure argument which was passed to the setDebugErrorFunction call. \since 0.16 */ typedef void (*PopplerDebugFunc)(const QString & /*message*/, const QVariant & /*closure*/); /** Set a new debug/error output function. If not set, by default error and debug messages will be sent to the Qt \p qDebug() function. \param debugFunction the new debug function \param closure user data which will be passes as-is to the debug function \since 0.16 */ POPPLER_QT4_EXPORT void setDebugErrorFunction(PopplerDebugFunc debugFunction, const QVariant &closure); /** Describes the physical location of text on a document page This very simple class describes the physical location of text on the page. It consists of - a QString that contains the text - a QRectF that gives a box that describes where on the page the text is found. */ class POPPLER_QT4_EXPORT TextBox { friend class Page; public: /** The default constructor sets the \p text and the rectangle that contains the text. Coordinates for the \p bBox are in points = 1/72 of an inch. */ TextBox(const QString& text, const QRectF &bBox); /** Destructor. */ ~TextBox(); /** Returns the text of this text box */ QString text() const; /** Returns the position of the text, in point, i.e., 1/72 of an inch \since 0.8 */ QRectF boundingBox() const; /** Returns the pointer to the next text box, if there is one. Otherwise, it returns a null pointer. */ TextBox *nextWord() const; /** Returns the bounding box of the \p i -th characted of the word. */ QRectF charBoundingBox(int i) const; /** Returns whether there is a space character after this text box */ bool hasSpaceAfter() const; private: Q_DISABLE_COPY(TextBox) TextBoxData *m_data; }; class FontInfoData; /** Container class for information about a font within a PDF document */ class POPPLER_QT4_EXPORT FontInfo { friend class Document; public: /** The type of font. */ enum Type { unknown, Type1, Type1C, Type1COT, Type3, TrueType, TrueTypeOT, CIDType0, CIDType0C, CIDType0COT, CIDTrueType, CIDTrueTypeOT }; /// \cond PRIVATE /** Create a new font information container. */ FontInfo(); /** Create a new font information container. */ FontInfo( const FontInfoData &fid ); /// \endcond /** Copy constructor. */ FontInfo( const FontInfo &fi ); /** Destructor. */ ~FontInfo(); /** The name of the font. Can be QString::null if the font has no name */ QString name() const; /** The path of the font file used to represent this font on this system, or a null string is the font is embedded */ QString file() const; /** Whether the font is embedded in the file, or not \return true if the font is embedded */ bool isEmbedded() const; /** Whether the font provided is only a subset of the full font or not. This only has meaning if the font is embedded. \return true if the font is only a subset */ bool isSubset() const; /** The type of font encoding \return a enumerated value corresponding to the font encoding used \sa typeName for a string equivalent */ Type type() const; /** The name of the font encoding used \note if you are looking for the name of the font (as opposed to the encoding format used), you probably want name(). \sa type for a enumeration version */ QString typeName() const; /** Standard assignment operator */ FontInfo& operator=( const FontInfo &fi ); private: FontInfoData *m_data; }; class FontIteratorData; /** Iterator for reading the fonts in a document. FontIterator provides a Java-style iterator for reading the fonts in a document. You can use it in the following way: \code Poppler::FontIterator* it = doc->newFontIterator(); while (it->hasNext()) { QList<Poppler::FontInfo> fonts = it->next(); // do something with the fonts } // after doing the job, the iterator must be freed delete it; \endcode \since 0.12 */ class POPPLER_QT4_EXPORT FontIterator { friend class Document; friend class DocumentData; public: /** Destructor. */ ~FontIterator(); /** Returns the fonts of the current page and then advances the iterator to the next page. */ QList<FontInfo> next(); /** Checks whether there is at least one more page to iterate, ie returns false when the iterator is beyond the last page. */ bool hasNext() const; /** Returns the current page where the iterator is. */ int currentPage() const; private: Q_DISABLE_COPY( FontIterator ) FontIterator( int, DocumentData *dd ); FontIteratorData *d; }; class EmbeddedFileData; /** Container class for an embedded file with a PDF document */ class POPPLER_QT4_EXPORT EmbeddedFile { friend class DocumentData; friend class AnnotationPrivate; public: /// \cond PRIVATE EmbeddedFile(EmbFile *embfile); /// \endcond /** Destructor. */ ~EmbeddedFile(); /** The name associated with the file */ QString name() const; /** The description associated with the file, if any. This will return an empty QString if there is no description element */ QString description() const; /** The size of the file. This will return < 0 if there is no size element */ int size() const; /** The modification date for the embedded file, if known. */ QDateTime modDate() const; /** The creation date for the embedded file, if known. */ QDateTime createDate() const; /** The MD5 checksum of the file. This will return an empty QByteArray if there is no checksum element. */ QByteArray checksum() const; /** The MIME type of the file, if known. \since 0.8 */ QString mimeType() const; /** The data as a byte array */ QByteArray data(); /** Is the embedded file valid? \since 0.12 */ bool isValid() const; /** A QDataStream for the actual data? */ //QDataStream dataStream() const; private: Q_DISABLE_COPY(EmbeddedFile) EmbeddedFile(EmbeddedFileData &dd); EmbeddedFileData *m_embeddedFile; }; /** \brief A page in a document. The Page class represents a single page within a PDF document. You cannot construct a Page directly, but you have to use the Document functions that return a new Page out of an index or a label. */ class POPPLER_QT4_EXPORT Page { friend class Document; public: /** Destructor. */ ~Page(); /** The type of rotation to apply for an operation */ enum Rotation { Rotate0 = 0, ///< Do not rotate Rotate90 = 1, ///< Rotate 90 degrees clockwise Rotate180 = 2, ///< Rotate 180 degrees Rotate270 = 3 ///< Rotate 270 degrees clockwise (90 degrees counterclockwise) }; /** The kinds of page actions */ enum PageAction { Opening, ///< The action when a page is "opened" Closing ///< The action when a page is "closed" }; /** How the text is going to be returned \since 0.16 */ enum TextLayout { PhysicalLayout, ///< The text is layouted to resemble the real page layout RawOrderLayout ///< The text is returned without any type of processing }; /** Additional flags for the renderToPainter method \since 0.16 */ enum PainterFlag { /** Do not save/restore the caller-owned painter. renderToPainter() by default preserves, using save() + restore(), the state of the painter specified; if this is not needed, this flag can avoid this job */ DontSaveAndRestore = 0x00000001 }; Q_DECLARE_FLAGS( PainterFlags, PainterFlag ) /** Render the page to a QImage using the current \link Document::renderBackend() Document renderer\endlink. If \p x = \p y = \p w = \p h = -1, the method will automatically compute the size of the image from the horizontal and vertical resolutions specified in \p xres and \p yres. Otherwise, the method renders only a part of the page, specified by the parameters (\p x, \p y, \p w, \p h) in pixel coordinates. The returned QImage then has size (\p w, \p h), independent of the page size. \param x specifies the left x-coordinate of the box, in pixels. \param y specifies the top y-coordinate of the box, in pixels. \param w specifies the width of the box, in pixels. \param h specifies the height of the box, in pixels. \param xres horizontal resolution of the graphics device, in dots per inch \param yres vertical resolution of the graphics device, in dots per inch \param rotate how to rotate the page \warning The parameter (\p x, \p y, \p w, \p h) are not well-tested. Unusual or meaningless parameters may lead to rather unexpected results. \returns a QImage of the page, or a null image on failure. \since 0.6 */ QImage renderToImage(double xres=72.0, double yres=72.0, int x=-1, int y=-1, int w=-1, int h=-1, Rotation rotate = Rotate0) const; /** Render the page to the specified QPainter using the current \link Document::renderBackend() Document renderer\endlink. If \p x = \p y = \p w = \p h = -1, the method will automatically compute the size of the page area from the horizontal and vertical resolutions specified in \p xres and \p yres. Otherwise, the method renders only a part of the page, specified by the parameters (\p x, \p y, \p w, \p h) in pixel coordinates. \param painter the painter to paint on \param x specifies the left x-coordinate of the box, in pixels. \param y specifies the top y-coordinate of the box, in pixels. \param w specifies the width of the box, in pixels. \param h specifies the height of the box, in pixels. \param xres horizontal resolution of the graphics device, in dots per inch \param yres vertical resolution of the graphics device, in dots per inch \param rotate how to rotate the page \param flags additional painter flags \warning The parameter (\p x, \p y, \p w, \p h) are not well-tested. Unusual or meaningless parameters may lead to rather unexpected results. \returns whether the painting succeeded \note This method is only supported for Arthur \since 0.16 */ bool renderToPainter(QPainter* painter, double xres=72.0, double yres=72.0, int x=-1, int y=-1, int w=-1, int h=-1, Rotation rotate = Rotate0, PainterFlags flags = 0) const; /** Get the page thumbnail if it exists. \return a QImage of the thumbnail, or a null image if the PDF does not contain one for this page \since 0.12 */ QImage thumbnail() const; /** Returns the text that is inside a specified rectangle \param rect the rectangle specifying the area of interest, with coordinates given in points, i.e., 1/72th of an inch. If rect is null, all text on the page is given \since 0.16 **/ QString text(const QRectF &rect, TextLayout textLayout) const; /** Returns the text that is inside a specified rectangle. The text is returned using the physical layout of the page \param rect the rectangle specifying the area of interest, with coordinates given in points, i.e., 1/72th of an inch. If rect is null, all text on the page is given **/ QString text(const QRectF &rect) const; /** The starting point for a search */ enum SearchDirection { FromTop, ///< Start sorting at the top of the document NextResult, ///< Find the next result, moving "down the page" PreviousResult ///< Find the previous result, moving "up the page" }; /** The type of search to perform */ enum SearchMode { CaseSensitive, ///< Case differences cause no match in searching CaseInsensitive ///< Case differences are ignored in matching }; /** Flags to modify the search behaviour \since 0.31 */ enum SearchFlag { IgnoreCase = 0x00000001, ///< Case differences are ignored WholeWords = 0x00000002 ///< Only whole words are matched }; Q_DECLARE_FLAGS( SearchFlags, SearchFlag ) /** Returns true if the specified text was found. \param text the text the search \param rect in all directions is used to return where the text was found, for NextResult and PreviousResult indicates where to continue searching for \param direction in which direction do the search \param caseSensitive be case sensitive? \param rotate the rotation to apply for the search order **/ Q_DECL_DEPRECATED bool search(const QString &text, QRectF &rect, SearchDirection direction, SearchMode caseSensitive, Rotation rotate = Rotate0) const; /** Returns true if the specified text was found. \param text the text the search \param rectXXX in all directions is used to return where the text was found, for NextResult and PreviousResult indicates where to continue searching for \param direction in which direction do the search \param caseSensitive be case sensitive? \param rotate the rotation to apply for the search order \since 0.14 **/ Q_DECL_DEPRECATED bool search(const QString &text, double &rectLeft, double &rectTop, double &rectRight, double &rectBottom, SearchDirection direction, SearchMode caseSensitive, Rotation rotate = Rotate0) const; /** Returns true if the specified text was found. \param text the text the search \param rectXXX in all directions is used to return where the text was found, for NextResult and PreviousResult indicates where to continue searching for \param direction in which direction do the search \param flags the flags to consider during matching \param rotate the rotation to apply for the search order \since 0.31 **/ bool search(const QString &text, double &rectLeft, double &rectTop, double &rectRight, double &rectBottom, SearchDirection direction, SearchFlags flags = 0, Rotation rotate = Rotate0) const; /** Returns a list of all occurrences of the specified text on the page. \param text the text to search \param caseSensitive whether to be case sensitive \param rotate the rotation to apply for the search order \warning Do not use the returned QRectF as arguments of another search call because of truncation issues if qreal is defined as float. \since 0.22 **/ Q_DECL_DEPRECATED QList<QRectF> search(const QString &text, SearchMode caseSensitive, Rotation rotate = Rotate0) const; /** Returns a list of all occurrences of the specified text on the page. \param text the text to search \param flags the flags to consider during matching \param rotate the rotation to apply for the search order \warning Do not use the returned QRectF as arguments of another search call because of truncation issues if qreal is defined as float. \since 0.31 **/ QList<QRectF> search(const QString &text, SearchFlags flags = 0, Rotation rotate = Rotate0) const; /** Returns a list of text of the page This method returns a QList of TextBoxes that contain all the text of the page, with roughly one text word of text per TextBox item. For text written in western languages (left-to-right and up-to-down), the QList contains the text in the proper order. \note The caller owns the text boxes and they should be deleted when no longer required. \warning This method is not tested with Asian scripts */ QList<TextBox*> textList(Rotation rotate = Rotate0) const; /** \return The dimensions (cropbox) of the page, in points (i.e. 1/72th of an inch) */ QSizeF pageSizeF() const; /** \return The dimensions (cropbox) of the page, in points (i.e. 1/72th of an inch) */ QSize pageSize() const; /** Returns the transition of this page \returns a pointer to a PageTransition structure that defines how transition to this page shall be performed. \note The PageTransition structure is owned by this page, and will automatically be destroyed when this page class is destroyed. **/ PageTransition *transition() const; /** Gets the page action specified, or NULL if there is no action. \since 0.6 **/ Link *action( PageAction act ) const; /** Types of orientations that are possible */ enum Orientation { Landscape, ///< Landscape orientation (portrait, with 90 degrees clockwise rotation ) Portrait, ///< Normal portrait orientation Seascape, ///< Seascape orientation (portrait, with 270 degrees clockwise rotation) UpsideDown ///< Upside down orientation (portrait, with 180 degrees rotation) }; /** The orientation of the page */ Orientation orientation() const; /** The default CTM */ void defaultCTM(double *CTM, double dpiX, double dpiY, int rotate, bool upsideDown); /** Gets the links of the page */ QList<Link*> links() const; /** Returns the annotations of the page \note If you call this method twice, you get different objects pointing to the same annotations (see Annotation). The caller owns the returned objects and they should be deleted when no longer required. */ QList<Annotation*> annotations() const; /** Returns the annotations of the page \param subtypes the subtypes of annotations you are interested in \note If you call this method twice, you get different objects pointing to the same annotations (see Annotation). The caller owns the returned objects and they should be deleted when no longer required. \since 0.28 */ QList<Annotation*> annotations(const QSet<Annotation::SubType> &subtypes) const; /** Adds an annotation to the page \note Ownership of the annotation object stays with the caller, who can delete it at any time. \since 0.20 */ void addAnnotation( const Annotation *ann ); /** Removes an annotation from the page and destroys the annotation object \note There mustn't be other Annotation objects pointing this annotation \since 0.20 */ void removeAnnotation( const Annotation *ann ); /** Returns the form fields on the page The caller gets the ownership of the returned objects. \since 0.6 */ QList<FormField*> formFields() const; /** Returns the page duration. That is the time, in seconds, that the page should be displayed before the presentation automatically advances to the next page. Returns < 0 if duration is not set. \since 0.6 */ double duration() const; /** Returns the label of the page, or a null string is the page has no label. \since 0.6 **/ QString label() const; private: Q_DISABLE_COPY(Page) Page(DocumentData *doc, int index); PageData *m_page; }; /** \brief PDF document. The Document class represents a PDF document: its pages, and all the global properties, metadata, etc. \section ownership Ownership of the returned objects All the functions that returns class pointers create new object, and the responsability of those is given to the callee. The only exception is \link Poppler::Page::transition() Page::transition()\endlink. \section document-loading Loading To get a Document, you have to load it via the load() & loadFromData() functions. In all the functions that have passwords as arguments, they \b must be Latin1 encoded. If you have a password that is a UTF-8 string, you need to use QString::toLatin1() (or similar) to convert the password first. If you have a UTF-8 character array, consider converting it to a QString first (QString::fromUtf8(), or similar) before converting to Latin1 encoding. \section document-rendering Rendering To render pages of a document, you have different Document functions to set various options. \subsection document-rendering-backend Backends %Poppler offers a different backends for rendering the pages. Currently there are two backends (see #RenderBackend), but only the Splash engine works well and has been tested. The available rendering backends can be discovered via availableRenderBackends(). The current rendering backend can be changed using setRenderBackend(). Please note that setting a backend not listed in the available ones will always result in null QImage's. \section document-cms Color management support %Poppler, if compiled with this support, provides functions to handle color profiles. To know whether the %Poppler version you are using has support for color management, you can query Poppler::isCmsAvailable(). In case it is not avilable, all the color management-related functions will either do nothing or return null. */ class POPPLER_QT4_EXPORT Document { friend class Page; friend class DocumentData; public: /** The page mode */ enum PageMode { UseNone, ///< No mode - neither document outline nor thumbnail images are visible UseOutlines, ///< Document outline visible UseThumbs, ///< Thumbnail images visible FullScreen, ///< Fullscreen mode (no menubar, windows controls etc) UseOC, ///< Optional content group panel visible UseAttach ///< Attachments panel visible }; /** The page layout */ enum PageLayout { NoLayout, ///< Layout not specified SinglePage, ///< Display a single page OneColumn, ///< Display a single column of pages TwoColumnLeft, ///< Display the pages in two columns, with odd-numbered pages on the left TwoColumnRight, ///< Display the pages in two columns, with odd-numbered pages on the right TwoPageLeft, ///< Display the pages two at a time, with odd-numbered pages on the left TwoPageRight ///< Display the pages two at a time, with odd-numbered pages on the right }; /** The render backends available \since 0.6 */ enum RenderBackend { SplashBackend, ///< Splash backend ArthurBackend ///< Arthur (Qt4) backend }; /** The render hints available \since 0.6 */ enum RenderHint { Antialiasing = 0x00000001, ///< Antialiasing for graphics TextAntialiasing = 0x00000002, ///< Antialiasing for text TextHinting = 0x00000004, ///< Hinting for text \since 0.12.1 TextSlightHinting = 0x00000008, ///< Lighter hinting for text when combined with TextHinting \since 0.18 OverprintPreview = 0x00000010, ///< Overprint preview \since 0.22 ThinLineSolid = 0x00000020, ///< Enhance thin lines solid \since 0.24 ThinLineShape = 0x00000040, ///< Enhance thin lines shape. Wins over ThinLineSolid \since 0.24 IgnorePaperColor = 0x00000080 ///< Do not compose with the paper color \since 0.35 }; Q_DECLARE_FLAGS( RenderHints, RenderHint ) /** Form types \since 0.22 */ enum FormType { NoForm, ///< Document doesn't contain forms AcroForm, ///< AcroForm XfaForm ///< Adobe XML Forms Architecture (XFA), currently unsupported }; /** Set a color display profile for the current document. \param outputProfileA is a \c cmsHPROFILE of the LCMS library. \since 0.12 */ void setColorDisplayProfile(void *outputProfileA); /** Set a color display profile for the current document. \param name is the name of the display profile to set. \since 0.12 */ void setColorDisplayProfileName(const QString &name); /** Return the current RGB profile. \return a \c cmsHPROFILE of the LCMS library. \since 0.12 */ void* colorRgbProfile() const; /** Return the current display profile. \return a \c cmsHPROFILE of the LCMS library. \since 0.12 */ void *colorDisplayProfile() const; /** Load the document from a file on disk \param filePath the name (and path, if required) of the file to load \param ownerPassword the Latin1-encoded owner password to use in loading the file \param userPassword the Latin1-encoded user ("open") password to use in loading the file \return the loaded document, or NULL on error \note The caller owns the pointer to Document, and this should be deleted when no longer required. \warning The returning document may be locked if a password is required to open the file, and one is not provided (as the userPassword). */ static Document *load(const QString & filePath, const QByteArray &ownerPassword=QByteArray(), const QByteArray &userPassword=QByteArray()); /** Load the document from memory \param fileContents the file contents. They are copied so there is no need to keep the byte array around for the full life time of the document. \param ownerPassword the Latin1-encoded owner password to use in loading the file \param userPassword the Latin1-encoded user ("open") password to use in loading the file \return the loaded document, or NULL on error \note The caller owns the pointer to Document, and this should be deleted when no longer required. \warning The returning document may be locked if a password is required to open the file, and one is not provided (as the userPassword). \since 0.6 */ static Document *loadFromData(const QByteArray &fileContents, const QByteArray &ownerPassword=QByteArray(), const QByteArray &userPassword=QByteArray()); /** Get a specified Page Note that this follows the PDF standard of being zero based - if you want the first page, then you need an index of zero. The caller gets the ownership of the returned object. \param index the page number index */ Page *page(int index) const; /** \overload The intent is that you can pass in a label like \c "ix" and get the page with that label (which might be in the table of contents), or pass in \c "1" and get the page that the user expects (which might not be the first page, if there is a title page and a table of contents). \param label the page label */ Page *page(const QString &label) const; /** The number of pages in the document */ int numPages() const; /** The type of mode that should be used by the application when the document is opened. Note that while this is called page mode, it is really viewer application mode. */ PageMode pageMode() const; /** The layout that pages should be shown in when the document is first opened. This basically describes how pages are shown relative to each other. */ PageLayout pageLayout() const; /** The predominant reading order for text as supplied by the document's viewer preferences. \since 0.26 */ Qt::LayoutDirection textDirection() const; /** Provide the passwords required to unlock the document \param ownerPassword the Latin1-encoded owner password to use in loading the file \param userPassword the Latin1-encoded user ("open") password to use in loading the file */ bool unlock(const QByteArray &ownerPassword, const QByteArray &userPassword); /** Determine if the document is locked */ bool isLocked() const; /** The date associated with the document You would use this method with something like: \code QDateTime created = m_doc->date("CreationDate"); QDateTime modified = m_doc->date("ModDate"); \endcode The available dates are: - CreationDate: the date of creation of the document - ModDate: the date of the last change in the document \param data the type of date that is required */ QDateTime date( const QString & data ) const; /** Set the Info dict date entry specified by \param key to \param val \returns true on success, false on failure */ bool setDate( const QString & key, const QDateTime & val ); /** The date of the creation of the document */ QDateTime creationDate() const; /** Set the creation date of the document to \param val \returns true on success, false on failure */ bool setCreationDate( const QDateTime & val ); /** The date of the last change in the document */ QDateTime modificationDate() const; /** Set the modification date of the document to \param val \returns true on success, false on failure */ bool setModificationDate( const QDateTime & val ); /** Get specified information associated with the document You would use this method with something like: \code QString title = m_doc->info("Title"); QString subject = m_doc->info("Subject"); \endcode In addition to \c Title and \c Subject, other information that may be available include \c Author, \c Keywords, \c Creator and \c Producer. \param data the information that is required \sa infoKeys() to get a list of the available keys */ QString info( const QString & data ) const; /** Set the value of the document's Info dictionary entry specified by \param key to \param val \returns true on success, false on failure */ bool setInfo( const QString & key, const QString & val ); /** The title of the document */ QString title() const; /** Set the title of the document to \param val \returns true on success, false on failure */ bool setTitle( const QString & val ); /** The author of the document */ QString author() const; /** Set the author of the document to \param val \returns true on success, false on failure */ bool setAuthor( const QString & val ); /** The subject of the document */ QString subject() const; /** Set the subject of the document to \param val \returns true on success, false on failure */ bool setSubject( const QString & val ); /** The keywords of the document */ QString keywords() const; /** Set the keywords of the document to \param val \returns true on success, false on failure */ bool setKeywords( const QString & val ); /** The creator of the document */ QString creator() const; /** Set the creator of the document to \param val \returns true on success, false on failure */ bool setCreator( const QString & val ); /** The producer of the document */ QString producer() const; /** Set the producer of the document to \param val \returns true on success, false on failure */ bool setProducer( const QString & val ); /** Remove the document's Info dictionary \returns true on success, false on failure */ bool removeInfo(); /** Obtain a list of the available string information keys. */ QStringList infoKeys() const; /** Test if the document is encrypted */ bool isEncrypted() const; /** Test if the document is linearised In some cases, this is called "fast web view", since it is mostly an optimisation for viewing over the Web. */ bool isLinearized() const; /** Test if the permissions on the document allow it to be printed */ bool okToPrint() const; /** Test if the permissions on the document allow it to be printed at high resolution */ bool okToPrintHighRes() const; /** Test if the permissions on the document allow it to be changed. \note depending on the type of change, it may be more appropriate to check other properties as well. */ bool okToChange() const; /** Test if the permissions on the document allow the contents to be copied / extracted */ bool okToCopy() const; /** Test if the permissions on the document allow annotations to be added or modified, and interactive form fields (including signature fields) to be completed. */ bool okToAddNotes() const; /** Test if the permissions on the document allow interactive form fields (including signature fields) to be completed. \note this can be true even if okToAddNotes() is false - this means that only form completion is permitted. */ bool okToFillForm() const; /** Test if the permissions on the document allow interactive form fields (including signature fields) to be set, created and modified */ bool okToCreateFormFields() const; /** Test if the permissions on the document allow content extraction (text and perhaps other content) for accessibility usage (eg for a screen reader) */ bool okToExtractForAccessibility() const; /** Test if the permissions on the document allow it to be "assembled" - insertion, rotation and deletion of pages; or creation of bookmarks and thumbnail images. \note this can be true even if okToChange() is false */ bool okToAssemble() const; /** The version of the PDF specification that the document conforms to \deprecated use getPdfVersion and avoid float point comparisons/handling */ Q_DECL_DEPRECATED double pdfVersion() const; /** The version of the PDF specification that the document conforms to \param major an optional pointer to a variable where store the "major" number of the version \param minor an optional pointer to a variable where store the "minor" number of the version \since 0.12 */ void getPdfVersion(int *major, int *minor) const; /** The fonts within the PDF document. This is a shorthand for getting all the fonts at once. \note this can take a very long time to run with a large document. You may wish to use a FontIterator if you have more than say 20 pages \see newFontIterator() */ QList<FontInfo> fonts() const; /** Scans for fonts within the PDF document. \param numPages the number of pages to scan \param fontList pointer to the list where the font information should be placed \note with this method you can scan for fonts only \em once for each document; once the end is reached, no more scanning with this method can be done \return false if the end of the document has been reached \deprecated this function is quite limited in its job (see note), better use fonts() or newFontIterator() \see fonts(), newFontIterator() */ Q_DECL_DEPRECATED bool scanForFonts( int numPages, QList<FontInfo> *fontList ) const; /** Creates a new FontIterator object for font scanning. The new iterator can be used for reading the font information of the document, reading page by page. The caller is responsible for the returned object, ie it should freed it when no more useful. \param startPage the initial page from which start reading fonts \see fonts() \since 0.12 */ FontIterator* newFontIterator( int startPage = 0 ) const; /** The font data if the font is an embedded one. \since 0.10 */ QByteArray fontData(const FontInfo &font) const; /** The documents embedded within the PDF document. \note there are two types of embedded document - this call only accesses documents that are embedded at the document level. */ QList<EmbeddedFile*> embeddedFiles() const; /** Whether there are any documents embedded in this PDF document. */ bool hasEmbeddedFiles() const; /** Gets the table of contents (TOC) of the Document. The caller is responsable for the returned object. In the tree the tag name is the 'screen' name of the entry. A tag can have attributes. Here follows the list of tag attributes with meaning: - Destination: A string description of the referred destination - DestinationName: A 'named reference' to the viewport - ExternalFileName: A link to a external filename - Open: A bool value that tells whether the subbranch of the item is open or not Resolving the final destination for each item can be done in the following way: - first, checking for 'Destination': if not empty, then a LinkDestination can be constructed straight with it - as second step, if the 'DestinationName' is not empty, then the destination can be resolved using linkDestination() Note also that if 'ExternalFileName' is not emtpy, then the destination refers to that document (and not to the current one). \returns the TOC, or NULL if the Document does not have one */ QDomDocument *toc() const; /** Tries to resolve the named destination \p name. \note this operation starts a search through the whole document \returns a new LinkDestination object if the named destination was actually found, or NULL otherwise */ LinkDestination *linkDestination( const QString &name ); /** Sets the paper color \param color the new paper color */ void setPaperColor(const QColor &color); /** The paper color The default color is white. */ QColor paperColor() const; /** Sets the backend used to render the pages. \param backend the new rendering backend \since 0.6 */ void setRenderBackend( RenderBackend backend ); /** The currently set render backend The default backend is \ref SplashBackend \since 0.6 */ RenderBackend renderBackend() const; /** The available rendering backends. \since 0.6 */ static QSet<RenderBackend> availableRenderBackends(); /** Sets the render \p hint . \note some hints may not be supported by some rendering backends. \param on whether the flag should be added or removed. \since 0.6 */ void setRenderHint( RenderHint hint, bool on = true ); /** The currently set render hints. \since 0.6 */ RenderHints renderHints() const; /** Gets a new PS converter for this document. The caller gets the ownership of the returned converter. \since 0.6 */ PSConverter *psConverter() const; /** Gets a new PDF converter for this document. The caller gets the ownership of the returned converter. \since 0.8 */ PDFConverter *pdfConverter() const; /** Gets the metadata stream contents \since 0.6 */ QString metadata() const; /** Test whether this document has "optional content". Optional content is used to optionally turn on (display) and turn off (not display) some elements of the document. The most common use of this is for layers in design applications, but it can be used for a range of things, such as not including some content in printing, and displaying content in the appropriate language. \since 0.8 */ bool hasOptionalContent() const; /** Itemviews model for optional content. The model is owned by the document. \since 0.8 */ OptContentModel *optionalContentModel(); /** Document-level JavaScript scripts. Returns the list of document level JavaScript scripts to be always executed before any other script. \since 0.10 */ QStringList scripts() const; /** The PDF identifiers. \param permanentId an optional pointer to a variable where store the permanent ID of the document \param updateId an optional pointer to a variable where store the update ID of the document \return whether the document has the IDs \since 0.16 */ bool getPdfId(QByteArray *permanentId, QByteArray *updateId) const; /** Returns the type of forms contained in the document \since 0.22 */ FormType formType() const; /** Destructor. */ ~Document(); private: Q_DISABLE_COPY(Document) DocumentData *m_doc; Document(DocumentData *dataA); }; class BaseConverterPrivate; class PSConverterPrivate; class PDFConverterPrivate; /** \brief Base converter. This is the base class for the converters. \since 0.8 */ class POPPLER_QT4_EXPORT BaseConverter { friend class Document; public: /** Destructor. */ virtual ~BaseConverter(); /** Sets the output file name. You must set this or the output device. */ void setOutputFileName(const QString &outputFileName); /** * Sets the output device. You must set this or the output file name. * * \since 0.8 */ void setOutputDevice(QIODevice *device); /** Does the conversion. \return whether the conversion succeeded */ virtual bool convert() = 0; enum Error { NoError, FileLockedError, OpenOutputError, NotSupportedInputFileError }; /** Returns the last error \since 0.12.1 */ Error lastError() const; protected: /// \cond PRIVATE BaseConverter(BaseConverterPrivate &dd); Q_DECLARE_PRIVATE(BaseConverter) BaseConverterPrivate *d_ptr; /// \endcond private: Q_DISABLE_COPY(BaseConverter) }; /** Converts a PDF to PS Sizes have to be in Points (1/72 inch) If you are using QPrinter you can get paper size by doing: \code QPrinter dummy(QPrinter::PrinterResolution); dummy.setFullPage(true); dummy.setPageSize(myPageSize); width = dummy.width(); height = dummy.height(); \endcode \since 0.6 */ class POPPLER_QT4_EXPORT PSConverter : public BaseConverter { friend class Document; public: /** Options for the PS export. \since 0.10 */ enum PSOption { Printing = 0x00000001, ///< The PS is generated for printing purposes StrictMargins = 0x00000002, ForceRasterization = 0x00000004, PrintToEPS = 0x00000008, ///< Output EPS instead of PS \since 0.20 HideAnnotations = 0x00000010 ///< Don't print annotations \since 0.20 }; Q_DECLARE_FLAGS( PSOptions, PSOption ) /** Destructor. */ ~PSConverter(); /** Sets the list of pages to print. Mandatory. */ void setPageList(const QList<int> &pageList); /** Sets the title of the PS Document. Optional */ void setTitle(const QString &title); /** Sets the horizontal DPI. Defaults to 72.0 */ void setHDPI(double hDPI); /** Sets the vertical DPI. Defaults to 72.0 */ void setVDPI(double vDPI); /** Sets the rotate. Defaults to not rotated */ void setRotate(int rotate); /** Sets the output paper width. Has to be set. */ void setPaperWidth(int paperWidth); /** Sets the output paper height. Has to be set. */ void setPaperHeight(int paperHeight); /** Sets the output right margin. Defaults to 0 */ void setRightMargin(int marginRight); /** Sets the output bottom margin. Defaults to 0 */ void setBottomMargin(int marginBottom); /** Sets the output left margin. Defaults to 0 */ void setLeftMargin(int marginLeft); /** Sets the output top margin. Defaults to 0 */ void setTopMargin(int marginTop); /** Defines if margins have to be strictly followed (even if that means changing aspect ratio), or if the margins can be adapted to keep aspect ratio. Defaults to false. */ void setStrictMargins(bool strictMargins); /** Defines if the page will be rasterized to an image before printing. Defaults to false */ void setForceRasterize(bool forceRasterize); /** Sets the options for the PS export. \since 0.10 */ void setPSOptions(PSOptions options); /** The currently set options for the PS export. The default flags are: Printing. \since 0.10 */ PSOptions psOptions() const; /** Sets a function that will be called each time a page is converted. The payload belongs to the caller. \since 0.16 */ void setPageConvertedCallback(void (* callback)(int page, void *payload), void *payload); bool convert(); private: Q_DECLARE_PRIVATE(PSConverter) Q_DISABLE_COPY(PSConverter) PSConverter(DocumentData *document); }; /** Converts a PDF to PDF (thus saves a copy of the document). \since 0.8 */ class POPPLER_QT4_EXPORT PDFConverter : public BaseConverter { friend class Document; public: /** Options for the PDF export. */ enum PDFOption { WithChanges = 0x00000001 ///< The changes done to the document are saved as well }; Q_DECLARE_FLAGS( PDFOptions, PDFOption ) /** Destructor. */ virtual ~PDFConverter(); /** Sets the options for the PDF export. */ void setPDFOptions(PDFOptions options); /** The currently set options for the PDF export. */ PDFOptions pdfOptions() const; bool convert(); private: Q_DECLARE_PRIVATE(PDFConverter) Q_DISABLE_COPY(PDFConverter) PDFConverter(DocumentData *document); }; /** Conversion from PDF date string format to QDateTime */ POPPLER_QT4_EXPORT QDateTime convertDate( char *dateString ); /** Whether the color management functions are available. \since 0.12 */ POPPLER_QT4_EXPORT bool isCmsAvailable(); /** Whether the overprint preview functionality is available. \since 0.22 */ POPPLER_QT4_EXPORT bool isOverprintPreviewAvailable(); class SoundData; /** Container class for a sound file in a PDF document. A sound can be either External (in that case should be loaded the file whose url is represented by url() ), or Embedded, and the player has to play the data contained in data(). \since 0.6 */ class POPPLER_QT4_EXPORT SoundObject { public: /** The type of sound */ enum SoundType { External, ///< The real sound file is external Embedded ///< The sound is contained in the data }; /** The encoding format used for the sound */ enum SoundEncoding { Raw, ///< Raw encoding, with unspecified or unsigned values in the range [ 0, 2^B - 1 ] Signed, ///< Twos-complement values muLaw, ///< mu-law-encoded samples ALaw ///< A-law-encoded samples }; /// \cond PRIVATE SoundObject(Sound *popplersound); /// \endcond ~SoundObject(); /** Is the sound embedded (SoundObject::Embedded) or external (SoundObject::External)? */ SoundType soundType() const; /** The URL of the sound file to be played, in case of SoundObject::External */ QString url() const; /** The data of the sound, in case of SoundObject::Embedded */ QByteArray data() const; /** The sampling rate of the sound */ double samplingRate() const; /** The number of sound channels to use to play the sound */ int channels() const; /** The number of bits per sample value per channel */ int bitsPerSample() const; /** The encoding used for the sound */ SoundEncoding soundEncoding() const; private: Q_DISABLE_COPY(SoundObject) SoundData *m_soundData; }; class MovieData; /** Container class for a movie object in a PDF document. \since 0.10 */ class POPPLER_QT4_EXPORT MovieObject { friend class AnnotationPrivate; public: /** The play mode for playing the movie */ enum PlayMode { PlayOnce, ///< Play the movie once, closing the movie controls at the end PlayOpen, ///< Like PlayOnce, but leaving the controls open PlayRepeat, ///< Play continuously until stopped PlayPalindrome ///< Play forward, then backward, then again foward and so on until stopped }; ~MovieObject(); /** The URL of the movie to be played */ QString url() const; /** The size of the movie */ QSize size() const; /** The rotation (either 0, 90, 180, or 270 degrees clockwise) for the movie, */ int rotation() const; /** Whether show a bar with movie controls */ bool showControls() const; /** How to play the movie */ PlayMode playMode() const; /** Returns whether a poster image should be shown if the movie is not playing. \since 0.22 */ bool showPosterImage() const; /** Returns the poster image that should be shown if the movie is not playing. If the image is null but showImagePoster() returns @c true, the first frame of the movie should be used as poster image. \since 0.22 */ QImage posterImage() const; private: /// \cond PRIVATE MovieObject( AnnotMovie *ann ); /// \endcond Q_DISABLE_COPY(MovieObject) MovieData *m_movieData; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::Page::PainterFlags) Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::Page::SearchFlags) Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::Document::RenderHints) Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::PDFConverter::PDFOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(Poppler::PSConverter::PSOptions) #endif
[ "remy.meja@inist.fr" ]
remy.meja@inist.fr
380093cdeaeb14c9713d29b3899bd89c0fe4bd3f
9aa414c4ce84f474cfe76997b2ca1630bd62d8e8
/src/cproton.cc
48f85b8c40ce0918cf93d8178e432c4c400caf2d
[]
no_license
pofallon/node-qpid
0564261d04e533a4dcb58faa3d04e815f49eb150
78984aae238666049d61597f2a3ded157c70c60b
refs/heads/master
2021-03-12T23:58:46.414011
2015-01-25T03:00:40
2015-01-25T03:00:40
7,335,942
22
5
null
2014-11-04T02:38:07
2012-12-27T04:39:12
C
UTF-8
C++
false
false
193
cc
#define BUILDING_NODE_EXTENSION #include <node.h> #include "messenger.h" using namespace v8; void InitAll(Handle<Object> target) { Messenger::Init(target); } NODE_MODULE(cproton, InitAll)
[ "paul@ofallonfamily.com" ]
paul@ofallonfamily.com
c96165bfaae976a9e20717003e9c3a6ee06399d4
e346b4507619e21b082226d87937ff4896c0c734
/base/process/process_metrics_posix.cc
3422a730dce691847b886de4f092c1720ede0c2f
[]
no_license
hicdre/libxz
4f190023ac08698b6072984cd0460866bb21206f
82ec093c25fb5e0c6a774c1b55a38b3e41d6623c
refs/heads/master
2021-01-13T02:30:20.111939
2014-04-25T03:01:53
2014-04-25T03:01:53
11,816,688
3
3
null
null
null
null
UTF-8
C++
false
false
559
cc
// Copyright (c) 2013 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 "base/process/process_metrics.h" #include <sys/time.h> namespace base { int64 TimeValToMicroseconds(const struct timeval& tv) { static const int kMicrosecondsPerSecond = 1000000; int64 ret = tv.tv_sec; // Avoid (int * int) integer overflow. ret *= kMicrosecondsPerSecond; ret += tv.tv_usec; return ret; } ProcessMetrics::~ProcessMetrics() { } } // namespace base
[ "iicdre@gmail.com" ]
iicdre@gmail.com
293e8eb5595f310f1df0a4aa0d1794d0d4a01d0a
fb5e449e5349bfa98ab987f96d179e94fb264dd5
/Fraction/src/ZFraction.cpp
a0e0ac6bb14474d6e23d8cc6bb269b5131c9da94
[]
no_license
th3fr33man/sdz
6bf80286d54a017313af118112e84335b8586afd
3c392d67f02be7bf2a726461386f009272d06487
refs/heads/master
2021-01-13T01:37:11.236105
2015-01-09T13:36:18
2015-01-09T13:36:18
25,178,456
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,608
cpp
/* * ZFraction.cpp * * Created on: 13 nov. 2014 * Author: rip */ #include <iostream> #include "ZFraction.h" using namespace std; /** * */ ZFraction::ZFraction(int a, int b) : m_num(a) , m_den(b) { // simplification simplification(); } int ZFraction::pgcd(int a, int b) { while (b != 0) { const int t = b; b = a%b; a=t; } return a; } void ZFraction::simplification() { int m_pgcd = pgcd(m_num, m_den); m_num /= m_pgcd; m_den /= m_pgcd; } double ZFraction::calculNombreReel() const { double m_reel = (double)m_num/m_den; return m_reel; } ZFraction& ZFraction::operator +=(const ZFraction& fraction) { // mise au même dénominateur int m_nouveauNumA = m_num * fraction.m_den; int m_nouveauNumB = fraction.m_num * m_den; int m_nouveauDen = m_den * fraction.m_den; m_num = m_nouveauNumA + m_nouveauNumB; m_den = m_nouveauDen; // simplification de la fraction simplification(); return *this; } ZFraction& ZFraction::operator -=(const ZFraction& fraction) { // mise au même dénominateur int m_nouveauNumA = m_num * fraction.m_den; int m_nouveauNumB = fraction.m_num * m_den; int m_nouveauDen = m_den * fraction.m_den; m_num = m_nouveauNumA - m_nouveauNumB; m_den = m_nouveauDen; // simplification de la fraction simplification(); return *this; } ZFraction& ZFraction::operator /=(const ZFraction& fraction) { m_num *= fraction.m_den; m_den *= fraction.m_num; simplification(); return *this; } ZFraction& ZFraction::operator *=(const ZFraction& fraction) { m_num *= fraction.m_num; m_den *= fraction.m_den; simplification(); return *this; } ZFraction& ZFraction::operator %=(const ZFraction& fraction) { } void ZFraction::afficher(std::ostream& out) const { out << m_num << "/" << m_den ; } bool ZFraction::estEgal(const ZFraction& b) const { return m_num/m_den == b.m_num/b.m_den; } bool ZFraction::estPlusPetitQue(const ZFraction& b) const { // on met au même dénominateur int m_nouveauNumA = m_num * b.m_den; int m_nouveauNumB = b.m_num * m_den; return m_nouveauNumA < m_nouveauNumB; } ZFraction::~ZFraction() { // TODO Auto-generated destructor stub } //======Operateurs================================================================ ostream& operator<<(ostream& out, ZFraction const& fraction) { fraction.afficher(out) ; return out; } bool operator ==(const ZFraction& a, const ZFraction& b) { return a.estEgal(b); } bool operator !=(const ZFraction& a, const ZFraction& b) { return !(a == b); } bool operator >(const ZFraction& a, const ZFraction& b) { return b.estPlusPetitQue(a); } bool operator <(const ZFraction& a, const ZFraction& b) { return a.estPlusPetitQue(b); } bool operator >=(const ZFraction& a, const ZFraction& b) { return a > b && a == b; } bool operator <=(const ZFraction& a, const ZFraction& b) { return a < b && a == b; } ZFraction operator +(const ZFraction& a, const ZFraction& b) { ZFraction copie(a); copie +=b; return copie; } ZFraction operator -(const ZFraction& a, const ZFraction& b) { ZFraction copie(a); copie -=b; return copie; } ZFraction operator *(const ZFraction& a, const ZFraction& b) { ZFraction copie(a); copie *=b; return copie; } ZFraction operator /(const ZFraction& a, const ZFraction& b) { ZFraction copie(a); copie /=b; return copie; } ZFraction operator %(const ZFraction& a, const ZFraction& b) { }
[ "raczkaromain@gmail.com" ]
raczkaromain@gmail.com
207052136dda363c306120a189826879894f1097
28f243f705fae7e092288c16e9826c27730564a5
/powietrzesala.h
4406aadbc9f75a1619018e38c3fec3d3c243a6d0
[]
no_license
Jaro966/kinoGitHub4
c792e5d67e8f21259c245fb78ff4befc66f1406c
0822bd1ea3a21fdcd555e4eac078ed50ccea460f
refs/heads/master
2020-04-29T12:43:28.544182
2019-03-24T18:55:39
2019-03-24T18:55:39
176,148,046
0
0
null
null
null
null
UTF-8
C++
false
false
1,620
h
/** * Klasa PowietrzeSala służy do modelowania parametrów powietrza - temperatury i stężenia CO2. * Pobiera trzy wartości typu int i zwraca wartość typu bool. * * \param[in] CO2zadaneSala wartość zadana stężenia CO2 wyrażona w ppm (objętościowo). * \param[in] emisjaCO2osoba wartość emisji CO2 na 1 osobę wyrażona w litrach CO2/(osoba x godz). * \param[in] zyskiCieplaOsoba wartość zysków ciepła generowanych przez 1 osobę wyrażone w Watach. * \return true jeśli da się zbudować trójkąt, false w przeciwnym wypadku */ #ifndef POWIETRZESALA_H #define POWIETRZESALA_H #include "sala.h" #include <QObject> class PowietrzeSala : public QObject { Q_OBJECT public: PowietrzeSala(); ~PowietrzeSala(); double CO2zadaneSala; /**< stężenie CO2 zadane w sali - setpoint CO2 */ double emisjaCO2osoba; /**< emisja CO2 przez 1 osobę - wartość domyślna w konstruktorze*/ double zyskiCieplaOsoba; /**< zyski ciepła od jednej osoby - wartość domyślna w konstruktorze */ double CO2zadaneZewn; /**< zawartość CO2 w powietrzu zewnętrznym - wartość domyślna w konstruktorze */ double tempChwilSali; /**< przechowuje temperaturę chwilową sali */ double tempZadanaSali; /**< przechowuje temperaturę zadaną sali */ double CO2chwilSali; /**< przechowuje stężenie chwilowe sali */ void obliczTempSali(double QprzenP, double QludzP, double QklimP, double VsaliP, double &tSala); void obliczCO2wSali(double Vchw, int &liczbaOsob, double Vkina, double &CO2Sala); signals: void valueChanged(int &newValue); }; #endif // POWIETRZESALA_H
[ "47575561+Jaro966@users.noreply.github.com" ]
47575561+Jaro966@users.noreply.github.com
6e4579ec93c2c155dc12614181aa8255d1b42612
15e4df20d16cddce804c0c9541da29a4d5e1b252
/2.Firmware/SimpleFOC_version/Ctrl-FOC-Lite-fw/lib/Arduino-FOC/examples/utils/driver_standalone_test/stepper_driver_2pwm_standalone/stepper_driver_2pwm_standalone.ino
6bf7dd7ac9cf989f7890fe3d18226195996404d8
[ "MIT" ]
permissive
asdlei99/Ctrl-FOC-Lite
acaee52046abe4cc6535bac14d8ee15251cf865c
a57dd3b2c3262d97789361c05a2ef86ba6ff8d73
refs/heads/main
2023-08-17T23:49:53.793225
2022-02-05T07:28:08
2022-02-05T07:28:08
447,481,103
0
0
null
2022-01-13T05:56:35
2022-01-13T05:56:35
null
UTF-8
C++
false
false
901
ino
// Stepper driver standalone example #include <SimpleFOC.h> // Stepper driver instance // StepperDriver2PWM(pwm1, in1a, in1b, pwm2, in2a, in2b, (en1, en2 optional)) StepperDriver2PWM driver = StepperDriver2PWM(3, 4, 5, 10, 9, 8, 11, 12); // StepperDriver2PWM(pwm1, dir1, pwm2, dir2,(en1, en2 optional)) // StepperDriver2PWM driver = StepperDriver2PWM(3, 4, 5, 6, 11, 12); void setup() { // pwm frequency to be used [Hz] // for atmega328 fixed to 32kHz // esp32/stm32/teensy configurable driver.pwm_frequency = 30000; // power supply voltage [V] driver.voltage_power_supply = 12; // Max DC voltage allowed - default voltage_power_supply driver.voltage_limit = 12; // driver init driver.init(); // enable driver driver.enable(); _delay(1000); } void loop() { // setting pwm // phase A: 3V // phase B: 6V driver.setPwm(3, 6); }
[ "593245898@qq.com" ]
593245898@qq.com
4cb7e55cbf76ba4f8a32c3912faa7f851aac0399
a77a50f3f25853ec6a7b5b8548a13b7a4b4b3980
/include/EntitiesManager.h
a636bf77a5c77f8b956613ebc9c4dacc20372c19
[]
no_license
nidoro/PointlessWars
f051b41cb71df783141e5953d2c03d9cf305150a
2e8a9c073026ebb07454922cc3caec41d8c68f29
refs/heads/master
2021-03-27T13:12:04.182891
2016-11-08T15:23:16
2016-11-08T15:23:16
71,281,107
0
0
null
null
null
null
UTF-8
C++
false
false
957
h
#ifndef ENTITIESMANAGER_H #define ENTITIESMANAGER_H #include "Entity.h" #include "Component.h" class EntitiesManager{ public: enum Event{ LIST_UPDATED, GAME_SCREEN_UPDATED }; EntitiesManager(); ~EntitiesManager(); void addEntity(Entity* e); void removeEntity(Entity* e); void addModified(Entity* e); void clearSystem(); bool listen(Event ev); void notify(Event ev); void clearEvents(); void updateList(); bool updated(); void clearActorScript(Entity* e); std::list<Entity*> addedEntities; std::list<Entity*> removedEntities; std::list<Entity*> modifiedEntities; Entity* createEntity(); bool isDead(Entity* e); int getCount(); void clearAll(); private: std::list<Entity*> entities; std::list<Event> events; }; #endif // ENTITIESMANAGER_H
[ "davi_doro@hotmail.com" ]
davi_doro@hotmail.com
424cd98a2243a25763f3d78c6b45f6f96fe5c1b5
699a07206dad2d5edc5bae8e51365ebcd1497984
/src/internet/model/ipv6-extension-header.cc
782badd6123685ba6181ef1478ab133323f56694
[]
no_license
anyonepaw/ns3-iot-realisation
d5bc126968a737e476e656b21a5810241b9905bd
02353ae9f1c8b4dc186a63b1e2f260a91aaa0447
refs/heads/master
2020-04-23T23:00:02.343096
2019-06-02T12:19:52
2019-06-02T12:19:52
171,520,704
7
5
null
2019-05-30T15:20:42
2019-02-19T17:44:57
C++
UTF-8
C++
false
false
16,500
cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2007-2009 Strasbourg University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: David Gross <gdavid.devel@gmail.com> */ #include "ns3/assert.h" #include "ns3/log.h" #include "ns3/header.h" #include "ipv6-extension-header.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("Ipv6ExtensionHeader"); NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHeader); TypeId Ipv6ExtensionHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionHeader") .AddConstructor<Ipv6ExtensionHeader> () .SetParent<Header> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionHeader::Ipv6ExtensionHeader () : m_length (0), m_nextHeader (0), m_data (0) { } Ipv6ExtensionHeader::~Ipv6ExtensionHeader () { } void Ipv6ExtensionHeader::SetNextHeader (uint8_t nextHeader) { m_nextHeader = nextHeader; } uint8_t Ipv6ExtensionHeader::GetNextHeader () const { return m_nextHeader; } void Ipv6ExtensionHeader::SetLength (uint16_t length) { NS_ASSERT_MSG (!(length & 0x7), "Invalid Ipv6ExtensionHeader Length, must be a multiple of 8 bytes."); NS_ASSERT_MSG (length > 0, "Invalid Ipv6ExtensionHeader Length, must be greater than 0."); NS_ASSERT_MSG (length < 2048, "Invalid Ipv6ExtensionHeader Length, must be a lower than 2048."); m_length = (length >> 3) - 1; } uint16_t Ipv6ExtensionHeader::GetLength () const { return (m_length + 1) << 3; } void Ipv6ExtensionHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )"; } uint32_t Ipv6ExtensionHeader::GetSerializedSize () const { return 2; } void Ipv6ExtensionHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (m_nextHeader); i.WriteU8 (m_length); i.Write (m_data.PeekData (), m_data.GetSize ()); } uint32_t Ipv6ExtensionHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; m_nextHeader = i.ReadU8 (); m_length = i.ReadU8 (); uint32_t dataLength = GetLength () - 2; uint8_t* data = new uint8_t[dataLength]; i.Read (data, dataLength); if (dataLength > m_data.GetSize ()) { m_data.AddAtEnd (dataLength - m_data.GetSize ()); } else { m_data.RemoveAtEnd (m_data.GetSize () - dataLength); } i = m_data.Begin (); i.Write (data, dataLength); delete[] data; return GetSerializedSize (); } OptionField::OptionField (uint32_t optionsOffset) : m_optionData (0), m_optionsOffset (optionsOffset) { } OptionField::~OptionField () { } uint32_t OptionField::GetSerializedSize () const { return m_optionData.GetSize () + CalculatePad (Ipv6OptionHeader::Alignment{ 8,0}); } void OptionField::Serialize (Buffer::Iterator start) const { start.Write (m_optionData.Begin (), m_optionData.End ()); uint32_t fill = CalculatePad (Ipv6OptionHeader::Alignment{8,0}); NS_LOG_LOGIC ("fill with " << fill << " bytes padding"); switch (fill) { case 0: return; case 1: Ipv6OptionPad1Header ().Serialize (start); return; default: Ipv6OptionPadnHeader (fill).Serialize (start); return; } } uint32_t OptionField::Deserialize (Buffer::Iterator start, uint32_t length) { uint8_t* buf = new uint8_t[length]; start.Read (buf, length); m_optionData = Buffer (); m_optionData.AddAtEnd (length); m_optionData.Begin ().Write (buf, length); delete[] buf; return length; } void OptionField::AddOption (Ipv6OptionHeader const& option) { NS_LOG_FUNCTION_NOARGS (); uint32_t pad = CalculatePad (option.GetAlignment ()); NS_LOG_LOGIC ("need " << pad << " bytes padding"); switch (pad) { case 0: break; //no padding needed case 1: AddOption (Ipv6OptionPad1Header ()); break; default: AddOption (Ipv6OptionPadnHeader (pad)); break; } m_optionData.AddAtEnd (option.GetSerializedSize ()); Buffer::Iterator it = m_optionData.End (); it.Prev (option.GetSerializedSize ()); option.Serialize (it); } uint32_t OptionField::CalculatePad (Ipv6OptionHeader::Alignment alignment) const { return (alignment.offset - (m_optionData.GetSize () + m_optionsOffset)) % alignment.factor; } uint32_t OptionField::GetOptionsOffset () { return m_optionsOffset; } Buffer OptionField::GetOptionBuffer () { return m_optionData; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHopByHopHeader); TypeId Ipv6ExtensionHopByHopHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionHopByHopHeader") .AddConstructor<Ipv6ExtensionHopByHopHeader> () .SetParent<Ipv6ExtensionHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionHopByHopHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionHopByHopHeader::Ipv6ExtensionHopByHopHeader () : OptionField (2) { } Ipv6ExtensionHopByHopHeader::~Ipv6ExtensionHopByHopHeader () { } void Ipv6ExtensionHopByHopHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )"; } uint32_t Ipv6ExtensionHopByHopHeader::GetSerializedSize () const { return 2 + OptionField::GetSerializedSize (); } void Ipv6ExtensionHopByHopHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetSerializedSize () >> 3) - 1); OptionField::Serialize (i); } uint32_t Ipv6ExtensionHopByHopHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); m_length = i.ReadU8 (); OptionField::Deserialize (i, GetLength () - 2); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionDestinationHeader); TypeId Ipv6ExtensionDestinationHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionDestinationHeader") .AddConstructor<Ipv6ExtensionDestinationHeader> () .SetParent<Ipv6ExtensionHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionDestinationHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionDestinationHeader::Ipv6ExtensionDestinationHeader () : OptionField (2) { } Ipv6ExtensionDestinationHeader::~Ipv6ExtensionDestinationHeader () { } void Ipv6ExtensionDestinationHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )"; } uint32_t Ipv6ExtensionDestinationHeader::GetSerializedSize () const { return 2 + OptionField::GetSerializedSize (); } void Ipv6ExtensionDestinationHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 ((GetSerializedSize () >> 3) - 1); OptionField::Serialize (i); } uint32_t Ipv6ExtensionDestinationHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); m_length = i.ReadU8 (); OptionField::Deserialize (i, GetLength () - 2); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionFragmentHeader); TypeId Ipv6ExtensionFragmentHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionFragmentHeader") .AddConstructor<Ipv6ExtensionFragmentHeader> () .SetParent<Ipv6ExtensionHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionFragmentHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionFragmentHeader::Ipv6ExtensionFragmentHeader () : m_offset (0), m_identification (0) { m_length = 0; } Ipv6ExtensionFragmentHeader::~Ipv6ExtensionFragmentHeader () { } void Ipv6ExtensionFragmentHeader::SetOffset (uint16_t offset) { // Clear the offset, and save the MF bit m_offset &= 1; m_offset |= offset & (~7); } uint16_t Ipv6ExtensionFragmentHeader::GetOffset () const { return m_offset & (~1); } void Ipv6ExtensionFragmentHeader::SetMoreFragment (bool moreFragment) { m_offset = moreFragment ? m_offset | 1 : m_offset & (~1); } bool Ipv6ExtensionFragmentHeader::GetMoreFragment () const { return m_offset & 1; } void Ipv6ExtensionFragmentHeader::SetIdentification (uint32_t identification) { m_identification = identification; } uint32_t Ipv6ExtensionFragmentHeader::GetIdentification () const { return m_identification; } void Ipv6ExtensionFragmentHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " offset = " << (uint32_t)GetOffset () << " MF = " << (uint32_t)GetMoreFragment () << " identification = " << (uint32_t)m_identification << " )"; } uint32_t Ipv6ExtensionFragmentHeader::GetSerializedSize () const { return 8; } void Ipv6ExtensionFragmentHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); // Fragment header does not carry an extension length i.WriteU8 (0); i.WriteHtonU16 (m_offset); i.WriteHtonU32 (m_identification); } uint32_t Ipv6ExtensionFragmentHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); // Fragment header does not carry an extension length i.ReadU8 (); m_offset = i.ReadNtohU16 (); m_identification = i.ReadNtohU32 (); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionRoutingHeader); TypeId Ipv6ExtensionRoutingHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionRoutingHeader") .AddConstructor<Ipv6ExtensionRoutingHeader> () .SetParent<Ipv6ExtensionHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionRoutingHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionRoutingHeader::Ipv6ExtensionRoutingHeader () : m_typeRouting (0), m_segmentsLeft (0) { } Ipv6ExtensionRoutingHeader::~Ipv6ExtensionRoutingHeader () { } void Ipv6ExtensionRoutingHeader::SetTypeRouting (uint8_t typeRouting) { m_typeRouting = typeRouting; } uint8_t Ipv6ExtensionRoutingHeader::GetTypeRouting () const { return m_typeRouting; } void Ipv6ExtensionRoutingHeader::SetSegmentsLeft (uint8_t segmentsLeft) { m_segmentsLeft = segmentsLeft; } uint8_t Ipv6ExtensionRoutingHeader::GetSegmentsLeft () const { return m_segmentsLeft; } void Ipv6ExtensionRoutingHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " typeRouting = " << (uint32_t)m_typeRouting << " segmentsLeft = " << (uint32_t)m_segmentsLeft << " )"; } uint32_t Ipv6ExtensionRoutingHeader::GetSerializedSize () const { return 4; } void Ipv6ExtensionRoutingHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; i.WriteU8 (GetNextHeader ()); i.WriteU8 (m_length); i.WriteU8 (m_typeRouting); i.WriteU8 (m_segmentsLeft); } uint32_t Ipv6ExtensionRoutingHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; SetNextHeader (i.ReadU8 ()); m_length = i.ReadU8 (); m_typeRouting = i.ReadU8 (); m_segmentsLeft = i.ReadU8 (); return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionLooseRoutingHeader); TypeId Ipv6ExtensionLooseRoutingHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionLooseRoutingHeader") .AddConstructor<Ipv6ExtensionLooseRoutingHeader> () .SetParent<Ipv6ExtensionRoutingHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionLooseRoutingHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionLooseRoutingHeader::Ipv6ExtensionLooseRoutingHeader () : m_routersAddress (0) { } Ipv6ExtensionLooseRoutingHeader::~Ipv6ExtensionLooseRoutingHeader () { } void Ipv6ExtensionLooseRoutingHeader::SetNumberAddress (uint8_t n) { m_routersAddress.clear (); m_routersAddress.assign (n, Ipv6Address ("")); } void Ipv6ExtensionLooseRoutingHeader::SetRoutersAddress (std::vector<Ipv6Address> routersAddress) { m_routersAddress = routersAddress; } std::vector<Ipv6Address> Ipv6ExtensionLooseRoutingHeader::GetRoutersAddress () const { return m_routersAddress; } void Ipv6ExtensionLooseRoutingHeader::SetRouterAddress (uint8_t index, Ipv6Address addr) { m_routersAddress.at (index) = addr; } Ipv6Address Ipv6ExtensionLooseRoutingHeader::GetRouterAddress (uint8_t index) const { return m_routersAddress.at (index); } void Ipv6ExtensionLooseRoutingHeader::Print (std::ostream &os) const { os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " typeRouting = " << (uint32_t)GetTypeRouting () << " segmentsLeft = " << (uint32_t)GetSegmentsLeft () << " "; for (std::vector<Ipv6Address>::const_iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++) { os << *it << " "; } os << " )"; } uint32_t Ipv6ExtensionLooseRoutingHeader::GetSerializedSize () const { return 8 + m_routersAddress.size () * 16; } void Ipv6ExtensionLooseRoutingHeader::Serialize (Buffer::Iterator start) const { Buffer::Iterator i = start; uint8_t buff[16]; uint8_t addressNum = m_routersAddress.size (); i.WriteU8 (GetNextHeader ()); i.WriteU8 (addressNum*2); i.WriteU8 (GetTypeRouting ()); i.WriteU8 (GetSegmentsLeft ()); i.WriteU32 (0); for (VectorIpv6Address_t::const_iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++) { it->Serialize (buff); i.Write (buff, 16); } } uint32_t Ipv6ExtensionLooseRoutingHeader::Deserialize (Buffer::Iterator start) { Buffer::Iterator i = start; uint8_t buff[16]; SetNextHeader (i.ReadU8 ()); m_length = i.ReadU8 (); SetTypeRouting (i.ReadU8 ()); SetSegmentsLeft (i.ReadU8 ()); i.ReadU32 (); uint8_t addressNum = m_length / 2; SetNumberAddress (addressNum); for (uint8_t index = 0; index < addressNum; index++) { i.Read (buff, 16); SetRouterAddress (index, Ipv6Address (buff)); } return GetSerializedSize (); } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionESPHeader); TypeId Ipv6ExtensionESPHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionESPHeader") .AddConstructor<Ipv6ExtensionESPHeader> () .SetParent<Ipv6ExtensionHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionESPHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionESPHeader::Ipv6ExtensionESPHeader () { } Ipv6ExtensionESPHeader::~Ipv6ExtensionESPHeader () { } void Ipv6ExtensionESPHeader::Print (std::ostream &os) const { /** \todo */ } uint32_t Ipv6ExtensionESPHeader::GetSerializedSize () const { /** \todo */ return 0; } void Ipv6ExtensionESPHeader::Serialize (Buffer::Iterator start) const { /** \todo */ } uint32_t Ipv6ExtensionESPHeader::Deserialize (Buffer::Iterator start) { /** \todo */ return 0; } NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionAHHeader); TypeId Ipv6ExtensionAHHeader::GetTypeId () { static TypeId tid = TypeId ("ns3::Ipv6ExtensionAHHeader") .AddConstructor<Ipv6ExtensionAHHeader> () .SetParent<Ipv6ExtensionHeader> () .SetGroupName ("Internet") ; return tid; } TypeId Ipv6ExtensionAHHeader::GetInstanceTypeId () const { return GetTypeId (); } Ipv6ExtensionAHHeader::Ipv6ExtensionAHHeader () { } Ipv6ExtensionAHHeader::~Ipv6ExtensionAHHeader () { } void Ipv6ExtensionAHHeader::Print (std::ostream &os) const { /** \todo */ } uint32_t Ipv6ExtensionAHHeader::GetSerializedSize () const { /** \todo */ return 0; } void Ipv6ExtensionAHHeader::Serialize (Buffer::Iterator start) const { /** \todo */ } uint32_t Ipv6ExtensionAHHeader::Deserialize (Buffer::Iterator start) { /** \todo */ return 0; } } /* namespace ns3 */
[ "gabrielcarvfer@gmail.com" ]
gabrielcarvfer@gmail.com
1e18ea02b94018727ffb28db53673df54e2c7999
c0d3e574b1f50522e0e8bfc8680f7a0817e4d2bc
/headers/Sound.hpp
8bf9edee3f55fb3d8cc65e635d1e9276cdb56fd4
[]
no_license
rgsax/MyAllegro
8ac3f1810cc20220457abcb57d90a384072e747e
64a50f9edac7097016edbf7325cff526d572ea64
refs/heads/master
2021-09-24T09:09:04.784709
2018-10-06T08:23:13
2018-10-06T08:23:13
113,880,223
0
0
null
null
null
null
UTF-8
C++
false
false
661
hpp
#ifndef SOUND_H #define SOUND_H #include <allegro5/allegro_audio.h> #include <allegro5/allegro_acodec.h> /* * Fa parte di un insieme di classi per gestire le primitive fornite * dalla libreria di Allegro. */ enum Mode{ ONCE = 0, LOOP, BIDIR }; class Sound{ public: Sound(const char*, Mode = ONCE); ~Sound(); ALLEGRO_SAMPLE* getContent(); void setVolume(float); float getVolume(); void setSpeed(float); float getSpeed(); void play(); void stop(); protected: ALLEGRO_SAMPLE *sample; ALLEGRO_SAMPLE_ID *id; ALLEGRO_PLAYMODE playmode; float volume; float speed; static bool primaIstanza; static unsigned istanze; }; #endif
[ "riccardog.sax@gmail.com" ]
riccardog.sax@gmail.com
9c6be09d156633527a623e6ce9863eac10fcd15c
230fb8845f39bef0f30f5d3541eff5dc0641de14
/Connect3/Export/windows/obj/include/haxe/ui/util/ImageLoader.h
d9e271cab5c41ede19b957213cd55ec2a16cd544
[]
no_license
vhlk/AlgoritmoMinMax
76abd62a6e2859ed229e5831264b6d8af27e318d
40eded4948794ca48d50d16d2133a9ab21207768
refs/heads/main
2023-06-30T15:16:17.492478
2021-08-02T13:29:32
2021-08-02T13:29:32
390,493,745
1
0
null
null
null
null
UTF-8
C++
false
true
2,099
h
// Generated by Haxe 4.2.0 #ifndef INCLUDED_haxe_ui_util_ImageLoader #define INCLUDED_haxe_ui_util_ImageLoader #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS3(haxe,ui,util,ImageLoader) HX_DECLARE_CLASS3(haxe,ui,util,VariantType) namespace haxe{ namespace ui{ namespace util{ class HXCPP_CLASS_ATTRIBUTES ImageLoader_obj : public ::hx::Object { public: typedef ::hx::Object super; typedef ImageLoader_obj OBJ_; ImageLoader_obj(); public: enum { _hx_ClassId = 0x6efa3c32 }; void __construct( ::haxe::ui::util::VariantType resource); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="haxe.ui.util.ImageLoader") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"haxe.ui.util.ImageLoader"); } static ::hx::ObjectPtr< ImageLoader_obj > __new( ::haxe::ui::util::VariantType resource); static ::hx::ObjectPtr< ImageLoader_obj > __alloc(::hx::Ctx *_hx_ctx, ::haxe::ui::util::VariantType resource); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~ImageLoader_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); ::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("ImageLoader",ae,e9,e1,84); } ::haxe::ui::util::VariantType _resource; void load( ::Dynamic callback); ::Dynamic load_dyn(); void loadFromHttp(::String url, ::Dynamic callback); ::Dynamic loadFromHttp_dyn(); void loadFromFile(::String filename, ::Dynamic callback); ::Dynamic loadFromFile_dyn(); }; } // end namespace haxe } // end namespace ui } // end namespace util #endif /* INCLUDED_haxe_ui_util_ImageLoader */
[ "vhlk@cin.ufpe.br" ]
vhlk@cin.ufpe.br
ffde3fc77d1ff03c44b007316d02054bf7af4574
59abf9cf4595cc3d2663fcb38bacd328ab6618af
/MCD/Render/Sphere.cpp
573d1d78a03432f9ea4f44d404e07a5e03316a5f
[]
no_license
DrDrake/mcore3d
2ce53148ae3b9c07a3d48b15b3f1a0eab7846de6
0bab2c59650a815d6a5b581a2c2551d0659c51c3
refs/heads/master
2021-01-10T17:08:00.014942
2011-03-18T09:16:28
2011-03-18T09:16:28
54,134,775
0
0
null
null
null
null
UTF-8
C++
false
false
2,152
cpp
#include "Pch.h" #include "Sphere.h" #include "MeshBuilder.h" #include "../Core/Math/Vec2.h" #include "../Core/Math/Mat33.h" #include "../Core/Math/BasicFunction.h" using namespace MCD; SphereBuilder::SphereBuilder(float radius, uint16_t segmentCount) { // const float width = radius; // const float height = radius; const uint16_t widthSegmentCount = segmentCount; const uint16_t heightSegmentCount = segmentCount; // Many code are borrowed from PlanMeshBuilder posId = declareAttribute(VertexFormat::get("position"), 1); normalId = declareAttribute(VertexFormat::get("normal"), 1); uvId = declareAttribute(VertexFormat::get("uv0"), 1); const uint16_t vxCount = widthSegmentCount + 1; // Number of vertex along x direction const uint16_t vzCount = heightSegmentCount + 1; // Number of vertex along z direction const uint16_t vertexCount = vxCount * vzCount; // Number of vertex for the whole plane const uint16_t triCount = 2 * widthSegmentCount * heightSegmentCount; MCD_VERIFY(reserveBuffers(vertexCount, triCount * 3)); // Create vertices for(uint16_t x = 0; x < vxCount; ++x) { for(uint16_t z = 0; z < vzCount; ++z) { // Calculate the 2 angles by mapping [0 - segment count] to [0 to 2PI] const float ax = 2 * Mathf::cPi() * float(x) / widthSegmentCount; const float az = 2 * Mathf::cPi() * float(z) / heightSegmentCount; Vec3f normal( cosf(ax) * cosf(az), sinf(az), sinf(ax) * cosf(az) /* Vec3f normal( cosf(ax) * sinf(az), sinf(ax) * sinf(az), cosf(az)*/ ); Vec3f pos = normal * radius; const Vec2f uv(float(x) / (vxCount-1), float(z) / (vzCount-1)); MCD_VERIFY(vertexAttribute(posId, &pos)); MCD_VERIFY(vertexAttribute(normalId, &normal)); MCD_VERIFY(vertexAttribute(uvId, &uv)); addVertex(); } } // Create index for(uint16_t z = 0; z < heightSegmentCount; ++z) { uint16_t indexedVertexCount = (z * vxCount); for(uint16_t x = indexedVertexCount; x < indexedVertexCount + widthSegmentCount; ++x) { MCD_VERIFY(addQuad( x, x + vxCount, x + vxCount + 1, x + 1 )); } } MCD_ASSERT(indexCount() / 3 == triCount); }
[ "mtlung@080b3119-2d51-0410-af92-4d39592ae298" ]
mtlung@080b3119-2d51-0410-af92-4d39592ae298
939baed83a4293545d2fe409918ae71dce0200a1
76511344cc27c1898d0fe8449c5073e41984922d
/Peggle Game/GameSceneManager.h
4566c6f124c589b2497bd1659040d072f0a51c55
[]
no_license
jonasrabello/Peggle-Game
2f07ff4800b58c2a993cce7e2f6c5e3cb287e8f9
a389c320cac317ca9da90845ad4580260308ef33
refs/heads/master
2020-05-31T10:16:43.356761
2019-06-04T16:09:25
2019-06-04T16:09:25
190,236,141
0
0
null
null
null
null
UTF-8
C++
false
false
457
h
#pragma once #include <iostream> #include <stdio.h> #include "Window.h" #include "Timer.h" #include "Scene.h" #include "Game.h" #include <SDL.h> class GameSceneManager { private: bool isRuning; Window* window; Timer* timer; Game* game; public: GameSceneManager(); ~GameSceneManager(); bool OnCreate(const char *title_, int width_, int height_, float xUnit, float yUnit); void OnDestroy(); void Run(); };
[ "noreply@github.com" ]
jonasrabello.noreply@github.com
a4a8b5bcff2521ae0c5672516027a24ac2b6d80e
1820c20fe574e95d2e98b5b51784f67119777fa3
/25.11.2017/Tribonacci.cpp
c76086783c3eb5e91f8c102ec0862d553e71ccac
[]
no_license
p4panash/Computer-Science-Problems
6ba1c8cb8224c2dbc984eb0c19da085f0faa8bdf
68e7c3a032ba7a9ed36c955c6fb2eff96e2eb4e2
refs/heads/master
2020-04-05T04:30:11.139949
2019-07-14T18:43:33
2019-07-14T18:43:33
156,554,088
0
0
null
null
null
null
UTF-8
C++
false
false
2,092
cpp
#include <iostream> using namespace std; void Read(int data[], int &lenght) { lenght = 0; int number; cin >> number; while (number != 0) { data[lenght] = number; lenght++; cin >> number; } } bool IsTribonacci(int number) { int a = 0; int b = 1; int c = 1; while (c < number) { int aux = c; c = a + b + c; a = b; b = aux; } if (c == number) return true; return false; } bool SubListIsTribonacci(int data[], int startPos, int endPos) { int a = 1; int b = 1; int c = 2; if (data[startPos] == 1 && data[startPos + 1] == 1) { startPos+=2; } else if (data[startPos] == 1) { startPos++; } else { while (c < data[startPos]) { int aux = c; c = a + b + c; a = b; b = aux; } } for (int i = startPos; i < endPos; i++) { if (c != data[i]) { return false; } else { int aux = c; c = a + b + c; a = b; b = aux; } } return true; } void GetMaximalSubList(int data[], int lenght, int &startPos, int &endPos) { int max = 0; for (int i = 0; i < lenght; i++) { if (IsTribonacci(data[i])) { for (int j = i; j < lenght; j++) { if (SubListIsTribonacci(data, i, j)) { if ((j - i) + 1 > max) { startPos = i; endPos = j; max = (j - i) + 1; } } } } } } void PrintResult(int data[], int startPos, int endPos) { for (int i = startPos; i < endPos; i++) cout << data[i] << " "; cout << endl; } int main() { int const MAX_SIZE = 1005; int data[MAX_SIZE]; int lenght = 0; Read(data, lenght); int startPos = -1, endPos = -1; //cout << SubListIsTribonacci(data, 6, 16); GetMaximalSubList(data, lenght, startPos, endPos); PrintResult(data, startPos, endPos); }
[ "muntean.catalin.avram@gmail.com" ]
muntean.catalin.avram@gmail.com
f9efc53c4899e6291f777d0a9852898c363158a9
26ad4cc35496d364b31396e43a863aee08ef2636
/SDK/SoT_Proposal_Merchant_Rank10Reward_001_functions.cpp
3a51705f9b54c1c4a430c8a9c3dbd28d5301ca38
[]
no_license
cw100/SoT-SDK
ddb9b19ce6ae623299b2b02dee51c29581537ba1
3e6f12384c8e21ed83ef56f00030ca0506d297fb
refs/heads/master
2020-05-05T12:09:55.938323
2019-03-20T14:11:57
2019-03-20T14:11:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
// Sea of Thieves (1.4) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_Proposal_Merchant_Rank10Reward_001_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de