text
stringlengths
8
6.88M
#include <cstdio> using namespace std; long long a,b; double c; int main() { scanf("%lld %lld",&a,&b); scanf("%lf",&c); printf("%lld %.2lf %lld\n",a,c,b); }
# include <iostream> struct persona { char nombre [ 20 ]; int edad; } persona1, persona2; int main ( int argc, char ** argv) { cout<<" dame el nombre de la persona:" <<endl; cin.getline(persona2.nombre , 20 , ' / n ' ); cout<<" dame la edad de la persona: "<<endl; cin>>persona2. Edad ; cout<<" el nombre es: "<<persona2.nombre<<endl; cout<<" la edad es; "<<persona2.edad<<endl; system("pause"); return 0 ; }
// Fill out your copyright notice in the Description page of Project Settings. #include "SPowerUpActor.h" // Sets default values ASPowerUpActor::ASPowerUpActor() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; PowerUpInterval = 0.0f; TotalTicks = 0; } // Called when the game starts or when spawned void ASPowerUpActor::BeginPlay() { Super::BeginPlay(); } //every tick once powerup has been activated void ASPowerUpActor::OnTickPowerUp() { TicksDone++; OnPowerUpTicked(); if (TicksDone >= TotalTicks) { OnExpired(); // Delete timer GetWorldTimerManager().ClearTimer(TimerHandlePowerUpTick); } } void ASPowerUpActor::ActivatePowerUp() { OnActivated(); if (PowerUpInterval > 0.0f) { GetWorldTimerManager().SetTimer(TimerHandlePowerUpTick, this, &ASPowerUpActor::OnTickPowerUp, PowerUpInterval, true); } else { OnTickPowerUp(); } } // Called every frame void ASPowerUpActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "OnlineSessionSettings.h" #include "COOP_GameMode.generated.h" //enum class EWaveState:uint8; // //DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnActorKilled, AActor*, VictimActor, AActor*, KillerActor, AController*, KillerController); UCLASS() class COOPGAME_API ACOOP_GameMode : public AGameModeBase { GENERATED_BODY() //protected: // // UFUNCTION(BlueprintImplementableEvent, Category = "COOP Game Mode") // void SpawnNewBot(); // // //Spawning bots // FTimerHandle TimerHandle_BotSpawner; // // FTimerHandle TimerHandle_NextWave; // // UPROPERTY() // int32 NrOfBotsToSpawn; // UPROPERTY() // int32 WaveCount = 0; // // UPROPERTY(EditDefaultsOnly, Category = "COOP Game Mode") // float TimerBetweenWaves; // UPROPERTY(EditDefaultsOnly, Category = "COOP Game Mode") // int32 NrBotsMultiplier = 5; // // UFUNCTION() // void StartWave(); // // UFUNCTION() // void SpawnBotTimerElapsed(); // // //Stop spawning bots // UFUNCTION() // void EndWave(); // // //Set Timer for next wave // UFUNCTION() // void PrepareNextWave(); // // UFUNCTION() // void GameOver(); // // void SetWaveState(EWaveState NewState); // // void RespawnDeadPlayers(); // // EWaveState CurrentWaveState; // //public: // // ACOOP_GameMode(); // // virtual void StartPlay() override; // // virtual void Tick(float DeltaSeconds) override; // // UPROPERTY(EditDefaultsOnly, Category="COOP Game Mode") // bool bIsLobby = true; // // UPROPERTY(BlueprintAssignable, Category = "COOP Game Mode") // FOnActorKilled OnActorKilled; // // UFUNCTION() // void CheckWaveState(); // // UFUNCTION() // void CheckAnyPlayerAlive(); // // virtual void PostLogin(APlayerController* NewPlayer) override; // // virtual void Logout(AController* Exiting) override; // // // UPROPERTY(EditDefaultsOnly, Category = "COOP GameMode") // bool bIsLANMatch = true; // UPROPERTY(EditDefaultsOnly, Category = "COOP GameMode") // int32 MaxPlayers = 4; // UPROPERTY(EditDefaultsOnly, Category = "COOP GameMode") // FString LevelName = "Blockout_P"; // //private: // // UPROPERTY() // TArray<AController*> AllPlayers; // // UPROPERTY() // int32 PlayersCount; // // UFUNCTION(BlueprintCallable, Category = "COOP GameMode") // int32 CountInGamePlayers(); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2000-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Yngve Pettersen */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #include "modules/libssl/sslbase.h" #include "modules/hardcore/mh/mh.h" #include "modules/libssl/options/sslopt.h" #include "modules/libssl/protocol/op_ssl.h" #include "modules/libssl/keyex/sslkeyex.h" #include "modules/prefs/prefsmanager/prefsmanager.h" #include "modules/hardcore/mem/mem_man.h" //#include "modules/libssl/ui/sslcctx.h" #include "modules/url/url_sn.h" #include "modules/libssl/debug/tstdump2.h" #define COMM_CONNECTION_FAILURE 0x02 #ifdef _DEBUG #ifdef YNP_WORK //#define _DEBUGSSL_HANDHASH #define _DEBUG_ERR #endif #endif //extern MessHandler *mess; //SSL_SessionStateRecordHead SSL::sessioncache; #ifdef HC_CAP_ERRENUM_AS_STRINGENUM #define SSL_ERRSTR(p,x) Str::##p##_##x #else #define SSL_ERRSTR(p,x) x #endif const SSL_statesdescription_record handlerecordstates[] = { {SSL_PREHANDSHAKE, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_PREHANDSHAKE }, {SSL_PREHANDSHAKE, SSL_Handshake, SSL_HANDLE_HANDSHAKE, SSL_PREHANDSHAKE }, {SSL_PREHANDSHAKE, SSL_Application, SSL_HANDLE_APPLICATION2, SSL_PREHANDSHAKE }, {SSL_WAITING_FOR_SESSION,SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_PREHANDSHAKE }, {SSL_WAITING_FOR_SESSION,SSL_Handshake, SSL_HANDLE_HANDSHAKE, SSL_PREHANDSHAKE }, {SSL_SENT_CLIENT_HELLO, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_SENT_CLIENT_HELLO }, {SSL_SENT_CLIENT_HELLO, SSL_Handshake, SSL_HANDLE_HANDSHAKE, SSL_SENT_CLIENT_HELLO }, {SSL_SENT_CLIENT_HELLO, SSL_Application, SSL_HANDLE_APPLICATION2, SSL_SENT_CLIENT_HELLO }, {SSL_NEGOTIATING, SSL_ChangeCipherSpec, SSL_CHANGE_CIPHER, SSL_NEGOTIATING }, {SSL_NEGOTIATING, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_NEGOTIATING }, {SSL_NEGOTIATING, SSL_Handshake, SSL_HANDLE_HANDSHAKE, SSL_NEGOTIATING }, {SSL_NEGOTIATING, SSL_Application, SSL_HANDLE_APPLICATION2, SSL_NEGOTIATING }, {SSL_CONNECTED, SSL_ChangeCipherSpec, SSL_ERROR_UNEXPECTED_MESSAGE, SSL_CLOSE_CONNECTION }, {SSL_CONNECTED, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_CONNECTED }, {SSL_CONNECTED, SSL_Handshake, SSL_HANDLE_HANDSHAKE, SSL_PREHANDSHAKE }, {SSL_CONNECTED, SSL_Application, SSL_HANDLE_APPLICATION, SSL_CONNECTED }, {SSL_CLOSE_CONNECTION, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_CLOSE_CONNECTION }, {SSL_CLOSE_CONNECTION, SSL_Handshake, SSL_IGNORE, SSL_CLOSE_CONNECTION }, {SSL_CLOSE_CONNECTION, SSL_Application, SSL_HANDLE_APPLICATION, SSL_CLOSE_CONNECTION }, {SSL_CLOSE_CONNECTION2, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_CLOSE_CONNECTION2 }, {SSL_CLOSE_CONNECTION2, SSL_Handshake, SSL_IGNORE, SSL_CLOSE_CONNECTION2 }, {SSL_CLOSE_CONNECTION2, SSL_Application, SSL_HANDLE_APPLICATION, SSL_CLOSE_CONNECTION2 }, {SSL_NOT_CONNECTED, SSL_Application, SSL_HANDLE_APPLICATION, SSL_NOT_CONNECTED }, // HACK to avoid latemessages {SSL_NOT_CONNECTED, SSL_AlertMessage, SSL_HANDLE_ALERT, SSL_NOT_CONNECTED }, // HACK to avoid latemessages {SSL_NOSTATE, SSL_Application, SSL_ERROR_UNEXPECTED_MESSAGE, SSL_CLOSE_CONNECTION } // Failsafe }; const SSL_statesdescription_alert handlealertstates[] = { {SSL_SENT_CLIENT_HELLO, SSL_Close_Notify, SSL_HANDLE_AS_HANDSHAKE_FAIL, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Close_Notify, SSL_HANDLE_AS_HANDSHAKE_FAIL, SSL_CLOSE_CONNECTION }, {SSL_ANYSTATE, SSL_Close_Notify, SSL_HANDLE_CLOSE, SSL_CLOSE_CONNECTION }, {SSL_ANYSTATE, SSL_InternalError, SSL_HANDLE_INTERNAL_ERRROR, SSL_CLOSE_CONNECTION }, {SSL_ANYSTATE, SSL_Illegal_Parameter, SSL_HANDLE_ILLEGAL_PARAMETER, SSL_CLOSE_CONNECTION }, {SSL_ANYSTATE, SSL_Unexpected_Message, SSL_ERROR_UNEXPECTED_MESSAGE, SSL_CLOSE_CONNECTION }, {SSL_ANYSTATE, SSL_Decompression_Failure, SSL_HANDLE_DECOMPRESSION_FAIL,SSL_CLOSE_CONNECTION }, {SSL_ANYSTATE, SSL_Bad_Record_MAC, SSL_HANDLE_BAD_MAC, SSL_CLOSE_CONNECTION }, {SSL_PREHANDSHAKE, SSL_Handshake_Failure, SSL_HANDLE_HANDSHAKE_FAIL, SSL_CLOSE_CONNECTION }, {SSL_SENT_CLIENT_HELLO, SSL_Handshake_Failure, SSL_HANDLE_HANDSHAKE_FAIL, SSL_CLOSE_CONNECTION }, {SSL_SENT_CLIENT_HELLO, SSL_Unrecognized_Name, SSL_IGNORE, SSL_SENT_CLIENT_HELLO}, {SSL_NEGOTIATING, SSL_Bad_Certificate, SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Unsupported_Certificate,SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Certificate_Revoked, SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Unsupported_Certificate,SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Certificate_Expired, SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Certificate_Not_Yet_Valid, SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Certificate_Unknown, SSL_HANDLE_BAD_CERT, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_Handshake_Failure, SSL_HANDLE_HANDSHAKE_FAIL, SSL_CLOSE_CONNECTION }, {SSL_NEGOTIATING, SSL_No_Certificate, SSL_HANDLE_NO_CLIENT_CERT, SSL_NEGOTIATING }, {SSL_NOSTATE, SSL_No_Description, SSL_ERROR_UNEXPECTED_ERROR, SSL_CLOSE_CONNECTION } // Failsafe }; void SSL::SessionNegotiatedContinueHandshake(BOOL success) { if(current_state == SSL_WAITING_FOR_SESSION) { if (success) current_state = Handle_Start_Handshake(loading_handshake, SSL_SENT_CLIENT_HELLO, FALSE); else current_state = Close_Connection(SSL_NOT_CONNECTED); } } BOOL SSL::SafeToDelete() const { return ( !Handling_callback && SSL_Record_Layer::SafeToDelete() ); } void SSL::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { Handling_callback++; switch(msg) { case MSG_COMM_LOADING_FINISHED: case MSG_COMM_LOADING_FAILED: if(is_connected) { //if(!flags.received_closure_alert && !server_info->IsIIS4Server() ) // IIS 4 servers apparently does not tell when they close the connection { /* if(connstate!= NULL && connstate->session != NULL) connstate->session->is_resumable = FALSE;*/ if(pending_connstate != NULL && pending_connstate->session != NULL && (connstate == NULL || pending_connstate->session != connstate->session)) pending_connstate->session->is_resumable = FALSE; } Stop(); } if((!is_connected || (current_state != SSL_RETRY && current_state != SSL_CLOSE_CONNECTION && current_state != SSL_CLOSE_CONNECTION2)) && !trying_to_reconnect) { mh->PostMessage(msg, Id(), par2); } else if(current_state == SSL_RECONNECTING) { mh->PostMessage(msg, Id(), par2); } break; case MSG_SSL_WAITING_SESSION_TMEOUT : if(current_state == SSL_WAITING_FOR_SESSION) current_state = Handle_Start_Handshake(loading_handshake,SSL_SENT_CLIENT_HELLO, TRUE); break; case MSG_SSL_WAIT_EMPTY_BUFFER : if(current_state == SSL_CLOSE_CONNECTION || current_state == SSL_CLOSE_CONNECTION2 || current_state == SSL_NOT_CONNECTED) { if((par2&0xff)==1) { current_state = Close_Connection(current_state); } else { Perform_ProcessReceivedData(); BOOL fin = EmptyBuffers(TRUE); mh->PostDelayedMessage(MSG_SSL_WAIT_EMPTY_BUFFER,Id(),fin, (fin ? 512 : 128)); #ifdef TST_DUMP if(fin) PrintfTofile("winsck.txt", "SSL::HandleMessage sending last MSG_SSL_WAIT_EMPTY_BUFFER signal for id : %d\n", Id()); #endif } } break; case MSG_DO_TLS_FALLBACK: if(mh && trying_to_reconnect && current_state != SSL_RECONNECTING) { if(par2 || ProtocolComm::Closed()) { BOOL allowed = FALSE; SetProgressInformation(RESTART_LOADING,0, &allowed); if(allowed) { ResetConnection(); Stop(); SSL_Record_Layer::Stop(); FlushBuffers(TRUE); ResetError(); // Forget any errors during the shutdown phase current_state = SSL_RECONNECTING; already_tried_to_reconnect = TRUE; Load(); } else { mh->PostMessage(MSG_SSL_RESTART_CONNECTION, Id(), 0); mh->PostMessage(MSG_COMM_LOADING_FAILED, Id(), Str::S_MSG_SSL_NonFatalError_Retry); } } else { mh->PostMessage(MSG_DO_TLS_FALLBACK,Id(),0); break; } } if(mh) mh->UnsetCallBack(this, MSG_DO_TLS_FALLBACK, Id()); break; case MSG_SSL_COMPLETEDVERIFICATION: if(pending_connstate->key_exchange && (MH_PARAM_1)pending_connstate->key_exchange->Id() == par1){ g_main_message_handler->UnsetCallBack(this, MSG_SSL_COMPLETEDVERIFICATION); SSL_STATE next_state = Process_KeyExchangeActions(SSL_NEGOTIATING, pending_connstate->key_exchange->GetPostVerifyAction()); if(!(next_state > SSL_Wait_ForAction_Start && next_state < SSL_Wait_ForAction_End)) next_state = ProgressHandshake(next_state); current_state = next_state; } break; default: SSL_Record_Layer::HandleCallback(msg,par1,par2); } if(ErrorRaisedFlag) current_state = Handle_Raised_Error(current_state); Handling_callback--; } void SSL::Handle_Record(SSL_ContentType recordtype) { const SSL_statesdescription_record *staterecord; SSL_STATE nextstate,tempstate; if(current_state == SSL_NOT_CONNECTED) return; if(::Valid(recordtype) && !flags.closing_connection) { if(current_state == SSL_SENT_CLIENT_HELLO) { switch(pending_connstate->server_info->GetFeatureStatus()) { case TLS_Test_1_2_Extensions: //case TLS_Test_1_1_Extensions: case TLS_Test_1_0: case TLS_Test_1_0_Extensions: case TLS_Test_SSLv3_only: // Disable featuretest timeout g_main_message_handler->UnsetCallBack(this, MSG_COMM_LOADING_FAILED, (MH_PARAM_1) this); g_main_message_handler->RemoveDelayedMessage(MSG_COMM_LOADING_FAILED, (MH_PARAM_1) this, SSL_ERRSTR(SI,ERR_HTTP_TIMEOUT)); break; } } staterecord = handlerecordstates; while ((tempstate =staterecord->present_state) != SSL_NOSTATE) { if((tempstate == SSL_ANYSTATE || tempstate == current_state) && staterecord->recordtype == recordtype) break; staterecord++; } nextstate = staterecord->default_nextstate; switch (staterecord->action) { case SSL_IGNORE : nextstate = current_state; break; case SSL_CHANGE_CIPHER : nextstate = Handle_Change_Cipher(nextstate); break; case SSL_HANDLE_ALERT : nextstate = Handle_Received_Alert(nextstate); break; case SSL_HANDLE_V2_RECORD : case SSL_HANDLE_HANDSHAKE : StartingToSetUpRecord(TRUE); WriteRecordsToBuffer(TRUE); // Make sure we collect the records without sending on network. This is to make the tcp packaging more efficient. nextstate = Handle_HandShake(nextstate); StartingToSetUpRecord(FALSE); WriteRecordsToBuffer(FALSE); // Allow sending on network StartEncrypt(); // Make sure every record in the record list is encrypted and sent Flush(); // flush in case anything is left in the buffer break; case SSL_HANDLE_APPLICATION : case SSL_HANDLE_APPLICATION2 : if(flags.application_records_permitted) nextstate = Handle_Application(nextstate); else RaiseAlert(SSL_Fatal,SSL_Unexpected_Message); break; case SSL_ERROR_UNEXPECTED_MESSAGE : if(!flags.closed_with_error) RaiseAlert(SSL_Fatal,SSL_Unexpected_Message); break; default: break; } current_state = nextstate; if(ErrorRaisedFlag) { current_state = Handle_Raised_Error(nextstate); } } if(!(current_state >= SSL_Wait_ForAction_Start && current_state <= SSL_Wait_ForAction_End)) RemoveRecord(); } void SSL::SetProgressInformation(ProgressState progress_level, unsigned long progress_info1, const void *progress_info2) { if (progress_level == UPLOADING_PROGRESS) { /** * Since SSL layer adds protocol overhead, the progress info from socket will * will report more bytes than the application layer sent to SSL layer. * * Until all data has been sent, the report to application layer will be * approximately correct. * * When last byte has been reported from comm, the rest of application * data will be reported. Thus, the application layer will receive * correct amount of progress, at the moment all data has been sent. */ double persent_progress = progress_info1 / buffered_amount_raw_data; OP_ASSERT(persent_progress <= 1); buffered_amount_raw_data -= progress_info1; unsigned long amount_application_data_to_report; if (buffered_amount_raw_data > 0) { // We report the approximate amount of data sent. amount_application_data_to_report = static_cast<unsigned long>(op_floor(persent_progress * buffered_amount_application_data)); buffered_amount_application_data -= amount_application_data_to_report; } else { // All data has been sent, we report the rest of the application data. amount_application_data_to_report = buffered_amount_application_data; buffered_amount_application_data = 0; } if (amount_application_data_to_report) SComm::SetProgressInformation(progress_level, amount_application_data_to_report, progress_info2); } else SComm::SetProgressInformation(progress_level, progress_info1, progress_info2); } CommState SSL::ConnectionEstablished() { buffered_amount_application_data = 0; buffered_amount_raw_data = 0; SSL_SessionStateRecordList *tempsession; if(server_info == (SSL_Port_Sessions *) NULL) { // Will not block current_state = Handle_Local_Error(SSL_Internal, SSL_Allocation_Failure,current_state); return COMM_REQUEST_FAILED; } SetDoNotReconnect(TRUE); flags.delayed_client_certificate_request = FALSE; current_state = SSL_PREHANDSHAKE; RETURN_VALUE_IF_ERROR(loading_handshake.SetMessage(SSL_NONE),COMM_REQUEST_FAILED); loading_handshake.ResetRecord(); //SSL_CipherSpec *read, *write; trying_to_reconnect = FALSE; if(g_securityManager == NULL || !g_securityManager->SecurityEnabled) { // Will not block current_state = Handle_Local_Error(SSL_Internal, SSL_Security_Disabled, current_state); return COMM_REQUEST_FAILED; } if(!(g_securityManager->Enable_SSL_V3_0 || g_securityManager->Enable_TLS_V1_0 || g_securityManager->Enable_TLS_V1_1 || g_securityManager->Enable_TLS_V1_2 )|| g_securityManager->SystemCipherSuite.Count() == 0 ) { // Will not block current_state = Handle_Local_Error(SSL_Internal, SSL_No_Cipher_Selected, current_state); return COMM_REQUEST_FAILED; } OP_DELETE(connstate->version_specific); connstate->version_specific = NULL; OP_DELETE(pending_connstate->version_specific); pending_connstate->version_specific = NULL; g_main_message_handler->UnsetCallBack(this, MSG_SSL_COMPLETEDVERIFICATION); OP_DELETE(pending_connstate->key_exchange); pending_connstate->key_exchange = NULL; connstate->last_client_finished.Resize(0); connstate->last_server_finished.Resize(0); pending_connstate->last_client_finished.Resize(0); pending_connstate->last_server_finished.Resize(0); flags.closing_connection = flags.closed_with_error = flags.received_closure_alert = FALSE; if(!mh->HasCallBack(this, MSG_SSL_WAITING_SESSION_TMEOUT, Id())) RAISE_AND_RETURN_VALUE_IF_ERROR(mh->SetCallBack(this, MSG_SSL_WAITING_SESSION_TMEOUT, Id()),COMM_REQUEST_FAILED); if(!mh->HasCallBack(this, MSG_SSL_WAIT_EMPTY_BUFFER, Id())) RAISE_AND_RETURN_VALUE_IF_ERROR(mh->SetCallBack(this, MSG_SSL_WAIT_EMPTY_BUFFER, Id()),COMM_REQUEST_FAILED); pending_connstate->RemoveSession(); /*read = */ pending_connstate->Prepare_cipher_spec(FALSE); /*write = */ pending_connstate->Prepare_cipher_spec(TRUE); if(connstate->write.cipher != NULL) connstate->write.cipher->Sequence_number = 0; if(connstate->read.cipher != NULL) connstate->read.cipher->Sequence_number = 0; if(ErrorRaisedFlag) { // Will not block current_state = Handle_Raised_Error(current_state); return COMM_REQUEST_FAILED; } pending_connstate->sigalg = SSL_Anonymous_sign; pending_connstate->handshake_queue.Clear(); security_profile = g_securityManager->FindSecurityProfile(SSL_Record_Layer::servername,SSL_Record_Layer::port); if(security_profile == NULL) return COMM_REQUEST_FAILED; tempsession = pending_connstate->FindSessionRecord(); if (tempsession != NULL) { tempsession->connections++; flags.allow_auto_disable_tls = !server_info->TLSDeactivated(); } SetProgressInformation(GET_APPLICATIONINFO, 0, &pending_connstate->ActiveURL); SetProgressInformation(GET_ORIGINATING_WINDOW, 0, &pending_connstate->window); #ifdef URL_DISABLE_INTERACTION pending_connstate->user_interaction_blocked = GetUserInteractionBlocked(); #endif if (!Init() || SSL_Record_Layer::ConnectionEstablished() == COMM_CONNECTION_FAILURE) return COMM_REQUEST_FAILED; current_state = Handle_Start_Handshake(loading_handshake, SSL_SENT_CLIENT_HELLO, FALSE); if(ErrorRaisedFlag) { current_state = Handle_Raised_Error(current_state); } if(current_state == SSL_NOT_CONNECTED) return COMM_REQUEST_FAILED; #ifdef SSL_ENABLE_URL_HANDSHAKE_STATUS if(pending_connstate->ActiveURL.IsValid()) pending_connstate->ActiveURL.SetAttribute(g_KSSLHandshakeSent,TRUE); #endif return COMM_LOADING; } SSL_STATE SSL::Handle_Change_Cipher(SSL_STATE pref_next_state_arg) { OP_MEMORY_VAR SSL_STATE pref_next_state = pref_next_state_arg; SSL_Alert msg; DataStream *source = GetRecord(); OP_ASSERT(source); while (source->MoreData()) { OP_MEMORY_VAR OP_STATUS op_err = OpRecStatus::OK; SSL_TRAP_AND_RAISE_ERROR_THIS(op_err = loading_chcipherspec.ReadRecordFromStreamL(source)); if(ErrorRaisedFlag) return SSL_PRE_CLOSE_CONNECTION; if(op_err != OpRecStatus::FINISHED) continue; if(!loading_chcipherspec.Finished()) continue; if(!loading_chcipherspec.Valid(&msg)) { msg.SetLevel(SSL_Fatal); RaiseAlert(msg); return SSL_PRE_CLOSE_CONNECTION; } if(!pending_connstate->version_specific->ExpectingCipherChange()) { RaiseAlert(SSL_Fatal,SSL_Unexpected_Message); return SSL_PRE_CLOSE_CONNECTION; } Do_ChangeCipher(FALSE); if(source->MoreData()) { RaiseAlert(SSL_Fatal,SSL_Unexpected_Message); return SSL_PRE_CLOSE_CONNECTION; } pending_connstate->version_specific->SessionUpdate(Session_Changed_Server_Cipher); pending_connstate->version_specific->GetFinishedMessage(/*!pending_connstate->client*/ FALSE, pending_connstate->prepared_server_finished); } return pref_next_state; } // Eddy/2002/Apr: would someone who knows what this is for please document it ... SSL_STATE SSL::Handle_Received_Alert(SSL_STATE pref_next_state) { OP_MEMORY_VAR SSL_STATE nextstate = SSL_ANYSTATE; // ... and give this a suitable initialiser. BOOL cont = FALSE; DataStream *source = GetRecord(); OP_ASSERT(source); while (source->MoreData()) { SSL_TRAP_AND_RAISE_ERROR_THIS(loading_alert.ReadRecordFromStreamL(source)); if(ErrorRaisedFlag) return SSL_PRE_CLOSE_CONNECTION; if(!loading_alert.Finished()) continue; if(flags.closing_connection) continue; SSL_AlertDescription alerttype = loading_alert.GetDescription(); #ifdef _DEBUG_ERR PrintfTofile("ssltrans.txt", " ID %d : Remote Error %d (%x)\r\n\r\n", Id(), ((int) alerttype)&0xff, ((int) alerttype)); #endif const SSL_statesdescription_alert *staterecord = handlealertstates; SSL_STATE tempstate; while ((tempstate =staterecord->present_state) != SSL_NOSTATE) { if((tempstate == SSL_ANYSTATE || tempstate == current_state) && staterecord->alerttype == alerttype) break; staterecord++; } if(staterecord->action == SSL_HANDLE_AS_HANDSHAKE_FAIL) loading_alert.Set(SSL_Fatal, SSL_Handshake_Failure); nextstate =staterecord->fatal_nextstate; BOOL display_warning = TRUE; if(!flags.closed_with_error && loading_alert.GetLevel() == SSL_Fatal && current_state != SSL_CONNECTED && connstate && pending_connstate && pending_connstate->sent_version.Compare(3,0) > 0 ) { // Try to restart using SSL v3.0 instead cont = FALSE; if(connstate->session != NULL) connstate->session->is_resumable = FALSE; if(pending_connstate->session != NULL) pending_connstate->session->is_resumable = FALSE; trying_to_reconnect = TRUE; display_warning = FALSE; switch(server_info->GetFeatureStatus()) { case TLS_Test_SSLv3_only: if (g_securityManager->Enable_SSL_V3_0) { server_info->SetTLSDeactivated(TRUE); server_info->SetFeatureStatus(TLS_SSL_v3_only); server_info->SetPreviousSuccesfullFeatureTest(TLS_SSL_v3_only); server_info->SetValidTo(g_timecache->CurrentTime() + SSL_VERSION_TEST_VALID_TIME ); trying_to_reconnect = TRUE; } break; case TLS_Test_1_0: server_info->SetValidTo(g_timecache->CurrentTime() + SSL_VERSION_TEST_VALID_TIME ); if(connstate->version < SSL_ProtocolVersion(3,1)) { if (g_securityManager->Enable_SSL_V3_0) { server_info->SetTLSDeactivated(TRUE); server_info->SetFeatureStatus(TLS_SSL_v3_only); trying_to_reconnect = TRUE; } break; } server_info->SetFeatureStatus(TLS_1_0_only); trying_to_reconnect = FALSE; break; #ifdef _SUPPORT_TLS_1_2 case TLS_Test_1_2_Extensions: server_info->SetFeatureStatus((current_state != SSL_SENT_CLIENT_HELLO && current_state != SSL_NEGOTIATING) || connstate->version.Compare(3,3) >= 0 ? TLS_1_2_and_Extensions : TLS_Test_1_0_Extensions); server_info->SetValidTo(g_timecache->CurrentTime() + SSL_VERSION_TEST_VALID_TIME ); break; #endif /* case TLS_Test_1_1_Extensions: server_info->SetFeatureStatus(g_securityManager->Enable_TLS_V1_0 && (current_state == SSL_SENT_CLIENT_HELLO || current_state == SSL_NEGOTIATING) && connstate->version.Compare(3,2) < 0 ? TLS_Test_1_0_Extensions : TLS_1_1_and_Extensions); server_info->SetValidTo(g_timecache->CurrentTime() + SSL_VERSION_TEST_VALID_TIME ); break; */ case TLS_Test_1_0_Extensions: server_info->SetFeatureStatus(TLS_Test_1_0); break; default: if(connstate->version > SSL_ProtocolVersion(3,0)) { trying_to_reconnect = FALSE; } break; } if(!trying_to_reconnect) { display_warning = TRUE; } } if(display_warning && (current_state != SSL_CONNECTED || ProtocolComm::IsActiveConnection())) { if(loading_alert.GetLevel() == SSL_Warning) ApplicationHandleWarning(loading_alert,TRUE,cont); else { ApplicationHandleFatal(loading_alert,TRUE); cont = FALSE; } } if(!cont ) { if(!trying_to_reconnect && alerttype != SSL_Close_Notify) { flags.closed_with_error = (flags.internal_error_message_set ? 2 : 1); if(connstate!= NULL && connstate->session != NULL) connstate->session->is_resumable = FALSE; if(pending_connstate != NULL && pending_connstate->session != NULL) pending_connstate->session->is_resumable = FALSE; } nextstate = Close_Connection(nextstate); } if(alerttype == SSL_Close_Notify) { flags.received_closure_alert = TRUE; SetProcessingInputData(FALSE); } current_state = nextstate; } return nextstate; } SSL_STATE SSL::Handle_Application(SSL_STATE pref_next_state) { MoveRecordToApplicationBuffer(); return pref_next_state; } BOOL SSL::AcceptNewVersion(const SSL_ProtocolVersion &nver) { if(current_state !=SSL_SENT_CLIENT_HELLO) return FALSE; connstate->SetVersion(nver); if(ErrorRaisedFlag) { current_state = SSL_PRE_CLOSE_CONNECTION;; return FALSE; } return TRUE; } void SSL::UpdateSecurityInformation() { /* This code does a final check and signals the security level to window layer. * * Note that the session security is modifed in many different places. This should be * re-factored and moved into one place, preferable into a security class. * * From 2011 the key size requirement for EV is raised to 2048. The key size == 2048 for * EV is correctly checked in VerifyCertificate_CheckKeySize and session->extended_validation * is false if it does't pass. * * Todo: check the 1024 bit size. It's unclear if that check is the same as in VerifyCertificate_CheckKeySize * or if it is another check. Anyhow, the 2048 check happens, and it will not be EV as long as that check fails. */ if(connstate && connstate->session) { SSL_SessionStateRecordList *session = connstate->session; #ifdef SSL_CHECK_EXT_VALIDATION_POLICY if(session->extended_validation && session->security_rating == SECURITY_STATE_FULL && session->lowest_keyex.RSA_keysize >= 1024) { session->security_rating = SECURITY_STATE_FULL_EXTENDED; } #endif SetProgressInformation(SET_SECURITYLEVEL, ((int) (session->security_rating & SECURITY_STATE_MASK)) | (((int) session->low_security_reason) << SECURITY_STATE_MASK_BITS), session->security_cipher_string.CStr()); #ifdef _SECURE_INFO_SUPPORT SetProgressInformation(SET_SESSION_INFORMATION,0, session->session_information); #endif if((connstate->session->low_security_reason & ( SECURITY_LOW_REASON_UNABLE_TO_CRL_VALIDATE | SECURITY_LOW_REASON_UNABLE_TO_OCSP_VALIDATE | SECURITY_LOW_REASON_OCSP_FAILED | SECURITY_LOW_REASON_CRL_FAILED)) != 0) { // If we were unable to check revocation, do not resume this session, next connection will do full handshake // Also, don't allow more than one (HTTP) request on this connection. connstate->session->is_resumable = FALSE; SetProgressInformation(STOP_FURTHER_REQUESTS, STOP_REQUESTS_TC_NOT_FIRST_REQUEST); } } } int SSL::GetSecurityLevel() const { return (connstate != NULL && connstate->session != NULL && connstate->session->cipherdescription != NULL ? (int) connstate->session->security_rating : SECURITY_STATE_UNKNOWN); } /* const uni_char *SSL::GetSecurityText() const { return (connstate != NULL && connstate->session != NULL && connstate->session->cipherdescription != NULL ? connstate->session->security_cipher_string.CStr() : NULL); } */ void SSL::ResetConnection() { } OP_STATUS SSL::SetCallbacks(MessageObject* master, MessageObject* parent) { static const OpMessage messages[] = { MSG_COMM_LOADING_FINISHED, MSG_COMM_LOADING_FAILED }; RETURN_IF_ERROR(mh->SetCallBackList((parent ? parent : master), Id(), messages, ARRAY_SIZE(messages))); return ProtocolComm::SetCallbacks(master, this); } BOOL SSL::HasId(unsigned int sid) { return (Id() == sid || (!trying_to_reconnect && ProtocolComm::HasId(sid))); } #endif
#include "GetRoomInfoProcess.h" #include "ProtocolServerId.h" #include "Room.h" #include "Logger.h" #include "ProcessManager.h" int GetRoomInfoProcess::doRequest(CDLSocketHandler *clientHandler, InputPacket *inputPacket, Context *pt) { short cmd = inputPacket->GetCmdType(); short subcmd = inputPacket->GetSubCmd(); short PageNo = inputPacket->ReadShort(); short PageNum = inputPacket->ReadShort(); _LOG_DEBUG_("==>[GetRoomInfoProcess] [0x%04x] \n", cmd); _LOG_DEBUG_("SubCmd=[%d] \n", subcmd); _LOG_DEBUG_("[DATA Parse] PageNo=[%d] \n", PageNo); _LOG_DEBUG_("[DATA Parse] PageNum=[%d] \n", PageNum); return doGetRoomInfo(clientHandler, PageNo, PageNum); } int GetRoomInfoProcess::doGetRoomInfo(CDLSocketHandler *clientHandler, int PageNo, int PageNum) { Room *room = Room::getInstance(); int total = room->getMaxTableCount(); //�ܼ�¼�� Table *tables = room->getAllTables(); int start = (PageNo - 1) * PageNum; //��ʼλ�� int end = start + PageNum; //����λ�� if (start < 0) start = 0; if (end < 0) end = 0; else if (end > total) end = total; int count = end - start; OutputPacket response; response.Begin(ADMIN_MSG_ROOMINFO); response.WriteShort(0); response.WriteString(""); response.WriteShort(total); response.WriteShort(count); for (int i = start; i < end; ++i) { Table *table = &tables[i]; response.WriteShort(table->id); response.WriteShort(table->m_nStatus); if (table->player_array[0]) { response.WriteInt(table->player_array[0]->id); response.WriteString(table->player_array[0]->name); response.WriteShort(table->player_array[0]->m_nStatus); } else { response.WriteInt(0); response.WriteString(""); response.WriteShort(0); } if (table->player_array[1]) { response.WriteInt(table->player_array[1]->id); response.WriteString(table->player_array[1]->name); response.WriteShort(table->player_array[1]->m_nStatus); } else { response.WriteInt(0); response.WriteString(""); response.WriteShort(0); } if (table->player_array[2]) { response.WriteInt(table->player_array[2]->id); response.WriteString(table->player_array[2]->name); response.WriteShort(table->player_array[2]->m_nStatus); } else { response.WriteInt(0); response.WriteString(""); response.WriteShort(0); } if (table->player_array[3]) { response.WriteInt(table->player_array[3]->id); response.WriteString(table->player_array[3]->name); response.WriteShort(table->player_array[3]->m_nStatus); } else { response.WriteInt(0); response.WriteString(""); response.WriteShort(0); } } response.End(); _LOG_DEBUG_("==>[Send response length = [%d] \n", response.packet_size()); this->send(clientHandler, &response); return 0; } REGISTER_PROCESS(ADMIN_MSG_ROOMINFO,GetRoomInfoProcess)
#pragma once #include "Map.h" namespace Game { extern std::vector<Object*> objects; extern BioMap::map_t map; void main(); typedef enum { OBJT_DUDE, OBJT_CITY, OBJT_STRUCTURE, } ObjectType; struct Object { uint8_t x; uint8_t y; virtual bool autoUpdate(); virtual bool move(); virtual bool destroy(); virtual bool update(); }; };
#include <iostream> #include <iomanip> using namespace std; const int dir_i[4] = {0, 0, 1, -1}; const int dir_j[4] = {1, -1, 0, 0}; double dir_rate[4]; int n; bool visited[31][31]; double ans = 0; void dfs(int index, int i, int j, double rate){ if(index == n){ ans += rate; return; } for (int dir = 0; dir < 4; dir++){ int ni = i + dir_i[dir]; int nj = j + dir_j[dir]; if(!visited[ni][nj]){ visited[ni][nj] = true; dfs(index + 1, ni, nj, rate * dir_rate[dir]); visited[ni][nj] = false; } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> dir_rate[0] >> dir_rate[1] >> dir_rate[2] >> dir_rate[3]; dir_rate[0] *= 0.01; dir_rate[1] *= 0.01; dir_rate[2] *= 0.01; dir_rate[3] *= 0.01; /* 일단 모든 가능성 탐색. */ visited[15][15] = true; dfs(0, 15, 15, 1.0); cout << fixed; cout << setprecision(10) << ans << '\n'; return 0; }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef XPATH_SUPPORT #include "modules/xpath/src/xpfunction.h" #include "modules/xpath/src/xpcontext.h" #include "modules/xpath/src/xpvalue.h" #include "modules/xpath/src/xpnode.h" #include "modules/xpath/src/xputils.h" #include "modules/xpath/src/xpapiimpl.h" #include "modules/xpath/src/xpliteralexpr.h" #include "modules/xpath/src/xpparser.h" #include "modules/xpath/src/xpunknown.h" #include "modules/util/str.h" #include "modules/xmlutils/xmlutils.h" /* static */ XPath_Expression * XPath_FunctionCallExpression::MakeL (XPath_Parser *parser, const XMLExpandedName &name, XPath_Expression **arguments, unsigned arguments_count) { XPath_Expression *expression = 0; XPath_Producer *producer = 0; unsigned type; BOOL is_count, is_true, is_position; #define XPATH_WRONG_NUMBER_OF_ARGUMENTS() XPATH_COMPILATION_ERROR_NAME ("wrong number of arguments to function ''", parser->GetCurrentLocation ()) if ((type = XP_VALUE_STRING, name == XMLExpandedName (UNI_L ("string"))) || (type = XP_VALUE_NUMBER, name == XMLExpandedName (UNI_L ("number")))) { XPath_Expression *argument = 0; if (arguments_count == 1) { if (arguments[0]->GetResultType () == type) expression = arguments[0]; else argument = arguments[0]; arguments[0] = 0; } else if (arguments_count > 1) XPATH_COMPILATION_ERROR_NAME ("too many arguments to function: ''", parser->GetCurrentLocation ()); if (!expression) if (type == XP_VALUE_STRING) expression = XPath_StringExpression::MakeL (parser, argument); else expression = XPath_NumberExpression::MakeL (parser, argument); } else if (name == XMLExpandedName (UNI_L ("boolean"))) if (arguments_count == 1) expression = XPath_BooleanExpression::MakeL (parser, arguments[0]); else XPATH_WRONG_NUMBER_OF_ARGUMENTS (); else if ((is_position = name == XMLExpandedName (UNI_L ("position"))) || name == XMLExpandedName (UNI_L ("last"))) if (arguments_count != 0) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); else expression = OP_NEW_L (XPath_ContextFunctionCall, (parser, is_position ? XPath_ContextFunctionCall::TYPE_position : XPath_ContextFunctionCall::TYPE_last)); else if (name == XMLExpandedName (UNI_L ("id"))) producer = XPath_IdProducer::MakeL (parser, arguments, arguments_count); else if ((is_count = name == XMLExpandedName (UNI_L ("count"))) || name == XMLExpandedName (UNI_L ("sum"))) expression = XPath_CumulativeNodeSetFunctionCall::MakeL (parser, is_count ? XPath_CumulativeNodeSetFunctionCall::TYPE_count : XPath_CumulativeNodeSetFunctionCall::TYPE_sum, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("local-name"))) expression = XPath_SingleNodeFunctionCall::MakeL (parser, XPath_SingleNodeFunctionCall::TYPE_localname, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("namespace-uri"))) expression = XPath_SingleNodeFunctionCall::MakeL (parser, XPath_SingleNodeFunctionCall::TYPE_namespaceuri, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("name"))) expression = XPath_SingleNodeFunctionCall::MakeL (parser, XPath_SingleNodeFunctionCall::TYPE_name, arguments, arguments_count); else if ((is_true = name == XMLExpandedName (UNI_L ("true"))) || name == XMLExpandedName (UNI_L ("false"))) if (arguments_count == 0) expression = XPath_LiteralExpression::MakeL (parser, is_true); else XPATH_WRONG_NUMBER_OF_ARGUMENTS (); else if (name == XMLExpandedName (UNI_L ("not"))) expression = XPath_NotFunctionCall::MakeL (parser, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("lang"))) if (arguments_count == 1) expression = XPath_LangFunctionCall::MakeL (parser, arguments); else XPATH_WRONG_NUMBER_OF_ARGUMENTS (); else if (name == XMLExpandedName (UNI_L ("floor"))) expression = XPath_NumberFunctionCall::MakeL (parser, XPath_NumberFunctionCall::TYPE_floor, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("ceiling"))) expression = XPath_NumberFunctionCall::MakeL (parser, XPath_NumberFunctionCall::TYPE_ceiling, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("round"))) expression = XPath_NumberFunctionCall::MakeL (parser, XPath_NumberFunctionCall::TYPE_round, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("concat"))) expression = XPath_ConcatFunctionCall::MakeL (parser, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("starts-with"))) expression = XPath_StartsWithOrContainsFunctionCall::MakeL (parser, XPath_StartsWithOrContainsFunctionCall::TYPE_starts_with, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("contains"))) expression = XPath_StartsWithOrContainsFunctionCall::MakeL (parser, XPath_StartsWithOrContainsFunctionCall::TYPE_contains, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("substring-before"))) expression = XPath_SubstringBeforeOrAfterFunctionCall::MakeL (parser, XPath_SubstringBeforeOrAfterFunctionCall::TYPE_substring_before, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("substring-after"))) expression = XPath_SubstringBeforeOrAfterFunctionCall::MakeL (parser, XPath_SubstringBeforeOrAfterFunctionCall::TYPE_substring_after, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("substring"))) expression = XPath_SubstringFunctionCall::MakeL (parser, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("string-length"))) expression = XPath_StringLengthFunctionCall::MakeL (parser, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("normalize-space"))) expression = XPath_NormalizeSpaceFunctionCall::MakeL (parser, arguments, arguments_count); else if (name == XMLExpandedName (UNI_L ("translate"))) expression = XPath_TranslateFunctionCall::MakeL (parser, arguments, arguments_count); if (producer) { expression = OP_NEW (XPath_ProducerExpression, (parser, producer)); if (!expression) { OP_DELETE (producer); LEAVE (OpStatus::ERR_NO_MEMORY); } } #ifdef XPATH_EXTENSION_SUPPORT if (!expression) if (XPathExtensions *extensions = parser->GetExtensions ()) { XPathFunction *function; OP_STATUS status = extensions->GetFunction (function, name); if (OpStatus::IsSuccess (status)) expression = XPath_Unknown::MakeL (parser, function, arguments, arguments_count); } #endif // XPATH_EXTENSION_SUPPORT if (!expression) XPATH_COMPILATION_ERROR_NAME ("unknown function called: ''", parser->GetCurrentLocation ()); return expression; } XPath_IdProducer::XPath_IdProducer (XPath_Parser *parser, XPath_Producer *producer, XPath_StringExpression *stringexpression) : producer (producer), stringexpression (stringexpression), #ifdef XPATH_EXTENSION_SUPPORT unknown (0), #endif // XPATH_EXTENSION_SUPPORT state_index (parser->GetStateIndex ()), offset_index (parser->GetStateIndex ()), value_index (parser->GetValueIndex ()), node_index (parser->GetNodeIndex ()), localci_index (parser->GetContextInformationIndex ()) { ci_index = localci_index; } #ifdef XPATH_EXTENSION_SUPPORT XPath_IdProducer::XPath_IdProducer (XPath_Parser *parser, XPath_Unknown *unknown) : producer (0), stringexpression (0), #ifdef XPATH_EXTENSION_SUPPORT unknown (unknown), unknownstate_index (parser->GetStateIndex ()), #endif // XPATH_EXTENSION_SUPPORT state_index (parser->GetStateIndex ()), offset_index (parser->GetStateIndex ()), value_index (parser->GetValueIndex ()), node_index (parser->GetNodeIndex ()) { } #endif // XPATH_EXTENSION_SUPPORT /* static */ XPath_Producer * XPath_IdProducer::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); #ifdef XPATH_EXTENSION_SUPPORT XPath_Unknown *unknown; if (arguments[0]->HasFlag (XPath_Expression::FLAG_UNKNOWN)) { unknown = static_cast<XPath_Unknown *> (arguments[0]); XPath_Producer *idproducer = OP_NEW_L (XPath_IdProducer, (parser, unknown)); arguments[0] = 0; return idproducer; } else { #endif // XPATH_EXTENSION_SUPPORT XPath_Producer *producer; XPath_StringExpression *stringexpression; producer = XPath_Expression::GetProducerL (parser, arguments[0]); if (producer) stringexpression = 0; else stringexpression = XPath_StringExpression::MakeL (parser, arguments[0]); arguments[0] = 0; XPath_Producer *idproducer = OP_NEW (XPath_IdProducer, (parser, producer, stringexpression)); if (!idproducer) { OP_DELETE (idproducer); OP_DELETE (stringexpression); LEAVE (OpStatus::ERR_NO_MEMORY); } return idproducer; } } /* virtual */ XPath_IdProducer::~XPath_IdProducer () { OP_DELETE (producer); OP_DELETE (stringexpression); #ifdef XPATH_EXTENSION_SUPPORT OP_DELETE (unknown); #endif // XPATH_EXTENSION_SUPPORT } /* virtual */ unsigned XPath_IdProducer::GetProducerFlags () { if (producer) return producer->GetProducerFlags () & (MASK_INHERITED & ~MASK_ORDER); #ifdef XPATH_EXTENSION_SUPPORT else if (unknown) return unknown->GetProducerFlags () & (MASK_INHERITED & ~MASK_ORDER); #endif // XPATH_EXTENSION_SUPPORT else { unsigned expression_flags = stringexpression->GetExpressionFlags (), flags = 0; if ((expression_flags & XPath_Expression::FLAG_CONTEXT_SIZE) != 0) flags = FLAG_CONTEXT_SIZE; if ((expression_flags & XPath_Expression::FLAG_CONTEXT_POSITION) != 0) flags = FLAG_CONTEXT_POSITION; return flags; } } /* virtual */ BOOL XPath_IdProducer::Reset (XPath_Context *context, BOOL local_context_only) { if (producer) producer->Reset (context, local_context_only); context->states[state_index] = 0; XPath_Value::DecRef (context, context->values[value_index]); context->values[value_index] = 0; #ifdef XPATH_EXTENSION_SUPPORT if (unknown) { unknown->Reset (context); context->states[unknownstate_index] = 0; } #endif // XPATH_EXTENSION_SUPPORT return FALSE; } /* virtual */ XPath_Node * XPath_IdProducer::GetNextNodeL (XPath_Context *context) { TempBuffer buffer; ANCHOR (TempBuffer, buffer); unsigned &state = context->states[state_index]; unsigned &offset = context->states[offset_index]; XPath_Value *&value = context->values[value_index]; XPath_Node &node = context->nodes[node_index]; XPath_Producer *use_producer = producer; const uni_char *base, *string; BOOL initial; #ifdef XPATH_EXTENSION_SUPPORT if (unknown) { XPath_ValueType unknown_type; if (context->states[unknownstate_index] < 2) { BOOL unknown_initial = context->states[unknownstate_index] == 0; context->states[unknownstate_index] = 1; unknown_type = unknown->GetActualResultTypeL (context, unknown_initial); context->states[unknownstate_index] = 2 | (unknown_type << 2); } else unknown_type = static_cast<XPath_ValueType> ((context->states[unknownstate_index] & ~3) >> 2); if (!XPath_IsPrimitive (unknown_type)) use_producer = unknown; } #endif // XPATH_EXTENSION_SUPPORT if (state < 2) { offset = 0; base = string = 0; initial = state == 0; } else { base = value->data.string; string = base + offset; initial = FALSE; } while (TRUE) { if (!string) { buffer.Clear (); if (use_producer) if (XPath_Node *node = use_producer->GetNextNodeL (context)) { node->GetStringValueL (buffer); XPath_Node::DecRef (context, node); base = string = buffer.GetStorage () ? buffer.GetStorage () : UNI_L(""); } else return 0; #ifdef XPATH_EXTENSION_SUPPORT else if (unknown) { XPath_ValueType conversion[4] = { XP_VALUE_STRING, XP_VALUE_STRING, XP_VALUE_STRING, XP_VALUE_INVALID }; XPath_Value *value = unknown->EvaluateL (context, initial, conversion); buffer.AppendL (value->data.string); base = string = buffer.GetStorage (); XPath_Value::DecRef (context, value); } #endif // XPATH_EXTENSION_SUPPORT else { state = 1; base = string = stringexpression->EvaluateToStringL (context, initial, buffer); } XPath_Value::DecRef (context, value); value = 0; state = 2; value = XPath_Value::MakeStringL (context, base); XP_SEQUENCE_POINT (context); } while (TRUE) { while (*string && XMLUtils::IsSpace (*string)) ++string; if (!*string) break; const uni_char *id = string; while (*string && !XMLUtils::IsSpace (*string)) ++string; if (XMLTreeAccessor::Node *treenode = context->node->GetTreeNodeByIdL (id, string - id)) { offset = string - base; node.Set (context->node->tree, treenode); return XPath_Node::IncRef (&node); } if (!*string) break; } if (!use_producer) return 0; string = 0; state = 1; XP_SEQUENCE_POINT (context); } } XPath_CumulativeNodeSetFunctionCall::XPath_CumulativeNodeSetFunctionCall (XPath_Parser *parser, Type type, XPath_Producer *producer) : XPath_NumberExpression (parser), type (type), producer (producer) { if (type == TYPE_count) count_index = parser->GetStateIndex (); else sum_index = parser->GetNumberIndex (); } XPath_CumulativeNodeSetFunctionCall::~XPath_CumulativeNodeSetFunctionCall () { OP_DELETE (producer); } /* static */ XPath_Expression * XPath_CumulativeNodeSetFunctionCall::MakeL (XPath_Parser *parser, Type type, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Producer *producer = XPath_Expression::GetProducerL (parser, arguments[0]); if (!producer) XPATH_COMPILATION_ERROR ("expected node-set expression", arguments[0]->location); arguments[0] = 0; producer = XPath_Producer::EnsureFlagsL (parser, producer, XPath_Producer::FLAG_NO_DUPLICATES); XPath_NumberExpression *expression = OP_NEW (XPath_CumulativeNodeSetFunctionCall, (parser, type, producer)); if (!expression) { OP_DELETE (producer); LEAVE (OpStatus::ERR_NO_MEMORY); } return expression; } /* virtual */ double XPath_CumulativeNodeSetFunctionCall::EvaluateToNumberL (XPath_Context *context, BOOL initial) { if (initial) producer->Reset (context); if (type == TYPE_count) { unsigned &count = context->states[count_index]; if (initial) count = 0; while (XPath_Node *node = producer->GetNextNodeL (context)) { ++count; XPath_Node::DecRef (context, node); } return (double) count; } else { double &sum = context->numbers[sum_index]; if (initial) sum = 0; TempBuffer *buffer = context->GetTempBuffer (); while (XPath_Node *node = producer->GetNextNodeL (context)) { buffer->Clear (); node->GetStringValueL (*buffer); sum += XPath_Value::AsNumber (buffer->GetStorage ()); XPath_Node::DecRef (context, node); } return sum; } } XPath_SingleNodeFunctionCall::XPath_SingleNodeFunctionCall (XPath_Parser *parser, Type type, XPath_Producer *argument) : XPath_StringExpression (parser), type (type), argument (argument) { } /* static */ XPath_Expression * XPath_SingleNodeFunctionCall::MakeL (XPath_Parser *parser, Type type, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 0 && arguments_count != 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); if (arguments_count == 1 && (arguments[0]->GetExpressionFlags () & XPath_Expression::FLAG_PRODUCER) == 0) XPATH_COMPILATION_ERROR ("expected node-set expression", arguments[0]->location); if (arguments_count == 1) { XPath_Producer *producer = XPath_Expression::GetProducerL (parser, arguments[0]); arguments[0] = 0; producer = XPath_Producer::EnsureFlagsL (parser, producer, XPath_Producer::FLAG_DOCUMENT_ORDER | XPath_Producer::FLAG_SINGLE_NODE); XPath_Expression *expression = OP_NEW (XPath_SingleNodeFunctionCall, (parser, type, producer)); if (!expression) { OP_DELETE (producer); LEAVE (OpStatus::ERR_NO_MEMORY); } return expression; } else return OP_NEW_L (XPath_SingleNodeFunctionCall, (parser, type, 0)); } XPath_SingleNodeFunctionCall::~XPath_SingleNodeFunctionCall () { OP_DELETE (argument); } /* virtual */ unsigned XPath_SingleNodeFunctionCall::GetExpressionFlags () { return ((argument ? argument->GetExpressionFlags () : 0) & MASK_INHERITED) | FLAG_STRING; } /* virtual */ const uni_char * XPath_SingleNodeFunctionCall::EvaluateToStringL (XPath_Context *context, BOOL initial, TempBuffer &buffer) { XPath_Node *node; if (argument) { if (initial) argument->Reset (context); node = argument->GetNextNodeL (context); } else node = XPath_Node::IncRef (context->node); if (node) { const uni_char *string; if (type == TYPE_name && (node->type == XP_NODE_ELEMENT || node->type == XP_NODE_ATTRIBUTE)) { node->GetQualifiedNameL (buffer); string = buffer.GetStorage (); } else { XMLExpandedName name; node->GetExpandedName (name); if (type == TYPE_localname || type == TYPE_name) string = name.GetLocalPart (); else string = name.GetUri (); } XPath_Node::DecRef (context, node); if (string) return string; } return UNI_L (""); } /* static */ XPath_BooleanExpression * XPath_LangFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments) { XPath_Expression *argument = arguments[0]; arguments[0] = 0; XPath_StringExpression *stringargument = XPath_StringExpression::MakeL (parser, argument); OpStackAutoPtr<XPath_Expression> stringargument_anchor (stringargument); XPath_LangFunctionCall *lang = OP_NEW_L (XPath_LangFunctionCall, (parser, stringargument)); stringargument_anchor.release (); return lang; } /* virtual */ XPath_LangFunctionCall::~XPath_LangFunctionCall () { OP_DELETE (argument); } /* virtual */ unsigned XPath_LangFunctionCall::GetExpressionFlags () { return (argument->GetExpressionFlags () & MASK_INHERITED) | FLAG_BOOLEAN; } /* virtual */ BOOL XPath_LangFunctionCall::EvaluateToBooleanL (XPath_Context *context, BOOL initial) { if (context->node->type == XP_NODE_ROOT) return FALSE; else { TempBuffer argument_buffer; ANCHOR (TempBuffer, argument_buffer); const uni_char *argument_string = argument->EvaluateToStringL (context, initial, argument_buffer); XMLTreeAccessor *tree = context->node->tree; XMLTreeAccessor::Node *treenode = context->node->treenode; XMLExpandedName lang_name (UNI_L ("http://www.w3.org/XML/1998/namespace"), UNI_L ("lang")); LEAVE_IF_ERROR (tree->SetAttributeNameFilter (lang_name)); if (!tree->FilterNode (treenode)) treenode = tree->GetParent (treenode); tree->ResetFilters (); if (treenode) { const uni_char *lang_string; BOOL id, specified; TempBuffer lang_buffer; ANCHOR (TempBuffer, lang_buffer); LEAVE_IF_ERROR (tree->GetAttribute (tree->GetAttributes (treenode, FALSE, TRUE), lang_name, lang_string, id, specified, &lang_buffer)); unsigned argument_length = uni_strlen (argument_string); return uni_strni_eq (argument_string, lang_string, argument_length) && (!lang_string[argument_length] || lang_string[argument_length] == '-'); } else return FALSE; } } XPath_NumberFunctionCall::XPath_NumberFunctionCall (XPath_Parser *parser, Type type, XPath_NumberExpression *argument) : XPath_NumberExpression (parser), type (type), argument (argument) { } /* static */ XPath_NumberExpression * XPath_NumberFunctionCall::MakeL (XPath_Parser *parser, Type type, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument0 = arguments[0]; arguments[0] = 0; XPath_NumberExpression *numberargument = XPath_NumberExpression::MakeL (parser, argument0); XPath_NumberFunctionCall *call = OP_NEW (XPath_NumberFunctionCall, (parser, type, numberargument)); if (!call) { OP_DELETE (numberargument); LEAVE (OpStatus::ERR_NO_MEMORY); } return call; } /* virtual */ XPath_NumberFunctionCall::~XPath_NumberFunctionCall () { OP_DELETE (argument); } /* virtual */ unsigned XPath_NumberFunctionCall::GetExpressionFlags () { return (argument->GetExpressionFlags () & MASK_INHERITED) | FLAG_NUMBER; } /* virtual */ double XPath_NumberFunctionCall::EvaluateToNumberL (XPath_Context *context, BOOL initial) { double argument_number = argument->EvaluateToNumberL (context, initial); if (type == TYPE_floor) return op_floor (argument_number); else if (type == TYPE_ceiling) return op_ceil (argument_number); else return XPath_Utils::Round (argument_number); } XPath_ContextFunctionCall::XPath_ContextFunctionCall (XPath_Parser *parser, Type type) : XPath_NumberExpression (parser), type (type) { } /* virtual */ unsigned XPath_ContextFunctionCall::GetExpressionFlags () { return (type == TYPE_position ? FLAG_CONTEXT_POSITION : FLAG_CONTEXT_SIZE) | FLAG_FUNCTIONCALL | FLAG_NUMBER; } /* virtual */ BOOL XPath_ContextFunctionCall::TransformL (XPath_Parser *parser, Transform transform, TransformData &data) { if (transform == TRANSFORM_XMLEXPANDEDNAME) { *data.name = type == TYPE_position ? XMLExpandedName (UNI_L ("count")) : XMLExpandedName (UNI_L ("last")); return TRUE; } return FALSE; } /* virtual */ double XPath_ContextFunctionCall::EvaluateToNumberL (XPath_Context *context, BOOL initial) { if (type == TYPE_position) return static_cast<double> (context->position); else return static_cast<double> (context->size); } XPath_ConcatFunctionCall::XPath_ConcatFunctionCall (XPath_Parser *parser) : XPath_StringExpression (parser), arguments (0), arguments_count (0), state_index (parser->GetStateIndex ()), buffer_index (parser->GetBufferIndex ()) { } /* static */ XPath_StringExpression * XPath_ConcatFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count < 2) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_ConcatFunctionCall *call = OP_NEW_L (XPath_ConcatFunctionCall, (parser)); OpStackAutoPtr<XPath_Expression> call_anchor (call); call->arguments = OP_NEWA_L (XPath_StringExpression *, arguments_count); for (unsigned index = 0; index < arguments_count; ++index) { XPath_Expression *argument = arguments[index]; arguments[index] = 0; call->arguments[index] = XPath_StringExpression::MakeL (parser, argument); ++call->arguments_count; } call_anchor.release (); return call; } /* virtual */ XPath_ConcatFunctionCall::~XPath_ConcatFunctionCall () { for (unsigned index = 0; index < arguments_count; ++index) OP_DELETE (arguments[index]); OP_DELETEA (arguments); } /* virtual */ unsigned XPath_ConcatFunctionCall::GetExpressionFlags () { unsigned flags = FLAG_STRING; for (unsigned index = 0; index < arguments_count; ++index) flags |= arguments[index]->GetExpressionFlags () & MASK_INHERITED; return flags; } /* virtual */ const uni_char * XPath_ConcatFunctionCall::EvaluateToStringL (XPath_Context *context, BOOL initial, TempBuffer &) { unsigned &state = context->states[state_index]; TempBuffer &buffer = context->buffers[buffer_index]; /* States: state & 1 == 0: evaluate argument (initial) state & 1 == 1: evaluate argument (continued) state / 2: current argument index */ if (initial) { state = 0; buffer.Clear (); } unsigned argument_index = state / 2; BOOL argument_initial = (state & 1) == 0; TempBuffer local; ANCHOR (TempBuffer, local); while (argument_index < arguments_count) { state |= 1; const uni_char *argument = arguments[argument_index]->EvaluateToStringL (context, argument_initial, local); ++state; ++argument_index; argument_initial = TRUE; buffer.AppendL (argument); local.Clear (); } const uni_char *storage = buffer.GetStorage (); if (!storage) storage = UNI_L (""); return storage; } XPath_SubstringFunctionCall::XPath_SubstringFunctionCall (XPath_Parser *parser, XPath_StringExpression *base, XPath_NumberExpression *offset, XPath_NumberExpression *length) : XPath_StringExpression (parser), base (base), offset (offset), length (length), state_index (parser->GetStateIndex ()), offset_index (parser->GetNumberIndex ()), length_index (parser->GetNumberIndex ()) { } /* static */ XPath_StringExpression * XPath_SubstringFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 2 && arguments_count != 3) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument0 = arguments[0]; arguments[0] = 0; XPath_StringExpression *base = XPath_StringExpression::MakeL (parser, argument0); OpStackAutoPtr<XPath_Expression> base_anchor (base); XPath_Expression *argument1 = arguments[1]; arguments[1] = 0; XPath_NumberExpression *offset = XPath_NumberExpression::MakeL (parser, argument1); OpStackAutoPtr<XPath_Expression> offset_anchor (offset); XPath_NumberExpression *length; if (arguments_count == 3) { XPath_Expression *argument2 = arguments[2]; arguments[2] = 0; length = XPath_NumberExpression::MakeL (parser, argument2); } else length = 0; OpStackAutoPtr<XPath_Expression> length_anchor (length); XPath_SubstringFunctionCall *call = OP_NEW_L (XPath_SubstringFunctionCall, (parser, base, offset, length)); base_anchor.release (); offset_anchor.release (); length_anchor.release (); return call; } /* virtual */ XPath_SubstringFunctionCall::~XPath_SubstringFunctionCall () { OP_DELETE (base); OP_DELETE (offset); OP_DELETE (length); } /* virtual */ unsigned XPath_SubstringFunctionCall::GetExpressionFlags () { unsigned flags = base->GetExpressionFlags () | offset->GetExpressionFlags (); if (length) flags |= length->GetExpressionFlags (); return (flags & MASK_INHERITED) | FLAG_STRING; } /* virtual */ const uni_char * XPath_SubstringFunctionCall::EvaluateToStringL (XPath_Context *context, BOOL initial, TempBuffer &buffer) { unsigned &state = context->states[state_index]; double &offset_value = context->numbers[offset_index]; double &length_value = context->numbers[length_index]; if (initial) state = 0; if (state < 2) { BOOL offset_initial = state == 0; state = 1; offset_value = offset->EvaluateToNumberL (context, offset_initial); state = 2; if (op_isnan (offset_value) || !op_isfinite (offset_value) && op_signbit (offset_value) == 0) return UNI_L (""); } if (state < 4) { if (length) { BOOL length_initial = state == 2; state = 3; length_value = length->EvaluateToNumberL (context, length_initial); if (op_isnan (length_value)) return UNI_L (""); double dend = XPath_Utils::Round (offset_value) + XPath_Utils::Round (length_value); if (op_isnan (dend) || !(1 < dend)) return UNI_L (""); } state = 4; } BOOL base_initial = state == 4; state = 5; const uni_char *base_value = base->EvaluateToStringL (context, base_initial, buffer); if (!*base_value) return base_value; else if (base_value != buffer.GetStorage ()) buffer.AppendL (base_value); double roffset; unsigned start = 0, end = 0, string_length = buffer.Length (); OP_ASSERT (!op_isnan (offset_value)); if (!op_isfinite (offset_value)) { OP_ASSERT (op_signbit (offset_value) == 1); start = 0; roffset = 0; } else { roffset = XPath_Utils::Round (offset_value); if (roffset > (double) string_length) return UNI_L (""); if (roffset < 1.) start = 0; else start = (unsigned) roffset - 1; } if (!length) end = string_length; else if (!op_isfinite (length_value)) end = string_length; else { double rlength = XPath_Utils::Round (length_value), dend = roffset + rlength - 1.; if (dend > (double) string_length) end = string_length; else if (dend < (double) start) end = start; else end = (unsigned) dend; } if (end - start == 0) return UNI_L (""); else { uni_char *result = buffer.GetStorage (); if (start > 0) op_memmove (result, result + start, (end - start) * sizeof *result); result[end - start] = 0; return result; } } XPath_TranslateFunctionCall::XPath_TranslateFunctionCall (XPath_Parser *parser, XPath_StringExpression *base, XPath_StringExpression *from, XPath_StringExpression *to) : XPath_StringExpression (parser), base (base), from (from), to (to), state_index (parser->GetStateIndex ()), from_buffer_index (parser->GetBufferIndex ()), to_buffer_index (parser->GetBufferIndex ()) { } /* static */ XPath_StringExpression * XPath_TranslateFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 3) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument0 = arguments[0]; arguments[0] = 0; XPath_StringExpression *base = XPath_StringExpression::MakeL (parser, argument0); OpStackAutoPtr<XPath_Expression> base_anchor (base); XPath_Expression *argument1 = arguments[1]; arguments[1] = 0; XPath_StringExpression *from = XPath_StringExpression::MakeL (parser, argument1); OpStackAutoPtr<XPath_Expression> from_anchor (from); XPath_Expression *argument2 = arguments[2]; arguments[2] = 0; XPath_StringExpression *to = XPath_StringExpression::MakeL (parser, argument2); OpStackAutoPtr<XPath_Expression> to_anchor (to); XPath_TranslateFunctionCall *call = OP_NEW_L (XPath_TranslateFunctionCall, (parser, base, from, to)); base_anchor.release (); from_anchor.release (); to_anchor.release (); return call; } /* virtual */ XPath_TranslateFunctionCall::~XPath_TranslateFunctionCall () { OP_DELETE (base); OP_DELETE (from); OP_DELETE (to); } /* virtual */ unsigned XPath_TranslateFunctionCall::GetExpressionFlags () { return ((base->GetExpressionFlags () | from->GetExpressionFlags () | to->GetExpressionFlags ()) & MASK_INHERITED) | FLAG_STRING; } /* virtual */ const uni_char * XPath_TranslateFunctionCall::EvaluateToStringL (XPath_Context *context, BOOL initial, TempBuffer &buffer) { unsigned &state = context->states[state_index]; TempBuffer &from_buffer = context->buffers[from_buffer_index]; TempBuffer &to_buffer = context->buffers[to_buffer_index]; if (initial) { state = 0; from_buffer.Clear (); to_buffer.Clear (); } if (state < 2) { BOOL from_initial = state == 0; state = 1; const uni_char *from_value = from->EvaluateToStringL (context, from_initial, from_buffer); state = 2; if (from_value != from_buffer.GetStorage ()) from_buffer.AppendL (from_value); } if (state < 4) { BOOL to_initial = state == 2; state = 3; const uni_char *to_value = to->EvaluateToStringL (context, to_initial, to_buffer); state = 4; if (to_value != to_buffer.GetStorage ()) to_buffer.AppendL (to_value); } BOOL base_initial = state == 4; state = 5; const uni_char *base_value = base->EvaluateToStringL (context, base_initial, buffer); const uni_char *from_value = from_buffer.GetStorage (); if (!from_value) return base_value; if (base_value != buffer.GetStorage ()) buffer.AppendL (base_value); uni_char *writep = buffer.GetStorage (); const uni_char *readp = writep, *to_value = to_buffer.GetStorage (); unsigned to_value_length; if (!to_value) to_value_length = 0; else to_value_length = uni_strlen (to_value); while (*readp) { const uni_char *location = uni_strchr (from_value, *readp); if (location) { unsigned index = location - from_value; if (index < to_value_length) *writep++ = to_value[index]; } else *writep++ = *readp; ++readp; } *writep = 0; return buffer.GetStorage (); } XPath_NormalizeSpaceFunctionCall::XPath_NormalizeSpaceFunctionCall (XPath_Parser *parser, XPath_StringExpression *base) : XPath_StringExpression (parser), base (base) { } /* static */ XPath_StringExpression * XPath_NormalizeSpaceFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count > 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument0; if (arguments_count == 1) { argument0 = arguments[0]; arguments[0] = 0; } else argument0 = 0; XPath_StringExpression *base = XPath_StringExpression::MakeL (parser, argument0); XPath_NormalizeSpaceFunctionCall *call = OP_NEW (XPath_NormalizeSpaceFunctionCall, (parser, base)); if (!call) { OP_DELETE (base); LEAVE (OpStatus::ERR_NO_MEMORY); } return call; } /* virtual */ XPath_NormalizeSpaceFunctionCall::~XPath_NormalizeSpaceFunctionCall () { OP_DELETE (base); } /* virtual */ unsigned XPath_NormalizeSpaceFunctionCall::GetExpressionFlags () { return (base->GetExpressionFlags () & MASK_INHERITED) | FLAG_STRING; } /* virtual */ const uni_char * XPath_NormalizeSpaceFunctionCall::EvaluateToStringL (XPath_Context *context, BOOL initial, TempBuffer &buffer) { const uni_char *value = base->EvaluateToStringL (context, initial, buffer); if (!value || !*value) return UNI_L (""); if (value != buffer.GetStorage ()) buffer.AppendL (value); uni_char *result = buffer.GetStorage (), *start = result; while (XMLUtils::IsSpace (*start)) ++start; const uni_char *readp = start; uni_char *writep = start; while (*readp) { if (!XMLUtils::IsSpace (*readp)) *writep++ = *readp++; else { *writep++ = ' '; while (XMLUtils::IsSpace (*readp)) ++readp; if (!*readp) { --writep; break; } else continue; } } if (result != start) op_memmove (result, start, (writep - start) * sizeof *result); result[writep - start] = 0; return result; } XPath_StringLengthFunctionCall::XPath_StringLengthFunctionCall (XPath_Parser *parser, XPath_StringExpression *base) : XPath_NumberExpression (parser), base (base) { } /* static */ XPath_NumberExpression * XPath_StringLengthFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count > 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument0; if (arguments_count == 1) { argument0 = arguments[0]; arguments[0] = 0; } else argument0 = 0; XPath_StringExpression *base = XPath_StringExpression::MakeL (parser, argument0); XPath_StringLengthFunctionCall *call = OP_NEW (XPath_StringLengthFunctionCall, (parser, base)); if (!call) { OP_DELETE (base); LEAVE (OpStatus::ERR_NO_MEMORY); } return call; } /* virtual */ XPath_StringLengthFunctionCall::~XPath_StringLengthFunctionCall () { OP_DELETE (base); } /* virtual */ unsigned XPath_StringLengthFunctionCall::GetExpressionFlags () { return (base->GetExpressionFlags () & MASK_INHERITED) | FLAG_NUMBER; } /* virtual */ double XPath_StringLengthFunctionCall::EvaluateToNumberL (XPath_Context *context, BOOL initial) { TempBuffer buffer; ANCHOR (TempBuffer, buffer); const uni_char *value = base->EvaluateToStringL (context, initial, buffer); return (double) uni_strlen (value); } XPath_BinaryStringFunctionCallBase::XPath_BinaryStringFunctionCallBase (XPath_Parser *parser) : argument1 (0), argument2 (0), state_index (parser->GetStateIndex ()), buffer1_index (parser->GetBufferIndex ()), buffer2_index (parser->GetBufferIndex ()) { } XPath_BinaryStringFunctionCallBase::~XPath_BinaryStringFunctionCallBase () { OP_DELETE (argument1); OP_DELETE (argument2); } void XPath_BinaryStringFunctionCallBase::SetArgumentsL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 2) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument1in = arguments[0]; arguments[0] = 0; argument1 = XPath_StringExpression::MakeL (parser, argument1in); XPath_Expression *argument2in = arguments[1]; arguments[1] = 0; argument2 = XPath_StringExpression::MakeL (parser, argument2in); } void XPath_BinaryStringFunctionCallBase::EvaluateArgumentsL (XPath_Context *context, BOOL initial, const uni_char *&value1, const uni_char *&value2) { unsigned &state = context->states[state_index]; TempBuffer &buffer1 = context->buffers[buffer1_index]; TempBuffer &buffer2 = context->buffers[buffer2_index]; if (initial) { state = 0; buffer1.Clear (); buffer2.Clear (); } if (state < 2) { BOOL initial1 = state == 0; state = 1; value1 = argument1->EvaluateToStringL (context, initial1, buffer1); if (*value1 && value1 != buffer1.GetStorage ()) buffer1.AppendL (value1); state = 2; XP_SEQUENCE_POINT (context); } value1 = buffer1.GetStorage (); if (state < 4) { BOOL initial2 = state == 2; state = 3; value2 = argument2->EvaluateToStringL (context, initial2, buffer2); if (*value2 && value2 != buffer2.GetStorage ()) buffer2.AppendL (value2); state = 4; XP_SEQUENCE_POINT (context); } value2 = buffer2.GetStorage (); if (!value1) value1 = UNI_L (""); if (!value2) value2 = UNI_L (""); } unsigned XPath_BinaryStringFunctionCallBase::GetExpressionFlags () { return (argument1->GetExpressionFlags () | argument2->GetExpressionFlags ()) & XPath_Expression::MASK_INHERITED; } XPath_StartsWithOrContainsFunctionCall::XPath_StartsWithOrContainsFunctionCall (XPath_Parser *parser, Type type) : XPath_BooleanExpression (parser), XPath_BinaryStringFunctionCallBase (parser), type (type) { } /* static */ XPath_BooleanExpression * XPath_StartsWithOrContainsFunctionCall::MakeL (XPath_Parser *parser, Type type, XPath_Expression **arguments, unsigned arguments_count) { XPath_StartsWithOrContainsFunctionCall *call = OP_NEW_L (XPath_StartsWithOrContainsFunctionCall, (parser, type)); OpStackAutoPtr<XPath_Expression> call_anchor (call); call->SetArgumentsL (parser, arguments, arguments_count); call_anchor.release (); return call; } /* virtual */ unsigned XPath_StartsWithOrContainsFunctionCall::GetExpressionFlags () { return XPath_BinaryStringFunctionCallBase::GetExpressionFlags () | FLAG_BOOLEAN; } /* virtual */ BOOL XPath_StartsWithOrContainsFunctionCall::EvaluateToBooleanL (XPath_Context *context, BOOL initial) { const uni_char *value1, *value2; EvaluateArgumentsL (context, initial, value1, value2); if (type == TYPE_starts_with) { unsigned length1 = uni_strlen (value1), length2 = uni_strlen (value2); return length1 >= length2 && op_memcmp (value1, value2, length2 * sizeof *value2) == 0; } else return uni_strstr (value1, value2) != 0; } XPath_SubstringBeforeOrAfterFunctionCall::XPath_SubstringBeforeOrAfterFunctionCall (XPath_Parser *parser, Type type) : XPath_StringExpression (parser), XPath_BinaryStringFunctionCallBase (parser), type (type) { } /* static */ XPath_StringExpression * XPath_SubstringBeforeOrAfterFunctionCall::MakeL (XPath_Parser *parser, Type type, XPath_Expression **arguments, unsigned arguments_count) { XPath_SubstringBeforeOrAfterFunctionCall *call = OP_NEW_L (XPath_SubstringBeforeOrAfterFunctionCall, (parser, type)); OpStackAutoPtr<XPath_Expression> call_anchor (call); call->SetArgumentsL (parser, arguments, arguments_count); call_anchor.release (); return call; } /* virtual */ unsigned XPath_SubstringBeforeOrAfterFunctionCall::GetExpressionFlags () { return XPath_BinaryStringFunctionCallBase::GetExpressionFlags () | FLAG_STRING; } /* virtual */ const uni_char * XPath_SubstringBeforeOrAfterFunctionCall::EvaluateToStringL (XPath_Context *context, BOOL initial, TempBuffer &buffer) { const uni_char *value1, *value2; EvaluateArgumentsL (context, initial, value1, value2); const uni_char *location = uni_strstr (value1, value2); if (location) { if (type == TYPE_substring_before) buffer.AppendL (value1, location - value1); else buffer.AppendL (location + uni_strlen (value2)); if (buffer.GetStorage ()) return buffer.GetStorage (); } return UNI_L (""); } /* static */ XPath_Expression * XPath_NotFunctionCall::MakeL (XPath_Parser *parser, XPath_Expression **arguments, unsigned arguments_count) { if (arguments_count != 1) XPATH_WRONG_NUMBER_OF_ARGUMENTS (); XPath_Expression *argument0 = arguments[0]; arguments[0] = 0; XPath_BooleanExpression *argument = XPath_BooleanExpression::MakeL (parser, argument0); OpStackAutoPtr<XPath_Expression> argument_anchor (argument); if (argument->HasFlag (FLAG_CONSTANT)) { BOOL value = !argument->EvaluateToBooleanL (0, TRUE); return XPath_LiteralExpression::MakeL (parser, value); } else { XPath_NotFunctionCall *call = OP_NEW_L (XPath_NotFunctionCall, (parser, argument)); argument_anchor.release (); return call; } } /* virtual */ XPath_NotFunctionCall::~XPath_NotFunctionCall () { OP_DELETE (argument); } /* virtual */ unsigned XPath_NotFunctionCall::GetExpressionFlags () { return (argument->GetExpressionFlags () & MASK_INHERITED) | FLAG_BOOLEAN; } /* virtual */ BOOL XPath_NotFunctionCall::EvaluateToBooleanL (XPath_Context *context, BOOL initial) { return !argument->EvaluateToBooleanL (context, initial); } #endif // XPATH_SUPPORT
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int N = 10; char ch[] = {'p','q','r','u','v','w','x','y','z'}; int main() { int t; scanf("%d",&t); while (t--) { int k; bool fr = true; for (int i = 0;i < N-1; i++) { scanf("%d",&k); if (k) { if (k == 1) { if (fr) {printf("%c",ch[i]);fr = false;} else printf("+%c",ch[i]); } else if (k == -1) { if (fr) {printf("-%c",ch[i]);fr = false;} else printf("-%c",ch[i]); } else { if (fr) {printf("%d%c",k,ch[i]);fr = false;} else printf("%+d%c",k,ch[i]); } } } scanf("%d",&k); if (k) { if (fr) {printf("%d",k);fr = false;} else printf("%+d",k); } printf("\n"); } return 0; }
#include<fstream> #include<string.h> #include<ctype.h> #include<algorithm> #include<map> #include<unordered_map> #include<array> #include<deque> #include<queue> #include<math.h> #include<functional> #include<unordered_set> #include<set> #include<iostream> #include<iomanip> #include<bitset> using namespace std; int n, k, santa, mickey,t,i,j,nin,nr; int main() { //ifstream f("file.in"); //ofstream g("file.out"); ifstream f("mere.in"); ofstream g("mere.out"); f >> t; for (j = 1; j <= t; j++) { f >> n >> k; nr = n / k; if (nr == 0) g << "Remiza\n"; else if ((nr % 2 == 0)&&(n%k==0)) g << "Remiza\n"; else g << "Santa Klaus\n"; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * */ #ifndef _BOOKMARK_ADR_STORAGE_H_ #define _BOOKMARK_ADR_STORAGE_H_ #include "modules/bookmarks/bookmark_storage_provider.h" #include "modules/bookmarks/bookmark_manager.h" #include "adjunct/quick/hotlist/hotlistfileio.h" #include "adjunct/quick/models/BookmarkModel.h" #include "adjunct/quick/models/FolderStack.h" /************************************************************** * * BookmarkAdrStorage * * Only supports _reading_ adr files. * For backwards compatibility and import. * * *************************************************************/ class BookmarkAdrStorage : public BookmarkStorageProvider { public: BookmarkAdrStorage(BookmarkManager *manager, const uni_char* path, BOOL sync = TRUE, BOOL merge_trash = FALSE); ~BookmarkAdrStorage() { Close(); } // --- BookmarkStorageProvider ------- virtual OP_STATUS ClearStorage(); virtual OP_STATUS Close(); virtual OP_STATUS UseFormat(BookmarkFormatType format); virtual OP_STATUS SaveBookmark(BookmarkItem *bookmark); virtual OP_STATUS FolderBegin(BookmarkItem *folder); virtual OP_STATUS FolderEnd(BookmarkItem *folder); virtual void RegisterListener(BookmarkStorageListener *l); virtual void UnRegisterListener(BookmarkStorageListener *l); virtual OP_STATUS LoadBookmark(BookmarkItem *bookmark); virtual BOOL MoreBookmarks(); // Read the data but don't add it to core OP_STATUS ReadBookmarkData(BookmarkItemData& item_data); const OpString& GetFilename(){ return m_filename; } protected: void SetFilename(const uni_char* filename) { m_filename.Set(filename); } OP_STATUS ParseHeader(); INT32 GetItemType(const OpString& line); INT32 GetItemField(const OpString& line, OpString& value); BOOL GetNextField(BookmarkItemData& item_data); BOOL Advance(); int IsKey(const uni_char* candidate, int candidateLen, const char* key, int keyLen); BOOL IsYes(const OpStringC value) { return value.Compare(UNI_L("YES")) == 0; } OP_STATUS DecodeUniqueId(uni_char *uid, char *new_uid); OP_STATUS OpenSave(); OP_STATUS OpenRead(); BOOL m_sync; // sync changes, FALSE when importing BOOL m_merge_trash; // should we merge all trashes into one when loading, set to TRUE when importing OpString m_filename; HotlistFileWriter* m_writer; HotlistFileReader* m_reader; FolderStack<BookmarkItem> m_stack; OpString m_last_line; BookmarkItem* m_last_item; BookmarkStorageListener *m_listener; }; // Parse the default bookmarks file when upgrading opera and // 1 add newly added default bookmarks to user profile // 2 udpate existing default bookmarks in user profile class DefaultBookmarkUpgrader : protected BookmarkAdrStorage { public: DefaultBookmarkUpgrader(); OP_STATUS Run(); private: OP_STATUS UpgradeBookmark(BookmarkItemData& item); OP_STATUS UpdateExistingBookmark(BookmarkItem* item, BookmarkItemData& item_data); // Record folders we added and remove empty ones at the end OpAutoVector<OpString> m_added_folders; }; #endif // BOOKMARK_ADR_STORAGE_H_
/** * Copyright (c) 2021, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 <memory> #include <thread> #include <vector> #include "file_converter_manager.hh" #include <unistd.h> #include "base/fs_util.hh" #include "base/injector.hh" #include "base/paths.hh" #include "config.h" #include "line_buffer.hh" #include "piper.looper.cfg.hh" namespace file_converter_manager { static const ghc::filesystem::path& cache_dir() { static auto INSTANCE = lnav::paths::workdir() / "conversion"; return INSTANCE; } Result<convert_result, std::string> convert(const external_file_format& eff, const std::string& filename) { log_info("attempting to convert file -- %s", filename.c_str()); ghc::filesystem::create_directories(cache_dir()); auto outfile = TRY(lnav::filesystem::open_temp_file( cache_dir() / fmt::format(FMT_STRING("{}.XXXXXX"), eff.eff_format_name))); auto err_pipe = TRY(auto_pipe::for_child_fd(STDERR_FILENO)); auto child = TRY(lnav::pid::from_fork()); err_pipe.after_fork(child.in()); if (child.in_child()) { auto dev_null = open("/dev/null", O_RDONLY | O_CLOEXEC); dup2(dev_null, STDIN_FILENO); dup2(outfile.second.get(), STDOUT_FILENO); outfile.second.reset(); auto new_path = lnav::filesystem::build_path({ eff.eff_source_path.parent_path(), lnav::paths::dotlnav() / "formats/default", }); setenv("PATH", new_path.c_str(), 1); log_info("invoking converter: %s (PATH=%s)", eff.eff_converter.c_str(), new_path.c_str()); auto format_str = eff.eff_format_name; const char* args[] = { eff.eff_converter.c_str(), format_str.c_str(), filename.c_str(), nullptr, }; execvp(eff.eff_converter.c_str(), (char**) args); if (errno == ENOENT) { fprintf(stderr, "cannot find converter: %s\n", eff.eff_converter.c_str()); } else { fprintf(stderr, "failed to execute converter: %s -- %s\n", eff.eff_converter.c_str(), strerror(errno)); } _exit(EXIT_FAILURE); } auto error_queue = std::make_shared<std::vector<std::string>>(); std::thread err_reader([err = std::move(err_pipe.read_end()), converter = eff.eff_converter, error_queue, child_pid = child.in()]() mutable { line_buffer lb; file_range pipe_range; bool done = false; lb.set_fd(err); while (!done) { auto load_res = lb.load_next_line(pipe_range); if (load_res.isErr()) { done = true; } else { auto li = load_res.unwrap(); pipe_range = li.li_file_range; if (li.li_file_range.empty()) { done = true; } else { lb.read_range(li.li_file_range) .then([converter, error_queue, child_pid](auto sbr) { auto line_str = string_fragment( sbr.get_data(), 0, sbr.length()) .trim("\n"); if (error_queue->size() < 5) { error_queue->emplace_back(line_str.to_string()); } log_debug("%s[%d]: %.*s", converter.c_str(), child_pid, line_str.length(), line_str.data()); }); } } } }); err_reader.detach(); log_info("started tshark %d to process file", child.in()); return Ok(convert_result{ std::move(child), outfile.first, error_queue, }); } void cleanup() { (void) std::async(std::launch::async, []() { const auto& cfg = injector::get<const lnav::piper::config&>(); auto now = std::chrono::system_clock::now(); auto cache_path = cache_dir(); std::vector<ghc::filesystem::path> to_remove; for (const auto& entry : ghc::filesystem::directory_iterator(cache_path)) { auto mtime = ghc::filesystem::last_write_time(entry.path()); auto exp_time = mtime + cfg.c_ttl; if (now < exp_time) { continue; } to_remove.emplace_back(entry); } for (auto& entry : to_remove) { log_debug("removing conversion: %s", entry.c_str()); ghc::filesystem::remove_all(entry); } }); } } // namespace file_converter_manager
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: factory.cpp,v 1.24.2.9 2005/02/17 15:29:21 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifdef HAVE_CONFIG_H #include "skcore/skbuildconfig.h" #endif #include <nspr/nspr.h> #include <nspr/plstr.h> #include <nspr/plhash.h> #include "../machine.h" #include "../error.h" #include "../log.h" #include "../refcount.h" #include "../skptr.h" #include "../envir/envir.h" #include "../factory/factory.h" #include "../simplifier.h" #include "../unicode/unicodesimplifier.h" #include "skfind/skfind.h" #include "skfind/backend/native/stream.h" #include "skfind/backend/native/field.h" #include "skfind/backend/native/record.h" #include "skfind/backend/native/buf.h" #include "skfind/backend/native/lc.h" #include "skfind/backend/native/table.h" #include "skfind/backend/cursor/cursorrs.h" SK_COMPONENT_DEFAULT_CREATOR(SKCursorRecordSet); #ifdef WIN32 #include "windows.h" // #include <sys/types.h> // #include <sys/stat.h> #include <stdio.h> static PRBool CheckDriveType(const char * pathName, PRBool bIncludeRemote); static char findLogicalDrive(const char * pszVolumeName, PRBool bIncludeRemote); #elif defined(LINUX) #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <mntent.h> #include "linux/iso_fs.h" static PRBool checkVolumeName(const char * device, const char * volume_label); #elif defined(SK_MACOSX) #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #endif #ifdef SK_USE_EXTERNAL_PROTECTION extern "C" unsigned long SKFactoryExternalProtection(const char* pszUrl); extern "C" unsigned long SKFactoryExternalProtectionLogout(); #endif //============================================================================ // Globals //============================================================================ // string used to match [lib]xxx_rtldg.[so.x.x|dll|dylib...] #define SK_RTLD_GLOBAL_SUFFIX "_rtldg." PLHashAllocOps SKFactory::m_sAllocOps = { SKFactory::AllocTable, SKFactory::FreeTable, SKFactory::AllocEntry, SKFactory::FreeEntry }; static const char* s_ppcszValidDllExtensions[] = { #ifdef XP_PC ".dll", /* Windows */ #endif #ifdef XP_UNIX ".so", /* Unix */ ".dylib", /* Mac OS X */ #endif #ifdef XP_MAC ".shlb", /* Mac OS 9 */ #endif #ifdef SK_MACOSX ".dylib", /* Mac OS X */ #endif NULL }; #ifdef XP_MAC static const char* s_pcszValidDllPrefix = "sk"; #endif #ifdef SK_MACOSX #define NEW_FLIMIT 1024 // moved from mac/sysresource.c void RaiseMacResourceLimit() { struct rlimit lim; lim.rlim_cur = (rlim_t)NEW_FLIMIT; lim.rlim_max = (rlim_t)NEW_FLIMIT; setrlimit( RLIMIT_NOFILE, &lim ); } #endif //============================================================================ // SKFactory //============================================================================ SKFactory::SKFactory() { m_pHash = NULL; m_bIsProtected = PR_FALSE; m_bIsTerminated = PR_FALSE; } //============================================================================ // ~SKFactory //============================================================================ SKFactory::~SKFactory() { } //============================================================================ // Terminate //============================================================================ SKERR SKFactory::Terminate() { m_bIsTerminated = PR_TRUE; #ifdef SK_USE_EXTERNAL_PROTECTION if (m_bIsProtected) { m_bIsProtected = PR_FALSE; return SKFactoryExternalProtectionLogout(); } #endif return noErr; } //---------------------------------------------------------------------------- // Init //---------------------------------------------------------------------------- SKERR SKFactory::Init() { if (m_bIsTerminated) return SKError(err_fac_terminated,"[SKFactory] Terminated"); skConsoleLog::Init(); #ifdef SK_USE_EXTERNAL_PROTECTION SKERR err = SKFactoryExternalProtection(NULL); if(err != noErr) return err; m_bIsProtected = PR_TRUE; #endif m_pHash = PL_NewHashTable(32, PL_HashString, PL_CompareStrings, PL_CompareValues, &m_sAllocOps, this); return OnInit(); } //---------------------------------------------------------------------------- // Reactivate //---------------------------------------------------------------------------- SKERR SKFactory::Reactivate() { if (!m_bIsTerminated) return noErr; #ifdef SK_USE_EXTERNAL_PROTECTION SKERR err = SKFactoryExternalProtection(NULL); if(err != noErr) return err; m_bIsProtected = PR_TRUE; #endif return noErr; } //---------------------------------------------------------------------------- // HasComponent //---------------------------------------------------------------------------- SKERR SKFactory::HasComponent(const char *pszComponent, PRBool *pbResult) { if (m_bIsTerminated) return SKError(err_fac_terminated,"[SKFactory] Terminated"); if (!m_pHash) return SKError(err_fac_not_initialised, "[SKFactory::HasComponent] Factory not initialized"); SK_ASSERT(pszComponent && pbResult); if(!pszComponent || !pbResult) return err_invalid; *pbResult = PR_FALSE; char *pszEnd = PL_strchr(pszComponent, ':'); if(!pszEnd) return err_failure; char *pszKey = PL_strndup(pszComponent, pszEnd - pszComponent); void *pData = PL_HashTableLookup(m_pHash, pszKey); PL_strfree(pszKey); if(pData) return RealHasComponent(pData, pszEnd + 1, pbResult); else { if(pbResult) *pbResult = PR_FALSE; return noErr; } } //---------------------------------------------------------------------------- // CreateInstance //---------------------------------------------------------------------------- SKERR SKFactory::CreateInstance(const char *pszParam, SKRefCount **ppInstance) { if (m_bIsTerminated) return SKError(err_fac_terminated,"[SKFactory] Terminated"); if (!m_pHash) return SKError(err_fac_not_initialised, "[SKFactory::CreateInstance] Factory not initialized"); SK_ASSERT(NULL != pszParam); if(!pszParam) return err_failure; char *pszEnd = PL_strchr(pszParam, ':'); if(!pszEnd) return err_failure; char *pszKey = PL_strndup(pszParam, pszEnd - pszParam); void *pData = PL_HashTableLookup(m_pHash, pszKey); SKERR err; if(pData) err = RealCreateInstance(pData, pszEnd + 1, ppInstance); else err = SKError(err_notfound, "[SKFactory::CreateInstance] component '%s' not found", pszKey); PL_strfree(pszKey); return err; } //---------------------------------------------------------------------------- // AllocTable //---------------------------------------------------------------------------- void * PR_CALLBACK SKFactory::AllocTable(void *pool, PRSize size) { return PR_MALLOC(size); } //---------------------------------------------------------------------------- // FreeTable //---------------------------------------------------------------------------- void PR_CALLBACK SKFactory::FreeTable(void *pool, void *item) { PR_Free(item); } //---------------------------------------------------------------------------- // AllocEntry //---------------------------------------------------------------------------- PLHashEntry * PR_CALLBACK SKFactory::AllocEntry(void *pool, const void *key) { return PR_NEW(PLHashEntry); } //---------------------------------------------------------------------------- // AllocTable //---------------------------------------------------------------------------- void PR_CALLBACK SKFactory::FreeEntry(void *pool, PLHashEntry *he, PRUintn flag) { if(flag == HT_FREE_ENTRY) { PL_strfree((char*)he->key); ((SKFactory*)pool)->DeleteValue(he->value); PR_Free(he); } else if(flag == HT_FREE_VALUE) { PL_strfree((char*)he->key); ((SKFactory*)pool)->DeleteValue(he->value); } } //---------------------------------------------------------------------------- // AddDisk //---------------------------------------------------------------------------- SKERR SKFactory::AddDisk(const char * pszVolumeName, PRBool bIncludeRemote) { SKERR err = noErr; SKEnvir *pEnv = NULL; SKEnvir::GetEnvir(&pEnv); #ifdef WINCE // do nothing #elif defined(WIN32) char pszPath[] = "A:\\;"; char driveLetter = findLogicalDrive(pszVolumeName, bIncludeRemote); if( driveLetter == 0 ) return SKError(err_notfound, "[SKFactory::AddDisk] " "Volume : '%s' not found", pszVolumeName); pszPath[0] = driveLetter; pEnv->PrependToValue("PATH", pszPath ); #elif defined(LINUX) FILE * mtab; struct mntent * entry; char * device; char * fs; char * tmp; mtab = setmntent("/etc/mtab", "r"); while ((entry = getmntent(mtab)) != NULL) { device = NULL; if (!PL_strcmp(entry->mnt_type, "supermount")) { fs = hasmntopt(entry, "fs"); if (fs != NULL) { while (*fs++ != '=') fs++; tmp = fs; while (*tmp != ',') tmp++; *tmp = 0; if (!PL_strcmp(fs, "iso9660")) { device = hasmntopt(entry, "dev"); if (device != NULL) { while (*device++ != '='); tmp = device; while (*tmp != ',') tmp++; *tmp = 0; //skConsoleLog::DebugLog("Device = %s, fs = %s\n", device, fs); } } else if (!PL_strcmp(fs, "auto")) { // if the filesystem is "auto", checks if the mount point // contains CD or DVD char * mnt_dir = entry->mnt_dir; if ((PL_strstr(mnt_dir, "/cd") != NULL) || (PL_strstr(mnt_dir, "/dvd") != NULL) ) { device = hasmntopt(entry, "dev"); if (device != NULL) { while (*device++ != '='); tmp = device; while (*tmp != ',') tmp++; *tmp = 0; //skConsoleLog::DebugLog("Device = %s, fs = %s\n", device, fs); } } } } } else if (!PL_strcmp(entry->mnt_type, "subfs")) { fs = hasmntopt(entry, "fs"); if (fs != NULL) { while (*fs++ != '=') fs++; tmp = fs; while (*tmp != ',') tmp++; *tmp = 0; if (!PL_strcmp(fs, "cdfss")) { device = entry->mnt_fsname; } } } else if (!PL_strcmp(entry->mnt_type, "iso9660")) { device = entry->mnt_fsname; } if (device != NULL) { if (checkVolumeName(device, pszVolumeName)) { break; } } } endmntent(mtab); if (entry != NULL) { skConsoleLog::Log("Found CD ?s?at : %s", pszVolumeName, entry->mnt_dir); } else { return SKError(err_notfound, "[SKFactory::AddDisk] " "Volume : '%s' not found", pszVolumeName); } pEnv->PrependToValue("PATH", ";"); pEnv->PrependToValue("PATH", entry->mnt_dir ); #elif defined(XP_MAC) PRUint32 uiLength = PL_strlen(pszVolumeName); char* pszTemp = (char *)PR_Malloc((uiLength+3) * sizeof(char)); pszTemp[0] = '/'; PL_strcpy( pszTemp + 1, pszVolumeName ); pszTemp[uiLength + 1] = '/'; pszTemp[uiLength + 2] = '\0'; if( PR_Access(pszTemp, PR_ACCESS_EXISTS) == PR_SUCCESS ) { //skConsoleLog::Log( "Found CD ?s?at : %s", pszVolumeName, pszTemp ); pEnv->PrependToValue("PATH", ";"); pEnv->PrependToValue("PATH", pszVolumeName ); pEnv->PrependToValue("PATH", "/"); } else err = SKError(err_notfound, "[SKFactory::AddDisk] " "Volume : '%s' not found", pszVolumeName); PL_strfree( pszTemp ); #elif defined(SK_MACOSX) #define MAC_VOLUMEPATH_PREFIX "/Volumes/" // CD: discussion // On Mac OS 10.3, the startup volume is correctly aliased in the /Volumes // mount dir. That was not the case in 10.2 but we don't care, since we are // not going to call addDisk on the startup volume. // If we ever want to, we will have to test the volume name against the // startup volume name and just add "/" in that case PRUint32 uiLength = PL_strlen(pszVolumeName) + sizeof(MAC_VOLUMEPATH_PREFIX); char* pszTemp = (char *)PR_Malloc( uiLength * sizeof(char) ); PL_strcpy( pszTemp, MAC_VOLUMEPATH_PREFIX ); PL_strcat( pszTemp, pszVolumeName ); if( PR_Access(pszTemp, PR_ACCESS_EXISTS) == PR_SUCCESS ) { // skConsoleLog::Log( "Found CD '%s' at : %s", pszVolumeName, pszTemp ); pEnv->PrependToValue("PATH", ";"); pEnv->PrependToValue("PATH", pszTemp ); } else err = SKError(err_notfound, "[SKFactory::AddDisk] " "Volume : '%s' not found", pszVolumeName); PL_strfree( pszTemp ); #else #error "SKFactory::AddDisk does nothing on your platform. Add code here." #endif return err; } //---------------------------------------------------------------------------- // UrlDecode //---------------------------------------------------------------------------- SKERR SKFactory::UrlDecode(char*s) { char* pc = s; for( ; *s; s++) { //+ to spaces if(*s=='+') *pc = ' '; else if(*s=='%') { // check that we still have 2 cars to read if(s[1] && s[2]) { // now do they look like valid hex digits ? if ( ((s[1]>='0'&&s[1]<='9') || (s[1]>='a' && s[1]<='f') || (s[1]>='A' && s[1]<='F')) && ((s[2]>='0'&&s[2]<='9') || (s[2]>='a' && s[2]<='f') || (s[2]>='A' && s[2]<='F')) ) { char tmp[3]; tmp[2] = '\0'; tmp[0] = s[1]; tmp[1] = s[2]; // do the actual conversion *pc = (char) strtol(tmp, NULL, 16); } else { *pc = '?'; return SKError(err_invalid, "[SKFactory::UrlDecode] " "bad URL format"); } // we have to eat to more caracters s += 2; } else { // we do not have enough to eat, so we are at the end of // the buffer *pc = '?'; pc[1] = '\0'; return SKError(err_invalid, "[SKFactory::UrlDecode] " "bad URL format"); } } else *pc = *s; pc++; } *pc ='\0'; return noErr; } //============================================================================ // SKSubFactory //============================================================================ SKSubFactory::~SKSubFactory() { if(m_pHash) PL_HashTableDestroy(m_pHash); } //---------------------------------------------------------------------------- // OnInit //---------------------------------------------------------------------------- SKERR SKSubFactory::OnInit() { return noErr; } //---------------------------------------------------------------------------- // RealHasComponent //---------------------------------------------------------------------------- SKERR SKSubFactory::RealHasComponent(void *pData, const char *pszComponent, PRBool *pbResult) { *pbResult = (pData != NULL); return noErr; } //---------------------------------------------------------------------------- // RealCreateInstance //---------------------------------------------------------------------------- SKERR SKSubFactory::RealCreateInstance(void *pData, const char *pszParam, SKRefCount **ppInstance) { return ((SKComponentData_t*)pData)->m_pfInstanceCreator(pszParam, ppInstance); } //---------------------------------------------------------------------------- // DeleteValue //---------------------------------------------------------------------------- void SKSubFactory::DeleteValue(void *pValue) { delete (SKComponentData_t *)pValue; } //---------------------------------------------------------------------------- // RegisterComponents //---------------------------------------------------------------------------- SKERR SKSubFactory::RegisterComponents( SKComponentData_t *pData ) { SKComponentData_t *pComponent = (SKComponentData_t *)PL_HashTableLookup(m_pHash, pData->m_pszName); if(!pComponent) { pComponent = new SKComponentData_t; pComponent->m_pszType = pData->m_pszType; pComponent->m_pszName = pData->m_pszName; pComponent->m_pfInstanceCreator = pData->m_pfInstanceCreator; char *pszKey = PL_strdup(pData->m_pszName); PL_HashTableAdd(m_pHash, pszKey, pComponent); } return noErr; } //============================================================================ // SKInlineFactory //============================================================================ SKInlineFactory::~SKInlineFactory() { if(m_pHash) PL_HashTableDestroy(m_pHash); } //---------------------------------------------------------------------------- // OnInit //---------------------------------------------------------------------------- SKERR SKInlineFactory::OnInit() { static SKComponentData_t componentData[] = { {"simplifier", "unicode", skStringUnicodeSimplifier::CreateUnicodeSimplifier}, {"recordset", "native", SKTable::CreateNativeRecordSet}, {"recordset", "cursor", _Create_SKCursorRecordSet}, {NULL, NULL, NULL} }; for(SKComponentData_t * pData = componentData; NULL != pData->m_pszType; pData++) { RegisterComponents(pData); } return noErr; } //---------------------------------------------------------------------------- // RealHasComponent //---------------------------------------------------------------------------- SKERR SKInlineFactory::RealHasComponent(void *pData, const char *pszComponent, PRBool *pbResult) { return ((SKSubFactory*)pData)->HasComponent(pszComponent, pbResult); } //---------------------------------------------------------------------------- // RealCreateInstance //---------------------------------------------------------------------------- SKERR SKInlineFactory::RealCreateInstance(void *pData, const char *pszParam, SKRefCount **ppInstance) { return ((SKSubFactory*)pData)->CreateInstance(pszParam, ppInstance); } //---------------------------------------------------------------------------- // DeleteValue //---------------------------------------------------------------------------- void SKInlineFactory::DeleteValue(void *pValue) { delete (SKSubFactory *)pValue; } //---------------------------------------------------------------------------- // RegisterComponents //---------------------------------------------------------------------------- SKERR SKInlineFactory::RegisterComponents(SKComponentData_t *pData) { SKSubFactory *pSubFactory = (SKSubFactory*)PL_HashTableLookup(m_pHash, pData->m_pszType); if(!pSubFactory) { pSubFactory = new SKSubFactory(); SKERR err = pSubFactory->Init(); if(err != noErr) { delete pSubFactory; return err; } char *pszKey = PL_strdup(pData->m_pszType); PL_HashTableAdd(m_pHash, pszKey, pSubFactory); } return pSubFactory->RegisterComponents(pData); } class skFactoryHolder { public: ~skFactoryHolder() { if(s_pInstance) { delete s_pInstance; s_pInstance = NULL; } } SKERR GetFactory(SKFactory **ppFactory); SKERR SetFactory(SKFactory *pFactory); static SKFactory *s_pInstance; }; SKFactory *skFactoryHolder::s_pInstance = NULL; SKERR skFactoryHolder::GetFactory(SKFactory **ppFactory) { *ppFactory = NULL; if(!s_pInstance) { s_pInstance = new SKInlineFactory; if(!s_pInstance) return err_memory; SKERR err = ((SKInlineFactory *)s_pInstance)->Init(); if(err != noErr) { delete s_pInstance; s_pInstance = NULL; return err; } } *ppFactory = s_pInstance; return noErr; } SKERR skFactoryHolder::SetFactory(SKFactory *pFactory) { SK_ASSERT(!s_pInstance || !pFactory || (s_pInstance == pFactory)); if(s_pInstance && (s_pInstance != pFactory)) delete s_pInstance; s_pInstance = pFactory; return noErr; } static skFactoryHolder g_skFactoryHolder; //---------------------------------------------------------------------------- // GetFactory //---------------------------------------------------------------------------- SKERR SKFactory::GetFactory(SKFactory **ppFactory) { return g_skFactoryHolder.GetFactory(ppFactory); } //---------------------------------------------------------------------------- // SetFactory //---------------------------------------------------------------------------- SKERR SKFactory::SetFactory(SKFactory *pFactory) { return g_skFactoryHolder.SetFactory(pFactory); }
#include "../LogSystem.h" // int main() { std::string str("This "); Log(str.c_str(), "is a Log"); LogWarn("This is a Log"); LogError("This is a Log, Error local ", __CODELOCAL__); // SetLogFilePath("../Log/"); FLog(str.c_str(), "is ", 1, " File Log"); float fvalue = 1.0F; FLogWarn("This is ", fvalue, " File Log"); double dvalue = 1.0F; FLogError("This is ", dvalue, " File Log, Error local ", __CODELOCAL__); // std::cin.get(); return 0; }
const int stepPin = 3; const int dirPin = 4; const int toggleA = 12; const int toggleB = 13; int buttonStateA = 0; int buttonStateB = 0; void setup() { // Sets int / outputs pinMode(stepPin,OUTPUT); pinMode(dirPin,OUTPUT); pinMode(toggleA,INPUT); pinMode(toggleB,INPUT); } void loop() { buttonStateA = digitalRead(toggleA); buttonStateB = digitalRead(toggleB); if (buttonStateA == HIGH) { digitalWrite(dirPin,LOW); // Enables the motor to move in a particular direction // Makes 200 pulses for making one full cycle rotation for(int x = 0; x < 200; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } } else { digitalWrite(stepPin,LOW); } if (buttonStateB == HIGH) { digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction // Makes 200 pulses for making one full cycle rotation for(int x = 0; x < 200; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } } else { digitalWrite(stepPin,LOW); } delay(100); } /*digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction // Makes 200 pulses for making one full cycle rotation for(int x = 0; x < 200; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } delay(1000); // One second delay digitalWrite(dirPin,LOW); //Changes the rotations direction // Makes 400 pulses for making two full cycle rotation for(int x = 0; x < 400; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } delay(1000); }*/
/***************************************************************************************** * * * owl * * * * Copyright (c) 2014 Jonas Strandstedt * * * * 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 <owl/data/any.h> #include <owl/data/dictionary.h> namespace owl { Any::Any(Any& that): ptr(that.clone()) {} Any::Any(Any&& that): ptr(that.ptr) { that.ptr = nullptr; } Any::Any(const Any& that): ptr(that.clone()) {} Any::Any(const Any&& that): ptr(that.clone()) {} Any::Any(const char* value) : ptr(new Derived<StorageType<std::string> >(std::string(value))) {} Any& Any::operator=(const Any& a) { if (ptr == a.ptr) return *this; auto old_ptr = ptr; ptr = a.clone(); if (old_ptr) delete old_ptr; return *this; } Any& Any::operator=(Any&& a) { if (ptr == a.ptr) return *this; std::swap(ptr, a.ptr); return *this; } Any::~Any() { if (ptr) delete ptr; } bool Any::is_null() const { return ptr == nullptr; } bool Any::not_null() const { return ptr != nullptr; } Any::Base* Any::clone() const { if (ptr) return ptr->clone(); else return nullptr; } std::string Any::typeName() const { if(ptr) return ptr->name(); return "nullptr"; } size_t Any::type() const { if(is<char>()) return Any_char; else if(is<char16_t>()) return Any_char16_t; else if(is<char32_t>()) return Any_char32_t; else if(is<wchar_t>()) return Any_wchar_t; else if(is<short>()) return Any_short; else if(is<int>()) return Any_int; else if(is<long int>()) return Any_long_int; else if(is<long long int>()) return Any_long_long_int; else if(is<unsigned short>()) return Any_unsigned_short; else if(is<unsigned int>()) return Any_unsigned_int; else if(is<unsigned long int>()) return Any_unsigned_long_int; else if(is<unsigned long long int>()) return Any_unsigned_long_long_int; else if(is<float>()) return Any_float; else if(is<double>()) return Any_double; else if(is<long double>()) return Any_long_double; else if(is<bool>()) return Any_bool; else if(is<std::string>()) return Any_std_string; else if(is<Dictionary>()) return Any_Dictionary; else if(is<std::vector<char> >()) return Any_vector_char; else if(is<std::vector<char16_t>>()) return Any_vector_char16_t; else if(is<std::vector<char32_t>>()) return Any_vector_char32_t; else if(is<std::vector<wchar_t>>()) return Any_vector_wchar_t; else if(is<std::vector<short>>()) return Any_vector_short; else if(is<std::vector<int>>()) return Any_vector_int; else if(is<std::vector<long int>>()) return Any_vector_long_int; else if(is<std::vector<long long int>>()) return Any_vector_long_long_int; else if(is<std::vector<unsigned short>>()) return Any_vector_unsigned_short; else if(is<std::vector<unsigned int>>()) return Any_vector_unsigned_int; else if(is<std::vector<unsigned long int>>()) return Any_vector_unsigned_long_int; else if(is<std::vector<unsigned long long int>>()) return Any_vector_unsigned_long_long_int; else if(is<std::vector<float>>()) return Any_vector_float; else if(is<std::vector<double>>()) return Any_vector_double; else if(is<std::vector<long double>>()) return Any_vector_long_double; else if(is<std::vector<std::string>>()) return Any_vector_std_string; else if(is<std::vector<Dictionary>>()) return Any_vector_Dictionary; return Any_unsupported; } void Any::serialize(const Any& v, std::ostream& out) { size_t type = v.type(); Serializer::serialize(type, out); if(type == Any_unsupported) { return; } if(type == Any_char) serialize<char>(v, out); else if(type == Any_char16_t) serialize<char16_t>(v, out); else if(type == Any_char32_t) serialize<char32_t>(v, out); else if(type == Any_wchar_t) serialize<wchar_t>(v, out); else if(type == Any_short) serialize<short>(v, out); else if(type == Any_int) serialize<int>(v, out); else if(type == Any_long_int) serialize<long int>(v, out); else if(type == Any_long_long_int) serialize<long long int>(v, out); else if(type == Any_unsigned_short) serialize<unsigned short>(v, out); else if(type == Any_unsigned_int) serialize<unsigned int>(v, out); else if(type == Any_unsigned_long_int) serialize<unsigned long int>(v, out); else if(type == Any_unsigned_long_long_int) serialize<unsigned long long int>(v, out); else if(type == Any_float) serialize<float>(v, out); else if(type == Any_double) serialize<double>(v, out); else if(type == Any_long_double) serialize<long double>(v, out); else if(type == Any_bool) serialize<bool>(v, out); else if(type == Any_std_string) serialize<std::string>(v, out); else if(type == Any_Dictionary) serialize<Dictionary>(v, out); else if(type == Any_vector_char) serialize<std::vector<char>>(v, out); else if(type == Any_vector_char16_t) serialize<std::vector<char16_t>>(v, out); else if(type == Any_vector_char32_t) serialize<std::vector<char32_t>>(v, out); else if(type == Any_vector_wchar_t) serialize<std::vector<wchar_t>>(v, out); else if(type == Any_vector_short) serialize<std::vector<short>>(v, out); else if(type == Any_vector_int) serialize<std::vector<int>>(v, out); else if(type == Any_vector_long_int) serialize<std::vector<long int>>(v, out); else if(type == Any_vector_long_long_int) serialize<std::vector<long long int>>(v, out); else if(type == Any_vector_unsigned_short) serialize<std::vector<unsigned short>>(v, out); else if(type == Any_vector_unsigned_int) serialize<std::vector<unsigned int>>(v, out); else if(type == Any_vector_unsigned_long_int) serialize<std::vector<unsigned long int>>(v, out); else if(type == Any_vector_unsigned_long_long_int) serialize<std::vector<unsigned long long int>>(v, out); else if(type == Any_vector_float) serialize<std::vector<float>>(v, out); else if(type == Any_vector_double) serialize<std::vector<double>>(v, out); else if(type == Any_vector_long_double) serialize<std::vector<long double>>(v, out); else if(type == Any_vector_std_string) serialize<std::vector<std::string>>(v, out); else if(type == Any_vector_Dictionary) serialize<std::vector<Dictionary>>(v, out); } void Any::deserialize(Any& v, std::istream& src) { size_t type; Serializer::deserialize(type, src); if(type == Any_char) deserialize<char>(v, src); else if(type == Any_char16_t) deserialize<char16_t>(v, src); else if(type == Any_char32_t) deserialize<char32_t>(v, src); else if(type == Any_wchar_t) deserialize<wchar_t>(v, src); else if(type == Any_short) deserialize<short>(v, src); else if(type == Any_int) deserialize<int>(v, src); else if(type == Any_long_int) deserialize<long int>(v, src); else if(type == Any_long_long_int) deserialize<long long int>(v, src); else if(type == Any_unsigned_short) deserialize<unsigned short>(v, src); else if(type == Any_unsigned_int) deserialize<unsigned int>(v, src); else if(type == Any_unsigned_long_int) deserialize<unsigned long int>(v, src); else if(type == Any_unsigned_long_long_int) deserialize<unsigned long long int>(v, src); else if(type == Any_float) deserialize<float>(v, src); else if(type == Any_double) deserialize<double>(v, src); else if(type == Any_long_double) deserialize<long double>(v, src); else if(type == Any_bool) deserialize<bool>(v, src); else if(type == Any_std_string) deserialize<std::string>(v, src); else if(type == Any_Dictionary) deserialize<Dictionary>(v, src); else if(type == Any_vector_char) deserialize<std::vector<char>>(v, src); else if(type == Any_vector_char16_t) deserialize<std::vector<char16_t>>(v, src); else if(type == Any_vector_char32_t) deserialize<std::vector<char32_t>>(v, src); else if(type == Any_vector_wchar_t) deserialize<std::vector<wchar_t>>(v, src); else if(type == Any_vector_short) deserialize<std::vector<short>>(v, src); else if(type == Any_vector_int) deserialize<std::vector<int>>(v, src); else if(type == Any_vector_long_int) deserialize<std::vector<long int>>(v, src); else if(type == Any_vector_long_long_int) deserialize<std::vector<long long int>>(v, src); else if(type == Any_vector_unsigned_short) deserialize<std::vector<unsigned short>>(v, src); else if(type == Any_vector_unsigned_int) deserialize<std::vector<unsigned int>>(v, src); else if(type == Any_vector_unsigned_long_int) deserialize<std::vector<unsigned long int>>(v, src); else if(type == Any_vector_unsigned_long_long_int) deserialize<std::vector<unsigned long long int>>(v, src); else if(type == Any_vector_float) deserialize<std::vector<float>>(v, src); else if(type == Any_vector_double) deserialize<std::vector<double>>(v, src); else if(type == Any_vector_long_double) deserialize<std::vector<long double>>(v, src); else if(type == Any_vector_std_string) deserialize<std::vector<std::string>>(v, src); else if(type == Any_vector_Dictionary) deserialize<std::vector<Dictionary>>(v, src); else { // Unsupported type v = Any(); } } } // namespace owl
/*==================================================================== Copyright(c) 2018 Adam Rankin 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. ====================================================================*/ // Local includes #include "pch.h" #include "AppView.h" #include "Volume.h" // Common includes #include "Common.h" #include "DeviceResources.h" #include "DirectXHelper.h" #include "StepTimer.h" // System includes #include "NotificationSystem.h" #include "RegistrationSystem.h" // DirectXTex includes #include <DirectXTex.h> // DirectX includes #include <d3d11_3.h> #include <DirectXColors.h> // Unnecessary, but reduces intellisense errors #include "Log.h" #include <WindowsNumerics.h> using namespace Concurrency; using namespace DirectX; using namespace Windows::Foundation::Numerics; using namespace Windows::Perception::Spatial; using namespace Windows::UI::Input::Spatial; namespace { // Function taken from https://github.com/mrdooz/kumi/blob/master/animation_manager.cpp float4x4 MatrixCompose(const float3& pos, const quaternion& rot, const float3& scale, bool transpose) { XMFLOAT3 zero = { 0, 0, 0 }; XMFLOAT4 id = { 0, 0, 0, 1 }; XMVECTOR vZero = XMLoadFloat3(&zero); XMVECTOR qId = XMLoadFloat4(&id); XMVECTOR qRot = XMLoadQuaternion(&rot); XMVECTOR vPos = XMLoadFloat3(&pos); XMVECTOR vScale = XMLoadFloat3(&scale); XMMATRIX mtx = XMMatrixTransformation(vZero, qId, vScale, vZero, qRot, vPos); if (transpose) { mtx = XMMatrixTranspose(mtx); } float4x4 res; XMStoreFloat4x4(&res, mtx); return res; } } namespace HoloIntervention { namespace Rendering { const float Volume::LERP_RATE = 2.5f; //---------------------------------------------------------------------------- Volume::Volume(const std::shared_ptr<DX::DeviceResources>& deviceResources, uint64 token, ID3D11Buffer* cwIndexBuffer, ID3D11Buffer* ccwIndexBuffer, ID3D11InputLayout* inputLayout, ID3D11Buffer* vertexBuffer, ID3D11VertexShader* volRenderVertexShader, ID3D11GeometryShader* volRenderGeometryShader, ID3D11PixelShader* volRenderPixelShader, ID3D11PixelShader* faceCalcPixelShader, ID3D11Texture2D* frontPositionTextureArray, ID3D11Texture2D* backPositionTextureArray, ID3D11RenderTargetView* frontPositionRTV, ID3D11RenderTargetView* backPositionRTV, ID3D11ShaderResourceView* frontPositionSRV, ID3D11ShaderResourceView* backPositionSRV, DX::StepTimer& timer) : m_deviceResources(deviceResources) , m_token(token) , m_cwIndexBuffer(cwIndexBuffer) , m_ccwIndexBuffer(ccwIndexBuffer) , m_inputLayout(inputLayout) , m_vertexBuffer(vertexBuffer) , m_volRenderVertexShader(volRenderVertexShader) , m_volRenderGeometryShader(volRenderGeometryShader) , m_volRenderPixelShader(volRenderPixelShader) , m_faceCalcPixelShader(faceCalcPixelShader) , m_frontPositionTextureArray(frontPositionTextureArray) , m_backPositionTextureArray(backPositionTextureArray) , m_frontPositionRTV(frontPositionRTV) , m_backPositionRTV(backPositionRTV) , m_frontPositionSRV(frontPositionSRV) , m_backPositionSRV(backPositionSRV) , m_timer(timer) { ControlPointList points; points.push_back(ControlPoint(0.f, float4(0.f, 0.f, 0.f, 0.f))); points.push_back(ControlPoint(255.f, float4(0.f, 0.f, 0.f, 1.f))); SetOpacityTransferFunctionTypeAsync(TransferFunction_Piecewise_Linear, 512, points); CreateDeviceDependentResources(); } //---------------------------------------------------------------------------- Volume::~Volume() { ReleaseDeviceDependentResources(); delete m_opacityTransferFunction; } //---------------------------------------------------------------------------- bool Volume::IsInFrustum() const { return m_isInFrustum; } //---------------------------------------------------------------------------- bool Volume::IsInFrustum(const Windows::Perception::Spatial::SpatialBoundingFrustum& frustum) const { if (m_timer.GetFrameCount() == m_frustumCheckFrameNumber) { return m_isInFrustum; } const std::vector<float3> points = { transform(float3(0.f, 0.f, 0.f), m_currentPose), transform(float3(0.f, 0.f, 1.f), m_currentPose), transform(float3(0.f, 1.f, 0.f), m_currentPose), transform(float3(0.f, 1.f, 1.f), m_currentPose), transform(float3(1.f, 0.f, 0.f), m_currentPose), transform(float3(1.f, 0.f, 1.f), m_currentPose), transform(float3(1.f, 1.f, 0.f), m_currentPose), transform(float3(1.f, 1.f, 1.f), m_currentPose) }; m_isInFrustum = HoloIntervention::IsInFrustum(frustum, points); m_frustumCheckFrameNumber = m_timer.GetFrameCount(); return m_isInFrustum; } //---------------------------------------------------------------------------- bool Volume::IsValid() const { return m_volumeReady; } //---------------------------------------------------------------------------- void Volume::Update() { if (!m_tfResourcesReady) { // nothing to do! return; } auto context = m_deviceResources->GetD3DDeviceContext(); auto device = m_deviceResources->GetD3DDevice(); const float& deltaTime = static_cast<float>(m_timer.GetElapsedSeconds()); float3 currentScale; quaternion currentRotation; float3 currentTranslation; decompose(m_currentPose, &currentScale, &currentRotation, &currentTranslation); float3 lastScale; quaternion lastRotation; float3 lastTranslation; decompose(m_currentPose, &lastScale, &lastRotation, &lastTranslation); const float3 deltaPosition = currentTranslation - lastTranslation; // meters m_velocity = deltaPosition * (1.f / deltaTime); // meters per second m_lastPose = m_currentPose; // Calculate new smoothed currentPose float3 desiredScale; quaternion desiredRotation; float3 desiredTranslation; decompose(m_desiredPose, &desiredScale, &desiredRotation, &desiredTranslation); float3 smoothedScale = lerp(currentScale, desiredScale, deltaTime * LERP_RATE); quaternion smoothedRotation = slerp(currentRotation, desiredRotation, deltaTime * LERP_RATE); float3 smoothedTranslation = lerp(currentTranslation, desiredTranslation, deltaTime * LERP_RATE); m_currentPose = MatrixCompose(smoothedTranslation, smoothedRotation, smoothedScale, true); if (m_volumeUpdateNeeded) { ReleaseVolumeResources(); CreateVolumeResources(); m_volumeUpdateNeeded = false; } if (m_onGPUFrame != m_frame) { UpdateGPUImageData(); } XMStoreFloat4x4(&m_constantBuffer.worldMatrix, XMLoadFloat4x4(&m_currentPose)); context->UpdateSubresource(m_volumeEntryConstantBuffer.Get(), 0, nullptr, &m_constantBuffer, 0, 0); } //---------------------------------------------------------------------------- void Volume::Render(uint32 indexCount) { if (!m_volumeReady || !m_tfResourcesReady) { return; } ID3D11DeviceContext3* context = m_deviceResources->GetD3DDeviceContext(); const UINT stride = sizeof(VertexPosition); const UINT offset = 0; context->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetInputLayout(m_inputLayout); // Cache render target ID3D11RenderTargetView* hololensRenderTargetView; ID3D11DepthStencilView* hololensStencilView; context->OMGetRenderTargets(1, &hololensRenderTargetView, &hololensStencilView); context->ClearRenderTargetView(m_frontPositionRTV, DirectX::Colors::Black); context->ClearRenderTargetView(m_backPositionRTV, DirectX::Colors::Black); context->RSSetState(nullptr); // Set index buffer to cw winding to calculate front faces context->IASetIndexBuffer(m_cwIndexBuffer, DXGI_FORMAT_R16_UINT, 0); ID3D11RenderTargetView* targets[1] = { m_frontPositionRTV }; context->OMSetRenderTargets(1, targets, nullptr); context->VSSetShader(m_volRenderVertexShader, nullptr, 0); context->VSSetConstantBuffers(0, 1, m_volumeEntryConstantBuffer.GetAddressOf()); if (!m_deviceResources->GetDeviceSupportsVprt()) { context->GSSetShader(m_volRenderGeometryShader, nullptr, 0); context->GSSetConstantBuffers(0, 1, m_volumeEntryConstantBuffer.GetAddressOf()); } context->PSSetShader(m_faceCalcPixelShader, nullptr, 0); context->DrawIndexedInstanced(indexCount, 2, 0, 0, 0); // Set index buffer to ccw winding to calculate back faces context->IASetIndexBuffer(m_ccwIndexBuffer, DXGI_FORMAT_R16_UINT, 0); targets[0] = m_backPositionRTV; context->OMSetRenderTargets(1, targets, nullptr); context->DrawIndexedInstanced(indexCount, 2, 0, 0, 0); // Now perform the actual volume render targets[0] = hololensRenderTargetView; context->OMSetRenderTargets(1, targets, hololensStencilView); context->IASetIndexBuffer(m_cwIndexBuffer, DXGI_FORMAT_R16_UINT, 0); ID3D11ShaderResourceView* shaderResourceViews[4] = { m_opacityLookupTableSRV.Get(), m_volumeSRV.Get(), m_frontPositionSRV, m_backPositionSRV }; context->PSSetShaderResources(0, 4, shaderResourceViews); ID3D11SamplerState* samplerStates[1] = { m_samplerState.Get() }; context->PSSetSamplers(0, 1, samplerStates); context->PSSetConstantBuffers(0, 1, m_volumeEntryConstantBuffer.GetAddressOf()); context->PSSetShader(m_volRenderPixelShader, nullptr, 0); context->DrawIndexedInstanced(indexCount, 2, 0, 0, 0); // Clear values ID3D11ShaderResourceView* ppSRVnullptr[4] = { nullptr, nullptr, nullptr, nullptr }; context->PSSetShaderResources(0, 4, ppSRVnullptr); ID3D11SamplerState* ppSamplerStatesnullptr[1] = { nullptr }; context->PSSetSamplers(0, 1, ppSamplerStatesnullptr); } //---------------------------------------------------------------------------- void Volume::SetFrame(UWPOpenIGTLink::VideoFrame^ frame) { auto frameSize = frame->Dimensions; if (frameSize[2] < 1) { return; } if (!m_volumeReady) { m_volumeUpdateNeeded = true; } else if (m_frame != nullptr) { if (m_frame != nullptr) { auto myFrameSize = m_frame->Dimensions; if (myFrameSize[0] != frameSize[0] || myFrameSize[1] != frameSize[1] || myFrameSize[2] != frameSize[2]) { // GPU needs to be reallocated m_volumeUpdateNeeded = true; } } } m_frame = frame; } //---------------------------------------------------------------------------- void Volume::SetShowing(bool showing) { m_showing = showing; } //---------------------------------------------------------------------------- uint64 Volume::GetToken() const { return m_token; } //---------------------------------------------------------------------------- void Volume::ForceCurrentPose(const Windows::Foundation::Numerics::float4x4& matrix) { m_desiredPose = m_currentPose = matrix; } //---------------------------------------------------------------------------- void Volume::SetDesiredPose(const Windows::Foundation::Numerics::float4x4& matrix) { m_desiredPose = matrix; } //---------------------------------------------------------------------------- float4x4 Volume::GetCurrentPose() const { return m_currentPose; } //---------------------------------------------------------------------------- float3 Volume::GetVelocity() const { return m_velocity; } //---------------------------------------------------------------------------- void Volume::UpdateGPUImageData() { const auto context = m_deviceResources->GetD3DDeviceContext(); auto bytesPerPixel = BitsPerPixel((DXGI_FORMAT)m_frame->GetPixelFormat(true)) / 8; std::shared_ptr<byte> image = *(std::shared_ptr<byte>*)(m_frame->Image->GetImageData()); if (image == nullptr) { LOG(LogLevelType::LOG_LEVEL_ERROR, "Unable to access image buffer."); return; } auto frameSize = m_frame->Dimensions; if (frameSize[2] < 1) { return; } // Map image resource and update data byte* imageRaw = image.get(); D3D11_MAPPED_SUBRESOURCE mappedResource; context->Map(m_volumeStagingTexture.Get(), 0, D3D11_MAP_READ_WRITE, 0, &mappedResource); byte* mappedData = reinterpret_cast<byte*>(mappedResource.pData); for (uint32 j = 0; j < frameSize[2]; ++j) { for (uint32 i = 0; i < frameSize[1]; ++i) { memcpy(mappedData, imageRaw, frameSize[0] * bytesPerPixel); mappedData += mappedResource.RowPitch; imageRaw += frameSize[0] * bytesPerPixel; } } context->Unmap(m_volumeStagingTexture.Get(), 0); context->CopyResource(m_volumeTexture.Get(), m_volumeStagingTexture.Get()); m_onGPUFrame = m_frame; } //---------------------------------------------------------------------------- void Volume::CreateDeviceDependentResources() { const auto device = m_deviceResources->GetD3DDevice(); if (m_opacityTFType != TransferFunction_Unknown) { std::lock_guard<std::mutex> guard(m_opacityTFMutex); CreateTFResources(); } if (m_frame != nullptr) { CreateVolumeResources(); } VolumeEntryConstantBuffer buffer; XMStoreFloat4x4(&buffer.worldMatrix, XMMatrixIdentity()); D3D11_SUBRESOURCE_DATA resData; resData.pSysMem = &buffer; resData.SysMemPitch = 0; resData.SysMemSlicePitch = 0; DX::ThrowIfFailed(device->CreateBuffer(&CD3D11_BUFFER_DESC(sizeof(VolumeEntryConstantBuffer), D3D11_BIND_CONSTANT_BUFFER), &resData, m_volumeEntryConstantBuffer.GetAddressOf())); } //---------------------------------------------------------------------------- void Volume::ReleaseDeviceDependentResources() { ReleaseVolumeResources(); ReleaseTFResources(); m_volumeEntryConstantBuffer.Reset(); } //---------------------------------------------------------------------------- void Volume::CreateVolumeResources() { const auto device = m_deviceResources->GetD3DDevice(); if (m_frame == nullptr) { return; } auto format = (DXGI_FORMAT)m_frame->GetPixelFormat(true); auto bytesPerPixel = BitsPerPixel(format) / 8; byte* imageRaw = GetDataFromIBuffer<byte>(m_frame->Image->ImageData); if (imageRaw == nullptr) { LOG(LogLevelType::LOG_LEVEL_ERROR, "Unable to access image buffer."); return; } auto frameSize = m_frame->Dimensions; if (frameSize[2] < 1) { return; } // Create a staging texture that will be used to copy data from the CPU to the GPU, // the staging texture will then copy to the render texture CD3D11_TEXTURE3D_DESC textureDesc(format, frameSize[0], frameSize[1], frameSize[2], 1, 0, D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ); D3D11_SUBRESOURCE_DATA imgData; imgData.pSysMem = imageRaw; imgData.SysMemPitch = frameSize[0] * bytesPerPixel; imgData.SysMemSlicePitch = frameSize[0] * frameSize[1] * bytesPerPixel; DX::ThrowIfFailed(device->CreateTexture3D(&textureDesc, &imgData, m_volumeStagingTexture.GetAddressOf())); // Create the texture that will be used by the shader to access the current volume to be rendered textureDesc = CD3D11_TEXTURE3D_DESC(format, frameSize[0], frameSize[1], frameSize[2], 1); DX::ThrowIfFailed(device->CreateTexture3D(&textureDesc, &imgData, m_volumeTexture.GetAddressOf())); #if _DEBUG m_volumeTexture->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof("VolumeTexture") - 1, "VolumeTexture"); #endif CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(m_volumeTexture.Get(), format); DX::ThrowIfFailed(device->CreateShaderResourceView(m_volumeTexture.Get(), &srvDesc, m_volumeSRV.GetAddressOf())); #if _DEBUG m_volumeSRV->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof("VolumeSRV") - 1, "VolumeSRV"); #endif // Compute the step size and number of iterations to use // The step size for each component needs to be a ratio of the largest component float maxSize = std::fmaxf(frameSize[0], std::fmaxf(frameSize[1], frameSize[2])); float3 stepSize = float3(1.0f / (frameSize[0] * (maxSize / frameSize[0])), 1.0f / (frameSize[1] * (maxSize / frameSize[1])), 1.0f / (frameSize[2] * (maxSize / frameSize[2]))); XMStoreFloat3(&m_constantBuffer.stepSize, XMLoadFloat3(&(stepSize * m_stepScale))); m_constantBuffer.numIterations = static_cast<uint32>(maxSize * (1.0f / m_stepScale)); float borderColour[4] = { 0.f, 0.f, 0.f, 0.f }; CD3D11_SAMPLER_DESC desc(D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_TEXTURE_ADDRESS_BORDER, D3D11_TEXTURE_ADDRESS_BORDER, D3D11_TEXTURE_ADDRESS_BORDER, 0.f, 3, D3D11_COMPARISON_NEVER, borderColour, 0, 3); DX::ThrowIfFailed(device->CreateSamplerState(&desc, m_samplerState.GetAddressOf())); #if _DEBUG m_samplerState->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof("VolRendSamplerState") - 1, "VolRendSamplerState"); #endif m_volumeReady = true; } //---------------------------------------------------------------------------- void Volume::ReleaseVolumeResources() { m_volumeReady = false; m_volumeStagingTexture.Reset(); m_volumeTexture.Reset(); m_volumeSRV.Reset(); m_samplerState.Reset(); } //---------------------------------------------------------------------------- task<void> Volume::SetOpacityTransferFunctionTypeAsync(TransferFunctionType functionType, uint32 tableSize, const ControlPointList& controlPoints) { return create_task([this, functionType, tableSize, controlPoints]() { std::lock_guard<std::mutex> guard(m_opacityTFMutex); delete m_opacityTransferFunction; switch (functionType) { case Volume::TransferFunction_Piecewise_Linear: { m_opacityTFType = Volume::TransferFunction_Piecewise_Linear; m_opacityTransferFunction = new PiecewiseLinearTransferFunction(); break; } default: throw std::invalid_argument("Function type not recognized."); break; } for (auto& point : controlPoints) { m_opacityTransferFunction->AddControlPoint(point.first, point.second.w); } m_opacityTransferFunction->SetLookupTableSize(tableSize); m_opacityTransferFunction->Update(); }).then([this]() { std::lock_guard<std::mutex> guard(m_opacityTFMutex); ReleaseTFResources(); CreateTFResources(); }); } //---------------------------------------------------------------------------- void Volume::CreateTFResources() { if (m_opacityTransferFunction == nullptr) { return; } if (!m_opacityTransferFunction->IsValid()) { throw std::exception("Transfer function table not valid."); } m_opacityTransferFunction->Update(); m_constantBuffer.lt_maximumXValue = m_opacityTransferFunction->GetMaximumXValue(); m_constantBuffer.lt_arraySize = m_opacityTransferFunction->GetTFLookupTable().GetArraySize(); // Set up GPU memory D3D11_BUFFER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.ByteWidth = sizeof(DirectX::XMFLOAT4) * m_opacityTransferFunction->GetTFLookupTable().GetArraySize(); desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED; desc.StructureByteStride = sizeof(DirectX::XMFLOAT4); D3D11_SUBRESOURCE_DATA bufferBytes = { m_opacityTransferFunction->GetTFLookupTable().GetLookupTableArray(), 0, 0 }; DX::ThrowIfFailed(m_deviceResources->GetD3DDevice()->CreateBuffer(&desc, &bufferBytes, m_opacityLookupTableBuffer.GetAddressOf())); #if _DEBUG m_opacityLookupTableBuffer->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof("OpacityLookupTable") - 1, "OpacityLookupTable"); #endif D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.ViewDimension = D3D11_SRV_DIMENSION_BUFFEREX; srvDesc.BufferEx.FirstElement = 0; srvDesc.Format = DXGI_FORMAT_UNKNOWN; srvDesc.BufferEx.NumElements = m_opacityTransferFunction->GetTFLookupTable().GetArraySize(); DX::ThrowIfFailed(m_deviceResources->GetD3DDevice()->CreateShaderResourceView(m_opacityLookupTableBuffer.Get(), &srvDesc, m_opacityLookupTableSRV.GetAddressOf())); #if _DEBUG m_opacityLookupTableSRV->SetPrivateData(WKPDID_D3DDebugObjectName, sizeof("OpacityLookupTableSRV") - 1, "OpacityLookupTableSRV"); #endif m_tfResourcesReady = true; } //---------------------------------------------------------------------------- void Volume::ReleaseTFResources() { m_tfResourcesReady = false; m_opacityLookupTableSRV.Reset(); m_opacityLookupTableBuffer.Reset(); } } }
#include<iostream> using namespace std; int CenturyFromYear(int year) { int cent; cent = ((year - 1) / 100) + 1; return cent; } int main() { for (int i = 0; i < 3000; i++) { std::cout << "The year " << i << " is " << CenturyFromYear(i) << "c." << std::endl; } return 0; }
#pragma once #include <bits/stdc++.h> #include <variant> #include "dispatcher_semantic_check.h" #include "visitor.h" #include "context.h" #include "llvm/IR/Value.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Function.h" #include "llvm/IR/Type.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Verifier.h" #include "llvm/IR/GlobalVariable.h" ostream& operator<<(ostream& s, const pair<string,vector<int>>& p); class Dispatcher_llvm_gen : public AbstractDispatcher { private: static const int _cpl_int_width = 32; static const int _cpl_char_width = 8; static const int _cpl_bool_width = 1; static const int _cpl_success = 1; llvm::LLVMContext the_context; llvm::IRBuilder<> *builder; llvm::Module* the_module; ContextNoError<std::string, llvm::AllocaInst*> named_values; Context<std::string, int> arr_sz; Context<std::string, int> var_type; Context<std::string, int> func_type; bool isGlobal; int curType; bool hasReturn; public: llvm::Value *ret; Dispatcher_llvm_gen(); // Declare overloads for each kind of node to dispatch void Dispatch(Argument_list&); void Dispatch(Assignment_statement&); void Dispatch(Binary_op&); void Dispatch(Block&); void Dispatch(BlockStatement&); void Dispatch(BooleanLiteral&); void Dispatch(CharacterLiteral&); void Dispatch(ExpressionBracketed&); void Dispatch(ExpressionFunctionCall&); void Dispatch(ExpressionIdentifier&); void Dispatch(ExpressionLiteral&); void Dispatch(For_statement&); void Dispatch(Function_call&); void Dispatch(Function_call_statement&); void Dispatch(Function_decl&); void Dispatch(Function_list&); void Dispatch(If_statement&); void Dispatch(IntegerLiteral&); void Dispatch(Multivar_decl&); void Dispatch(Parameter_list&); void Dispatch(Program&); void Dispatch(Return_statement&); void Dispatch(Statement_list&); void Dispatch(StringLiteral&); void Dispatch(Ternary_op&); void Dispatch(Unary_op&); void Dispatch(UnsignedLiteral&); void Dispatch(Var_decl&); void Dispatch(Variable_list&); void Dispatch(While_statement&); void codeout(); void codeout(std::string); llvm::AllocaInst *create_entry_alloc(llvm::Function*, std::string, int); };
/**************************************************************** * TianGong RenderLab * * Copyright (c) Gaiyitp9. All rights reserved. * * This code is licensed under the MIT License (MIT). * *****************************************************************/ #include "Math/Color.hpp" namespace TG::Math { //----------------------------------------------------------------- // 颜色取自 DirectXColors.h -- C++ Color Math library // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // http://go.microsoft.com/fwlink/?LinkID=615560 //----------------------------------------------------------------- Color Color::AliceBlue { 0.941176534f, 0.972549081f, 1.000000000f, 1.000000000f }; Color Color::AntiqueWhite { 0.980392218f, 0.921568692f, 0.843137324f, 1.000000000f }; Color Color::Aqua { 0.000000000f, 1.000000000f, 1.000000000f, 1.000000000f }; Color Color::Aquamarine { 0.498039246f, 1.000000000f, 0.831372619f, 1.000000000f }; Color Color::Azure { 0.941176534f, 1.000000000f, 1.000000000f, 1.000000000f }; Color Color::Beige { 0.960784376f, 0.960784376f, 0.862745166f, 1.000000000f }; Color Color::Bisque { 1.000000000f, 0.894117713f, 0.768627524f, 1.000000000f }; Color Color::Black { 0.000000000f, 0.000000000f, 0.000000000f, 1.000000000f }; Color Color::Blanchedalmond { 1.000000000f, 0.921568692f, 0.803921640f, 1.000000000f }; Color Color::Blue { 0.000000000f, 0.000000000f, 1.000000000f, 1.000000000f }; Color Color::BlueViolet { 0.541176498f, 0.168627456f, 0.886274576f, 1.000000000f }; Color Color::Brown { 0.647058845f, 0.164705887f, 0.164705887f, 1.000000000f }; Color Color::BurlyWood { 0.870588303f, 0.721568644f, 0.529411793f, 1.000000000f }; Color Color::Chartreuse { 0.498039246f, 1.000000000f, 0.000000000f, 1.000000000f }; Color Color::Chocolate { 0.823529482f, 0.411764741f, 0.117647067f, 1.000000000f }; Color Color::Coral { 1.000000000f, 0.498039246f, 0.313725501f, 1.000000000f }; Color Color::CornflowerBlue { 0.392156899f, 0.584313750f, 0.929411829f, 1.000000000f }; Color Color::Cornsilk { 1.000000000f, 0.972549081f, 0.862745166f, 1.000000000f }; Color Color::Crimson { 0.862745166f, 0.078431375f, 0.235294133f, 1.000000000f }; Color Color::Cyan { 0.000000000f, 1.000000000f, 1.000000000f, 1.000000000f }; Color Color::DarkBlue { 0.000000000f, 0.000000000f, 0.545098066f, 1.000000000f }; Color Color::DarkCyan { 0.000000000f, 0.545098066f, 0.545098066f, 1.000000000f }; Color Color::DarkGoldenrod { 0.721568644f, 0.525490224f, 0.043137256f, 1.000000000f }; Color Color::DarkGrey { 0.662745118f, 0.662745118f, 0.662745118f, 1.000000000f }; Color Color::DarkGreen { 0.000000000f, 0.392156899f, 0.000000000f, 1.000000000f }; Color Color::DarkKhaki { 0.741176486f, 0.717647076f, 0.419607878f, 1.000000000f }; Color Color::DarkMagenta { 0.545098066f, 0.000000000f, 0.545098066f, 1.000000000f }; Color Color::DarkOliverGreen { 0.333333343f, 0.419607878f, 0.184313729f, 1.000000000f }; Color Color::DarkOrange { 1.000000000f, 0.549019635f, 0.000000000f, 1.000000000f }; Color Color::DarkOrchid { 0.600000024f, 0.196078449f, 0.800000072f, 1.000000000f }; Color Color::DarkRed { 0.545098066f, 0.000000000f, 0.000000000f, 1.000000000f }; Color Color::DarkSalmon { 0.913725555f, 0.588235319f, 0.478431404f, 1.000000000f }; Color Color::DarkSeaGreen { 0.560784340f, 0.737254918f, 0.545098066f, 1.000000000f }; Color Color::DarkSlateBlue { 0.282352954f, 0.239215702f, 0.545098066f, 1.000000000f }; Color Color::DarkSlateGray { 0.184313729f, 0.309803933f, 0.309803933f, 1.000000000f }; Color Color::DarkTurquoise { 0.000000000f, 0.807843208f, 0.819607913f, 1.000000000f }; Color Color::DarkViolet { 0.580392182f, 0.000000000f, 0.827451050f, 1.000000000f }; Color Color::DeepPink { 1.000000000f, 0.078431375f, 0.576470613f, 1.000000000f }; Color Color::DeepSkyBlue { 0.000000000f, 0.749019623f, 1.000000000f, 1.000000000f }; Color Color::DimGray { 0.411764741f, 0.411764741f, 0.411764741f, 1.000000000f }; Color Color::DodgerBlue { 0.117647067f, 0.564705908f, 1.000000000f, 1.000000000f }; Color Color::Firebrick { 0.698039234f, 0.133333340f, 0.133333340f, 1.000000000f }; Color Color::FloralWhite { 1.000000000f, 0.980392218f, 0.941176534f, 1.000000000f }; Color Color::ForestGreen { 0.133333340f, 0.545098066f, 0.133333340f, 1.000000000f }; Color Color::Fuchsia { 1.000000000f, 0.000000000f, 1.000000000f, 1.000000000f }; Color Color::Gainsboro { 0.862745166f, 0.862745166f, 0.862745166f, 1.000000000f }; Color Color::GhostWhite { 0.972549081f, 0.972549081f, 1.000000000f, 1.000000000f }; Color Color::Gold { 1.000000000f, 0.843137324f, 0.000000000f, 1.000000000f }; Color Color::Goldenrod { 0.854902029f, 0.647058845f, 0.125490203f, 1.000000000f }; Color Color::Gray { 0.501960814f, 0.501960814f, 0.501960814f, 1.000000000f }; Color Color::Green { 0.000000000f, 0.501960814f, 0.000000000f, 1.000000000f }; Color Color::GreenYellow { 0.678431392f, 1.000000000f, 0.184313729f, 1.000000000f }; Color Color::Honeydew { 0.941176534f, 1.000000000f, 0.941176534f, 1.000000000f }; Color Color::HotPink { 1.000000000f, 0.411764741f, 0.705882370f, 1.000000000f }; Color Color::IndianRed { 0.803921640f, 0.360784322f, 0.360784322f, 1.000000000f }; Color Color::Indigo { 0.294117659f, 0.000000000f, 0.509803951f, 1.000000000f }; Color Color::Ivory { 1.000000000f, 1.000000000f, 0.941176534f, 1.000000000f }; Color Color::Khaki { 0.941176534f, 0.901960850f, 0.549019635f, 1.000000000f }; Color Color::Lavender { 0.901960850f, 0.901960850f, 0.980392218f, 1.000000000f }; Color Color::LavenderBlush { 1.000000000f, 0.941176534f, 0.960784376f, 1.000000000f }; Color Color::LawnGreen { 0.486274540f, 0.988235354f, 0.000000000f, 1.000000000f }; Color Color::LemonChiffon { 1.000000000f, 0.980392218f, 0.803921640f, 1.000000000f }; Color Color::LightBlue { 0.678431392f, 0.847058892f, 0.901960850f, 1.000000000f }; Color Color::LightCoral { 0.941176534f, 0.501960814f, 0.501960814f, 1.000000000f }; Color Color::LightCyan { 0.878431439f, 1.000000000f, 1.000000000f, 1.000000000f }; Color Color::LightGoldenrodYellow { 0.980392218f, 0.980392218f, 0.823529482f, 1.000000000f }; Color Color::LightGreen { 0.564705908f, 0.933333397f, 0.564705908f, 1.000000000f }; Color Color::LightGray { 0.827451050f, 0.827451050f, 0.827451050f, 1.000000000f }; Color Color::LightPink { 1.000000000f, 0.713725507f, 0.756862819f, 1.000000000f }; Color Color::LightSalmon { 1.000000000f, 0.627451003f, 0.478431404f, 1.000000000f }; Color Color::LightSeaGreen { 0.125490203f, 0.698039234f, 0.666666687f, 1.000000000f }; Color Color::LightSkyBlue { 0.529411793f, 0.807843208f, 0.980392218f, 1.000000000f }; Color Color::LightSlateGray { 0.466666698f, 0.533333361f, 0.600000024f, 1.000000000f }; Color Color::LightSteelBlue { 0.690196097f, 0.768627524f, 0.870588303f, 1.000000000f }; Color Color::LightYellow { 1.000000000f, 1.000000000f, 0.878431439f, 1.000000000f }; Color Color::Lime { 0.000000000f, 1.000000000f, 0.000000000f, 1.000000000f }; Color Color::LimeGreen { 0.196078449f, 0.803921640f, 0.196078449f, 1.000000000f }; Color Color::Linen { 0.980392218f, 0.941176534f, 0.901960850f, 1.000000000f }; Color Color::Magenta { 1.000000000f, 0.000000000f, 1.000000000f, 1.000000000f }; Color Color::Maroon { 0.501960814f, 0.000000000f, 0.000000000f, 1.000000000f }; Color Color::MediumAquamarine { 0.400000036f, 0.803921640f, 0.666666687f, 1.000000000f }; Color Color::MediumBlue { 0.000000000f, 0.000000000f, 0.803921640f, 1.000000000f }; Color Color::MediumOrchid { 0.729411781f, 0.333333343f, 0.827451050f, 1.000000000f }; Color Color::MediumPurple { 0.576470613f, 0.439215720f, 0.858823597f, 1.000000000f }; Color Color::MediumSeaGreen { 0.235294133f, 0.701960802f, 0.443137288f, 1.000000000f }; Color Color::MediumSlateBlue { 0.482352972f, 0.407843173f, 0.933333397f, 1.000000000f }; Color Color::MediumSpringGreen { 0.000000000f, 0.980392218f, 0.603921592f, 1.000000000f }; Color Color::MediumTurquoise { 0.282352954f, 0.819607913f, 0.800000072f, 1.000000000f }; Color Color::MediumVioletRed { 0.780392230f, 0.082352944f, 0.521568656f, 1.000000000f }; Color Color::MidnightBlue { 0.098039225f, 0.098039225f, 0.439215720f, 1.000000000f }; Color Color::MintCream { 0.960784376f, 1.000000000f, 0.980392218f, 1.000000000f }; Color Color::MistyRose { 1.000000000f, 0.894117713f, 0.882353008f, 1.000000000f }; Color Color::Moccasin { 1.000000000f, 0.894117713f, 0.709803939f, 1.000000000f }; Color Color::NavajoWhite { 1.000000000f, 0.870588303f, 0.678431392f, 1.000000000f }; Color Color::Navy { 0.000000000f, 0.000000000f, 0.501960814f, 1.000000000f }; Color Color::OldLace { 0.992156923f, 0.960784376f, 0.901960850f, 1.000000000f }; Color Color::Olive { 0.501960814f, 0.501960814f, 0.000000000f, 1.000000000f }; Color Color::OliveDrab { 0.419607878f, 0.556862772f, 0.137254909f, 1.000000000f }; Color Color::Orange { 1.000000000f, 0.647058845f, 0.000000000f, 1.000000000f }; Color Color::OrangeRed { 1.000000000f, 0.270588249f, 0.000000000f, 1.000000000f }; Color Color::Orchid { 0.854902029f, 0.439215720f, 0.839215755f, 1.000000000f }; Color Color::PaleGoldenrod { 0.933333397f, 0.909803987f, 0.666666687f, 1.000000000f }; Color Color::PaleGreen { 0.596078455f, 0.984313786f, 0.596078455f, 1.000000000f }; Color Color::PaleTurquoise { 0.686274529f, 0.933333397f, 0.933333397f, 1.000000000f }; Color Color::PaleVioletRed { 0.858823597f, 0.439215720f, 0.576470613f, 1.000000000f }; Color Color::PapayaWhip { 1.000000000f, 0.937254965f, 0.835294187f, 1.000000000f }; Color Color::PeachPuff { 1.000000000f, 0.854902029f, 0.725490212f, 1.000000000f }; Color Color::Peru { 0.803921640f, 0.521568656f, 0.247058839f, 1.000000000f }; Color Color::Pink { 1.000000000f, 0.752941251f, 0.796078503f, 1.000000000f }; Color Color::Plum { 0.866666734f, 0.627451003f, 0.866666734f, 1.000000000f }; Color Color::PowderBlue { 0.690196097f, 0.878431439f, 0.901960850f, 1.000000000f }; Color Color::Purple { 0.501960814f, 0.000000000f, 0.501960814f, 1.000000000f }; Color Color::Red { 1.000000000f, 0.000000000f, 0.000000000f, 1.000000000f }; Color Color::RosyBrown { 0.737254918f, 0.560784340f, 0.560784340f, 1.000000000f }; Color Color::RoyalBlue { 0.254901975f, 0.411764741f, 0.882353008f, 1.000000000f }; Color Color::SaddleBrown { 0.545098066f, 0.270588249f, 0.074509807f, 1.000000000f }; Color Color::Salmon { 0.980392218f, 0.501960814f, 0.447058856f, 1.000000000f }; Color Color::SandyBrown { 0.956862807f, 0.643137276f, 0.376470625f, 1.000000000f }; Color Color::SeaGreen { 0.180392161f, 0.545098066f, 0.341176480f, 1.000000000f }; Color Color::SeaShell { 1.000000000f, 0.960784376f, 0.933333397f, 1.000000000f }; Color Color::Sienna { 0.627451003f, 0.321568638f, 0.176470593f, 1.000000000f }; Color Color::Silver { 0.752941251f, 0.752941251f, 0.752941251f, 1.000000000f }; Color Color::SkyBlue { 0.529411793f, 0.807843208f, 0.921568692f, 1.000000000f }; Color Color::SlateBlue { 0.415686309f, 0.352941185f, 0.803921640f, 1.000000000f }; Color Color::SlateGray { 0.439215720f, 0.501960814f, 0.564705908f, 1.000000000f }; Color Color::Snow { 1.000000000f, 0.980392218f, 0.980392218f, 1.000000000f }; Color Color::SpringGreen { 0.000000000f, 1.000000000f, 0.498039246f, 1.000000000f }; Color Color::SteelBlue { 0.274509817f, 0.509803951f, 0.705882370f, 1.000000000f }; Color Color::Tan { 0.823529482f, 0.705882370f, 0.549019635f, 1.000000000f }; Color Color::Teal { 0.000000000f, 0.501960814f, 0.501960814f, 1.000000000f }; Color Color::Thistle { 0.847058892f, 0.749019623f, 0.847058892f, 1.000000000f }; Color Color::Tomato { 1.000000000f, 0.388235331f, 0.278431386f, 1.000000000f }; Color Color::Transparent { 0.000000000f, 0.000000000f, 0.000000000f, 0.000000000f }; Color Color::Turquoise { 0.250980407f, 0.878431439f, 0.815686345f, 1.000000000f }; Color Color::Violet { 0.933333397f, 0.509803951f, 0.933333397f, 1.000000000f }; Color Color::Wheat { 0.960784376f, 0.870588303f, 0.701960802f, 1.000000000f }; Color Color::White { 1.000000000f, 1.000000000f, 1.000000000f, 1.000000000f }; Color Color::WhiteSmoke { 0.960784376f, 0.960784376f, 0.960784376f, 1.000000000f }; Color Color::Yellow { 1.000000000f, 1.000000000f, 0.000000000f, 1.000000000f }; Color Color::YellowGreen { 0.603921592f, 0.803921640f, 0.196078449f, 1.000000000f }; }
#include "std_lib_facilities.h" #include <iostream> #include "Token_stream.h" #include "factorial.h" Token_stream ts; // provides get() and putback() double expression(); // ad for use in primary() /// deal with numbers and parentheses double primary() { Token t = ts.get(); switch (t.kind) { case '(': // handle '(' expression ')' { double d = expression(); t = ts.get(); if (t.kind != ')') error("')' expected"); return d; } case '{': { double d = expression(); t = ts.get(); if (t.kind != '}') error("need '}' "); return d; } case '|': // module { double d = expression(); t = ts.get(); if (t.kind != '|') error("'|' expected"); return abs(d); } case number: // we use '8' to represent a number return t.value; case name: return get_value(t.name); case '-': return -primary(); case '+': return primary(); default: { ts.putback(t); error("primary expected"); } } } //the secondary expression is needed to calculate the factorial so that it can work without parentheses double secondary() { double left = primary(); Token t = ts.get(); switch (t.kind) { case '!': { if (fmod(left, 1) != 0) error("for factorial you need integer"); left = factorial(left); t = ts.get(); break; } default: ts.putback(t); } return left; } // For a tertiary expression that performs actions with elements in parentheses. // Decimal logarithm, power, square root double third() { Token t = ts.get(); switch (t.kind) { case pow_: { t = ts.get(); if (t.kind != '(') error("you need '('"); double left = expression(); t = ts.get(); if (t.kind != ',') error("you need ','"); double right = expression(); if (fmod(right, 1) != 0) error("for pow need integer"); //fmod - fractional part when divided by 1 t = ts.get(); if (t.kind != ')') error("you need ')'"); return pow(left, right); } case sqrt_: { t = ts.get(); if (t.kind != '(') error("for sqrt need '('"); double d = expression(); if (d < 0) error("sqrt of less than 0"); d = sqrt(d); t = ts.get(); if (t.kind != ')') error("sqrt need ')'"); return d; } case log10_: { t = ts.get(); if (t.kind != '(') error("for log10 need '('"); double d = expression(); if (d < 0) error("in log10 can't be negative"); d = log10(d); t = ts.get(); if (t.kind != ')') error(" for log10 need ')'"); return d; } default: ts.putback(t); return secondary(); } } /// deal with *, /, and % double term() { double left = third(); Token t = ts.get(); // get the next token from token stream while (true) { switch (t.kind) { case '*': left *= third(); t = ts.get(); break; case '/': { double d = third(); if (d == 0) error("divide by zero"); left /= d; t = ts.get(); break; } //You can also disable the % operation for floating-point arguments (the second option is case) case '%': //int i1=narrow_cast<ini>(left); { //int i2=narrow_cast<ini>(primary()); double d = third(); //if (i2==0) error("%: division by zero"); if (d == 0) error("%: division by zero"); //left=i1%i2; left = fmod(left, d); //t=ts.get(); t = ts.get(); break; //break; } default: ts.putback(t); // put t back into the token stream return left; } } } /// deal with + and - double expression() { double left = term(); // read and evaluate a Term Token t = ts.get(); // get the next token from token stream while (true) { switch (t.kind) { case '+': left += term(); // evaluate Term and add t = ts.get(); break; case '-': left -= term(); // evaluate Term and subtract t = ts.get(); break; default: ts.putback(t); // put t back into the token stream return left; // finally: no more + or -: return the answer } } } double declaration() // We believe that we have already encountered the word "let" // Processing: Name = Expression // Declaration of a variable with A name with an initial value, // specified by the Expression { Token t = ts.get(); if (t.kind != name) error("The variable name is expected in the Declaration"); string var_name = t.name; Token t2 = ts.get(); if (t2.kind != '=') error("Omitted the ' = ' character in the ad", var_name); double d = expression(); define_name(var_name, d); return d; } double statement() { Token t = ts.get(); switch (t.kind) { case let: return declaration(); default: ts.putback(t); return expression(); } } void clean_up_mess() { ts.ignore(print); } void calculate() //Cycle for computing the expression { string iname = "D:/Progs/DAFE_CPP_013/Safuan_Ysupov/calc_cin.txt"; ifstream ist{ iname }; if (!ist) error("can't open file", iname); string oname = "D:/Progs/DAFE_CPP_013/Safuan_Ysupov/calc_cout.txt"; ofstream ost{ oname }; if (!ost) error("can't open file", oname); while (ist) try { ost << prompt; Token t = ts.get(); while (t.kind == print) t = ts.get(); // Discarding output commands if (t.kind == quit) return; ts.putback(t); ost << result << statement() << '\n'; } catch (exception& e) { ost << e.what() << '\n'; // The output of the error message clean_up_mess(); } }
#pragma once #include <SFML/Graphics.hpp> #include <Box2D/Box2D.h> class Ray : public sf::Drawable { private: b2World * m_pWorld; //!< Pointer to the Box2D world sf::VertexArray m_line; //!< Line to render the ray float m_direction; //!< Direction of the ray float m_maxLength; //!< Maximum length of the ray public: Ray() {}; //!< Default constructor Ray(b2World * world, float maxLength, sf::Color colour); //!< Full constructor void draw(sf::RenderTarget& target, sf::RenderStates states) const; void cast(sf::Vector2f start); //!< Cast the ray void setDirection(float direction); //!< Set ray direction };
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 1000 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; int bag[MAXN+10][MAXN+10]; int conV[MAXN+10],infV[MAXN+10]; int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); int kind,num; while( kase-- ){ scanf("%d %d",&kind,&num); for(int i = 0 ; i < kind ; i++ ) scanf("%d %d",&conV[i],&infV[i]); for(int i = 0 ; i <= num ; i++ ) for(int j = 0 ; j <= num ; j++ ) bag[i][j] = INF; bag[0][0] = 0; for(int k = 0 ; k < kind ; k++ ) for(int i = conV[k] ; i <= num ; i++ ) for(int j = infV[k] ; j <= num ; j++ ) if( bag[i-conV[k]][j-infV[k]] != INF ) bag[i][j] = min(bag[i][j],bag[i-conV[k]][j-infV[k]]+1); int ans = INF; for(int i = 0 ; i <= num ; i++ ) for(int j = 0 ; j <= num ; j++ ) if( i*i+j*j == num*num ) ans = min(ans,bag[i][j]); if( ans == INF ) printf("not possible\n"); else printf("%d\n",ans); } return 0; }
/***************************************************************************************************************** * File Name : checkForPairForSum.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page08\checkForPairForSum.h * Created on : Jan 2, 2014 :: 5:51:10 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef CHECKFORPAIRFORSUM_H_ #define CHECKFORPAIRFORSUM_H_ struct pair{ int first; int second; }; vector<pair> getPairForGivenSumON2(vector<int> userInput,int sum){ vector<pair> allPairsForSum; if(userInput.size() == 0){ return allPairsForSum; } unsigned int outerCrawler,innerCrawler; for(outerCrawler = 0;outerCrawler < userInput.size();outerCrawler++){ for(innerCrawler = 0;innerCrawler < userInput.size();innerCrawler++){ if(outerCrawler == innerCrawler){ continue; } if(userInput[innerCrawler] + userInput[outerCrawler] == sum){ pair newPair = (pair)malloc(sizeof(pair)); newPair.first = userInput[outerCrawler]; newPair.second = userInput[innerCrawler]; allPairsForSum.push_back(newPair); } } } } vector<pair> getPairForGivenSumONLOGN(vector<int> userInput,int sum){ vector<pair> allPairsForSum; if(userInput.size() == 0){ return allPairsForSum; } sort(userInput.begin(),userInput.end()); unsigned int startCrawler=0,endCrawler = userInput.size()-1; int currentSum; while(startCrawler < endCrawler){ currentSum = userInput[startCrawler] + userInput[endCrawler]; if(currentSum == sum){ pair newPair = (pair)malloc(sizeof(pair)); newPair.first = userInput[startCrawler]; newPair.second = userInput[endCrawler]; allPairsForSum.push_back(newPair); startCrawler += 1; endCrawler -= 1; }else{ if(currentSum > sum){ endCrawler -= 1; }else{ startCrawler -= 1; } } } } vector<pair> getPairForGivenSumONLOGNBST(vector<int> userInput,int sum){ } vector<pair> getPairForGivenSumON(vector<int> userInput,int sum){ vector<pair> allPairsForSum; if(userInput.size() == 0){ return allPairsForSum; } hash_map<int,unsigned int> frequencyMap; hash_map<int,unsigned int>::iterator itToFrequencyMap; for(unsigned int counter = 0;counter < userInput.size();counter++){ if((itToFrequencyMap = frequencyMap.find(userInput[counter])) != frequencyMap.end()){ frequencyMap[userInput[counter]] += 1; }else{ frequencyMap.insert(pair<int,unsigned int>(userInput[counter],1)); } } for(unsigned int counter = 0;counter < userInput.size();counter++){ if((itToFrequencyMap = frequencyMap.find(sum - userInput[counter])) != frequencyMap.end()){ pair newPair = (pair)malloc(sizeof(pair)); newPair.first = userInput[counter]; newPair.second = itToFrequencyMap->first; } } } #endif /* CHECKFORPAIRFORSUM_H_ */ /************************************************* End code *******************************************************/
/* NAME: Green LEDs functionality test for a display module with TM1638 controller DESCRIPTION: The sketch tests all red LEDs of a display module. - Connect controller's pins to Arduino's pins as follows: - TM1638 pin CLK to Arduino pin D2 - TM1638 pin DIO to Arduino pin D3 - TM1638 pin STB to Arduino pin D4 - TM1638 pin Vcc to Arduino pin 5V - TM1638 pin GND to Arduino pin GND - The sketch is configured to work with all 8 green LEDs with common cathode. - Some display modules are not equipped with two-color LEDs, so that do not use this sketch with modules just with red LEDs. LICENSE: This program is free software; you can redistribute it and/or modify it under the terms of the MIT License (MIT). CREDENTIALS: Author: Libor Gabaj */ #include "gbj_tm1638.h" #define SKETCH "GBJ_TM1638_TEST_LEDS_RED 1.0.0" const unsigned int PERIOD_TEST = 500; // Time in miliseconds between tests const unsigned char PIN_TM1638_CLK = 2; const unsigned char PIN_TM1638_DIO = 3; const unsigned char PIN_TM1638_STB = 4; gbj_tm1638 Sled = gbj_tm1638(PIN_TM1638_CLK, PIN_TM1638_DIO, PIN_TM1638_STB); void errorHandler() { if (Sled.isSuccess()) return; Serial.print("Error: "); Serial.println(Sled.getLastResult()); } void displayTest() { if (Sled.display()) errorHandler(); delay(PERIOD_TEST); } void setup() { Serial.begin(9600); Serial.println(SKETCH); Serial.println("Libraries:"); Serial.println(gbj_tm1638::VERSION); Serial.println("---"); // Initialize controller if (Sled.begin()) { errorHandler(); return; } } void loop() { if (Sled.isError()) return; // Display LEDs one by one for (unsigned char led = 0; led < Sled.getLeds(); led++) { Sled.printLedOnGreen(led); displayTest(); Sled.printLedOff(led); } for (signed char led = Sled.getLeds() - 2; led >= 0; led--) { Sled.printLedOnGreen(led); displayTest(); Sled.printLedOff(led); } displayTest(); // Display LEDs as thermometer for (unsigned char led = 0; led < Sled.getLeds(); led++) { Sled.printLedOnGreen(led); displayTest(); } for (signed char led = Sled.getLeds() - 1; led >=0; led--) { Sled.printLedOff(led); displayTest(); } }
#pragma once #include "Token.h" class Variable : public Token { public: Variable() : Token(3) {} void print(ostream& outs = cout) const { outs << var; } ~Variable() {} private: char var = 'x'; };
#ifndef AD_AMERICANBINOMIALMETHOD_H #define AD_AMERICANBINOMIALMETHOD_H #include "../../BinomialMethod.hpp" template<typename X> class AmericanBinomialMethod : public BinomialMethod<X> { protected: X **asset_price; X **option_price; public: explicit AmericanBinomialMethod(Case<X> *_case); ~AmericanBinomialMethod() override; X getResult() override; protected: void build_asset_price_tree() override; void calculate_payoff_for_initial_cond() override; void calculate_option_values() override; }; #include "AmericanBinomialMethod.tpp" #endif //AD_AMERICANBINOMIALMETHOD_H
/******************************************************************************** ** Form generated from reading UI file 'dimmanuel.ui' ** ** Created: Fri 3. May 09:49:03 2013 ** by: Qt User Interface Compiler version 4.8.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DIMMANUEL_H #define UI_DIMMANUEL_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QPushButton> #include <QtGui/QSlider> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_DimManuel { public: QHBoxLayout *horizontalLayout_2; QVBoxLayout *verticalLayout_3; QHBoxLayout *horizontalLayout_5; QHBoxLayout *horizontalLayout_6; QLabel *label_2; QVBoxLayout *verticalLayout_2; QLabel *label_parametre1; QSlider *horizontalSlider; QHBoxLayout *horizontalLayout_11; QHBoxLayout *horizontalLayout_14; QLabel *label_3; QVBoxLayout *verticalLayout_4; QLabel *label_parametre2; QSlider *horizontalSlider_2; QHBoxLayout *horizontalLayout_12; QHBoxLayout *horizontalLayout_13; QLabel *label_4; QVBoxLayout *verticalLayout_5; QLabel *label_parametre3; QSlider *horizontalSlider_3; QHBoxLayout *horizontalLayout_10; QHBoxLayout *horizontalLayout_15; QLabel *label_5; QVBoxLayout *verticalLayout_6; QLabel *label_parametre4; QSlider *horizontalSlider_4; QHBoxLayout *horizontalLayout_21; QHBoxLayout *horizontalLayout_23; QLabel *label_7; QVBoxLayout *verticalLayout_7; QLabel *label_parametre5; QSlider *horizontalSlider_5; QHBoxLayout *horizontalLayout_18; QHBoxLayout *horizontalLayout_20; QLabel *label_6; QVBoxLayout *verticalLayout_8; QLabel *label_parametre6; QSlider *horizontalSlider_6; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout_3; QHBoxLayout *horizontalLayout_17; QHBoxLayout *horizontalLayout; QPushButton *pushButton; QHBoxLayout *horizontalLayout_16; QPushButton *pushButton_Retour; void setupUi(QWidget *DimManuel) { if (DimManuel->objectName().isEmpty()) DimManuel->setObjectName(QString::fromUtf8("DimManuel")); DimManuel->resize(1280, 800); horizontalLayout_2 = new QHBoxLayout(DimManuel); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); verticalLayout_3 = new QVBoxLayout(); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); horizontalLayout_5 = new QHBoxLayout(); horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5")); horizontalLayout_6 = new QHBoxLayout(); horizontalLayout_6->setObjectName(QString::fromUtf8("horizontalLayout_6")); horizontalLayout_6->setSizeConstraint(QLayout::SetFixedSize); label_2 = new QLabel(DimManuel); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setMaximumSize(QSize(200, 16777215)); QFont font; font.setPointSize(12); label_2->setFont(font); label_2->setAlignment(Qt::AlignCenter); horizontalLayout_6->addWidget(label_2); horizontalLayout_5->addLayout(horizontalLayout_6); verticalLayout_2 = new QVBoxLayout(); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); label_parametre1 = new QLabel(DimManuel); label_parametre1->setObjectName(QString::fromUtf8("label_parametre1")); label_parametre1->setAlignment(Qt::AlignCenter); verticalLayout_2->addWidget(label_parametre1); horizontalSlider = new QSlider(DimManuel); horizontalSlider->setObjectName(QString::fromUtf8("horizontalSlider")); horizontalSlider->setMaximumSize(QSize(300, 100)); horizontalSlider->setMouseTracking(true); horizontalSlider->setMaximum(100); horizontalSlider->setPageStep(1); horizontalSlider->setOrientation(Qt::Horizontal); horizontalSlider->setTickPosition(QSlider::NoTicks); verticalLayout_2->addWidget(horizontalSlider); horizontalLayout_5->addLayout(verticalLayout_2); horizontalLayout_5->setStretch(0, 50); horizontalLayout_5->setStretch(1, 50); verticalLayout_3->addLayout(horizontalLayout_5); horizontalLayout_11 = new QHBoxLayout(); horizontalLayout_11->setObjectName(QString::fromUtf8("horizontalLayout_11")); horizontalLayout_14 = new QHBoxLayout(); horizontalLayout_14->setObjectName(QString::fromUtf8("horizontalLayout_14")); horizontalLayout_14->setSizeConstraint(QLayout::SetFixedSize); label_3 = new QLabel(DimManuel); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setMaximumSize(QSize(200, 16777215)); label_3->setFont(font); label_3->setAlignment(Qt::AlignCenter); horizontalLayout_14->addWidget(label_3); horizontalLayout_11->addLayout(horizontalLayout_14); verticalLayout_4 = new QVBoxLayout(); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); label_parametre2 = new QLabel(DimManuel); label_parametre2->setObjectName(QString::fromUtf8("label_parametre2")); label_parametre2->setAlignment(Qt::AlignCenter); verticalLayout_4->addWidget(label_parametre2); horizontalSlider_2 = new QSlider(DimManuel); horizontalSlider_2->setObjectName(QString::fromUtf8("horizontalSlider_2")); horizontalSlider_2->setMaximumSize(QSize(300, 100)); horizontalSlider_2->setMaximum(100); horizontalSlider_2->setPageStep(1); horizontalSlider_2->setOrientation(Qt::Horizontal); verticalLayout_4->addWidget(horizontalSlider_2); horizontalLayout_11->addLayout(verticalLayout_4); horizontalLayout_11->setStretch(0, 50); horizontalLayout_11->setStretch(1, 50); verticalLayout_3->addLayout(horizontalLayout_11); horizontalLayout_12 = new QHBoxLayout(); horizontalLayout_12->setObjectName(QString::fromUtf8("horizontalLayout_12")); horizontalLayout_13 = new QHBoxLayout(); horizontalLayout_13->setObjectName(QString::fromUtf8("horizontalLayout_13")); horizontalLayout_13->setSizeConstraint(QLayout::SetFixedSize); label_4 = new QLabel(DimManuel); label_4->setObjectName(QString::fromUtf8("label_4")); label_4->setMaximumSize(QSize(200, 16777215)); label_4->setFont(font); label_4->setAlignment(Qt::AlignCenter); horizontalLayout_13->addWidget(label_4); horizontalLayout_12->addLayout(horizontalLayout_13); verticalLayout_5 = new QVBoxLayout(); verticalLayout_5->setObjectName(QString::fromUtf8("verticalLayout_5")); label_parametre3 = new QLabel(DimManuel); label_parametre3->setObjectName(QString::fromUtf8("label_parametre3")); label_parametre3->setAlignment(Qt::AlignCenter); verticalLayout_5->addWidget(label_parametre3); horizontalSlider_3 = new QSlider(DimManuel); horizontalSlider_3->setObjectName(QString::fromUtf8("horizontalSlider_3")); horizontalSlider_3->setMaximumSize(QSize(300, 100)); horizontalSlider_3->setMaximum(100); horizontalSlider_3->setPageStep(1); horizontalSlider_3->setOrientation(Qt::Horizontal); verticalLayout_5->addWidget(horizontalSlider_3); horizontalLayout_12->addLayout(verticalLayout_5); horizontalLayout_12->setStretch(0, 50); horizontalLayout_12->setStretch(1, 50); verticalLayout_3->addLayout(horizontalLayout_12); horizontalLayout_10 = new QHBoxLayout(); horizontalLayout_10->setObjectName(QString::fromUtf8("horizontalLayout_10")); horizontalLayout_15 = new QHBoxLayout(); horizontalLayout_15->setObjectName(QString::fromUtf8("horizontalLayout_15")); horizontalLayout_15->setSizeConstraint(QLayout::SetFixedSize); label_5 = new QLabel(DimManuel); label_5->setObjectName(QString::fromUtf8("label_5")); label_5->setMaximumSize(QSize(200, 16777215)); label_5->setFont(font); label_5->setAlignment(Qt::AlignCenter); horizontalLayout_15->addWidget(label_5); horizontalLayout_10->addLayout(horizontalLayout_15); verticalLayout_6 = new QVBoxLayout(); verticalLayout_6->setObjectName(QString::fromUtf8("verticalLayout_6")); label_parametre4 = new QLabel(DimManuel); label_parametre4->setObjectName(QString::fromUtf8("label_parametre4")); label_parametre4->setContextMenuPolicy(Qt::DefaultContextMenu); label_parametre4->setAlignment(Qt::AlignCenter); verticalLayout_6->addWidget(label_parametre4); horizontalSlider_4 = new QSlider(DimManuel); horizontalSlider_4->setObjectName(QString::fromUtf8("horizontalSlider_4")); horizontalSlider_4->setMaximumSize(QSize(300, 100)); horizontalSlider_4->setMaximum(100); horizontalSlider_4->setPageStep(1); horizontalSlider_4->setOrientation(Qt::Horizontal); verticalLayout_6->addWidget(horizontalSlider_4); horizontalLayout_10->addLayout(verticalLayout_6); horizontalLayout_10->setStretch(0, 50); horizontalLayout_10->setStretch(1, 50); verticalLayout_3->addLayout(horizontalLayout_10); horizontalLayout_21 = new QHBoxLayout(); horizontalLayout_21->setObjectName(QString::fromUtf8("horizontalLayout_21")); horizontalLayout_23 = new QHBoxLayout(); horizontalLayout_23->setObjectName(QString::fromUtf8("horizontalLayout_23")); horizontalLayout_23->setSizeConstraint(QLayout::SetFixedSize); label_7 = new QLabel(DimManuel); label_7->setObjectName(QString::fromUtf8("label_7")); label_7->setMaximumSize(QSize(200, 16777215)); label_7->setFont(font); label_7->setAlignment(Qt::AlignCenter); horizontalLayout_23->addWidget(label_7); horizontalLayout_21->addLayout(horizontalLayout_23); verticalLayout_7 = new QVBoxLayout(); verticalLayout_7->setObjectName(QString::fromUtf8("verticalLayout_7")); label_parametre5 = new QLabel(DimManuel); label_parametre5->setObjectName(QString::fromUtf8("label_parametre5")); label_parametre5->setAlignment(Qt::AlignCenter); verticalLayout_7->addWidget(label_parametre5); horizontalSlider_5 = new QSlider(DimManuel); horizontalSlider_5->setObjectName(QString::fromUtf8("horizontalSlider_5")); horizontalSlider_5->setMaximumSize(QSize(300, 100)); horizontalSlider_5->setMaximum(100); horizontalSlider_5->setPageStep(1); horizontalSlider_5->setOrientation(Qt::Horizontal); verticalLayout_7->addWidget(horizontalSlider_5); horizontalLayout_21->addLayout(verticalLayout_7); horizontalLayout_21->setStretch(0, 50); horizontalLayout_21->setStretch(1, 50); verticalLayout_3->addLayout(horizontalLayout_21); horizontalLayout_18 = new QHBoxLayout(); horizontalLayout_18->setObjectName(QString::fromUtf8("horizontalLayout_18")); horizontalLayout_20 = new QHBoxLayout(); horizontalLayout_20->setObjectName(QString::fromUtf8("horizontalLayout_20")); horizontalLayout_20->setSizeConstraint(QLayout::SetFixedSize); label_6 = new QLabel(DimManuel); label_6->setObjectName(QString::fromUtf8("label_6")); label_6->setMaximumSize(QSize(200, 16777215)); label_6->setFont(font); label_6->setAlignment(Qt::AlignCenter); horizontalLayout_20->addWidget(label_6); horizontalLayout_18->addLayout(horizontalLayout_20); verticalLayout_8 = new QVBoxLayout(); verticalLayout_8->setObjectName(QString::fromUtf8("verticalLayout_8")); label_parametre6 = new QLabel(DimManuel); label_parametre6->setObjectName(QString::fromUtf8("label_parametre6")); label_parametre6->setAlignment(Qt::AlignCenter); verticalLayout_8->addWidget(label_parametre6); horizontalSlider_6 = new QSlider(DimManuel); horizontalSlider_6->setObjectName(QString::fromUtf8("horizontalSlider_6")); horizontalSlider_6->setMaximumSize(QSize(300, 100)); horizontalSlider_6->setMaximum(100); horizontalSlider_6->setPageStep(1); horizontalSlider_6->setOrientation(Qt::Horizontal); verticalLayout_8->addWidget(horizontalSlider_6); horizontalLayout_18->addLayout(verticalLayout_8); horizontalLayout_18->setStretch(0, 50); horizontalLayout_18->setStretch(1, 50); verticalLayout_3->addLayout(horizontalLayout_18); horizontalLayout_2->addLayout(verticalLayout_3); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); verticalLayout->addLayout(horizontalLayout_3); horizontalLayout_17 = new QHBoxLayout(); horizontalLayout_17->setObjectName(QString::fromUtf8("horizontalLayout_17")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); pushButton = new QPushButton(DimManuel); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setMaximumSize(QSize(1280, 800)); horizontalLayout->addWidget(pushButton); horizontalLayout_17->addLayout(horizontalLayout); horizontalLayout_16 = new QHBoxLayout(); horizontalLayout_16->setObjectName(QString::fromUtf8("horizontalLayout_16")); pushButton_Retour = new QPushButton(DimManuel); pushButton_Retour->setObjectName(QString::fromUtf8("pushButton_Retour")); pushButton_Retour->setMaximumSize(QSize(1280, 800)); horizontalLayout_16->addWidget(pushButton_Retour); horizontalLayout_17->addLayout(horizontalLayout_16); verticalLayout->addLayout(horizontalLayout_17); verticalLayout->setStretch(0, 80); verticalLayout->setStretch(1, 20); horizontalLayout_2->addLayout(verticalLayout); horizontalLayout_2->setStretch(0, 70); horizontalLayout_2->setStretch(1, 30); retranslateUi(DimManuel); QMetaObject::connectSlotsByName(DimManuel); } // setupUi void retranslateUi(QWidget *DimManuel) { DimManuel->setWindowTitle(QApplication::translate("DimManuel", "Form", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("DimManuel", "Param\303\250tre 1:", 0, QApplication::UnicodeUTF8)); label_parametre1->setText(QApplication::translate("DimManuel", "TextLabel", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("DimManuel", "Param\303\250tre 2:", 0, QApplication::UnicodeUTF8)); label_parametre2->setText(QApplication::translate("DimManuel", "TextLabel", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("DimManuel", "Param\303\250tre 3:", 0, QApplication::UnicodeUTF8)); label_parametre3->setText(QApplication::translate("DimManuel", "TextLabel", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("DimManuel", "Param\303\250tre 4:", 0, QApplication::UnicodeUTF8)); label_parametre4->setText(QApplication::translate("DimManuel", "TextLabel", 0, QApplication::UnicodeUTF8)); label_7->setText(QApplication::translate("DimManuel", "Param\303\250tre 5:", 0, QApplication::UnicodeUTF8)); label_parametre5->setText(QApplication::translate("DimManuel", "TextLabel", 0, QApplication::UnicodeUTF8)); label_6->setText(QApplication::translate("DimManuel", "Param\303\250tre 6:", 0, QApplication::UnicodeUTF8)); label_parametre6->setText(QApplication::translate("DimManuel", "TextLabel", 0, QApplication::UnicodeUTF8)); pushButton->setText(QApplication::translate("DimManuel", "Simuler", 0, QApplication::UnicodeUTF8)); pushButton_Retour->setText(QApplication::translate("DimManuel", "Retour", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class DimManuel: public Ui_DimManuel {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DIMMANUEL_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef WIDGET_RUNTIME_SUPPORT # ifdef WIDGET_RUNTIME_UNITE_SUPPORT #include "WebServerDeviceHandler.h" #include "WebServerPrefs.h" #include "adjunct/quick/webserver/controller/WebServerSettingsContext.h" namespace { const uni_char* DEFAULT_DEVICE_NAMES[] = { UNI_L("home"), UNI_L("work"), UNI_L("office"), UNI_L("notebook"), UNI_L("school"), }; } WebServerDeviceHandler::WebServerDeviceHandler() : m_taking_over_device(FALSE) { } WebServerDeviceHandler::~WebServerDeviceHandler() { OpStatus::Ignore(ReleaseDevice()); } OP_STATUS WebServerDeviceHandler::Init() { return OpStatus::OK; } OP_STATUS WebServerDeviceHandler::RegisterDevice() { OP_STATUS result = OpStatus::ERR; const OpStringC& device_name = WebServerPrefs::ReadDeviceName(); if (device_name.HasContent()) { OpString install_id; g_desktop_account_manager->GetInstallID(install_id); OpString username; RETURN_IF_ERROR(username.Set(g_desktop_account_manager->GetUsername())); OpString password; RETURN_IF_ERROR(password.Set(g_desktop_account_manager->GetPassword())); result = g_desktop_account_manager->Authenticate( username, password, device_name, install_id); } return result; } OP_STATUS WebServerDeviceHandler::ReleaseDevice() { OP_STATUS result = OpStatus::ERR; const OpStringC& device_name = WebServerPrefs::ReadDeviceName(); if (device_name.HasContent()) { OpString username; RETURN_IF_ERROR(username.Set(g_desktop_account_manager->GetUsername())); OpString password; RETURN_IF_ERROR(password.Set(g_desktop_account_manager->GetPassword())); result = g_desktop_account_manager->ReleaseDevice( username, password, device_name); } return result; } OP_STATUS WebServerDeviceHandler::TakeOverDevice() { RETURN_IF_ERROR(g_desktop_account_manager->AddListener(this)); RETURN_IF_ERROR(ReleaseDevice()); m_taking_over_device = TRUE; return OpStatus::OK; // ...and continue in OnOperaAccountReleaseDevice()... } void WebServerDeviceHandler::OnOperaAccountReleaseDevice(OperaAuthError error) { // Error comments copied from // WebServerManager::OnOperaAccountReleaseDevice() switch (error) { // code 400: missing argument/malformed URL. This REALLY shouldn't // happen. case AUTH_ERROR_PARSER: // code 403/404: seems to happen when another computer took over the // computer name and this computer is trying to disable case AUTH_ACCOUNT_AUTH_FAILURE: // code 411: invalid device name case AUTH_ACCOUNT_AUTH_INVALID_KEY: // There shouldn't really be an error here. OP_ASSERT(!"Unexpected auth error"); // Fall through. case AUTH_OK: if (m_taking_over_device) { // Finalize device take-over now. m_taking_over_device = FALSE; g_desktop_account_manager->RemoveListener(this); RegisterDevice(); } break; default: // Ignore ; } } OP_STATUS WebServerDeviceHandler::AddDefaultDeviceNames( WebServerSettingsContext& settings) { OpAutoPtr<OpString> name; for (size_t i = 0; i < ARRAY_SIZE(DEFAULT_DEVICE_NAMES); ++i) { name.reset(OP_NEW(OpString, ())); if (NULL != name.get()) { RETURN_IF_ERROR(name->Set(DEFAULT_DEVICE_NAMES[i])); RETURN_IF_ERROR(settings.AddDeviceNameSuggestion(name.get())); name.release(); } } return OpStatus::OK; } # endif // WIDGET_RUNTIME_UNITE_SUPPORT #endif // WIDGET_RUNTIME_SUPPORT
#include "InputManager.h" #include "InputActionButton.h" #include "Game.h" #include "GameFramework.h" #include "Logfile.h" namespace WGF { InputManager::InputManager() { //ctor GameFramework::GetSingleton().GetLogfile().Log("The InputManager greets the World: \"Hello World!\""); } void InputManager::Init() { GameFramework::GetSingleton().GetLogfile().Log("InputManager initializing..."); //create the common actions if necessary //needs to access the InputManager via the Framework so it has to be available there and I think it's not until it's finished construction if(Game::mCommonButtonActions.size() == 0) { GameFramework::GetSingleton().GetLogfile().Log("- creating common actions"); InputListener* framework = GameFramework::GetSingletonPtr(); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_UP, "@MOVE_UP_FORWARD", "@MOVE_UP_FORWARD_DESC", framework, sf::Key::Up)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_DOWN, "@MOVE_DOWN_BACKWARD", "@MOVE_DOWN_BACKWARD_DESC", framework, sf::Key::Down)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_LEFT, "@MOVE_TURN_LEFT", "@MOVE_TURN_LEFT_DESC", framework, sf::Key::Left)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_RIGHT, "@MOVE_TURN_RIGHT", "@MOVE_TURN_RIGHT_DESC", framework, sf::Key::Right)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ATTACK, "@ATTACK", "@ATTACK_DESC", framework, sf::Key::LShift)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ATTACK2, "@ATTACK2", "@ATTACK2_DESC", framework, sf::Key::LControl)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_USE, "@USE", "@USE_DESC", framework, sf::Key::E)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_JUMP, "@JUMP", "@JUMP_DESC", framework, sf::Key::Space)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM1, "@ITEM1", "@ITEM1_DESC", framework, sf::Key::Num1)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM2, "@ITEM2", "@ITEM2_DESC", framework, sf::Key::Num2)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM3, "@ITEM3", "@ITEM3_DESC", framework, sf::Key::Num3)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM4, "@ITEM4", "@ITEM4_DESC", framework, sf::Key::Num4)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM5, "@ITEM5", "@ITEM5_DESC", framework, sf::Key::Num5)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM6, "@ITEM6", "@ITEM6_DESC", framework, sf::Key::Num6)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM7, "@ITEM7", "@ITEM7_DESC", framework, sf::Key::Num7)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM8, "@ITEM8", "@ITEM8_DESC", framework, sf::Key::Num8)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM9, "@ITEM9", "@ITEM9_DESC", framework, sf::Key::Num9)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_ITEM10, "@ITEM10", "@ITEM10_DESC", framework, sf::Key::Num0)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_PAUSE, "@PAUSE", "@PAUSE_DESC", framework, sf::Key::P)); Game::mCommonButtonActions.push_back(new InputActionButton(Game::ACT_STOP, "@STOP", "@STOP_DESC", framework, sf::Key::Escape)); } GameFramework::GetSingleton().GetLogfile().Log("InputManager initialized!"); } InputManager::~InputManager() { //dtor for(std::vector<InputActionButton*>::iterator it = Game::mCommonButtonActions.begin(); it != Game::mCommonButtonActions.end(); ++it) { delete (*it); } Game::mCommonButtonActions.clear(); for(std::map<InputListener*, GameInputMapping*>::iterator it = mInputMappings.begin(); it != mInputMappings.end(); ++it) { delete it->second; } } void InputManager::KeyPressed (const sf::Event::KeyEvent& keyEvent) { TellAboutKeyEvent(GameFramework::GetSingletonPtr(), keyEvent, true); if(GameFramework::GetSingleton().GetCurrentGame()) { TellAboutKeyEvent(GameFramework::GetSingleton().GetCurrentGame(), keyEvent, true); } } void InputManager::KeyReleased (const sf::Event::KeyEvent& keyEvent) { TellAboutKeyEvent(GameFramework::GetSingletonPtr(), keyEvent, false); if(GameFramework::GetSingleton().GetCurrentGame()) { TellAboutKeyEvent(GameFramework::GetSingleton().GetCurrentGame(), keyEvent, false); } } void InputManager::TellAboutKeyEvent(InputListener* who, const sf::Event::KeyEvent& keyEvent, const bool pressed) { //are there any key-action-mappings for this listener? std::map<InputListener*, GameInputMapping*>::iterator inputMapping = mInputMappings.find(who); //whether we have yet checked the GameFramework, our fallback bool searchedForGameFramework = (who == GameFramework::GetSingletonPtr()); if(inputMapping == mInputMappings.end()) { //if not: are there any for the game framework? if(!searchedForGameFramework && (inputMapping = mInputMappings.find(GameFramework::GetSingletonPtr())) == mInputMappings.end()) { //if not: return return; } else { searchedForGameFramework = true; } } //Does this key do anything? std::map<sf::Key::Code, InputActionButton*>::iterator action = inputMapping->second->KeyboardActions.find(keyEvent.Code); //if not: does it do something for the framework (provided that's not what's been checked before) if(!searchedForGameFramework && action == inputMapping->second->KeyboardActions.end()) { inputMapping = mInputMappings.find(GameFramework::GetSingletonPtr()); if(inputMapping == mInputMappings.end()) { return; } action = inputMapping->second->KeyboardActions.find(keyEvent.Code); } if(action != inputMapping->second->KeyboardActions.end()) { action->second->mIsPressed = pressed; if(pressed) { who->ButtonPressed(action->second); } else { who->ButtonReleased(action->second); } } } void InputManager::Unregister(InputAction* action) { std::map<InputListener*, GameInputMapping*>::iterator IMIt = mInputMappings.find(action->GetOwner()); if(IMIt == mInputMappings.end()) { return; } // Look for the action in the actions without assigned buttons for(std::vector<InputAction*>::iterator UAfind = IMIt->second->UnassignedActions.begin(); UAfind != IMIt->second->UnassignedActions.end(); ++UAfind) { if(*UAfind != action) continue; IMIt->second->UnassignedActions.erase(UAfind); //an action shouldn't be saved more than once return; } // Look for the action in the actions with assigned keyboard buttons for(std::map<sf::Key::Code, InputActionButton*>::iterator it = IMIt->second->KeyboardActions.begin(); it != IMIt->second->KeyboardActions.end(); ++it) { if(it->second == action) { IMIt->second->KeyboardActions.erase(it); //an action shouldn't be saved more than once return; } } } void InputManager::RegisterAction(InputActionButton* action) { GetInputMapping(action->GetOwner())->UnassignedActions.push_back(action); } void InputManager::RegisterAction(InputActionButton* action, sf::Key::Code key, const bool overwrite) { InputListener* framework = GameFramework::GetSingletonPtr(); //check if another action from the action's game uses this key GameInputMapping* IM = GetInputMapping(action->GetOwner()); std::map<sf::Key::Code, InputActionButton*>::iterator find = IM->KeyboardActions.find(key); if(find != IM->KeyboardActions.end()) { //there is one... if(overwrite) { IM->UnassignedActions.push_back(find->second); } else { IM->UnassignedActions.push_back(action); return; } } //else check if a default action uses this key GameInputMapping* IM2 = GetInputMapping(framework); find = IM2->KeyboardActions.find(key); if(find != IM2->KeyboardActions.end()) { //if so... if(overwrite) { IM2->UnassignedActions.push_back(find->second); } else { IM->UnassignedActions.push_back(action); return; } } //else assign this action to the key IM->KeyboardActions[key] = action; } InputManager::GameInputMapping* InputManager::GetInputMapping(InputListener* which) { std::map<InputListener*, GameInputMapping*>::iterator find = mInputMappings.find(which); if(find == mInputMappings.end()) { mInputMappings[which] = new GameInputMapping; } return mInputMappings[which]; } } // namespace WGF
#include <iostream> #include <fstream> #include <unordered_set>; #include <vector> #include <algorithm> using namespace std; int main() { unordered_set<int> nrSet; vector<int> numbers; unordered_set<int> pairs; const int year = 2020; ifstream input; input.open("input1"); ofstream output; output.open("output1B"); int nr; while (input >> nr) { numbers.push_back(nr); nrSet.insert(nr); } for (int i = 0; i < (int)numbers.size(); i++) { for (int j = i + 1; j < (int)numbers.size(); j++) { if (nrSet.find(year - numbers[i] - numbers[j]) != nrSet.end()) { pairs.insert(numbers[i] * numbers[j] * (year - numbers[i] - numbers[j])); } } } for (auto &pair : pairs) { output << pair << '\n'; } input.close(); output.close(); return 0; }
/** * @file Policy_Allocator.hpp * * @brief This header contains the definition of Policy Allocator. * * The Policy Allocator is built using preprocesor templates to provide * compile-time functionality through aggregate ("Policy") classes. * * This is made possible due to template's form of aspect-oriented programming. * * @author Matthew Rodusek (matthew.rodusek@gmail.com) * @date January 1, 2015 */ #ifndef VALKNUT_POLICY_MEMORY_ALLOCATOR_HPP_ #define VALKNUT_POLICY_MEMORY_ALLOCATOR_HPP_ #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // valknut::memory libraries #include <valknut/memory/Memory_Pool.hpp> #include <valknut/memory/Allocator.hpp> namespace valknut{ //////////////////////////////////////////////////////////////////////////// /// @class valknut::Policy_Allocator /// /// Class handling allocation and deallocation of memory /// /// @tparam Allocation_Policy Defines how memory is allocated/deallocated /// @tparam Thread_Policy Defines how threads are handled /// @tparam Tracking_Policy Defines how memory is tracked /// @tparam Tagging_Policy Defines how memory is tagged /// @tparam Bound_Policy Defines how memory boundaries are checked /// /// @ingroup memory //////////////////////////////////////////////////////////////////////////// template< class Allocation_Policy, class Thread_Policy, class Tracking_Policy, class Tagging_Policy > class Policy_Allocator : public Allocator{ //-------------------------------------------------------------------------- // Public Member Types //-------------------------------------------------------------------------- public: using Allocator::void_pointer; using Allocator::const_void_pointer; using Allocator::size_type; using Allocator::alignment_type; using Allocator::offset_type; using Allocator::difference_type; typedef Memory_Pool pool_type; typedef Policy_Allocator allocator_type; typedef Allocation_Policy allocation_type; typedef Thread_Policy thread_type; typedef Tracking_Policy tracking_type; typedef Tagging_Policy tagging_type; typedef void bound_type; //-------------------------------------------------------------------------- // Constructor / Assignment / Destructor //-------------------------------------------------------------------------- public: /// /// @brief Constructs an allocator with no specified memory location for /// heap or static-based allocators. /// Policy_Allocator( ); /// /// @brief Constructs an allocator in the specified memory location /// Policy_Allocator( void* memory, size_type memory_size ); /// /// @brief Constructs an allocator in the specified memory pool /// template<class Pool> Policy_Allocator( Pool& pool ); //-------------------------------------------------------------------------- // Capacity //-------------------------------------------------------------------------- public: /// /// @brief Gets the current amount of bytes used by this allocator. /// /// @note the number of bytes includes offsets, headers, and alignments /// /// @return the number of bytes used /// inline virtual size_type size( ) const VALKNUT_NOEXCEPT; /// /// @brief Gets the maximum amount of bytes this allocator can handle /// /// @return the max number of bytes this allocator can handle /// inline virtual size_type max_size( ) const VALKNUT_NOEXCEPT; /// /// @brief Gets the pointer to the memory used by this allocator /// /// @return the pointer to the memory in this allocator /// inline virtual const void* ptr() const VALKNUT_NOEXCEPT; /// /// @brief Checks if a pointer resides in the allocator's memory space /// /// @return true if the pointer is in the allocator /// inline virtual bool in_allocator( const void_pointer ptr ) const VALKNUT_NOEXCEPT; /// /// @brief Gets a reference to the pool used in this allocator /// /// @return the reference to the pool /// inline const pool_type& get_pool() const VALKNUT_NOEXCEPT; //-------------------------------------------------------------------------- // Allocation //-------------------------------------------------------------------------- public: /// /// @brief Allocate a given amount of memory /// /// @tparam T the type of object to allocate memory to /// /// @param size the size of the allocation /// @param align the alignment of the allocation /// /// @returns A pointer to the newly allocated memory, or nullptr on error /// virtual void* allocate( size_type size, size_type align = Allocator::default_alignment_size, size_type offset = 0 ) VALKNUT_NOEXCEPT; //-------------------------------------------------------------------------- // Deallocation //-------------------------------------------------------------------------- public: /// /// @brief Deallocate memory at the specified pointer /// /// @note This method must be called to deallocate memory that has been /// allocated using allocate() /// /// @param ptr The pointer to deallocate /// virtual void deallocate( void* ptr ) VALKNUT_NOEXCEPT; //-------------------------------------------------------------------------- // Clearing the allocator //-------------------------------------------------------------------------- public: /// /// @brief Resets all memory handled by this allocator. This method does /// not call destructors /// /// @note This is not supported by all allocation policies, and may assert /// virtual void reset( ); //-------------------------------------------------------------------------- // Private Members //-------------------------------------------------------------------------- private: pool_type m_memory_pool; /// The memory pool allocation_type m_allocation_policy; /// Memory allocation policy thread_type m_thread_policy; /// Threading policy tracking_type m_tracking_policy; /// Memory Tracking (for debugging) tagging_type m_tagging_policy; /// Tag Policy // bound_type m_bound_policy; /// Bound policy }; } // namespace valknut //----------------------------------------------------------------------------- #include "detail/Policy_Allocator.inl" #endif /* VALKNUT_POLICY_MEMORY_ALLOCATOR_HPP_ */
// // C++ Interface: ProgramData // // Description: 与iptux相关的程序数据 // // // Author: Jally <jallyx@163.com>, (C) 2008 // // Copyright: See COPYING file that comes with this distribution // // #ifndef PROGRAMDATA_H #define PROGRAMDATA_H #include "sys.h" #include "net.h" #include "deplib.h" /* flags // 消息(:7);当有消息时自动打开聊天窗口 // 图标(:6);程序启动后只显示托盘图标而不显示面板 // 传输(:5);当有文件传输时自动打开文件传输窗口 // enter(:4);使用Enter键发送消息 // 历史(:3);关闭好友对话框后自动清空聊天历史 // 日志(:2);开启日志记录功能 // 黑名单(:1);不允许删除的好友再出现 // 共享(:0);好友请求本人的共享文件时需要得到确认 *//* sndfgs // 传输(:2);文件传输完成后需要播放提示音 // 消息(:1);有消息到来后需要播放提示音 // 声音(:0);是否需要提示音 */ class ProgramData { public: ProgramData(); ~ProgramData(); void InitSublayer(); void WriteProgData(); GSList *CopyNetSegment(); char *FindNetSegDescription(in_addr_t ipv4); char *nickname; //昵称 * char *mygroup; //所属群组 * char *myicon; //个人头像 * char *path; //存档路径 * char *sign; //个性签名 * char *codeset; //候选编码 * char *encode; //默认通信编码 * char *palicon; //默认头像 * char *font; //面板字体 * uint8_t flags; //6 图标,5 传输:4 enter:3 历史:2 日志:1 黑名单:0 共享 char *transtip; //传输完成提示声音 * char *msgtip; //消息到来提示声音 * double volume; //音量控制 uint8_t sndfgs; //2 传输:1 消息:0 声音 GSList *netseg; //需要通知登录的IP段 GRegex *urlregex; //URL正则表达式 GdkCursor *xcursor, *lcursor; //光标 GtkTextTagTable *table; //tag table guint cnxnid; //GConfClient连接ID struct timeval timestamp; //程序数据时间戳 pthread_mutex_t mutex; //锁 private: void ReadProgData(); void AddGconfNotify(); void CheckIconTheme(); void CreateRegex(); void CreateCursor(); void CreateTagTable(); void WriteNetSegment(GConfClient *client); void ReadNetSegment(GConfClient *client); private: static void GconfNotifyFunc(GConfClient *client, guint cnxnid, GConfEntry *entry, ProgramData *progdt); }; #endif
#include <AFMotor.h> const int DOORSENSOR_OPEN=A1; const int DOORSENSOR_CLOSED=A0; AF_DCMotor motor(3, MOTOR12_64KHZ); void setup() { Serial.begin(9600); Serial.println("Motor test!"); motor.setSpeed(200); pinMode(A0, INPUT); pinMode(A1, INPUT); digitalWrite(A0,HIGH); digitalWrite(A1,HIGH); } void loop() { Serial.println("trying to open"); while ((digitalRead(DOORSENSOR_OPEN)==HIGH) ) { Serial.println("not open yet"); motor.run(FORWARD); } Serial.println("it is open"); motor.run(RELEASE); delay(1000); Serial.println("trying to close"); while ((digitalRead(DOORSENSOR_CLOSED)==HIGH) ) { Serial.println("not closed yet"); motor.run(BACKWARD); } Serial.println("it is closed"); motor.run(RELEASE); delay(1000); }
#ifndef __CP_WORLD_H__ #define __CP_WORLD_H__ #include "cocos2d.h" #include "CPContactListener.h" #include <unordered_set> #define CONTACTS_SET std::unordered_set<CPContact, CPContact::CPContactHasher> // Forward declarations class CPBody; // Physics world that stores all the bodies and evaluates their contacts in step function // When world is destroyed, all memory for all of its bodies is cleared class CPWorld { public: // All bodies handled by this world. Public so that user can iterate through them easily std::vector<CPBody*> bodies; // All contacts detected in this world. Public so that user can iterate through them easily CONTACTS_SET currentContacts; // Finds collisions, sends events (and can move physics simulation if we were actually simulating something) void step(float dT); // Add a new listener that will react to collisions void addContactListener(CPContactListener* listener) { assert(listener); listeners_.push_back(listener); } // Removes a contact listener void removeContactListener(CPContactListener* listener) { assert(listener); listeners_.erase(std::find(listeners_.begin(), listeners_.end(), listener)); } // Called from newly created bodies // Adds these bodies and sets them for evaluation void onCreatedBody(CPBody* body) { assert(body); bodies.push_back(body); forEvaluation_.insert(body); } // Called from bodies when they are moved or changed in other ways // Sets these bodies for evaluation void onManipulatedBody(CPBody* body) { assert(body); forEvaluation_.insert(body); } // Destructor clears all memory for all bodies ~CPWorld(); private: std::vector<CPContactListener*> listeners_; std::unordered_set<CPBody*> forEvaluation_; // we need set so that one body isn't added for evaluation several times }; #endif // __CP_WORLD_H__
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifdef USE_SDL #ifndef BAJKA_TTFFONT_H_ #define BAJKA_TTFFONT_H_ #include <SDL/SDL_ttf.h> #include "ReflectionMacros.h" #include "IFont.h" namespace View { class TTFFont : public IFont { public: C__ (std::string const &) TTFFont (std::string const &path); C_ (std::string const &, int) TTFFont (std::string const &path, int ptSize); C_ (std::string const &, int, long int) TTFFont (std::string const &path, int ptSize, long int index); ~TTFFont (); enum Type { SOLID, SHADED, BLENDED }; enum Style { NORMAL = TTF_STYLE_NORMAL, BOLD = TTF_STYLE_BOLD, ITALIC = TTF_STYLE_ITALIC, UNDERLINE = TTF_STYLE_UNDERLINE, STRIKETHROUGH = TTF_STYLE_STRIKETHROUGH }; // TODO Tu jest jakoś źle chyba. enum Hinting { FULL, LIGHT, MONO, NONE }; Ptr <IBitmap> render (std::string const &text, View::Color const &fgColor, View::Color const &bgColor); Ptr <IBitmap> renderMulti (std::string const &text, View::Color const &fgColor, View::Color const &bgColor, TextAlign textAlign = LEFT); // TODO Typ zwracany powinien być Hinting int getHinting () const; m_ (setHinting) void setHinting (int hint); int getType () const { return type; } m_ (setType) void setType (int t) { type = t; } bool getUtf8 () const { return utf8; } m_ (setUtf8) void setUtf8 (bool b) { utf8 = b; } int getStyle () const; m_ (setStyle) void setStyle (int i); int getOutline () const; m_ (setOutline) void setOutline (int i); bool getKerning () const; m_ (setKerning) void setKerning (bool b); private: void open (std::string const &path, int ptSize = -1, long int index = -1); private: TTF_Font *font; int type; // TODO to powinno być typu Type bool utf8; E_ (TTFFont) }; } /* namespace View */ #endif /* TTFFONT_H_ */ #endif
#include <cmath> #include <thread> #include <ros/ros.h> #include <ros/console.h> #include <image_transport/image_transport.h> #include <image_geometry/pinhole_camera_model.h> #include <tf2_ros/transform_listener.h> #include <tf2_sensor_msgs/tf2_sensor_msgs.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/TransformStamped.h> #include <cv_bridge/cv_bridge.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <pcl_conversions/pcl_conversions.h> sensor_msgs::CameraInfo CreateCameraInfo(cv::Size frame_size, std::string frame_id) { sensor_msgs::CameraInfo ci; double fx = double(frame_size.width) / 2; double fy = double(frame_size.height) / 2; cv::Mat K = (cv::Mat_<double>(3, 3) << fx, 0, double(frame_size.width) / 2, 0, fy, double(frame_size.height) / 2, 0, 0, 1); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) ci.K[i * 3 + j] = K.at<double>(i, j); for (int i = 0; i < 5; ++i) ci.D.push_back(0); cv::Mat P = (cv::Mat_<double>(3, 4) << fx, 0, double(frame_size.width) / 2, 0, 0, fy, double(frame_size.height) / 2, 0, 0, 0, 1, 0); for (int i = 0; i < 3; ++i) for (int j = 0; j < 4; ++j) ci.P[i * 4 + j] = P.at<double>(i, j); ci.width = frame_size.width; ci.height = frame_size.height; ci.distortion_model = "plumb_bob"; ci.header.frame_id = frame_id; ci.header.stamp = ros::Time::now(); return ci; } class CloudConverter { public: tf2_ros::Buffer tfBuffer; tf2_ros::TransformListener tfListener; image_geometry::PinholeCameraModel cameraModel; sensor_msgs::CameraInfo info_msg; cv::Size cameraSize; std::string world_frame; ros::NodeHandle nh; image_transport::ImageTransport it; image_transport::CameraPublisher pub_; ros::Subscriber cloud_sub; double max_depth; std::string camera_frame; int camera_width; int camera_height; int num_threads; bool postprocess_x; int x_max_gap; bool postprocess_y; int y_max_gap; CloudConverter(): nh("~"), it(nh), tfListener(tfBuffer) { pub_ = it.advertiseCamera("/depth/image_raw", 1); if (!nh.getParam("world_frame", world_frame)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read world_frame parameter."); } if (!nh.getParam("max_depth", max_depth)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read max_depth parameter."); } if (!nh.getParam("camera_frame", camera_frame)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read camera_frame parameter."); } if (!nh.getParam("camera_width", camera_width)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read camera_width parameter."); } if (!nh.getParam("camera_height", camera_height)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read camera_height parameter."); } if (!nh.getParam("postprocess_x", postprocess_x)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read postprocess_x parameter."); } if (postprocess_x) { if (!nh.getParam("x_max_gap", x_max_gap)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read x_max_gap parameter. Setting to 1."); x_max_gap = 1; } ROS_INFO_STREAM("x_max_gap: " << x_max_gap); } if (!nh.getParam("postprocess_y", postprocess_y)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read postprocess_y parameter."); } if (postprocess_y) { if (!nh.getParam("y_max_gap", y_max_gap)) { ROS_WARN("[LASER_TO_POINTCLOUD2] Cannot read y_max_gap parameter. Setting to 1."); y_max_gap = 1; } } cloud_sub = nh.subscribe<sensor_msgs::PointCloud2>( "/cloud_in", 1, &CloudConverter::NewCloud2Callback, this); cameraSize = cv::Size(camera_width, camera_height); info_msg = CreateCameraInfo(cameraSize, camera_frame); cameraModel.fromCameraInfo(info_msg); num_threads = std::max(std::thread::hardware_concurrency(), 1u); ROS_INFO_STREAM("Using " << num_threads << " threads to optimize processing."); } ~CloudConverter(); void NewCloud2Callback(const sensor_msgs::PointCloud2::ConstPtr& cmsg); private: void CastPoints(pcl::PointCloud<pcl::PointXYZ>& cloud, int start_idx, int end_idx, cv::Mat& image); void InterpolateLine(cv::Mat& image, int start_idx, int end_idx, int step_size, int max_gap); void InterpolateRowsRange(cv::Mat& image, int row_min, int row_max, int max_gap); void InterpolateColsRange(cv::Mat& image, int col_min, int col_max, int max_gap); }; CloudConverter::~CloudConverter() { ros::param::del("~"); ros::shutdown(); } void CloudConverter::NewCloud2Callback(const sensor_msgs::PointCloud2::ConstPtr& cmsg) { ros::Time begin = ros::Time::now(); ROS_DEBUG_STREAM("Starting the callback!"); cv::Mat image = cv::Mat::zeros(cameraSize, CV_16UC1); geometry_msgs::TransformStamped transform; sensor_msgs::PointCloud2 cloud_out; ROS_DEBUG_STREAM("RECEIVED new message!"); try { ros::Time acquisition_time = cmsg->header.stamp; ROS_DEBUG_STREAM("Asking can tf?"); // std::string error_msg; // if (!tfBuffer.canTransform( // cameraModel.tfFrame(), cameraModel.stamp(), // world_frame, acquisition_time + ros::Duration().fromSec(0.2), // world_frame, ros::Duration(1.0/25)), // &error_msg){ // ROS_WARN_STREAM("[POINTCLOUD2_TO_DEPTH] Cannot find tf transforms for this message. " // "Skipping... The tfs are: " << cameraModel.tfFrame() << " and " << world_frame << // " acquisition_time: " << acquisition_time << " cameraModel.stamp(): " << cameraModel.stamp() << // " with error: " << error_msg); // return; // } // or ? tfBuffer.lookupTransform(cameraModel.tfFrame(), world_frame, ros::Time::now()) // if (!tfBuffer.canTransform( // cameraModel.tfFrame(), // world_frame, // acquisition_time + ros::Duration().fromSec(0.2), // ros::Duration(1.0/25))){ // ROS_WARN_STREAM("[POINTCLOUD2_TO_DEPTH] Cannot find tf transforms for this message. " // "Skipping... The tfs are: " << cameraModel.tfFrame() << " and " << world_frame << // " acquisition_time: " << acquisition_time); // return; // } ROS_DEBUG_STREAM("CAN do the transform!!!"); transform = tfBuffer.lookupTransform(cameraModel.tfFrame(), world_frame, ros::Time(0), //acquisition_time - ros::Duration().fromSec(45), ros::Duration(1.0 / 25)); ROS_DEBUG_STREAM("Will perform the transform"); tf2::doTransform(*cmsg, cloud_out, transform); ROS_DEBUG_STREAM("Converted the pointcloud tf."); } catch (tf2::TransformException& ex) { ROS_WARN("[POINTCLOUD2_TO_DEPTH] TF exception:\n%s", ex.what()); ROS_WARN_STREAM("At: " << cmsg->header.stamp); return; } ROS_DEBUG_STREAM("Done with transformations!"); // Convert to pcl::PointCloud pcl::PointCloud<pcl::PointXYZ> pcl_cloud; pcl::fromROSMsg(cloud_out, pcl_cloud); int cloudsize = pcl_cloud.width * pcl_cloud.height; std::thread t[num_threads]; int batch = std::ceil(float(cloudsize) / num_threads); // Start threads for (int i = 0; i < num_threads; ++i) { t[i] = std::thread(&CloudConverter::CastPoints, this, std::ref(pcl_cloud), batch * i, std::min(batch * (i + 1), cloudsize), std::ref(image)); } // Join threads for (int i = 0; i < num_threads; ++i) { t[i].join(); } if (postprocess_x) { batch = std::ceil(float(image.rows) / num_threads); for (int i = 0; i < num_threads; ++i) { t[i] = std::thread(&CloudConverter::InterpolateRowsRange, this, std::ref(image), batch * i, std::min(batch * (i + 1), image.rows), x_max_gap); } for (int i = 0; i < num_threads; ++i) { t[i].join(); } } if (postprocess_y) { batch = std::ceil(float(image.cols) / num_threads); for (int i = 0; i < num_threads; ++i) { t[i] = std::thread(&CloudConverter::InterpolateColsRange, this, std::ref(image), batch * i, std::min(batch * (i + 1), image.cols), y_max_gap); } for (int i = 0; i < num_threads; ++i) { t[i].join(); } } ROS_DEBUG_STREAM("Publishing!"); sensor_msgs::ImagePtr image_msg = cv_bridge::CvImage(std_msgs::Header(), "mono16" , image).toImageMsg(); pub_.publish(*image_msg, info_msg); ROS_DEBUG_STREAM("Endign the callback"); ROS_INFO_STREAM("Callback timer: " << ros::Time::now() - begin << " sec."); } void CloudConverter::CastPoints(pcl::PointCloud<pcl::PointXYZ>& cloud, int start_idx, int end_idx, cv::Mat& image) { ushort* image_data = (ushort*)(image.data); for (int i = start_idx; i < end_idx; ++i) { // ROS_DEBUG_STREAM("Laser (x,y,z) = " << pcl_cloud.points[i]); cv::Point3d pt_cv(cloud.points[i].x, cloud.points[i].y, cloud.points[i].z); cv::Point2d uv = cameraModel.project3dToPixel(pt_cv); // ROS_WARN_STREAM("Projected to: " << uv); if (!cv::Rect(0, 0, image.cols, image.rows).contains(uv)) continue; ushort depth_value = 0; if (pt_cv.z <= max_depth) depth_value = ushort(pt_cv.z * 1000); // Convert metres to mm. image_data[uint(uv.y) * image.cols + uint(uv.x)] = depth_value; } } void CloudConverter::InterpolateRowsRange(cv::Mat& image, int row_min, int row_max, int max_gap) { for (int i = row_min; i < row_max; ++i) { InterpolateLine(image, i * image.cols, (i + 1) * image.cols, 1, max_gap); } } void CloudConverter::InterpolateColsRange(cv::Mat& image, int col_min, int col_max, int max_gap) { for (int i = col_min; i < col_max; ++i) { InterpolateLine(image, i, i + image.cols * (image.rows - 1), image.cols, max_gap); // ROS_INFO_STREAM("COLS: " << i << " to " << i + image.cols * (image.rows - 1)); } } void CloudConverter::InterpolateLine(cv::Mat& image, int start_idx, int end_idx, int step_size, int max_gap) { // skip the first zero pixels int last_non_zero = -1; int dist = 0; ushort* image_data = (ushort*)(image.data); for (int i = start_idx; i < end_idx; i += step_size, ++dist) { // ROS_INFO_STREAM("Inner idx: " << i); if (image_data[i] == 0) continue; if (last_non_zero != -1) { // current i has some pixel value // Look how far away we were // int dist = (i - last_non_zero) / step_size; if (dist < max_gap && dist > 1) { // ROS_INFO_STREAM("Using at dist " << dist << " max_gap " << max_gap << " id: " << // last_non_zero << " " << i); double gradient = std::abs( double(image_data[last_non_zero] - image_data[i]) / dist); // ROS_INFO_STREAM("gradient: " << gradient); // In range - go back and fill in the gap int k = 0; for (int j = last_non_zero; j < i; j += step_size, ++k) { image_data[j] = ushort(image_data[last_non_zero] + gradient * k); } } } last_non_zero = i; dist = 0; } } int main(int argc, char** argv) { ros::init(argc, argv, "pointcloud2_to_depth"); // if( ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug) ) { // ros::console::notifyLoggerLevelsChanged(); // } CloudConverter converter; ros::spin(); ros::param::del("~"); ros::shutdown(); return 0; }
#line 71 "NextNumber.cc" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; class NextNumber { public: int getNextNumber(int N) { string n; while (N) { if (N&1) n+='1'; else n+='0'; N >>=1; } n+='0'; reverse(n.begin(), n.end()); next_permutation(n.begin(), n.end()); int ret = 0; int mul = 1; for(int i = n.size() - 1; i >= 0; --i) { if (n[i] == '1') ret += mul; mul <<= 1; } return ret; } }; // Powered by FileEdit // Powered by TZTester 1.01 [25-Feb-2003] // Powered by CodeProcessor
#include "SceneManager.h" #include "Scene.h" SceneManager::SceneManager() : activeScene(nullptr) { } SceneManager::~SceneManager() { } void SceneManager::addScene(Scene* scene) { this->scenes.emplace_back(scene); this->activeScene = scene; } void SceneManager::setScenes(const ScenesList& scenes) { this->scenes = scenes; } bool SceneManager::removeScene(Scene* scene) { auto it = std::find(this->scenes.begin(), this->scenes.end(), scene); if (it != this->scenes.end()) { this->scenes.erase(it); return true; } else return false; } Scene *SceneManager::getActiveScene() { return this->activeScene; }
#include <iostream> #include <string> #include <cstring> #include <sstream> #include <vector> #include <algorithm> #include <iterator> #include <fstream> //files #include <errno.h> //errors #include <stdio.h> //printf #include <unistd.h> // sys calls #include <sys/types.h> // O_ constants #include <sys/ipc.h> // IPC_ constnts #include <sys/msg.h> // SysV message queue char in [1000]; struct message { long mtype; char mtext[80]; }; int main(int argc, char** argv) { struct message mg; long dummy; key_t key = ftok("/tmp/msg.temp", 1); int msgid = msgget(key,0); int res = msgrcv(msgid,&mg,(sizeof(mg)-sizeof(dummy)),0,0); if (res > 0){ std::ofstream log; log.open("/home/box/message.txt", std::ios::out); log << mg.mtext << std::endl; log.close(); mg.mtext[res-1] = '\0'; std::cout << "size:" << res << std::endl; std::cout << "received:" << mg.mtext << std::endl; } else { return -1*res; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #if defined(SVG_SUPPORT) && defined(SVG_DOM) && defined(SVG_TINY_12) #include "modules/svg/src/svgpch.h" #include "modules/svg/src/SVGPaint.h" #include "modules/svg/src/svgdom/svgdomrgbcolorimpl.h" SVGDOMRGBColorImpl::SVGDOMRGBColorImpl(SVGObject* color) : m_color_val(color) { OP_ASSERT(color->Type() == SVGOBJECT_PAINT || color->Type() == SVGOBJECT_COLOR); SVGObject::IncRef(m_color_val); } /* virtual */ SVGDOMRGBColorImpl::~SVGDOMRGBColorImpl() { SVGObject::DecRef(m_color_val); } /* virtual */ const char* SVGDOMRGBColorImpl::GetDOMName() { return "SVGRGBColor"; } OP_STATUS SVGDOMRGBColorImpl::GetRGBColor(UINT32 &rgbcolor) { if(m_color_val->Type() == SVGOBJECT_PAINT) { SVGPaint& paint = static_cast<SVGPaintObject*>(m_color_val)->GetPaint(); // It's possible though unlikely that URI_RGBCOLOR, URI_RGBCOLOR_ICCCOLOR should be here too. if (paint.GetPaintType() == SVGPaint::RGBCOLOR || paint.GetPaintType() == SVGPaint::RGBCOLOR_ICCCOLOR) { rgbcolor = paint.GetRGBColor(); } else return OpStatus::ERR_OUT_OF_RANGE; } else if(m_color_val->Type() == SVGOBJECT_COLOR) { SVGColor& color = static_cast<SVGColorObject*>(m_color_val)->GetColor(); if (color.GetColorType() == SVGColor::SVGCOLOR_RGBCOLOR || color.GetColorType() == SVGColor::SVGCOLOR_RGBCOLOR_ICCCOLOR) { rgbcolor = color.GetRGBColor(); } else return OpStatus::ERR_OUT_OF_RANGE; } else { return OpStatus::ERR; } return OpStatus::OK; } /* virtual */ OP_STATUS SVGDOMRGBColorImpl::GetComponent(int type, double& val) { if(m_color_val) { UINT32 rgbcolor; RETURN_IF_ERROR(GetRGBColor(rgbcolor)); switch(type) { case 0: val = GetRValue(rgbcolor); break; case 1: val = GetGValue(rgbcolor); break; case 2: val = GetBValue(rgbcolor); break; } return OpStatus::OK; } return OpStatus::ERR; } /* virtual */ OP_STATUS SVGDOMRGBColorImpl::SetComponent(int type, double val) { if(m_color_val) { UINT32 rgbcolor; RETURN_IF_ERROR(GetRGBColor(rgbcolor)); UINT8 r = GetRValue(rgbcolor); UINT8 g = GetGValue(rgbcolor); UINT8 b = GetBValue(rgbcolor); switch(type) { case 0: r = (UINT8)val; break; case 1: g = (UINT8)val; break; case 2: b = (UINT8)val; break; } if(m_color_val->Type() == SVGOBJECT_PAINT) { SVGPaint& paint = static_cast<SVGPaintObject*>(m_color_val)->GetPaint(); paint.SetRGBColor(r, g, b); } else if(m_color_val->Type() == SVGOBJECT_COLOR) { SVGColor& color = static_cast<SVGColorObject*>(m_color_val)->GetColor(); color.SetRGBColor(r, g, b); } return OpStatus::OK; } return OpStatus::ERR; } #endif // SVG_SUPPORT && SVG_DOM && SVG_TINY_12
// Copyright (c) 2020 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Aspect_TrackedDevicePose_HeaderFile #define _Aspect_TrackedDevicePose_HeaderFile #include <gp_Trsf.hxx> #include <NCollection_Array1.hxx> //! Describes a single pose for a tracked object (for XR). struct Aspect_TrackedDevicePose { gp_Trsf Orientation; //!< device to absolute transformation gp_Vec Velocity; //!< velocity in tracker space in m/s gp_Vec AngularVelocity; //!< angular velocity in radians/s bool IsValidPose; //!< indicates valid pose bool IsConnectedDevice; //!< indicates connected state //! Empty constructor. Aspect_TrackedDevicePose() : IsValidPose (false), IsConnectedDevice (false) {} }; //! Array of tracked poses. typedef NCollection_Array1<Aspect_TrackedDevicePose> Aspect_TrackedDevicePoseArray; #endif // _Aspect_TrackedDevicePose_HeaderFile
#include "ICloudManager.h" namespace android { BpCloudManager::BpCloudManager(const sp<IBinder>& impl) : BpInterface<ICloudManager>(impl) { } void BpCloudManager::test() { printf("Client call server test method\n"); Parcel data, reply; data.writeInterfaceToken(ICloudManager::getInterfaceDescriptor()); remote()->transact(TEST, data, &reply); int code = reply.readExceptionCode(); printf("Server exepction code: %d\n", code); } void BpCloudManager::print(const char* str) { printf("Client call server print method\n"); Parcel data, reply; data.writeInterfaceToken(ICloudManager::getInterfaceDescriptor()); data.writeString16(String16(str)); remote()->transact(PRINT, data, &reply); int code = reply.readExceptionCode(); printf("Server exepction code: %d\n", code); } int BpCloudManager::add(int a, int b) { printf("Client call server add method\n"); Parcel data, reply; data.writeInterfaceToken(ICloudManager::getInterfaceDescriptor()); data.writeInt32(a); data.writeInt32(b); remote()->transact(ADD, data, &reply); int code = reply.readExceptionCode(); int result; reply.readInt32(&result); printf("Server exepction code: %d\n", code); return result; } } int main() { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder = sm->getService(String16("cloudservice")); sp<ICloudManager> cs = interface_cast<ICloudManager>(binder); cs->test(); cs->print("Hello world"); int result=cs->add(2,3); printf("client receive add result from server : %d\n",result); return 0; }
#ifndef __POINTLOCATOR_H__ #define __POINTLOCATOR_H__ #include <dax/Types.h> #include <dax/cont/UniformGrid.h> #include <dax/math/Precision.h> #include <dax/cont/Scheduler.h> #include <dax/cont/DeviceAdapter.h> #include <dax/cont/internal/DeviceAdapterAlgorithm.h> #include <dax/exec/WorkletMapField.h> #include "PointLocatorExec.h" using namespace dax::cont; class PointLocator { public: PointLocator(); virtual ~PointLocator(); void setAutomatic(bool automatic) { this->automatic = automatic; } void setPointsPerBucket(int ppb) { pointsPerBucket = ppb; } void setDimensions(int x, int y, int z); void setBounds(float x, float y, float z); void setPoints(const std::vector<dax::Vector3>& points); void build(); // smart getter function that only becomes valid // after you setPoints, // it returns the number of cells per dimension depending on // whether it's automatic mode or manual mode dax::Id3 getDimensions() const { return dimensions(); } std::vector<dax::Vector3> getSortPoints() const; std::vector<dax::Id> getPointStarts() const; std::vector<int> getPointCounts() const; dax::Id locatePoint(const dax::Vector3& point) const; std::vector<dax::Vector3> getBucketPoints(const dax::Id& bucketId) const; PointLocatorExec prepareExecutionObject() const; protected: // when automatic is true, // grid resolution is calculated automatically, // when false, user needs to specify the grid spacing // default to be true bool automatic; // average points per bucket, // used to compute the grid resolution in automatic mode. // defaut to be 3 int pointsPerBucket; dax::Vector3 Bounds; dax::Id3 Dimensions; ArrayHandle<dax::Vector3> hSortPoints; ArrayHandle<dax::Id> hPointStarts; ArrayHandle<dax::Id> hPointCounts; ArrayHandle<dax::Id> mapPoints2Bin(); ArrayHandle<dax::Id> sortPoints(ArrayHandle<dax::Id> hOriBucketIds); void formatBucketIds(ArrayHandle<dax::Id> hBucketIds); dax::Id binPoint(const dax::Vector3& point) const; dax::Vector3 bounds() const; dax::Id3 dimensions() const; int bucketCount() const; UniformGrid<> grid() const; private: }; #endif //__POINTLOCATOR_H__
#pragma once #include "Vector.h" class Light { public: Light(); Light(float, float, float); Light(float); float GetRedIntensity(); void SetRedIntensity(const float); float GetGreenIntensity(); void SetGreenIntensity(const float); float GetBlueIntensity(); void SetBlueIntensity(const float); protected: // colour values ranging 0-255 float _iRed; float _iGreen; float _iBlue; };
#include <sstream> #include <dirent.h> #include <iostream> #include <string> //#include <ctime.h> #include "cloud.h" //This is the constructor method Cloud::Cloud(std::string backgroundPath, float x_pos, float y_pos, int cloudId) { m_CloudId = cloudId; m_Texture.loadFromFile(backgroundPath); m_Sprite.setTexture(m_Texture); m_Sprite.setPosition(x_pos, y_pos); m_Active = false; m_StartingYpos = y_pos; srand((int)time(0) * 10); m_SpriteSpeed = (rand() % 200); } void Cloud::randomizeHeight() { srand((int)time(0) * (m_CloudId*10)); float height = (rand() % (m_CloudId*150)) - 100; m_Sprite.setPosition(-200, height); } void Cloud::randomizeSpeed() { srand((int)time(0) * (m_CloudId * 10)); m_SpriteSpeed = (rand() % 200); } void Cloud::move() { m_Sprite.setPosition( m_Sprite.getPosition().x + (m_SpriteSpeed * dt.asSeconds()), m_Sprite.getPosition().y); } bool Cloud::isActive() { dt = clock.restart(); return m_Active; } void Cloud::setActive(bool active) { m_Active = active; } float Cloud::getXPos() { return m_Sprite.getPosition().x; } sf::Sprite Cloud::getSprite() { return m_Sprite; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * spoon / Arjan van Leeuwen (arjanl) */ #ifndef WIDGET_THUMBNAIL_GENERATOR_H #define WIDGET_THUMBNAIL_GENERATOR_H #include "modules/img/image.h" #include "modules/skin/OpSkinManager.h" class OpWidget; class OpBrowserView; class WidgetThumbnailGenerator : public TransparentBackgroundListener { public: /** Constructor * @param widget Widget to generate thumbnails for */ WidgetThumbnailGenerator(OpWidget& widget); /** Generate a thumbnail of the current state of the widget * @param thumbnail_width Desired width of the thumbnail * @param thumbnail_height Desired height of the thumbnail * @param high_quality TRUE for higher quality thumbnails - default is FALSE */ Image GenerateThumbnail(int thumbnail_width, int thumbnail_height, BOOL high_quality = FALSE); /** Generate a screen shot of the current state of the widget */ Image GenerateSnapshot(); /** @return The scale (in percent) that this thumbnail is being painted at */ int GetScale() const; int GetThumbnailWidth() const { return m_thumbnail_width; } int GetThumbnailHeight() const { return m_thumbnail_height; } // TransparentBackgroundListener - needed to any persona image we might use, usually for speed dial only virtual void OnBackgroundCleared(OpPainter *painter, const OpRect& clear_rect); private: Image GenerateThumbnail(); OP_STATUS PrepareForPainting(); void PaintWhiteBackground(); OP_STATUS PaintThumbnail(); OP_STATUS PaintSnapshot(); void PaintBrowserViewThumbnails(OpWidget* widget); void PaintBrowserViewThumbnail(OpBrowserView* browser_view); OpRect ScaleRect(const OpRect& rect); void CleanupAfterPainting(); OpWidget& m_widget; int m_thumbnail_width; int m_thumbnail_height; OpBitmap* m_bitmap; OpPainter* m_painter; Image m_thumbnail; BOOL m_no_scale; // TRUE if no scaling is to be performed BOOL m_high_quality; // TRUE for higher quality thumbnails }; #endif // WIDGET_THUMBNAIL_GENERATOR_H
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "11000" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif long long male[105],female[105]; int num; male[0] = 0; female[0] = 1; for(int i = 1 ; i < 105 ; i++ ){ male[i] = female[i-1]+male[i-1]; female[i] = male[i-1]+1; } while( ~scanf("%d",&num) && num >= 0 ) printf("%lld %lld\n",male[num],male[num]+female[num] ); return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/logging/QLoggerConstants.h> namespace quic { folly::StringPiece vantagePointString(VantagePoint vantagePoint) noexcept { switch (vantagePoint) { case VantagePoint::Client: return kQLogClientVantagePoint; case VantagePoint::Server: return kQLogServerVantagePoint; } folly::assume_unreachable(); } folly::StringPiece toQlogString(FrameType frame) { switch (frame) { case FrameType::PADDING: return "padding"; case FrameType::PING: return "ping"; case FrameType::ACK: return "ack"; case FrameType::ACK_ECN: return "ack_ecn"; case FrameType::RST_STREAM: return "rst_stream"; case FrameType::STOP_SENDING: return "stop_sending"; case FrameType::CRYPTO_FRAME: return "crypto_frame"; case FrameType::NEW_TOKEN: return "new_token"; case FrameType::STREAM: case FrameType::STREAM_FIN: case FrameType::STREAM_LEN: case FrameType::STREAM_LEN_FIN: case FrameType::STREAM_OFF: case FrameType::STREAM_OFF_FIN: case FrameType::STREAM_OFF_LEN: case FrameType::STREAM_OFF_LEN_FIN: return "stream"; case FrameType::MAX_DATA: return "max_data"; case FrameType::MAX_STREAM_DATA: return "max_stream_data"; case FrameType::MAX_STREAMS_BIDI: case FrameType::MAX_STREAMS_UNI: return "max_streams"; case FrameType::DATA_BLOCKED: return "data_blocked"; case FrameType::STREAM_DATA_BLOCKED: return "stream_data_blocked"; case FrameType::STREAMS_BLOCKED_BIDI: case FrameType::STREAMS_BLOCKED_UNI: return "streams_blocked"; case FrameType::NEW_CONNECTION_ID: return "new_connection_id"; case FrameType::RETIRE_CONNECTION_ID: return "retire_connection_id"; case FrameType::PATH_CHALLENGE: return "path_challenge"; case FrameType::PATH_RESPONSE: return "path_response"; case FrameType::CONNECTION_CLOSE: case FrameType::CONNECTION_CLOSE_APP_ERR: return "connection_close"; case FrameType::HANDSHAKE_DONE: return "handshake_done"; case FrameType::DATAGRAM: case FrameType::DATAGRAM_LEN: return "datagram"; case FrameType::KNOB: return "knob"; case FrameType::ACK_FREQUENCY: return "ack_frequency"; case FrameType::IMMEDIATE_ACK: return "immediate_ack"; case FrameType::GROUP_STREAM: case FrameType::GROUP_STREAM_FIN: case FrameType::GROUP_STREAM_LEN: case FrameType::GROUP_STREAM_LEN_FIN: case FrameType::GROUP_STREAM_OFF: case FrameType::GROUP_STREAM_OFF_FIN: case FrameType::GROUP_STREAM_OFF_LEN: case FrameType::GROUP_STREAM_OFF_LEN_FIN: return "group_stream"; case FrameType::ACK_RECEIVE_TIMESTAMPS: return "ack_receive_timestamps"; } folly::assume_unreachable(); } folly::StringPiece toQlogString(LongHeader::Types type) { switch (type) { case LongHeader::Types::Initial: return "initial"; case LongHeader::Types::Retry: return "RETRY"; case LongHeader::Types::Handshake: return "handshake"; case LongHeader::Types::ZeroRtt: return "0RTT"; } folly::assume_unreachable(); } } // namespace quic
int mode = 2; double distance; double calibration; void setup() { Serial.begin(9600); pinMode(12, INPUT); } void loop() { if(mode == 1) { //Read duration in microSeconds long duration = pulseIn(12, HIGH); //Operation Range: 20 cm min (50 cm for accurate) distance = duration / 58.0; calibration = -20; } else if (mode == 2) { //Analog In .49 mV per unit double voltage = analogRead(5)*.0049; //.49 mV per cm distance = voltage/.0049; calibration = 0.0; } double cmToInch = 0.393701; //Analog Seems to be More Accurate due to PWM timing Serial.print((distance+calibration)*cmToInch); Serial.println(); delay(100); }
#ifndef MAINOPERATIONWIDGET_H #define MAINOPERATIONWIDGET_H #include <QWidget> #include <QCameraImageCapture> #include <QCameraInfo> #include <QMediaRecorder> namespace Ui { class MainOperationWidget; } class MainOperationWidget : public QWidget { Q_OBJECT public: explicit MainOperationWidget(QWidget *parent = nullptr); ~MainOperationWidget(); QCameraInfo defaultCameraInfo; void setCamera(const QCameraInfo &cameraInfo); void updateCaptureMode(); public slots: void updateRecordTime(); void updateCameraState(QCamera::State state); void updateRecorderState(QMediaRecorder::State state); void setExposureCompensation(int index); void displayRecorderError(); void displayCameraError(); void updateCameraDevice(QAction *action); void processCapturedImage(int requestId, const QImage &img); void capture(); private slots: void on_capture_btn_clicked(); private: Ui::MainOperationWidget *ui; QScopedPointer<QCamera> m_camera; QScopedPointer<QCameraImageCapture> m_imageCapture; QScopedPointer<QMediaRecorder> m_mediaRecorder; QImageEncoderSettings m_imageSettings; QAudioEncoderSettings m_audioSettings; QVideoEncoderSettings m_videoSettings; QString m_videoContainerFormat; bool m_isCapturingImage = false; bool m_applicationExiting = false; }; #endif // MAINOPERATIONWIDGET_H
#ifndef _ELEPHANT_H_ #define _ELEPHANT_H_ #include"Animal.hpp" #include<iostream> using namespace std; class Elephant : public Animal { public: Elephant(); Elephant(string name, char mark, int* pattern, int size, int position); ~Elephant(); virtual void showExcitement() const; }; #endif
// // AIDo.h // holdem // // Created by apple on 15/5/9. // // #include <string> #include <assert.h> #include <stdint.h> #ifndef __holdem__AIDo__ #define __holdem__AIDo__ #include "Typedef.h" #include "GameLogic.h" #define AI_FOLD 1 #define AI_CALL 2 #define AI_RAISE 3 class AIDo { public: //publicCard[5] 没有填0 //callNeedChips 没有填0 static AIDo* getInstance(); int getAIDo(BYTE myCard[2],BYTE publicCard[5],int64_t publicPool,int64_t callNeedChips,int64_t bigblind, BYTE playnum); private: private: AIDo(){}; virtual ~AIDo(); double getWinRate(BYTE myCard[2],BYTE publicCard[5],BYTE playnum); double getPotRate(int64_t publicPool,int64_t callNeedChips); GameLogic logic; }; #endif /* defined(__holdem__AIDo__) */
#pragma once #include <cinttypes> #include <memory> #include <Rendering/Texture.h> #include <Rendering/Tileset.h> #include <Rendering/TextureAtlas.h> #include <Rendering/Renderer.h> #include <Parsers/Parser.h> #include <boost/filesystem.hpp> namespace Sourcehold { namespace Parsers { using namespace Rendering; /** * Container format for tiles/animations/images * Creates an entry in TextureAtlas for every image collection (Building, unit, etc.) * and a Tileset depending on the stored type */ class Gm1File : private Parser { public: Gm1File(); Gm1File(boost::filesystem::path path); Gm1File(const Gm1File&) = delete; Gm1File& operator=(const Gm1File&)= delete; ~Gm1File(); bool LoadFromDisk(boost::filesystem::path path); void DumpInformation(); void Free(); inline std::weak_ptr<Tileset> GetTileset() { return tileset; } inline std::weak_ptr<TextureAtlas> GetTextureAtlas() { return textureAtlas; } protected: const uint32_t max_num = 2048; bool GetImage(uint32_t index); void ReadPalette(); private: struct ImageHeader; struct Gm1Entry; struct Gm1Header { /* Unknown */ uint32_t u0[3]; /* Number of entries */ uint32_t num; /* Unknown */ uint32_t u1; /* Type of stored entries */ enum DataType : uint32_t { TYPE_INTERFACE = 0x01, /* Tgx images */ TYPE_ANIMATION = 0x02, /* Animation */ TYPE_TILE = 0x03, /* Tile object (tgx) */ TYPE_FONT = 0x04, /* Tgx-compressed font */ TYPE_MISC1 = 0x05, /* Uncompressed image */ TYPE_CONSTSIZE = 0x06, /* Constant size */ TYPE_MISC2 = 0x07, /* Like 0x05 */ FIRST = TYPE_INTERFACE, LAST = TYPE_MISC2, } type; /* Unknown */ uint32_t u2[14]; /* Data size */ uint32_t len; /* Unknown */ uint32_t u3; } header; std::shared_ptr<TextureAtlas> textureAtlas; std::shared_ptr<Tileset> tileset; boost::filesystem::path path; /* Offset of data section */ uint32_t offData; /* If tileset, how many actual entries does it contain? */ uint32_t numCollections; /* Raw image data */ char *imgdata = nullptr; /* All of the entries */ std::vector<Gm1Entry> entries; }; } }
// // EPITECH PROJECT, 2018 // zappy // File description: // StaticText.hpp // #ifndef STATICTEXT_HPP #define STATICTEXT_HPP #include "include.hpp" #include "utils.hpp" class StaticText { public: StaticText(irr::gui::IGUIStaticText *txt, int id); ~StaticText(); int getId() const; void setText(const char *str); void setVisible(bool visible); private: int _id; irr::gui::IGUIStaticText *txt; }; #endif
#pragma once #include "GameObject.h" #define TEMPSIZE 1 class Rect : public GameObject { private: struct Vertex { Vector2 position; DWORD color; Vector2 uv; }; Vertex vertice[4]; LPDIRECT3DTEXTURE9 pTex; LPD3DXEFFECT pEffect; float deltaTime; class Camera* camera; class AnimationClip* clips; Transform* tempTrans[TEMPSIZE]; RectCollider* tempCollider; bool isTexture; bool isInterpolation; float delta; Transform* tileTrans; public: Rect(); ~Rect(); void Init(wstring shaderFile, const Vector2 min, const Vector2 max, const DWORD color, bool isTex); void Release(); void Update(); void Render(); void RenderRect(); void InitShader(wstring shaderFile); void InitVertex(DWORD color, Vector2 min, Vector2 max); void InitBuffer(); void DrawInterface(); void SetCamera(Camera* camera) { this->camera = camera; } void SetTexture(LPDIRECT3DTEXTURE9 tex) { pTex = tex; } void SetTransform(Transform* transform) { this->transform = transform; } void SetInterPolation(bool isInterPolation) { this->isInterpolation = isInterPolation; } void SetTileTrans(Transform* tileTrans) { this->tileTrans = tileTrans; } };
#pragma once #include "Vector4.h" #include "BasicLogicDefinitions.h" class DynamicObjectModel { public: typedef struct { float left,top, right,bottom; } Rect; enum DynamicObjectState { DYNAMIC_OBJECT_STATE_MOVE_UP, DYNAMIC_OBJECT_STATE_MOVE_DOWN, DYNAMIC_OBJECT_STATE_MOVE_RIGHT, DYNAMIC_OBJECT_STATE_MOVE_LEFT, DYNAMIC_OBJECT_STATE_MOVE_UP_RIGHT, DYNAMIC_OBJECT_STATE_MOVE_UP_LEFT, DYNAMIC_OBJECT_STATE_MOVE_DOWN_RIGHT, DYNAMIC_OBJECT_STATE_MOVE_DOWN_LEFT, DYNAMIC_OBJECT_STATE_IMPACTING, DYNAMIC_OBJECT_STATE_VANISHING, DYNAMIC_OBJECT_STATE_VANISHED }; enum DynamicObjectAction { DYNAMIC_OBJECT_ACTION_IDLE, DYNAMIC_OBJECT_ACTION_MOVE_UP, DYNAMIC_OBJECT_ACTION_MOVE_DOWN, DYNAMIC_OBJECT_ACTION_MOVE_RIGHT, DYNAMIC_OBJECT_ACTION_MOVE_LEFT, DYNAMIC_OBJECT_ACTION_MOVE_UP_RIGHT, DYNAMIC_OBJECT_ACTION_MOVE_UP_LEFT, DYNAMIC_OBJECT_ACTION_MOVE_DOWN_RIGHT, DYNAMIC_OBJECT_ACTION_MOVE_DOWN_LEFT, DYNAMIC_OBJECT_ACTION_IMPACT, DYNAMIC_OBJECT_ACTION_VANISH }; public: DynamicObjectModel(); virtual ~DynamicObjectModel(); public: virtual DynamicObjectState getState(){return m_state;} virtual void setState(DynamicObjectState state){m_state = state;} virtual DynamicObjectAction getAction(){return m_action;} virtual void setAction(DynamicObjectAction action){m_action = action; } const float getTimeout(){ return m_timeout;}; void setTimeout(float timeout){m_timeout = timeout;} void setTerrainPosition(const Vector4& terrainPosition) { m_terrainPosition = terrainPosition; } const Vector4& getTerrainPosition() const { return m_terrainPosition; } const Vector4 getScreenPosition() const { return m_terrainPosition*PIXELS_PER_METER; } void setScreenPosition(const Vector4& screenPosition) { m_terrainPosition = screenPosition * (float)(1/ (float)PIXELS_PER_METER); } void setStep(const float &stepX, const float &stepY){ m_stepX = stepX; m_stepY = stepY; } void getStep(float *stepX, float *stepY){ *stepX = m_stepX; *stepY = m_stepY; } void setPixelWidth(int width){ m_pixelWidth = width; } const int getPixelWidth(){return m_pixelWidth;} void setPixelHeight(int height){ m_pixelHeight = height; } const int getPixelHeight(){return m_pixelHeight;} void setRect(const Rect rect){ m_rect = rect; } const Rect getRect(){return m_rect;} virtual float getCelerity() = 0; const float getDamagePoints(){ return m_damagePoints;} void setDamagePoints(float damagePoints){ m_damagePoints = damagePoints;} protected: int m_damagePoints; DynamicObjectState m_state; DynamicObjectAction m_action; Vector4 m_terrainPosition; Vector4 m_screenPosition; float m_timeout; float m_stepX; float m_stepY; int m_pixelWidth; int m_pixelHeight; Rect m_rect; };
#ifndef SYNTHVIEW_H #define SYNTHVIEW_H #include "viewwidget.h" #include <vector> #include "motiontrack.h" #include "motioncombined.h" #include "BVH.h" class SynthView : public ViewWidget { Q_OBJECT public: typedef std::vector<MotionTrack*> MotionTrackVector; /// Ctor explicit SynthView(Manager*m, QWidget *parent = 0); /// Dtor ~SynthView(); protected: /// Initialise the GL scene void initializeGL(); /// Paint the GL scene void paintGL(); /// Resize the GL scene void resizeGL(int width, int height); /// Update the current frame using MLS projection void updateFrame(); void timerEvent(QTimerEvent *); private: /// The motion track vector containing our database of motion and their associated latent space MotionTrackVector m_tracks; /// A combined database for querying which tracks to project onto MotionCombined *m_combinedTracks; /// The BVH motion player BVH *m_bvh; /// The central (shared) storage of the latent space data double ** m_latentData; /// The central storage of the full channel and frame data for the BVH double *m_fullData; /// The current frame, to be rendered using the BVH player double *m_currentFrame; /// Load the full / latent data from binary files void loadFullData(const char * motion_data_file); void loadLatentData(const char * motion_data_file); /// Some handy numbers int m_latentDim, m_numChannels, m_numTracks, m_framesPerTrack; /// The last used squared search radius - this will be modified in the running of /// the algorithm, potentially causing discontinuities! double m_sqRad; }; #endif // SYNTHVIEW_H
// Heap //https://cacm.acm.org/magazines/2010/7/95061-youre-doing-it-wrong/fulltext#F1 //http://theoryofprogramming.com/2015/02/01/binary-heaps-and-heapsort-algorithm/ // emplace - O(log2(n)) // pop - O(log2(n)) // remove - O(n) // TAOCP - page 334 // 2.3.2. Binary Tree Representation of Trees template <typename T, typename TAlloc> class NodeBinaryHeap : protected TAlloc { struct Node { Node* parent; Node* left; Node* right; ui32 id; ui64 p; T data; }; ui32 Id; ui32 Size; Node* Root; unsigned leading_zero_naive3(ui32 x) { // #ifdef _MSC_VER // unsigned long index; // auto isNonzero = _BitScanReverse(&index, (unsigned long)x); // if (isNonzero) // return (sizeof(x) * 8) - index - 1; // else return sizeof(x) * 8; // #else int n; if (x == 0) return 32; for (n = 0; ((x & 0x80000000) == 0); n++, x <<= 1); return n; //#endif } template <typename... TArgs> Node* emplaceAtInsertionPoint(ui64 priotity, TArgs&&... args) { // While inserting itself we could keep a track of the heap size. So, // this takes constant time. While inserting, we must search for the // appropriate location. For this, we will convert the size into its // binary representation and begin the traversal from the root. How? // Keep reading the bits of the binary representation you just // generated, if you encounter ‘0’ go to the left child of the parent, // if it is a ‘1’ go to the right child of the parent. I know it // sounds really weird, but that’s the best thing we can do. //http://theoryofprogramming.com/2015/02/01/binary-heaps-and-heapsort-algorithm/ auto path = ++Size; auto pos = leading_zero_naive3(path) + 1; Node* parent = nullptr; Node* current = Root; while (current != nullptr && pos < 32) { parent = current; auto dir = (path & (1 << ((sizeof(path) * 8) - pos))) > 0; if (dir) { if (current->right == nullptr) { current->right = TAlloc::template alloc<Node>( parent, nullptr, nullptr, Id++, priotity, T{std::forward<TArgs>(args)...}); return current->right; } current = current->right; } else { if (current->left == nullptr) { current->left = TAlloc::template alloc<Node>( parent, nullptr, nullptr, Id++, priotity, T{std::forward<TArgs>(args)...}); return current->left; } current = current->left; } ++pos; } Root = TAlloc::template alloc<Node>( nullptr, nullptr, nullptr, Id++, priotity, T{std::forward<TArgs>(args)...}); return Root; } Node* detachAtRemotionPoint() { auto path = Size--; auto pos = leading_zero_naive3(path) + 1; Node* current = Root; while (current != nullptr && pos < 32) { auto dir = (path & (1 << ((sizeof(path) * 8) - pos))) > 0; if (dir == 1) { if (current->right == nullptr) break; current = current->right; } else if (dir == 0) { if (current->left == nullptr) break; current = current->left; } ++pos; } //assert is not null //assert is leaf if (current->parent == nullptr) { Root = nullptr; return current; } if (current->parent->left == current) current->parent->left = nullptr; else current->parent->right = nullptr; current->parent = nullptr; return current; } /* pp | p / \ n pr / \ nl nr */ void LeftSwap(Node*& parent, Node*& n) { auto pparent = parent->parent; auto pright = parent->right; auto nleft = n->left; auto nright = n->right; n->parent = pparent; n->right = pright; n->left = parent; parent->parent = n; parent->left = nleft; parent->right = nright; } /* pp | p / \ pl n / \ nl nr */ void RightSwap(Node*& parent, Node*& n) { Node* pparent = parent->parent; Node* pleft = parent->left; Node* nleft = n->left; Node* nright = n->right; n->parent = pparent; n->right = parent; n->left = pleft; parent->parent = n; parent->left = nleft; parent->right = nright; } void Swap(Node*& parent, Node*& n) { if (parent == nullptr) return; if (n == nullptr) return; if (parent->left == n) LeftSwap(parent, n); else RightSwap(parent, n); } void PercolateUp(Node* n) { if (n == nullptr) return; while ((n->parent) && (n->parent->p > n->p)) Swap(n->parent, n); } void PercolateDown(Node* n) { if (n == nullptr) return; while ( ((n->left) && (n->p > n->left->p)) || ((n->right) && (n->p > n->right->p)) ) { int swap; if (n->left && n->right) { if (n->left->p < n->right->p) swap = 0; else swap = 1; } else if (n->right == nullptr) swap = 0; else swap = 1; if (swap == 0) Swap(n, n->left); else if (swap == 1) Swap(n, n->right); } } void DetachLeaf(Node* n) { if (n->parent == nullptr) return; auto dir = n->parent->right == n ? 1 : 0; if (dir == 0) n->parent->left = nullptr; else n->parent->right = nullptr; n->parent = nullptr; } Node* remove(ui32 id, Node * n) { if (n == nullptr) return nullptr; if (n->id == id) { n->p = std::numeric_limits<ui32>::max(); PercolateDown(n); DetachLeaf(n); return n; } auto l = remove(id, n->left); if (l != nullptr) return l; return remove(id, n->right); } public: NodeBinaryHeap() : Size{0}, Root{nullptr}, Id {0} { } ui32 size() const { return Size; } template <typename... TArgs> ui32 emplace(ui64 priority, TArgs&&... args) { auto node = emplaceAtInsertionPoint(priority, std::forward<TArgs>(args)...); PercolateUp(node); return node->id; } T pop() { auto oldRoot = Root; auto data = Root->data; auto node = detachAtRemotionPoint(); node->left = oldRoot->left; node->right = oldRoot->right; Root = node; PercolateDown(node); TAlloc::del(oldRoot); return data; } T& peek() const { return Root->data; } bool remove(ui32 id) { auto node = remove(id, Root); TAlloc::del(node); return node != nullptr; } };
/* A class responsible for the Drawing about Geometry */ #ifndef H_DRAWGRAPHICS_H #define H_DRAWGRAPHICS_H #include <gl\freeglut.h> #include "Mesh.h" #include "Points.h" #include "math_3d.h" #include "Math_basics.h" namespace P_RVD { class GraphicsDrawer { public: /* Initialize the environmnet of the Grawing */ void Init(); /* Run the Renderring */ void Run(); /* Graw Points. Include : 1, Seeds 2, Intersection Vertex */ void DrawVertex(Vector3d _point) {}; /* Graw Points */ void DrawPoints(Points _points); /* Graw Triangle Include : 1, Mesh facets 2, RVD clipped Polygon (for each triangle) */ void DrawMesh(const Mesh& _m); /* Draw Triangle with 3 exact position of vertex */ void DrawTriangle(Vector3d _v1, Vector3d _v2, Vector3d _v3); protected: /* camera attributes */ Vector3f cameraPosition, centerPosition, upDirection; /* light attributes */ GLfloat lightPosition[4]; GLfloat shininess; GLfloat ambient[4], diffuse[4], specular[4]; }; } #endif /* H_DRAWGRAPHICS_H */
#include "clone_ptr.inl.hpp" #include "reconstructable.hpp" struct NonCopyable { explicit NonCopyable(int a) : x(a) , y(a) {} NonCopyable(int a, int b) : x(a) , y(b) {} NonCopyable(const NonCopyable&) = delete; NonCopyable& operator=(const NonCopyable&) = delete; int x, y; }; #include <iostream> int main() { { ClonePtr<NonCopyable> x(1); auto y = x; y->y = 3; auto z = y; std::cout << "x = {1} : " << x->x << ", " << x->y << std::endl; std::cout << "y = x.ctor(), modified: " << y->x << ", " << y->y << std::endl; std::cout << "z = y.ctor() : " << z->x << ", " << z->y << std::endl; std::cout << std::endl; } { ClonePtr<NonCopyable> x(1, 2); auto y = x; y->y = 3; auto z = y; std::cout << "x = {1, 2} : " << x->x << ", " << x->y << std::endl; std::cout << "y = x.ctor(), modified: " << y->x << ", " << y->y << std::endl; std::cout << "z = y.ctor() : " << z->x << ", " << z->y << std::endl; y.reconstruct(); std::cout << "y.reconstruct() : " << y->x << ", " << y->y << std::endl; std::cout << std::endl; } { NonCopyable x(1, 2); std::cout << "x = {1, 2} : " << x.x << ", " << x.y << std::endl; ReconstructorImpl<NonCopyable, int, int>{std::make_tuple(3, 4)}.reconstruct(x); std::cout << "reconstruct(x, 3, 4) : " << x.x << ", " << x.y << std::endl; std::cout << std::endl; } { Reconstructable<NonCopyable> x(1, 2); x.x = 3; x.y = 4; std::cout << "create with {1, 2}, modified: " << x.x << ", " << x.y << std::endl; x.reconstruct(); std::cout << "reconstructed : " << x.x << ", " << x.y << std::endl; std::cout << std::endl; } { ReconstructableImpl<NonCopyable> x(true, 1, 2); std::cout << "YOU SHOULD NOT CALL ReconstructableImpl(true, ...): " << std::endl; x.reconstruct(); std::cout << std::endl; } return 0; }
// Copyright (c) 2020 The Orbit 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 "TracepointInfoManager.h" #include "gtest/gtest.h" TEST(TracepointInfoManager, Contains) { TracepointInfoManager tracepoint_info_manager; tracepoint_info_manager.AddUniqueTracepointEventInfo(1, orbit_grpc_protos::TracepointInfo{}); EXPECT_TRUE(tracepoint_info_manager.Contains(1)); EXPECT_FALSE(tracepoint_info_manager.Contains(0)); } TEST(TracepointInfoManager, AddUniqueTracepointEventInfo) { TracepointInfoManager tracepoint_info_manager; EXPECT_TRUE( tracepoint_info_manager.AddUniqueTracepointEventInfo(1, orbit_grpc_protos::TracepointInfo{})); EXPECT_TRUE(tracepoint_info_manager.Contains(1)); EXPECT_FALSE( tracepoint_info_manager.AddUniqueTracepointEventInfo(1, orbit_grpc_protos::TracepointInfo{})); EXPECT_TRUE( tracepoint_info_manager.AddUniqueTracepointEventInfo(2, orbit_grpc_protos::TracepointInfo{})); EXPECT_TRUE(tracepoint_info_manager.Contains(2)); } TEST(TracepointInfoManager, Get) { TracepointInfoManager tracepoint_info_manager; orbit_grpc_protos::TracepointInfo tracepoint_info; tracepoint_info.set_category("sched"); tracepoint_info.set_name("sched_switch"); EXPECT_TRUE( tracepoint_info_manager.AddUniqueTracepointEventInfo(1, orbit_grpc_protos::TracepointInfo{})); EXPECT_TRUE( tracepoint_info_manager.AddUniqueTracepointEventInfo(2, orbit_grpc_protos::TracepointInfo{})); EXPECT_TRUE(tracepoint_info_manager.AddUniqueTracepointEventInfo(3, tracepoint_info)); EXPECT_FALSE( tracepoint_info_manager.AddUniqueTracepointEventInfo(1, orbit_grpc_protos::TracepointInfo{})); EXPECT_TRUE(tracepoint_info_manager.Get(3).category().compare("sched") == 0 && tracepoint_info_manager.Get(3).name().compare("sched_switch") == 0); EXPECT_FALSE(tracepoint_info_manager.Get(2).category().compare("sched") == 0 && tracepoint_info_manager.Get(2).name().compare("sched_switch") == 0); }
/* * Copyright 2012 Google Inc. * * 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. */ // Author: jefftk@google.com (Jeff Kaufman) #include "ngx_server_context.h" #include "ngx_message_handler.h" #include "ngx_request_context.h" #include "ngx_rewrite_driver_factory.h" #include "ngx_rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_stats.h" #include "net/instaweb/system/public/add_headers_fetcher.h" #include "net/instaweb/system/public/loopback_route_fetcher.h" #include "net/instaweb/system/public/system_caches.h" #include "net/instaweb/util/public/shared_mem_statistics.h" #include "net/instaweb/util/public/split_statistics.h" #include "net/instaweb/util/public/statistics.h" namespace net_instaweb { const char kCacheFlushCount[] = "cache_flush_count"; const char kCacheFlushTimestampMs[] = "cache_flush_timestamp_ms"; // Statistics histogram names. const char kHtmlRewriteTimeUsHistogram[] = "Html Time us Histogram"; NgxServerContext::NgxServerContext(NgxRewriteDriverFactory* factory) : SystemServerContext(factory), ngx_factory_(factory), initialized_(false) { } NgxServerContext::~NgxServerContext() { } NgxRewriteOptions* NgxServerContext::config() { return NgxRewriteOptions::DynamicCast(global_options()); } void NgxServerContext::ChildInit() { DCHECK(!initialized_); if (!initialized_) { initialized_ = true; set_lock_manager(ngx_factory_->caches()->GetLockManager(config())); if (split_statistics_.get() != NULL) { // Readjust the SHM stuff for the new process local_statistics_->Init(false, message_handler()); // Create local stats for the ServerContext, and fill in its // statistics() and rewrite_stats() using them; if we didn't do this here // they would get set to the factory's by the InitServerContext call // below. set_statistics(split_statistics_.get()); local_rewrite_stats_.reset(new RewriteStats( split_statistics_.get(), ngx_factory_->thread_system(), ngx_factory_->timer())); set_rewrite_stats(local_rewrite_stats_.get()); } ngx_factory_->InitServerContext(this); // TODO(oschaaf): in mod_pagespeed, the ServerContext owns // the fetchers, and sets up the UrlAsyncFetcherStats here } } void NgxServerContext::CreateLocalStatistics( Statistics* global_statistics) { local_statistics_ = ngx_factory_->AllocateAndInitSharedMemStatistics( hostname_identifier(), *config()); split_statistics_.reset(new SplitStatistics( ngx_factory_->thread_system(), local_statistics_, global_statistics)); // local_statistics_ was ::InitStat'd by AllocateAndInitSharedMemStatistics, // but we need to take care of split_statistics_. NgxRewriteDriverFactory::InitStats(split_statistics_.get()); } void NgxServerContext::InitStats(Statistics* statistics) { // TODO(oschaaf): we need to port the cache flush mechanism statistics->AddVariable(kCacheFlushCount); statistics->AddVariable(kCacheFlushTimestampMs); Histogram* html_rewrite_time_us_histogram = statistics->AddHistogram(kHtmlRewriteTimeUsHistogram); // We set the boundary at 2 seconds which is about 2 orders of magnitude // worse than anything we have reasonably seen, to make sure we don't // cut off actual samples. html_rewrite_time_us_histogram->SetMaxValue(2 * Timer::kSecondUs); // TODO(oschaaf): Once the ServerContext owns the fetchers, // initialise UrlAsyncFetcherStats here } void NgxServerContext::ApplySessionFetchers( const RequestContextPtr& request, RewriteDriver* driver) { const NgxRewriteOptions* conf = NgxRewriteOptions::DynamicCast( driver->options()); CHECK(conf != NULL); NgxRequestContext* ngx_request = NgxRequestContext::DynamicCast( request.get()); if (ngx_request == NULL) { return; // decoding_driver has a null RequestContext. } // Note that these fetchers are applied in the opposite order of how they are // added // TODO(oschaaf): in mod_pagespeed, LoopbackRouteFetcher is not added when // one of these is set: disable_loopback_routing, slurping_enabled, or // test_proxy. // Note the port here is our port, not from the request, since // LoopbackRouteFetcher may decide we should be talking to ourselves. driver->SetSessionFetcher(new LoopbackRouteFetcher( driver->options(), ngx_request->local_ip(), ngx_request->local_port(), driver->async_fetcher())); if (driver->options()->num_custom_fetch_headers() > 0) { driver->SetSessionFetcher(new AddHeadersFetcher(driver->options(), driver->async_fetcher())); } } } // namespace net_instaweb
#include <systemc.h> #include <fstream> #include "tester.h" #include "adder1.h" using namespace std; int sc_main(int argc, char *argv[]) { sc_signal <bool> mod_in1, mod_in2, mod_cin; sc_signal <bool> mod_out, mod_cout; sc_clock clk("clock", 10, SC_NS); Adder module_adder("adder"); module_adder.in1(mod_in1); module_adder.in2(mod_in2); module_adder.cin(mod_cin); module_adder.out(mod_out); module_adder.cout(mod_cout); Tester testbench("testbench1"); testbench.clk(clk); testbench.add_in1(mod_in1); testbench.add_in2(mod_in2); testbench.add_cin(mod_cin); sc_trace_file *t_file = sc_create_vcd_trace_file("test"); sc_trace(t_file, clk, "clock"); sc_trace(t_file, mod_in1, "a"); sc_trace(t_file, mod_in2, "b"); sc_trace(t_file, mod_cin, "cin"); sc_trace(t_file, mod_out, "s"); sc_trace(t_file, mod_cout, "cout"); sc_start(); }
#include "tpltn.h" int main() { string Name; getline(cin, Name); // cin >> Name; string Surname; getline(cin, Surname); string FullName = Name + ' ' + Surname; // конкатенация строк cout << FullName << endl; cout << FullName.size() << endl; // длина строки //C-style strings: char SayHello[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // \0 - знак окончания строки cout << SayHello << endl; char Buffer[20] = {'\0'}; string line; getline(cin, line); if (line.length() < 20) strcpy_s(Buffer, line.c_str()); //strcpy_s - безопасный вариант копирования строк посимвольно cout << Buffer << endl; wait(); }
#include "test_shader.h" namespace sloth { TestShader * TestShader::m_Inst(nullptr); TestShader * TestShader::inst() { if (m_Inst == nullptr) m_Inst = new TestShader(); return m_Inst; } void TestShader::loadModel(const glm::mat4 & model) { glProgramUniformMatrix4fv(m_ID, m_LocModel, 1, GL_FALSE, glm::value_ptr(model)); } void TestShader::loadView(const glm::mat4 & view) { glProgramUniformMatrix4fv(m_ID, m_LocView, 1, GL_FALSE, glm::value_ptr(view)); } void TestShader::loadProjection(const glm::mat4 & projection) { glProgramUniformMatrix4fv(m_ID, m_LocProjection, 1, GL_FALSE, glm::value_ptr(projection)); } TestShader::TestShader() :Shader(TEST_VERTEX_FILE,TEST_FRAGMENT_FILE) { getAllUniformLocation(); } void TestShader::getAllUniformLocation() { m_LocModel = glGetUniformLocation(m_ID, "model"); m_LocView = glGetUniformLocation(m_ID, "view"); m_LocProjection = glGetUniformLocation(m_ID, "projection"); } }
#include <iostream> #include <fstream> #include <string> #include "myClasses.cpp" using namespace std; const int REGISTRATION = 1; const int AUTHENTICATION = 2; const int EXIT = 3; int main() { BusinessManager businessManager; businessManager.setMenuSelection(); while (businessManager.getMenuSelection() != EXIT) { if (businessManager.getMenuSelection() == REGISTRATION) { businessManager.registration(); } else if (businessManager.getMenuSelection() == AUTHENTICATION) { businessManager.authentication(); } businessManager.setMenuSelection(); } return 0; }
/****************************************************************************** * $Id$ * * Project: libLAS - http://liblas.org - A BSD library for LAS format data. * Purpose: LAS header class * Author: Mateusz Loskot, mateusz@loskot.net * ****************************************************************************** * Copyright (c) 2008, Mateusz Loskot * Copyright (c) 2008, Phil Vachon * * 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 Martin Isenburg or Iowa Department * of Natural Resources 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. ****************************************************************************/ #include <liblas/header.hpp> #include <liblas/spatialreference.hpp> #include <liblas/schema.hpp> #include <liblas/detail/private_utility.hpp> #include <liblas/utility.hpp> #ifdef HAVE_LASZIP #include <liblas/detail/zippoint.hpp> #include <laszip/laszip.hpp> #endif // boost #include <boost/cstdint.hpp> #include <boost/lambda/lambda.hpp> #include <boost/bind.hpp> //std #include <algorithm> #include <fstream> #include <stdexcept> #include <string> #include <vector> #include <cstring> // std::memset, std::memcpy, std::strncpy #include <cassert> #include <ctime> using namespace boost; namespace liblas { char const* const Header::FileSignature = "LASF"; char const* const Header::SystemIdentifier = "libLAS"; char const* const Header::SoftwareIdentifier = "libLAS 1.8.2"; Header::Header() : m_schema(ePointFormat3) { Init(); } Header::Header(Header const& other) : m_sourceId(other.m_sourceId), m_reserved(other.m_reserved), m_projectGuid(other.m_projectGuid), m_versionMajor(other.m_versionMajor), m_versionMinor(other.m_versionMinor), m_createDOY(other.m_createDOY), m_createYear(other.m_createYear), m_headerSize(other.m_headerSize), m_dataOffset(other.m_dataOffset), m_recordsCount(other.m_recordsCount), // m_dataFormatId(other.m_dataFormatId), // m_dataRecordLen(other.m_dataRecordLen), m_pointRecordsCount(other.m_pointRecordsCount), m_scales(other.m_scales), m_offsets(other.m_offsets), m_extent(other.m_extent), m_srs(other.m_srs), m_schema(other.m_schema), m_isCompressed(other.m_isCompressed), m_headerPadding(other.m_headerPadding) { void* p = 0; p = std::memcpy(m_signature, other.m_signature, eFileSignatureSize); assert(p == m_signature); p = std::memcpy(m_systemId, other.m_systemId, eSystemIdSize); assert(p == m_systemId); p = std::memcpy(m_softwareId, other.m_softwareId, eSoftwareIdSize); assert(p == m_softwareId); std::vector<uint32_t>(other.m_pointRecordsByReturn).swap(m_pointRecordsByReturn); assert(ePointsByReturnSize >= m_pointRecordsByReturn.size()); std::vector<VariableRecord>(other.m_vlrs).swap(m_vlrs); } Header& Header::operator=(Header const& rhs) { if (&rhs != this) { void* p = 0; p = std::memcpy(m_signature, rhs.m_signature, eFileSignatureSize); assert(p == m_signature); m_sourceId = rhs.m_sourceId; m_reserved = rhs.m_reserved; m_projectGuid = rhs.m_projectGuid; m_versionMajor = rhs.m_versionMajor; m_versionMinor = rhs.m_versionMinor; p = std::memcpy(m_systemId, rhs.m_systemId, eSystemIdSize); assert(p == m_systemId); p = std::memcpy(m_softwareId, rhs.m_softwareId, eSoftwareIdSize); assert(p == m_softwareId); m_createDOY = rhs.m_createDOY; m_createYear = rhs.m_createYear; m_headerSize = rhs.m_headerSize; m_dataOffset = rhs.m_dataOffset; m_recordsCount = rhs.m_recordsCount; m_pointRecordsCount = rhs.m_pointRecordsCount; std::vector<uint32_t>(rhs.m_pointRecordsByReturn).swap(m_pointRecordsByReturn); assert(ePointsByReturnSize >= m_pointRecordsByReturn.size()); std::vector<VariableRecord>(rhs.m_vlrs).swap(m_vlrs); m_scales = rhs.m_scales; m_offsets = rhs.m_offsets; m_extent = rhs.m_extent; m_srs = rhs.m_srs; m_schema = rhs.m_schema; m_isCompressed = rhs.m_isCompressed; m_headerPadding = rhs.m_headerPadding; } return *this; } bool Header::operator==(Header const& other) const { if (&other == this) return true; if (m_scales != other.m_scales) return false; if (m_offsets != other.m_offsets) return false; if (m_signature != other.m_signature) return false; if (m_sourceId != other.m_sourceId) return false; if (m_reserved != other.m_reserved) return false; if (m_projectGuid != other.m_projectGuid) return false; if (m_versionMajor != other.m_versionMajor) return false; if (m_versionMinor != other.m_versionMinor) return false; if (m_systemId != other.m_systemId) return false; if (m_softwareId != other.m_softwareId) return false; if (m_createDOY != other.m_createDOY) return false; if (m_createYear != other.m_createYear) return false; if (m_headerSize != other.m_headerSize) return false; if (m_dataOffset != other.m_dataOffset) return false; if (m_recordsCount != other.m_recordsCount) return false; if (m_pointRecordsCount != other.m_pointRecordsCount) return false; if (m_pointRecordsByReturn != other.m_pointRecordsByReturn) return false; if (m_extent != other.m_extent) return false; if (m_isCompressed != other.m_isCompressed) return false; if (m_headerPadding != other.m_headerPadding) return false; if (m_schema != other.m_schema) return false; return true; } std::string Header::GetFileSignature() const { return std::string(m_signature, eFileSignatureSize); } void Header::SetFileSignature(std::string const& v) { if (0 != v.compare(0, eFileSignatureSize, FileSignature)) throw std::invalid_argument("invalid file signature"); std::strncpy(m_signature, v.c_str(), eFileSignatureSize); } uint16_t Header::GetFileSourceId() const { return m_sourceId; } void Header::SetFileSourceId(uint16_t v) { // TODO: Should we warn or throw about type overflow occuring when // user passes 65535 + 1 = 0 m_sourceId = v; } uint16_t Header::GetReserved() const { return m_reserved; } void Header::SetReserved(uint16_t v) { // TODO: Should we warn or throw about type overflow occuring when // user passes 65535 + 1 = 0 m_reserved = v; } boost::uuids::uuid Header::GetProjectId() const { return m_projectGuid; } void Header::SetProjectId(boost::uuids::uuid const& v) { m_projectGuid = v; } uint8_t Header::GetVersionMajor() const { return m_versionMajor; } void Header::SetVersionMajor(uint8_t v) { if (eVersionMajorMin > v || v > eVersionMajorMax) throw std::out_of_range("version major out of range"); m_versionMajor = v; } uint8_t Header::GetVersionMinor() const { return m_versionMinor; } void Header::SetVersionMinor(uint8_t v) { if (v > eVersionMinorMax) throw std::out_of_range("version minor out of range"); m_versionMinor = v; } std::string Header::GetSystemId(bool pad /*= false*/) const { // copy array of chars and trim zeros if smaller than 32 bytes std::string tmp(std::string(m_systemId, eSystemIdSize).c_str()); // pad right side with spaces if (pad && tmp.size() < eSystemIdSize) { tmp.resize(eSystemIdSize, 0); assert(tmp.size() == eSystemIdSize); } assert(tmp.size() <= eSystemIdSize); return tmp; } void Header::SetSystemId(std::string const& v) { if (v.size() > eSystemIdSize) throw std::invalid_argument("system id too long"); std::fill(m_systemId, m_systemId + eSystemIdSize, 0); std::strncpy(m_systemId, v.c_str(), eSystemIdSize); } std::string Header::GetSoftwareId(bool pad /*= false*/) const { std::string tmp(std::string(m_softwareId, eSoftwareIdSize).c_str()); // pad right side with spaces if (pad && tmp.size() < eSoftwareIdSize) { tmp.resize(eSoftwareIdSize, 0); assert(tmp.size() == eSoftwareIdSize); } assert(tmp.size() <= eSoftwareIdSize); return tmp; } void Header::SetSoftwareId(std::string const& v) { if (v.size() > eSoftwareIdSize) throw std::invalid_argument("generating software id too long"); // m_softwareId = v; std::fill(m_softwareId, m_softwareId + eSoftwareIdSize, 0); std::strncpy(m_softwareId, v.c_str(), eSoftwareIdSize); } uint16_t Header::GetCreationDOY() const { return m_createDOY; } void Header::SetCreationDOY(uint16_t v) { m_createDOY = v; } uint16_t Header::GetCreationYear() const { return m_createYear; } void Header::SetCreationYear(uint16_t v) { m_createYear = v; } uint16_t Header::GetHeaderSize() const { return m_headerSize; } void Header::SetHeaderSize(uint16_t v) { m_headerSize = v; } uint32_t Header::GetDataOffset() const { return m_dataOffset; } void Header::SetDataOffset(uint32_t v) { m_dataOffset = v; } uint32_t Header::GetHeaderPadding() const { return m_headerPadding; } uint32_t Header::GetVLRBlockSize() const { uint32_t vlr_total_size = 0; for (uint32_t i = 0; i < GetRecordsCount(); ++i) { VariableRecord const & vlr = GetVLR(i); vlr_total_size += static_cast<uint32_t>(vlr.GetTotalSize()); } return vlr_total_size; } void Header::SetHeaderPadding(uint32_t v) { m_headerPadding = v; } uint32_t Header::GetRecordsCount() const { return m_recordsCount; } void Header::SetRecordsCount(uint32_t v) { m_recordsCount = v; } liblas::PointFormatName Header::GetDataFormatId() const { return m_schema.GetDataFormatId(); } void Header::SetDataFormatId(liblas::PointFormatName v) { m_schema.SetDataFormatId(v); } uint16_t Header::GetDataRecordLength() const { // No matter what the schema says, this must be a a short in size. return static_cast<uint16_t>(m_schema.GetByteSize()); } uint32_t Header::GetPointRecordsCount() const { return m_pointRecordsCount; } void Header::SetPointRecordsCount(uint32_t v) { m_pointRecordsCount = v; } Header::RecordsByReturnArray const& Header::GetPointRecordsByReturnCount() const { return m_pointRecordsByReturn; } void Header::SetPointRecordsByReturnCount(std::size_t index, uint32_t v) { assert(m_pointRecordsByReturn.size() == Header::ePointsByReturnSize); uint32_t& t = m_pointRecordsByReturn.at(index); t = v; } double Header::GetScaleX() const { return m_scales.x; } double Header::GetScaleY() const { return m_scales.y; } double Header::GetScaleZ() const { return m_scales.z; } void Header::SetScale(double x, double y, double z) { // double const minscale = 0.01; m_scales.x = x; m_scales.y = y; m_scales.z = z; } double Header::GetOffsetX() const { return m_offsets.x; } double Header::GetOffsetY() const { return m_offsets.y; } double Header::GetOffsetZ() const { return m_offsets.z; } void Header::SetOffset(double x, double y, double z) { m_offsets = PointOffsets(x, y, z); } double Header::GetMaxX() const { return (m_extent.max)(0); } double Header::GetMinX() const { return (m_extent.min)(0); } double Header::GetMaxY() const { return (m_extent.max)(1); } double Header::GetMinY() const { return (m_extent.min)(1); } double Header::GetMaxZ() const { return (m_extent.max)(2); } double Header::GetMinZ() const { return (m_extent.min)(2); } void Header::SetMax(double x, double y, double z) { // m_extent = Bounds(m_extent.min(0), m_extent.min(1), m_extent.max(0), m_extent.max(1), m_extent.min(2), m_extent.max(2)); // Bounds(minx, miny, minz, maxx, maxy, maxz) m_extent = Bounds<double>((m_extent.min)(0), (m_extent.min)(1), (m_extent.min)(2), x, y, z); } void Header::SetMin(double x, double y, double z) { m_extent = Bounds<double>(x, y, z, (m_extent.max)(0), (m_extent.max)(1), (m_extent.max)(2)); } void Header::SetExtent(Bounds<double> const& extent) { m_extent = extent; } const Bounds<double>& Header::GetExtent() const { return m_extent; } void Header::AddVLR(VariableRecord const& v) { m_vlrs.push_back(v); m_recordsCount += 1; } VariableRecord const& Header::GetVLR(uint32_t index) const { return m_vlrs[index]; } const std::vector<VariableRecord>& Header::GetVLRs() const { return m_vlrs; } void Header::DeleteVLR(uint32_t index) { if (index >= m_vlrs.size()) throw std::out_of_range("index is out of range"); std::vector<VariableRecord>::iterator i = m_vlrs.begin() + index; m_vlrs.erase(i); m_recordsCount = static_cast<uint32_t>(m_vlrs.size()); } void Header::Init() { // Initialize public header block with default // values according to LAS 1.2 m_versionMajor = 1; m_versionMinor = 2; m_createDOY = m_createYear = 0; std::time_t now; std::time(&now); std::tm* ptm = std::gmtime(&now); if (0 != ptm) { m_createDOY = static_cast<uint16_t>(ptm->tm_yday); m_createYear = static_cast<uint16_t>(ptm->tm_year + 1900); } m_headerSize = eHeaderSize; m_projectGuid = boost::uuids::nil_uuid(); m_sourceId = m_reserved = uint16_t(); m_dataOffset = eHeaderSize; // excluding 2 bytes of Point Data Start Signature m_headerPadding = 0; m_recordsCount = 0; m_pointRecordsCount = 0; std::memset(m_signature, 0, eFileSignatureSize); std::strncpy(m_signature, FileSignature, eFileSignatureSize); std::memset(m_systemId, 0, eSystemIdSize); std::strncpy(m_systemId, SystemIdentifier, eSystemIdSize); std::memset(m_softwareId, 0, eSoftwareIdSize); std::strncpy(m_softwareId, SoftwareIdentifier, eSoftwareIdSize); m_pointRecordsByReturn.resize(ePointsByReturnSize); SetScale(1.0, 1.0, 1.0); m_isCompressed = false; } bool SameVLRs(std::string const& name, uint16_t id, liblas::VariableRecord const& record) { if (record.GetUserId(false) == name) { if (record.GetRecordId() == id) { return true; } } return false; } void Header::DeleteVLRs(std::string const& name, uint16_t id) { m_vlrs.erase( std::remove_if( m_vlrs.begin(), m_vlrs.end(), boost::bind( &SameVLRs, name, id, _1 ) ), m_vlrs.end()); m_recordsCount = static_cast<uint32_t>(m_vlrs.size()); } void Header::SetGeoreference() { std::vector<VariableRecord> vlrs = m_srs.GetVLRs(); // Wipe the GeoTIFF-related VLR records off of the Header DeleteVLRs("LASF_Projection", 34735); DeleteVLRs("LASF_Projection", 34736); DeleteVLRs("LASF_Projection", 34737); std::vector<VariableRecord>::const_iterator i; for (i = vlrs.begin(); i != vlrs.end(); ++i) { AddVLR(*i); } } SpatialReference Header::GetSRS() const { return m_srs; } void Header::SetSRS(SpatialReference& srs) { m_srs = srs; } Schema const& Header::GetSchema() const { return m_schema; } void Header::SetSchema(const Schema& format) { m_schema = format; // Reset the X, Y, Z dimensions with offset and scale values boost::optional< Dimension const& > x_c = m_schema.GetDimension("X"); if (!x_c) throw liblas_error("X dimension not on schema, you\'ve got big problems!"); liblas::Dimension x(*x_c); x.SetScale(m_scales.x); x.IsFinitePrecision(true); x.SetOffset(m_offsets.x); m_schema.AddDimension(x); boost::optional< Dimension const& > y_c = m_schema.GetDimension("Y"); liblas::Dimension y(*y_c); y.SetScale(m_scales.y); y.IsFinitePrecision(true); y.SetOffset(m_offsets.y); m_schema.AddDimension(y); boost::optional< Dimension const& > z_c = m_schema.GetDimension("Z"); liblas::Dimension z(*z_c); z.SetScale(m_scales.z); z.IsFinitePrecision(true); z.SetOffset(m_offsets.z); m_schema.AddDimension(z); } void Header::SetCompressed(bool b) { m_isCompressed = b; } bool Header::Compressed() const { return m_isCompressed; } liblas::property_tree::ptree Header::GetPTree( ) const { using liblas::property_tree::ptree; ptree pt; pt.put("filesignature", GetFileSignature()); pt.put("projectdid", GetProjectId()); pt.put("systemid", GetSystemId()); pt.put("softwareid", GetSoftwareId()); std::ostringstream version; version << static_cast<int>(GetVersionMajor()); version <<"."; version << static_cast<int>(GetVersionMinor()); pt.put("version", version.str()); pt.put("filesourceid", GetFileSourceId()); pt.put("reserved", GetReserved()); ptree srs = GetSRS().GetPTree(); pt.add_child("srs", srs); std::ostringstream date; date << GetCreationDOY() << "/" << GetCreationYear(); pt.put("date", date.str()); pt.put("size", GetHeaderSize()); pt.put("dataoffset", GetDataOffset()); pt.put("header_padding", GetHeaderPadding()); pt.put("count", GetPointRecordsCount()); pt.put("dataformatid", GetDataFormatId()); pt.put("datarecordlength", GetDataRecordLength()); pt.put("compressed", Compressed()); #ifdef HAVE_LASZIP liblas::detail::ZipPoint zp(GetDataFormatId(), GetVLRs()); LASzip* laszip = zp.GetZipper(); std::ostringstream zip_version; zip_version <<"LASzip Version " << (int)laszip->version_major << "." << (int)laszip->version_minor << "r" << (int)laszip->version_revision << " c" << (int)laszip->compressor; if (laszip->compressor == LASZIP_COMPRESSOR_CHUNKED) zip_version << " "<< (int)laszip->chunk_size << ":"; else zip_version << ":"; for (int i = 0; i < (int)laszip->num_items; i++) zip_version <<" "<< laszip->items[i].get_name()<<" "<< (int)laszip->items[i].version; pt.put("compression_info", zip_version.str()); #endif ptree return_count; liblas::Header::RecordsByReturnArray returns = GetPointRecordsByReturnCount(); for (uint32_t i=0; i< 5; i++){ ptree r; r.put("id", i); r.put("count", returns[i]); return_count.add_child("return", r); } pt.add_child("returns", return_count); pt.put("scale.x", GetScaleX()); pt.put("scale.y", GetScaleY()); pt.put("scale.z", GetScaleZ()); pt.put("offset.x", GetOffsetX()); pt.put("offset.y", GetOffsetY()); pt.put("offset.z", GetOffsetZ()); pt.put("minimum.x", GetMinX()); pt.put("minimum.y", GetMinY()); pt.put("minimum.z", GetMinZ()); pt.put("maximum.x", GetMaxX()); pt.put("maximum.y", GetMaxY()); pt.put("maximum.z", GetMaxZ()); for (uint32_t i=0; i< GetRecordsCount(); i++) { pt.add_child("vlrs.vlr", GetVLR(i).GetPTree()); } liblas::Schema const& schema = GetSchema(); ptree t = schema.GetPTree(); pt.add_child("schema", t); return pt; } void Header::to_rst(std::ostream& os) const { using liblas::property_tree::ptree; ptree tree = GetPTree(); os << "---------------------------------------------------------" << std::endl; os << " Header Summary" << std::endl; os << "---------------------------------------------------------" << std::endl; os << std::endl; os << " Version: " << tree.get<std::string>("version") << std::endl; os << " Source ID: " << tree.get<uint32_t>("filesourceid") << std::endl; os << " Reserved: " << tree.get<std::string>("reserved") << std::endl; os << " Project ID/GUID: '" << tree.get<std::string>("projectdid") << "'" << std::endl; os << " System ID: '" << tree.get<std::string>("systemid") << "'" << std::endl; os << " Generating Software: '" << tree.get<std::string>("softwareid") << "'" << std::endl; os << " File Creation Day/Year: " << tree.get<std::string>("date") << std::endl; os << " Header Byte Size " << tree.get<uint32_t>("size") << std::endl; os << " Data Offset: " << tree.get<uint32_t>("dataoffset") << std::endl; os << " Header Padding: " << tree.get<uint32_t>("header_padding") << std::endl; os << " Number Var. Length Records: "; try { os << tree.get_child("vlrs").size(); } catch (liblas::property_tree::ptree_bad_path const& e) { ::boost::ignore_unused_variable_warning(e); os << "None"; } os << std::endl; os << " Point Data Format: " << tree.get<uint32_t>("dataformatid") << std::endl; os << " Number of Point Records: " << tree.get<uint32_t>("count") << std::endl; os << " Compressed: " << (tree.get<bool>("compressed")?"True":"False") << std::endl; if (tree.get<bool>("compressed")) { os << " Compression Info: " << tree.get<std::string>("compression_info") << std::endl; } os << " Number of Points by Return: " ; BOOST_FOREACH(ptree::value_type &v, tree.get_child("returns")) { os << v.second.get<uint32_t>("count")<< " "; } os << std::endl; os.setf(std::ios_base::fixed, std::ios_base::floatfield); double x_scale = tree.get<double>("scale.x"); double y_scale = tree.get<double>("scale.y"); double z_scale = tree.get<double>("scale.z"); uint32_t x_precision = 14;//GetStreamPrecision(x_scale); uint32_t y_precision = 14; //GetStreamPrecision(y_scale); uint32_t z_precision = 14; //GetStreamPrecision(z_scale); os << " Scale Factor X Y Z: "; os.precision(x_precision); os << tree.get<double>("scale.x") << " "; os.precision(y_precision); os << tree.get<double>("scale.y") << " "; os.precision(z_precision); os << tree.get<double>("scale.z") << std::endl; x_precision = GetStreamPrecision(x_scale); y_precision = GetStreamPrecision(y_scale); z_precision = GetStreamPrecision(z_scale); os << " Offset X Y Z: "; os.precision(x_precision); os << tree.get<double>("offset.x") << " "; os.precision(y_precision); os << tree.get<double>("offset.y") << " "; os.precision(z_precision); os << tree.get<double>("offset.z") << std::endl; os << " Min X Y Z: "; os.precision(x_precision); os << tree.get<double>("minimum.x") << " "; os.precision(y_precision); os << tree.get<double>("minimum.y") << " "; os.precision(z_precision); os << tree.get<double>("minimum.z") << std::endl; os << " Max X Y Z: "; os.precision(x_precision); os << tree.get<double>("maximum.x") << " "; os.precision(y_precision); os << tree.get<double>("maximum.y") << " "; os.precision(z_precision); os << tree.get<double>("maximum.z") << std::endl; os << " Spatial Reference: "; #ifdef HAVE_GDAL if (tree.get<std::string>("srs.prettywkt").size() > 0) #else if (tree.get<std::string>("srs.gtiff").size() > 0) #endif { os << std::endl << tree.get<std::string>("srs.prettywkt") << std::endl; os << std::endl << tree.get<std::string>("srs.gtiff") << std::endl; } else { os << "None" << std::endl; } } std::ostream& operator<<(std::ostream& os, liblas::Header const& h) { h.to_rst(os); return os; } } // namespace liblas
#include <iostream> #include <vector> using namespace std; int main() { int n; cin>>n; int a[n]; int leftout = 0,rightout = n - 1,temp = 0,sum = -1,templeft = 0; for(int i = 0;i < n;i++){ cin>>a[i]; temp = temp + a[i]; if(temp > sum){ sum = temp; rightout = i; leftout = templeft; }else if(temp < 0){ temp = 0; templeft = i + 1; } } if(sum < 0) sum = 0; cout<<sum<<" "<<a[leftout]<<" "<<a[rightout]; return 0; }
#include<iostream> #include<algorithm> using namespace std; int main() { int x, n, q, a[100000]; cin >> n >> q; for(int i=0;i<n; ++i) cin>>a[i]; sort(a, a+n); for(int i=0; i<q; ++i) { cin >> x; int lo, hi, mid; lo = 0; hi = n-1; bool isPresent = false; while(lo <= hi) { mid = (lo + hi)/2; if(a[mid] == x) { isPresent = true; break; } else if(a[mid] > x) hi = mid - 1; else lo = mid + 1; } if(isPresent) cout << "YES" << endl; else cout<<"NO"<<endl; } return 0; }
// // Created by charris on 6/29/20. // #include "ros/ros.h" #include "std_msgs/String.h" #include "ros_tutorials/Score.h" class RosNodeExample{ public: explicit RosNodeExample(ros::NodeHandle &nh): _nh(nh){ initialize_stuff(); } void initialize_stuff() { ROS_INFO("Initializing subs and pubs..."); _pub = _nh.advertise<ros_tutorials::Score>("score_updated", 10); // Subscriber _sub = _nh.subscribe("score", 10, &RosNodeExample::callback, this); // Params _name = "Johnathan"; _number = 100; } void callback(const ros_tutorials::Score::ConstPtr &msg) { ROS_INFO("Message received for %s with score %i", msg->first_name.c_str(), msg->score); ros_tutorials::Score score_new; score_new.score = msg->score + 1; score_new.first_name = _name; score_new.last_name = msg->last_name; score_new.age = msg->age; _pub.publish(score_new); } // OTHER FUNCTIONS HERE void spin() { ros::spin(); } private: // Node // ros::NodeHandle _nh; ros::NodeHandle _nh; ros::Subscriber _sub; // Publishers ros::Publisher _pub; uint _number; std::string _name; }; int main(int argc, char **argv) { // Initialize ROS ros::init(argc,argv,"pub_sub_node"); ros::NodeHandle nh; RosNodeExample pf(nh); ROS_INFO("node spinning."); pf.spin(); return 0; } // // Created by charris on 6/29/20. //
/* Copyright (c) 2007-2022 Xavier Leclercq Released under the MIT License See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt */ #include "TestHarnessTests.hpp" #include "Ishiko/TestFramework/Core/TestHarness.hpp" #include <boost/filesystem.hpp> #include <Ishiko/Configuration.hpp> using namespace Ishiko; TestHarnessTests::TestHarnessTests(const TestNumber& number, const TestContext& context) : TestSequence(number, "TestHarness tests", context) { append<HeapAllocationErrorsTest>("Constructor test 1", ConstructorTest1); append<HeapAllocationErrorsTest>("Constructor test 2", ConstructorTest2); append<HeapAllocationErrorsTest>("run test 1", RunTest1); append<HeapAllocationErrorsTest>("run test 2", RunTest2); append<HeapAllocationErrorsTest>("run test 3", RunTest3); append<HeapAllocationErrorsTest>("run test 4", RunTest4); append<HeapAllocationErrorsTest>("JUnit XML test report test 1", JUnitXMLReportTest1); append<HeapAllocationErrorsTest>("JUnit XML test report test 2", JUnitXMLReportTest2); append<HeapAllocationErrorsTest>("JUnit XML test report test 3", JUnitXMLReportTest3); append<HeapAllocationErrorsTest>("JUnit XML test report test 4", JUnitXMLReportTest4); } void TestHarnessTests::ConstructorTest1(Test& test) { TestHarness theTestHarness("TestHarnessTests_ConstructorTest1"); ISHIKO_TEST_PASS(); } void TestHarnessTests::ConstructorTest2(Test& test) { // This is not really a persistent storage path, we only need an arbitrary path for testing boost::filesystem::path outputPath = test.context().getOutputPath("TestHarnessTests_ConstructorTest2.xml"); Configuration configuration = TestHarness::CommandLineSpecification().createDefaultConfiguration(); configuration.set("persistent-storage", outputPath.string()); TestHarness theTestHarness("TestHarnessTests_ConstructorTest2", configuration); ISHIKO_TEST_FAIL_IF_NEQ(theTestHarness.context().getOutputDirectory("persistent-storage"), outputPath); ISHIKO_TEST_PASS(); } void TestHarnessTests::RunTest1(Test& test) { TestHarness theTestHarness("TestHarnessTests_RunTest1"); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::testFailure); ISHIKO_TEST_PASS(); } void TestHarnessTests::RunTest2(Test& test) { TestHarness theTestHarness("TestHarnessTests_RunTest2"); std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); theTestHarness.tests().append(test1); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::ok); ISHIKO_TEST_PASS(); } void TestHarnessTests::RunTest3(Test& test) { TestHarness theTestHarness("TestHarnessTests_RunTest3"); std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::skipped); theTestHarness.tests().append(test1); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::ok); ISHIKO_TEST_PASS(); } void TestHarnessTests::RunTest4(Test& test) { TestHarness theTestHarness("TestHarnessTests_RunTest2"); std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); theTestHarness.tests().append(test1); std::shared_ptr<Test> test2 = std::make_shared<Test>(TestNumber(2), "Test", TestResult::failed); theTestHarness.tests().append(test2); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::testFailure); ISHIKO_TEST_PASS(); } void TestHarnessTests::JUnitXMLReportTest1(Test& test) { boost::filesystem::path outputPath = test.context().getOutputPath("TestHarnessTests_JUnitXMLReportTest1.xml"); Configuration configuration = TestHarness::CommandLineSpecification().createDefaultConfiguration(); configuration.set("junit-xml-test-report", outputPath.string()); TestHarness theTestHarness("TestHarnessTests_JUnitXMLReportTest1", configuration); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::testFailure); ISHIKO_TEST_FAIL_IF_OUTPUT_AND_REFERENCE_FILES_NEQ("TestHarnessTests_JUnitXMLReportTest1.xml"); ISHIKO_TEST_PASS(); } void TestHarnessTests::JUnitXMLReportTest2(Test& test) { boost::filesystem::path outputPath = test.context().getOutputPath("TestHarnessTests_JUnitXMLReportTest2.xml"); Configuration configuration = TestHarness::CommandLineSpecification().createDefaultConfiguration(); configuration.set("junit-xml-test-report", outputPath.string()); TestHarness theTestHarness("TestHarnessTests_JUnitXMLReportTest2", configuration); std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); theTestHarness.tests().append(test1); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::ok); ISHIKO_TEST_FAIL_IF_OUTPUT_AND_REFERENCE_FILES_NEQ("TestHarnessTests_JUnitXMLReportTest2.xml"); ISHIKO_TEST_PASS(); } void TestHarnessTests::JUnitXMLReportTest3(Test& test) { boost::filesystem::path outputPath = test.context().getOutputPath("TestHarnessTests_JUnitXMLReportTest3.xml"); Configuration configuration = TestHarness::CommandLineSpecification().createDefaultConfiguration(); configuration.set("junit-xml-test-report", outputPath.string()); TestHarness theTestHarness("TestHarnessTests_JUnitXMLReportTest3", configuration); std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::skipped); theTestHarness.tests().append(test1); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::ok); ISHIKO_TEST_FAIL_IF_OUTPUT_AND_REFERENCE_FILES_NEQ("TestHarnessTests_JUnitXMLReportTest3.xml"); ISHIKO_TEST_PASS(); } void TestHarnessTests::JUnitXMLReportTest4(Test& test) { boost::filesystem::path outputPath = test.context().getOutputPath("TestHarnessTests_JUnitXMLReportTest4.xml"); Configuration configuration = TestHarness::CommandLineSpecification().createDefaultConfiguration(); configuration.set("junit-xml-test-report", outputPath.string()); TestHarness theTestHarness("TestHarnessTests_JUnitXMLReportTest4", configuration); std::shared_ptr<Test> test1 = std::make_shared<Test>(TestNumber(1), "Test", TestResult::passed); theTestHarness.tests().append(test1); std::shared_ptr<Test> test2 = std::make_shared<Test>(TestNumber(2), "Test", TestResult::failed); theTestHarness.tests().append(test2); int returnCode = theTestHarness.run(); ISHIKO_TEST_FAIL_IF_NEQ(returnCode, TestApplicationReturnCode::testFailure); ISHIKO_TEST_FAIL_IF_OUTPUT_AND_REFERENCE_FILES_NEQ("TestHarnessTests_JUnitXMLReportTest4.xml"); ISHIKO_TEST_PASS(); }
/* * Stopping Times * Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com> */ #ifndef _TESTER_H_ #define _TESTER_H_ #include "test.h" #include <memory> #include <vector> #include <utility> #include <vector> #include "logger.h" namespace StoppingTimes{ namespace Testing{ class Tester { public: void runAll(Logger * logger); void loadAll(const char* path); void add(Test* t); ~Tester(); protected: private: std::vector< std::unique_ptr<Test> > tests_; }; }} #endif // _TESTER_H_
#include <conio.h> #include <iostream.h> void main () { int op,op1,op2,op3,op4; float feet, meter; do { // Start of Main dowhile clrscr(); cout <<"\n\t\tOPTIONAL SOFTWARE\n"; cout <<"\n\n\t1. Calculator"; cout <<"\n\n\t2. Weight"; cout <<"\n\n\t3. Temperature"; cout <<"\n\n\t4. Length"; cout <<"\n\n\t5. Exit"; cout <<"\n\n\tEnter your choice: "; cin >>op; switch (op) { int a,b; case 1: do { // Start of nested dowhile-1 clrscr(); cout <<"\n\n\tWELCOME TO CALCULATOR"; cout <<"\n\n\t1. Addition"; cout <<"\n\n\t2. Subtraction"; cout <<"\n\n\t3. Multiplication"; cout <<"\n\n\t4. Division"; cout <<"\n\n\t5. Remainder"; cout <<"\n\n\t6. Back"; cout <<"\n\n\tEnter your choice: "; cin >>op1; switch (op1) { // Start of inner Switch clrscr(); case 1: cout <<"\n\n\tWELCOME TO ADDITION"; cout <<"\n\n\tEnter 1st value: "; cin >>a; cout <<"\n\n\tEnter 2nd value: "; cin >>b; cout <<"\n\n\tThe Addition is: " <<a+b; break; case 2: cout <<"\n\n\tWELCOME TO SUBTRACTION"; cout <<"\n\n\tEnter 1st value: "; cin >>a; cout <<"\n\n\tEnter 2nd value: "; cin >>b; cout <<"\n\n\tThe Subtraction is: " <<a-b; break; case 3: cout <<"\n\n\tWELCOME TO MULTIPLICATION"; cout <<"\n\n\tEnter 1st value: "; cin >>a; cout <<"\n\n\tEnter 2nd value: "; cin >>b; cout <<"\n\n\tThe Multiplication is: " <<a*b; break; case 4: cout <<"\n\n\tWELCOME TO DIVISION"; cout <<"\n\n\tEnter 1st value: "; cin >>a; cout <<"\n\n\tEnter 2nd value: "; cin >>b; cout <<"\n\n\tThe Division is: " <<a/b; break; case 5: cout <<"\n\n\tWELCOME TO REMAINDER"; cout <<"\n\n\tEnter 1st value: "; cin >>a; cout <<"\n\n\tEnter 2nd value: "; cin >>b; cout <<"\n\n\tThe Remainder is: " <<a%b; break; case 6: continue; break; default: cout <<"\n\n\tInvalid choice !"; break; } // End of Inner Switch getche(); } while (op1!=6); // End of Nested Dowhile-1 break; case 2: do { // Start of Nested DoWhile-2 clrscr(); cout <<"\n\n\tWELCOME TO WEIGHT CONVERTOR"; cout <<"\n\n\tWeight Convertor"; cout <<"\n\n\t1. Gram into Kilogram"; cout <<"\n\n\t2. Kilogram into Gram"; cout <<"\n\n\t3. Pounds into Kilogram"; cout <<"\n\n\t4. Kilogram into Pounds"; cout <<"\n\n\t5. Gram into Pounds"; cout <<"\n\n\t6. Pounds into Gram"; cout <<"\n\n\t7. Back"; cout <<"\n\n\n\tEnter the case no. for desired conversion:"; cin >>op2; switch (op2) { // Start of inner switch 2 clrscr(); case 1: float gm, kg, pd; clrscr(); cout <<"\n\n\t\tConversion of Gram into Kilogram"; cout <<"\n\n\n\tEnter the value in Grams = "; cin >>gm; kg=(gm*0.001); cout <<"\n\n\tThe given Grams are equal to "; cout <<kg; cout <<" Kilograms"; break; case 2: clrscr(); cout <<"\n\n\t\tConversion of Kilogram into Gram"; cout <<"\n\n\n\tEnter the value in Kilograms = "; cin >>kg; gm=(kg*1000); cout <<"\n\n\tThe given Kilograms are equal to "; cout <<gm; cout <<" Grams"; break; case 3: clrscr(); cout <<"\n\n\t\tConversion of Pounds into Kilogram"; cout <<"\n\n\n\tEnter the value in Pounds = "; cin >>pd; kg=(pd*0.45359237); cout <<"\n\n\tThe given Pounds are equal to "; cout <<kg; cout <<" Kilograms"; break; case 4: clrscr(); cout <<"\n\n\t\tConversion of Kilogram into Pounds"; cout <<"\n\n\n\tEnter the value in Kilograms = "; cin >>kg; pd=(kg*2.20462262); cout <<"\n\n\tThe given Kilograms are equal to "; cout <<pd; cout <<" Pounds"; break; case 5: clrscr(); cout <<"\n\n\t\tConversion of Gram into Pounds"; cout <<"\n\n\n\tEnter the value in Grams = "; cin >>gm; pd=(gm*0.00220462262); cout <<"\n\n\tThe given Grams are equal to "; cout <<pd; cout <<" Pounds"; break; case 6: clrscr(); cout <<"\n\n\t\tConversion of Pounds into Gram"; cout <<"\n\n\n\tEnter the value in Pounds = "; cin >>pd; gm=(pd*453.59237); cout <<"\n\n\tThe given Pounds are equal to "; cout <<gm; cout <<" Grams"; break; case 7: continue; break; default: cout <<"\n\n\tInvalid choice !"; break; } // End of inner switch 2 getche(); } while (op2!=7); // End of Nested DoWhile-2 break; case 3: do { //Start of Nested DoWhile-3 float c,f,k; clrscr(); cout <<"\n\t\tWELCOME TO TEMPERATURE CONVERTOR\n"; cout <<"\n\t1. Celsius into Fahrenhiet"; cout <<"\n\t2. Fahrenhiet into Celsius"; cout <<"\n\t3. Kelvin into Celsius"; cout <<"\n\t4. Celsius into Kelvin"; cout <<"\n\t5. Kelvin into Fahrenhiet"; cout <<"\n\t6. Fahrenhiet into Kelvin"; cout <<"\n\t7. Back"; cout <<"\n\nEnter any choice: "; cin >>op3; switch (op3) { // Start of Inner Switch 3 case 1: cout <<"\n\n\tCelsius into Fahrenhiet Convertor"; cout <<"\n\nEnter temperature in øC: "; cin >> c; f = (c*9/5)+32; cout <<"\n\tThe given temperature in Fahrenhiet is: "; cout << f; cout << "øF"; break; case 2: cout <<"\n\tFahrenhiet into Celsius Convertor"; cout <<"\n\nEnter temperature øF: "; cin >> f; c = (f*5/9)-32; cout <<"\n\tThe given temperature in Celsius is: "; cout << c; cout << "øC"; break; case 3: cout <<"\n\tKelvin into Celsius Convertor"; cout <<"\n\nEnter temperature in øK:"; cin >> k; c = (k-273.15); cout <<"\n\tThe given temperature in Celsius is: "; cout << c; cout << "øC"; break; case 4: cout <<"\n\tCelsius into Kelvin Convertor"; cout <<"\n\nEnter temperature in øC: "; cin >> c; k = (c+273.15); cout <<"\n\tThe given temperature in Kelvin is: "; cout << k; cout << "øK"; break; case 5: cout <<"\n\tKelvin into Fahrenhiet Convertor"; cout <<"\n\nEnter temperature in øK: "; cin >> k; f = ((k - 273) * 9/5 ) + 32; cout <<"\n\tThe given temperature in Fahrenhiet is: "; cout << f; cout << "øF"; break; case 6: cout <<"\n\tFahrenhiet into Kelvin Convertor"; cout <<"\n\nEnter temperature in øF: "; cin >> f; k = (5/9*(f - 32) + 273); cout <<"\n\tThe given temperature in Kelvin is: "; cout << k; cout << "øK"; break; case 7: continue; break; default: cout <<"\n\tInvalid choice !"; break; } // End of inner Switch 3 getche(); } while (op3!=7); //End of Nested DoWhile-3 break; case 4: do { // Start of Nested DoWhile-4 clrscr(); cout <<"\n\n\t\tWELCOME TO LENGTH CONVERTOR"; cout <<"\n\n\t1. Feet into Meter"; cout <<"\n\n\t2. Meter into Feet"; cout <<"\n\n\t3. Back"; cout <<"\n\n\tEnter your Choice: "; cin >>op4; switch (op4) { // Start of Inner Switch 4 case 1: cout <<"\n\n\t\tFeet into Meter Convertor"; cout <<"\n\n\tEnter value in feet: "; cin >>feet; cout <<"\n\n\tThe given feet in meter is: " <<feet*0.3048; break; case 2: cout <<"\n\n\t\tMeter into Feet Convertor"; cout <<"\n\n\tEnter value in meter: "; cin >>meter; cout <<"\n\n\tThe given meter in feet is: " <<meter/0.3048; break; case 3: continue; break; default: cout <<"\n\n\tInvalid choice !"; break; } // End of inner switch 4 getche(); } while(op4!=3); // End of Nested Dowhile-4 break; case 5: continue; break; if (op>5) { default: cout<<"\n\n\tInvalid choice !"; cout<<"\n\n\tPress Enter to go back"; getche(); break; } } } while (op!=5); // End of Main DoWhile }
#include <iostream> #include <string> using namespace std; inline int min(int a, int b) { return (a>b)? b : a; } int edit_dist(string &str1, string &str2) { int n1 = str1.size(); int n2 = str2.size(); int d[str1.size()][str2.size()]; for(int i = 0; i <= n2; i++) d[0][i] = i; for(int i = 0; i <= n1; i++) d[i][0] = i; for(int i = 1; i <= n1; i++) { for(int j = 1; j <= n2; j++) { d[i][j] = min(d[i-1][j] + 1, d[i][j-1] + 1); d[i][j] = min(d[i][j], (d[i-1][j-1] + (str1[i-1] != str2[j-1]))); } } return d[n1][n2]; } int main(int argc, char **argv) { string str1; string str2; cin >> str1; cin >> str2; int dist = edit_dist(str1, str2); cout << dist << endl; return 0; }
// // Created by Данил Козловский on 2019-03-28. // #ifndef INC_2_FACTORY_H #define INC_2_FACTORY_H #include "triangle.h" #include "rectangle.h" class Factory { public: triangle* addObjectTr(); rectangle* addObjectRe(); void deleteObjects(rectangle *re, triangle *tr); }; #endif //INC_2_FACTORY_H
// Created on: 2001-09-10 // Created by: Sergey KUUL // Copyright (c) 2001-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Transfer_MapContainer_HeaderFile #define _Transfer_MapContainer_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TColStd_DataMapOfTransientTransient.hxx> #include <Standard_Transient.hxx> class Transfer_MapContainer; DEFINE_STANDARD_HANDLE(Transfer_MapContainer, Standard_Transient) class Transfer_MapContainer : public Standard_Transient { public: Standard_EXPORT Transfer_MapContainer(); //! Set map already translated geometry objects. Standard_EXPORT void SetMapObjects (TColStd_DataMapOfTransientTransient& theMapObjects); //! Get map already translated geometry objects. Standard_EXPORT TColStd_DataMapOfTransientTransient& GetMapObjects(); DEFINE_STANDARD_RTTIEXT(Transfer_MapContainer,Standard_Transient) protected: private: TColStd_DataMapOfTransientTransient myMapObj; }; #endif // _Transfer_MapContainer_HeaderFile
//: C16:TStack2.h // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Szablon klasy Stack, zawierajacy zagniezdzony iterator #ifndef TSTACK2_H #define TSTACK2_H template<class T> class Stack { struct Link { T* data; Link* next; Link(T* dat, Link* nxt) : data(dat), next(nxt) {} }* head; public: Stack() : head(0) {} ~Stack(); void push(T* dat) { head = new Link(dat, head); } T* peek() const { return head ? head->data : 0; } T* pop(); // Zagniezdzona klasa iteratora: class iterator; // Wymagana deklaracja friend class iterator; // Uczyn klase przyjacielem class iterator { // A teraz ja zdefiniuj Stack::Link* p; public: iterator(const Stack<T>& tl) : p(tl.head) {} // Konstruktor kopiujacy: iterator(const iterator& tl) : p(tl.p) {} // Iterator bedacy znacznikiem konca: iterator() : p(0) {} // operator++ zwraca wartosc logiczna sygnalizujaca koniec: bool operator++() { if(p->next) p = p->next; else p = 0; // Koniec listy return bool(p); } bool operator++(int) { return operator++(); } T* current() const { if(!p) return 0; return p->data; } // Operator wyluskania wskaznika: T* operator->() const { require(p != 0, "PStack::iterator::operator-> zwrocil 0"); return current(); } T* operator*() const { return current(); } // Konwersja do typu bool, do testow warunkow: operator bool() const { return bool(p); } // Porownanie, umozliwiajace wykrycie konca: bool operator==(const iterator&) const { return p == 0; } bool operator!=(const iterator&) const { return p != 0; } }; iterator begin() const { return iterator(*this); } iterator end() const { return iterator(); } }; template<class T> Stack<T>::~Stack() { while(head) delete pop(); } template<class T> T* Stack<T>::pop() { if(head == 0) return 0; T* result = head->data; Link* oldHead = head; head = head->next; delete oldHead; return result; } #endif // TSTACK2_H ///:~
#ifndef FOOTSIES_H #define FOOTSIES_H #include "Character/Character.h" #include "Character/Move.h" #include "Character/Frame.h" #include "Stage/Stage.h" class Character; class Footsies { public: int initial_separation; int stage_boundaries; Character *character1; Character *character2; Stage *stage; int counter; int frame; int player1_wins; int player2_wins; bool game_over; int game_over_frames; Footsies(); void gameLoop(); }; #endif
#ifndef BAZOOKABULLET_H #define BAZOOKABULLET_H #include "bullet.h" class BazookaBullet : public Bullet { void setRadiusDamage(); bool isInRadius(Element *e); int _radius; public: BazookaBullet(XY pos, XY velo, int bullet_power, int radius, Team *aggressor_team, GameManager *game); void hurtElements(); void handleCollisions(); }; #endif // BAZOOKABULLET_H
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * 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 * */ // // Network topology // // n0 // \ 5 Mb/s, 2ms // \ 1.5Mb/s, 10ms // n2 -------------------------n3 // / // / 5 Mb/s, 2ms // n1 // // - all links are point-to-point links with indicated one-way BW/delay // - CBR/UDP flows from n0 to n3, and from n3 to n1 // - FTP/TCP flow from n0 to n3, starting at time 1.2 to time 1.35 sec. // - UDP packet size of 210 bytes, with per-packet interval 0.00375 sec. // (i.e., DataRate of 448,000 bps) // - DropTail queues // - Tracing of queues and packet receptions to file "simple-global-routing.tr" #include <iostream> #include <fstream> #include <string> #include <cassert> // #include <fstream> #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h" #include "ns3/flow-monitor-helper.h" #include "ns3/ipv4-global-routing-helper.h" #include "ns3/flow-monitor-module.h" #include <fstream> #include "ns3/gnuplot.h" using namespace ns3; NS_LOG_COMPONENT_DEFINE ("SimpleGlobalRoutingExample"); Ptr<PacketSink> cbrsink , tcpSink; AsciiTraceHelper ascii; using namespace ns3; int main (int argc, char *argv[]) { // Users may find it convenient to turn on explicit debugging // for selected modules; the below lines suggest how to do this #if 0 LogComponentEnable ("SimpleGlobalRoutingExample", LOG_LEVEL_INFO); #endif std::string plotFileName1 = "UDP.plt"; std::string plotFileName2 = "TcpHighSpeed.plt"; Gnuplot plot1 ("UDP.png"); Gnuplot plot2 ("TcpHighSpeed.png"); plot1.SetTitle ("UDP"); plot1.SetTerminal ("png"); plot1.SetLegend ("Packet_size", "Throughput"); plot1.AppendExtra ("set xrange [0:10500]"); plot2.SetTitle ("TCP_highspeed"); plot2.SetTerminal ("png"); plot2.SetLegend ("Packet_size", "Throughput"); plot2.AppendExtra ("set xrange [0:10500]"); Gnuplot2dDataset dataset1,dataset2; dataset1.SetTitle ("UDP"); dataset1.SetStyle (Gnuplot2dDataset::LINES_POINTS); dataset2.SetTitle ("TCP_highspeed"); dataset2.SetStyle (Gnuplot2dDataset::LINES_POINTS); //bool tracing = false; // Set up some default values for the simulation. Use the for(uint32_t maxBytes = 500;maxBytes<10500;maxBytes += 100){ Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (210)); Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("448kb/s")); Config::SetDefault ("ns3::TcpL4Protocol::SocketType", TypeIdValue (TcpHighSpeed::GetTypeId ())); //DefaultValue::Bind ("DropTailQueue::m_maxPackets", 30); // Allow the user to override any of the defaults and the above // DefaultValue::Bind ()s at run-time, via command-line arguments CommandLine cmd; bool enableFlowMonitor = false; cmd.AddValue ("EnableMonitor", "Enable Flow Monitor", enableFlowMonitor); cmd.Parse (argc, argv); // Here, we will explicitly create four nodes. In more sophisticated // topologies, we could configure a node factory. NS_LOG_INFO ("Create nodes."); NodeContainer c; c.Create (6); NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2)); NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2)); NodeContainer n2n3 = NodeContainer (c.Get (2), c.Get (3)); // NodeContainer n3n2 = NodeContainer (c.Get (3), c.Get (2)); NodeContainer n3n4 = NodeContainer (c.Get (3), c.Get (4)); NodeContainer n3n5 = NodeContainer (c.Get (3), c.Get (5)); InternetStackHelper internet; internet.Install (c); // We create the channels first without any IP addressing information NS_LOG_INFO ("Create channels."); PointToPointHelper p2p; // p2p.SetDeviceAttribute ("DataRate", StringValue ("10000000")); p2p.SetDeviceAttribute ("DataRate", StringValue ("80Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("20ms")); NetDeviceContainer d0d2 = p2p.Install (n0n2); NetDeviceContainer d1d2 = p2p.Install (n1n2); NetDeviceContainer d3d4 = p2p.Install (n3n4); NetDeviceContainer d3d5 = p2p.Install (n3n5); const uint16_t a = 64000; (*d1d2.Get(0)).SetMtu(a); (*d0d2.Get(0)).SetMtu(a); (*d3d4.Get(0)).SetMtu(a); (*d3d5.Get(0)).SetMtu(a); p2p.SetDeviceAttribute ("DataRate", StringValue ("30Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("100ms")); uint32_t qshr = (30*1024*1024)/(10*1024*8); p2p.SetQueue ("ns3::DropTailQueue", "MaxPackets" , UintegerValue(qshr)); // NetDeviceContainer d3d2 = p2p.Install (n3n2); NetDeviceContainer d2d3 = p2p.Install (n2n3); (*d2d3.Get(0)).SetMtu(a); // Later, we add IP addresses. NS_LOG_INFO ("Assign IP Addresses."); Ipv4AddressHelper ipv4; ipv4.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer i0i2 = ipv4.Assign (d0d2); ipv4.SetBase ("10.1.2.0", "255.255.255.0"); Ipv4InterfaceContainer i1i2 = ipv4.Assign (d1d2); ipv4.SetBase ("10.1.3.0", "255.255.255.0"); Ipv4InterfaceContainer i2i3 = ipv4.Assign (d2d3); ipv4.SetBase ("10.1.4.0", "255.255.255.0"); Ipv4InterfaceContainer i3i4 = ipv4.Assign (d3d4); ipv4.SetBase ("10.1.5.0", "255.255.255.0"); Ipv4InterfaceContainer i3i5 = ipv4.Assign (d3d5); // Create router nodes, initialize routing database and set up the routing // tables in the nodes. Ipv4GlobalRoutingHelper::PopulateRoutingTables (); // Create the OnOff application to send UDP datagrams of size // 210 bytes at a rate of 448 Kb/s //holla niggers chose diffrent data rates here :P :P // uint32_t maxBytes = 1024; Config::SetDefault ("ns3::TcpSocket::SegmentSize", UintegerValue (maxBytes)); NS_LOG_INFO ("Create Applications."); uint16_t port = 9; // Discard port (RFC 863) OnOffHelper onoff ("ns3::UdpSocketFactory", Address (InetSocketAddress (i3i4.GetAddress (1), port))); onoff.SetConstantRate (DataRate ("2Mb/s")); onoff.SetAttribute ("PacketSize", UintegerValue (maxBytes)); ApplicationContainer apps = onoff.Install (c.Get (0)); apps.Start (Seconds (0.0)); apps.Stop (Seconds (5.0)); // Create a packet sink to receive these packets PacketSinkHelper sink ("ns3::UdpSocketFactory", Address (InetSocketAddress (Ipv4Address::GetAny (), port))); apps = sink.Install (c.Get (4)); apps.Start (Seconds (0.0)); apps.Stop (Seconds (5.0)); onoff.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); onoff.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); cbrsink = DynamicCast<PacketSink> (apps.Get (0)); uint16_t port2 = 12344; // well-known echo port number BulkSendHelper source ("ns3::TcpSocketFactory",InetSocketAddress (i3i5.GetAddress (1), port2)); source.SetAttribute ("MaxBytes", UintegerValue (0)); ApplicationContainer sourceApps = source.Install (c.Get (1)); sourceApps.Start (Seconds (5.0)); sourceApps.Stop (Seconds (10.0)); PacketSinkHelper sink2 ("ns3::TcpSocketFactory",InetSocketAddress (Ipv4Address::GetAny (), port2)); ApplicationContainer sinkApps = sink2.Install (c.Get (5)); sinkApps.Start (Seconds (5.0)); sinkApps.Stop (Seconds (10.0)); tcpSink = DynamicCast<PacketSink> (sinkApps.Get (0)); // // Trace changes to the congestion window // // ...and schedule the sending "Application"; This is similar to what an // ns3::Application subclass would do internally. AsciiTraceHelper ascii; p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-global-routing.tr")); p2p.EnablePcapAll ("simple-global-routing"); // Flow Monitor FlowMonitorHelper flowmonHelper; if (enableFlowMonitor){flowmonHelper.InstallAll ();} NS_LOG_INFO ("Run Simulation."); Ptr<FlowMonitor> flowMonitor; FlowMonitorHelper flowHelper; flowMonitor = flowHelper.InstallAll(); Simulator::Stop (Seconds (11)); Simulator::Run (); Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowHelper.GetClassifier ()); std::map<FlowId, FlowMonitor::FlowStats> stats = flowMonitor->GetFlowStats (); // std::fstream fs; // fs.open("/home/sour/Documents/ns-allinone-3.28/ns-3.28/z0.txt", std::fstream::in | std::fstream::out); // myfile.open ("example.txt"); // ofstream myfile; // myfile.open ("example.txt", ios_base::openmode mode = ios_base::in | ios_base::out); // myfile.open ("example.bin", ios::out ); for(std::map<FlowId, FlowMonitor::FlowStats>::iterator i = stats.begin();i != stats.end();i++) { Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow(i->first); if(t.sourceAddress == "10.1.1.1"){ double x = maxBytes; double y = i->second.rxBytes * 8.0 / (i->second.timeLastRxPacket.GetSeconds () - i->second.timeFirstRxPacket.GetSeconds ()) / 1000000; dataset1.Add (x, y); } if(t.sourceAddress == "10.1.2.1"){ double x = maxBytes; double y = i->second.rxBytes * 8.0 / (i->second.timeLastRxPacket.GetSeconds () - i->second.timeFirstRxPacket.GetSeconds ()) / 1000000; dataset2.Add (x, y); } } flowMonitor->SerializeToXmlFile("data.flowmon", true, true); Simulator::Destroy (); } plot1.AddDataset (dataset1); plot2.AddDataset (dataset2); std::ofstream plotFile1 (plotFileName1.c_str()); plot1.GenerateOutput (plotFile1); plotFile1.close (); std::ofstream plotFile2 (plotFileName2.c_str()); plot2.GenerateOutput (plotFile2); plotFile2.close (); // plot2.AddDataset (dataset2); // std::ofstream plotFile (plotFileName2.c_str()); // plot2.GenerateOutput (plotFile2); // plotFile2.close (); NS_LOG_INFO ("Done."); return 0; }
#ifndef CUDA_GKNP_KERNELS_H_ #define CUDA_GKNP_KERNELS_H_ /* -------------------------------------------------------------------------- * * OpenMM-GKNP * * -------------------------------------------------------------------------- */ #include "GKNPKernels.h" #include "openmm/cuda/CudaContext.h" #include "openmm/cuda/CudaArray.h" #include "openmm/reference/RealVec.h" using namespace std; namespace GKNPPlugin { /** * This kernel is invoked by GKNPForce to calculate the forces acting on the system and the energy of the system. */ class CudaCalcGKNPForceKernel : public CalcGKNPForceKernel { public: CudaCalcGKNPForceKernel(std::string name, const OpenMM::Platform &platform, OpenMM::CudaContext &cu, const OpenMM::System &system) : CalcGKNPForceKernel(name, platform), cu(cu), system(system) { hasCreatedKernels = false; hasInitializedKernels = false; radtypeScreened = NULL; radtypeScreener = NULL; selfVolume = NULL; selfVolumeLargeR = NULL; Semaphor = NULL; volScalingFactor = NULL; BornRadius = NULL; invBornRadius = NULL; invBornRadius_fp = NULL; GBDerY = NULL; GBDerBrU = NULL; GBDerU = NULL; VdWDerBrW = NULL; VdWDerW = NULL; GaussianExponent = NULL; GaussianVolume = NULL; GaussianExponentLargeR = NULL; GaussianVolumeLargeR = NULL; AtomicGamma = NULL; grad = NULL; //i4_lut = NULL; PanicButton = NULL; pinnedPanicButtonBuffer = NULL; } ~CudaCalcGKNPForceKernel(); /** * Initialize the kernel. * * @param system the System this kernel will be applied to * @param force the GKNPForce this kernel will be used for */ void initialize(const OpenMM::System &system, const GKNPForce &force); /** * Execute the kernel to calculate the forces and/or energy. * * @param context the context in which to execute this kernel * @param includeForces true if forces should be calculated * @param includeEnergy true if the energy should be calculated * @return the potential energy due to the force */ double execute(OpenMM::ContextImpl &context, bool includeForces, bool includeEnergy); /** * Copy changed parameters over to a context. * * @param context the context to copy parameters to * @param force the GKNPForce to copy the parameters from */ void copyParametersToContext(OpenMM::ContextImpl &context, const GKNPForce &force); class CudaOverlapTree { public: CudaOverlapTree(void) { ovAtomTreePointer = NULL; ovAtomTreeSize = NULL; ovTreePointer = NULL; ovNumAtomsInTree = NULL; ovFirstAtom = NULL; NIterations = NULL; ovAtomTreePaddedSize = NULL; ovAtomTreeLock = NULL; ovLevel = NULL; ovG = NULL; ovVolume = NULL; ovVsp = NULL; ovVSfp = NULL; ovSelfVolume = NULL; ovVolEnergy = NULL; ovGamma1i = NULL; ovDV1 = NULL; ovDV2 = NULL; ovPF = NULL; ovLastAtom = NULL; ovRootIndex = NULL; ovChildrenStartIndex = NULL; ovChildrenCount = NULL; ovChildrenCountTop = NULL; ovChildrenCountBottom = NULL; ovProcessedFlag = NULL; ovOKtoProcessFlag = NULL; ovChildrenReported = NULL; ovAtomBuffer = NULL; selfVolumeBuffer_long = NULL; selfVolumeBuffer = NULL; AccumulationBuffer1_long = NULL; AccumulationBuffer1_real = NULL; AccumulationBuffer2_long = NULL; AccumulationBuffer2_real = NULL; gradBuffers_long = NULL; temp_buffer_size = -1; gvol_buffer_temp = NULL; tree_pos_buffer_temp = NULL; i_buffer_temp = NULL; atomj_buffer_temp = NULL; has_saved_noverlaps = false; tree_size_boost = 2;//6;//debug 2 is default hasExceededTempBuffer = false; }; ~CudaOverlapTree(void) { delete ovAtomTreePointer; delete ovAtomTreeSize; delete ovTreePointer; delete ovNumAtomsInTree; delete ovFirstAtom; delete NIterations; delete ovAtomTreePaddedSize; delete ovAtomTreeLock; delete ovLevel; delete ovG; delete ovVolume; delete ovVsp; delete ovVSfp; delete ovSelfVolume; delete ovVolEnergy; delete ovGamma1i; delete ovDV1; delete ovDV2; delete ovPF; delete ovLastAtom; delete ovRootIndex; delete ovChildrenStartIndex; delete ovChildrenCount; delete ovChildrenCountTop; delete ovChildrenCountBottom; delete ovProcessedFlag; delete ovOKtoProcessFlag; delete ovChildrenReported; delete ovAtomBuffer; delete selfVolumeBuffer_long; delete selfVolumeBuffer; delete AccumulationBuffer1_long; delete AccumulationBuffer1_real; delete AccumulationBuffer2_long; delete AccumulationBuffer2_real; delete gradBuffers_long; delete gvol_buffer_temp; delete tree_pos_buffer_temp; delete i_buffer_temp; delete atomj_buffer_temp; }; //initializes tree sections and sizes with number of atoms and number of overlaps void init_tree_size(int num_atoms, int padded_num_atoms, int num_compute_units, int pad_modulo, vector<int> &noverlaps_current); //simpler version with precomputed tree sizes void init_tree_size(int padded_num_atoms, int tree_section_size, int num_compute_units, int pad_modulo); //resizes tree buffers void resize_tree_buffers(OpenMM::CudaContext &cu, int ov_work_group_size); //copies the tree framework to Cuda device memory int copy_tree_to_device(void); // host variables and buffers int num_atoms; int padded_num_atoms; int total_atoms_in_tree; int total_tree_size; int num_sections; vector<int> tree_size; vector<int> padded_tree_size; vector<int> atom_tree_pointer; //pointers to 1-body atom slots vector<int> tree_pointer; //pointers to tree sections vector<int> natoms_in_tree; //no. atoms in each tree section vector<int> first_atom; //the first atom in each tree section /* overlap tree buffers on Device */ OpenMM::CudaArray *ovAtomTreePointer; OpenMM::CudaArray *ovAtomTreeSize; OpenMM::CudaArray *ovTreePointer; OpenMM::CudaArray *ovNumAtomsInTree; OpenMM::CudaArray *ovFirstAtom; OpenMM::CudaArray *NIterations; OpenMM::CudaArray *ovAtomTreePaddedSize; OpenMM::CudaArray *ovAtomTreeLock; OpenMM::CudaArray *ovLevel; OpenMM::CudaArray *ovG; // real4: Gaussian position + exponent OpenMM::CudaArray *ovVolume; OpenMM::CudaArray *ovVsp; OpenMM::CudaArray *ovVSfp; OpenMM::CudaArray *ovSelfVolume; OpenMM::CudaArray *ovVolEnergy; OpenMM::CudaArray *ovGamma1i; /* volume derivatives */ OpenMM::CudaArray *ovDV1; // real4: dV12/dr1 + dV12/dV1 for each overlap OpenMM::CudaArray *ovDV2; // volume gradient accumulator OpenMM::CudaArray *ovPF; //(P) and (F) aux variables OpenMM::CudaArray *ovLastAtom; OpenMM::CudaArray *ovRootIndex; OpenMM::CudaArray *ovChildrenStartIndex; OpenMM::CudaArray *ovChildrenCount; OpenMM::CudaArray *ovChildrenCountTop; OpenMM::CudaArray *ovChildrenCountBottom; OpenMM::CudaArray *ovProcessedFlag; OpenMM::CudaArray *ovOKtoProcessFlag; OpenMM::CudaArray *ovChildrenReported; OpenMM::CudaArray *ovAtomBuffer; OpenMM::CudaArray *selfVolumeBuffer_long; OpenMM::CudaArray *selfVolumeBuffer; OpenMM::CudaArray *AccumulationBuffer1_long; OpenMM::CudaArray *AccumulationBuffer1_real; OpenMM::CudaArray *AccumulationBuffer2_long; OpenMM::CudaArray *AccumulationBuffer2_real; OpenMM::CudaArray *gradBuffers_long; int temp_buffer_size; OpenMM::CudaArray *gvol_buffer_temp; OpenMM::CudaArray *tree_pos_buffer_temp; OpenMM::CudaArray *i_buffer_temp; OpenMM::CudaArray *atomj_buffer_temp; double tree_size_boost; int has_saved_noverlaps; vector<int> saved_noverlaps; bool hasExceededTempBuffer; };//class CudaOverlapTree private: const GKNPForce *gvol_force; int numParticles; unsigned int version; bool useCutoff; bool usePeriodic; bool useExclusions; double cutoffDistance; double roffset; float common_gamma; int maxTiles; bool hasInitializedKernels; bool hasCreatedKernels; OpenMM::CudaContext &cu; const OpenMM::System &system; int ov_work_group_size; //thread group size int num_compute_units; CudaOverlapTree *gtree; //tree of atomic overlaps double solvent_radius; //solvent probe radius for GKNP2 OpenMM::CudaArray *radiusParam1; OpenMM::CudaArray *radiusParam2; OpenMM::CudaArray *gammaParam1; OpenMM::CudaArray *gammaParam2; OpenMM::CudaArray *ishydrogenParam; OpenMM::CudaArray *chargeParam; OpenMM::CudaArray *alphaParam; //C++ vectors corresponding to parameter buffers above vector<float> radiusVector1; //enlarged radii vector<float> radiusVector2; //vdw radii vector<float> gammaVector1; //gamma/radius_offset vector<float> gammaVector2; //-gamma/radius_offset vector<float> chargeVector; //charge vector<float> alphaVector; //alpha vdw parameter vector<int> ishydrogenVector; OpenMM::CudaArray *testBuffer; OpenMM::CudaArray *radtypeScreened; OpenMM::CudaArray *radtypeScreener; OpenMM::CudaArray *selfVolume; //vdw radii OpenMM::CudaArray *selfVolumeLargeR; //large radii OpenMM::CudaArray *Semaphor; OpenMM::CudaArray *volScalingFactor; OpenMM::CudaArray *BornRadius; OpenMM::CudaArray *invBornRadius; OpenMM::CudaArray *invBornRadius_fp; OpenMM::CudaArray *GBDerY; OpenMM::CudaArray *GBDerBrU; OpenMM::CudaArray *GBDerU; OpenMM::CudaArray *VdWDerBrW; OpenMM::CudaArray *VdWDerW; OpenMM::CudaArray *grad; CUfunction resetBufferKernel; CUfunction resetOvCountKernel; CUfunction resetTree; CUfunction resetSelfVolumesKernel; CUfunction InitOverlapTreeKernel_1body_1; CUfunction InitOverlapTreeKernel_1body_2; CUfunction InitOverlapTreeCountKernel; CUfunction reduceovCountBufferKernel; CUfunction InitOverlapTreeKernel; int InitOverlapTreeKernel_first_nbarg; CUfunction ComputeOverlapTreeKernel; CUfunction ComputeOverlapTree_1passKernel; CUfunction computeSelfVolumesKernel; CUfunction reduceSelfVolumesKernel_tree; CUfunction reduceSelfVolumesKernel_buffer; CUfunction updateSelfVolumesForcesKernel; CUfunction resetTreeKernel; CUfunction SortOverlapTree2bodyKernel; CUfunction resetComputeOverlapTreeKernel; CUfunction ResetRescanOverlapTreeKernel; CUfunction InitRescanOverlapTreeKernel; CUfunction RescanOverlapTreeKernel; CUfunction RescanOverlapTreeGammasKernel_W; CUfunction InitOverlapTreeGammasKernel_1body_W; //CUfunction computeVolumeEnergyKernel; /* Gaussian atomic parameters */ vector<float> gaussian_exponent; vector<float> gaussian_volume; OpenMM::CudaArray *GaussianExponent; OpenMM::CudaArray *GaussianVolume; OpenMM::CudaArray *GaussianExponentLargeR; OpenMM::CudaArray *GaussianVolumeLargeR; /* gamma parameters */ vector<float> atomic_gamma; OpenMM::CudaArray *AtomicGamma; vector<int> atom_ishydrogen; int niterations; int verbose_level; void executeInitKernels(OpenMM::ContextImpl &context, bool includeForces, bool includeEnergy); double executeGVolSA(OpenMM::ContextImpl &context, bool includeForces, bool includeEnergy); //TODO: Panic Button? //flag to give up OpenMM::CudaArray *PanicButton; vector<int> panic_button; int *pinnedPanicButtonBuffer; CUevent downloadPanicButtonEvent; }; } // namespace GKNPPlugin #endif /*CUDA_GKNP_KERNELS_H_*/
#pragma once #include <iberbar/RHI/D3D9/Headers.h> #include <iberbar/RHI/RenderState.h> namespace iberbar { namespace RHI { namespace D3D9 { class CBlendState : public IBlendState { public: CBlendState( const UBlendDesc& Desc ) : IBlendState( Desc ) { } }; class CDepthStencilState : public IDepthStencilState { public: CDepthStencilState( const UDepthStencilDesc& Desc ) : IDepthStencilState( Desc ) { } }; class CSamplerState : public ISamplerState { public: CSamplerState( const UTextureSamplerState& SamplerDesc ) : ISamplerState( SamplerDesc ) { } }; } } }
/******************************************************************************** ** Form generated from reading UI file 'menuprincipale.ui' ** ** Created: Wed 18. Dec 01:59:44 2013 ** by: Qt User Interface Compiler version 4.8.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MENUPRINCIPALE_H #define UI_MENUPRINCIPALE_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QHeaderView> #include <QtGui/QPushButton> QT_BEGIN_NAMESPACE class Ui_menuprincipale { public: QPushButton *quitterPB; QPushButton *precedentPB; QPushButton *stockPB; QPushButton *clientPB; QPushButton *financePB; QPushButton *afficherstockPB; QPushButton *ajouterstockPB; QPushButton *rechercherstockPB; QPushButton *supprimerstockPB; QPushButton *modifierstockPB; QPushButton *afficherclientPB; QPushButton *ajouterclientPB; QPushButton *rechercherclientPB; QPushButton *supprimerclientPB; QPushButton *modifierclientPB; QPushButton *afficherfinancePB; QPushButton *ajouterfinancePB; QPushButton *rechercherfinancePB; QPushButton *supprimerfinancePB; QPushButton *modifierfinancePB; void setupUi(QDialog *menuprincipale) { if (menuprincipale->objectName().isEmpty()) menuprincipale->setObjectName(QString::fromUtf8("menuprincipale")); menuprincipale->resize(640, 480); quitterPB = new QPushButton(menuprincipale); quitterPB->setObjectName(QString::fromUtf8("quitterPB")); quitterPB->setGeometry(QRect(524, 380, 91, 31)); precedentPB = new QPushButton(menuprincipale); precedentPB->setObjectName(QString::fromUtf8("precedentPB")); precedentPB->setGeometry(QRect(420, 380, 91, 31)); stockPB = new QPushButton(menuprincipale); stockPB->setObjectName(QString::fromUtf8("stockPB")); stockPB->setGeometry(QRect(40, 30, 75, 23)); clientPB = new QPushButton(menuprincipale); clientPB->setObjectName(QString::fromUtf8("clientPB")); clientPB->setGeometry(QRect(150, 30, 75, 23)); financePB = new QPushButton(menuprincipale); financePB->setObjectName(QString::fromUtf8("financePB")); financePB->setGeometry(QRect(250, 30, 75, 23)); afficherstockPB = new QPushButton(menuprincipale); afficherstockPB->setObjectName(QString::fromUtf8("afficherstockPB")); afficherstockPB->setGeometry(QRect(40, 70, 75, 31)); ajouterstockPB = new QPushButton(menuprincipale); ajouterstockPB->setObjectName(QString::fromUtf8("ajouterstockPB")); ajouterstockPB->setGeometry(QRect(40, 110, 75, 31)); rechercherstockPB = new QPushButton(menuprincipale); rechercherstockPB->setObjectName(QString::fromUtf8("rechercherstockPB")); rechercherstockPB->setGeometry(QRect(40, 150, 75, 31)); supprimerstockPB = new QPushButton(menuprincipale); supprimerstockPB->setObjectName(QString::fromUtf8("supprimerstockPB")); supprimerstockPB->setGeometry(QRect(40, 190, 75, 31)); modifierstockPB = new QPushButton(menuprincipale); modifierstockPB->setObjectName(QString::fromUtf8("modifierstockPB")); modifierstockPB->setGeometry(QRect(40, 230, 75, 31)); afficherclientPB = new QPushButton(menuprincipale); afficherclientPB->setObjectName(QString::fromUtf8("afficherclientPB")); afficherclientPB->setGeometry(QRect(150, 70, 75, 31)); ajouterclientPB = new QPushButton(menuprincipale); ajouterclientPB->setObjectName(QString::fromUtf8("ajouterclientPB")); ajouterclientPB->setGeometry(QRect(150, 110, 75, 31)); rechercherclientPB = new QPushButton(menuprincipale); rechercherclientPB->setObjectName(QString::fromUtf8("rechercherclientPB")); rechercherclientPB->setGeometry(QRect(150, 150, 75, 31)); supprimerclientPB = new QPushButton(menuprincipale); supprimerclientPB->setObjectName(QString::fromUtf8("supprimerclientPB")); supprimerclientPB->setGeometry(QRect(150, 190, 75, 31)); modifierclientPB = new QPushButton(menuprincipale); modifierclientPB->setObjectName(QString::fromUtf8("modifierclientPB")); modifierclientPB->setGeometry(QRect(150, 230, 75, 31)); afficherfinancePB = new QPushButton(menuprincipale); afficherfinancePB->setObjectName(QString::fromUtf8("afficherfinancePB")); afficherfinancePB->setGeometry(QRect(250, 70, 75, 31)); ajouterfinancePB = new QPushButton(menuprincipale); ajouterfinancePB->setObjectName(QString::fromUtf8("ajouterfinancePB")); ajouterfinancePB->setGeometry(QRect(250, 110, 75, 31)); rechercherfinancePB = new QPushButton(menuprincipale); rechercherfinancePB->setObjectName(QString::fromUtf8("rechercherfinancePB")); rechercherfinancePB->setGeometry(QRect(250, 150, 75, 31)); supprimerfinancePB = new QPushButton(menuprincipale); supprimerfinancePB->setObjectName(QString::fromUtf8("supprimerfinancePB")); supprimerfinancePB->setGeometry(QRect(250, 190, 75, 31)); modifierfinancePB = new QPushButton(menuprincipale); modifierfinancePB->setObjectName(QString::fromUtf8("modifierfinancePB")); modifierfinancePB->setGeometry(QRect(250, 230, 75, 31)); retranslateUi(menuprincipale); QMetaObject::connectSlotsByName(menuprincipale); } // setupUi void retranslateUi(QDialog *menuprincipale) { menuprincipale->setWindowTitle(QApplication::translate("menuprincipale", "Dialog", 0, QApplication::UnicodeUTF8)); quitterPB->setText(QApplication::translate("menuprincipale", "quitter", 0, QApplication::UnicodeUTF8)); precedentPB->setText(QApplication::translate("menuprincipale", "precedent", 0, QApplication::UnicodeUTF8)); stockPB->setText(QApplication::translate("menuprincipale", "stock", 0, QApplication::UnicodeUTF8)); clientPB->setText(QApplication::translate("menuprincipale", "client", 0, QApplication::UnicodeUTF8)); financePB->setText(QApplication::translate("menuprincipale", "finance", 0, QApplication::UnicodeUTF8)); afficherstockPB->setText(QApplication::translate("menuprincipale", "AfficherS", 0, QApplication::UnicodeUTF8)); ajouterstockPB->setText(QApplication::translate("menuprincipale", "AjouterS", 0, QApplication::UnicodeUTF8)); rechercherstockPB->setText(QApplication::translate("menuprincipale", "RechercherS", 0, QApplication::UnicodeUTF8)); supprimerstockPB->setText(QApplication::translate("menuprincipale", "SupprimerS", 0, QApplication::UnicodeUTF8)); modifierstockPB->setText(QApplication::translate("menuprincipale", "ModifierS", 0, QApplication::UnicodeUTF8)); afficherclientPB->setText(QApplication::translate("menuprincipale", "AfficherC", 0, QApplication::UnicodeUTF8)); ajouterclientPB->setText(QApplication::translate("menuprincipale", "AjouterC", 0, QApplication::UnicodeUTF8)); rechercherclientPB->setText(QApplication::translate("menuprincipale", "RechercherC", 0, QApplication::UnicodeUTF8)); supprimerclientPB->setText(QApplication::translate("menuprincipale", "SupprimerC", 0, QApplication::UnicodeUTF8)); modifierclientPB->setText(QApplication::translate("menuprincipale", "ModifierC", 0, QApplication::UnicodeUTF8)); afficherfinancePB->setText(QApplication::translate("menuprincipale", "AfficherF", 0, QApplication::UnicodeUTF8)); ajouterfinancePB->setText(QApplication::translate("menuprincipale", "AjouterF", 0, QApplication::UnicodeUTF8)); rechercherfinancePB->setText(QApplication::translate("menuprincipale", "RechercherF", 0, QApplication::UnicodeUTF8)); supprimerfinancePB->setText(QApplication::translate("menuprincipale", "SupprimerF", 0, QApplication::UnicodeUTF8)); modifierfinancePB->setText(QApplication::translate("menuprincipale", "ModifierF", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class menuprincipale: public Ui_menuprincipale {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MENUPRINCIPALE_H
#ifndef GNTEGIDKEY_H #define GNTEGIDKEY_H #include "GnAnimationKey.h" class GnTegIDKey : public GnAnimationKey { GnDeclareAnimationStream; protected: guint32 mTegID; public: GnTegIDKey(){}; virtual ~GnTegIDKey(){}; inline guint32 GetTegID() { return mTegID; } inline void SetTegID(guint32 val) { mTegID = val; } private: }; GnRegsterAnimationKeyStream(GnTegIDKey); #endif // GNTEGIDKEY_H
#include <stdio.h> #include <iostream> #include <sstream> #include <vector> #include <fstream> using namespace std; fstream fin; ofstream fout; const int MAX = 1000; const int INF = 0x3F3F3F3F; int g[MAX][MAX]; int n; void input(void) { vector<int> digits(3, 0); int i1; int digit; fin.open("input.txt"); string str; getline(fin, str); stringstream ss; ss << str; while (ss >> digit) { n = digit; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { g[i][j] = 0; /* заполняем главную диагональ нулями и все остальное бесконечностью*/ } else { g[i][j] = INF; } } } while (!fin.eof()) { /*заполняем матрицу смеежности*/ i1 = 0; getline(fin, str); stringstream ss; ss << str; while (ss >> digit) { digits[i1] = digit; i1++; } g[digits[0] - 1][digits[1] - 1] = digits[2]; g[digits[1] - 1][digits[0] - 1] = digits[2]; } fin.close(); } void floyd(void) { int i, j, k; for (k = 0; k < n; k++) for (i = 0; i < n; i++) for (j = 0; j < n; j++) // заполняем МС по алгоритму Флойда if (g[i][k] + g[k][j] < g[i][j]) { g[i][j] = g[i][k] + g[k][j]; //cout << g[i][j] << endl; } } int main() { int diam = 0, max; // диаметр графа input(); floyd(); for (int i = 0; i < n; i++) { // ищем максимальное расстояние в новой МС max = 0; for (int j = 0; j < n; j++) if (g[i][j] > max) max = g[i][j]; if (max > diam) diam = max; } fout.open("output.txt"); fout << diam; fout.close(); return 0; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef INTERNAL_SPELLCHECK_SUPPORT #ifndef SPC_USE_HUNSPELL_ENGINE #include "modules/spellchecker/src/opspellchecker.h" /* ===============================CompoundRule=============================== */ OP_STATUS CompoundRule::Initialize(int cond_count, int total_cond_flags, OpSpellCheckerAllocator *allocator) { m_added_conditions = 0; m_total_cond_flags = total_cond_flags; m_last_single_pos = -1; m_cond_count = cond_count; if (!cond_count) { m_jump_table = NULL; m_retry_table = NULL; m_multiple = NULL; return OpStatus::OK; } m_jump_table = (UINT8*)allocator->Allocate8(total_cond_flags*(cond_count+1)); m_retry_table = (UINT8*)allocator->Allocate8(total_cond_flags*cond_count); m_multiple = OP_NEWA(BOOL, cond_count); if (!m_jump_table || !m_retry_table || !m_multiple) { OP_DELETEA(m_multiple); m_multiple = NULL; return SPC_ERROR(OpStatus::ERR); } return OpStatus::OK; } #define SPC_JUMP_TABLE(x) (m_jump_table + (x)*m_total_cond_flags) #define SPC_RETRY_TABLE(x) (m_retry_table + (x)*m_total_cond_flags) #define SPC_NO_JUMP 255 #define SPC_EXISTS 254 void CompoundRule::AddCondition(UINT16 *cond_ids, int cond_ids_count, BOOL is_negative, BOOL multiple) { int i,j,k; OP_ASSERT(m_added_conditions < m_cond_count); UINT8 *jump = SPC_JUMP_TABLE(m_added_conditions), *retry; op_memset(jump, is_negative ? SPC_EXISTS : SPC_NO_JUMP, m_total_cond_flags); for (i=0;i<cond_ids_count;i++) jump[cond_ids[i]] = is_negative ? SPC_NO_JUMP : SPC_EXISTS; m_multiple[m_added_conditions++] = multiple; if (m_added_conditions != m_cond_count) return; op_memset(m_jump_table+m_total_cond_flags*m_cond_count,0xFF,m_total_cond_flags); // set the "after last" condition to match nothing for (i=m_cond_count-1;i>=0;i--) { multiple = m_multiple[i]; if (!multiple && m_last_single_pos < 0) m_last_single_pos = i; for (j=0;j<m_total_cond_flags;j++) { jump = SPC_JUMP_TABLE(i); if (jump[j] != SPC_EXISTS) continue; jump[j] = multiple ? 0 : 1; BOOL other_accept_passed = FALSE; for (k=i-1;k>=0 && m_multiple[k];k--) { jump = SPC_JUMP_TABLE(k); retry = SPC_RETRY_TABLE(k); if (jump[j] == SPC_NO_JUMP) { if (!other_accept_passed) jump[j] = (UINT8)(i-k + (multiple ? 0 : 1)); else // jump[j] will be set later to previous accept retry[j] = (UINT8)i; } else // SPC_EXISTS { OP_ASSERT(jump[j] == SPC_EXISTS); if (other_accept_passed) break; other_accept_passed = TRUE; retry[j] = (UINT8)i; } } } } OP_DELETEA(m_multiple); m_multiple = NULL; } BOOL CompoundRule::Matches(UINT16 *indexes, int count) { UINT8 *jumps = m_jump_table; UINT8 *retry = m_retry_table; int cond_pos = 0, index_pos = 0, retry_cond = 0, retry_index = 0; int idx,jump; for (;;) { idx = indexes[index_pos]; jump = jumps[idx]; cond_pos += jump; if (jump==SPC_NO_JUMP) // doesn't match condition! { do_retry: if (!retry_cond) // There is no previous point to retry from return FALSE; cond_pos = retry_cond; index_pos = retry_index; retry_cond = 0; retry = SPC_RETRY_TABLE(cond_pos); jumps = SPC_JUMP_TABLE(cond_pos); continue; } if (!retry_cond && retry[idx]) { retry_cond = retry[idx]; retry_index = index_pos; } if (++index_pos == count) { if (cond_pos > m_last_single_pos) return TRUE; goto do_retry; } if (jump) { if (jump == 1) { retry += m_total_cond_flags; jumps += m_total_cond_flags; } else { retry = SPC_RETRY_TABLE(cond_pos); jumps = SPC_JUMP_TABLE(cond_pos); } } } // unreachable... } #endif //!USE_HUNSPELL_ENGINE #endif // INTERNAL_SPELLCHECK_SUPPORT
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** psmaas - Patricia Aas */ #include "core/pch.h" #ifdef HISTORY_SUPPORT #include "modules/history/src/HistoryModel.h" #include "modules/history/history_structs.h" //___________________________________________________________________________ // Supported prefixes in history : // // Make sure that the toplevel prefix (eg http://) is listed before a contained // prefix (eg http://www.). //___________________________________________________________________________ OP_STATUS HistoryModel::MakeHistoryPrefixes(HistoryPrefix *& history_prefixes, int & size) { // -------------------- // Calculate the arrays size // -------------------- UINT array_size = 14; #ifndef NO_FTP_SUPPORT array_size += 4; #endif //NO_FTP_SUPPORT #if defined(_LOCALHOST_SUPPORT_) && defined(HISTORY_FILE_SUPPORT) array_size += 3; #endif // _LOCALHOST_SUPPORT_ && HISTORY_FILE_SUPPORT // -------------------- // Allocate the array // -------------------- history_prefixes = OP_NEWA(HistoryPrefix, array_size); if(!history_prefixes) return OpStatus::ERR_NO_MEMORY; // -------------------- // Fill in the array // -------------------- UINT i = 0; // Prefix Suffix Prefix/ Protocol Show_all // Suffix // Lengths history_prefixes[i++] = HistoryPrefix(UNI_L(""), UNI_L(""), 0, 0, NONE_PROTOCOL, FALSE); history_prefixes[i++] = HistoryPrefix(UNI_L("opera:"), UNI_L(""), 6, 0, OPERA_PROTOCOL, TRUE); #if defined(_LOCALHOST_SUPPORT_) && defined(HISTORY_FILE_SUPPORT) history_prefixes[i++] = HistoryPrefix(UNI_L("file:/"), UNI_L(""), 6, 0, FILE_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("file://"), UNI_L(""), 7, 0, FILE_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("file://localhost"), UNI_L("localhost"), 16, 9, FILE_PROTOCOL, TRUE); #endif // _LOCALHOST_SUPPORT_ && HISTORY_FILE_SUPPORT #ifndef NO_FTP_SUPPORT history_prefixes[i++] = HistoryPrefix(UNI_L("ftp://"), UNI_L(""), 6, 0, FTP_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("ftp://ftp."), UNI_L("ftp."), 10, 4, FTP_PROTOCOL, TRUE); #endif //NO_FTP_SUPPORT history_prefixes[i++] = HistoryPrefix(UNI_L("http://"), UNI_L(""), 7, 0, HTTP_PROTOCOL, FALSE); #ifndef NO_FTP_SUPPORT history_prefixes[i++] = HistoryPrefix(UNI_L("http://ftp."), UNI_L("ftp."), 11, 4, HTTP_PROTOCOL, TRUE); #endif //NO_FTP_SUPPORT history_prefixes[i++] = HistoryPrefix(UNI_L("http://home."), UNI_L("home."), 12, 5, HTTP_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("http://wap."), UNI_L("wap."), 11, 4, HTTP_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("http://web."), UNI_L("web."), 11, 4, HTTP_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("http://www."), UNI_L("www."), 11, 4, HTTP_PROTOCOL, FALSE); history_prefixes[i++] = HistoryPrefix(UNI_L("http://www2."), UNI_L("www2."), 12, 5, HTTP_PROTOCOL, FALSE); history_prefixes[i++] = HistoryPrefix(UNI_L("https://"), UNI_L(""), 8, 0, HTTPS_PROTOCOL, FALSE); #ifndef NO_FTP_SUPPORT history_prefixes[i++] = HistoryPrefix(UNI_L("https://ftp."), UNI_L("ftp."), 12, 4, HTTPS_PROTOCOL, TRUE); #endif //NO_FTP_SUPPORT history_prefixes[i++] = HistoryPrefix(UNI_L("https://home."), UNI_L("home."), 13, 5, HTTPS_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("https://wap."), UNI_L("wap."), 12, 4, HTTPS_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("https://web."), UNI_L("web."), 12, 4, HTTPS_PROTOCOL, TRUE); history_prefixes[i++] = HistoryPrefix(UNI_L("https://www."), UNI_L("www."), 12, 4, HTTPS_PROTOCOL, FALSE); history_prefixes[i++] = HistoryPrefix(UNI_L("https://www2."), UNI_L("www2."), 13, 5, HTTPS_PROTOCOL, FALSE); // -------------------- // Do some sanity checking // -------------------- OP_ASSERT(i == array_size); // -------------------- // Set the size parameter // -------------------- size = array_size; return OpStatus::OK; } #endif // HISTORY_SUPPORT
/** * Peripheral Definition File * * I2C - Inter-integrated circuit interface * * MCUs containing this peripheral: * - STM32F0xx * - STM32F3xx * - STM32F7xx * - STM32H7xx * - STM32L0xx * - STM32L4xx */ #pragma once #include <cstdint> #include <cstddef> namespace io { struct I2c { /** Control register 1 */ struct Cr1 { Cr1(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t PE : 1; // Peripheral enable uint32_t TXIE : 1; // TX Interrupt enable uint32_t RXIE : 1; // RX Interrupt enable uint32_t ADDRIE : 1; // Address match Interrupt enable (slave only) uint32_t NACKIE : 1; // Not acknowledge received Interrupt enable uint32_t STOPIE : 1; // STOP detection Interrupt enable uint32_t TCIE : 1; // Transfer Complete interrupt enable uint32_t ERRIE : 1; // Error interrupts enable uint32_t DNF : 4; // Digital noise filter uint32_t ANF : 1; // Analog noise filter OFF uint32_t : 1; uint32_t TXDMAEN : 1; // DMA transmission requests enable uint32_t RXDMAEN : 1; // DMA reception requests enable uint32_t SBC : 1; // Slave byte control uint32_t NOSTRETCH : 1; // Clock stretching disable uint32_t WUPEN : 1; // Wakeup from Stop mode enable // F0, F3, H7, L0, L4 uint32_t GCEN : 1; // General call enable uint32_t SMBHEN : 1; // SMBus Host address enable uint32_t SMBDEN : 1; // SMBus Device Default address enable uint32_t ALERTEN : 1; // SMBus alert enable uint32_t PECEN : 1; // PEC enable uint32_t : 8; }; union { uint32_t r; Bits b; }; }; /** Control register 2 */ struct Cr2 { Cr2(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t SADD : 10; // Slave address uint32_t RD_WRN : 1; // Transfer direction (master mode) uint32_t ADD10 : 1; // 10-bit addressing mode (master mode) uint32_t HEAD10R : 1; // 10-bit address header only read direction (master receiver mode) uint32_t START : 1; // Start generation uint32_t STOP : 1; // Stop generation (master mode) uint32_t NACK : 1; // NACK generation (slave mode) uint32_t NBYTES : 8; // Number of bytes uint32_t RELOAD : 1; // NBYTES reload mode uint32_t AUTOEND : 1; // Automatic end mode (master mode) uint32_t PECBYTE : 1; // Packet error checking byte uint32_t : 5; }; union { uint32_t r; Bits b; }; }; /** Own address 1 register */ struct Oar1 { Oar1(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t OA1 : 10; // Interface address uint32_t OA1MODE : 1; // Own Address 1 10-bit mode uint32_t : 4; uint32_t OA1EN : 1; // Own Address 1 enable uint32_t : 16; }; union { uint32_t r; Bits b; }; }; /** Own address 2 register */ struct Oar2 { Oar2(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t : 1; uint32_t OA2 : 7; // Interface address uint32_t OA2MASK : 3; // Own Address 2 masks uint32_t : 4; uint32_t OA2EN : 1; // Own Address 2 enable uint32_t : 16; }; union { uint32_t r; Bits b; }; }; /** Timing register */ struct Timingr { Timingr(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t SCLL : 8; // SCL low period (master mode) uint32_t SCLH : 8; // SCL high period (master mode) uint32_t SDADEL : 4; // Data hold time uint32_t SCLDEL : 4; // Data setup time uint32_t : 4; uint32_t PRESC : 4; // Timing prescaler }; union { uint32_t r; Bits b; }; }; /** Timeout register */ struct Timeoutr { Timeoutr(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t TIMEOUTA : 12; // Bus Timeout A uint32_t TIDLE : 1; // Idle clock timeout detection uint32_t : 2; uint32_t TIMEOUTEN : 1; // Clock timeout enable uint32_t TIMEOUTB : 12; // Bus timeout B uint32_t : 3; uint32_t TEXTEN : 1; // Extended clock timeout enable }; union { uint32_t r; Bits b; }; }; /** Interrupt and status register */ struct Isr { Isr(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t TXE : 1; // Transmit data register empty (transmitters) uint32_t TXIS : 1; // Transmit interrupt status (transmitters) const uint32_t RXNE : 1; // Receive data register not empty (receivers) const uint32_t ADDR : 1; // Address matched (slave mode) const uint32_t NACKF : 1; // Not Acknowledge received flag const uint32_t STOPF : 1; // Stop detection flag const uint32_t TC : 1; // Transfer Complete (master mode) const uint32_t TCR : 1; // Transfer Complete Reload const uint32_t BERR : 1; // Bus error const uint32_t ARLO : 1; // Arbitration lost const uint32_t OVR : 1; // Overrun/Underrun (slave mode) const uint32_t PECERR : 1; // PEC Error in reception const uint32_t TIMEOUT : 1; // Timeout or tLOW detection flag const uint32_t ALERT : 1; // SMBus alert const uint32_t : 1; const uint32_t BUSY : 1; // Bus busy const uint32_t DIR : 1; // Transfer direction (Slave mode) const uint32_t ADDCODE : 7; // Address match code (Slave mode) uint32_t : 8; }; union { uint32_t r; Bits b; }; }; /** Interrupt clear register */ struct Icr { Icr(const uint32_t raw=0) { r = raw; } struct Bits { uint32_t : 3; uint32_t ADDRCF : 1; // Address Matched flag clear uint32_t NACKCF : 1; // Not Acknowledge flag clear uint32_t STOPCF : 1; // Stop detection flag clear uint32_t : 2; uint32_t BERRCF : 1; // Bus error flag clear uint32_t ARLOCF : 1; // Arbitration Lost flag clea uint32_t OVRCF : 1; // Overrun/Underrun flag clear uint32_t PECCF : 1; // PEC Error flag clear uint32_t TIMOUTCF : 1; // Timeout detection flag clear uint32_t ALERTCF : 1; // Alert flag clear uint32_t : 18; }; union { uint32_t r; Bits b; }; }; /** Packet error checking register */ struct Pecr { union { uint32_t r; uint32_t PEC; // Packet error checking register (8-bit used) }; }; /** Receive data register */ struct Rxdr { union { uint32_t r; uint32_t RXDATA; // 8-bit receive data }; }; /** Transmit data register */ struct Txdr { union { uint32_t r; uint32_t TXDATA; // 8-bit transmit data }; }; volatile Cr1 CR1; // Control register 1 volatile Cr2 CR2; // Control register 2 volatile Oar1 OAR1; // Own address 1 register volatile Oar2 OAR2; // Own address 2 register volatile Timingr TIMINGR; // Timing register volatile Timeoutr TIMEOUTR; // Timeout register volatile Isr ISR; // Interrupt and status register volatile Icr ICR; // Interrupt clear register volatile Pecr PECR; // Packet error checking register volatile Rxdr RXDR; // Receive data register volatile Txdr TXDR; // Transmit data register }; static inline constexpr I2c &I2C(const size_t base) { return *reinterpret_cast<I2c *>(base); } }
#include "DynamicArray.h" // 先序遍历 void preOrderRecursion(cNode* root){ if (root == nullptr) return; printf("%c", root->name); preOrderRecursion(root->lChild); preOrderRecursion(root->rChild); } // 中序遍历 void midOrderRecursion(cNode* root){ if(root == nullptr) return; midOrderRecursion(root->lChild); printf("%c", root->name); midOrderRecursion(root->rChild); } // 后序遍历 void postOrderRecursion(cNode* root){ if(root == nullptr) return; postOrderRecursion(root->lChild); postOrderRecursion(root->rChild); printf("%c", root->name); } // 计算叶子节点 void calculateLeafNum(cNode* root, int& numLeaf){ if(root == NULL) return; if(root->lChild == NULL && root->rChild == NULL) numLeaf += 1; calculateLeafNum(root->lChild, numLeaf); calculateLeafNum(root->rChild, numLeaf); } // 计算树的高度(或深度) int calculateTreeHeight(cNode* root){ if(root == NULL) return 0; int left = calculateTreeHeight(root->lChild); int right = calculateTreeHeight(root->rChild); return left > right? left + 1: right + 1; } // 拷贝二叉树 cNode* copyBinaryTree(cNode* root){ if(root == NULL) return NULL; // 后序遍历 cNode* lChild = copyBinaryTree(root->lChild); cNode* rChild = copyBinaryTree(root->rChild); cNode* newNode = (cNode*)malloc(sizeof(cNode)); newNode->name = root->name; newNode->lChild = lChild; newNode->rChild = rChild; return newNode; } void freeBinaryTree(cNode *root){ if(root == NULL) return; freeBinaryTree(root->lChild); freeBinaryTree(root->rChild); free(root); } void binaryTree(){ /** * A * / \ * B F * \ \ * C G * / \ / * D E H * * NLR: ABCDEFGH * LNR: BDCEAFHG * LRN: DECBHGFA */ // 创建二叉树 cNode nA = {'A', NULL, NULL}; cNode nB = {'B', NULL, NULL}; cNode nC = {'C', NULL, NULL}; cNode nD = {'D', NULL, NULL}; cNode nE = {'E', NULL, NULL}; cNode nF = {'F', NULL, NULL}; cNode nG = {'G', NULL, NULL}; cNode nH = {'H', NULL, NULL}; nA.lChild = &nB; nB.rChild = &nC; nC.lChild = &nD; nC.rChild = &nE; nA.rChild = &nF; nF.rChild = &nG; nG.lChild = &nH; printf("先序遍历:\n"); printf("ABCDEFGH\n"); preOrderRecursion(&nA); printf("\n\n"); printf("中序遍历:\n"); printf("BDCEAFHG\n"); midOrderRecursion(&nA); printf("\n\n"); printf("后序遍历:\n"); printf("DECBHGFA\n"); postOrderRecursion(&nA); printf("\n\n"); int leafNum = 0; calculateLeafNum(&nA, leafNum); printf("叶子节点数量:%d\n\n", leafNum); int treeHeight = calculateTreeHeight(&nA); printf("树的高度:%d\n\n", treeHeight); printf("先序遍历(拷贝树):\n"); printf("ABCDEFGH\n"); cNode* newTree = copyBinaryTree(&nA); preOrderRecursion(newTree); printf("\n\n"); printf("释放二叉树:\n"); freeBinaryTree(newTree); printf("已释放\n"); preOrderRecursion(newTree); printf("\n\n"); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef _PLUGIN_H_INC_ #define _PLUGIN_H_INC_ #ifdef _PLUGIN_SUPPORT_ #include "modules/logdoc/elementref.h" #include "modules/ns4plugins/src/pluginhandler.h" #include "modules/ns4plugins/src/plugincommon.h" #include "modules/ns4plugins/src/pluginscript.h" #include "modules/ns4plugins/opns4plugin.h" #include "modules/idle/idle_detector.h" #include "modules/inputmanager/inputcontext.h" #ifdef USE_PLUGIN_EVENT_API #include "modules/pi/OpNS4PluginAdapter.h" #include "modules/pi/OpKeys.h" #endif // USE_PLUGIN_EVENT_API #include "modules/pi/OpPluginWindow.h" #if NS4P_INVALIDATE_INTERVAL > 0 #include "modules/hardcore/timer/optimer.h" #endif // NS4P_INVALIDATE_INTERVAL > 0 #include "modules/util/simset.h" #include "modules/url/url2.h" #include "modules/url/url_docload.h" class FramesDocument; class EmbedBox; class PluginStream; class HTML_Element; class VisualDevice; typedef enum { NotAsked = 0, WantsAllNetworkStreams = 1, WantsOnlySucceededNetworkStreams = 2 } WantsAllNetworkStreamsType; typedef enum { /** The handle event lock could not be acquired and events may not be delivered to the plug-in. */ HandleEventNotAllowed, /** The handle event lock was acquired and a single event may be delivered to the plug-in. * ReleaseHandleEventLock() must be called immediately after the event has been delivered. * Before TryTakeHandleEventLock() nesting was allowed, ReleaseHandleEventLock() will restore * the nesting permission correspondingly. */ WindowProtectedNestingAllowed, /** The handle event lock was acquired and a single event may be delivered to the plug-in. * ReleaseHandleEventLock() must be called immediately after the event has been delivered. * Before TryTakeHandleEventLock() nesting was _NOT_ allowed, ReleaseHandleEventLock() will restore * the nesting permission correspondingly. */ WindowProtectedNestingBlocked, } HandleEventLock; /** * @brief An instance of a URLLink with an additional stream_count member variable * @author Hanne Elisabeth Larsen * * * Declaration : * Allocation : * Deletion : */ class StreamCount_URL_Link : public URLLink { public: int stream_count; /** * StreamCount_URL_Link : constructed when a PluginStream is created. * * @param u URL to be streamed to the plugin * * @return when an URLLink instance has been constructed with initialized stream_count */ StreamCount_URL_Link(const URL &u): URLLink(u), stream_count(1) {} }; /** * @brief An instance of a plugin * @author Hanne Elisabeth Larsen * * * Declaration : * Allocation : * Deletion : */ class Plugin : public Link , public OpNS4Plugin #ifndef USE_PLUGIN_EVENT_API , public OpInputContext #endif // !USE_PLUGIN_EVENT_API #if NS4P_INVALIDATE_INTERVAL > 0 , public OpTimerListener #endif // NS4P_INVALIDATE_INTERVAL > 0 , public URL_DocumentLoader , public ElementRef { public: /** * */ Plugin(); /** * */ virtual ~Plugin(); /** * * * @param plugin_dll * @param component_type Component type to use for this plugin * @param id * * @return */ OP_STATUS Create(const uni_char* plugin_dll, OpComponentType component_type, int id); /** * Windowless API : called when a ui event was detected in the * portion of the browserwindow that belongs to the plugin. The * event will have to be translated to a platform plugin event * and passed on to the plugin. * * @param event that occurred * @param point where it occurred * @param button_or_key_or_delta which button/key it concerns or scroll delta * @param modifiers any modifiers that were present at the time * * @return TRUE if the event was successfully passed to the plugin */ BOOL HandleEvent(DOM_EventType event, const OpPoint& point, int button_or_key_or_delta, ShiftKeyState modifiers); #ifdef USE_PLUGIN_EVENT_API virtual bool DeliverKeyEvent(OpKey::Code key, const uni_char *key_value, OpPlatformKeyEventData *key_event_data, const OpPluginKeyState key_state, OpKey::Location location, const ShiftKeyState modifiers); virtual bool DeliverFocusEvent(bool focus, FOCUS_REASON reason); /** * * * @param event * @param event_type * * @return */ BOOL SendEvent(OpPlatformEvent * event, OpPluginEventType event_type); #endif // USE_PLUGIN_EVENT_API /** * * * @param frames_doc * @param plugin_window * @param mimetype * @param mode * @param argc * @param argn * @param argv * @param url * @param embed_url_changed * * @return */ OP_STATUS New(FramesDocument* frames_doc, #ifndef USE_PLUGIN_EVENT_API void* plugin_window, #endif // !USE_PLUGIN_EVENT_API const uni_char *mimetype, uint16 mode, #ifndef USE_PLUGIN_EVENT_API int16 argc, const uni_char *argn[], const uni_char *argv[], #endif // !USE_PLUGIN_EVENT_API URL* url, BOOL embed_url_changed); #ifdef USE_PLUGIN_EVENT_API /** Display the plug-in. Tell it about changes in its window. * * Can be either called during painting, reflowing or at arbitrary time * in case plugin window has not been created yet. * * When called first time and NPP_New() has returned, this will create plugin * window. Otherwise plugin window will be created at soonest opportunity. * First call should be called with 'show' argument set to FALSE to ensure * that a plug-in that e.g. produces sound, but is not within the visible * view, will not start playing the sound even if it's not visible. * * During reflowing some arguments (namely show and is_fixed_positioned) * have hardcoded FALSE value which does not necessarily reflect reality * thus plugin window is not being updated during that phase as that * would cause flickering if visibility would change for example. * * Can also be called from HandleBusyState() in case plugin window has not * been created yet. That is similar to reflowing in a sense that both * show and is_fixed_positioned arguments are FALSE. * * For windowed plug-ins, this will update the position and dimension of * the plug-in window, and show it (unless 'show' is FALSE), and notify the * plug-in library about the new values. * * For windowless plug-ins, this will notify the plug-in library about the * position and dimension, and then paint it (unless 'show' is * FALSE). Whatever the plug-in wants to paint must be painted now, to get * layout box stacking order right. * * In some cases, when the plug-in is busy or not yet initialized, the * plug-in cannot be displayed immediately. If this is the case, Display() * will make sure that a paint request will be issued when the plug-in * becomes ready (which in turn will cause this method to be called again). * * @param plugin_rect Position and size of the plug-in. Coordinates are * relative to the viewport. All values are unscaled ("document" values). * @param paint_rect Area to paint. This is only used for windowless * plug-ins. Coordinates are relative to the viewport. All values are * unscaled ("document" values). This rectangle will always be fully * contained by 'plugin_rect', i.e. so that * paint_rect.IntersectWith(plugin_rect) has no effect. * @param show TRUE if the plug-in is to be shown / painted, FALSE if the * plug-in is only to be notified about its dimensions and whereabouts, * without being shown or painted. Some plug-ins are defined as hidden (in * the HTML markup), typically because the plug-in is only needed for its * ability to produce sound, or to perform other non-visual operations, in * which case this parameter will be FALSE. * @param fixed_position_subtree The first ancestor fixed positioned element * of the plug-in (including the element owning the plugin) * or NULL if no such exists. * * @return OK if successful (this also includes busy or not initialized * plug-ins, since this does not require the caller to take any actions), * ERR_NO_MEMORY if OOM, ERR for other errors. */ OP_STATUS Display(const OpRect& plugin_rect, const OpRect& paint_rect, BOOL show, HTML_Element* fixed_position_subtree); #else OP_STATUS SetWindow(int x, int y, unsigned int width, unsigned int height, BOOL show, const OpRect* rect = NULL); #endif // USE_PLUGIN_EVENT_API # ifdef _PRINT_SUPPORT_ /** * * * @param vd * @param x * @param y * @param width * @param height */ void Print(const VisualDevice* vd, const int x, const int y, const unsigned int width, const unsigned int height); # endif // _PRINT_SUPPORT_ /** * Schedule the destruction of a plugin. Its window will be detached * immediately (if it has one), and all resources will be released * on the next revolution of the message cycle. * * @return OpStatus::OK on success. */ OP_STATUS ScheduleDestruction(); /** * Destroy the plugin instance. Will call NPP_Destroy and release * all resources, including the plugin window. * * Calling this haphazardly may have terrible consequences, so * unless you know exactly what you're doing, please call * ScheduleDestruction() instead. * * @return OpStatus::ERR_NO_MEMORY on OOM, else OpStatus::OK. */ OP_STATUS Destroy(); #ifdef USE_PLUGIN_EVENT_API /** * Passes the platform plugin event on to the plugin, will inform * the platform with SaveState(event_type) and RestoreState(event_type) * before and after the call respectivly. * Will query the OpPluginWindow with IsAcceptingEvents(event_type) * and will only perform the call if this returns true. * * @param event to be passed to the plugin * @param event_type of the event * * @return the return value of the NPP_HandleEvent call to the plugin */ int16 HandleEvent(OpPlatformEvent* event, OpPluginEventType event_type, BOOL lock = TRUE); #else int16 HandleEvent(void *event, BOOL lock = TRUE); #endif // USE_PLUGIN_EVENT_API /** * Try to acquire the lock needed to be able to deliver an event to the plug-in. * * @param event_type the type of event that the caller plans to deliver to the plug-in * @param window_protection_needed true if the plug-in window needs to be protected during * event delivery (i.e. calls to NPP_SetWindow blocked). * @return if the return value is != HandleEventNotAllowed, then the locking was * successful and an event may be delivered to the plug-in via one of the event * handling functions in PluginFunctions:: (i.e. HandleFocusEvent, * HandleWindowlessKeyEvent, HandleWindowlessPaint or HandleWindowlessMouseEvent). * After the event has been delivered to the plug-in, the caller must pass * this return value into ReleaseHandleEventLock() which will unprotect the * window and restore the old nesting permission as returned by * g_pluginscriptdata->AllowNestedMessageLoop() before the lock was acquired. */ HandleEventLock TryTakeHandleEventLock(OpPluginEventType event_type, BOOL window_protection_needed); /** * Release lock needed to be able to deliver an event to the plug-in. * * This function must be called immediately after event delivery. * See docs for TryTakeHandleEventLock(). * * @param lock return value from a previous call to TryTakeHandleEventLock(), must be * either WindowProtectedNestingAllowed or WindowProtectedNestingBlocked * because if TryTakeHandleEventLock() returned HandleEventNotAllowed the * lock was not succesfully acquired and thus it's not necessary to release it. * @param event_type type of the single event that was delivered to the plug-in between * the calls to TryTakeHandleEventLock() and ReleaseHandleEventLock(). */ void ReleaseHandleEventLock(HandleEventLock lock, OpPluginEventType event_type); /** * Set that this plugin should be windowless, note that this * is only meaningful before the first SetWindow, since this * will define what should be in the NPWindow.type field. * * @param winless whether the plugin should be windowless */ void SetWindowless(BOOL winless); /** Return TRUE if the plug-in is windowless, FALSE otherwise. */ BOOL IsWindowless() const { return windowless; } Plugin* Suc() { return (Plugin*) Link::Suc(); } INT32 GetID() const { return ID; } /** Get plugin's clip rectangle. * Check that the plugin is visible on screen, compensate for scrolling * and find the intersect rectangle between the visual area and the plugin. * @param[in] x plugin's x position relative to parent OpView in scaled units * @param[in] y plugin's y position relative to parent OpView in scaled units * @param[in] width plugin's width, in scaled units * @param[in] height plugin's height, in scaled units * @returns clipped rectangle relative to the plugin rect, in scaled units */ OpRect GetClipRect(int x, int y, int width, int height); #ifdef USE_PLUGIN_EVENT_API /** Call NPP_SetWindow() and possibly window position changed event * unless the NPP_SetWindow() information is unchanged or * if plugin is already processing a NPP_ call. */ void CallSetWindow(); #else OP_STATUS SetWindow(); #endif // USE_PLUGIN_EVENT_API #ifdef _DEBUG int m_loading_streams; int m_loaded_streams; #endif // _DEBUG /** Adds a new stream to the plugin. * @param new_stream Will contain a pointer to the newly created stream if successful. * @param url The URL to stream data from. * @param notify If TRUE, a notification will be sent to the plugin. * @param notify_data Pointer to the plugin specific data to be sent along with the notification. * @param loadInTarget VERIFY: Set to TRUE if loaded in another window or something. * @returns Normal OOM values. */ OP_STATUS AddStream(PluginStream*& new_stream, URL& url, BOOL notify, void* notify_data, BOOL loadInTarget); /** Adds a new stream to the plugin. Implements OpNS4Plugin::AddPluginStream() * @param url The URL to stream data from. * @param mime_type The mime type specified for the plugin. Can be NULL. * @returns Normal OOM values. */ OP_STATUS AddPluginStream(URL& url, const uni_char* mime_type); /** Must be called when there is more data available for the stream of the plugin itself. * @return Normal OOM values */ OP_STATUS OnMoreDataAvailable(); /** Implements OpNS4Plugin::StopLoadingAllStreams() */ void StopLoadingAllStreams() { URL_DocumentLoader::StopLoadingAll(); } OP_STATUS InterruptStream(NPStream* pstream, NPReason reason); #ifdef _PRINT_SUPPORT_ BOOL HaveSameSourceURL(const uni_char* src_url); #endif // _PRINT_SUPPORT_ uni_char* GetName() const { return plugin_name; }; OP_STATUS GetScriptableObject(ES_Runtime* runtime, BOOL allow_suspend, ES_Value* value); OP_STATUS GetFormsValue(uni_char*& string_value); OP_STATUS GetPluginDescriptionStringValue(); /* Checks if the plugin is interested in receiving the http body of all http requests * including failed ones, http status != 200. * * @return the returned value from the plugin, where default value is OpBoolean::IS_FALSE. */ OP_BOOLEAN GetPluginWantsAllNetworkStreams(); #if defined(_PLUGIN_NAVIGATION_SUPPORT_) BOOL NavigateInsidePlugin(INT32 direction); #endif PluginStream* FindStream(int id); FramesDocument* GetDocument() const { return m_document; } NPPluginFuncs* GetPluginfuncs() const { return pluginfuncs; } NPP GetInstance() { return &instance_struct; } NPWindow* GetNPWindow() { return &npwin; } ServerName* GetHostName() { return m_document_url.GetServerName(); } void SetTransparent(BOOL transp) { transparent = transp; } BOOL IsTransparent() { return transparent; } void* GetWindow() const { return m_plugin_window ? m_plugin_window->GetHandle() : NULL; } #ifdef USE_PLUGIN_EVENT_API /** Returns plugin rect relative to parent OpView, in scaled units. */ int GetWindowX() const {return m_view_rect.x;} int GetWindowY() const {return m_view_rect.y;} #else int GetWindowX() const {return win_x;} int GetWindowY() const {return win_y;} #endif // USE_PLUGIN_EVENT_API // For the Plugin Event API the input context is in layout on ExternalContent #ifndef USE_PLUGIN_EVENT_API virtual const char * GetInputContextName() {return "Plugin Instance";} void OnFocus(BOOL focus, FOCUS_REASON reason); #endif // !USE_PLUGIN_EVENT_API #ifdef NS4P_CHECK_PLUGIN_NAME OP_BOOLEAN CheckPluginName(const uni_char* plugin_name); #endif // NS4P_CHECK_PLUGIN_NAME OP_STATUS DestroyAllStreams(); /** DestroyAllLoadingStreams() destroys all loading streams. */ void DestroyAllLoadingStreams(); void RemoveLinkedUrl(URL_ID url_id); NPMIMEType GetMimeType() const { return m_mimetype; } StreamCount_URL_Link* GetEmbedSrcUrl() { return static_cast<StreamCount_URL_Link *>(url_list.First()); } HTML_Element* GetHtmlElement() const { return m_htm_elm; } void SetHtmlElement(HTML_Element* htm_elm) { m_htm_elm = htm_elm; } /* ElementRef implementation. */ /** Called when the element is about to be deleted. */ virtual void OnDelete(FramesDocument* document); void SetSaved(NPSavedData* sav) { saved = sav; } NPSavedData* GetSaved() { return saved; } char** GetArgs8() { return m_args8; } int16 GetArgc() { return m_argc; } void PushLockEnabledState(); void PopLockEnabledState(); BOOL GetLockEnabledState() { return m_lock_stack != NULL; } /** * Check if the plug-in can handle painting or NPP_SetWindow. * * Display() will be post-poned if the plug-in has not been initialized * (NPP_SetWindow cannot precede NPP_New) or we are busy processing another * paint event or SetWindow call. * * @return TRUE if the plug-in can process Plugin::Display(). */ BOOL IsDisplayAllowed(); /** * Check if we are already processing NPP_SetWindow or NPP_HandleEvent(paint). * * See Plugin::SetWindowProtected(). */ BOOL IsWindowProtected() { return m_is_window_protected; } /** * Prevent or allow calls to Plugin::Display(). * * Set TRUE before entering NPP_SetWindow or NPP_HandleEvent (when painting) * to ensure we do not nest window related calls. Set FALSE afterwards. * * @param is_window_protected TRUE to protect window, FALSE otherwise. */ void SetWindowProtected(BOOL is_window_protected = TRUE); /** * Check if Display() was called while IsDisplayAllowed() was false, and * if that was the case, then perform the post-poned Display. * * This method may only be called if IsDisplayAllowed(). */ void HandlePendingDisplay(); void SetContextMenuActive(BOOL c) { m_context_menu_active = c; } BOOL GetContextMenuActive() { return m_context_menu_active; } #if defined(NS4P_WMP_STOP_STREAMING) || defined(NS4P_WMP_CONVERT_CODEBASE) || defined(NS4P_WMP_LOCAL_FILES) BOOL IsWMPMimetype() { return m_is_wmp_mimetype; } #endif // NS4P_WMP_STOP_STREAMING || NS4P_WMP_CONVERT_CODEBASE || NS4P_WMP_LOCAL_FILES OpNPObject* GetScriptableObject() const { return m_scriptable_object; } ES_Object* GetDOMElement() const { return m_domelement; } uint16 GetMode() { return m_mode; } void SetPluginUrlRequestsDisplayed(BOOL stat) { m_plugin_url_requests_displayed = stat; } BOOL GetPluginUrlRequestsDisplayed() { return m_plugin_url_requests_displayed; } void PushPopupsEnabledState(NPBool enabled); void PopPopupsEnabledState(); NPBool GetPopupEnabledState() { return m_popup_stack && m_popup_stack->GetPopupState(); } NPObject* GetWindowNPObject(); NPObject* GetPluginElementNPObject(); BOOL SameWindow(NPWindow npwin); #ifdef USE_PLUGIN_EVENT_API OP_STATUS AddParams(URL* url, BOOL embed_url_changed, BOOL add_allowscriptaccess); OP_STATUS AddParams(int argc, const uni_char* argn[], const uni_char* argv[], URL* url, BOOL embed_url_changed, BOOL is_flash); #else OP_STATUS AddParams(int16 argc, const uni_char* argn[], const uni_char* argv[], URL* url, BOOL embed_url_changed, BOOL is_flash); #endif // USE_PLUGIN_EVENT_API #ifdef USE_PLUGIN_EVENT_API /** Register a listener that will receive plugin events for this plugin. * If the listener object is destroyed before the plugin object, the * listener should be detach using SetWindowListener(NULL). If the plugin * is destroyed first, it will implicitly stop delivering events. */ void SetWindowListener(OpPluginWindowListener* listener); #endif // USE_PLUGIN_EVENT_API OpPluginWindow* GetPluginWindow() const { return m_plugin_window; } #ifdef USE_PLUGIN_EVENT_API OpNS4PluginAdapter* GetPluginAdapter() const { return m_plugin_adapter; } #endif // USE_PLUGIN_EVENT_API #ifndef USE_PLUGIN_EVENT_API void RemovePluginWindow() { m_plugin_window = NULL; } #endif // !USE_PLUGIN_EVENT_API void SetPopupsEnabled(BOOL enabled); BOOL IsPopupsEnabled() { return m_popups_enabled; } void StopLoading(URL& url); OP_BOOLEAN HandlePostRequest(BYTE type, const char* url_name, const char* window, uint32 len, const char* buf, NPBool file, void* notifyData = NULL); OP_STATUS InterruptStream(int url_id, NPReason reason); OP_STATUS Redirect(URL_ID orig_url_id); OP_STATUS SetWindowPos(int x, int y); void HideWindow(); /** * Detach plugin window from its parents and siblings in the window * system. The window will remain alive and fully intact. * * Intended to allow the UI's destruction of windows and tabs to be * decoupled from plugin instance termination. */ void DetachWindow(); URL DetermineURL(BYTE type, const char* url_name, BOOL unique); URL GetBaseURL(); void DeterminePlugin(BOOL& is_flash, BOOL& is_acrobat_reader); OP_STATUS SetFailure(BOOL crashed, const OpMessageAddress& address = OpMessageAddress()); BOOL IsFailure() { return m_is_failure; } #ifdef NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND BOOL SpoofUA() const { return m_spoof_ua; } OP_STATUS DetermineSpoofing(); #endif // NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND #ifdef NS4P_TRY_CATCH_PLUGIN_CALL OP_STATUS SetException() { m_is_exception = TRUE; return SetFailure(FALSE); } BOOL IsException() { return m_is_exception; } #endif // NS4P_TRY_CATCH_PLUGIN_CALL virtual BOOL IsPluginFullyInited(); /** * Get the origin of the plugin's document URL. * * @param[out] The origin of the document on success. * @return OpStatus::OK on success * OpStatus::ERR_NO_SUCH_RESOURCE if document was detached. * OpStatus::ERR_NO_MEMORY on OOM. */ OP_STATUS GetOrigin(char** origin); void Activate(); void DeleteStream(PluginStream* ps); void EnterSynchronousLoop() { m_in_synchronous_loop++; } void LeaveSynchronousLoop() { m_in_synchronous_loop--; } BOOL IsInSynchronousLoop() { return m_in_synchronous_loop > 0; } void SetScriptException(BOOL e) { m_script_exception = e; } BOOL IsScriptException() { return m_script_exception; } OP_STATUS SetExceptionMessage(const NPUTF8 *message) { return m_script_exception_message.SetFromUTF8(message); } const uni_char* GetExceptionMessage() { return m_script_exception_message.CStr(); } #ifdef _MACINTOSH_ NPDrawingModel GetDrawingModel() { return m_drawing_model; } void SetDrawingModel(NPDrawingModel drawing_model) { m_drawing_model = drawing_model; } /** * Enable/disable use of Core Animation. * @param ca Whether to use Core Animation. */ void SetCoreAnimation(BOOL ca) { m_core_animation = ca; } #endif // _MACINTOSH_ /* * When NS4P_INVALIDATE_INTERVAL is set to 0 this method simply invokes InvalidateInternal(). * When NS4P_INVALIDATE_INTERVAL > 0 this method assures that InvalidateInternal() isn't called more often then NS4P_INVALIDATE_INTERVAL, * so the region to invalidate is stored in m_invalid_rect and the timer is set. * For flash video InvalidateInternal() is called independently of NS4P_INVALIDATE_INTERVAL - according to one of CORE-23977 goals * it is not throttled. * @param invalidRect the region to invalidate */ void Invalidate(NPRect *invalidRect); #if NS4P_INVALIDATE_INTERVAL > 0 /* * Invokes dalayed InvalidateInternal(). */ void OnTimeOut(OpTimer* timer); /* * This method is called from the PluginStream to mark plugin as the flash video content. * According to one of CORE-23977 goals flesh videos should not be throttled. * @param isFlashVideo new value for m_is_flash_video member */ void SetIsFlashVideo(BOOL isFlashVideo) { m_is_flash_video = isFlashVideo; } #endif // NS4P_INVALIDATE_INTERVAL > 0 void OnStreamDeleted(PluginStream* stream) { if (stream == m_main_stream) m_main_stream = NULL; } /* Checks if an equal url is already streaming (by being one of the predecessors of ps). * Note that when a plugin stream is finished, it is removed from the list. * @param ps PluginStream object representing the url to be streamed to the plugin * * @return TRUE ps has a predecessor PluginStream object with the same url id * FALSE ps has no predecessor PluginStream objects with the same url id */ BOOL IsEqualUrlAlreadyStreaming(PluginStream* ps); #if NS4P_STARVE_WHILE_LOADING_RATE>0 /* * Starving the plugin delays processing of the data by the plugin decreasing the CPU consumption during page loading. * The value of NS4P_STARVE_WHILE_LOADING_RATE defines how often plugin will be starved (not fed with data) when the page is being loaded. * @return TRUE plugin should be starved in this cycle * FALSE plugin should not be starved in this cycle */ BOOL IsStarving(); #endif // NS4P_STARVE_WHILE_LOADING_RATE /** * Order is important - allows us to check states with range comparisons. */ enum LifeCycleState { FAILED_OR_TERMINATED = 0, ///< Broken UNINITED = 1, ///< Start state PRE_NEW, ///< Inside the New call NEW_WITHOUT_WINDOW, ///< Between New but before any SetWindow WITH_WINDOW, ///< After a SetWindow but before READYFORSTREAMING RUNNING ///< Fully started, everything goes }; void SetLifeCycleState(LifeCycleState new_state) { OP_ASSERT(new_state == FAILED_OR_TERMINATED || m_life_cycle_state != FAILED_OR_TERMINATED); // Can never leave FAILED_OR_TERMINATED OP_ASSERT(new_state == FAILED_OR_TERMINATED || new_state == m_life_cycle_state + 1); // Can only move forward one step at the time m_life_cycle_state = new_state; } LifeCycleState GetLifeCycleState() const { return m_life_cycle_state; } /** Add an ES_Object -> OpNPObject to the list of active bindings. * * @param internal Key. * @param object Value. * * @return OpStatus::OK, or OpStatus::ERR_NO_MEMORY on memory allocation failure. */ OP_STATUS AddBinding(const ES_Object* internal, OpNPObject* object); /** Remove an ES_Object -> OpNPObject from the list of active bindings. * * @param object Object to be removed. */ void RemoveBinding(const ES_Object* internal); /** Invalidate OpNPObject. * * @param object Object that should no longer be referenced. */ void InvalidateObject(OpNPObject* object); /** Look up an OpNPObject based on its internal ES_Object. * * @param internal The internal ES_Object to match against. * * @return A uniquely matching OpNPObject or NULL if none exist. */ OpNPObject* FindObject(const ES_Object* internal); /** Take ownership of an OpNPObject. * * @param object The object now belonging to this plug-in instance. */ void AddObject(OpNPObject* object) { object->Into(&m_objects); } private: /* * Does the actual work of invalidating the specified drawing area prior to repainting or refreshing. * @param invalidRect the region to invalidate * @param currentRuntimeMs this parameter is used to pass the actual value of GetRuntimeMS in order to reduce the number of calls to this method. * If 0. is passed in this parameter GetRuntimeMS is called internally in order to obtain the current runtime. */ void InvalidateInternal(OpRect *invalidRect, double currentRuntimeMs = 0.); private: #if NS4P_INVALIDATE_INTERVAL > 0 /** The time of last InvalidateInternal execution */ double m_last_invalidate_time; /** The rect to invalidate in next InvalidateInternal execution */ OpRect m_invalid_rect; /** Indicates that the last invalidate is already delayed, so the next InvalidateInternal should invalidate the union of previous and current rects. */ BOOL m_invalidate_timer_set; /** Timer for delaying plugin invalidates */ OpTimer *m_invalidate_timer; /** See SetIsFlashVideo() method */ BOOL m_is_flash_video; #endif // NS4P_INVALIDATE_INTERVAL > 0 #if NS4P_STARVE_WHILE_LOADING_RATE>0 /** See IsStarving() method */ int m_starvingStep; #endif // NS4P_STARVE_WHILE_LOADING_RATE Head stream_list; Head url_list; /* Make sure files aren't deleted while the plug-in runs */ uni_char* plugin_name; INT32 ID; int stream_counter; FramesDocument* m_document; URL m_document_url; PluginStream* m_main_stream; LifeCycleState m_life_cycle_state; #ifdef USE_PLUGIN_EVENT_API OpPluginWindowListener* m_window_listener; OpRect m_view_rect; ///< plug-in window rectangle relative to the OpView, in scaled units #endif // USE_PLUGIN_EVENT_API OpPluginWindow* m_plugin_window; BOOL m_plugin_window_detached; ///< plug-in window has been detached after creation. #ifdef USE_PLUGIN_EVENT_API OpNS4PluginAdapter* m_plugin_adapter; #ifdef NS4P_COMPONENT_PLUGINS OpMessageAddress m_plugin_adapter_channel_address; #endif // NS4P_COMPONENT_PLUGINS #endif // USE_PLUGIN_EVENT_API NPPluginFuncs* pluginfuncs; NPP_t instance_struct; NPSavedData* saved; NPWindow npwin; #ifndef USE_PLUGIN_EVENT_API int win_x; int win_y; #endif // !USE_PLUGIN_EVENT_API BOOL windowless; BOOL transparent; BOOL m_core_animation; NPMIMEType m_mimetype; HTML_Element* m_htm_elm; PluginMsgType m_lastposted; char** m_args8; int16 m_argc; #ifdef USE_PLUGIN_EVENT_API /** Display was called while !IsDisplayAllowed() and must be re-started. @See HandlePendingDisplay(). */ BOOL m_pending_display; /** Initial display was called while !IsDisplayAllowed() and must be re-started. @See HandlePendingDisplay(). */ BOOL m_pending_create_window; #endif // USE_PLUGIN_EVENT_API #ifdef _MACINTOSH_ NPDrawingModel m_drawing_model; #endif // _MACINTOSH_ class LockStack { private: LockStack* m_previous_lock; public: LockStack(LockStack* previous_lock) { m_previous_lock = previous_lock;} ~LockStack() {} LockStack* Pred() { return m_previous_lock; } }; LockStack* m_lock_stack; /** Are we performing NPP_SetWindow or NPP_HandleEvent(paint)? @See Plugin::SetWindowProtected(). */ BOOL m_is_window_protected; BOOL m_context_menu_active; #if defined(NS4P_WMP_STOP_STREAMING) || defined(NS4P_WMP_CONVERT_CODEBASE) BOOL m_is_wmp_mimetype; #endif // NS4P_WMP_STOP_STREAMING || NS4P_WMP_CONVERT_CODEBASE void SetLastPosted( const PluginMsgType ty ) { m_lastposted = ty; } PluginMsgType GetLastPosted() const { return m_lastposted; } OP_STATUS CreatePluginWindow(const OpRect& scaled_rect); /** ES_Object -> OpNPObject map. */ OpPointerHashTable<ES_Object, OpNPObject> m_internal_objects; /** Objects belonging to this instance. */ List<OpNPObject> m_objects; /** Cached plugin scriptable object. May be NULL. Included in m_objects. */ OpNPObject* m_scriptable_object; ES_Object* m_domelement; uint16 m_mode; BOOL m_plugin_url_requests_displayed; OpComponentType m_component_type; class PopupStack { private: NPBool m_popup_enabled; PopupStack* m_previous_popup; public: PopupStack(NPBool popup_enabled, PopupStack* previous_popup) { m_popup_enabled = popup_enabled; m_previous_popup = previous_popup;} ~PopupStack() {} PopupStack* Pred() { return m_previous_popup; } NPBool GetPopupState() { return m_popup_enabled; } }; PopupStack* m_popup_stack; NPWindow m_last_npwin; OP_STATUS SetMimeType(const uni_char* mime_type); BOOL m_popups_enabled; BOOL m_is_failure; # ifdef NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND BOOL m_spoof_ua; # endif // NS4P_WINDOWLESS_MACROMEDIA_WORKAROUND #ifdef NS4P_TRY_CATCH_PLUGIN_CALL BOOL m_is_exception; #endif // NS4P_TRY_CATCH_PLUGIN_CALL INT m_in_synchronous_loop; BOOL m_script_exception; OpString m_script_exception_message; WantsAllNetworkStreamsType m_wants_all_network_streams_type; /** Check if any additional NPP_New() argn parameters should be added and * assign the extra parameters to Plugin::m_args8 and Plugin::m_argc. * @param[in, out] count The number of parameters added so far * @param[in] add_restricted_allowscriptaccess If TRUE, ALLOWSCRIPTACCESS=SAMEDOMAIN is added * @param[in] add_baseurl If TRUE, BASEURL=<baseurl> is added * @param[in] baseurl Name of the baseurl * @param[in] add_srcurl If TRUE, SRC=<srcurl> is added * @param[in] srcurl Name of the srcurl * @returns Normal OOM values. */ OP_STATUS AddExtraParams(int& count, BOOL add_restricted_allowscriptaccess, BOOL add_baseurl, OpString baseurl, BOOL add_srcurl, OpString srcurl); /** Keeps a local 'is active'-state for all plugins. Used to detect if opera is idle, important for testing */ OpAutoActivity activity_plugin; // ----------------------------------------------------------- // // DEPRECATED API : // // ----------------------------------------------------------- #ifndef USE_PLUGIN_EVENT_API DEPRECATED(OP_STATUS OldSetWindow()); DEPRECATED(int16 OldHandleEvent(void *event, BOOL lock = TRUE)); DEPRECATED(BOOL OldHandleEvent(DOM_EventType event, const OpPoint& point, int button_or_key, ShiftKeyState modifiers)); DEPRECATED(OP_STATUS OldNew(FramesDocument* frames_doc, void* plugin_window, const uni_char *mimetype, uint16 mode, int16 argc, const uni_char *argn[], const uni_char *argv[], URL* url, BOOL embed_url_changed)); DEPRECATED(OP_STATUS OldSetWindow(int x, int y, unsigned int width, unsigned int height, BOOL show, const OpRect* rect = NULL)); DEPRECATED(void OldPrint(const VisualDevice* vd, const int x, const int y, const unsigned int width, const unsigned int height)); DEPRECATED(OP_STATUS OldDestroy()); DEPRECATED(void OldPluginDestructor()); #endif // USE_PLUGIN_EVENT_API // ----------------------------------------------------------- }; #ifndef USE_PLUGIN_EVENT_API inline OP_STATUS Plugin::OldSetWindow() { return SetWindow(); } #endif // !USE_PLUGIN_EVENT_API /** Class for linked parameters, built with removed duplicates of name, as a temporary solution for bug #253601 */ class PluginParameter : public Link { private: /** The parameter's name, unique in the linked list. */ OpString m_parameter_name; /** The parameter's matched (first) value. */ OpString m_parameter_value; public: OP_STATUS SetNameAndValue(const uni_char* name, const uni_char* value) { RETURN_IF_ERROR(m_parameter_name.Set(name)); return m_parameter_value.Set(value); } const uni_char* GetName() const { return m_parameter_name.CStr(); } const uni_char* GetValue() const { return m_parameter_value.CStr(); } /** Contain() checks if the parameter's name matches a given string */ BOOL Contain(const uni_char* name) { return uni_stri_eq(m_parameter_name.CStr(), name); } /** Suc() returns the next parameter in the list, built with removed duplicates */ PluginParameter* Suc() const { return (PluginParameter*)Link::Suc(); } /** FindInValue() checks if the parameter's value starts with a given string */ BOOL FindInValue(const uni_char* name) { return (m_parameter_value.Find(name) == 0) ? TRUE : FALSE; } }; #if defined(NS4P_TRY_CATCH_PLUGIN_CALL) || defined(MEMTOOLS_ENABLE_STACKGUARD) class InCallFromPlugin { #ifdef MEMTOOLS_ENABLE_STACKGUARD OpStackTraceGuard stop_stack_trace_extraction; // Don't venture into calling plugin #endif // MEMTOOLS_ENABLE_STACKGUARD #ifdef NS4P_TRY_CATCH_PLUGIN_CALL BOOL m_knew_that_it_was_plugin; public: InCallFromPlugin() { // Sometimes the plugin that is calling us is coming // directly from the platform message loop and in that // case we haven't registered that we were in a plugin // and should not set the flag either because nobody will // clear it when the plugin returns. m_knew_that_it_was_plugin = g_opera->ns4plugins_module.is_executing_plugin_code; g_opera->ns4plugins_module.is_executing_plugin_code = FALSE; } ~InCallFromPlugin() { g_opera->ns4plugins_module.is_executing_plugin_code = m_knew_that_it_was_plugin; } #endif // NS4P_TRY_CATCH_PLUGIN_CALL }; # define IN_CALL_FROM_PLUGIN InCallFromPlugin in_call_from_plugin; // sets global state #else # define IN_CALL_FROM_PLUGIN #endif // NS4P_TRY_CATCH_PLUGIN_CALL || MEMTOOLS_ENABLE_STACKGUARD #endif // _PLUGIN_SUPPORT_ #endif // !_PLUGIN_H_INC_
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Path.hpp" #include "Core/Variant.hpp" #include "Core/ResourceManager.hpp" #include "Render/Uniform.hpp" #include <vector> #include <string> namespace Push { class Shader : public Noncopyable { public: Shader(); void Setup() const; bool IsReady() const; bool HasUniform(UniformName uniform) const; Variant& GetUniform(UniformName name); template<typename T> void SetUniform(UniformName uniform, const T& value); template<typename Serializer> void Serialize(Serializer& serializer); void Initialize(const Path& file); void Initialize(const char* vsh, const char* fsh, const std::vector<UniformName>& uniforms); private: void Initialize(); private: Path m_file; std::unique_ptr<Resource, ResourceDeleter> m_resource; Path m_resourceFile; Variant m_values[Value(UniformName::Count)]; bool m_uniforms[Value(UniformName::Count)] = {false}; }; template<typename Serializer> void Shader::Serialize(Serializer& serializer) { Push::Serialize(serializer, "Resource", m_resourceFile); for(size_t index = 0; index < Value(UniformName::Count); index += 1) { //Serialize(serializer, s_uniforms[index].m_name, m_uniforms[index]); } //INITIALIZE(); } template<typename T> void Shader::SetUniform(UniformName uniform, const T& value) { m_values[Value(uniform)] = value; } }
#pragma once #include <iostream> #include <string> #include <fstream> #include <stdio.h> #include <cstring> #include <cstdio> #include "prototyps.h" using namespace std;
#pragma once #include"pch.h" #include"WICTextureLoader.h" static const WCHAR* TEXTURE_PATH = L"Textures/"; static const WCHAR* ERROR_TEXTURE = L"error_tex.png"; class ResourceHandler { private: ResourceHandler() {}; std::map<const std::wstring, ID3D11ShaderResourceView*> map; std::map<const std::wstring, DirectX::SoundEffect*> audioMap; bool createTextureFromFile(ID3D11Device* device, ID3D11DeviceContext* dContext, const WCHAR* txturePath) { bool couldLoad = true; map[txturePath] = nullptr; HRESULT hr = DirectX::CreateWICTextureFromFile(device, dContext, txturePath, nullptr, &map[txturePath]); if (FAILED(hr)) { couldLoad = false; } assert(SUCCEEDED(hr) && "Error, failed to load texture file!"); return couldLoad; } public: static ResourceHandler& get() { static ResourceHandler handlerInstance; return handlerInstance; } ResourceHandler(ResourceHandler const&) = delete; void operator=(ResourceHandler const&) = delete; ~ResourceHandler() { std::map<const std::wstring, ID3D11ShaderResourceView*>::iterator i = map.begin(); while(i != map.end()) { i->second->Release(); i++; } std::map<const std::wstring, DirectX::SoundEffect*>::iterator ai = audioMap.begin(); while (ai != audioMap.end()) { delete ai->second; ai++; } } ID3D11ShaderResourceView* getTexture(const WCHAR* texturePath) { if (map[texturePath] == nullptr) { if (m_device != nullptr) { createTextureFromFile(m_device, m_dContext, texturePath); } return map[texturePath]; } else { return map[texturePath]; } } void loadAudio(const std::wstring sound, const std::shared_ptr<DirectX::AudioEngine> m_audioEngine) { if (audioMap[sound] == nullptr) { audioMap[sound] = new DirectX::SoundEffect(m_audioEngine.get(), sound.c_str()); } } DirectX::SoundEffect* getAudio(const std::wstring sound) { if (audioMap[sound] == nullptr) { assert(false && "Error, trying to get audio not yet loaded!"); } return audioMap[sound]; } ID3D11Device* m_device = nullptr; ID3D11DeviceContext* m_dContext = nullptr; };
// // stuctsProj1.cpp // dataone // // Created by John Goza on 6/16/16. // Copyright © 2016 JohnGoza. All rights reserved. // #include <stdio.h> #include "assignment.h" #include <fstream> #include <list> using namespace std; int main(){ }
/* XMRig * Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh> * Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/net/dns/DnsConfig.h" #include "3rdparty/rapidjson/document.h" #include "base/io/json/Json.h" #include <algorithm> namespace xmrig { const char *DnsConfig::kField = "dns"; const char *DnsConfig::kIPv6 = "ipv6"; const char *DnsConfig::kTTL = "ttl"; } // namespace xmrig xmrig::DnsConfig::DnsConfig(const rapidjson::Value &value) { m_ipv6 = Json::getBool(value, kIPv6, m_ipv6); m_ttl = std::max(Json::getUint(value, kTTL, m_ttl), 1U); } rapidjson::Value xmrig::DnsConfig::toJSON(rapidjson::Document &doc) const { using namespace rapidjson; auto &allocator = doc.GetAllocator(); Value obj(kObjectType); obj.AddMember(StringRef(kIPv6), m_ipv6, allocator); obj.AddMember(StringRef(kTTL), m_ttl, allocator); return obj; }
#include <string> #include <cstdio> #include <chrono> #include <iostream> #include <vector> #include <utility> #include <algorithm> using namespace std; typedef vector<int> TrabajosFinales; typedef int Indice; typedef vector<vector<int> > Costos; int cantTrabajos; Costos cs; vector<vector<int> > matriz; int minimizacionDeCostos(int m1, int m2) { int sigTrabajo = max(m1, m2)+1; //calculo el siguiente trabajo if (sigTrabajo > cantTrabajos) return 0; if (matriz[m1][m2]>-1) return matriz[m1][m2]; else { int costo1 = cs[sigTrabajo-1][m1] + minimizacionDeCostos(sigTrabajo, m2); int costo2 = cs[sigTrabajo-1][m2] + minimizacionDeCostos(m1, sigTrabajo); if (costo1 < costo2) { matriz[m1][m2] = costo1; matriz[m2][m1] = costo1; return costo1; } else { matriz[m1][m2] = costo2; matriz[m2][m1] = costo2; return costo2; } } } void inicializarMinimizacionDeCostos() { //caso base: No hay trabajos if(cantTrabajos == 0){ cout << 0 << " " << 0 <<endl; return; } matriz.resize(cantTrabajos); for(int i = 0; i < cantTrabajos; i++) matriz[i].resize(cantTrabajos, -1); cout << minimizacionDeCostos(0,0) << " "; int m1=0, m2=0; vector<int> maquina1; for (int i = 1; i < cantTrabajos; ++i) if (matriz[i][m2] < matriz[m1][i]) m1 = i; else { m2 = i; maquina1.push_back(i); } if (cs[cantTrabajos-1][m2] < cs[cantTrabajos-1][m1]) maquina1.push_back(cantTrabajos); cout << maquina1.size() << " "; for (unsigned int i = 0; i < maquina1.size(); ++i) cout << maquina1[i] << " "; cout << endl; return; } int main() { // stdin = freopen("./ej1.in", "r", stdin); int termino = '1'; while (termino != '0') { int c; cs.clear(); //Limpio cs para las proximas instancias cin >> cantTrabajos; //Me guardo la cantidad de trabajos cs.resize(cantTrabajos); //Mi matriz de costos tiene una fila por cada trabajo for (int i=0;i<cantTrabajos;++i) { //En cada trabajo tiene una cantidad de costos escalonada depdendiente el i-ésimo trabajo for (int j=0;j<=i;++j) { cin >> c; cs[i].push_back(c); } } auto t1 = chrono::high_resolution_clock::now(); inicializarMinimizacionDeCostos(); auto t2 = chrono::high_resolution_clock::now(); auto x = chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count(); cerr << cantTrabajos << " " << x << endl; termino = (cin >> ws).peek(); } return 0; }
#include <iostream> #include <algorithm> int main(void) { int n; scanf("%d", &n); int** originArr = new int*[n]; int** solArr = new int*[n]; for (int i = 0; i < n; i++) { originArr[i] = new int[3]; solArr[i] = new int[3]; } for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { scanf("%d", &originArr[i][j]); } if (i == 0) { for (int j = 0; j < 3; j++) solArr[0][j] = originArr[0][j]; } else { solArr[i][0] = std::min(solArr[i - 1][1], solArr[i - 1][2]) + originArr[i][0]; solArr[i][1] = std::min(solArr[i - 1][0], solArr[i - 1][2]) + originArr[i][1]; solArr[i][2] = std::min(solArr[i - 1][0], solArr[i - 1][1]) + originArr[i][2]; } } int min = std::min(solArr[n - 1][0], std::min(solArr[n - 1][1], solArr[n - 1][2])); printf("%d", min); for (int i = 0; i < n; i++) { delete[] originArr[i]; delete[] solArr[i]; } delete[] originArr; delete[] solArr; return 0; }
/* * levelset.h * deflektor-ds * * Created by Hugh Cole-Baker on 4/1/09. * A levelset manages a series of levels, and plays through them in sequence. * There are also some functions for fading out the screen in between levels * and if the player gets "game over" */ #ifndef deflektor_levelset_h #define deflektor_levelset_h #include <unistd.h> struct LevelParams; class Level; class LevelSet { char levelStr[11]; char livesStr[9]; int currentScore, currentLives, currentLevel, dirLen; public: static void fadeToBlack(); static void fadeFromBlack(); static void blackScreen(); static void blackScreenSub(); static void disableFade(); static void fadeToBlackSub(); static void disableFadeSub(); void gameOver(Level* ended); static void captureScreen(int bank); static void blurScreen(int iters, int bank, bool fadeSub); bool playLevel(char* levelfile); char filename[MAXPATHLEN]; LevelSet(char* directory); void playLevelSet(); }; #endif