text
stringlengths
8
6.88M
#include <iostream> #include <stdio.h> #include <string> #include <stdlib.h> #include "camadaenlace.cpp" #include "camadafisica.cpp" using namespace std; int main (){ int size = 32; int quadro[size]; //CamadaEnlaceDadosTransmissora(quadro); AplicacaoTransmissora(); }
/************************************************************************************** * File Name : Vertices.cpp * Project Name : Keyboard Warriors * Primary Author : JeongHak Kim * Secondary Author : * Copyright Information : * "All content 2019 DigiPen (USA) Corporation, all rights reserved." **************************************************************************************/ #include "GL/glew.h" #include "Vertices.h" #include "Mesh.h" Vertices::Vertices(const Mesh& mesh, const VerticesDescription& vertex_layout) noexcept { InitializeWithMeshAndLayout(mesh, vertex_layout); } void Vertices::InitializeWithMeshAndLayout(const Mesh& mesh, const VerticesDescription& vertex_layout) noexcept { switch (mesh.GetShapePattern()) { case ShapePattern::Line: pattern = GL_LINES; break; case ShapePattern::Quads: pattern = GL_QUADS; break; case ShapePattern::Triangles: pattern = GL_TRIANGLES; break; case ShapePattern::TriangleFan: pattern = GL_TRIANGLE_FAN; break; case ShapePattern::TriangleStrip: pattern = GL_TRIANGLE_STRIP; break; } layout = vertex_layout; verticesCount = static_cast<int>(mesh.GetPointsCount()); bufferVertexCapacity = static_cast<int>(verticesCount * layout.GetVertexSize()); glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); SelectVAO(*this); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, bufferVertexCapacity, NULL, GL_STATIC_DRAW); layout.EnableAttributes(); WriteMeshDataToVertexBuffer(mesh); } void Vertices::UpdateVeticesFromMesh(const Mesh& mesh) { if (static_cast<int>(mesh.GetPointsCount()) > bufferVertexCapacity) { DeleteVerticesOnGPU(); InitializeWithMeshAndLayout(mesh, layout); } } void Vertices::SelectVAO(const Vertices& vertices) noexcept { glBindVertexArray(vertices.VAO); } void Vertices::SelectNothing() { glBindVertexArray(0); } unsigned Vertices::GetPattern() const noexcept { return pattern; } int Vertices::GetVerticesCount() const noexcept { return verticesCount; } void Vertices::WriteMeshDataToVertexBuffer(const Mesh& mesh) const noexcept { char* buffer = reinterpret_cast<char*>(glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY)); glBindBuffer(GL_ARRAY_BUFFER, VBO); unsigned offset = 0; vec2<float> point; Color4f color; vec2<float> texture; for (int i = 0; i < static_cast<int>(verticesCount); ++i) { for (VerticesDescription::Type element : layout.GetTypes()) { switch (element) { case VerticesDescription::Type::Point: point = mesh.GetPoint(i); memcpy(buffer + offset, &point, sizeof(point)); offset += sizeof(vec2<float>); break; case VerticesDescription::Type::Color: color = mesh.GetColor(i); memcpy(buffer + offset, &color, sizeof(color)); offset += sizeof(Color4f); break; case VerticesDescription::Type::TextureCoordinate: texture = mesh.GetTextureCoordinate(i); memcpy(buffer + offset, &texture, sizeof(texture)); offset += sizeof(vec2<float>); break; } } } glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); SelectNothing(); } void Vertices::DeleteVerticesOnGPU() const { glDeleteBuffers(1, &VBO); glDeleteVertexArrays(1, &VAO); }
/* Includes ------------------------------------------------------------------*/ #include "chassis_ctrl.h" /* Function prototypes -------------------------------------------------------*/ /** * @brief Constructor */ ChassisCtrl_Classdef::ChassisCtrl_Classdef() :xScale(1.f), yScale(1.f) {} /** * @brief Destructor */ ChassisCtrl_Classdef::~ChassisCtrl_Classdef() {} /** * @brief Write PID parameters * @param kp, ki, kd, i_max, out_max: Refer to PID.h * @retval None */ void ChassisCtrl_Classdef::initPID(float kp, float ki, float kd, float i_max, float out_max) { chassisYawAngle.SetPIDParam(kp, ki, kd, i_max, out_max); } /** * @brief Single step follow-up kinematic solution to the chassis * @param mode: Current control mode * @retval None */ void ChassisCtrl_Classdef::singleStepControl(Mode_Enumdef mode) { float speed_raw[3] = {}; float speed_calc[3] = {}; switch (mode) { case NORMAL: case ASSIST: speed_raw[X] = axisSpeed[X] * xScale; speed_raw[Y] = axisSpeed[Y] * yScale; chassisYawAngle.Current = yawMotorAng; chassisYawAngle.Target = 0; chassisYawAngle.Adjust(); speed_raw[Z] = chassisYawAngle.Out; break; case ROTATE: speed_raw[X] = speed_raw[Y] = 0; speed_raw[Z] = 80; break; case RUNE: case STATIC: case RUNAWAY: speed_raw[X] = speed_raw[Y] = speed_raw[Z] = 0; break; case TUNE_PID: speed_raw[X] = axisSpeed[X] * xScale; speed_raw[Y] = axisSpeed[Y] * yScale; //chassisYawAngle.Current = fmod(yawMotorAng, 2 * 3.1415926); chassisYawAngle.Current = yawMotorAng; chassisYawAngle.Target = 0; chassisYawAngle.Adjust(); speed_raw[Z] = chassisYawAngle.Out; } yawMotorAng = 0; speed_calc[X] = speed_raw[X] * cos(yawMotorAng * 3.1415926 / 180.0) + speed_raw[Y] * sin(yawMotorAng * 3.1415926 / 180.0); speed_calc[Y] = speed_raw[Y] * cos(yawMotorAng * 3.1415926 / 180.0) - speed_raw[X] * sin(yawMotorAng * 3.1415926 / 180.0); speed_calc[Z] = speed_raw[Z]; this->wheelSpeed[0] = -speed_calc[X] - speed_calc[Y] - speed_calc[Z]; this->wheelSpeed[1] = -speed_calc[X] + speed_calc[Y] - speed_calc[Z]; this->wheelSpeed[2] = +speed_calc[X] + speed_calc[Y] - speed_calc[Z]; this->wheelSpeed[3] = +speed_calc[X] - speed_calc[Y] - speed_calc[Z]; } /* Here is emporarily */ void ChassisCtrl_Classdef::writeCtrlData(float x, float y) { this->axisSpeed[X] = x; this->axisSpeed[Y] = y; } void ChassisCtrl_Classdef::writeMotorData(float yaw_ang) { this->yawMotorAng = yaw_ang; } /************************ COPYRIGHT(C) SCUT-ROBOTLAB **************************/
#include <iostream> #include "Evenement.hh" using namespace std;
/* Solicitar números reais do usuário (UTILIZE ESTRUTURA DE REPETIÇÃO) e imprimir: Total de números entre 20 e 50. Total de números menores que 4. O programa termina quando o número for um número negativo (que não deve ser considerado na contagem). */ #include<stdlib.h> #include<stdio.h> main(){ int num=0, total=0, menos=0; while(1){ printf("Digite um numero: "); scanf("%d",&num); if (num<0){ break; } if ( (num >=0) && (num <4) ){ menos++; } if ( (num >= 20) && (num <= 50) ){ total++; } } printf("\nTotal de numeros entre 20 e 50: %d",total); printf("\nTotal de numeros menores que 4: %d",menos); }
#include "../idlib/precompiled.h" #pragma hdrstop #include "Game_local.h" #include "ai/AI_Manager.h" /* =============================================================================== idTrigger =============================================================================== */ const idEventDef EV_Enable( "enable", NULL ); const idEventDef EV_Disable( "disable", NULL ); CLASS_DECLARATION( idEntity, idTrigger ) EVENT( EV_Enable, idTrigger::Event_Enable ) EVENT( EV_Disable, idTrigger::Event_Disable ) END_CLASS /* ================ idTrigger::DrawDebugInfo ================ */ void idTrigger::DrawDebugInfo( void ) { idMat3 axis = gameLocal.GetLocalPlayer()->viewAngles.ToMat3(); idVec3 up = axis[ 2 ] * 5.0f; idBounds viewTextBounds( gameLocal.GetLocalPlayer()->GetPhysics()->GetOrigin() ); idBounds viewBounds( gameLocal.GetLocalPlayer()->GetPhysics()->GetOrigin() ); idBounds box( idVec3( -4.0f, -4.0f, -4.0f ), idVec3( 4.0f, 4.0f, 4.0f ) ); idEntity *ent; idEntity *target; int i; bool show; const function_t *func; viewTextBounds.ExpandSelf( 128.0f ); viewBounds.ExpandSelf( 512.0f ); for( ent = gameLocal.spawnedEntities.Next(); ent != NULL; ent = ent->spawnNode.Next() ) { if ( ent->GetPhysics()->GetContents() & ( CONTENTS_TRIGGER | CONTENTS_FLASHLIGHT_TRIGGER ) ) { show = viewBounds.IntersectsBounds( ent->GetPhysics()->GetAbsBounds() ); if ( !show ) { for( i = 0; i < ent->targets.Num(); i++ ) { target = ent->targets[ i ].GetEntity(); if ( target && viewBounds.IntersectsBounds( target->GetPhysics()->GetAbsBounds() ) ) { show = true; break; } } } if ( !show ) { continue; } gameRenderWorld->DebugBounds( colorOrange, ent->GetPhysics()->GetAbsBounds() ); if ( viewTextBounds.IntersectsBounds( ent->GetPhysics()->GetAbsBounds() ) ) { gameRenderWorld->DrawText( ent->name.c_str(), ent->GetPhysics()->GetAbsBounds().GetCenter(), 0.1f, colorWhite, axis, 1 ); gameRenderWorld->DrawText( ent->GetEntityDefName(), ent->GetPhysics()->GetAbsBounds().GetCenter() + up, 0.1f, colorWhite, axis, 1 ); if ( ent->IsType( idTrigger::Type ) ) { func = static_cast<idTrigger *>( ent )->GetScriptFunction(); } else { func = NULL; } if ( func ) { gameRenderWorld->DrawText( va( "call script '%s'", func->Name() ), ent->GetPhysics()->GetAbsBounds().GetCenter() - up, 0.1f, colorWhite, axis, 1 ); } } for( i = 0; i < ent->targets.Num(); i++ ) { target = ent->targets[ i ].GetEntity(); if ( target ) { gameRenderWorld->DebugArrow( colorYellow, ent->GetPhysics()->GetAbsBounds().GetCenter(), target->GetPhysics()->GetOrigin(), 10, 0 ); gameRenderWorld->DebugBounds( colorGreen, box, target->GetPhysics()->GetOrigin() ); if ( viewTextBounds.IntersectsBounds( target->GetPhysics()->GetAbsBounds() ) ) { gameRenderWorld->DrawText( target->name.c_str(), target->GetPhysics()->GetAbsBounds().GetCenter(), 0.1f, colorWhite, axis, 1 ); } } } } } } /* ================ idTrigger::Enable ================ */ void idTrigger::Enable( void ) { GetPhysics()->SetContents( CONTENTS_TRIGGER ); GetPhysics()->EnableClip(); } /* ================ idTrigger::Disable ================ */ void idTrigger::Disable( void ) { // we may be relinked if we're bound to another object, so clear the contents as well GetPhysics()->SetContents( 0 ); GetPhysics()->DisableClip(); } /* ================ idTrigger::CallScript ================ */ void idTrigger::CallScript( idEntity* scriptEntity ) { // RAVEN BEGIN // abahr for( int ix = scriptFunctions.Num() - 1; ix >= 0; --ix ) { scriptFunctions[ix].InsertEntity( scriptEntity, 0 );//We could pass both the activator and self if wanted scriptFunctions[ix].CallFunc( &spawnArgs ); scriptFunctions[ix].RemoveIndex( 0 ); } // RAVEN END } /* ================ idTrigger::GetScriptFunction ================ */ const function_t *idTrigger::GetScriptFunction( void ) const { // RAVEN BEGIN // abahr: return (scriptFunctions.Num()) ? scriptFunctions[0].GetFunc() : NULL; // RAVEN END } /* ================ idTrigger::Save ================ */ void idTrigger::Save( idSaveGame *savefile ) const { // RAVEN BEGIN // abahr savefile->WriteInt( scriptFunctions.Num() ); for( int ix = scriptFunctions.Num() - 1; ix >= 0; --ix ) { scriptFunctions[ix].Save( savefile ); } // RAVEN END } /* ================ idTrigger::Restore ================ */ void idTrigger::Restore( idRestoreGame *savefile ) { // RAVEN BEGIN // abahr int numScripts = 0; savefile->ReadInt( numScripts ); scriptFunctions.SetNum( numScripts ); for( int ix = scriptFunctions.Num() - 1; ix >= 0; --ix ) { scriptFunctions[ix].Restore( savefile ); } // RAVEN END } /* ================ idTrigger::Event_Enable ================ */ void idTrigger::Event_Enable( void ) { Enable(); } /* ================ idTrigger::Event_Disable ================ */ void idTrigger::Event_Disable( void ) { Disable(); } /* ================ idTrigger::idTrigger ================ */ idTrigger::idTrigger() { // RAVEN BEGIN // abahr: scriptFunction init's itself //scriptFunction = NULL; // RAVEN END } /* ================ idTrigger::Spawn ================ */ void idTrigger::Spawn( void ) { GetPhysics()->SetContents( CONTENTS_TRIGGER ); // RAVEN BEGIN // abahr: scriptFunctions.SetGranularity( 1 ); for( const idKeyValue* kv = spawnArgs.MatchPrefix("call"); kv; kv = spawnArgs.MatchPrefix("call", kv) ) { if( !kv->GetValue() ) { continue; } rvScriptFuncUtility& utility = scriptFunctions.Alloc(); if( !utility.Init(kv->GetValue()) ) { gameLocal.Warning( "Trigger '%s' at (%s) trying to call an unknown function.", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } } // RAVEN END } /* =============================================================================== idTrigger_Multi =============================================================================== */ // RAVEN BEGIN // abahr: changed to 'E' to allow NULL entities const idEventDef EV_TriggerAction( "<triggerAction>", "E" ); // RAVEN END CLASS_DECLARATION( idTrigger, idTrigger_Multi ) EVENT( EV_FindTargets, idTrigger_Multi::Event_FindTargets ) EVENT( EV_Touch, idTrigger_Multi::Event_Touch ) EVENT( EV_SpectatorTouch, idTrigger_Multi::Event_SpectatorTouch ) EVENT( EV_Activate, idTrigger_Multi::Event_Trigger ) EVENT( EV_TriggerAction, idTrigger_Multi::Event_TriggerAction ) // RAVEN BEGIN // kfuller: respond to earthquakes EVENT( EV_Earthquake, idTrigger_Multi::Event_EarthQuake ) // RAVEN END END_CLASS /* ================ idTrigger_Multi::idTrigger_Multi ================ */ idTrigger_Multi::idTrigger_Multi( void ) { wait = 0.0f; random = 0.0f; delay = 0.0f; random_delay = 0.0f; nextTriggerTime = 0; removeItem = 0; touchClient = false; touchOther = false; touchVehicle = false; touchSpec = false; triggerFirst = false; triggerWithSelf = false; buyZoneTrigger = 0; controlZoneTrigger = 0; prevZoneController = TEAM_NONE; } /* ================ idTrigger_Multi::Save ================ */ void idTrigger_Multi::Save( idSaveGame *savefile ) const { savefile->WriteFloat( wait ); savefile->WriteFloat( random ); savefile->WriteFloat( delay ); savefile->WriteFloat( random_delay ); savefile->WriteInt( nextTriggerTime ); savefile->WriteString( requires ); savefile->WriteInt( removeItem ); savefile->WriteBool( touchClient ); savefile->WriteBool( touchOther ); savefile->WriteBool( touchVehicle ); savefile->WriteBool( triggerFirst ); savefile->WriteBool( triggerWithSelf ); } /* ================ idTrigger_Multi::Restore ================ */ void idTrigger_Multi::Restore( idRestoreGame *savefile ) { savefile->ReadFloat( wait ); savefile->ReadFloat( random ); savefile->ReadFloat( delay ); savefile->ReadFloat( random_delay ); savefile->ReadInt( nextTriggerTime ); savefile->ReadString( requires ); savefile->ReadInt( removeItem ); savefile->ReadBool( touchClient ); savefile->ReadBool( touchOther ); savefile->ReadBool( touchVehicle ); savefile->ReadBool( triggerFirst ); savefile->ReadBool( triggerWithSelf ); } /* ================ idTrigger_Multi::IsTeleporter Returns true if there is a single target, which is a teleporter ================ */ bool idTrigger_Multi::IsTeleporter( void ) const { if ( targets.Num() != 1 ) { return false; } return targets[ 0 ].GetEntity()->IsType( idPlayerStart::GetClassType() ); } /* ================ idTrigger_Multi::Spawn "wait" : Seconds between triggerings, 0.5 default, -1 = one time only. "call" : Script function to call when triggered "random" wait variance, default is 0 Variable sized repeatable trigger. Must be targeted at one or more entities. so, the basic time between firing is a random time between (wait - random) and (wait + random) ================ */ void idTrigger_Multi::Spawn( void ) { spawnArgs.GetFloat( "wait", "0.5", wait ); spawnArgs.GetFloat( "random", "0", random ); spawnArgs.GetFloat( "delay", "0", delay ); spawnArgs.GetFloat( "random_delay", "0", random_delay ); if ( random && ( random >= wait ) && ( wait >= 0 ) ) { random = wait - 1; gameLocal.Warning( "idTrigger_Multi '%s' at (%s) has random >= wait", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } if ( random_delay && ( random_delay >= delay ) && ( delay >= 0 ) ) { random_delay = delay - 1; gameLocal.Warning( "idTrigger_Multi '%s' at (%s) has random_delay >= delay", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } spawnArgs.GetString( "requires", "", requires ); spawnArgs.GetInt( "removeItem", "0", removeItem ); spawnArgs.GetBool( "triggerFirst", "0", triggerFirst ); spawnArgs.GetBool( "triggerWithSelf", "0", triggerWithSelf ); spawnArgs.GetInt( "buyZone", "0", buyZoneTrigger); spawnArgs.GetInt( "controlZone", "0", controlZoneTrigger); if ( buyZoneTrigger == -1 ) gameLocal.Warning( "trigger_buyzone '%s' at (%s) has no buyZone key set!", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); if ( controlZoneTrigger == -1 ) gameLocal.Warning( "trigger_controlzone '%s' at (%s) has no controlZone key set!", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); if ( spawnArgs.GetBool( "onlyVehicle" ) ) { touchVehicle = true; } else if ( spawnArgs.GetBool( "anyTouch" ) ) { touchClient = true; touchOther = true; } else if ( spawnArgs.GetBool( "noTouch" ) ) { touchClient = false; touchOther = false; } else if ( spawnArgs.GetBool( "noClient" ) ) { touchClient = false; touchOther = true; } else { touchClient = true; touchOther = false; } nextTriggerTime = 0; if ( spawnArgs.GetBool( "flashlight_trigger" ) ) { GetPhysics()->SetContents( CONTENTS_FLASHLIGHT_TRIGGER ); } else if ( spawnArgs.GetBool( "projectile_trigger" ) ) { GetPhysics()->SetContents( CONTENTS_TRIGGER | CONTENTS_PROJECTILE ); } else { GetPhysics()->SetContents( CONTENTS_TRIGGER ); } BecomeActive( TH_THINK ); } /* ================ idTrigger_Multi::FindTargets ================ */ void idTrigger_Multi::Event_FindTargets( void ) { FindTargets(); touchSpec = !spawnArgs.GetBool( "noSpec", IsTeleporter() ? "0" : "1" ); } /* ================ idTrigger_Multi::CheckFacing ================ */ bool idTrigger_Multi::CheckFacing( idEntity *activator ) { if ( spawnArgs.GetBool( "facing" ) ) { if ( !activator->IsType( idPlayer::GetClassType() ) ) { return true; } idPlayer *player = static_cast< idPlayer* >( activator ); // Unfortunately, the angle key rotates the trigger entity also. So I've added // an angleFacing key which is used instead when present, otherwise the code defaults // to the behaviour present prior to this change idVec3 tFacing = GetPhysics()->GetAxis()[0]; if ( spawnArgs.FindKey( "angleFacing" )) { idAngles angs(0,spawnArgs.GetFloat( "angleFacing", "0" ),0); tFacing = angs.ToForward(); } float dot = player->viewAngles.ToForward() * tFacing; float angle = RAD2DEG( idMath::ACos( dot ) ); if ( angle > spawnArgs.GetFloat( "angleLimit", "30" ) ) { return false; } } return true; } /* ================ idTrigger_Multi::TriggerAction ================ */ void idTrigger_Multi::TriggerAction( idEntity *activator ) { // RAVEN BEGIN // jdischler: added for Aweldon. The trigger, when activated, will call the listed func with all attached targets, then return. if ( spawnArgs.GetBool( "_callWithTargets", "0" )) { idEntity *ent; for( int i = 0; i < targets.Num(); i++ ) { ent = targets[ i ].GetEntity(); if ( !ent ) { continue; } CallScript( ent ); } return; } // RAVEN END ActivateTargets( triggerWithSelf ? this : activator ); CallScript( triggerWithSelf ? this : activator ); if ( wait >= 0 ) { nextTriggerTime = gameLocal.time + SEC2MS( wait + random * gameLocal.random.CRandomFloat() ); } else { // we can't just remove (this) here, because this is a touch function // called while looping through area links... nextTriggerTime = gameLocal.time + 1; PostEventMS( &EV_Remove, 0 ); } } /* ================ idTrigger_Multi::Event_TriggerAction ================ */ void idTrigger_Multi::Event_TriggerAction( idEntity *activator ) { TriggerAction( activator ); } /* ================ idTrigger_Multi::Event_Trigger the trigger was just activated activated should be the entity that originated the activation sequence (ie. the original target) activator should be set to the activator so it can be held through a delay so wait for the delay time before firing ================ */ void idTrigger_Multi::Event_Trigger( idEntity *activator ) { // RAVEN BEGIN // bdube: moved trigger first if ( triggerFirst ) { triggerFirst = false; return; } if ( nextTriggerTime > gameLocal.time ) { // can't retrigger until the wait is over return; } // see if this trigger requires an item if ( !gameLocal.RequirementMet( activator, requires, removeItem ) ) { return; } if ( !CheckFacing( activator ) ) { return; } // RAVEN END // don't allow it to trigger twice in a single frame nextTriggerTime = gameLocal.time + 1; if ( delay > 0 ) { // don't allow it to trigger again until our delay has passed nextTriggerTime += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() ); PostEventSec( &EV_TriggerAction, delay, activator ); } else { TriggerAction( activator ); } } void idTrigger_Multi::HandleControlZoneTrigger() { // This only does something in multiplayer with gameType == DeadZone if ( !gameLocal.isMultiplayer || gameLocal.gameType != GAME_DEADZONE ) return; const int TEAM_DEADLOCK = 2; int pCount = 0; int count = 0, controllingTeam = TEAM_NONE; count = playersInTrigger.Num(); for ( int i = 0; i<count; i++ ) { // No token? Ignore em! if ( spawnArgs.GetBool("requiresDeadZonePowerup", "1") && !playersInTrigger[i]->PowerUpActive( POWERUP_DEADZONE ) ) continue; if ( spawnArgs.GetBool("requiresDeadZonePowerup", "1") ) { pCount++; } int team = playersInTrigger[i]->team; if ( i == 0 ) controllingTeam = playersInTrigger[i]->team; // Assign the controlling team based on the first player // for zones that accept both. if ( team != controllingTeam ) { controllingTeam = TEAM_DEADLOCK; pCount = 0; } } if ( controllingTeam != controlZoneTrigger-1 && controlZoneTrigger != 3 ) { controllingTeam = TEAM_NONE; pCount = 0; } int situation = DZ_NONE; if ( controllingTeam != prevZoneController ) { if ( controllingTeam == TEAM_MARINE && prevZoneController == TEAM_NONE ) situation = DZ_MARINES_TAKEN; else if ( controllingTeam == TEAM_STROGG && prevZoneController == TEAM_NONE ) situation = DZ_STROGG_TAKEN; else if ( controllingTeam == TEAM_NONE && prevZoneController == TEAM_MARINE ) situation = DZ_MARINES_LOST; else if ( controllingTeam == TEAM_NONE && prevZoneController == TEAM_STROGG ) situation = DZ_STROGG_LOST; else if ( controllingTeam == TEAM_MARINE && prevZoneController == TEAM_STROGG ) situation = DZ_STROGG_TO_MARINE; else if ( controllingTeam == TEAM_STROGG && prevZoneController == TEAM_MARINE ) situation = DZ_MARINE_TO_STROGG; // DEADLOCK else if ( controllingTeam == TEAM_DEADLOCK && prevZoneController == TEAM_MARINE ) situation = DZ_MARINE_DEADLOCK; else if ( controllingTeam == TEAM_DEADLOCK && prevZoneController == TEAM_STROGG ) situation = DZ_STROGG_DEADLOCK; else if ( controllingTeam == TEAM_DEADLOCK && prevZoneController == TEAM_NONE ) situation = DZ_MARINE_DEADLOCK; // Unlikely case, just use this. else if ( controllingTeam == TEAM_MARINE && prevZoneController == TEAM_DEADLOCK ) situation = DZ_MARINE_REGAIN; else if ( controllingTeam == TEAM_STROGG && prevZoneController == TEAM_DEADLOCK ) situation = DZ_STROGG_REGAIN; else if ( controllingTeam == TEAM_NONE && prevZoneController == TEAM_DEADLOCK ) situation = DZ_MARINES_LOST; // Unlikely case, just use this. } /// Report individual credits for( int i = 0; i < count; i++ ) { idPlayer* player = playersInTrigger[i]; // No token? Ignore em! if ( spawnArgs.GetBool("requiresDeadZonePowerup", "1") && !player->PowerUpActive( POWERUP_DEADZONE ) ) continue; int team = player->team; if( team == controllingTeam ) { gameLocal.mpGame.ReportZoneControllingPlayer( player ); } } /// Report zone control to multiplayer game manager gameLocal.mpGame.ReportZoneController(controllingTeam, pCount, situation, this); playersInTrigger.Clear(); prevZoneController = controllingTeam; } /* ================ idTrigger_Multi::Think ================ */ void idTrigger_Multi::Think() { // Control zone handling if ( controlZoneTrigger > 0 ) HandleControlZoneTrigger(); } /* ================ idTrigger_Multi::Event_Touch ================ */ void idTrigger_Multi::Event_Touch( idEntity *other, trace_t *trace ) { if( triggerFirst ) { return; } // RAVEN BEGIN // jdischler: vehicle only trigger if ( touchVehicle ) { if ( !other->IsType(rvVehicle::GetClassType()) ) { return; } } else { // RAVEN BEGIN // jnewquist: Use accessor for static class type bool player = other->IsType( idPlayer::GetClassType() ); // RAVEN END if ( player ) { if ( !touchClient ) { return; } if ( static_cast< idPlayer * >( other )->spectating ) { Event_SpectatorTouch( other, trace ); return; } // Buy zone handling if ( buyZoneTrigger /*&& gameLocal.mpGame.mpGameState.gameState.currentState != 1*/ ) { idPlayer *p = static_cast< idPlayer * >( other ); if ( buyZoneTrigger-1 == p->team || buyZoneTrigger == 3) { p->inBuyZone = true; p->inBuyZonePrev = true; } } // Control zone handling if ( controlZoneTrigger > 0 ) { idPlayer *p = static_cast< idPlayer * >( other ); if ( p->PowerUpActive(POWERUP_DEADZONE) || !spawnArgs.GetBool("requiresDeadZonePowerup", "1") ) playersInTrigger.Append(p); } } else if ( !touchOther ) { return; } } if ( nextTriggerTime > gameLocal.time ) { // can't retrigger until the wait is over return; } // see if this trigger requires an item if ( !gameLocal.RequirementMet( other, requires, removeItem ) ) { return; } if ( !CheckFacing( other ) ) { return; } if ( spawnArgs.GetBool( "toggleTriggerFirst" ) ) { triggerFirst = true; } // RAVEN BEGIN // rjohnson: added block if ( developer.GetBool() && *spawnArgs.GetString ( "message" ) ) { gameLocal.DPrintf ( "Trigger: %s\n", spawnArgs.GetString ( "message" ) ); } // RAVEN END nextTriggerTime = gameLocal.time + 1; if ( delay > 0 ) { // don't allow it to trigger again until our delay has passed nextTriggerTime += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() ); PostEventSec( &EV_TriggerAction, delay, other ); } else { TriggerAction( other ); } } /* ================ idTrigger_Multi::Event_Touch ================ */ void idTrigger_Multi::Event_SpectatorTouch( idEntity *other, trace_t *trace ) { idPlayer *player; if ( !touchSpec ) { return; } if ( !other->IsType( idPlayer::GetClassType() ) ) { return; } player = static_cast< idPlayer* >( other ); if ( !player->spectating ) { return; } if ( player->lastSpectateTeleport > (gameLocal.time - 1000) ) { // can't retrigger until the wait is over return; } if ( !CheckFacing( other ) ) { return; } player->lastSpectateTeleport = gameLocal.time + 1; if ( delay > 0 ) { // don't allow it to trigger again until our delay has passed player->lastSpectateTeleport += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() ); PostEventSec( &EV_TriggerAction, delay, other ); } else { TriggerAction( other ); } } // RAVEN BEGIN // kfuller: void idTrigger_Multi::Event_EarthQuake(float requiresLOS) { // does this entity even care about earthquakes? float quakeChance = 0; if (!spawnArgs.GetFloat("quakeChance", "0", quakeChance)) { return; } if (rvRandom::flrand(0, 1.0f) > quakeChance) { // failed its activation roll return; } if (requiresLOS) { // if the player doesn't have line of sight to this fx, don't do anything trace_t trace; idPlayer *player = gameLocal.GetLocalPlayer(); idVec3 viewOrigin; idMat3 viewAxis; player->GetViewPos(viewOrigin, viewAxis); // RAVEN BEGIN // ddynerman: multiple clip worlds gameLocal.TracePoint( this, trace, viewOrigin, GetPhysics()->GetOrigin(), MASK_OPAQUE, player ); // RAVEN END if (trace.fraction < 1.0f) { // something blocked LOS return; } } // activate this effect now TriggerAction(gameLocal.entities[ENTITYNUM_WORLD]); } // RAVEN END /* =============================================================================== idTrigger_EntityName =============================================================================== */ CLASS_DECLARATION( idTrigger, idTrigger_EntityName ) EVENT( EV_Touch, idTrigger_EntityName::Event_Touch ) EVENT( EV_Activate, idTrigger_EntityName::Event_Trigger ) EVENT( EV_TriggerAction, idTrigger_EntityName::Event_TriggerAction ) END_CLASS /* ================ idTrigger_EntityName::idTrigger_EntityName ================ */ idTrigger_EntityName::idTrigger_EntityName( void ) { wait = 0.0f; random = 0.0f; delay = 0.0f; random_delay = 0.0f; nextTriggerTime = 0; triggerFirst = false; } /* ================ idTrigger_EntityName::Save ================ */ void idTrigger_EntityName::Save( idSaveGame *savefile ) const { savefile->WriteFloat( wait ); savefile->WriteFloat( random ); savefile->WriteFloat( delay ); savefile->WriteFloat( random_delay ); savefile->WriteInt( nextTriggerTime ); savefile->WriteBool( triggerFirst ); savefile->WriteString( entityName ); } /* ================ idTrigger_EntityName::Restore ================ */ void idTrigger_EntityName::Restore( idRestoreGame *savefile ) { savefile->ReadFloat( wait ); savefile->ReadFloat( random ); savefile->ReadFloat( delay ); savefile->ReadFloat( random_delay ); savefile->ReadInt( nextTriggerTime ); savefile->ReadBool( triggerFirst ); savefile->ReadString( entityName ); } /* ================ idTrigger_EntityName::Spawn ================ */ void idTrigger_EntityName::Spawn( void ) { spawnArgs.GetFloat( "wait", "0.5", wait ); spawnArgs.GetFloat( "random", "0", random ); spawnArgs.GetFloat( "delay", "0", delay ); spawnArgs.GetFloat( "random_delay", "0", random_delay ); if ( random && ( random >= wait ) && ( wait >= 0 ) ) { random = wait - 1; gameLocal.Warning( "idTrigger_EntityName '%s' at (%s) has random >= wait", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } if ( random_delay && ( random_delay >= delay ) && ( delay >= 0 ) ) { random_delay = delay - 1; gameLocal.Warning( "idTrigger_EntityName '%s' at (%s) has random_delay >= delay", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } spawnArgs.GetBool( "triggerFirst", "0", triggerFirst ); entityName = spawnArgs.GetString( "entityname" ); if ( !entityName.Length() ) { gameLocal.Error( "idTrigger_EntityName '%s' at (%s) doesn't have 'entityname' key specified", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } nextTriggerTime = 0; if ( !spawnArgs.GetBool( "noTouch" ) ) { GetPhysics()->SetContents( CONTENTS_TRIGGER ); } } /* ================ idTrigger_EntityName::TriggerAction ================ */ void idTrigger_EntityName::TriggerAction( idEntity *activator ) { // RAVEN BEGIN // abahr: want same functionality as trigger_multi. Need to move this code into these two function calls idEntity* scriptEntity = spawnArgs.GetBool("triggerWithSelf") ? this : activator; ActivateTargets( scriptEntity ); CallScript( scriptEntity ); // RAVEN END if ( wait >= 0 ) { nextTriggerTime = gameLocal.time + SEC2MS( wait + random * gameLocal.random.CRandomFloat() ); } else { // we can't just remove (this) here, because this is a touch function // called while looping through area links... nextTriggerTime = gameLocal.time + 1; PostEventMS( &EV_Remove, 0 ); } } /* ================ idTrigger_EntityName::Event_TriggerAction ================ */ void idTrigger_EntityName::Event_TriggerAction( idEntity *activator ) { TriggerAction( activator ); } /* ================ idTrigger_EntityName::Event_Trigger the trigger was just activated activated should be the entity that originated the activation sequence (ie. the original target) activator should be set to the activator so it can be held through a delay so wait for the delay time before firing ================ */ void idTrigger_EntityName::Event_Trigger( idEntity *activator ) { if ( nextTriggerTime > gameLocal.time ) { // can't retrigger until the wait is over return; } // RAVEN BEGIN // abahr: so we can exclude an entity by name if( !activator ) { return; } if( spawnArgs.GetBool("excludeEntityName") && activator->name == entityName ) { return; } if( !spawnArgs.GetBool("excludeEntityName") && activator->name != entityName ) { return; } // RAVEN END if ( triggerFirst ) { triggerFirst = false; return; } // don't allow it to trigger twice in a single frame nextTriggerTime = gameLocal.time + 1; if ( delay > 0 ) { // don't allow it to trigger again until our delay has passed nextTriggerTime += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() ); PostEventSec( &EV_TriggerAction, delay, activator ); } else { TriggerAction( activator ); } } /* ================ idTrigger_EntityName::Event_Touch ================ */ void idTrigger_EntityName::Event_Touch( idEntity *other, trace_t *trace ) { if( triggerFirst ) { return; } if ( nextTriggerTime > gameLocal.time ) { // can't retrigger until the wait is over return; } // RAVEN BEGIN // abahr: so we can exclude an entity by name if( !other ) { return; } if( spawnArgs.GetBool("excludeEntityName") && other->name == entityName ) { return; } if( !spawnArgs.GetBool("excludeEntityName") && other->name != entityName ) { return; } // RAVEN END nextTriggerTime = gameLocal.time + 1; if ( delay > 0 ) { // don't allow it to trigger again until our delay has passed nextTriggerTime += SEC2MS( delay + random_delay * gameLocal.random.CRandomFloat() ); PostEventSec( &EV_TriggerAction, delay, other ); } else { TriggerAction( other ); } } /* =============================================================================== idTrigger_Timer =============================================================================== */ const idEventDef EV_Timer( "<timer>", NULL ); CLASS_DECLARATION( idTrigger, idTrigger_Timer ) EVENT( EV_Timer, idTrigger_Timer::Event_Timer ) EVENT( EV_Activate, idTrigger_Timer::Event_Use ) END_CLASS /* ================ idTrigger_Timer::idTrigger_Timer ================ */ idTrigger_Timer::idTrigger_Timer( void ) { random = 0.0f; wait = 0.0f; on = false; delay = 0.0f; } /* ================ idTrigger_Timer::Save ================ */ void idTrigger_Timer::Save( idSaveGame *savefile ) const { savefile->WriteFloat( random ); savefile->WriteFloat( wait ); savefile->WriteBool( on ); savefile->WriteFloat( delay ); savefile->WriteString( onName ); savefile->WriteString( offName ); } /* ================ idTrigger_Timer::Restore ================ */ void idTrigger_Timer::Restore( idRestoreGame *savefile ) { savefile->ReadFloat( random ); savefile->ReadFloat( wait ); savefile->ReadBool( on ); savefile->ReadFloat( delay ); savefile->ReadString( onName ); savefile->ReadString( offName ); } /* ================ idTrigger_Timer::Spawn Repeatedly fires its targets. Can be turned on or off by using. ================ */ void idTrigger_Timer::Spawn( void ) { spawnArgs.GetFloat( "random", "1", random ); spawnArgs.GetFloat( "wait", "1", wait ); spawnArgs.GetBool( "start_on", "0", on ); spawnArgs.GetFloat( "delay", "0", delay ); onName = spawnArgs.GetString( "onName" ); offName = spawnArgs.GetString( "offName" ); if ( random >= wait && wait >= 0 ) { random = wait - 0.001; gameLocal.Warning( "idTrigger_Timer '%s' at (%s) has random >= wait", name.c_str(), GetPhysics()->GetOrigin().ToString(0) ); } if ( on ) { PostEventSec( &EV_Timer, delay ); } } /* ================ idTrigger_Timer::Enable ================ */ void idTrigger_Timer::Enable( void ) { // if off, turn it on if ( !on ) { on = true; PostEventSec( &EV_Timer, delay ); } } /* ================ idTrigger_Timer::Disable ================ */ void idTrigger_Timer::Disable( void ) { // if on, turn it off if ( on ) { on = false; CancelEvents( &EV_Timer ); } } /* ================ idTrigger_Timer::Event_Timer ================ */ void idTrigger_Timer::Event_Timer( void ) { ActivateTargets( this ); // set time before next firing if ( wait >= 0.0f ) { PostEventSec( &EV_Timer, wait + gameLocal.random.CRandomFloat() * random ); } } /* ================ idTrigger_Timer::Event_Use ================ */ void idTrigger_Timer::Event_Use( idEntity *activator ) { // if on, turn it off if ( on ) { if ( offName.Length() && offName.Icmp( activator->GetName() ) ) { return; } on = false; CancelEvents( &EV_Timer ); } else { // turn it on if ( onName.Length() && onName.Icmp( activator->GetName() ) ) { return; } on = true; PostEventSec( &EV_Timer, delay ); } } /* =============================================================================== idTrigger_Count =============================================================================== */ CLASS_DECLARATION( idTrigger, idTrigger_Count ) EVENT( EV_Activate, idTrigger_Count::Event_Trigger ) EVENT( EV_TriggerAction, idTrigger_Count::Event_TriggerAction ) END_CLASS /* ================ idTrigger_Count::idTrigger_Count ================ */ idTrigger_Count::idTrigger_Count( void ) { goal = 0; count = 0; delay = 0.0f; } /* ================ idTrigger_Count::Save ================ */ void idTrigger_Count::Save( idSaveGame *savefile ) const { savefile->WriteInt( goal ); savefile->WriteInt( count ); savefile->WriteFloat( delay ); } /* ================ idTrigger_Count::Restore ================ */ void idTrigger_Count::Restore( idRestoreGame *savefile ) { savefile->ReadInt( goal ); savefile->ReadInt( count ); savefile->ReadFloat( delay ); } /* ================ idTrigger_Count::Spawn ================ */ void idTrigger_Count::Spawn( void ) { spawnArgs.GetInt( "count", "1", goal ); spawnArgs.GetFloat( "delay", "0", delay ); count = 0; } /* ================ idTrigger_Count::Event_Trigger ================ */ void idTrigger_Count::Event_Trigger( idEntity *activator ) { // goal of -1 means trigger has been exhausted if (goal >= 0) { count++; if ( count >= goal ) { if (spawnArgs.GetBool("repeat")) { count = 0; } else { goal = -1; } PostEventSec( &EV_TriggerAction, delay, activator ); } } } /* ================ idTrigger_Count::Event_TriggerAction ================ */ void idTrigger_Count::Event_TriggerAction( idEntity *activator ) { ActivateTargets( activator ); CallScript( activator ); if ( goal == -1 ) { PostEventMS( &EV_Remove, 0 ); } } /* =============================================================================== idTrigger_Hurt =============================================================================== */ CLASS_DECLARATION( idTrigger, idTrigger_Hurt ) EVENT( EV_Touch, idTrigger_Hurt::Event_Touch ) EVENT( EV_Activate, idTrigger_Hurt::Event_Toggle ) END_CLASS /* ================ idTrigger_Hurt::idTrigger_Hurt ================ */ idTrigger_Hurt::idTrigger_Hurt( void ) { on = false; delay = 0.0f; nextTime = 0; } /* ================ idTrigger_Hurt::Save ================ */ void idTrigger_Hurt::Save( idSaveGame *savefile ) const { savefile->WriteBool( on ); savefile->WriteFloat( delay ); savefile->WriteInt( nextTime ); // RAVEN BEGIN // bdube: playeronly flag savefile->WriteBool ( playerOnly ); // RAVEN END } /* ================ idTrigger_Hurt::Restore ================ */ void idTrigger_Hurt::Restore( idRestoreGame *savefile ) { savefile->ReadBool( on ); savefile->ReadFloat( delay ); savefile->ReadInt( nextTime ); // RAVEN BEGIN // bdube: playeronly flag savefile->ReadBool( playerOnly ); // RAVEN END } /* ================ idTrigger_Hurt::Spawn Damages activator Can be turned on or off by using. ================ */ void idTrigger_Hurt::Spawn( void ) { spawnArgs.GetBool( "on", "1", on ); spawnArgs.GetFloat( "delay", "1.0", delay ); // RAVEN BEGIN // kfuller: playeronly flag spawnArgs.GetBool( "playerOnly", "0", playerOnly ); // RAVEN END nextTime = gameLocal.time; Enable(); } /* ================ idTrigger_Hurt::Event_Touch ================ */ void idTrigger_Hurt::Event_Touch( idEntity *other, trace_t *trace ) { const char *damage; // RAVEN BEGIN // kfuller: playeronly flag // jnewquist: Use accessor for static class type if ( playerOnly && !other->IsType( idPlayer::GetClassType() ) ) { return; } // RAVEN END if ( on && other && gameLocal.time >= nextTime ) { damage = spawnArgs.GetString( "def_damage", "damage_painTrigger" ); other->Damage( this, NULL, vec3_origin, damage, 1.0f, INVALID_JOINT ); ActivateTargets( other ); CallScript( other ); nextTime = gameLocal.time + SEC2MS( delay ); } } /* ================ idTrigger_Hurt::Event_Toggle ================ */ void idTrigger_Hurt::Event_Toggle( idEntity *activator ) { on = !on; } /* =============================================================================== idTrigger_Fade =============================================================================== */ CLASS_DECLARATION( idTrigger, idTrigger_Fade ) EVENT( EV_Activate, idTrigger_Fade::Event_Trigger ) END_CLASS /* ================ idTrigger_Fade::Event_Trigger ================ */ void idTrigger_Fade::Event_Trigger( idEntity *activator ) { idVec4 fadeColor; int fadeTime; idPlayer *player; player = gameLocal.GetLocalPlayer(); if ( player ) { fadeColor = spawnArgs.GetVec4( "fadeColor", "0, 0, 0, 1" ); fadeTime = SEC2MS( spawnArgs.GetFloat( "fadeTime", "0.5" ) ); player->playerView.Fade( fadeColor, fadeTime ); PostEventMS( &EV_ActivateTargets, fadeTime, activator ); } } /* =============================================================================== idTrigger_Touch =============================================================================== */ CLASS_DECLARATION( idTrigger, idTrigger_Touch ) EVENT( EV_Activate, idTrigger_Touch::Event_Trigger ) END_CLASS /* ================ idTrigger_Touch::idTrigger_Touch ================ */ idTrigger_Touch::idTrigger_Touch( void ) { clipModel = NULL; } /* ================ idTrigger_Touch::idTrigger_Touch ================ */ idTrigger_Touch::~idTrigger_Touch( ) { if ( clipModel ) { delete clipModel; clipModel = 0; } } /* ================ idTrigger_Touch::Spawn ================ */ void idTrigger_Touch::Spawn( void ) { // get the clip model // RAVEN BEGIN // mwhitlock: Dynamic memory consolidation RV_PUSH_HEAP_MEM(this); // RAVEN END clipModel = new idClipModel( GetPhysics()->GetClipModel() ); // RAVEN BEGIN // mwhitlock: Dynamic memory consolidation RV_POP_HEAP(); // RAVEN END // remove the collision model from the physics object GetPhysics()->SetClipModel( NULL, 1.0f ); if ( spawnArgs.GetBool( "start_on" ) ) { BecomeActive( TH_THINK ); } filterTeam = -1; idStr filterTeamStr = spawnArgs.GetString( "filterTeam" ); if ( filterTeamStr.Size() ) { if ( !idStr::Icmp( "marine", filterTeamStr.c_str() ) ) { filterTeam = AITEAM_MARINE; } else if ( !idStr::Icmp( "strogg", filterTeamStr.c_str() ) ) { filterTeam = AITEAM_STROGG; } } } /* ================ idTrigger_Touch::Save ================ */ void idTrigger_Touch::Save( idSaveGame *savefile ) { savefile->WriteClipModel( clipModel ); savefile->WriteInt( filterTeam ); } /* ================ idTrigger_Touch::Restore ================ */ void idTrigger_Touch::Restore( idRestoreGame *savefile ) { savefile->ReadClipModel( clipModel ); savefile->ReadInt( filterTeam ); } /* ================ idTrigger_Touch::TouchEntities ================ */ void idTrigger_Touch::TouchEntities( void ) { int numClipModels, i; idBounds bounds; idClipModel *cm, *clipModelList[ MAX_GENTITIES ]; // RAVEN BEGIN // abahr: now scriptFunction list if ( clipModel == NULL || !scriptFunctions.Num() ) { // RAVEN END return; } bounds.FromTransformedBounds( clipModel->GetBounds(), GetBindMaster()!=NULL?GetPhysics()->GetOrigin():clipModel->GetOrigin(), GetBindMaster()!=NULL?GetPhysics()->GetAxis():clipModel->GetAxis() ); // RAVEN BEGIN // MCG: filterTeam if ( filterTeam != -1 ) { idActor* actor; // Iterate through the filter team for( actor = aiManager.GetAllyTeam ( (aiTeam_t)filterTeam ); actor; actor = actor->teamNode.Next() ) { // Skip hidden actors and actors that can't be targeted if( actor->fl.notarget || actor->fl.isDormant || ( actor->IsHidden ( ) && !actor->IsInVehicle() ) ) { continue; } if ( !bounds.IntersectsBounds ( actor->GetPhysics()->GetAbsBounds ( ) ) ) { continue; } cm = actor->GetPhysics()->GetClipModel(); if ( !cm || !cm->IsTraceModel() ) { continue; } if ( !gameLocal.ContentsModel( this, cm->GetOrigin(), cm, cm->GetAxis(), -1, clipModel->GetCollisionModel(), GetBindMaster()!=NULL?GetPhysics()->GetOrigin():clipModel->GetOrigin(), GetBindMaster()!=NULL?GetPhysics()->GetAxis():clipModel->GetAxis() ) ) { continue; } ActivateTargets( (idEntity*)actor ); CallScript( (idEntity*)actor ); } return; } // ddynerman: multiple clip worlds numClipModels = gameLocal.ClipModelsTouchingBounds( this, bounds, -1, clipModelList, MAX_GENTITIES ); // RAVEN END for ( i = 0; i < numClipModels; i++ ) { cm = clipModelList[ i ]; if ( !cm->IsTraceModel() ) { continue; } idEntity *entity = cm->GetEntity(); if ( !entity ) { continue; } // RAVEN BEGIN // ddynerman: multiple clip worlds if ( !gameLocal.ContentsModel( this, cm->GetOrigin(), cm, cm->GetAxis(), -1, clipModel->GetCollisionModel(), clipModel->GetOrigin(), clipModel->GetAxis() ) ) { // RAVEN END continue; } ActivateTargets( entity ); // RAVEN BEGIN // abahr: changed to be compatible with new script function utility CallScript( entity ); // RAVEN END } } /* ================ idTrigger_Touch::Think ================ */ void idTrigger_Touch::Think( void ) { if ( thinkFlags & TH_THINK ) { TouchEntities(); } idEntity::Think(); } /* ================ idTrigger_Touch::Event_Trigger ================ */ void idTrigger_Touch::Event_Trigger( idEntity *activator ) { if ( thinkFlags & TH_THINK ) { BecomeInactive( TH_THINK ); } else { BecomeActive( TH_THINK ); } } /* ================ idTrigger_Touch::Enable ================ */ void idTrigger_Touch::Enable( void ) { BecomeActive( TH_THINK ); } /* ================ idTrigger_Touch::Disable ================ */ void idTrigger_Touch::Disable( void ) { BecomeInactive( TH_THINK ); }
#pragma once #ifndef LUCE_H #define LUCE_H #include "Posizione.h" class Luce { public: Luce(); Posizione getPosizione(); void setPosizione(Posizione pos); void move(double x, double y, double z); void disegnaLuce(); private: Posizione posizione; }; #endif
#include <iostream> using namespace std; int d[1001]; int dp(int x) { if (x == 1) return 1; if (x == 2) return 3; if (d[x] != 0) return d[x]; return d[x] = (dp(x - 1) + 2*dp(x-2)) % 10007; } int main(void) { int x; cin >> x; cout << dp(x) << endl; }
#pragma once #include "HUDView.h" #include "LevelModel.h" #include "LevelView.h" #include "PlayerController.h" #include "StaticObjectController.h" #include "DynamicObjectController.h" #include "TmxParser/Tmx.h" class LevelController { public: enum LevelProgressState { LEVEL_IN_PROGRESS, LEVEL_FINISHED, LEVEL_GAME_OVER }; static const float m_TileSizeInMeters; public: LevelController(); ~LevelController(); void loadNewLevel(Tmx::Map* map); void draw(); void update(const float elapsedTime); LevelProgressState getState(){return m_state;} private: void loadMap(Tmx::Map* map); void computeLevelLogic(); void addPlayer(const Vector4& playerInitialPosition); int addEnemy(const Vector4& enemyPosition, std::string enemyName); void removeEnemy(int key); int addStaticObject(const Vector4& position, std::string name); void removeStaticObject(int key); int addDynamicObject(); void removeDynamicObject(int key); private: HUDView m_hudView; LevelModel m_levelModel; LevelView m_levelView; LevelProgressState m_state; PlayerController* m_playerController; std::map<int, AvatarController*> m_enemyControllers; int m_nextNewEnemyId; std::map<int, StaticObjectController*> m_staticObjectControllers; std::map<int, DynamicObjectController*> m_dynamicObjectControllers; int m_nextNewStaticObjectId; int m_nextNewDynamicObjectId; int m_toggleTime; };
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back ll n,x; int main() { cin >> n >> x; vector<ll> a(n,0); rep(i,n) { cin >> a[i]; } sort(a.begin(), a.end()); int cnt = 0, ans = 0; while (x > 0 && cnt < n) { if (a[cnt] <= x) { if (cnt == n-1) { if (a[cnt] == x) { ans++; } } else { ans++; x -= a[cnt]; } } cnt++; } cout << ans << endl; }
/*! @file LogVol_DynodesArray.hh @brief Defines mandatory user class LogVol_DynodesArray. @date August, 2015 @author Flechas (D. C. Flechas dcflechasg@unal.edu.co) @version 1.9 In this header file, the 'physical' setup is defined: materials, geometries and positions. This class defines the experimental hall used in the toolkit. */ /* no-geant4 classes*/ #include "LogVol_DynodesArray.hh" /* units and constants */ #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4PhysicalConstants.hh" /* geometric objects */ #include "G4Box.hh" #include "G4Tubs.hh" #include "G4Polycone.hh" #include "G4UnionSolid.hh" /* logic and physical volume */ #include "G4LogicalVolume.hh" #include "G4PVPlacement.hh" #include "G4PVReplica.hh" /* geant4 materials */ #include "G4NistManager.hh" #include "G4Material.hh" /* visualization */ #include "G4VisAttributes.hh" LogVol_DynodesArray:: LogVol_DynodesArray(G4String fname, G4double frad, G4double flen, G4int fnum): G4LogicalVolume(new G4Box(fname+"_Sol",10*mm, 10*mm, 10*mm),(G4NistManager::Instance())->FindOrBuildMaterial("G4_C"),fname,0,0,0) { /* set variables */ SetName(fname); SetHeight(frad); SetLength(flen); SetThickness(0.05*cm); if(fnum<12) SetNumOfDynodes(fnum); else { G4cout<<"Too many dynodes. Set number of dynodes to 11"<<G4endl; SetNumOfDynodes(11); } Material=(G4NistManager::Instance())->FindOrBuildMaterial("G4_C"); /* Construct solid volume */ ConstructSolidVol_DynodesArray(); /* Visualization */ // this->SetVisAttributes(G4VisAttributes::GetInvisible());//never show G4VisAttributes* red_vis = new G4VisAttributes(true,G4Colour::Red()); red_vis->SetForceWireframe(false); red_vis->SetForceSolid(false); this->SetVisAttributes(G4VisAttributes::GetInvisible()); } LogVol_DynodesArray::~LogVol_DynodesArray() {} void LogVol_DynodesArray::ConstructSolidVol_DynodesArray(void) { ///**** Geaneral solid: Shielding container ****/// DynodesArray_solid = new G4Box(Name+"dynArray_box",Height/2.0,Height/2.0,Length/2.); /*** Main trick here: Set the new solid volume ***/ SetSolidVol_DynodesArray(); //*** Dynode ***// G4Box * solid_dynode = new G4Box(Name+"dynode_Sol",Height/2.0, (Height*std::sqrt(2))/4.0,Thickness/2.); G4LogicalVolume* logic_dynode = new G4LogicalVolume(solid_dynode,Material, Name+"Dynode_Log",0,0,0); G4VisAttributes* blue_vis = new G4VisAttributes(true,G4Colour::Blue()); logic_dynode->SetVisAttributes(blue_vis); G4RotationMatrix* Rotation = new G4RotationMatrix(); Rotation->rotateX(M_PI/4*rad); G4VPhysicalVolume* dynodesArray_phys; if(NumberOfDynodes>1) dynodesArray_phys = new G4PVReplica( Name+"Dynode_Phy", logic_dynode, this, kZAxis, NumberOfDynodes, Length/NumberOfDynodes);//Thickness); else dynodesArray_phys = new G4PVPlacement(Rotation, G4ThreeVector(0.,0.,-Length/2.+Thickness/2.0), logic_dynode, Name+"Dynode_Phy", this, false, 0, true); } void LogVol_DynodesArray::SetSolidVol_DynodesArray(void) { /*** Main trick here: Set the new solid volume ***/ if(DynodesArray_solid) this->SetSolid(DynodesArray_solid); }
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> P; typedef long long ll; int main(){ string s; cin >> s; int ans = 0; int x = 0; int y = 0; for(int i=0; i<s.size();i ++){ if(i%2 == 0 && s[i] == '0') x++; else if(i%2 == 1 && s[i] == '1') y++; } int len = s.size(); ans = min(x+y, len - x - y); cout << ans << endl; return 0; }
#include <iostream> #include "core/types.h" #include "core/aabbtree.h" #include "core/mesh.h" #include "core/pfm.h" #include "graphics/rendergl/glutil.h" using namespace std; const uint32_t g_screenWidth = 1024; const uint32_t g_screenHeight = 512; Point3 g_camPos; Rotation g_camDir; PfmImage g_probe; uint32_t g_buffer[g_screenWidth*g_screenHeight]; Colour SampleProbe(const Vector3& dir, const PfmImage& image) { // convert world space dir to probe space float c = (1.0f / kPi) * acosf(dir.z)/sqrt(dir.x*dir.x + dir.y*dir.y); uint32_t px = (0.5f + 0.5f*(dir.x*c))*g_probe.m_width; uint32_t py = (0.5f + 0.5f*(-dir.y*c))*g_probe.m_height; float r = g_probe.m_data[py*g_probe.m_width*3 + (px*3)+0]; float g = g_probe.m_data[py*g_probe.m_width*3 + (px*3)+1]; float b = g_probe.m_data[py*g_probe.m_width*3 + (px*3)+2]; return Colour(r, g, b, 1.0f); } void Init() { //const char* probeFile = "../../probes/grace_probe.pfm.pfm"; const char* probeFile = "../../probes/uffizi_probe.pfm.pfm"; if (!PfmLoad(probeFile, g_probe)) { cout << "Couldn't load probe\n" << endl; exit(-1); } } void GLUTUpdate() { GlVerify(glEnable(GL_CULL_FACE)); GlVerify(glEnable(GL_DEPTH_TEST)); GlVerify(glDisable(GL_LIGHTING)); GlVerify(glDisable(GL_BLEND)); GlVerify(glViewport(0, 0, g_screenWidth, g_screenHeight)); GlVerify(glClearColor(0.5f, 0.5f, 0.5f, 1.0f)); GlVerify(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); Matrix44 rasterToScreen( 2.0f / g_screenWidth, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f / g_screenHeight, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f); float f = tanf(DegToRad(45.0f)*0.5f); float aspect = float(g_screenWidth) / g_screenHeight; Matrix44 screenToCamera(f*aspect, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix44 cameraToWorld = TransformMatrix(g_camDir, Point3(0.0f)); Matrix44 rasterToWorld = cameraToWorld*screenToCamera*rasterToScreen; for (uint32_t y=0; y < g_screenHeight; ++y) { for (uint32_t x=0; x < g_screenWidth; ++x) { Point3 p = rasterToWorld * Point3(float(x) + 0.5f, float(y) + 0.5f, 0.0f); Vector3 dir = Normalize(p-Point3(0.0f)); g_buffer[y*g_screenWidth + x] = ColourToRGBA8(LinearToSrgb(ToneMap(SampleProbe(dir, g_probe)))); } } GlVerify(glDrawPixels(g_screenWidth, g_screenHeight, GL_RGBA, GL_UNSIGNED_BYTE, g_buffer)); // flip GlVerify(glutSwapBuffers()); } void GLUTReshape(int width, int height) { } void GLUTArrowKeys(int key, int x, int y) { } void GLUTArrowKeysUp(int key, int x, int y) { } void GLUTKeyboardDown(unsigned char key, int x, int y) { switch (key) { case 'e': { break; } case 27: exit(0); break; }; } void GLUTKeyboardUp(unsigned char key, int x, int y) { switch (key) { case 'e': { break; } case 'd': { break; } case ' ': { break; } } } static int lastx; static int lasty; void GLUTMouseFunc(int b, int state, int x, int y) { switch (state) { case GLUT_UP: { lastx = x; lasty = y; } case GLUT_DOWN: { lastx = x; lasty = y; } } } void GLUTMotionFunc(int x, int y) { int dx = x-lastx; int dy = y-lasty; const float sensitivity = 0.1f; g_camDir.yaw -= dx*sensitivity; g_camDir.roll += dy*sensitivity; lastx = x; lasty = y; } void GLUTPassiveMotionFunc(int x, int y) { int dx = x-lastx; int dy = y-lasty; lastx = x; lasty = y; } int main(int argc, char* argv[]) { // init gl glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(g_screenWidth, g_screenHeight); glutCreateWindow("ProbeView"); glutPositionWindow(350, 100); #if WIN32 glewInit(); #endif Init(); glutMouseFunc(GLUTMouseFunc); glutReshapeFunc(GLUTReshape); glutDisplayFunc(GLUTUpdate); glutKeyboardFunc(GLUTKeyboardDown); glutKeyboardUpFunc(GLUTKeyboardUp); glutIdleFunc(GLUTUpdate); glutSpecialFunc(GLUTArrowKeys); glutSpecialUpFunc(GLUTArrowKeysUp); glutMotionFunc(GLUTMotionFunc); glutPassiveMotionFunc(GLUTPassiveMotionFunc); glutMainLoop(); }
#include "stdafx.h" #include "Person.h" #include <string> #include <iostream> Person::Person(char* szName, int age) { memset((void*)(this->szName), 0, sizeof(this->szName)); strcpy(this->szName, szName); this->age = age; std::cout << "Person constructor." << std::endl; } Person::~Person() { } Student::Student(char* szName, int age, char* szSchool) : Person(szName, age) { memset((void*)(this->szSchool), 0, sizeof(this->szSchool)); strcpy(this->szSchool, szSchool); std::cout << "Student constructor." << std::endl; } Student::~Student() { } Employee::Employee(char* szName, int age, char* szEmployer) : Person(szName, age) { memset((void*)(this->szEmployer), 0, sizeof(this->szEmployer)); strcpy(this->szEmployer, szEmployer); std::cout << "Employee constructor." << std::endl; } Employee::~Employee() { } PartTimeStudent::PartTimeStudent(char* szName, int age, char* szSchool, char* szEmployer) : Person(szName, age), Student(szName, age, szSchool), Employee(szName, age, szEmployer) { std::cout << "Part-time student constructor." << std::endl; } PartTimeStudent::~PartTimeStudent() { }
/** * Copyright (c) 2023, 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. * * @file auto_fd.cc */ #include "auto_fd.hh" #include <fcntl.h> #include <unistd.h> #include "lnav_log.hh" int auto_fd::pipe(auto_fd* af) { int retval, fd[2]; require(af != nullptr); if ((retval = ::pipe(fd)) == 0) { af[0] = fd[0]; af[1] = fd[1]; } return retval; } auto_fd auto_fd::dup_of(int fd) { if (fd == -1) { return auto_fd{}; } auto new_fd = ::dup(fd); if (new_fd == -1) { throw std::bad_alloc(); } return auto_fd(new_fd); } auto_fd::auto_fd(int fd) : af_fd(fd) { require(fd >= -1); } auto_fd::auto_fd(auto_fd&& af) noexcept : af_fd(af.release()) {} auto_fd auto_fd::dup() const { int new_fd; if (this->af_fd == -1 || (new_fd = ::dup(this->af_fd)) == -1) { throw std::bad_alloc(); } return auto_fd{new_fd}; } auto_fd::~auto_fd() { this->reset(); } void auto_fd::reset(int fd) { require(fd >= -1); if (this->af_fd != fd) { if (this->af_fd != -1) { switch (this->af_fd) { case STDIN_FILENO: case STDOUT_FILENO: case STDERR_FILENO: break; default: close(this->af_fd); break; } } this->af_fd = fd; } } void auto_fd::close_on_exec() const { if (this->af_fd == -1) { return; } log_perror(fcntl(this->af_fd, F_SETFD, FD_CLOEXEC)); } void auto_fd::non_blocking() const { auto fl = fcntl(this->af_fd, F_GETFL, 0); if (fl < 0) { return; } log_perror(fcntl(this->af_fd, F_SETFL, fl | O_NONBLOCK)); } auto_fd& auto_fd::operator=(int fd) { require(fd >= -1); this->reset(fd); return *this; } Result<void, std::string> auto_fd::write_fully(string_fragment sf) { while (!sf.empty()) { auto rc = write(this->af_fd, sf.data(), sf.length()); if (rc < 0) { return Err( fmt::format(FMT_STRING("failed to write {} bytes to FD {}"), sf.length(), this->af_fd)); } sf = sf.substr(rc); } return Ok(); } Result<auto_pipe, std::string> auto_pipe::for_child_fd(int child_fd) { auto_pipe retval(child_fd); if (retval.open() == -1) { return Err(std::string(strerror(errno))); } return Ok(std::move(retval)); } auto_pipe::auto_pipe(int child_fd, int child_flags) : ap_child_flags(child_flags), ap_child_fd(child_fd) { switch (child_fd) { case STDIN_FILENO: this->ap_child_flags = O_RDONLY; break; case STDOUT_FILENO: case STDERR_FILENO: this->ap_child_flags = O_WRONLY; break; } } void auto_pipe::after_fork(pid_t child_pid) { int new_fd; switch (child_pid) { case -1: this->close(); break; case 0: if (this->ap_child_flags == O_RDONLY) { this->write_end().reset(); if (this->read_end().get() == -1) { this->read_end() = ::open("/dev/null", O_RDONLY); } new_fd = this->read_end().get(); } else { this->read_end().reset(); if (this->write_end().get() == -1) { this->write_end() = ::open("/dev/null", O_WRONLY); } new_fd = this->write_end().get(); } if (this->ap_child_fd != -1) { if (new_fd != this->ap_child_fd) { dup2(new_fd, this->ap_child_fd); this->close(); } } break; default: if (this->ap_child_flags == O_RDONLY) { this->read_end().reset(); } else { this->write_end().reset(); } break; } } int auto_pipe::open() { int retval = auto_fd::pipe(this->ap_fd); this->ap_fd[0].close_on_exec(); this->ap_fd[1].close_on_exec(); return retval; }
#ifndef __HallHandler_H__ #define __HallHandler_H__ #include <map> #include "CDLSocketHandler.h" #include "Packet.h" #include "DLDecoder.h" class HallHandler :public CDLSocketHandler { public: HallHandler(); virtual ~HallHandler(); int OnConnected() ; int OnClose(); int OnPacketComplete(const char* data, int len); CDL_Decoder* CreateDecoder() { return &DLDecoder::getInstance(); } public: int uid; private: }; #endif
#include <string> #include <vector> using namespace std; vector<long long> solution(int x, int n) { vector<long long> answer; int mul=1; while(mul<=n){ answer.push_back(x*mul); mul++; } return answer; }
//=========================================================================== //! @file gpu_texture.h //! @brief テクスチャ //=========================================================================== #pragma once //=========================================================================== //! @namespace gpu //=========================================================================== namespace gpu { //=========================================================================== //! @class Texture //=========================================================================== class Texture { public: //----------------------------------------------------------------------- //! @name 初期化 //----------------------------------------------------------------------- //@{ //! @brief コンストラクタ Texture() = default; //! @brief デストラクタ ~Texture() = default; //@} //----------------------------------------------------------------------- //! @name タスク //----------------------------------------------------------------------- //@{ //----------------------------------------------------------------------- //! @brief 初期化(D3DResource指定) //! @param [in] d3dResource ID3D11Resourceのポインタ //! @param [in] cubemap キューブマップかどうか //! @return true 正常終了 //! @return false エラー終了 //----------------------------------------------------------------------- bool initialize(ID3D11Resource* d3dResource, bool cubemap = false); //@} //----------------------------------------------------------------------- //! @name 取得 //----------------------------------------------------------------------- //@{ u32 getWidth() const { return width_; } // 幅取得 u32 getHeight() const { return height_; } // 高さ取得 u32 getMipLevels() const { return mipLevels_; } // ミップレベル取得 DXGI_FORMAT getFormat() const { return format_; } // 形式取得 ID3D11Resource* getD3DResource() const { return d3dResource_.Get(); } // テクスチャメモリー ID3D11ShaderResourceView* getD3DSrv() const { return d3dSrv_.Get(); } // SRV ID3D11RenderTargetView* getD3DRtv() const { return d3dRtv_.Get(); } // RTV ID3D11DepthStencilView* getD3DDsv() const { return d3dDsv_.Get(); } // DSV ID3D11UnorderedAccessView* getD3DUav() const { return d3dUav_.Get(); } // UAV //@} private: u32 width_ = 0; //!< 幅 u32 height_ = 0; //!< 高さ u32 depth_ = 0; //!< 奥行き u32 mipLevels_ = 0; //!< ミップレベル数 DXGI_FORMAT format_ = DXGI_FORMAT_UNKNOWN; //!< ピクセルフォーマット u32 bindFlags_ = 0; //!< 関連付け情報(D3D11_BIND_FLAGの組み合わせ) com_ptr<ID3D11Resource> d3dResource_; //!< テクスチャメモリー com_ptr<ID3D11ShaderResourceView> d3dSrv_; //!< SRV com_ptr<ID3D11RenderTargetView> d3dRtv_; //!< RTV com_ptr<ID3D11DepthStencilView> d3dDsv_; //!< DSV com_ptr<ID3D11UnorderedAccessView> d3dUav_; //!< UAV }; //----------------------------------------------------------------------- //! @brief テクスチャ作成(ファイル名指定) //! @param [in] filePath ファイル名 //! @param [in] cubemap キューブマップかどうか //! @return テクスチャのポインタ, 失敗nullptr //----------------------------------------------------------------------- gpu::Texture* createTexture(const std::string& filePath, bool cubemap = false); //----------------------------------------------------------------------- //! @brief テクスチャを作成(ID3D11Resource指定) //! @param [in] filePath ファイル名 //! @param [in] cubemap キューブマップかどうか //! @return テクスチャのポインタ, 失敗nullptr //----------------------------------------------------------------------- gpu::Texture* createTexture(ID3D11Resource* d3dResouce, bool cubemap = false); //----------------------------------------------------------------------- //! @brief 描画ターゲット作成 //! @param [in] width 幅 //! @param [in] height 高さ //! @param [in] format ピクセル形式 //! @param [in] cubemap キューブマップかどうか //! @return テクスチャのポインタ //----------------------------------------------------------------------- gpu::Texture* createRenderTarget(u32 width, u32 height, DXGI_FORMAT format, bool cubemap = false); } // namespace gpu
#pragma once //======include section====== #include "Score.h" #include "Lives.h" #include "Location.h" #include "macros.h" class Player { public: // c-tors Player (Location location); Player(); // getters int get_score(); int get_lives(); Location get_location(); // setters void set_loctaion(Location& new_location); void set_lives(int lives); void set_score(int score); // misc void increse_score(int value); void decrese_live(); void reset(Location& starting_location); void increse_score_end_level(int level); private: Score m_player_score; Lives m_player_lives; Location m_player_loctaion; };
#ifndef note_h #define note_h #include <QString> #include <QDate> #include <QXmlStreamWriter> /********************************************************************* *** Execption *** **********************************************************************/ class NotesException{ public: NotesException(const QString& message):info(message) {} QString getInfo() const { return info; } private: QString info; }; /*********************************************************************/ /********************************************************************* *** Note Abstract Class *** **********************************************************************/ class Note { protected: int id ; QString title ; QDate dateC; QDate dateM; bool archive; public: static int idIterator; ///Constructor Note(int i, const QString t=(QString)"", QDate d_c=QDate::currentDate(), QDate d_lm=QDate::currentDate(), bool a=false): id(i), title(t), dateC(d_c), dateM(d_lm), archive(a){} Note(): id(), title(""), dateC(QDate::currentDate()), dateM(QDate::currentDate()), archive(false) {} virtual ~Note() {} virtual Note* clone() =0; ///Accessor int getId() const {return id;} const QString& getTitle() const {return title;} const QDate& getDateC() const {return dateC;} const QDate& getDateM() const {return dateM;} bool GetArchive() const {return archive;} ///Method set void setTitle(const QString& newTitle) {title=newTitle ;} void setDateLastModification() {dateM=QDate::currentDate();} void setArchive() {archive=!archive ;} void setId() {id = idIterator++;} ///Method save virtual void saveNote(QXmlStreamWriter &stream) const = 0; }; /*********************************************************************/ /********************************************************************* *** Article ** *********************************************************************/ class Article : public Note { private: QString text; public : ///Constructor Article(int i, const QString t=(QString)"", QDate d_c=QDate::currentDate(), QDate d_lm=QDate::currentDate(), bool a=false, const QString txt=(QString)""): Note(i,t,d_c,d_lm,a), text(txt)/*, careTaker(new MementoA*[5]),nbMemento(0),nbMax(5)*/ {} Article() : Note(), text("") {} ///clone virtual Article* clone(); ///Accessor const QString& getText() const {return text ;} const QDate& getDateC() const {return dateC;} ///Modify attribute void setText(const QString& t) {text=t ;} ~Article() {} ///Method save void saveNote(QXmlStreamWriter &stream) const; }; /********************************************************************/ /******************************************************************** *** Task *** *********************************************************************/ enum state {Waiting,Ongoing,Done}; inline QString toString(state s){ switch (s){ case Waiting: return "Waiting"; case Ongoing: return "Ongoing"; case Done: return "Done"; default: return "[Unknown status]"; } } inline state toState(const QString& s){ if (s == "Waiting") return Waiting; if (s == "Ongoing") return Ongoing; if (s == "Done") return Done; else throw NotesException("ERROR"); } class Task : public Note { private: QString action; unsigned int priority; QDate deadline; state status; public : ///Constructor (how to put deadline optional) Task(int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString act, unsigned int p=0, QDate dl=QDate(0000,00,00), state s=Waiting): Note(i,t,d_c,d_lm,a), action(act), priority(p), deadline(dl), status(s) {} Task() : Note(), action(""), priority(0), deadline(QDate::currentDate()), status(Waiting) {} ///clone virtual Task* clone(); ///Accessor const QString& getAction() const {return action ;} const unsigned int& getPriority() const {return priority ;} const QDate& getDeadline() const {return deadline ;} const state& getState() const {return status ;} ///Modify attribute void setAction(const QString& newAction) {action=newAction;} void setPriority (unsigned int p) {priority = p ;} void setDeadline (QDate newDl) {deadline=newDl ;} void setState (const QString& s) {status = toState(s);} ///Method save void saveNote(QXmlStreamWriter &stream) const; ~Task() {} }; /*********************************************************************/ /********************************************************************* *** Multimedia *** **********************************************************************/ class Multimedia : public Note { private: QString description; QString image; public: //Constructor Multimedia (int i, const QString t, QDate d_c, QDate d_lm, bool a, const QString& d, const QString& f) : Note(i,t,d_c,d_lm,a), description(d), image(f) {} Multimedia() : Note(), description(""), image("") {} //Accessor const QString& getDescription() const {return description;} const QString& getImage() const {return image;} //setMethod void setDescription(const QString& d) { description=d;} void setImage(const QString & i) { image = i;} //clone virtual pure virtual Multimedia* clone()=0; ///Method save void saveNote(QXmlStreamWriter &stream) const; ~Multimedia(){} }; /*********************************************************************/ /********************************************************************* *** Image *** **********************************************************************/ class Image : public Multimedia{ public: Image(int i, const QString t, QDate d_c ,QDate d_m ,bool a, const QString& d, const QString& f): Multimedia(i,t,d_c,d_m,a,d,f) {} Image() : Multimedia() {} virtual Image * clone (); ///Method save void saveNote(QXmlStreamWriter &stream) const; ~Image() {} }; /*********************************************************************/ /********************************************************************* *** Enregistrement Audio *** **********************************************************************/ class Audio : public Multimedia{ public: Audio(int i, const QString t, QDate d_c ,QDate d_m ,bool a, const QString& d, const QString& f): Multimedia(i,t,d_c,d_m,a,d,f) {} Audio(): Multimedia() {} virtual Audio* clone (); ///Method save void saveNote(QXmlStreamWriter &stream) const; ~Audio() {} }; /*********************************************************************/ /********************************************************************* *** video *** **********************************************************************/ class Video : public Multimedia{ public: Video(int i, const QString t, QDate d_c ,QDate d_m ,bool a, const QString& d, const QString& f): Multimedia(i,t,d_c,d_m,a,d,f) {} Video() : Multimedia() {} virtual Video * clone (); ///Method save void saveNote(QXmlStreamWriter &stream) const; ~Video() {} }; /*********************************************************************/ #endif
#include "ShapesBlocks.h" void cuboidBlocks:: SortAscendingOfDiameterSPhere(){ sort(W.begin(), W.end()); cout << "Sorted \n"; for (auto x : W) cout << x << endl; }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; // Author: Tatparya Shankar void getChocolates() { long long int numSlices; long long int totalNumPieces = 0; long long int horizontal; long long int vertical; cin >> numSlices; horizontal = ceil( numSlices / 2 ); vertical = numSlices - horizontal; totalNumPieces = horizontal * vertical; cout << totalNumPieces << endl; } int main() { int numTestCases; cin >> numTestCases; for( int i = 0; i < numTestCases; i++ ) { getChocolates(); } return 0; }
/** * @author:divyakhetan * @date: 2/1/2019 */ #include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int n; // no.of char cin >> n; char pattern[n]; for(int i = 0; i < n; i++) cin >> pattern[i]; int hash_str[256]; int hash_pattern[256]; memset(hash_str, 0, sizeof(hash_str)); memset(hash_pattern, 0, sizeof(hash_pattern)); if(n > s.length()) cout << "Not possible"; else{ for(int i = 0; i < n; i++){ char x = pattern[i]; hash_pattern[x]++; } int count = 0; int start = 0; int start_ind = -1; int minlen = INT_MAX; for(int i = 0; i < s.length(); i++){ char x = s[i]; hash_str[x]++; //check if part of pattern also and we need to avoid overcounting for a particular char. if(hash_pattern[x] != 0 && hash_str[x] <= hash_pattern[x]) count++; // avoid useless char from the start if(count == n){ while(hash_str[s[start]] > hash_pattern[s[start]] ){ cout << s[start] << " "; hash_str[s[start]]--; start++; // move start to right } int len = i - start + 1; if(len < minlen){ minlen = len; start_ind = start; } } } // if(start_ind == -1) cout << "No such substring"; // else // cout << s.substr(start_ind, minlen); } }
#include "pr2_head_manager/ArtificialLife.h" #include "resource_management/message_storage/MessageWrapper.h" #include "pr2_head_manager_msgs/RawPitchYaw.h" namespace pr2_head_manager { ArtificialLife::ArtificialLife(std::shared_ptr<resource_management::ReactiveBuffer> buffer) : resource_management::ArtificialLife(100 /* you can change the artficial life frame rate here*/, buffer), poisson_distribution(5000), normal_distribution(0.0, 0.2) { // set an initial value in the artificial life buffer // if you do not do that that resource will not start in artificial life mode // Example: // 1 - Wrap your data with one of your types: // auto wrapped_Point_data = std::make_shared<resource_management::MessageWrapper<geometry_msgs::PointStamped>>(data); // auto wrapped_PitchYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::RawPitchYaw>>(data); // auto wrapped_PrioritizedPitch_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::Pitch>>(data); // auto wrapped_PrioritizedYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::Yaw>>(data); // // 2 - Set the useless priority to your wrapped data: // wrapped_Point_data->setPriority(resource_management::useless); // wrapped_PitchYaw_data->setPriority(resource_management::useless); // wrapped_PrioritizedPitch_data->setPriority(resource_management::useless); // wrapped_PrioritizedYaw_data->setPriority(resource_management::useless); // // 3 - Insert your wrapped data into the rtificial life buffer: // _buffer->setData(wrapped_Point_data); // _buffer->setData(wrapped_PitchYaw_data); // _buffer->setData(wrapped_PrioritizedPitch_data); // _buffer->setData(wrapped_PrioritizedYaw_data); pr2_head_manager_msgs::RawPitchYaw data; data.pitch = 0.0; data.yaw = 0.0; auto wrapped_PitchYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::RawPitchYaw>>(data); wrapped_PitchYaw_data->setPriority(resource_management::low); _buffer->setData(wrapped_PitchYaw_data); } void ArtificialLife::init() { // Put our own initialisation function here // It will be called each time a new artificial life cycle begins // Set an initial value in the artificial life buffer // if you do not do that, at each new cycle, the resource // will start with the previous artificial life value // Example: // 1 - Wrap your data with one of your types: // auto wrapped_Point_data = std::make_shared<resource_management::MessageWrapper<geometry_msgs::PointStamped>>(data); // auto wrapped_PitchYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::RawPitchYaw>>(data); // auto wrapped_PrioritizedPitch_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::Pitch>>(data); // auto wrapped_PrioritizedYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::Yaw>>(data); // // 2 - Set the useless priority to your wrapped data: // wrapped_Point_data->setPriority(resource_management::useless); // wrapped_PitchYaw_data->setPriority(resource_management::useless); // wrapped_PrioritizedPitch_data->setPriority(resource_management::useless); // wrapped_PrioritizedYaw_data->setPriority(resource_management::useless); // // 3 - Insert your wrapped data into the rtificial life buffer: // _buffer->setData(wrapped_Point_data); // _buffer->setData(wrapped_PitchYaw_data); // _buffer->setData(wrapped_PrioritizedPitch_data); // _buffer->setData(wrapped_PrioritizedYaw_data); pr2_head_manager_msgs::RawPitchYaw data; data.pitch = 0.0; data.yaw = 0.0; auto wrapped_PitchYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::RawPitchYaw>>(data); wrapped_PitchYaw_data->setPriority(resource_management::low); _buffer->setData(wrapped_PitchYaw_data); last_moved_time = std::chrono::system_clock::now(); next_duration = poisson_distribution(generator); } void ArtificialLife::inLoop() { // This function will be called at the specified frame rate // will the artificial life cycle is running // DO NOT CREATE YOUR OWN LOOP HERE // creat a new data and feed it to the artficial life buffer // Example: // 1 - Wrap your data with one of your types: // auto wrapped_Point_data = std::make_shared<resource_management::MessageWrapper<geometry_msgs::PointStamped>>(data); // auto wrapped_PitchYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::RawPitchYaw>>(data); // auto wrapped_PrioritizedPitch_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::Pitch>>(data); // auto wrapped_PrioritizedYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::Yaw>>(data); // // 2 - Set the useless priority to your wrapped data: // wrapped_Point_data->setPriority(resource_management::useless); // wrapped_PitchYaw_data->setPriority(resource_management::useless); // wrapped_PrioritizedPitch_data->setPriority(resource_management::useless); // wrapped_PrioritizedYaw_data->setPriority(resource_management::useless); // // 3 - Insert your wrapped data into the rtificial life buffer: // _buffer->setData(wrapped_Point_data); // _buffer->setData(wrapped_PitchYaw_data); // _buffer->setData(wrapped_PrioritizedPitch_data); // _buffer->setData(wrapped_PrioritizedYaw_data); auto now = std::chrono::system_clock::now(); if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_moved_time).count() >= next_duration) { pr2_head_manager_msgs::RawPitchYaw data; data.pitch = normal_distribution(generator); data.yaw = normal_distribution(generator); auto wrapped_PitchYaw_data = std::make_shared<resource_management::MessageWrapper<pr2_head_manager_msgs::RawPitchYaw>>( data); wrapped_PitchYaw_data->setPriority(resource_management::low); _buffer->setData(wrapped_PitchYaw_data); last_moved_time = now; next_duration = poisson_distribution(generator); } } } // namespace pr2_head_manager
/* * AQEM Sensor Display System * By: Connor Widder * Date: 11/04/2019 * * This sketch: * Communicates with BME280s with different I2C addresses * Displays BME280 sensor values on the LCD (I2C comm) * * Devices: * SparkFun BME280 & CCS811 Sensor w/ Breakout board * SparkFun RGB OpenLCD Serial display * SparkFun Logic Level Converter * * Hardware connections: * BME280 / Arduino * GND / GND * 3.3 / 3.3 * SDA / SDA * SCL / SCL * * LCD / Arduino * GND / GND * RAW / Logic Level Converer * SDA / SDA * SCL / SCL * */ #include <Wire.h> #include "SparkFunBME280.h" BME280 mySensorA; //Uses default I2C address 0x77 #include <SerLCD.h> //Click here to get the library: http://librarymanager/All#SparkFun_SerLCD SerLCD lcd; // Initialize the library with default I2C address 0x72 float temperatureF = 0; //Backup sensor float tempSensorValue = 0; float temp_VOut = 0; float temp2 = 0; //CO int co = 0; //co_VOut = 0; int humidity = 0; float pressureFlt = 0; int pressure = 0; //LCD preset posistions const byte pos_Title[2] = {8,0}; //const byte pos_Time[2] = {15,0}; //const byte pos_Date[2] = {6,0}; const byte pos_A1[2] = {2,1}; const byte pos_A2[2] = {12,1}; const byte pos_B1[2] = {2,3}; const byte pos_B2[2] = {12,3}; //Bottons const int buttonUpPin = 7; int buttonUpState = 0; const int buttonDownPin = 6; int buttonDownState = 0; int scrollIndex = 0; //Char symbols int degF_Sym = 0; byte degF_Char[8] = { 0x1C, 0x14, 0x1C, 0x07, 0x04, 0x07, 0x04, 0x04 }; //Temp Symbol int temp_Sym = 1; byte temp_Char[8] = { 0x04, 0x0A, 0x0A, 0x0E, 0x0E, 0x1F, 0x1F, 0x0E }; //Humidity Symbol int hum_Sym = 2; byte hum_Char[8] = { 0x04, 0x04, 0x0A, 0x0A, 0x11, 0x11, 0x11, 0x0E }; //Ambient Light Symbol int light_Sym = 3; byte light_Char[8] = { 0x00, 0x04, 0x15, 0x0E, 0x1F, 0x0E, 0x15, 0x04 }; //CO int co_Sym = 4; /*byte co_Char[8] = { B01110, B10001, B10001, B01110, B00000, B10001, B10001, B01110 };*/ byte co_Char[8] = { B01110, B10001, B10001, B00000, B01110, B10001, B10001, B01110 }; void setup() { //Setup serial port Serial.begin(9600); Serial.println("----AQEM sensor validation----"); //Initial serial statment //Set up I2C Communications Wire.begin(); //The default for the SparkFun Environmental Combo board is 0x77 (jumper open). //If you close the jumper it is 0x76 //The I2C address must be set before .begin() otherwise the cal values will fail to load. mySensorA.setI2CAddress(0x77); if(mySensorA.beginI2C() == false) Serial.println("Sensor A connect failed"); //Define Pins pinMode(A0, INPUT); pinMode(A1, INPUT); pinMode(buttonUpPin, INPUT); pinMode(buttonDownPin, INPUT); //Setup the LCD (20x4) lcd.begin(Wire); lcd.setBacklight(255, 255, 255); //Set backlight to bright white //lcd.setContrast(5); //Set contrast. Lower to 0 for higher contrast. lcd.clear(); //Clear the display - this moves the cursor to home position as well delay(2000); lcd.setCursor(3, 1); lcd.print("---- AQEM ----"); lcd.setCursor(3, 2); delay(5000/14); for (int i = 0; i < 14;i++){ lcd.print(char(255)); delay(3000/14); } lcd.clear(); //Custom Characters lcd.createChar(degF_Sym, degF_Char); //Degree symbol with F lcd.createChar(temp_Sym, temp_Char); //Temnp symbol lcd.createChar(hum_Sym, hum_Char); //Humidity symbol lcd.createChar(light_Sym, light_Char); //Ambient light symbol lcd.createChar(co_Sym, co_Char); //CO symbol symbol } void loop() { readSensors(); //serialLog(); //readButtonStates(); updateDisplay(); } void readSensors(){ //Temp temperatureF = mySensorA.readTempF(); //Temp 2 tempSensorValue = analogRead(0); temp_VOut = (tempSensorValue * 5000) / 1024; temp2 = temp_VOut/10; //Humidity humidity = mySensorA.readFloatHumidity(); //Pressure pressureFlt = mySensorA.readFloatPressure(); pressureFlt /= 100.0; pressure = round(pressureFlt); //CO co = analogRead(1); } void updateDisplay(){ //Read scroll buttons buttonUpState = digitalRead(buttonUpPin); buttonDownState = digitalRead(buttonDownPin); if((buttonUpState == 1) && (scrollIndex < 10)){ scrollIndex++; delay(50); }else if((buttonDownState == 1) && (scrollIndex > 0)){ scrollIndex--; delay(50); } //Header lcd.setCursorPos(pos_Title); lcd.print("AQEM "); lcd.print(scrollIndex); /*//Date and Time * lcd.setCursorPos(pos_Time); * lcd.print("00:00"); * lcd.setCursorPos(pos_Date); * lcd.print("00/00/00"); */ //Temperature //lcd.setCursor(0, 1); lcd.setCursorPos(pos_A1); lcd.write(temp_Sym); lcd.print(temperatureF,1); lcd.print(String((char)223) + String("F")); lcd.setCursor(3,2); lcd.print(temp2,1); //Humidity lcd.setCursorPos(pos_A2); lcd.write(hum_Sym); lcd.print(String(humidity) + String((char)37)); //Pressure lcd.setCursorPos(pos_B1); lcd.print(String(pressure) + String("hPa")); //CO lcd.setCursor(12,2); lcd.write(co_Sym); lcd.print(String(co)); //Ambient Light lcd.setCursorPos(pos_B2); lcd.write(light_Sym); lcd.print(String(co) + String((char)37)); } void serialLog(){ //Display enviromental snesors //Temp Serial.print("TempA: "); Serial.print(temperatureF, 0); //Humidity Serial.print(" HumidityA: "); Serial.print(humidity, 0); //Pressure Serial.print(" PressureA: "); Serial.print(pressure, 0); Serial.println(); } void scrollPages(){ //LCD data locations /* * A1: (0,1), A2: (10,1) * B1: (0,3), A2: (10,3) */ //Read button states //Next page //Prev page //Define pages /* * 1: S1 - S2 / S3 - S4 * 2: S3 - S4 / S5 - S6 * 3: S5 - S6 / S7 - S8 * 4: S7 - S8 / S9 - S10 * 5: S9 - S10 / S11 -S12 */ //Case statement base on button states/indexs to determine page }
/** * @file rasterize.h * @brief CUDA-accelerated rasterization pipeline. * @authors Skeleton code: Yining Karl Li, Kai Ninomiya, Shuai Shao (Shrek) * @date 2012-2016 * @copyright University of Pennsylvania & STUDENT */ #pragma once #define NEARPLANE 0.1f #define FARPLANE 1000.0f #define BACKFACE_CULLING 1 #define BACKFACE_CULLING_THRUST 0 #define PERSPECTIVE_CORRECTION 1 #define USING_MUTEX 1 #define SSAA 0 #define BLINNPHONG 0 #define PBS 1 #define BLOOM 1 #define DEBUG_DEPTH 0 #define DEBUG_NORMAL 0 #define DEBUG_ROUGHNESS 0 #define DEBUG_METALLIC 0 #define DEBUG_UV 0 #define DEBUG_ENV 0 #define DEBUG_TIME 0 #define LightSize 3 #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <thrust/remove.h> #include <thrust/execution_policy.h> #include <thrust/device_vector.h> #include <thrust/device_ptr.h> #include <chrono> #include <ctime> namespace tinygltf{ class Scene; } void rasterizeInit(int width, int height); void rasterizeSetBuffers(const tinygltf::Scene & scene); void rasterize(uchar4 *pbo, const glm::mat4 & MVP, const glm::mat4 & MV, const glm::mat3 MV_normal); void rasterizeFree();
#include "flickdataview.h" #include "module_base_def.h" #include "statdatatool.h" #include <QComboBox> #include <QDateTime> CFlickDataView::CFlickDataView(QWidget *parent) : CStatViewBase(parent) { m_mapFileName["sflick.dat"] = StatItemInfo("短闪变", ""); m_mapFileName["lflick.dat"] = StatItemInfo("长闪变", ""); QMap<QString, StatItemInfo>::iterator ite = m_mapFileName.begin(); for (; ite != m_mapFileName.end(); ++ite) { m_pCombDataSel->addItem(ite.value().chinese); } m_pCombDataSel->setCurrentIndex(0); } bool CFlickDataView::_getStatDataFromFile(QString statFilePath, StatDataPoints *points) { // 从统计文件中读取所有统计数据 CStatDataTool tool; StatRecordInfo info; int idx = statFilePath.lastIndexOf('/'); QString infoFilePath = statFilePath.left(idx + 1) + "stat.info"; for (int i = 0; i != 4; i++) points[i].clear(); // 先读取统计配置信息,获取起始时间以及统计数据数量 if (!tool.ReadInfoFromFile(infoFilePath.toStdString(), info)) return false; if (!tool.InitReadFile(statFilePath.toStdString(), _getStatPhaseCount(statFilePath))) return false; // 转化为显示的统计数据缓存起来 StatDatas dats; if (!tool.ReadDataFromFile(0, info.statTotalCnt - 1, dats)) return false; // 计算闪变起始时间 UtcTime curTime = info.firstTime.toUtcTime(); int stepTime = info.statCycle; if (statFilePath.contains("sflick")) stepTime = 60 * 10; else if (statFilePath.contains("lflick")) stepTime = 60 * 60 * 2; int tmp = curTime.tv_sec % stepTime; curTime.tv_sec += stepTime - tmp; for (int i = 0; i != (int)dats.size(); i++) { DateTime curDate = curTime.toDateTime(); QDateTime tmp(QDate(curDate.year, curDate.month, curDate.day), QTime(curDate.hour, curDate.minute, curDate.second, curDate.ms)); StatOnePoint point[4]; for (int j = 0; j != (int)dats.at(i).max_val.size(); j++) point[0].y.push_back(dats.at(i).max_val.at(j)); for (int j = 0; j != (int)dats.at(i).min_val.size(); j++) point[1].y.push_back(dats.at(i).min_val.at(j)); for (int j = 0; j != (int)dats.at(i).avg_val.size(); j++) point[2].y.push_back(dats.at(i).avg_val.at(j)); for (int j = 0; j != (int)dats.at(i).cp95_val.size(); j++) point[3].y.push_back(dats.at(i).cp95_val.at(j)); for (int j = 0; j != 4; j++) { point[j].x = tmp.toTime_t(); points[j].push_back(point[j]); } curTime.tv_sec += stepTime; } return true; }
#pragma once #include <iostream> #include <allegro5/allegro5.h> #include <allegro5/allegro_primitives.h> #include "Globals.h" //*Description of class*// class GameObject { private: int ID; bool isAlive; bool isCollidable; protected: int x; int y; int speed; int boundX; int boundY; public: GameObject(); void initiate(int x, int y, int speed, int boundX, int boundY); void virtual update() = 0; void virtual render()= 0; int getX() {return x;} int getY() {return y;} void setX(int x) {GameObject::x = x;} void setY(int y) {GameObject::y = y;} int getBoundX() {return boundX;} int getBoundY() {return boundY;} int getID() {return ID;} void setID(int ID) {GameObject::ID = ID;} bool getAlive() {return isAlive;} void setAlive(bool isAlive) {GameObject::isAlive =isAlive;} bool checkCollisions(GameObject *otherObject); void virtual collided(int otherObjectID) = 0; bool collidable(); };
#ifndef WORLD_H #define WORLD_H #define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <glm/glm.hpp> #include <unordered_map> #include <vector> class World; #include "block.hpp" #include "chunk.hpp" #include "../graphics/GameObject3D.hpp" #include <pthread.h> #include <mutex> #include <deque> #include <condition_variable> #include "generators/generator.hpp" /** * specifies how many threads should be used for World Gen * I ran the test with 1 thread, 2 threads and 4 threads. * * When using 1 thread the speed was too slow and player * could out run the world generation * * When using 2 threads the speed was fast enough for the * chunks to generate before the player reached them, but * was still able to see generation artifacts * * When using 4 threads similar effect to running with two threads * was observed */ #define WORLDGEN_THREAD_COUNT_MAX 2 /** * Comparators for unordered map of chunks */ struct ivec3Comparator{ size_t operator()(glm::ivec3 const& k)const{ return ((std::hash<int>()(k.x) ^ (std::hash<int>()(k.y) << 1)) >> 1) ^ (std::hash<int>()(k.z) << 1); } bool operator()(glm::ivec3 const& lhs, glm::ivec3 const& rhs)const{ return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } }; class World{ public: /** * Stores the seed of the world */ uint32_t seed; World(); World(uint32_t seed); World(uint32_t wseed, Generator* wworldGenerator); /** * Sets block to `block` at absolute `pos` */ void SetBlock(glm::ivec3 pos, Block* block); /** * Sets block to `block` at absolute x/y/z */ void SetBlock(int x, int y, int z, Block* block); /** * Gets block at absolute `pos` */ Block* GetBlock(glm::ivec3 pos); /** * Gets block at absolute x/y/z */ Block* GetBlock(int x, int y, int z); /** * Gets mesh of the world */ GameObject3D GetMesh(glm::ivec3 pos, int distance); /** * Converts absolute coordinate to coordinate of chunk */ static glm::ivec3 ConvertToChunk(glm::ivec3 pos); /** * Converts absolute coordinate to coordinate of block within chunk */ static glm::ivec3 ConvertToChunkRelative(glm::ivec3 pos); /** * Stops the world multithreading */ void Stop(); /** * Stores the world generator used by this world. */ Generator* worldGenerator; private: /** * Stores chunks within the world */ std::unordered_map<glm::ivec3, Chunk*, ivec3Comparator, ivec3Comparator> chunks; /** * Stores list of threads that are used for world generator */ std::vector<pthread_t> worldGenThread; /** * Mutex for world generator threads */ std::mutex worldGenMutex; /** * Queue for chunks to be generated by other treads */ std::deque<Chunk*> worldGenQueue; /** * Used to block generator threads */ std::condition_variable worldGenCond; /** * Specifies whatever generator threads should continue to work */ bool worldGenContinue = true; /** * Helper function for world::WorldGen * Allows passage of the world object */ static void *WorldGenHelper(void *context); /** * generator thread loop */ void *WorldGen(); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; 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. ** */ #ifndef VEGAD3D10SHADER_H #define VEGAD3D10SHADER_H #ifdef VEGA_BACKEND_DIRECT3D10 #include "modules/libvega/vega3ddevice.h" #include "modules/util/stringhash.h" #ifdef CANVAS3D_SUPPORT #include <D3Dcompiler.h> #include "platforms/vega_backends/d3d10/vegad3d10device.h" #ifndef NO_DXSDK class VEGAD3d10Shader : public VEGA3dShader { public: VEGAD3d10Shader() : m_isPixelShader(FALSE), m_attribute_count(0), m_attributes(NULL) { } ~VEGAD3d10Shader(); OP_STATUS Construct(const char* src, BOOL pixelShader, unsigned int attribute_count, VEGA3dDevice::AttributeData *attributes); const char* getSource(){return m_source.CStr();} unsigned int getSourceLength(){return m_source.Length();} virtual BOOL isFragmentShader(){return m_isPixelShader;} virtual BOOL isVertexShader(){return !m_isPixelShader;} VEGA3dDevice::AttributeData* getAttributes(){return m_attributes;} unsigned int getAttributeCount(){return m_attribute_count;} private: OpString8 m_source; BOOL m_isPixelShader; unsigned int m_attribute_count; VEGA3dDevice::AttributeData* m_attributes; }; #endif //NO_DXSDK #endif // CANVAS3D_SUPPORT #ifndef NO_DXSDK class VEGAD3d10ShaderConstants { public: VEGAD3d10ShaderConstants() : m_names(NULL), m_values(NULL), m_count(0), m_slotCount(0), #ifdef CANVAS3D_SUPPORT m_shader_reflection(NULL), #endif // CANVAS3D_SUPPORT m_ramBuffer(NULL), m_cbuffer(NULL), m_dirty(true) {} ~VEGAD3d10ShaderConstants() { Release(); } void Release(); int getConstantOffset(int idx); #ifdef CANVAS3D_SUPPORT OP_STATUS getConstantValue(int idx, float* val, VEGA3dShaderProgram::ConstantType type, int arrayIndex); OP_STATUS getConstantValue(int idx, int* val, VEGA3dShaderProgram::ConstantType type, int arrayIndex); #endif // CANVAS3D_SUPPORT int lookupConstName(const char* name); #ifdef CANVAS3D_SUPPORT unsigned int getInputCount() { return m_attrib_to_semantic_index.count(); } unsigned int getInputMaxLength(); int attribToSemanticIndex(const char *name); unsigned int getConstantCount() { return m_count; } unsigned int getConstantMaxLength(); /// NOTE: may overwrite global 2k temp-buffer OP_STATUS indexToAttributeName(unsigned idx, const char **name); OP_STATUS getConstantDescription(unsigned int idx, VEGA3dShaderProgram::ConstantType* type, unsigned int* size, const char** name); int getSemanticIndex(unsigned int idx); OP_STATUS initializeForCustomShader(ID3D10Device1 *dev, ID3D10ShaderReflection *shader_reflection); OP_STATUS addAttributes(unsigned int attr_count, VEGA3dDevice::AttributeData* attributes); #endif // CANVAS3D_SUPPORT // The variable with name names[i] has the offset values[i] within the // cbuffer const char *const *m_names; const unsigned int *m_values; unsigned int m_count; unsigned int m_slotCount; #ifdef CANVAS3D_SUPPORT ID3D10ShaderReflection *m_shader_reflection; #endif // CANVAS3D_SUPPORT void* m_ramBuffer; ID3D10Buffer* m_cbuffer; bool m_dirty; #ifdef CANVAS3D_SUPPORT StringHash<unsigned> m_attrib_to_semantic_index; #endif // CANVAS3D_SUPPORT }; class VEGAD3d10ShaderProgram : public VEGA3dShaderProgram { public: VEGAD3d10ShaderProgram(ID3D10Device1* dev, bool level9); ~VEGAD3d10ShaderProgram(); #ifdef CANVAS3D_SUPPORT OP_STATUS loadShader(VEGA3dShaderProgram::ShaderType shdtype, WrapMode mode, pD3DCompile D3DCompileProc, VEGAD3D10_pD3DReflectShader D3DReflectShaderProc); #else OP_STATUS loadShader(VEGA3dShaderProgram::ShaderType shdtype, WrapMode mode); #endif virtual ShaderType getShaderType(){return m_type;} #ifdef CANVAS3D_SUPPORT /** For custom shaders. */ virtual OP_STATUS addShader(VEGA3dShader* shader); virtual OP_STATUS removeShader(VEGA3dShader* shader); virtual OP_STATUS link(OpString *info_log); virtual OP_STATUS setAsRenderTarget(VEGA3dRenderTarget *target); virtual OP_STATUS validate(); virtual bool isValid(); virtual unsigned int getNumInputs(); virtual unsigned int getNumConstants(); virtual unsigned int getInputMaxLength() { return m_vertexConstants.getInputMaxLength(); } virtual unsigned int getConstantMaxLength() { return MAX(m_pixelConstants.getConstantMaxLength(), m_vertexConstants.getConstantMaxLength()); } /// NOTE: may overwrite global 2k temp-buffer virtual OP_STATUS indexToAttributeName(unsigned int idx, const char **name); virtual OP_STATUS getConstantDescription(unsigned int idx, ConstantType* type, unsigned int* size, const char** name); int getSemanticIndex(unsigned int idx); /** Maps an attribute name to the corresponding semantic index for the shader. For example, if we have 'float4 foo : TEXCOORD3' in the shader, then attribToSemanticIndex("foo") = 3. Returns -1 if the shader does not have an attribute with the specified name. */ virtual int attribToSemanticIndex(const char *name); #endif // CANVAS3D_SUPPORT virtual int getConstantLocation(const char* name); int getConstantOffset(int idx); virtual OP_STATUS setScalar(int idx, float val); virtual OP_STATUS setScalar(int idx, int val); virtual OP_STATUS setScalar(int idx, float* val, int count); virtual OP_STATUS setScalar(int idx, int* val, int count); virtual OP_STATUS setVector2(int idx, float* val, int count); virtual OP_STATUS setVector2(int idx, int* val, int count); virtual OP_STATUS setVector3(int idx, float* val, int count); virtual OP_STATUS setVector3(int idx, int* val, int count); virtual OP_STATUS setVector4(int idx, float* val, int count); virtual OP_STATUS setVector4(int idx, int* val, int count); virtual OP_STATUS setMatrix2(int idx, float* val, int count, bool transpose); virtual OP_STATUS setMatrix3(int idx, float* val, int count, bool transpose); virtual OP_STATUS setMatrix4(int idx, float* val, int count, bool transpose); #ifdef CANVAS3D_SUPPORT virtual OP_STATUS getConstantValue(int idx, float* val, VEGA3dShaderProgram::ConstantType type, int arrayIndex); virtual OP_STATUS getConstantValue(int idx, int* val, VEGA3dShaderProgram::ConstantType type, int arrayIndex); #endif // CANVAS3D_SUPPORT ID3D10PixelShader* getPixelShader(){return m_pshader;} ID3D10VertexShader* getVertexShader(){return m_vshader;} const BYTE* getShaderData(){return m_vsSource;} unsigned int getShaderDataSize(){return m_vsSourceSize;} ID3D10Buffer* getVertConstBuffer(); ID3D10Buffer* getPixConstBuffer(); bool isVertConstantDataModified(){return m_vertexConstants.m_dirty;} bool isPixConstantDataModified(){return m_pixelConstants.m_dirty;} unsigned int getLinkId() const { return m_linkId; } private: /** * Helper function. If 'error_blob' is non-null, appends its contents to * 'error_log' (if it is non-null), and then Release()s 'error_blob'. Does * nothing if 'error_blob' is null. */ void registerErrorsFromBlob(ID3D10Blob *error_blob, OpString *error_log); ID3D10Device1* m_device; ID3D10PixelShader* m_pshader; ID3D10VertexShader* m_vshader; ID3D10Blob* m_vshaderBlob; VEGAD3d10ShaderConstants m_pixelConstants; VEGAD3d10ShaderConstants m_vertexConstants; #ifdef CANVAS3D_SUPPORT VEGAD3d10Shader *m_pshaderObject; VEGAD3d10Shader *m_vshaderObject; #endif // CANVAS3D_SUPPORT const BYTE* m_vsSource; unsigned int m_vsSourceSize; bool m_featureLevel9; ShaderType m_type; #ifdef CANVAS3D_SUPPORT pD3DCompile m_D3DCompileProc; VEGAD3D10_pD3DReflectShader m_D3DReflectShaderProc; #endif unsigned int m_linkId; }; #endif //NO_DXSDK #endif // VEGA_BACKEND_DIRECT3D10 #endif // !VEGAD3D10SHADER_H
#include "stdafx.h" #include "RectCollider.h" RectCollider::RectCollider() { } RectCollider::~RectCollider() { } void RectCollider::GetWorldBox(const Transform * trans, Vector2* outBoxPos) { Vector2 vertices[4]; // 왼쪽하단 vertices[0] = Vector2(this->localMinPos.x, this->localMaxPos.y); // 왼쪽상단 vertices[1] = Vector2(this->localMinPos.x, this->localMinPos.y); // 오른쪽상단 vertices[2] = Vector2(this->localMaxPos.x, this->localMinPos.y); // 오른쪽하단 vertices[3] = Vector2(this->localMaxPos.x, this->localMaxPos.y); Matrix matFinal = trans->GetFinalMatrix(); for (int i = 0; i < 4; i++) outBoxPos[i] = vertices[i].TransformCoord(matFinal); } void RectCollider::GetWorldAABBMinMax(const Transform * trans, Vector2 * min, Vector2 * max) { Vector2 worldPos[4]; GetWorldBox(trans, worldPos); *min = worldPos[0]; *max = worldPos[0]; for (int i = 1; i < 4; i++) { if (min->x > worldPos[i].x) min->x = worldPos[i].x; if (min->y > worldPos[i].y) min->y = worldPos[i].y; if (max->x < worldPos[i].x) max->x = worldPos[i].x; if (max->y < worldPos[i].y) max->y = worldPos[i].y; } } void RectCollider::RenderGizmo(const Transform * trans) { Vector2 worldPos[4]; this->GetWorldBox(trans, worldPos); // OBB 박스 // 원래 기즈모 물체에 씌워주는 색은 초록색임 GIZMO->Line(worldPos[0], worldPos[1], 0xffffff00); GIZMO->Line(worldPos[1], worldPos[2], 0xffffff00); GIZMO->Line(worldPos[2], worldPos[3], 0xffffff00); GIZMO->Line(worldPos[3], worldPos[0], 0xffffff00); // AABB 박스 Vector2 minPos; Vector2 maxPos; this->GetWorldAABBMinMax(trans, &minPos, &maxPos); // 0xff808000 - 노란색인데 약간 어두운 노란색임 GIZMO->AABBBox(minPos, maxPos, 0xff808000); } void RectCollider::SetBound(const Vector2 * pCenter, const Vector2 * pHalfSize) { CircleCollider::SetBound(pCenter, pHalfSize); this->localMinPos = this->localCenter - this->halfSize; this->localMaxPos = this->localCenter + this->halfSize; } void RectCollider::RenderGizmoSpecialRed(Transform * trans) { Vector2 min, max; this->GetWorldAABBMinMax(trans, &min, &max); Vector2 pos = trans->GetWorldPosition(); Vector2 vertices[6]; float radius = max.y - min.y; for (int i = 0; i < 6; i++) { vertices[i].x = pos.x + cosf(2.0f * D3DX_PI / 6 * i - 30.0f / 180.0f * D3DX_PI) * radius; vertices[i].y = pos.y - sinf(2.0f * D3DX_PI / 6 * i - 30.0f / 180.0f * D3DX_PI) * radius; } for (int i = 0; i <= 4; i += 2) { GIZMO->Line(vertices[i], vertices[(i + 2) % 6], 0xffff0000); GIZMO->Line(vertices[i + 1], vertices[(i + 2) % 6 + 1], 0xfff0000); } GIZMO->Circle(pos, radius, 0xffff0000); } void RectCollider::RenderGizmoSpecialGreen(Transform * trans) { Vector2 min, max; this->GetWorldAABBMinMax(trans, &min, &max); Vector2 pos = trans->GetWorldPosition(); Vector2 vertices[10]; float radius = max.y - min.y; float subRadius = radius / 12 * 7; vertices[0].x = pos.x + cosf(2.0f * D3DX_PI / 6 - 2.0f * D3DX_PI / 12) * radius; vertices[0].y = pos.y - sinf(2.0f * D3DX_PI / 6 - 2.0f * D3DX_PI / 12) * radius; vertices[1].x = pos.x + cosf(2.0f * D3DX_PI / 2 - 2.0f * D3DX_PI / 12) * radius; vertices[1].y = pos.y - sinf(2.0f * D3DX_PI / 2 - 2.0f * D3DX_PI / 12) * radius; vertices[2].x = pos.x + cosf(2.0f * D3DX_PI / 3 * 2 - 2.0f * D3DX_PI / 12) * radius; vertices[2].y = pos.y - sinf(2.0f * D3DX_PI / 3 * 2 - 2.0f * D3DX_PI / 12) * radius; vertices[3].x = pos.x + cosf(-2.0f * D3DX_PI / 12) * radius; vertices[3].y = pos.y - sinf(-2.0f * D3DX_PI / 12) * radius; for (int i = 4; i < 10; i++) { vertices[i].x = pos.x + cosf(2.0f * D3DX_PI / 6 * (i-4)) * subRadius; vertices[i].y = pos.y - sinf(2.0f * D3DX_PI / 6 * (i-4)) * subRadius; } for (int i = 0; i < 4; i++) { if (i == 0) { GIZMO->Line(vertices[i], vertices[i + 4], 0xff00ff00); GIZMO->Line(vertices[i], vertices[i + 5], 0xff00ff00); } else if (i == 3) { GIZMO->Line(vertices[i], vertices[i + 1], 0xff00ff00); GIZMO->Line(vertices[i], vertices[i + 6], 0xff00ff00); } else { GIZMO->Line(vertices[i], vertices[i + 5], 0xff00ff00); GIZMO->Line(vertices[i], vertices[i + 6], 0xff00ff00); } } for (int i = 4; i < 7; i++) { GIZMO->Line(vertices[i], vertices[i + 3], 0xff00ff00); } GIZMO->Circle(pos, radius, 0xff00ff00); } void RectCollider::RenderGizmoSpecialBlue(Transform * trans) { Vector2 min, max; this->GetWorldAABBMinMax(trans, &min, &max); Vector2 pos = trans->GetWorldPosition(); Vector2 vertices[8]; float radius = max.y - min.y; //for (int i = 0; i < 4; i++) { // vertices[i].x = pos.x + cosf(2.0f * D3DX_PI / 4 * i + 45.0f / 180.0f * D3DX_PI) * radius; // vertices[i].y = pos.y - sinf(2.0f * D3DX_PI / 4 * i + 45.0f / 180.0f * D3DX_PI) * radius; //} float angle = 30.0f; vertices[0].x = pos.x + cosf(angle / 180.0f * D3DX_PI) * radius; vertices[0].y = pos.y - sinf(angle / 180.0f * D3DX_PI) * radius; vertices[1].x = pos.x + cosf(D3DX_PI - angle / 180.0f * D3DX_PI) * radius; vertices[1].y = pos.y - sinf(D3DX_PI - angle / 180.0f * D3DX_PI) * radius; vertices[2].x = pos.x + cosf(D3DX_PI + angle / 180.0f * D3DX_PI) * radius; vertices[2].y = pos.y - sinf(D3DX_PI + angle / 180.0f * D3DX_PI) * radius; vertices[3].x = pos.x + cosf(-angle / 180.0f * D3DX_PI) * radius; vertices[3].y = pos.y - sinf(-angle / 180.0f * D3DX_PI) * radius; float temp = fabs(vertices[0].x - vertices[1].x) / 3; vertices[4].x = vertices[0].x - temp; vertices[4].y = vertices[0].y; vertices[5].x = vertices[1].x + temp; vertices[5].y = vertices[1].y; vertices[6].x = vertices[2].x + temp; vertices[6].y = vertices[2].y; vertices[7].x = vertices[3].x - temp; vertices[7].y = vertices[3].y; GIZMO->Line(vertices[0], vertices[1], 0xff0000ff); GIZMO->Line(vertices[2], vertices[3], 0xff0000ff); GIZMO->Line(vertices[0], vertices[7], 0xff0000ff); GIZMO->Line(vertices[1], vertices[6], 0xff0000ff); GIZMO->Line(vertices[2], vertices[5], 0xff0000ff); GIZMO->Line(vertices[3], vertices[4], 0xff0000ff); GIZMO->Line(vertices[4], vertices[6], 0xff0000ff); GIZMO->Line(vertices[5], vertices[7], 0xff0000ff); GIZMO->Circle(pos, radius, 0xff0000ff); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef GADGET_UTILS_H #define GADGET_UTILS_H #ifdef GADGET_SUPPORT #include "modules/img/image.h" #ifdef OPERA_CONSOLE # include "modules/console/opconsoleengine.h" # define GADGETS_REPORT_TO_CONSOLE(a) do { OpGadgetUtils::ReportToConsole a; } while(0) # define GADGETS_REPORT_ERROR_TO_CONSOLE(a) do { OpGadgetUtils::ReportErrorToConsole a; } while(0) #else # define GADGETS_REPORT_TO_CONSOLE(a) do {} while (0) # define GADGETS_REPORT_ERROR_TO_CONSOLE(a) do {} while(0) #endif // OPERA_CONSOLE ////////////////////////////////////////////////////////////////////////// // OpGadgetStatus ////////////////////////////////////////////////////////////////////////// class OpGadgetStatus : public OpStatus { public: enum GadErrEnum { ERR_INVALID_ZIP = USER_ERROR + 1, ///< The zip archive is invalid. ERR_WRONG_WIDGET_FORMAT = USER_ERROR + 2, ///< The widget configuration document is invalid. ERR_WRONG_NAMESPACE = USER_ERROR + 3, ///< The gadget's config file is not using the correct namespace. (e.g. extensions need to be w3c widgets). ERR_CONFIGURATION_FILE_NOT_FOUND = USER_ERROR + 4, ///< The widget configuration document was not found. ERR_START_FILE_NOT_FOUND = USER_ERROR + 5, ///< The widget start file was not found. ERR_CONTENT_TYPE_NOT_SUPPORTED = USER_ERROR + 6, ///< The widget start file type is not supported by Opera. ERR_FEATURE_NOT_SUPPORTED = USER_ERROR + 7, ///< The feature which was specified as required is not supported. ERR_GADGET_TYPE_NOT_SUPPORTED = USER_ERROR + 8, ///< The widget type requested is not supported by this build of opera. ERR_BAD_PARAM = USER_ERROR + 9, ///< A feature contains a badly declared parameter. OK_UNKNOWN_FEATURE = USER_SUCCESS + 1, ///< The feature which was specified as not required is not supported. OK_SIGNATURE_VERIFICATION_IN_PROGRESS = USER_SUCCESS + 2 ///< The widget signature verification hasn't finished yet. }; }; typedef OP_STATUS OP_GADGET_STATUS; ////////////////////////////////////////////////////////////////////////// // OpGadgetUtils ////////////////////////////////////////////////////////////////////////// class OpGadgetUtils { public: #ifdef OPERA_CONSOLE static void ReportErrorToConsole(const uni_char* url, const uni_char* fmt, ...); static void ReportToConsole(const uni_char* url, OpConsoleEngine::Severity severity, const uni_char* fmt, ...); static void ReportToConsole(const uni_char* url, OpConsoleEngine::Severity severity, const uni_char* fmt, va_list args); #endif // OPERA_CONSOLE static BOOL IsAttrStringTrue(const uni_char* attr_str, BOOL dval = FALSE); static UINT32 AttrStringToI(const uni_char* attr_str, UINT32 dval = 0); static void AttrStringToI(const uni_char* attr_str, UINT32& result, OP_GADGET_STATUS &success); #if PATHSEPCHAR != '/' /** Convert a slash separated path to be delimited by the local system's * path separator. Any occurances of the local path seperator is replaced * by a slash. * @param pathstr Path to convert. */ static void ChangeToLocalPathSeparators(uni_char *pathstr); #endif static OP_GADGET_STATUS AppendToList(OpString &string, const char *str); static OP_STATUS NormalizeText(const uni_char *text, TempBuffer *result, uni_char bidi_marker = 0); static OP_STATUS GetTextNormalized(class XMLFragment *f, TempBuffer *result, uni_char bidi_marker = 0); static BOOL IsSpace(uni_char c); static BOOL IsUniWhiteSpace(uni_char c); static BOOL IsValidIRI(const uni_char* str, BOOL allow_wildcard = FALSE); }; ////////////////////////////////////////////////////////////////////////// // BufferContentProvider (Helper class for OpGadgetClass) ////////////////////////////////////////////////////////////////////////// class BufferContentProvider : public ImageContentProvider { public: static OP_STATUS Make(BufferContentProvider*& obj, char* data, UINT32 numbytes); ~BufferContentProvider() { OP_DELETEA(data); } OP_STATUS GetData(const char*& data, INT32& data_len, BOOL& more) { data = this->data; data_len = numbytes; more = FALSE; return OpStatus::OK; } OP_STATUS Grow() { return OpStatus::ERR; } void ConsumeData(INT32 len) { loaded = TRUE; } void Reset() {} void Rewind() {} BOOL IsLoaded() { return TRUE; } INT32 ContentType() { return content_type; } void SetContentType(INT32 type) { content_type = type; } INT32 ContentSize() { return numbytes; } BOOL IsEqual(ImageContentProvider* content_provider) { return FALSE; } private: BufferContentProvider(char* data, UINT32 numbytes) : data(data), numbytes(numbytes), content_type(0), loaded(FALSE) {} const char* data; UINT32 numbytes; INT32 content_type; BOOL loaded; }; ////////////////////////////////////////////////////////////////////////// // OpPersistentStorageListener ////////////////////////////////////////////////////////////////////////// class OpPersistentStorageListener { public: virtual ~OpPersistentStorageListener() { } virtual OP_STATUS SetPersistentData(const uni_char* section, const uni_char* key, const uni_char* value) = 0; virtual const uni_char* GetPersistentData(const uni_char* section, const uni_char* key) = 0; virtual OP_STATUS DeletePersistentData(const uni_char* section, const uni_char* key) = 0; virtual OP_STATUS GetPersistentDataItem(UINT32 idx, OpString& key, OpString& data) = 0; virtual OP_STATUS GetStoragePath(OpString& path) = 0; virtual OP_STATUS GetApplicationPath(OpString& path) { return OpStatus::ERR; } }; #endif // GADGET_SUPPORT #endif // !GADGET_UTILS_H
//Do not edit this file (unless you know what you are doing) #ifndef SOLUTION_H #define SOLUTION_H #include"matrix.h" #include"ode_solver.h" class solution { friend ostream &operator<<(ostream &, const solution &); public: matrix x; matrix g; matrix H; matrix y; static int f_calls; static int g_calls; static int H_calls; static void clear_calls(); solution(double = 0.0); solution(const matrix &); solution(double *, int); void fit_fun(matrix = 0.0); void grad(matrix = 0.0); void hess(matrix = 0.0); static double a; }; #endif
#ifndef INSTR_H #define INSTR_H #include <string> #include "sem.h" #include "expr.h" Expression* create_expression(Term* t); class Instr { public: /** * @return error code, 0 if nothing wrong happened. */ virtual int execute(Env*, Store*) = 0; }; class Call : public Instr, public Expression { public: Call(LTerm*); Call(LTerm*, int op); virtual int execute(Env*, Store*); virtual Val eval(Store* s, Env* e); private : std::string name; std::vector<Expression*> argument; }; class Assignement : public Instr, public Expression { public: Assignement(LTerm*); virtual int execute(Env*, Store*); virtual Val eval(Store* s, Env* e); std::string getVarName(); void setVarRef(int); private: std::string name; Expression* expr; int var_ref; }; class Return : public Instr, public SNode { public : Return(LTerm*); virtual int execute(Env*, Store*); private : Expression* expr; }; class If : public Instr, public SNode { public : If(LTerm*); virtual int execute(Env*, Store*); private : int executeList(Env*, Store*, std::vector<Instr*>&); Expression* expr; std::vector<Instr*> yes; std::vector<Instr*> no; }; class While : public Instr, public SNode { public : While(LTerm*); virtual int execute(Env*, Store*); private : int executeList(Env*, Store*, std::vector<Instr*>&); Expression* expr; std::vector<Instr*> yes; }; class Skip : public Instr, public SNode { public : Skip(LTerm *); virtual int execute(Env*, Store*); }; #endif
// // Created by 邦邦 on 2022/7/8. // #ifndef BB_FILE_H #define BB_FILE_H #include <string> #include <vector> #include <sys/stat.h> //S_IRWXU #include <unistd.h> //关闭文件描述符(close) namespace bb{ class file{ public: static size_t mkdir_pF(std::string &dir){ std::vector<std::string> dir_list{}; std::string str; for(auto &v:dir){ if(v == '.'){}else if(v == '/'){ if(!str.empty()){ dir_list.push_back(str); str += '/'; } }else{ str+=v; } } if(!str.empty()){ dir_list.push_back(str); } for(auto &v:dir_list){ if(access(("./"+v).c_str(),F_OK) == -1){ mkdir(("./"+v).c_str(),S_IRWXU); } } return dir_list.size(); } }; } #endif //BB_FILE_H
// Handout #1: Source code of a C++ Program, which // converts distance in miles to kilometers. #include "BigNaturalNumber.h" #include <iostream> //inclusion of support for doing input & output #include <vector> //inclusion of support for doing input & output #include <ctime> #include <time.h> #include <algorithm> #include <fstream> using namespace std; //declare access to standard stuff like cin, cout int main() { srand(time(NULL)); BigNaturalNumber x; BigNaturalNumber y; x.random(1000); y.random(1000); BigNaturalNumber z; cout << "Start Timer" << endl; //Where Timer Starts clock_t timer; timer = clock(); z = x * y; // Where Timer Ends timer = clock() - timer; cout << "First Number" << endl; for (int i = 0; i < x.number.size(); i++) { cout << x.number[i]; } cout << endl; cout << "Second Number" << endl; for (int i = 0; i < y.number.size(); i++) { cout << y.number[i]; } cout << endl; for (int i = 32; i >= 0; i--) { cout << "-"; } cout << endl; cout << "Answer" << endl; for (int i = 0; i < z.number.size(); i++) { cout << z.number[i]; } cout << endl; ofstream fout; fout.open("output.txt"); fout << "This took " << (((float)timer) / CLOCKS_PER_SEC) << " seconds" << endl; fout.close(); cout << "All results have been saved to output.txt." << endl; cout << endl << "Please enter any charcter and a return to quit the program." << endl; // Wait for the user input before ending the program char inputCharacter; // Declare a variable for storing a character input from the keyboard cin >> inputCharacter; // Wait to read in a character input from the keyboard //Finish the program and return the control to the operating system. return 0; } //End of the main function.
/********************************************************************** *Project : EngineTask * *Author : Jorge Cásedas * *Starting date : 24/06/2020 * *Ending date : 03/07/2020 * *Purpose : Creating a 3D engine that can be used later on for developing a playable demo, with the engine as static library * **********************************************************************/ #pragma once namespace engine { class Message; class MessageBus; /// /// Base class for creating objects that will be waiting for messages /// class MessageListener { MessageBus* messageBus; public: MessageListener(MessageBus& bus); virtual void UseMessage(Message* message); }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2007 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 SVG_SUPPORT #include "modules/svg/src/svgpch.h" #include "modules/svg/src/SVGPattern.h" #ifdef SVG_SUPPORT_PATTERNS #include "modules/svg/src/AttrValueStore.h" #include "modules/svg/src/SVGDocumentContext.h" #include "modules/svg/src/SVGChildIterator.h" #include "modules/svg/src/SVGTraverse.h" #include "modules/svg/src/svgpaintnode.h" #include "modules/libvega/vegafill.h" #include "modules/libvega/vegarenderer.h" #include "modules/libvega/vegarendertarget.h" OP_STATUS SVGPattern::GetFill(VEGAFill** vfill, VEGATransform& vfilltrans, SVGPainter* painter, SVGPaintNode* context_node) { if (m_target) { // GetFill without PutFill (not a good idea) VEGARenderTarget::Destroy(m_target); m_target = NULL; } SVGBoundingBox bbox; if (m_units == SVGUNITS_OBJECTBBOX || !m_viewbox && m_content_units == SVGUNITS_OBJECTBBOX) bbox = context_node->GetBBox(); SVGRect pattern_rect = m_pattern_rect; if (m_units == SVGUNITS_OBJECTBBOX) { // Scale with bounding box // [ (maxx-minx) 0 0 (maxy-miny) minx miny ] SVGMatrix objbbox_transform; objbbox_transform.SetValues(bbox.maxx - bbox.minx, 0, 0, bbox.maxy - bbox.miny, bbox.minx, bbox.miny); pattern_rect = objbbox_transform.ApplyToRect(pattern_rect); } SVGNumber expansion = painter->GetTransform().GetExpansionFactor() * m_transform.GetExpansionFactor(); // Dimension the surface to draw on SVGNumber bitmap_w = pattern_rect.width * expansion; SVGNumber bitmap_h = pattern_rect.height * expansion; // Sanity check size of pattern surface OpRect pattern_pixel_dim(0, 0, bitmap_w.GetIntegerValue(), bitmap_h.GetIntegerValue()); if (pattern_pixel_dim.width == 0) pattern_pixel_dim.width = 1; if (pattern_pixel_dim.height == 0) pattern_pixel_dim.height = 1; // Shrink the bitmap so that it fits in the space available OpStatus::Ignore(SVGUtils::ShrinkToFit(pattern_pixel_dim.width, pattern_pixel_dim.height, m_max_res_width, m_max_res_height)); SVGMatrix pattern_paint_transform; // Compensate for the rounding (truncation) pattern_paint_transform.LoadScale(SVGNumber(pattern_pixel_dim.width) / pattern_rect.width, SVGNumber(pattern_pixel_dim.height) / pattern_rect.height); SVGRect dummy_clip_rect; SVGMatrix viewboxtransform; SVGRect pattern_vp(0, 0, pattern_rect.width, pattern_rect.height); RETURN_IF_ERROR(SVGUtils::GetViewboxTransform(pattern_vp, m_viewbox ? &m_viewbox->rect : NULL, m_aspectratio, viewboxtransform, dummy_clip_rect)); pattern_paint_transform.PostMultiply(viewboxtransform); // Should not apply this if we have a viewbox if (!m_viewbox && m_content_units == SVGUNITS_OBJECTBBOX) { // [ (maxx-minx) 0 0 (maxy-miny) 0 0 ] SVGMatrix objbbox_transform; objbbox_transform.SetValues(bbox.maxx - bbox.minx, 0, 0, bbox.maxy - bbox.miny, 0, 0); pattern_paint_transform.PostMultiply(objbbox_transform); } VEGARenderer pattern_renderer; RETURN_IF_ERROR(pattern_renderer.Init(pattern_pixel_dim.width, pattern_pixel_dim.height)); RETURN_IF_ERROR(pattern_renderer.createIntermediateRenderTarget(&m_target, pattern_pixel_dim.width, pattern_pixel_dim.height)); SVGPainter pattern_painter; RETURN_IF_ERROR(pattern_painter.BeginPaint(&pattern_renderer, m_target, pattern_pixel_dim)); #ifdef PI_VIDEO_LAYER pattern_painter.SetAllowOverlay(FALSE); #endif // PI_VIDEO_LAYER pattern_painter.SetTransform(pattern_paint_transform); pattern_painter.SetClipRect(pattern_pixel_dim); pattern_painter.Clear(0, &pattern_pixel_dim); pattern_painter.SetFlatness(painter->GetFlatness()); if (m_content_node) m_content_node->PaintContent(&pattern_painter); pattern_painter.EndPaint(); RETURN_IF_ERROR(m_target->getImage(vfill)); (*vfill)->setSpread(VEGAFill::SPREAD_REPEAT); (*vfill)->setQuality(VEGAFill::QUALITY_LINEAR); // vfilltrans = T(pattern.x, pattern.y) * PatternTransform m_transform.CopyToVEGATransform(vfilltrans); VEGATransform tmp; tmp.loadTranslate(pattern_rect.x.GetVegaNumber(), pattern_rect.y.GetVegaNumber()); vfilltrans.multiply(tmp); // Compensate for the rounding (truncation) SVGNumberPair inv_pat_scale(pattern_rect.width / pattern_pixel_dim.width, pattern_rect.height / pattern_pixel_dim.height); tmp.loadScale(inv_pat_scale.x.GetVegaNumber(), inv_pat_scale.y.GetVegaNumber()); vfilltrans.multiply(tmp); return OpStatus::OK; } void SVGPattern::PutFill(VEGAFill* vfill) { VEGARenderTarget::Destroy(m_target); m_target = NULL; } SVGPattern::~SVGPattern() { SVGObject::DecRef(m_viewbox); SVGObject::DecRef(m_aspectratio); OP_DELETE(m_content_node); VEGARenderTarget::Destroy(m_target); } // // m_transform (PatternTransform) = m_transform * S(1 / pat_scale) [or S^-1(pat_scale)] // Pattern Canvas CTM = S(pat_scale) * ViewboxTransform {* BBOX-dim | no viewbox && content units is OBB} // // where pat_scale is: <canvas expansion> * <size compensation> // struct SVGPatternParameters { SVGLengthObject* x; SVGLengthObject* y; SVGLengthObject* width; SVGLengthObject* height; }; OP_STATUS SVGPattern::FetchValues(HTML_Element* pattern_element, SVGElementResolver* resolver, SVGDocumentContext* doc_ctx, SVGPatternParameters* params, HTML_Element** content_root) { OP_ASSERT(pattern_element && pattern_element->IsMatchingType(Markup::SVGE_PATTERN, NS_SVG)); HTML_Element* inh_pattern_element = SVGUtils::FindHrefReferredNode(resolver, doc_ctx, pattern_element); if (inh_pattern_element) { if (inh_pattern_element->IsMatchingType(Markup::SVGE_PATTERN, NS_SVG)) { OP_STATUS status = resolver->FollowReference(inh_pattern_element); if (OpStatus::IsSuccess(status)) { doc_ctx->RegisterDependency(pattern_element, inh_pattern_element); status = FetchValues(inh_pattern_element, resolver, doc_ctx, params, content_root); resolver->LeaveReference(inh_pattern_element); RETURN_IF_ERROR(status); } } } // "If this element has no children, and the referenced element does (possibly due to its // own href attribute), then this element inherits the children from the referenced element." if (SVGUtils::HasChildren(pattern_element)) *content_root = pattern_element; if (AttrValueStore::HasTransform(pattern_element, Markup::SVGA_PATTERNTRANSFORM, NS_IDX_SVG)) { SVGMatrix matrix; AttrValueStore::GetMatrix(pattern_element, Markup::SVGA_PATTERNTRANSFORM, matrix); SetTransform(matrix); } if (AttrValueStore::HasObject(pattern_element, Markup::SVGA_PATTERNCONTENTUNITS, NS_IDX_SVG)) { SVGUnitsType units; AttrValueStore::GetUnits(pattern_element, Markup::SVGA_PATTERNCONTENTUNITS, units, SVGUNITS_USERSPACEONUSE); SetContentUnits(units); } if (AttrValueStore::HasObject(pattern_element, Markup::SVGA_PATTERNUNITS, NS_IDX_SVG)) { SVGUnitsType units; AttrValueStore::GetUnits(pattern_element, Markup::SVGA_PATTERNUNITS, units, SVGUNITS_OBJECTBBOX); SetUnits(units); } SVGRectObject *viewbox = NULL; AttrValueStore::GetViewBox(pattern_element, &viewbox); if (viewbox) SetViewBox(viewbox); SVGAspectRatio* ar = NULL; AttrValueStore::GetPreserveAspectRatio(pattern_element, ar); if (ar) SetAspectRatio(ar); AttrValueStore::GetLength(pattern_element, Markup::SVGA_X, &params->x, params->x); AttrValueStore::GetLength(pattern_element, Markup::SVGA_Y, &params->y, params->y); AttrValueStore::GetLength(pattern_element, Markup::SVGA_WIDTH, &params->width, params->width); AttrValueStore::GetLength(pattern_element, Markup::SVGA_HEIGHT, &params->height, params->height); return OpStatus::OK; } void SVGPattern::ResolvePatternParameters(const SVGPatternParameters& params, const SVGValueContext& vcxt) { m_pattern_rect.x = SVGUtils::ResolveLengthWithUnits(params.x, SVGLength::SVGLENGTH_X, m_units, vcxt); m_pattern_rect.y = SVGUtils::ResolveLengthWithUnits(params.y, SVGLength::SVGLENGTH_Y, m_units, vcxt); m_pattern_rect.width = SVGUtils::ResolveLengthWithUnits(params.width, SVGLength::SVGLENGTH_X, m_units, vcxt); m_pattern_rect.height = SVGUtils::ResolveLengthWithUnits(params.height, SVGLength::SVGLENGTH_Y, m_units, vcxt); } OP_STATUS SVGPattern::GeneratePatternContent(SVGDocumentContext* doc_ctx, SVGElementResolver* resolver, const SVGValueContext& vcxt, HTML_Element *pattern_element, HTML_Element* content_root, HTML_Element* context_element) { SVGBoundingBox bbox; if (m_content_units == SVGUNITS_OBJECTBBOX || m_units == SVGUNITS_OBJECTBBOX) { // We need the bounding box SVGNumberPair vp(vcxt.viewport_width, vcxt.viewport_height); RETURN_IF_ERROR(GetElementBBox(doc_ctx, context_element, vp, bbox)); } // Determine limits (consider doing this based on painting // context, rt-size, instead). int max_width = INT_MAX; int max_height = INT_MAX; SVGUtils::LimitCanvasSize(doc_ctx->GetDocument(), doc_ctx->GetVisualDevice(), max_width, max_height); m_max_res_width = max_width; m_max_res_height = max_height; SVGRect pattern_rect = m_pattern_rect; if (m_units == SVGUNITS_OBJECTBBOX) { // Scale with bounding box // [ (maxx-minx) 0 0 (maxy-miny) minx miny ] SVGMatrix objbbox_transform; objbbox_transform.SetValues(bbox.maxx - bbox.minx, 0, 0, bbox.maxy - bbox.miny, bbox.minx, bbox.miny); pattern_rect = objbbox_transform.ApplyToRect(pattern_rect); } SVGMatrix canvas_transform; SVGRect dummy_clip_rect; SVGMatrix viewboxtransform; SVGRect pattern_vp(0, 0, pattern_rect.width, pattern_rect.height); RETURN_IF_ERROR(SVGUtils::GetViewboxTransform(pattern_vp, m_viewbox ? &m_viewbox->rect : NULL, m_aspectratio, viewboxtransform, dummy_clip_rect)); canvas_transform.PostMultiply(viewboxtransform); // Should not apply this if we have a viewbox if (!m_viewbox && m_content_units == SVGUNITS_OBJECTBBOX) { // [ (maxx-minx) 0 0 (maxy-miny) 0 0 ] SVGMatrix objbbox_transform; objbbox_transform.SetValues(bbox.maxx - bbox.minx, 0, 0, bbox.maxy - bbox.miny, 0, 0); canvas_transform.PostMultiply(objbbox_transform); } SVGNullCanvas canvas; canvas.SetDefaults(doc_ctx->GetRenderingQuality()); canvas.ConcatTransform(canvas_transform); SVGElementResolverStack resolver_stack(resolver); RETURN_IF_ERROR(resolver_stack.Push(content_root)); SVGNumberPair pattern_viewport; // FIXME: Which document context here? External vs. same document. // (Under investigation - see: http://lists.w3.org/Archives/Public/www-svg/2010Feb/0082.html) RETURN_IF_ERROR(SVGUtils::GetViewportForElement(pattern_element, doc_ctx, pattern_viewport)); SVGVectorImageNode* pattern_content_node = OP_NEW(SVGVectorImageNode, ()); if (!pattern_content_node) return OpStatus::ERR_NO_MEMORY; pattern_content_node->Reset(); m_content_node = pattern_content_node; SVGRenderingTreeChildIterator rtci; SVGPaintTreeBuilder pattern_content_builder(&rtci, pattern_content_node); pattern_content_builder.SetCurrentViewport(pattern_viewport); pattern_content_builder.SetDocumentContext(doc_ctx); pattern_content_builder.SetupResolver(resolver); pattern_content_builder.SetCanvas(&canvas); return SVGTraverser::Traverse(&pattern_content_builder, content_root, NULL); } class AutoSVGPattern { public: AutoSVGPattern(SVGPattern* pat) : m_ref(pat) {} ~AutoSVGPattern() { SVGPaintServer::DecRef(m_ref); } SVGPattern* operator->() { return m_ref; } SVGPattern* get() { return m_ref; } SVGPattern* release() { SVGPattern* pat = m_ref; m_ref = NULL; return pat; } private: SVGPattern* m_ref; }; OP_STATUS SVGPattern::Create(HTML_Element *pattern_element, HTML_Element* context_element, SVGElementResolver* resolver, SVGDocumentContext* doc_ctx, const SVGValueContext& vcxt, SVGPattern **outpat) { OP_ASSERT(outpat); OP_ASSERT(pattern_element && pattern_element->IsMatchingType(Markup::SVGE_PATTERN, NS_SVG)); RETURN_IF_ERROR(resolver->FollowReference(pattern_element)); OP_STATUS status; HTML_Element* content_root = NULL; AutoSVGPattern pattern(OP_NEW(SVGPattern, ())); if (pattern.get()) { SVGPatternParameters params; // This is the default for x, y, width and height SVGLengthObject def_dim; params.x = params.y = &def_dim; params.width = params.height = &def_dim; status = pattern->FetchValues(pattern_element, resolver, doc_ctx, &params, &content_root); if (OpStatus::IsSuccess(status)) pattern->ResolvePatternParameters(params, vcxt); } else { status = OpStatus::ERR_NO_MEMORY; } // We remove the pattern element from the visited set here, since // we may need to add one of it's parents further down resolver->LeaveReference(pattern_element); RETURN_IF_ERROR(status); // "A negative value is an error. // A value of zero disables rendering of the element // (i.e., no paint is applied). // If the attribute is not specified, the effect is as if a // value of zero were specified." // // Treating invalid (negative) values as zero also. if (pattern->m_pattern_rect.height <= 0 || pattern->m_pattern_rect.width <= 0) return OpSVGStatus::COLOR_IS_NONE; // If there are no content elements - disable rendering. if (!content_root) return OpSVGStatus::COLOR_IS_NONE; RETURN_IF_ERROR(pattern->GeneratePatternContent(doc_ctx, resolver, vcxt, pattern_element, content_root, context_element)); *outpat = pattern.release(); return OpStatus::OK; } #endif // SVG_SUPPORT_PATTERNS #endif // SVG_SUPPORT
#pragma once //////////////////////////////////////////////////////////////////////////////// #include <cellogram/common.h> #include <geogram/mesh/mesh.h> #include <Eigen/Dense> #include <vector> #include <queue> //////////////////////////////////////////////////////////////////////////////// namespace cellogram { struct edge { int x, y; double w; edge(void) : x(), y(), w() {} edge(int a, int b, double c) : x(a), y(b), w(c) {} bool operator< (const edge &e) const { return w > e.w; // Extract min-cost edges first } }; void dijkstra(std::vector<std::vector<edge> > &graph, std::vector<int> &prev, std::vector<int> &dist, int source); // Build an undirected adjacency graph for the vertices of a triangle mesh void build_adjacency_graph(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, std::vector<std::vector<int>> &ajd); // Propagate a scalar from the given sources, ensuring a given grading void dijkstra_grading(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, Eigen::VectorXd &S, double grading, const std::vector<int> &sources); }
#include "utils.hpp" #include <iostream> char *ft_memcat(char *dest, const char *src, size_t nb) { size_t i; int len_dest; i = 0; (void)nb; len_dest = (int)ft_strlen((const char*)dest); while (i < nb) { dest[len_dest + i] = src[i]; i++; } return (dest); }
#pragma once #include <type_traits> namespace prv { namespace lex { namespace detail { //=== string_cat ===// template <typename Lhs, typename Rhs> struct string_cat_impl; template <template <char...> class String, char... Lhs, char... Rhs> struct string_cat_impl<String<Lhs...>, String<Rhs...>> { using type = String<Lhs..., Rhs...>; }; template <typename Lhs, typename Rhs> using string_cat = typename string_cat_impl<Lhs, Rhs>::type; //=== check_string_size ===// template <typename T, std::size_t Size, std::size_t MaxSize> struct check_string_size { static_assert(Size <= MaxSize, "string out of range"); using type = T; }; } // namespace detail } // namespace lex } // namespace prv // expands to String<Chars[I]> if that is not null // String<> otherwise // // the range check inside String<Chars[I]> prevents reading out-of-bound string literal if it is // instantiated #define PRV_LEX_DETAIL_STRING_TAKE(String, Chars, I) \ std::conditional_t<(I < sizeof(Chars) && Chars[I] != 0), \ String<(I >= sizeof(Chars)) ? 0 : Chars[I]>, String<>> // recursively split the string in two #define PRV_LEX_DETAIL_STRING2(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING_TAKE(String, Chars, I), \ PRV_LEX_DETAIL_STRING_TAKE(String, Chars, I + 1)> #define PRV_LEX_DETAIL_STRING4(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING2(String, Chars, I), \ PRV_LEX_DETAIL_STRING2(String, Chars, I + 2)> #define PRV_LEX_DETAIL_STRING8(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING4(String, Chars, I), \ PRV_LEX_DETAIL_STRING4(String, Chars, I + 4)> #define PRV_LEX_DETAIL_STRING16(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING8(String, Chars, I), \ PRV_LEX_DETAIL_STRING8(String, Chars, I + 8)> #define PRV_LEX_DETAIL_STRING32(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING16(String, Chars, I), \ PRV_LEX_DETAIL_STRING16(String, Chars, I + 16)> #define PRV_LEX_DETAIL_STRING64(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING32(String, Chars, I), \ PRV_LEX_DETAIL_STRING32(String, Chars, I + 32)> #define PRV_LEX_DETAIL_STRING128(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING64(String, Chars, I), \ PRV_LEX_DETAIL_STRING64(String, Chars, I + 64)> #define PRV_LEX_DETAIL_STRING256(String, Chars, I) \ prv::lex::detail::string_cat<PRV_LEX_DETAIL_STRING128(String, Chars, I), \ PRV_LEX_DETAIL_STRING128(String, Chars, I + 128)> #define PRV_LEX_DETAIL_STRING(String, Chars) \ prv::lex::detail::check_string_size< \ PRV_LEX_DETAIL_STRING256(String, Chars, 0), sizeof(Chars) - 1, 256>::type
#pragma once #include "ScalarStorage.hpp" class VariableStorageTag{}; class VariableDeltaStorageTag{}; template<class Type> using VariableStorage = ScalarStorage<Type, VariableStorageTag>; template<class Type> using VariableDeltaStorage = ScalarStorage<Type, VariableDeltaStorageTag>;
#include "core/pch.h" #include "modules/libgogi/mde.h" #ifdef MDE_OPENGL_PAINTING #ifdef WIN32 #pragma comment (lib, "opengl32.lib") #define WINGDIAPI #define APIENTRY __stdcall #endif #include <GL/gl.h> #include <stdlib.h> #include <assert.h> //MDE_BUFFER *gl_screen_buffer; struct MDE_BUFFER_GL_INFO { unsigned int texture; void *lockdata; MDE_RECT lockarea; int tex_w, tex_h; }; int GetNearestPowerOfTwo(int val) { int i; for(i = 31; i >= 0; i--) if ((val - 1) & (1<<i)) break; return (1<<(i + 1)); } int MDE_GL_FORMAT(MDE_FORMAT format) { switch(format) { case MDE_FORMAT_BGRA32: return GL_BGRA_EXT; case MDE_FORMAT_BGR24: return GL_BGR_EXT; default: MDE_ASSERT(FALSE); return GL_RGBA; } } MDE_BUFFER *MDE_CreateBuffer(int w, int h, MDE_FORMAT format, int pal_len) { if (format != MDE_FORMAT_BGRA32 && format != MDE_FORMAT_BGR24) { MDE_ASSERT(0); return NULL; } MDE_BUFFER *buf = OP_NEW(MDE_BUFFER, ()); if (!buf) return NULL; MDE_InitializeBuffer(w, h, MDE_GetBytesPerPixel(format) * w, format, NULL, NULL, buf); MDE_BUFFER_GL_INFO *info = OP_NEW(MDE_BUFFER_GL_INFO, ()); if (!info) { MDE_DeleteBuffer(buf); return NULL; } buf->user_data = info; info->texture = 0; info->lockdata = NULL; info->tex_w = GetNearestPowerOfTwo(buf->w); info->tex_h = GetNearestPowerOfTwo(buf->h); buf->stride = info->tex_w * MDE_GetBytesPerPixel(buf->format); return buf; } void MDE_DeleteBuffer(MDE_BUFFER *&buf) { if (buf) { MDE_BUFFER_GL_INFO *info = (MDE_BUFFER_GL_INFO *) buf->user_data; if (info) { if (info->texture) glDeleteTextures(1, &info->texture); OP_DELETE(info); } char *data_ptr = (char*) buf->data; OP_DELETEA(data_ptr); OP_DELETEA(buf->pal); OP_DELETE(buf); buf = NULL; } } void* MDE_LockBuffer(MDE_BUFFER *buf, const MDE_RECT &rect, int &stride, bool readable) { MDE_BUFFER_GL_INFO *info = (MDE_BUFFER_GL_INFO *) buf->user_data; MDE_ASSERT(!info->lockdata); stride = buf->stride; info->lockdata = OP_NEWA(unsigned char, stride*info->tex_h); if (!info->lockdata) return NULL; info->lockarea = rect; if (readable) { if (info->texture) { glBindTexture(GL_TEXTURE_2D, info->texture); glGetTexImage(GL_TEXTURE_2D, 0, MDE_GL_FORMAT(buf->format), GL_UNSIGNED_BYTE, info->lockdata); glBindTexture(GL_TEXTURE_2D, 0); } } return ((unsigned char*)info->lockdata) + stride*rect.y + MDE_GetBytesPerPixel(buf->format)*rect.x; } void MDE_UnlockBuffer(MDE_BUFFER *buf, bool changed) { MDE_BUFFER_GL_INFO *info = (MDE_BUFFER_GL_INFO *) buf->user_data; MDE_ASSERT(info->lockdata); if (changed) { if (info->texture) { MDE_RECT rect = info->lockarea; glBindTexture(GL_TEXTURE_2D, info->texture); glPixelStorei(GL_UNPACK_ROW_LENGTH, buf->stride/MDE_GetBytesPerPixel(buf->format)); glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x, rect.y, rect.w, rect.h, MDE_GL_FORMAT(buf->format), GL_UNSIGNED_BYTE, ((unsigned char*)info->lockdata) + buf->stride*rect.y + MDE_GetBytesPerPixel(buf->format)*rect.x); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glBindTexture(GL_TEXTURE_2D, 0); } else { glGenTextures(1, &info->texture); glBindTexture(GL_TEXTURE_2D, info->texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, MDE_GetBytesPerPixel(buf->format), info->tex_w, info->tex_h, 0, MDE_GL_FORMAT(buf->format), GL_UNSIGNED_BYTE, info->lockdata); glBindTexture(GL_TEXTURE_2D, 0); } } unsigned char *ptr = (unsigned char*)info->lockdata; OP_DELETEA(ptr); info->lockdata = NULL; } // == PAINTING ================================================================ void DrawQuad(int x, int y, int w, int h, float ss = 0.f, float st = 0.f, float es = 1.0f, float et = 1.0f) { glBegin(GL_QUADS); glTexCoord2f(ss, st); glVertex2i(x, y); glTexCoord2f(es, st); glVertex2i(x + w, y); glTexCoord2f(es, et); glVertex2i(x + w, y + h); glTexCoord2f(ss, et); glVertex2i(x, y + h); glEnd(); } void MDE_SetColor(unsigned int col, MDE_BUFFER *dstbuf) { dstbuf->col = col; } void MDE_SetClipRect(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); dstbuf->clip = MDE_RectClip(rect, dstbuf->outer_clip); MDE_RECT r = rect; r.x += dstbuf->ofs_x; r.y += dstbuf->ofs_y; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); r.y = viewport[3] - (r.y + r.h); glScissor(r.x, r.y, r.w, r.h); } void MDE_DrawBuffer(MDE_BUFFER *srcbuf, const MDE_RECT &dst, int srcx, int srcy, MDE_BUFFER *dstbuf) { MDE_DrawBufferStretch(srcbuf, dst, MDE_MakeRect(srcx, srcy, dst.w, dst.h), dstbuf); } void MDE_DrawBufferStretch(MDE_BUFFER *srcbuf, const MDE_RECT &dst, const MDE_RECT &src, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); if (srcbuf->method == MDE_METHOD_ALPHA) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } MDE_BUFFER_GL_INFO *info = (MDE_BUFFER_GL_INFO *) srcbuf->user_data; if (info) glBindTexture(GL_TEXTURE_2D, info->texture); if (srcbuf->method == MDE_METHOD_COLOR) { glColor4ub(MDE_COL_R(dstbuf->col), MDE_COL_G(dstbuf->col), MDE_COL_B(dstbuf->col), MDE_COL_A(dstbuf->col)); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else glColor4ub(255, 255, 255, 255); DrawQuad(dst.x + dstbuf->ofs_x, dst.y + dstbuf->ofs_y, dst.w, dst.h, (float)(src.x)/(float)info->tex_w, (float)(src.y)/(float)info->tex_h, (float)(src.x+src.w)/(float)info->tex_w, (float)(src.y+src.h)/(float)info->tex_h); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_BLEND); } void MDE_DrawBufferData(MDE_BUFFER_DATA *srcdata, MDE_BUFFER_INFO *srcinf, int src_stride, const MDE_RECT &dst, int srcx, int srcy, MDE_BUFFER *dstbuf) { MDE_DrawBufferDataStretch(srcdata, srcinf, src_stride, dst, MDE_MakeRect(srcx, srcy, srcdata->w - srcx, srcdata->h - srcy), dstbuf); } void MDE_DrawBufferDataStretch(MDE_BUFFER_DATA *srcdata, MDE_BUFFER_INFO *srcinf, int src_stride, const MDE_RECT &dst, const MDE_RECT &src, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); if (srcinf->method == MDE_METHOD_COLOR) glColor4ub(MDE_COL_R(srcinf->col), MDE_COL_G(srcinf->col), MDE_COL_B(srcinf->col), MDE_COL_A(srcinf->col)); else glColor4ub(255, 255, 255, 255); DrawQuad(dst.x + dstbuf->ofs_x, dst.y + dstbuf->ofs_y, dst.w, dst.h); } void MDE_DrawRect(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); glColor4ub(MDE_COL_R(dstbuf->col), MDE_COL_G(dstbuf->col), MDE_COL_B(dstbuf->col), MDE_COL_A(dstbuf->col)); MDE_RECT r = rect; r.x += dstbuf->ofs_x; r.y += dstbuf->ofs_y; glBegin(GL_LINE_STRIP); glVertex2i(r.x, r.y); glVertex2i(r.x + r.w - 1, r.y); glVertex2i(r.x + r.w - 1, r.y + r.h - 1); glVertex2i(r.x, r.y + r.h - 1); glVertex2i(r.x, r.y); glEnd(); } void MDE_DrawRectFill(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); glColor4ub(MDE_COL_R(dstbuf->col), MDE_COL_G(dstbuf->col), MDE_COL_B(dstbuf->col), MDE_COL_A(dstbuf->col)); DrawQuad(rect.x + dstbuf->ofs_x, rect.y + dstbuf->ofs_y, rect.w, rect.h); } void MDE_DrawRectInvert(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); glColor4ub(0, 0, 0, 128); DrawQuad(rect.x + dstbuf->ofs_x, rect.y + dstbuf->ofs_y, rect.w, rect.h); } void MDE_DrawEllipse(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); } void MDE_DrawEllipseFill(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); } void MDE_DrawEllipseInvertFill(const MDE_RECT &rect, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); } void MDE_DrawLine(int x1, int y1, int x2, int y2, MDE_BUFFER *dstbuf) { //MDE_ASSERT(dstbuf == gl_screen_buffer); glColor4ub(MDE_COL_R(dstbuf->col), MDE_COL_G(dstbuf->col), MDE_COL_B(dstbuf->col), MDE_COL_A(dstbuf->col)); glBegin(GL_LINES); glVertex2i(x1 + dstbuf->ofs_x, y1 + dstbuf->ofs_y); glVertex2i(x2 + dstbuf->ofs_x, y2 + dstbuf->ofs_y); glEnd(); } void MDE_DrawLineInvert(int x1, int y1, int x2, int y2, MDE_BUFFER *dstbuf) { // FIXME: MDE_ASSERT(0); //MDE_ASSERT(dstbuf == gl_screen_buffer); glColor4ub(MDE_COL_R(dstbuf->col), MDE_COL_G(dstbuf->col), MDE_COL_B(dstbuf->col), MDE_COL_A(dstbuf->col)); glBegin(GL_LINES); glVertex2i(x1 + dstbuf->ofs_x, y1 + dstbuf->ofs_y); glVertex2i(x2 + dstbuf->ofs_x, y2 + dstbuf->ofs_y); glEnd(); } bool MDE_UseMoveRect() { return false; } void MDE_MoveRect(const MDE_RECT &rect, int dx, int dy, MDE_BUFFER *dstbuf) { MDE_ASSERT(0); } #endif // MDE_OPENGL_PAINTING
#pragma once #include "common_def.h" #include "lock.h" namespace sj { enum UNIQUE_ID_TYPE { UIT_UDP_SID = 0, UIT_TCP_SID = 1, UIT_COUNT, UIT_MAX_COUNT = 0xFF, }; unid_t GetUniqueID(UNIQUE_ID_TYPE uit) { static struct { unid_t _index = 0; mutex_lock _lock; }idxs[UIT_COUNT]; mutex_lock_guard _l(idxs[uit]._lock); idxs[uit]._index ++; return (idxs[uit]._index << 8) | (uit & UIT_MAX_COUNT); } }
#include <stdio.h> #include<stdlib.h> #include <math.h> //reindel john a. raneses void scan_data(char , float ); float do_next_op(char , float , float ); int main() { printf("Press enter to use this calculator"); scan_data('w',1); return 0; } void scan_data(char sign, float num) { char op, oo; float result; result = 0; do { scanf("%c", &oo); scanf("%c", &op); if(op=='q'||op=='Q') { printf("Final result is %1.1f\n", result); exit(0); } else { scanf("%f", &num); result = do_next_op(op, num, result); } }while(op!='q'||op!='Q'); } float do_next_op(char oper, float num, float total) { switch(oper) { case('^'): total = pow(total,num); printf("result so far is %1.1f\n", total); return total; break; case('*'): total = total * num; printf("result so far is %1.1f\n",total); return total; break; case('/'): if(num>0) { total=total/num; printf("result so far is %1.1f\n", total); return total; break; } else { printf("undefined\n"); printf("result so far is %1.1f\n", total); return total; break; } case('+'): total=total+num; printf("result so far is %1.1f\n", total); return total; break; case('-'): total=total-num; printf("result so far is %1.1f\n", total); return total; break; case('q'): printf("final result is %1.1f\n", total); exit(0); default: break; } }
#include<iostream> using namespace std; int main() { int n; cout << "Enter the size of the array \t"; cin >> n; int arr[n]; cout << "Enter values \t"; for (int i = 0; i < n; i++) { cout << "Enter value " << i + 1 << " : "; cin >> arr[i]; } cout << "\n"; int a, b, c; cout << "Enter value of a , b , c" << endl; cin >> a; cin>> b; cin>> c; int flag = 0; for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if ((abs(arr[i] - arr[j]) <= a) && (abs(arr[j] - arr[k]) <= b) && (abs(arr[i] - arr[k]) <= c)) { flag++; } } } } cout << flag; }
#include <iostream> #include <cstdio> using namespace std; void fun(int x, int y); int main() { while(1) { int a, b; cin >> a >> b; fun(a, b); // cout << a << endl << a * b / a << endl; } return 0; } void fun(int x, int y) { int m = x; int n = y; int z = 1; while(z) { z = x % y; x = y; y = z; } cout << x << endl << m * n / x << endl; }
//王者荣耀之后的新阶段第一题就如此尴尬 //刚开始想的那个思路如此麻烦 最终都没做出来 //然后突然想出另一个思路,感觉还很简单 试了下,不到3分钟就accept了 //论思路的重要性 //45MS 8.07% int quicksort(vector<Interval>& data,int low,int high){ int partition(vector<Interval>& data,int low,int high); if ((high-low)<1){ return 0; } int middle=partition(data,low,high-1); quicksort(data,low,middle); quicksort(data,middle+1,high); return 0; } int partition(vector<Interval>& data,int low,int high){ int backup_low=low; int backup_high=high; Interval middle_data=data[low]; for(;low<high;){ for(;low<high;){ if(data[high].start>middle_data.start){ high=high-1; }else{ data[low]=data[high]; low=low+1; break; } } for(;low<high;){ if(data[low].start<middle_data.start){ low=low+1; }else{ data[high]=data[low]; high=high-1; break; } } } int middle=low; data[low]=middle_data; low=backup_low; high=backup_high; return middle; } class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { intervals.push_back(newInterval); if(intervals.size()<=1){ return intervals; } quicksort(intervals, 0 ,intervals.size()); vector<Interval> result; result.push_back(intervals[0]); for(int i = 1,j = 0;i<intervals.size();++i){ if(intervals[i].start<=result[j].end&&intervals[i].end>=result[j].start){ Interval temp(min(result[j].start,intervals[i].start),max(result[j].end,intervals[i].end)); result.pop_back(); result.push_back(temp); while(j>=1&&result[j].start<=result[j-1].end&&result[j].end>=result[j-1].start){ Interval temp(min(result[j].start,intervals[j-1].start),max(result[j].end,intervals[j-1].end)); result.pop_back(); result.pop_back(); result.push_back(temp); --j; } }else{ result.push_back(intervals[i]); ++j; } } return result; } }; /* //感觉这个题可以利用一下56 然后加点东西就好了 int quicksort(vector<Interval>& data,int low,int high){ int partition(vector<Interval>& data,int low,int high); if ((high-low)<1){ return 0; } int middle=partition(data,low,high-1); quicksort(data,low,middle); quicksort(data,middle+1,high); return 0; } int partition(vector<Interval>& data,int low,int high){ int backup_low=low; int backup_high=high; Interval middle_data=data[low]; for(;low<high;){ for(;low<high;){ if(data[high].start>middle_data.start){ high=high-1; }else{ data[low]=data[high]; low=low+1; break; } } for(;low<high;){ if(data[low].start<middle_data.start){ low=low+1; }else{ data[high]=data[low]; high=high-1; break; } } } int middle=low; data[low]=middle_data; low=backup_low; high=backup_high; return middle; } class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { if(intervals.size()==0){ vector<Interval> result_2; result_2.push_back(newInterval); return result_2; } if(intervals.size()>=2){ quicksort(intervals, 0 ,intervals.size()); } vector<Interval> result; result.push_back(intervals[0]); for(int i = 1,j = 0;i<intervals.size();++i){ if(intervals[i].start<=result[j].end&&intervals[i].end>=result[j].start){ Interval temp(min(result[j].start,intervals[i].start),max(result[j].end,intervals[i].end)); result.pop_back(); result.push_back(temp); while(j>=1&&result[j].start<=result[j-1].end&&result[j].end>=result[j-1].start){ Interval temp(min(result[j].start,intervals[j-1].start),max(result[j].end,intervals[j-1].end)); result.pop_back(); result.pop_back(); result.push_back(temp); --j; } }else{ result.push_back(intervals[i]); ++j; } } vector<Interval> result_2; int a=0; int b=0; while(a<result.size()&&newInterval.start>result[a].end){ ++a; } --a; while(b<result.size()&&newInterval.end>=result[b].start){ ++b; } --b; if(a==result.size()-2){ //特殊情况 result.push_back(newInterval); return result; } for(int i=0;i<=a;++i){ result_2.push_back(result[i]); } if(a==result.size()-1){ result_2.push_back(newInterval); return result_2; } Interval temp(min(newInterval.start,result[a+1].start),max(newInterval.end,result[b].end)); result_2.push_back(temp); for(int i=b+1;b<result.size();++i){ result_2.push_back(result[i]); } return result_2; } }; */
// This test file sees if the staggered operator can be well preconditioned // by a staggered operator with a laplace term. #include <iostream> #include <iomanip> // to set output precision. #include <cmath> #include <string> #include <sstream> #include <complex> #include <random> #include <cstring> // should be replaced by using sstream // Things for timing. #include <stdlib.h> #include <unistd.h> #include <time.h> // For Dslash pieces #include "generic_gcr.h" #include "generic_gcr_var_precond.h" #include "generic_vector.h" #include "generic_precond.h" #include "verbosity.h" #include "u1_utils.h" #include "operators.h" using namespace std; // Define pi. #define PI 3.141592653589793 // Custom routine to load gauge field. void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA); // Timing routine. timespec diff(timespec start, timespec end) { timespec tmp; if ((end.tv_nsec-start.tv_nsec) < 0) { tmp.tv_sec = end.tv_sec-start.tv_sec-1; tmp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { tmp.tv_sec = end.tv_sec-start.tv_sec; tmp.tv_nsec = end.tv_nsec-start.tv_nsec; } return tmp; } int main(int argc, char** argv) { // Declare some variables. cout << setiosflags(ios::scientific) << setprecision(6); int i,j,x,y; complex<double> *gfield; // Holds the gauge field. complex<double> *lhs, *lhs2, *rhs, *rhs2, *check; // For some Kinetic terms. complex<double> *rhs_internal, *lhs_internal, *lhs2_internal; complex<double> tmp; complex<double> *tmp2, *tmp3; std::mt19937 generator (1337u); // RNG, 1337u is the seed. inversion_info invif; staggered_u1_op stagif; double bnorm; stringstream sstream; // Timing. timespec time1, time2, timediff; // Set parameters. // L_x = L_y = Dimension for a square lattice. int square_size = 32; // Can be set on command line with --square_size. // What masses should we use? double mass = 1e-1; // Solver precision. double outer_precision = 1e-6; // Restart iterations. int outer_restart = 64; // Gauge field information. double BETA = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta). // For heatbath gauge field, corresponds to non-compact beta. // Can be set on command line with --beta. // Load an external cfg? char* load_cfg = NULL; bool do_load = false; ///////////////////////////////////////////// // Get a few parameters from command line. // ///////////////////////////////////////////// for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0) { cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--lattice-size [32, 64, 128] (default 32)\n"; cout << "--mass [#] (default 1e-1)\n"; cout << "--load-cfg [path] (default do not load, overrides beta)\n"; return 0; } if (i+1 != argc) { if (strcmp(argv[i], "--beta") == 0) { BETA = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--lattice-size") == 0) { square_size = atoi(argv[i+1]); i++; } else if (strcmp(argv[i], "--mass") == 0) { mass = atof(argv[i+1]); i++; } else if (strcmp(argv[i], "--load-cfg") == 0) { load_cfg = argv[i+1]; do_load = true; i++; } else { cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n"; cout << "--operator [laplace, staggered, g5_staggered, \n"; cout << " normal_staggered, index] (default staggered)\n"; cout << "--lattice-size [32, 64, 128] (default 32)\n"; cout << "--mass [#] (default 1e-2)\n"; cout << "--load-cfg [path] (default do not load, overrides beta)\n"; return 0; } } } //printf("Mass %.8e Blocksize %d %d Null Vectors %d\n", MASS, X_BLOCKSIZE, Y_BLOCKSIZE, n_null_vector); //return 0; /////////////////////////////////////// // End of human-readable parameters! // /////////////////////////////////////// // Only relevant for free laplace test. int Nc = 1; // Only value that matters for staggered // Describe the fine lattice. int x_fine = square_size; int y_fine = square_size; int fine_size = x_fine*y_fine*Nc; cout << "[VOL]: X " << x_fine << " Y " << y_fine << " Volume " << x_fine*y_fine; cout << "\n"; // Do some allocation. // Initialize the lattice. Indexing: index = y*N + x. gfield = new complex<double>[2*fine_size]; lhs = new complex<double>[fine_size]; rhs = new complex<double>[fine_size]; rhs2 = new complex<double>[fine_size]; lhs2 = new complex<double>[fine_size]; check = new complex<double>[fine_size]; tmp2 = new complex<double>[fine_size]; tmp3 = new complex<double>[fine_size]; lhs_internal = new complex<double>[fine_size]; lhs2_internal = new complex<double>[fine_size]; rhs_internal = new complex<double>[fine_size]; // Zero it out. zero<double>(gfield, 2*fine_size); zero<double>(rhs, fine_size); zero<double>(rhs2, fine_size); zero<double>(lhs, fine_size); zero<double>(lhs2, fine_size); zero<double>(check, fine_size); zero<double>(tmp2, fine_size); zero<double>(tmp3, fine_size); zero<double>(lhs_internal, fine_size); zero<double>(rhs_internal, fine_size); zero<double>(lhs2_internal, fine_size); // // Fill stagif. stagif.lattice = gfield; stagif.mass = mass; stagif.x_fine = x_fine; stagif.y_fine = y_fine; stagif.Nc = Nc; // Only relevant for laplace test only. // Create the verbosity structure. inversion_verbose_struct verb; verb.verbosity = VERB_SUMMARY; //VERB_DETAIL; verb.precond_verbosity = VERB_NONE; //VERB_SUMMARY; // Describe the gauge field. cout << "[GAUGE]: Creating a gauge field.\n"; unit_gauge_u1(gfield, x_fine, y_fine); // Load the gauge field. if (do_load) { read_gauge_u1(gfield, x_fine, y_fine, load_cfg); cout << "[GAUGE]: Loaded a U(1) gauge field from " << load_cfg << "\n"; } else // various predefined cfgs. { internal_load_gauge_u1(gfield, x_fine, y_fine, BETA); } cout << "[GAUGE]: The average plaquette is " << get_plaquette_u1(gfield, x_fine, y_fine) << ".\n"; cout << "[GAUGE]: The topological charge is " << get_topo_u1(gfield, x_fine, y_fine) << ".\n"; /************** * BEGIN TESTS * **************/ // Set a random source. Should be the same every time b/c we hard code the seed above. gaussian<double>(rhs, fine_size, generator); ////// // First test: invert the staggered Dslash with GCR(1024). ////// zero<double>(lhs, fine_size); verb.verb_prefix = "[Dslash]: "; invif = minv_vector_gcr_restart(lhs, rhs, fine_size, 100000, outer_precision, 1024, square_staggered_u1, (void*)&stagif, &verb); ////// // Second test: invert the staggered Dslash with GCR(1024), preconditioned by GCR(8) of the staggered Dslash. ////// // Create a stagif structure for the preconditioned solve. staggered_u1_op stagif_precond; stagif_precond.lattice = gfield; stagif_precond.mass = mass; stagif_precond.x_fine = x_fine; stagif_precond.y_fine = y_fine; stagif_precond.Nc = 1; stagif_precond.wilson_coeff = 0.0; // Create a GCR(8) preconditioner struct. gcr_precond_struct_complex gcrprec; gcrprec.n_step = 8; gcrprec.rel_res = 1e-10; // guarantee we always do 8 steps. gcrprec.matrix_vector = square_staggered_u1; gcrprec.matrix_extra_data = &stagif_precond; // Do the inversion zero<double>(lhs, fine_size); verb.verb_prefix = "[Dslash_W=0]: "; verb.precond_verb_prefix = "[Dslash_W=0_GCR(8)]: "; invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 100000, outer_precision, 1024, square_staggered_u1, (void*)&stagif, gcr_preconditioner, &gcrprec, &verb); ////// // Third test: invert the staggered Dslash with GCR(1024), preconditioned by GCR(8) // of the staggered + laplace Dslash, w/ coefficient 0.01. ////// // Set the wilson coeff for this solve. stagif_precond.wilson_coeff = 0.01; stagif_precond.mass = mass; // Update GCR precond function with new fcn. gcrprec.matrix_vector = square_staggered_2linklaplace_u1; // Do the inversion zero<double>(lhs, fine_size); verb.verb_prefix = "[Dslash_W=0p01]: "; verb.precond_verb_prefix = "[Dslash_W=0p01_GCR(8)]: "; invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 100000, outer_precision, 1024, square_staggered_u1, (void*)&stagif, gcr_preconditioner, &gcrprec, &verb); ////// // Fourth test: invert the staggered Dslash with GCR(1024), preconditioned by GCR(8) // of the staggered + laplace Dslash, w/ coefficient 0.02. ////// // Set the wilson coeff for this solve. stagif_precond.wilson_coeff = 0.05; stagif_precond.mass = mass; // Update GCR precond function with new fcn. gcrprec.matrix_vector = square_staggered_2linklaplace_u1; // Do the inversion zero<double>(lhs, fine_size); verb.verb_prefix = "[Dslash_W=0p05]: "; verb.precond_verb_prefix = "[Dslash_W=0p05_GCR(8)]: "; invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 100000, outer_precision, 1024, square_staggered_u1, (void*)&stagif, gcr_preconditioner, &gcrprec, &verb); ////// // Fifth test: invert the staggered Dslash with GCR(1024), preconditioned by GCR(8) // of the staggered + laplace Dslash, w/ coefficient 0.04. ////// // Set the wilson coeff for this solve. stagif_precond.wilson_coeff = 0.12; stagif_precond.mass = mass; // Update GCR precond function with new fcn. gcrprec.matrix_vector = square_staggered_2linklaplace_u1; // Do the inversion zero<double>(lhs, fine_size); verb.verb_prefix = "[Dslash_W=0p12]: "; verb.precond_verb_prefix = "[Dslash_W=0p12_GCR(8)]: "; invif = minv_vector_gcr_var_precond_restart(lhs, rhs, fine_size, 100000, outer_precision, 1024, square_staggered_u1, (void*)&stagif, gcr_preconditioner, &gcrprec, &verb); /************ * END TESTS * ************/ // Free the lattice. delete[] gfield; delete[] lhs; delete[] lhs2; delete[] rhs; delete[] rhs2; delete[] check; delete[] tmp2; delete[] tmp3; delete[] lhs_internal; delete[] rhs_internal; delete[] lhs2_internal; return 0; } // Custom routine to load gauge field. void internal_load_gauge_u1(complex<double>* lattice, int x_fine, int y_fine, double BETA) { if (x_fine == 32 && y_fine == 32) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l32t32bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 64 && y_fine == 64) { if (abs(BETA - 3.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64b30_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l64t64bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else if (x_fine == 128 && y_fine == 128) { if (abs(BETA - 6.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l128t128b60_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l128t128b100_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else if (abs(BETA - 10000.0) < 1e-8) { read_gauge_u1(lattice, x_fine, y_fine, "../../multigrid/aa_mg/cfg/l128t128bperturb_heatbath.dat"); cout << "[GAUGE]: Loaded a U(1) gauge field with non-compact beta = " << 1.0/sqrt(BETA) << "\n"; } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } } else { cout << "[GAUGE]: Saved U(1) gauge field with correct beta, volume does not exist.\n"; } }
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Sort String int t; cin >> t; string s; while(t--) { cin >> s; sort(s.begin(), s.end()); // sorry, not sorry :) cout << s << endl; } return 0; }
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <string> #include <stdio.h> #ifndef LTEXTURE_H #define LTEXTURE_H const int SPLASH_WIDTH = 1400; const int SPLASH_HEIGHT = 700; const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 800; class LTexture { public: //Initializes variables LTexture(); //Deallocates memory ~LTexture(); //Loads image at specified path bool loadFromFile( std::string path, SDL_Renderer* gRenderer ); //Deallocates texture void free(); //Renders texture at given point void render( SDL_Renderer* gRenderer, int x, int y, SDL_Rect* clip = NULL, int w = 100, int h = 100); //Set Blend Mode void setBlendMode(SDL_BlendMode blending); //Set alpha Modulation void setAlpha(Uint8 alpha); //Gets and sets image dimensions int getWidth(); int getHeight(); void setWidth(int); void setHeight(int); void scaleToScreen(); private: //The actual hardware texture SDL_Texture* mTexture; //Image dimensions int mWidth; int mHeight; }; #endif
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.10.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QVBoxLayout *verticalLayout; QLabel *label_image; QHBoxLayout *horizontalLayout; QPushButton *saveNext; QPushButton *generateXML; QPushButton *saveQuit; QMenuBar *menuBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(401, 330); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); verticalLayout = new QVBoxLayout(centralWidget); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); label_image = new QLabel(centralWidget); label_image->setObjectName(QStringLiteral("label_image")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(3); sizePolicy.setHeightForWidth(label_image->sizePolicy().hasHeightForWidth()); label_image->setSizePolicy(sizePolicy); verticalLayout->addWidget(label_image); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); saveNext = new QPushButton(centralWidget); saveNext->setObjectName(QStringLiteral("saveNext")); QSizePolicy sizePolicy1(QSizePolicy::Minimum, QSizePolicy::Preferred); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(saveNext->sizePolicy().hasHeightForWidth()); saveNext->setSizePolicy(sizePolicy1); horizontalLayout->addWidget(saveNext); generateXML = new QPushButton(centralWidget); generateXML->setObjectName(QStringLiteral("generateXML")); horizontalLayout->addWidget(generateXML); saveQuit = new QPushButton(centralWidget); saveQuit->setObjectName(QStringLiteral("saveQuit")); sizePolicy1.setHeightForWidth(saveQuit->sizePolicy().hasHeightForWidth()); saveQuit->setSizePolicy(sizePolicy1); horizontalLayout->addWidget(saveQuit); verticalLayout->addLayout(horizontalLayout); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 401, 22)); MainWindow->setMenuBar(menuBar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", Q_NULLPTR)); label_image->setText(QString()); saveNext->setText(QApplication::translate("MainWindow", "Save n Next", Q_NULLPTR)); generateXML->setText(QApplication::translate("MainWindow", "Generate XML", Q_NULLPTR)); saveQuit->setText(QApplication::translate("MainWindow", "Save n Quit", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 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" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/dom/src/js/js_plugin.h" #include "modules/dom/src/js/mimetype.h" #include "modules/doc/frm_doc.h" #include "modules/dom/src/domrestartobject.h" #include "modules/util/str.h" #include "modules/viewers/viewers.h" #include "modules/viewers/plugins.h" #include "modules/prefs/prefsmanager/collections/pc_display.h" /* Empty function, defined in domobj.cpp. */ extern DOM_FunctionImpl DOM_dummyMethod; #ifdef _PLUGIN_SUPPORT_ BOOL PluginsDisabled(DOM_EnvironmentImpl *environment) { FramesDocument *frm_doc = environment->GetFramesDocument(); if (frm_doc && frm_doc->GetWindow()->IsThumbnailWindow()) return TRUE; return !g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::PluginsEnabled, DOM_EnvironmentImpl::GetHostName(frm_doc)); } #ifdef NS4P_COMPONENT_PLUGINS class DOM_PluginDetectionRestartObject : public PluginViewers::OpDetectionDoneListener, public DOM_RestartObject { public: static ES_GetState BlockUntilDetected(ES_Value *value, ES_Runtime* origining_runtime) { DOM_PluginDetectionRestartObject* restart_obj; GET_FAILED_IF_ERROR(DOMSetObjectRuntime(restart_obj = OP_NEW(DOM_PluginDetectionRestartObject, ()), static_cast<DOM_Runtime*>(origining_runtime))); GET_FAILED_IF_ERROR(restart_obj->KeepAlive()); GET_FAILED_IF_ERROR(g_plugin_viewers->AddDetectionDoneListener(restart_obj)); return restart_obj->BlockGet(value, origining_runtime); } virtual void DetectionDone() { OP_NEW_DBG("DOM_PluginDetectionRestartObject::DetectionDone()", "ns4p"); OP_DBG(("Detection done signal received, resuming thread.")); Resume(); } ~DOM_PluginDetectionRestartObject() { OP_NEW_DBG("~DOM_PluginDetectionRestartObject", "ns4p"); OP_DBG(("DOM_PluginDetectionRestartObject destroyed, removing detection done listener.")); /* Ignoring; no good way to return error from destructor. */ OpStatus::Ignore(g_plugin_viewers->RemoveDetectionDoneListener(this)); } }; #endif // NS4P_COMPONENT_PLUGINS #endif // _PLUGIN_SUPPORT_ /* static */ OP_STATUS JS_PluginArray::Make(JS_PluginArray *&plugins, DOM_EnvironmentImpl *environment) { DOM_Runtime *runtime = environment->GetDOMRuntime(); return DOMSetObjectRuntime(plugins = OP_NEW(JS_PluginArray, ()), runtime, runtime->GetPrototype(DOM_Runtime::PLUGINARRAY_PROTOTYPE), "PluginArray"); } /* virtual */ ES_GetState JS_PluginArray::GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime) { OP_NEW_DBG("JS_PluginArray::GetName", "ns4p"); #ifdef _PLUGIN_SUPPORT_ if (PluginsDisabled(GetEnvironment())) if (property_code == OP_ATOM_length) { DOMSetNumber(value, 0); return GET_SUCCESS; } else return GET_FAILED; #ifdef NS4P_COMPONENT_PLUGINS if (g_plugin_viewers->IsDetecting()) { OP_DBG(("Suspending thread that uses navigator.plugins because plugin detection is in progress, thread will be resumed when detection is done.")); return DOM_PluginDetectionRestartObject::BlockUntilDetected(value, origining_runtime); } #endif // NS4P_COMPONENT_PLUGINS if (property_code == OP_ATOM_length) { DOMSetNumber(value, g_plugin_viewers->GetPluginViewerCount(TRUE)); return GET_SUCCESS; } for (unsigned i = 0; i < g_plugin_viewers->GetPluginViewerCount(); ++i) if (PluginViewer *plugin_viewer = g_plugin_viewers->GetPluginViewer(i)) { if (!plugin_viewer->IsEnabled()) continue; const uni_char *prod_name = plugin_viewer->GetProductName(); if (prod_name) if (uni_str_eq(property_name, prod_name)) { if (value) { JS_Plugin *plugin; GET_FAILED_IF_ERROR(JS_Plugin::Make(plugin, GetEnvironment(), plugin_viewer)); DOMSetObject(value, plugin); } return GET_SUCCESS; } } #else // _PLUGIN_SUPPORT_ if (property_code == OP_ATOM_length) { DOMSetNumber(value, 0); return GET_SUCCESS; } #endif // _PLUGIN_SUPPORT_ return GET_FAILED; } #ifdef NS4P_COMPONENT_PLUGINS /* virtual */ ES_GetState JS_PluginArray::GetNameRestart(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime, ES_Object* restart_object) { return GetName(property_name, 0, value, origining_runtime); } #endif // NS4P_COMPONENT_PLUGINS /* virtual */ ES_GetState JS_PluginArray::GetIndex(int property_index, ES_Value* value, ES_Runtime *origining_runtime) { OP_NEW_DBG("JS_PluginArray::GetIndex", "ns4p"); #ifdef _PLUGIN_SUPPORT_ #ifdef NS4P_COMPONENT_PLUGINS if (g_plugin_viewers->IsDetecting()) { OP_DBG(("Suspending thread that uses navigator.plugins[i] because plugin detection is in progress, thread will be resumed when detection is done.")); return DOM_PluginDetectionRestartObject::BlockUntilDetected(value, origining_runtime); } #endif // NS4P_COMPONENT_PLUGINS int enabled_count = 0; for (UINT i = 0; i < g_plugin_viewers->GetPluginViewerCount(); i++) { PluginViewer *plugin_viewer = g_plugin_viewers->GetPluginViewer(i); // Count only enabled plugins to find plugin matching requested index if (plugin_viewer && plugin_viewer->IsEnabled() && property_index == enabled_count++) { if (value) { JS_Plugin *plugin; GET_FAILED_IF_ERROR(JS_Plugin::Make(plugin, GetEnvironment(), plugin_viewer)); DOMSetObject(value, plugin); } return GET_SUCCESS; } } #endif // _PLUGIN_SUPPORT_ return GET_FAILED; } #ifdef NS4P_COMPONENT_PLUGINS /* virtual */ ES_GetState JS_PluginArray::GetIndexRestart(int property_index, ES_Value *value, ES_Runtime *origining_runtime, ES_Object *restart_object) { return GetIndex(property_index, value, origining_runtime); } #endif // NS4P_COMPONENT_PLUGINS /* virtual */ ES_GetState JS_PluginArray::GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime) { #ifdef _PLUGIN_SUPPORT_ count = g_plugin_viewers->GetPluginViewerCount(TRUE); #else // _PLUGIN_SUPPORT_ count = 0; #endif // _PLUGIN_SUPPORT_ return GET_SUCCESS; } /* static */ int JS_PluginArray::refresh(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT_UNUSED(DOM_TYPE_PLUGINARRAY); #ifdef _PLUGIN_SUPPORT_ if (PluginsDisabled(origining_runtime->GetEnvironment())) return ES_FAILED; CALL_FAILED_IF_ERROR(g_plugin_viewers->RefreshPluginViewers(FALSE)); if (argc > 0 && argv[0].value.boolean) if (FramesDocument* frames_doc = origining_runtime->GetFramesDocument()) frames_doc->GetDocManager()->Reload(NotEnteredByUser); #endif // _PLUGIN_SUPPORT_ return ES_FAILED; } #include "modules/dom/src/domglobaldata.h" DOM_FUNCTIONS_START(JS_PluginArray) DOM_FUNCTIONS_FUNCTION(JS_PluginArray, JS_PluginArray::refresh, "-refresh", "b-") DOM_FUNCTIONS_END(JS_PluginArray) #ifdef _PLUGIN_SUPPORT_ JS_Plugin::JS_Plugin() : description(NULL), filename(NULL), name(NULL) { } /* static */ OP_STATUS JS_Plugin::Make(JS_Plugin *&plugin, DOM_EnvironmentImpl *environment, PluginViewer *plugin_viewer) { DOM_Runtime *runtime = environment->GetDOMRuntime(); RETURN_IF_ERROR(DOMSetObjectRuntime(plugin = OP_NEW(JS_Plugin, ()), runtime, runtime->GetObjectPrototype(), "Plugin")); const uni_char *description = plugin_viewer->GetDescription(); const uni_char *filename = plugin_viewer->GetPath(); const uni_char *name = plugin_viewer->GetProductName(); // We don't want scripts to have access to the path as that gives // the script information about the local computer's directory // structure and might contain user names and other sensitive information. // Strip everything before the last path seperator. if (filename) { const uni_char* last_sep = uni_strrchr(filename, PATHSEPCHAR); if (last_sep) filename = last_sep + 1; } if (!(plugin->description = UniSetNewStr(description ? description : UNI_L(""))) || !(plugin->filename = UniSetNewStr(filename ? filename : UNI_L(""))) || !(plugin->name = UniSetNewStr(name ? name : UNI_L("")))) return OpStatus::ERR_NO_MEMORY; else return OpStatus::OK; } JS_Plugin::~JS_Plugin() { OP_DELETEA(description); OP_DELETEA(filename); OP_DELETEA(name); } /* virtual */ ES_GetState JS_Plugin::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { if (PluginsDisabled(GetEnvironment())) return GET_FAILED; switch (property_name) { case OP_ATOM_description: DOMSetString(value, description); return GET_SUCCESS; case OP_ATOM_filename: DOMSetString(value, filename); return GET_SUCCESS; case OP_ATOM_name: DOMSetString(value, name); return GET_SUCCESS; case OP_ATOM_length: if (value) { int count = 0; ChainedHashIterator* viewer_iter; GET_FAILED_IF_ERROR(g_viewers->CreateIterator(viewer_iter)); while (Viewer *viewer = g_viewers->GetNextViewer(viewer_iter)) { if (viewer->FindPluginViewerByName(name, TRUE)) ++count; } OP_DELETE(viewer_iter); DOMSetNumber(value, count); } return GET_SUCCESS; default: return GET_FAILED; } } /* virtual */ ES_GetState JS_Plugin::GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime) { ES_GetState result = DOM_Object::GetName(property_name, property_code, value, origining_runtime); if (result != GET_FAILED) return result; Viewer *viewer = NULL; viewer = g_viewers->FindViewerByMimeType(property_name); if (viewer && !viewer->FindPluginViewerByName(name, TRUE)) viewer = NULL; if (viewer) { if (value) { JS_MimeType *mimetype; GET_FAILED_IF_ERROR(JS_MimeType::Make(mimetype, GetEnvironment(), viewer)); DOMSetObject(value, mimetype); } return GET_SUCCESS; } else return GET_FAILED; } /* virtual */ ES_GetState JS_Plugin::GetIndex(int property_index, ES_Value* value, ES_Runtime *origining_runtime) { if (PluginsDisabled(GetEnvironment())) return GET_FAILED; ChainedHashIterator *viewer_iter; GET_FAILED_IF_ERROR(g_viewers->CreateIterator(viewer_iter)); while (Viewer *viewer = g_viewers->GetNextViewer(viewer_iter)) if (viewer->FindPluginViewerByName(name, TRUE)) if (property_index > 0) --property_index; else { if (value) { JS_MimeType *mimetype; OP_STATUS rc = JS_MimeType::Make(mimetype, GetEnvironment(), viewer); if (OpStatus::IsError(rc)) { OP_DELETE(viewer_iter); return rc == OpStatus::ERR_NO_MEMORY ? GET_NO_MEMORY : GET_FAILED; } DOMSetObject(value, mimetype); } OP_DELETE(viewer_iter); return GET_SUCCESS; } OP_DELETE(viewer_iter); return GET_FAILED; } /* virtual */ ES_PutState JS_Plugin::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { if (GetName(property_name, NULL, origining_runtime) == GET_SUCCESS) return PUT_READ_ONLY; else return PUT_FAILED; } #endif // _PLUGIN_SUPPORT_
#ifndef DEVICE_HPP #define DEVICE_HPP #include <string> #include <fstream> #include <map> #include <CL/cl.h> #include <iostream> #define OCL_CHECK(condition, content) \ do {\ cl_int error = condition; \ if (error != CL_SUCCESS) std::cout << "error: " << error << " [ " << content << " ]" << std::endl; \ } while (0) class Device { public: Device() : numPlatforms(0), numDevices(0), device_id(INT_MIN), oclKernelPath("./kernelGen/cl_kernels/"), buildOption(" ") { } ~Device(); cl_uint numPlatforms; cl_platform_id * platformIDs; char platformName[64]; char openclVersion[64]; cl_uint numDevices; cl_device_id * DeviceIDs; cl_context Context; cl_command_queue CommandQueue; cl_command_queue CommandQueue_helper; cl_program Program; cl_device_id * pDevices; int device_id; std::string oclKernelPath; std::string buildOption; std::map<std::string, cl_kernel> Kernels; cl_int Init(int device_id = -1); cl_int ConvertToString(std::string pFileName, std::string &Str); cl_kernel GetKernel(std::string kernel_name); void DisplayPlatformInfo(); void DisplayInfo(cl_platform_id id, cl_platform_info name, std::string str); int GetDevice() { return device_id; } void GetDeviceInfo(); void DeviceQuery(); void BuildProgram(std::string kernel_dir); bool SetKernelPath(std::string path); bool SetBuildOption(std::string option); template <typename T> void DisplayDeviceInfo(cl_device_id id, cl_device_info name, std::string str); template <typename T> void appendBitfield(T info, T value, std::string name, std::string &str); void ReleaseKernels(); }; #endif //DEVICE_HPP
#pragma once #include <Dot++/parser/TokenInfoHandle.hpp> #include <Dot++/parser/TokenStack.hpp> #include <Dot++/parser/ParserState.hpp> namespace dot_pp { namespace parser { template<class ConstructionPolicy> class ParserStateInterface { public: virtual ~ParserStateInterface(){} virtual ParserState consume(const TokenInfoHandle& token, TokenStack& stack, TokenStack& attributes, ConstructionPolicy& constructor) = 0; }; }}
#include <iostream> #include "vector.h" using namespace std; int main() { vector v = vector(10); v.set(1, 7); cout << "Value of the second element: " << v.get(1) << '\n' << "Value of the third element: " << v.get(2) << '\n' << "Vector's size: " << v.size() << '\n'; return 0; }
// Copyright (C) 2012-2013 Mihai Preda // this is the only file that uses "placement new" // and must include the <new> header #include "Array.h" #include "Map.h" #include "Func.h" #include "Proto.h" #include "CFunc.h" #include "String.h" #include "GC.h" #include "SymbolTable.h" #include <assert.h> #include <new> /* SymbolTable *SymbolTable::alloc(GC *gc) { return new (gc->alloc(sizeof(SymbolTable), true)) SymbolTable; } */ Array *Array::alloc(GC *gc, int iniSize) { return new (gc->alloc(sizeof(Array), true)) Array(iniSize); } Map *Map::alloc(GC *gc, unsigned sizeHint) { (void) sizeHint; return new (gc->alloc(sizeof(Map), true)) Map; } Func *Func::alloc(GC *gc, Proto *proto, Value *contextUps, Value *regs, byte recSlot) { return new (gc->alloc(sizeof(Func), true)) Func(proto, contextUps, regs, recSlot); } Proto *Proto::alloc(GC *gc, Proto *up) { return new (gc->alloc(sizeof(Proto), true)) Proto(up); } CFunc *CFunc::alloc(GC *gc, tfunc f, unsigned dataSize) { assert(dataSize); return new (gc->alloc(sizeof(CFunc) + dataSize, true)) CFunc(f); } SymbolTable *SymbolTable::alloc(GC *gc) { return new (gc->alloc(sizeof(SymbolTable), true)) SymbolTable(); }
/* -*- 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. */ #include "core/pch.h" #ifdef M2_SUPPORT #ifdef _BITTORRENT_SUPPORT_ #include "modules/util/gen_math.h" #include "adjunct/m2/src/engine/engine.h" #include "adjunct/m2/src/engine/account.h" #include "modules/ecmascript/ecmascript.h" #include "modules/util/OpLineParser.h" #include "adjunct/m2/src/util/autodelete.h" #include "adjunct/m2/src/util/str/strutil.h" #include "adjunct/quick/dialogs/BTStartDownloadDialog.h" #include "modules/url/protocols/pcomm.h" #include "modules/url/protocols/comm.h" #include "modules/url/url2.h" #include "adjunct/bittorrent/bt-util.h" #include "adjunct/bittorrent/bt-download.h" #include "adjunct/bittorrent/bt-tracker.h" #include "adjunct/bittorrent/bt-benode.h" #include "adjunct/bittorrent/bt-info.h" #include "adjunct/bittorrent/dl-base.h" #include "adjunct/bittorrent/bt-globals.h" #include "adjunct/bittorrent/connection.h" #include "adjunct/bittorrent/bt-packet.h" void BTInfo::LoadTorrentFile(OpTransferItem * transfer_item) { m_info_impl->LoadTorrentFile(transfer_item); } BOOL BTInfo::LoadTorrentFile(OpString& filename) { return m_info_impl->LoadTorrentFile(filename); } void BTInfo::OnTorrentAvailable(URL& url) { OpString loc; OpString tmp_storage; loc.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_SAVE_FOLDER, tmp_storage)); if(loc.IsEmpty()) { /* The return value of the previous GetFolderPathIgnoreErrrors * call is no longer in use, so I can reuse tmp_storage. */ loc.Set(g_folder_manager->GetFolderPathIgnoreErrors(OPFILE_DOWNLOAD_FOLDER, tmp_storage)); } BTStartDownloadDialog *dlg = OP_NEW(BTStartDownloadDialog, ()); if (dlg) { BTDownloadInfo *info = OP_NEW(BTDownloadInfo, ()); if (info) { info->savepath.TakeOver(loc); info->url = url; OpString urlname; url.GetAttribute(URL::KName_Username_Password_Hidden_Escaped, urlname); info->loadpath.Set(urlname); info->btinfo = this; if (OpStatus::IsSuccess(dlg->Init(g_application->GetActiveDesktopWindow(), info))) return; OP_DELETE(info); } OP_DELETE(dlg); } } void BTInfo::Cancel(BTDownloadInfo * btdinfo) { OP_DELETE(btdinfo); //?OnFinished(); } void BTInfo::InitiateDownload(BTDownloadInfo * btdinfo) { m_info_impl->InitiateDownload(btdinfo); } void BTInfoImpl::InitiateDownload(BTDownloadInfo * btdinfo) { // the torrent file: BOOL has_more = TRUE; m_pSource.Empty(); URL_DataDescriptor *data_descriptor; data_descriptor = btdinfo->url.GetDescriptor(NULL, TRUE, TRUE); if(!data_descriptor) { OP_DELETE(btdinfo); return; } OP_STATUS err = OpStatus::OK; while(has_more) { OP_MEMORY_VAR unsigned long source_len = 0; TRAP(err, source_len = data_descriptor->RetrieveDataL(has_more)); if (OpStatus::IsError(err)) break; unsigned char *src = (unsigned char *)data_descriptor->GetBuffer(); if (src == NULL || source_len == 0) break; m_pSource.Append(src, source_len); data_descriptor->ConsumeData(source_len); } OP_DELETE(data_descriptor); if (OpStatus::IsError(err)) { OP_DELETE(btdinfo); return; } // where to put the result OpString loc; loc.TakeOver(btdinfo->savepath); if (loc.Length() && loc[loc.Length()-1] != PATHSEPCHAR) loc.Append(PATHSEP); g_folder_manager->SetFolderPath(OPFILE_SAVE_FOLDER, loc.CStr()); m_targetdirectory.TakeOver(loc); OpString torrentfile; torrentfile.Set(m_targetdirectory); OpString urlname; btdinfo->url.GetAttribute(URL::KName_Username_Password_Hidden_Escaped, urlname); int idx = urlname.FindLastOf('/'); if(idx != -1) { if (torrentfile.Length() && torrentfile[torrentfile.Length()-1] != PATHSEPCHAR) torrentfile.Append(PATHSEP); torrentfile.Append(urlname.CStr() + idx+1); } m_savefilename.TakeOver(torrentfile); m_sLoadedFromPath.Set(urlname); if(LoadTorrentBuffer(&m_pSource)) { AddTorrentToDownload(); } btdinfo->url.ForceStatus(URL_UNLOADED); OP_DELETE(btdinfo); if (m_listener) m_listener->OnFinished(); } ////////////////////////////////////////////////////////////////////// // BTInfoImpl construction BTInfoImpl::BTInfoImpl() : m_bValid(FALSE), m_bDataSHA1(FALSE), m_nTotalSize(0), m_nBlockSize(0), m_nBlockCount(0), m_pBlockSHA1(NULL), m_nFiles(0), m_pFiles(NULL), m_private_torrent(FALSE), m_nTestByte(0), m_attachtodownload(NULL), m_multi_tracker(NULL), m_listener(NULL) { BT_RESOURCE_ADD("BTInfoImpl", this); } #ifdef _METHODNAME_ #undef _METHODNAME_ #define _METHODNAME_ "BTInfoImpl::~BTInfoImpl()" #endif BTInfoImpl::~BTInfoImpl() { Clear(); DEBUGTRACE8_RES(UNI_L("*** DESTRUCTOR for %s ("), _METHODNAME_); DEBUGTRACE8_RES(UNI_L("0x%08x)\n"), this); BT_RESOURCE_REMOVE(this); } BTInfoImpl::BTFile::BTFile() { m_nSize = 0; m_bSHA1 = FALSE; m_nOffset = 0; BT_RESOURCE_ADD("BTInfoImpl::BTFile", this); } #ifdef _METHODNAME_ #undef _METHODNAME_ #define _METHODNAME_ "BTInfoImpl::BTFile::~BTFile()" #endif BTInfoImpl::BTFile::~BTFile() { DEBUGTRACE8_RES(UNI_L("*** DESTRUCTOR for %s ("), _METHODNAME_); DEBUGTRACE8_RES(UNI_L("0x%08x)\n"), this); BT_RESOURCE_REMOVE(this); } ////////////////////////////////////////////////////////////////////// // BTInfo clear void BTInfoImpl::Clear() { OP_DELETEA(m_pBlockSHA1); OP_DELETEA(m_pFiles); OP_DELETE(m_multi_tracker); m_bValid = FALSE; m_nTotalSize = 0; m_nBlockSize = 0; m_nBlockCount = 0; m_pBlockSHA1 = NULL; m_nFiles = 0; m_pFiles = NULL; m_sName.Empty(); } ////////////////////////////////////////////////////////////////////// // BTInfo copy void BTInfoImpl::Copy(BTInfoImpl* pSource) { OP_ASSERT(pSource != NULL); Clear(); m_bValid = pSource->m_bValid; m_pInfoSHA1 = pSource->m_pInfoSHA1; m_bDataSHA1 = pSource->m_bDataSHA1; m_pDataSHA1 = pSource->m_pDataSHA1; m_nTotalSize = pSource->m_nTotalSize; m_nBlockSize = pSource->m_nBlockSize; m_nBlockCount = pSource->m_nBlockCount; m_sName.Set(pSource->m_sName); m_nFiles = pSource->m_nFiles; m_sLoadedFromPath.Set(pSource->m_sLoadedFromPath); m_pSource.Append(pSource->m_pSource.Buffer(), pSource->m_pSource.DataSize()); pSource->GetTargetDirectory(m_targetdirectory); m_savefilename.Set(pSource->m_savefilename); m_private_torrent = pSource->m_private_torrent; if(pSource->m_pBlockSHA1 != NULL) { m_pBlockSHA1 = OP_NEWA(SHAStruct, m_nBlockCount); if (m_pBlockSHA1) memcpy(m_pBlockSHA1, pSource->m_pBlockSHA1, sizeof(SHAStruct) * (UINT32)m_nBlockCount); else m_nBlockCount = 0; } if(pSource->m_pFiles != NULL) { m_pFiles = OP_NEWA(BTFile, m_nFiles); if (m_pFiles) for (int nFile = 0 ; nFile < m_nFiles ; nFile++) m_pFiles[ nFile ].Copy(&pSource->m_pFiles[ nFile ]); else m_nFiles = 0; } m_multi_tracker = pSource->GetTracker()->Copy(); } ////////////////////////////////////////////////////////////////////// // BTInfo::BTFile copy void BTInfoImpl::BTFile::Copy(BTFile* pSource) { m_sPath.Append(pSource->m_sPath); m_nSize = pSource->m_nSize; m_nOffset = pSource->m_nOffset; m_bSHA1 = pSource->m_bSHA1; m_pSHA1 = pSource->m_pSHA1; } void BTInfoImpl::LoadTorrentFile(OpTransferItem * transfer_item) { m_pSource.Empty(); OpString filename; ((TransferItem *)transfer_item)->GetMetaFile(filename); if(LoadTorrentFile(filename)) { AddTorrentToDownload(); if(m_listener) { m_listener->OnFinished(); } } } ////////////////////////////////////////////////////////////////////// // BTInfo load .torrent file BOOL BTInfoImpl::LoadTorrentFile(OpString& filename) { OpFile file; OpFileLength nLength; if ((file.Construct(filename.CStr()) != OpStatus::OK) || (file.Open(OPFILE_READ) != OpStatus::OK)) { return FALSE; } if (OpStatus::IsSuccess(file.GetFileLength(nLength)) && nLength > 0) { if (nLength < 20 * 1024 * 1024) { unsigned char *buf = OP_NEWA(unsigned char, (int)nLength); if (!buf) return FALSE; OpFileLength bytes_read = 0; if(file.Read(buf, nLength, &bytes_read) != OpStatus::OK) { OP_DELETEA(buf); return FALSE; } m_pSource.Empty(); m_pSource.Append(buf, (UINT)nLength); OP_DELETEA(buf); return LoadTorrentBuffer(&m_pSource); } } return FALSE; } ////////////////////////////////////////////////////////////////////// // BTInfo save .torrent file BOOL BTInfoImpl::SaveTorrentFile(OpString& targetdirectory) { if(!IsAvailable()) return FALSE; if(m_pSource.DataSize() == 0) return FALSE; OP_STATUS status = OpStatus::ERR; OpFile file; OpString path; OpString name; int seppos; path.Set(targetdirectory); seppos = path.FindLastOf(PATHSEPCHAR); if(seppos != KNotFound) { if(seppos != path.Length() - 1) { path.Append(PATHSEP); } } GetName(name); path.Append(name); path.Append(".torrent"); status = file.Construct(path.CStr()); file.Open(OPFILE_SHAREDENYWRITE | OPFILE_READ); if(!file.IsOpen()) { status = file.Open(OPFILE_SHAREDENYWRITE | OPFILE_OVERWRITE); if(file.IsOpen()) { if(file.Write(m_pSource.Buffer(), m_pSource.DataSize()) != OpStatus::OK) { status = OpStatus::ERR; } else { m_savefilename.Set(path); } file.Close(); } } else { m_savefilename.Set(path); file.Close(); } return status == OpStatus::OK; } ////////////////////////////////////////////////////////////////////// // BTInfo load torrent info from buffer BOOL BTInfoImpl::LoadTorrentBuffer(OpByteBuffer* pBuffer) { BENode* pNode = BENode::Decode(pBuffer); if (pNode == NULL) return FALSE; BOOL bSuccess = LoadTorrentTree(pNode); OP_DELETE(pNode); return bSuccess; } void BTInfoImpl::GetInfoHash(SHAStruct *pSHA1) { memcpy(pSHA1, &m_pInfoSHA1, sizeof(SHAStruct)); } ////////////////////////////////////////////////////////////////////// // BTInfo load torrent info from tree BOOL BTInfoImpl::LoadTorrentTree(BENode* pRoot) { Clear(); if(!pRoot->IsType(BENode::beDict)) { return FALSE; } m_multi_tracker = OP_NEW(BTMultiTracker, ()); if(!m_multi_tracker) { return FALSE; } BENode* pAnnounce; pAnnounce = pRoot->GetNode("announce-list"); if(pAnnounce) { DEBUGTRACE_TORRENT(UNI_L("BT: announce-list:\n"), 0); // multitracker if (pAnnounce->IsType(BENode::beList)) { int cnt; for(cnt = 0; cnt < pAnnounce->GetCount(); cnt++) { BENode* tracker = pAnnounce->GetNode(cnt); if(tracker) { OpString tracker_url; BTTrackerGroup *tracker_group = m_multi_tracker->CreateTrackerGroup(); if(tracker->IsType(BENode::beString)) { tracker->GetStringFromUTF8(tracker_url); DEBUGTRACE_TORRENT(UNI_L("%s\n"), (uni_char *)tracker_url.CStr()); if(tracker_group) { if(OpStatus::IsError(tracker_group->CreateTrackerEntry(tracker_url))) { return FALSE; } } } else if(tracker->IsType(BENode::beList)) { int cnt2; for(cnt2 = 0; cnt2 < tracker->GetCount(); cnt2++) { BENode* tracker_node = tracker->GetNode(cnt2); if(tracker_node) { if(tracker_node->IsType(BENode::beString)) { tracker_node->GetStringFromUTF8(tracker_url); if(tracker_group) { DEBUGTRACE_TORRENT(UNI_L(" %s\n"), (uni_char *)tracker_url.CStr()); if(OpStatus::IsError(tracker_group->CreateTrackerEntry(tracker_url))) { return FALSE; } } } else { OP_ASSERT(FALSE); } } } } } } } } else { pAnnounce = pRoot->GetNode("announce"); if (pAnnounce->IsType(BENode::beString)) { OpString tracker_url; BTTrackerGroup *tracker_group = m_multi_tracker->CreateTrackerGroup(); if(!tracker_group) { return FALSE; } pAnnounce->GetStringFromUTF8(tracker_url); if(OpStatus::IsError(tracker_group->CreateTrackerEntry(tracker_url))) { return FALSE; } DEBUGTRACE_TORRENT(UNI_L("BT: announce: %s\n"), tracker_url.CStr()); // if (m_sTracker.Find(UNI_L("http")) != 0) // { // m_sTracker.Empty(); // return FALSE; // } } } BENode* pInfo = pRoot->GetNode("info"); if (! pInfo->IsType(BENode::beDict)) { return FALSE; } BENode* pName = pInfo->GetNode("name.utf-8"); // prefer utf-8 if it exists: this is a hack for erroneously generated content. if (!pName) pName = pInfo->GetNode("name"); if (pName->IsType(BENode::beString)) { pName->GetStringFromUTF8(m_sName); DEBUGTRACE_TORRENT(UNI_L("BT: name: %s\n"), m_sName.CStr()); } BENode *pPrivate = pInfo->GetNode("private"); if (pPrivate->IsType(BENode::beInt)) { int priv = (int)pPrivate->GetInt(); DEBUGTRACE_TORRENT(UNI_L("BT: private: %d\n"), priv); if(priv) { m_private_torrent = TRUE; } else { m_private_torrent = FALSE; } } else { m_private_torrent = FALSE; } if (m_sName.IsEmpty()) { OpString8 str; str.AppendFormat("Unnamed_Torrent_%i", (int)rand()); m_sName.Append(str); } BENode* pPL = pInfo->GetNode("piece length"); if(!pPL->IsType(BENode::beInt)) { return FALSE; } m_nBlockSize = (UINT32)pPL->GetInt(); if(!m_nBlockSize) { return FALSE; } DEBUGTRACE_TORRENT(UNI_L("BT: blocksize: %d\n"), m_nBlockSize); BENode* pHash = pInfo->GetNode("pieces"); if (! pHash->IsType(BENode::beString)) return FALSE; if (pHash->GetStringLength() % sizeof(SHAStruct)) return FALSE; m_nBlockCount = (UINT32)(pHash->GetStringLength() / sizeof(SHAStruct)); if (! m_nBlockCount || m_nBlockCount > 209716) return FALSE; DEBUGTRACE_TORRENT(UNI_L("BT: pieces: %d\n"), m_nBlockCount); m_pBlockSHA1 = OP_NEWA(SHAStruct, m_nBlockCount); if (m_pBlockSHA1) { for (UINT32 nBlock = 0 ; nBlock < m_nBlockCount ; nBlock++) { SHAStruct* pSource = (SHAStruct*)pHash->GetString(); memcpy(m_pBlockSHA1 + nBlock, pSource + nBlock, sizeof(SHAStruct)); } } else m_nBlockCount = 0; BENode* pSHA1 = pInfo->GetNode("sha1"); if (pSHA1) { if (! pSHA1->IsType(BENode::beString) || pSHA1->GetStringLength() != sizeof(SHAStruct)) return FALSE; m_bDataSHA1 = TRUE; memcpy(&m_pDataSHA1, pSHA1->GetString(), sizeof(SHAStruct)); } BENode* pFiles = pInfo->GetNode("files"); BENode* pLength = pInfo->GetNode("length"); if(pLength) { if (! pLength->IsType(BENode::beInt)) return FALSE; m_nTotalSize = pLength->GetInt(); if (! m_nTotalSize) return FALSE; DEBUGTRACE_TORRENT(UNI_L("BT: length: %d\n"), m_nTotalSize); m_pFiles = OP_NEWA(BTFile, 1); if (m_pFiles) { m_nFiles = 1; m_pFiles[0].m_sPath.Append(m_sName); m_pFiles[0].m_nSize = m_nTotalSize; m_pFiles[0].m_nOffset = 0; m_pFiles[0].m_bSHA1 = m_bDataSHA1; m_pFiles[0].m_pSHA1 = m_pDataSHA1; } } else if (pFiles) { if (! pFiles->IsType(BENode::beList)) return FALSE; m_nFiles = pFiles->GetCount(); if (! m_nFiles || m_nFiles > 8192) return FALSE; m_pFiles = OP_NEWA(BTFile, m_nFiles); if (!m_pFiles) m_nFiles = 0; DEBUGTRACE_TORRENT(UNI_L("BT: files: %d\n"), m_nFiles); m_nTotalSize = 0; UINT64 offset = 0; for (int nFile = 0 ; nFile < m_nFiles ; nFile++) { BENode* pFile = pFiles->GetNode(nFile); if (! pFile->IsType(BENode::beDict)) return FALSE; BENode* pLength = pFile->GetNode("length"); if (! pLength->IsType(BENode::beInt)) return FALSE; m_pFiles[ nFile ].m_nSize = pLength->GetInt(); m_pFiles[ nFile ].m_nOffset = offset; BENode* pPath = pFile->GetNode("path.utf-8"); // prefer utf-8 if it exists: this is a hack for erroneously generated content. if (!pPath) pPath = pFile->GetNode("path"); if (! pPath->IsType(BENode::beList)) return FALSE; if (pPath->GetCount() > 32) return FALSE; // Hack to prefix all m_pFiles[ nFile ].m_sPath.Set(m_sName); for (int nPath = 0 ; nPath < pPath->GetCount() ; nPath++) { BENode* pPart = pPath->GetNode(nPath); if (! pPart->IsType(BENode::beString)) return FALSE; if (m_pFiles[ nFile ].m_sPath.Length()) m_pFiles[ nFile ].m_sPath.Append(PATHSEP); OpString strTmp; pPart->GetStringFromUTF8(strTmp); // BTInfo::SafeFilename(strTmp); m_pFiles[ nFile ].m_sPath.Append(strTmp); DEBUGTRACE_TORRENT(UNI_L("BT: filename: %s "), m_pFiles[ nFile ].m_sPath.CStr()); DEBUGTRACE_TORRENT(UNI_L("(%d)\n"), m_pFiles[ nFile ].m_nSize); } if (BENode* pSHA1 = pFile->GetNode("sha1")) { if (! pSHA1->IsType(BENode::beString) || pSHA1->GetStringLength() != sizeof(SHAStruct)) return FALSE; m_pFiles[ nFile ].m_bSHA1 = TRUE; memcpy(&m_pFiles[ nFile ].m_pSHA1, pSHA1->GetString(), sizeof(SHAStruct)); } m_nTotalSize += m_pFiles[ nFile ].m_nSize; offset += m_pFiles[ nFile ].m_nSize; } } else { return FALSE; } if((m_nTotalSize + m_nBlockSize - 1) / m_nBlockSize != m_nBlockCount) return FALSE; if(!CheckFiles()) return FALSE; pInfo->GetSHA1(&m_pInfoSHA1); m_bValid = TRUE; return TRUE; } ////////////////////////////////////////////////////////////////////// // BTInfo load torrent info from tree BOOL BTInfoImpl::CheckFiles() { OpString * pszPath; for (int nFile = 0 ; nFile < m_nFiles ; nFile++) { m_pFiles[ nFile ].m_sPath.Strip(TRUE, TRUE); pszPath = &(m_pFiles[ nFile ].m_sPath); if(pszPath->IsEmpty()) return FALSE; if(pszPath->Find(":") != KNotFound) return FALSE; if(pszPath->Compare("\\", 1) == 0 || pszPath->Compare("/", 1) == 0) return FALSE; if(pszPath->Find("..\\") != KNotFound) return FALSE; if(pszPath->Find("../") != KNotFound) return FALSE; } return(m_nFiles > 0); } ////////////////////////////////////////////////////////////////////// // BTInfo block testing void BTInfoImpl::BeginBlockTest() { OP_ASSERT(IsAvailable()); OP_ASSERT(m_pBlockSHA1 != NULL); m_pTestSHA1.Reset(); m_nTestByte = 0; } void BTInfoImpl::AddToTest(void *pInput, UINT32 nLength) { if (nLength == 0) return; OP_ASSERT(IsAvailable()); OP_ASSERT(m_pBlockSHA1 != NULL); OP_ASSERT(m_nTestByte + nLength <= m_nBlockSize); m_pTestSHA1.Add(pInput, nLength); m_nTestByte += nLength; } BOOL BTInfoImpl::FinishBlockTest(UINT32 nBlock) { OP_ASSERT(IsAvailable()); OP_ASSERT(m_pBlockSHA1 != NULL); if (nBlock >= m_nBlockCount) return FALSE; SHAStruct pSHA1; m_pTestSHA1.Finish(); m_pTestSHA1.GetHash(&pSHA1); return (BOOL)(pSHA1 == m_pBlockSHA1[ nBlock ]); } void BTInfoImpl::Escape(SHAStruct *pSHA1, OpString8& strEscaped) { static const char *pszHex = "0123456789ABCDEF"; char tmpbuf[sizeof(SHAStruct) * 3 + 1]; // max used if every character needs to be escaped + 1 byte for NUL terminator char *psz = (char *)tmpbuf; for (unsigned int nByte = 0 ; nByte < sizeof(SHAStruct) ; nByte++) { UINT32 nValue = (UINT32)pSHA1->n[ nByte ]; if ((nValue >= '0' && nValue <= '9') || (nValue >= 'a' && nValue <= 'z') || (nValue >= 'A' && nValue <= 'Z')) { *psz++ = (char)nValue; } else { *psz++ = '%'; *psz++ = pszHex[ (nValue >> 4) & 15 ]; *psz++ = pszHex[ nValue & 15 ]; } } *psz = 0; strEscaped.Set((char *)tmpbuf); } OP_STATUS BTInfoImpl::AddTorrentToDownload() { if(m_attachtodownload != NULL) { BTDownload *dl = (BTDownload *)m_attachtodownload; if(dl->SetTorrent(this) == OpStatus::OK) { BOOL fail; dl->FileDownloadBegin(fail); dl->CheckExistingFile(); } } else { SHAStruct SHA1; GetInfoHash(&SHA1); BTDownload *download = (BTDownload *)g_Downloads->FindByBTH(&SHA1); if(download == NULL) { download = OP_NEW(BTDownload, ()); if(download != NULL) { if(download->SetTorrent(this) == OpStatus::OK) { BOOL fail; g_Downloads->Add(download); download->FileDownloadBegin(fail); download->CheckExistingFile(); } else { OP_DELETE(download); } } } else { // download-> } } return OpStatus::OK; } #endif // _BITTORRENT_SUPPORT_ #endif //M2_SUPPORT
// // CCAsyncSprite.h // CCAsyncSprite // // Created by mac on 13-7-23. // // #ifndef __CCAsyncSprite__CCAsyncSprite__ #define __CCAsyncSprite__CCAsyncSprite__ #include <iostream> #include "cocos2d.h" #include "NetworkOperation.h" USING_NS_CC; class CCAsyncSprite :public CCSprite, public NetworkOperationDelegate { public: CCAsyncSprite(){}; ~CCAsyncSprite(); static CCAsyncSprite *createWithUrl(const char* pszUrl); virtual void operationDidFinish(NetworkOperation *operation); virtual void operationDidFail(NetworkOperation *operation); bool initWithUrl(const char* pszUrl); void setSpriteWithCCImage(CCImage *img); void setImage(const char *data, size_t size, const string &url); std::string m_strFileName; }; #endif /* defined(__CCAsyncSprite__CCAsyncSprite__) */
#ifndef PLAYER_H #define PLYAER_H #include "cocos2d.h" #include "Entity.h" #include "cocostudio\CocoStudio.h" using namespace cocostudio; USING_NS_CC; class EventFsm; class Player : public Entity { public: Player(); ~Player(); CREATE_FUNC(Player); virtual bool init(); virtual void stand(); virtual void run(); virtual void attack(); virtual void skill(); virtual void hurt(); virtual void dead(); virtual void win(); void bigfuck(); void sxskill(); virtual void setViewPointByPlayer(); void setTiledMap(TMXTiledMap* map); virtual void setTagPosition(float x, float y); void change(); void changes(); void sdingditu(); private: Armature* animate; Armature* animateq; EventFsm* fsm; TMXTiledMap* m_map; TMXLayer* meta; Point tileCoordForPosition(Point pos); bool lrxs = true; bool sdmap = false; }; #endif
#include<bits/stdc++.h> using namespace std; const int siz=20005; int rt,top,sum; int dfn[siz],low[siz],sta[siz],vis[siz]; vector<int> tmp,G[siz]; void tarjan(int u,int fa){ int i,v,id; sta[++top]=u; low[u]=dfn[u]=++rt; for(i=0;i<G[u].size();i++){ v=G[u][i]; if(dfn[v]==0){ tarjan(v,u); low[u]=min(low[u],low[v]); } else if(v!=fa) low[u]=min(low[u],dfn[v]); } if(low[u]==dfn[u]){ tmp.clear(); v=-1,id=u,sum++; while(v!=u){ v=sta[top--]; id=min(id,v); tmp.push_back(v); } for(i=0;i<tmp.size();i++) vis[tmp[i]]=id; } }
#ifndef PAIR_H #define PAIR_H #include <iostream> template<typename T> class Pair { public: Pair(void); Pair(T, T); Pair(const Pair<T>&); virtual ~Pair(void); void setInstance(T, T); void setInstance1(T); void setInstance2(T); T getInstance1(void); T getInstance2(void); const Pair<T>& operator=(const Pair<T>&); bool operator==(const Pair<T>&) const; private: T instance1; T instance2; }; template<typename T> Pair<T>::Pair(void) { instance1 = NULL; instance2 = NULL; // std::cerr << "make pair null\n"; } template<typename T> Pair<T>::Pair(T t1, T t2) : instance1(t1), instance2(t2) { // std::cerr << "make pair ordinary\n"; } template<typename T> Pair<T>::Pair(const Pair<T>& pair) { instance1 = pair.instance1; instance2 = pair.instance2; // std::cerr << " copy pair\n"; } template<typename T> Pair<T>::~Pair(void) { //do nothing? // std::cerr << "delete pair\n"; } template<typename T> void Pair<T>::setInstance(T t1, T t2) { instance1 = t1; instance2 = t2; } template<typename T> void Pair<T>::setInstance1(T t) { instance1 = t; } template<typename T> void Pair<T>::setInstance2(T t) { instance2 = t; } template<typename T> T Pair<T>::getInstance1(void) { return instance1; } template<typename T> T Pair<T>::getInstance2(void) { return instance2; } template<typename T> const Pair<T>& Pair<T>::operator=(const Pair<T>& pair) { instance1 = pair.instance1; instance2 = pair.instance2; return *this; } template<typename T> bool Pair<T>::operator==(const Pair<T>& pair) const { if ((instance1 == pair.instance1) && (instance2 == pair.instance2)) return true; if ((instance1 == pair.instance2) && (instance2 == pair.instance1)) return true; return false; } #endif
// Next Permutation /* 1. We can find next permutation using C++ STL @ Suppose we have a sting s = "bca" @ Code for that will be string s = "bca"; bool res = next_permutation(s.begin(), s.end()); if(res == false){ cout<<"No word possible"; } else{ cout<< s << endl; } 2. In the brute force approach we will calculate all the possible permutation @ After that we will find the next permutation. @ In case we have to find the next permutation of last element we can say that it would be 1st element. @ Time complexity => O(N*N) */ #include<bits/stdc++.h> using namespace std; void nextPermutation(vector<int>& a) { int idx = -1; int n = a.size(); for(int i=n-1; i>0; i--){ if(a[i] > a[i-1]){ idx = i; break; } } if(idx == -1){ reverse(a.begin(), a.end()); } else{ int prev = idx; for(int i=idx+1;i<n;i++){ if(a[i]>a[idx-1] and a[i]<=a[prev]){ prev = i; } } swap(a[idx-1], a[prev]); reverse(a.begin()+idx, a.end()); } } int main(){ vector<int> vect; vect.push_back(1); vect.push_back(2); vect.push_back(3); nextPermutation(vect); return 0; }
//PennyBoki @ </dream.in.code> #include <stdio.h> #include <conio.h> int main() { clrscr(); int A[3][3]; int B[3][3]; int C[3][3]; int X[3][3][3]; int i,j,m; printf("==========Enter matrix A==========\n"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) { printf(" A[%d][%d]= ",i,j); scanf("%d", &A[i][j]); C[i][j]=0; } } printf("\n==========Enter matrix B==========\n"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) { printf(" B[%d][%d]= ",i,j); scanf("%d", &B[i][j]); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) { for(m=0;m<3;m++) { X[i][j][m]=A[i][m]*B[m][j]; C[i][j]=C[i][j]+X[i][j][m]; } } } printf("\n==========matrix C==========\n"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) { printf(" C[%d][%d]= %d",i,j,C[i][j]); } } printf("\n\n"); getche(); return 0; }
class Solution{ public: // arr: input array // n: size of array //Function to sort the array into a wave-like array. void convertToWave(vector<int>& arr, int n){ sort(arr.begin(),arr.end()); for(int i =0;i<n-1;i+=2){ swap(arr[i],arr[i+1]); } } };
#include <WiFiClientSecure.h> #include <WiFiServerSecureBearSSL.h> #include <ESP8266WiFiType.h> #include <ESP8266WiFi.h> #include <CertStoreBearSSL.h> #include <WiFiServer.h> #include <WiFiClientSecureAxTLS.h> #include <WiFiClient.h> #include <WiFiServerSecureAxTLS.h> #include <WiFiClientSecureBearSSL.h> #include <ESP8266WiFiSTA.h> #include <ESP8266WiFiMulti.h> #include <ESP8266WiFiScan.h> #include <ESP8266WiFiGeneric.h> #include <BearSSLHelpers.h> #include <WiFiServerSecure.h> #include <ESP8266WiFiAP.h> #include <WiFiUdp.h> #include <DS1302RTC.h> #include <Time.h> #include <Stepper.h> #define STEPS 200 const int stepsPerRevolution = 200; Stepper stepper(stepsPerRevolution, 8, 9, 10, 11); DS1302RTC rtc(4, 6, 5); int previous = 0; void setup() { stepper.setSpeed(100); Serial.begin(115200); Serial.setDebugOutput(true); // if (rtc.haltRTC()) { // Serial.print("Clock stopped!"); // } // else { // Serial.print("Clock working."); // } // setSyncProvider(rtc.get); // the function to get the time from the RTC // if (timeStatus() == timeSet) { // Serial.print(" Ok!"); // } // else { // Serial.print(" FAIL!"); // } // Serial.println(); ESP.wdtDisable(); WiFi.begin("Casa_VM", "660f97a209"); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); } void loop() { digitalClockDisplay(); while (hour() >= 0 ) { //and (minute() >= 38 and minute() <= 50)) { rotateMotor(); } } void digitalClockDisplay() { // digital clock display of the time Serial.print(hour()); printDigits(minute()); printDigits(second()); Serial.println(); } void printDigits(int digits) { // utility function for digital clock display: prints preceding colon and leading 0 Serial.print(":"); if (digits < 10) Serial.print('0'); Serial.print(digits); } void rotateMotor() { stepper.step(-stepsPerRevolution); }
// Created on: 2014-03-17 // Created by: Kirill GAVRILOV // Copyright (c) 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 OpenGl_GlCore41_HeaderFile #define OpenGl_GlCore41_HeaderFile #include <OpenGl_GlCore40.hxx> //! OpenGL 4.1 definition. struct OpenGl_GlCore41 : public OpenGl_GlCore40 { private: typedef OpenGl_GlCore40 theBaseClass_t; public: //! @name GL_ARB_ES2_compatibility (added to OpenGL 4.1 core) using theBaseClass_t::glReleaseShaderCompiler; using theBaseClass_t::glShaderBinary; using theBaseClass_t::glGetShaderPrecisionFormat; using theBaseClass_t::glDepthRangef; using theBaseClass_t::glClearDepthf; public: //! @name GL_ARB_get_program_binary (added to OpenGL 4.1 core) using theBaseClass_t::glGetProgramBinary; using theBaseClass_t::glProgramBinary; using theBaseClass_t::glProgramParameteri; public: //! @name GL_ARB_separate_shader_objects (added to OpenGL 4.1 core) using theBaseClass_t::glUseProgramStages; using theBaseClass_t::glActiveShaderProgram; using theBaseClass_t::glCreateShaderProgramv; using theBaseClass_t::glBindProgramPipeline; using theBaseClass_t::glDeleteProgramPipelines; using theBaseClass_t::glGenProgramPipelines; using theBaseClass_t::glIsProgramPipeline; using theBaseClass_t::glGetProgramPipelineiv; using theBaseClass_t::glProgramUniform1i; using theBaseClass_t::glProgramUniform1iv; using theBaseClass_t::glProgramUniform1f; using theBaseClass_t::glProgramUniform1fv; using theBaseClass_t::glProgramUniform1d; using theBaseClass_t::glProgramUniform1dv; using theBaseClass_t::glProgramUniform1ui; using theBaseClass_t::glProgramUniform1uiv; using theBaseClass_t::glProgramUniform2i; using theBaseClass_t::glProgramUniform2iv; using theBaseClass_t::glProgramUniform2f; using theBaseClass_t::glProgramUniform2fv; using theBaseClass_t::glProgramUniform2d; using theBaseClass_t::glProgramUniform2dv; using theBaseClass_t::glProgramUniform2ui; using theBaseClass_t::glProgramUniform2uiv; using theBaseClass_t::glProgramUniform3i; using theBaseClass_t::glProgramUniform3iv; using theBaseClass_t::glProgramUniform3f; using theBaseClass_t::glProgramUniform3fv; using theBaseClass_t::glProgramUniform3d; using theBaseClass_t::glProgramUniform3dv; using theBaseClass_t::glProgramUniform3ui; using theBaseClass_t::glProgramUniform3uiv; using theBaseClass_t::glProgramUniform4i; using theBaseClass_t::glProgramUniform4iv; using theBaseClass_t::glProgramUniform4f; using theBaseClass_t::glProgramUniform4fv; using theBaseClass_t::glProgramUniform4d; using theBaseClass_t::glProgramUniform4dv; using theBaseClass_t::glProgramUniform4ui; using theBaseClass_t::glProgramUniform4uiv; using theBaseClass_t::glProgramUniformMatrix2fv; using theBaseClass_t::glProgramUniformMatrix3fv; using theBaseClass_t::glProgramUniformMatrix4fv; using theBaseClass_t::glProgramUniformMatrix2dv; using theBaseClass_t::glProgramUniformMatrix3dv; using theBaseClass_t::glProgramUniformMatrix4dv; using theBaseClass_t::glProgramUniformMatrix2x3fv; using theBaseClass_t::glProgramUniformMatrix3x2fv; using theBaseClass_t::glProgramUniformMatrix2x4fv; using theBaseClass_t::glProgramUniformMatrix4x2fv; using theBaseClass_t::glProgramUniformMatrix3x4fv; using theBaseClass_t::glProgramUniformMatrix4x3fv; using theBaseClass_t::glProgramUniformMatrix2x3dv; using theBaseClass_t::glProgramUniformMatrix3x2dv; using theBaseClass_t::glProgramUniformMatrix2x4dv; using theBaseClass_t::glProgramUniformMatrix4x2dv; using theBaseClass_t::glProgramUniformMatrix3x4dv; using theBaseClass_t::glProgramUniformMatrix4x3dv; using theBaseClass_t::glValidateProgramPipeline; using theBaseClass_t::glGetProgramPipelineInfoLog; public: //! @name GL_ARB_vertex_attrib_64bit (added to OpenGL 4.1 core) using theBaseClass_t::glVertexAttribL1d; using theBaseClass_t::glVertexAttribL2d; using theBaseClass_t::glVertexAttribL3d; using theBaseClass_t::glVertexAttribL4d; using theBaseClass_t::glVertexAttribL1dv; using theBaseClass_t::glVertexAttribL2dv; using theBaseClass_t::glVertexAttribL3dv; using theBaseClass_t::glVertexAttribL4dv; using theBaseClass_t::glVertexAttribLPointer; using theBaseClass_t::glGetVertexAttribLdv; public: //! @name GL_ARB_viewport_array (added to OpenGL 4.1 core) using theBaseClass_t::glViewportArrayv; using theBaseClass_t::glViewportIndexedf; using theBaseClass_t::glViewportIndexedfv; using theBaseClass_t::glScissorArrayv; using theBaseClass_t::glScissorIndexed; using theBaseClass_t::glScissorIndexedv; using theBaseClass_t::glDepthRangeArrayv; using theBaseClass_t::glDepthRangeIndexed; using theBaseClass_t::glGetFloati_v; using theBaseClass_t::glGetDoublei_v; }; #endif // _OpenGl_GlCore41_Header
/* -*- 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_ && defined LIBSSL_ENABLE_KEYGEN #include "modules/libssl/ssl_api.h" #include "modules/libssl/sslbase.h" #include "modules/libssl/options/sslopt.h" #include "modules/libssl/keygen_tracker.h" #include "modules/windowcommander/src/SSLSecurtityPasswordCallbackImpl.h" SSL_Private_Key_Generator::SSL_Private_Key_Generator() : m_format(SSL_Netscape_SPKAC), m_type(SSL_RSA), m_keysize(0), window(NULL), msg_handler(NULL), finished_message(MSG_NO_MESSAGE), finished_id(0), optionsManager(NULL), external_opt(FALSE), asking_password(NULL) { } SSL_Private_Key_Generator::~SSL_Private_Key_Generator() { m_spki_string.Wipe(); m_spki_string.Empty(); if(optionsManager && optionsManager->dec_reference() == 0) OP_DELETE(optionsManager); optionsManager = NULL; OP_DELETE(asking_password); asking_password = NULL; g_main_message_handler->UnsetCallBacks(this); } OP_STATUS SSL_Private_Key_Generator::Construct(SSL_dialog_config &config, URL &target, SSL_Certificate_Request_Format format, SSL_BulkCipherType type, const OpStringC8 &challenge, unsigned int keygen_size, SSL_Options *opt) { m_target_url = target; m_format = format; m_type = type; m_keysize = keygen_size; RETURN_IF_ERROR(m_challenge.Set(challenge)); window = config.window; msg_handler = config.msg_handler; finished_message = config.finished_message; finished_id = config.finished_id; if(opt) { optionsManager = opt; opt->inc_reference(); external_opt = TRUE; } return OpStatus::OK; } void SSL_Private_Key_Generator::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch(msg) { case MSG_LIBSSL_RUN_KEYALGORITHM_ITERATION: { OP_STATUS op_err = IterateKeyGeneration(); if(op_err != InstallerStatus::ERR_PASSWORD_NEEDED && OpStatus::IsError(op_err)) { Finished(FALSE); return; } else if(op_err == InstallerStatus::KEYGEN_WORKING) { g_main_message_handler->PostMessage( MSG_LIBSSL_RUN_KEYALGORITHM_ITERATION, (MH_PARAM_1) this, 0); } } break; case MSG_FINISHED_OPTIONS_PASSWORD: { g_main_message_handler->UnsetCallBack(this, MSG_FINISHED_OPTIONS_PASSWORD); if(par2 != IDOK) { Finished(FALSE); return; } OP_STATUS op_err = InternalStoreKey(); if(OpStatus::IsSuccess(op_err) || op_err != InstallerStatus::ERR_PASSWORD_NEEDED) Finished(OpStatus::IsSuccess(op_err)); } break; } } OP_STATUS SSL_Private_Key_Generator::StartKeyGeneration() { OP_STATUS op_err = InitiateKeyGeneration(); if(op_err == InstallerStatus::ERR_PASSWORD_NEEDED) return OpStatus::OK; else if(OpStatus::IsError(op_err)) return op_err; else if(op_err == InstallerStatus::KEYGEN_WORKING) { g_main_message_handler->PostMessage( MSG_LIBSSL_RUN_KEYALGORITHM_ITERATION, (MH_PARAM_1) this, 0); return g_main_message_handler->SetCallBack(this, MSG_LIBSSL_RUN_KEYALGORITHM_ITERATION, (MH_PARAM_1) this); } return op_err; } OP_STATUS SSL_Private_Key_Generator::StoreKey(SSL_secure_varvector32 &pkcs8_private_key, SSL_secure_varvector32 &public_key_hash) { m_pkcs8_private_key = pkcs8_private_key; if(m_pkcs8_private_key.Error()) return m_pkcs8_private_key.GetOPStatus(); m_public_key_hash = public_key_hash; if(m_public_key_hash.Error()) return m_public_key_hash.GetOPStatus(); if(!optionsManager) { optionsManager = g_ssl_api->CreateSecurityManager(TRUE); if(optionsManager == NULL) { Finished(FALSE); return OpStatus::ERR_NO_MEMORY; } external_opt = FALSE; } OP_STATUS op_err = OpStatus::OK; if(OpStatus::IsError(op_err = optionsManager->Init(SSL_ClientStore))) { Finished(FALSE); return op_err; } return InternalStoreKey(); } OP_STATUS SSL_Private_Key_Generator::InternalStoreKey() { if(optionsManager == NULL) return OpStatus::ERR_NULL_POINTER; SSL_dialog_config dialog_options(window, g_main_message_handler, MSG_FINISHED_OPTIONS_PASSWORD, (MH_PARAM_1) this, m_target_url); OpString temp_name; OpStatus::Ignore(m_target_url.GetAttribute(URL::KUniName, 0, temp_name)); OP_STATUS op_err = optionsManager->AddPrivateKey(m_type, m_keysize, m_pkcs8_private_key, m_public_key_hash, temp_name, dialog_options); if(op_err == InstallerStatus::ERR_PASSWORD_NEEDED) { g_main_message_handler->SetCallBack(this, MSG_FINISHED_OPTIONS_PASSWORD, (MH_PARAM_1) this); return op_err; } Finished(OpStatus::IsSuccess(op_err)); return op_err; } void SSL_Private_Key_Generator::Finished(BOOL success) { if(success && !external_opt) g_ssl_api->CommitOptionsManager(optionsManager); msg_handler->PostMessage(finished_message, finished_id, (success ? TRUE : FALSE)); } #endif // LIBSSL_ENABLE_KEYGEN
#include "ManagerUtils/PlotUtils/interface/Common.hpp" #include "TriggerEfficiency/EfficiencyPlot/interface/EfficiencyPlot.h" using namespace std; extern void DrawEff() { for( const auto& trg : PlotMgr().GetListData<string>( "trglst" ) ){ DrawEta( trg ); DrawPt( trg ); } } extern void DrawEta(const string& trg) { string trgname = dra::GetSingle<string>( "trgname", PlotMgr().GetSubTree( trg ) ); string cut = dra::GetSingle<string>( "pcut", PlotMgr().GetSubTree( trg ) ); TCanvas* c = mgr::NewCanvas(); TPad* top = mgr::NewTopPad(); top->Draw(); top->cd(); TH1F* h1 = gPad->DrawFrame( -3, 0, 3, 1.2 ); SetHistTitle( h1, "", "Efficiency" ); mgr::SetTopPlotAxis( h1 ); TLegend* leg = mgr::NewLegend( 0.55, 0.18, 0.65, 0.35 ); leg->SetLineColor( kWhite ); TGraphAsymmErrors* data = HistTEff( "data" + trg, "eff_eta" )->CreateGraph(); TGraphAsymmErrors* mc = HistTEff( "mc" + trg, "eff_eta" )->CreateGraph(); data->Draw( "EP" ); mc->Draw("EP"); SetHist(data, kGray+1, 33); SetHist(mc, kAzure-3, 8); leg->AddEntry( data, PlotMgr().GetOption<string>( "source" ).c_str(), "lp" ); leg->AddEntry( mc, "MC", "lp" ); leg->Draw(); TPaveText* pt = mgr::NewTextBox( .45, .76, .93, .84 ); pt->AddText( ( trgname + cut ).c_str() ); pt->Draw(); TLine* line1 = new TLine( -3, 1, 3, 1 ); line1->SetLineColor( kRed ); line1->SetLineStyle( 8 ); line1->Draw(); c->cd(); /**************************************************************************/ TPad* bot = mgr::NewBottomPad(); bot->Draw(); bot->cd(); TH1F* h2 = gPad->DrawFrame( -3, 0.9, 3, 1.1 ); SetHistTitle( h2, "SuperCluster #eta", "Data/Mc" ); mgr::SetBottomPlotAxis( h2 ); h2->GetYaxis()->SetLabelSize(14); TGraphAsymmErrors* scale = DividedGraph(data, mc); scale->Draw("EP"); SetBottomHist(scale); TLine* line2 = new TLine( -3, 1, 3, 1 ); line2->SetLineColor( kRed ); line2->SetLineStyle( 8 ); line2->Draw(); c->cd(); mgr::DrawCMSLabelOuter( PRELIMINARY ); mgr::DrawLuminosity( PlotMgr().GetOption<double>( "lumi" ) ); mgr::SaveToPDF( c, PlotMgr().GetResultsName( "pdf", "Eta_Eff_" + trg ) ); mgr::SaveToROOT( scale, PlotMgr().GetResultsName( "root", "SF_" + trg ), "eta" ); delete c; delete line1; delete line2; delete leg; delete pt; } extern void DrawPt( const string& trg ) { string trgname = dra::GetSingle<string>( "trgname", PlotMgr().GetSubTree( trg ) ); string cut = dra::GetSingle<string>( "ecut", PlotMgr().GetSubTree( trg ) ); TCanvas* c = mgr::NewCanvas(); TPad* top = mgr::NewTopPad(); top->Draw(); top->cd(); TH1F* h1 = gPad->DrawFrame( 0, 0, 500, 1.2 ); SetHistTitle( h1, "", "Efficiency" ); mgr::SetTopPlotAxis( h1 ); TLegend* leg = mgr::NewLegend( 0.65, 0.23, 0.75, 0.4 ); leg->SetLineColor( kWhite ); TGraphAsymmErrors* data = HistTEff( "data" + trg, "eff_pt" )->CreateGraph(); TGraphAsymmErrors* mc = HistTEff( "mc" + trg, "eff_pt" )->CreateGraph(); data->Draw( "EP" ); mc->Draw("EP"); SetHist(data, kGray+1, 33); SetHist(mc, kAzure-3, 8); leg->AddEntry( data, PlotMgr().GetOption<string>( "source" ).c_str(), "lp" ); leg->AddEntry( mc, "MC", "lp" ); leg->Draw(); TLine* line1 = new TLine( 0, 1, 500, 1 ); line1->SetLineColor( kRed ); line1->SetLineStyle( 8 ); line1->Draw(); TPaveText* pt = mgr::NewTextBox( .5, .76, .93, .84 ); pt->AddText( ( trgname + cut ).c_str() ); pt->Draw(); c->cd(); /**************************************************************************/ TPad* bot = mgr::NewBottomPad(); bot->Draw(); bot->cd(); TH1F* h2 = gPad->DrawFrame( 0, 0.9, 500, 1.1 ); SetHistTitle( h2, "P_{T}", "Data/MC" ); mgr::SetBottomPlotAxis( h2 ); h2->GetYaxis()->SetLabelSize(14); TGraphAsymmErrors* scale = DividedGraph(data, mc); scale->Draw("EP"); SetBottomHist(scale); TLine* line2 = new TLine( 0, 1, 500, 1 ); line2->SetLineColor( kRed ); line2->SetLineStyle( 8 ); line2->Draw(); c->cd(); mgr::DrawCMSLabelOuter( PRELIMINARY ); mgr::DrawLuminosity( PlotMgr().GetOption<double>( "lumi" ) ); mgr::SaveToPDF( c, PlotMgr().GetResultsName( "pdf", "Pt_Eff_" + trg ) ); mgr::SaveToROOT( scale, PlotMgr().GetResultsName( "root", "SF_" + trg ), "pt" ); delete c; delete line1; delete line2; delete leg; delete pt; } extern void SetBottomHist(TGraphAsymmErrors* hist) { hist->SetMarkerSize(1); hist->SetMarkerStyle(8); } extern void SetHist(TGraphAsymmErrors* hist, Color_t c, int m) { hist->SetLineWidth(2); hist->SetLineColor(c); hist->SetMarkerColor(c); hist->SetMarkerSize(1); hist->SetMarkerStyle(m); } extern void SetHistTitle( TH1* h, const string& xaxis, const string& yaxis ) { h->GetXaxis()->SetTitle( xaxis.c_str() ); h->GetYaxis()->SetTitle( yaxis.c_str() ); } extern TGraphAsymmErrors* DividedGraph( TGraphAsymmErrors* num, TGraphAsymmErrors* den ) { TGraphAsymmErrors* ans = new TGraphAsymmErrors( num->GetN() ); for( int i = 0; i < num->GetN(); ++i ){ const double numy = num->GetY()[i]; const double numyerrlo = num->GetErrorYlow( i ); const double numyerrhi = num->GetErrorYhigh( i ); const double deny = den->GetY()[i]; const double denyerrlo = den->GetErrorYlow( i ); const double denyerrhi = den->GetErrorYhigh( i ); const double numx = num->GetX()[i]; const double xerrlo = num->GetErrorXlow( i ); const double xerrhi = num->GetErrorXhigh( i ); ans->SetPoint( i, numx, numy / deny ); ans->SetPointError( i, xerrlo, xerrhi, ErrorProp( numy, numyerrlo, deny, denyerrlo ), ErrorProp( numy, numyerrhi, deny, denyerrhi ) ); } ans->SetTitle( "" ); return ans; }
#ifndef MACRO_MANAGER_H #define MACRO_MANAGER_H #include <sc2api\sc2_api.h> #include "Orders.h" #include "Order.h" using namespace sc2; class MacroManager { public: MacroManager(); void GetObservations(const ObservationInterface * obs); ~MacroManager(); Orders ThinkAndSendOrders(const sc2::ObservationInterface* observation); }; #endif
#include <iostream> #include <cstring> using namespace std; char TF[27]; char TM[27]; void TL( int p1, int p2, int q1, int q2, int root ) { if ( p1 > p2 ) return; for ( root = q1 ; TM[root] != TF[p1] ; ++ root ); TL( p1+1, p1+root-q1, q1, root-1, 0 ); TL( p1+root-q1+1, p2, root+1, q2, 0 ); cout << TM[root]; } int main() { while ( cin >> TF >> TM ) { int L = strlen(TF)-1; TL( 0, L, 0, L, 0 ); cout << endl; } return 0; }
#pragma once #include "GameObject.h" class Character; class Cage : public GameObject { public: Cage(DirectX::XMFLOAT3 position = {}); virtual ~Cage() = default; Cage(const Cage& other) = delete; Cage(Cage&& other) noexcept = delete; Cage& operator=(const Cage& other) = delete; Cage& operator=(Cage&& other) noexcept = delete; void Initialize(const GameContext& gameContext) override; void Update(const GameContext& gameContext) override; private: DirectX::XMFLOAT3 m_Position; UINT m_Health = 3; bool m_IsCollected = false; Character* m_Player = nullptr; };
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "LevinProtocol.h" #include <System/TcpConnection.h> using namespace cn; namespace { const uint64_t LEVIN_SIGNATURE = 0x0101010101012101LL; //Bender's nightmare const uint32_t LEVIN_PACKET_REQUEST = 0x00000001; const uint32_t LEVIN_PACKET_RESPONSE = 0x00000002; const uint32_t LEVIN_DEFAULT_MAX_PACKET_SIZE = 100000000; //100MB by default const uint32_t LEVIN_PROTOCOL_VER_1 = 1; #pragma pack(push) #pragma pack(1) struct bucket_head2 { uint64_t m_signature; uint64_t m_cb; bool m_have_to_return_data; uint32_t m_command; int32_t m_return_code; uint32_t m_flags; uint32_t m_protocol_version; }; #pragma pack(pop) } bool LevinProtocol::Command::needReply() const { return !(isNotify || isResponse); } LevinProtocol::LevinProtocol(platform_system::TcpConnection& connection) : m_conn(connection) {} void LevinProtocol::sendMessage(uint32_t command, const BinaryArray& out, bool needResponse) { bucket_head2 head = { 0 }; head.m_signature = LEVIN_SIGNATURE; head.m_cb = out.size(); head.m_have_to_return_data = needResponse; head.m_command = command; head.m_protocol_version = LEVIN_PROTOCOL_VER_1; head.m_flags = LEVIN_PACKET_REQUEST; // write header and body in one operation BinaryArray writeBuffer; writeBuffer.reserve(sizeof(head) + out.size()); common::VectorOutputStream stream(writeBuffer); stream.writeSome(&head, sizeof(head)); stream.writeSome(out.data(), out.size()); writeStrict(writeBuffer.data(), writeBuffer.size()); } bool LevinProtocol::readCommand(Command& cmd) { bucket_head2 head = { 0 }; if (!readStrict(reinterpret_cast<uint8_t*>(&head), sizeof(head))) { return false; } if (head.m_signature != LEVIN_SIGNATURE) { throw std::runtime_error("Levin signature mismatch"); } if (head.m_cb > LEVIN_DEFAULT_MAX_PACKET_SIZE) { throw std::runtime_error("Levin packet size is too big"); } BinaryArray buf; if (head.m_cb != 0) { buf.resize(head.m_cb); if (!readStrict(&buf[0], head.m_cb)) { return false; } } cmd.command = head.m_command; cmd.buf = std::move(buf); cmd.isNotify = !head.m_have_to_return_data; cmd.isResponse = (head.m_flags & LEVIN_PACKET_RESPONSE) == LEVIN_PACKET_RESPONSE; return true; } void LevinProtocol::sendReply(uint32_t command, const BinaryArray& out, int32_t returnCode) { bucket_head2 head = { 0 }; head.m_signature = LEVIN_SIGNATURE; head.m_cb = out.size(); head.m_have_to_return_data = false; head.m_command = command; head.m_protocol_version = LEVIN_PROTOCOL_VER_1; head.m_flags = LEVIN_PACKET_RESPONSE; head.m_return_code = returnCode; BinaryArray writeBuffer; writeBuffer.reserve(sizeof(head) + out.size()); common::VectorOutputStream stream(writeBuffer); stream.writeSome(&head, sizeof(head)); stream.writeSome(out.data(), out.size()); writeStrict(writeBuffer.data(), writeBuffer.size()); } void LevinProtocol::writeStrict(const uint8_t* ptr, size_t size) { size_t offset = 0; while (offset < size) { offset += m_conn.write(ptr + offset, size - offset); } } bool LevinProtocol::readStrict(uint8_t* ptr, size_t size) { size_t offset = 0; while (offset < size) { size_t read = m_conn.read(ptr + offset, size - offset); if (read == 0) { return false; } offset += read; } return true; }
#ifndef SPEECH_H #define SPEECH_H #include <QDialog> namespace Ui { class speech; } class speech : public QDialog { Q_OBJECT public: explicit speech(QWidget *parent = 0); ~speech(); private slots: void on_pushButton_clicked(); void on_pushButton_2_clicked(); private: Ui::speech *ui; }; #endif // SPEECH_H
/* https://www.acmicpc.net/problem/9498 */ #include <iostream> using namespace std; // 시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, 나머지 점수는 F를 출력하는 프로그램을 작성하시오. int main(void) { int score; scanf("%d", &score); if (score >= 90) printf("A"); else if (score >= 80) printf("B"); else if (score >= 70) printf("C"); else if (score >= 60) printf("D"); else printf("F"); return 0; }
#include "odb/client/tcp-data-client.hh" #include <arpa/inet.h> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <netdb.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include "odb/mess/tcp-transfer.hh" namespace odb { namespace { bool err(const char *msg) { std::cerr << "Warning: TCPDataClient: " << msg << "\n"; return false; } } // namespace TCPDataClient::TCPDataClient(const std::string &hostname, int port) : _hostname(hostname), _port(port), _fd(-1) {} TCPDataClient::~TCPDataClient() { if (_fd != -1) close(_fd); } bool TCPDataClient::connect() { if ((_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return err("Failed to create socket"); struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(_port); if (inet_pton(AF_INET, _hostname.c_str(), &serv_addr.sin_addr) <= 0) return err("Failed to convert hostname to ip"); if (::connect(_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) return err("Failed to connect to server"); // Disable Nagle algorithm to solve small packets issue int yes = 1; if (setsockopt(_fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == -1) return err("setsockopt TCP_NODELAY failed"); return true; } bool TCPDataClient::send_data(const SerialOutBuff &os) { return send_data_tcp(os, _fd); } bool TCPDataClient::recv_data(SerialInBuff &is) { return recv_data_tcp(is, _fd); } } // namespace odb
#include "test.hpp" #include "graph.hpp" namespace { void test_selectGraphParam() { const int M = 1234; for(int i = 0; i <= M; ++i) { bool called = false; selectGraphParam<M>(i, [&](auto sel) { const int N = sel.Val; checkLessOrEqual(i, N); if(i == 0) { checkEqual(N, 1); } else { checkGreater(2 * i, N); } checkLessOrEqual(i, Graph<N>::B::BitCount); called = true; }); checkTrue(called); } } void test_readGraph() { for(int t = 0; t < 100; ++t) { int n = UnifInt<int>(0, min(DefaultMaxGraphSize, 64))(rng); double p = UnifReal<double>(-0.05, 1.05)(rng); vector<vector<bool>> vals(n); for(int i = 0; i < n; ++i) { vals[i].resize(n); for(int j = 0; j < n; ++j) { if(i != j && UnifReal<double>(0.0, 1.0)(rng) < p) { vals[i][j] = true; } } } stringstream ss; ss << n << '\n'; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(j) { ss << ' '; } ss << (int)vals[i][j]; } ss << '\n'; } ss.seekg(0); bool called = false; readGraph(ss, [&](auto g) { checkEqual(g.size(), n); checkLessOrEqual(n, g.ParamN); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { checkEqual(g(i, j), (bool)vals[i][j]); } } ss.seekg(0); Graph<g.ParamN> g2 = Graph<g.ParamN>::read(ss); checkEqual(g, g2); called = true; }); checkTrue(called); ss.seekg(0); GraphData graphData = GraphData::read(ss); graphData.accessGraph([&](auto g) { ss.seekg(0); Graph<g.ParamN> g2 = Graph<g.ParamN>::read(ss); checkEqual(g, g2); }); } } template <int N> struct TestGraph { typedef Graph<N> G; typedef typename G::B B; static G randomGraph() { int n = UnifInt<int>(0, N)(rng); G g(n); double p = UnifReal<double>(-0.05, 1.05)(rng); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(i != j && UnifReal<double>(0.0, 1.0)(rng) < p) { g.addD(i, j); } } } return g; } static void testConstructors() { { G g; checkEqual(g.size(), 0); } for(int n = 0; n <= N; ++n) { G g(n); checkEqual(g.size(), n); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { checkFalse(g(i, j)); } } } } static void testAccessors() { for(int t = 0; t < 100; ++t) { G g = randomGraph(); for(int i = 0; i < g.size(); ++i) { for(int j = 0; j < g.size(); ++j) { checkEqual(g(i, j), g.edgesOut(i).has(j)); checkEqual(g(j, i), g.edgesOut(j).has(i)); checkEqual(g(i, j), g.edgesIn(j).has(i)); checkEqual(g(j, i), g.edgesIn(i).has(j)); } } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); for(int v = 0; v < g.size(); ++v) { checkTrue(isSubset(g.edgesIn(v), B::range(g.size()))); checkTrue(isSubset(g.edgesOut(v), B::range(g.size()))); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); G h(g.size()); for(int i = 0; i < g.size(); ++i) { for(int j = 0; j < g.size(); ++j) { if(g(i, j)) { h.addD(i, j); } } } checkEqual(g, h); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } G a = g; a.addD(x, y); G b = g; b.setD(x, y, true); checkEqual(a, b); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } G a = g; a.delD(x, y); G b = g; b.setD(x, y, false); checkEqual(a, b); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } G a = g; a.addU(x, y); G b = g; b.setU(x, y, true); checkEqual(a, b); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } G a = g; a.delU(x, y); G b = g; b.setU(x, y, false); checkEqual(a, b); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } G a = g; a.addU(x, y); G b = g; b.addD(x, y); b.addD(y, x); checkEqual(a, b); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } G a = g; a.delU(x, y); G b = g; b.delD(x, y); b.delD(y, x); checkEqual(a, b); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); checkEqual(g.vertexSet(), B::range(g.size())); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); for(int i = 0; i < g.size(); ++i) { for(int j = 0; j < g.size(); ++j) { checkEqual(g.neighbors(i).has(j), g(i, j) || g(j, i)); checkEqual(g.bidirectionalNeighbors(i).has(j), g(i, j) && g(j, i)); checkEqual(g.directedEdgesOut(i).has(j), g(i, j) && !g(j, i)); checkEqual(g.directedEdgesIn(i).has(j), g(j, i) && !g(i, j)); } } } } static void testComparisons() { for(int t = 0; t < 100; ++t) { G a = randomGraph(); G b = a; checkTrue(a == b); checkFalse(a != b); } for(int t = 0; t < 100; ++t) { G a = randomGraph(); G b = randomGraph(); bool eq = a.size() == b.size(); if(eq) { for(int i = 0; i < a.size(); ++i) { for(int j = 0; j < b.size(); ++j) { if(a(i, j) != b(i, j)) { eq = false; } } } } checkEqual(a == b, eq); checkNotEqual(a != b, eq); } for(int t = 0; t < 100; ++t) { G a = randomGraph(); if(a.size() >= 2) { G b = a; int x = UnifInt<int>(0, a.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, a.size() - 1)(rng); } b.setD(x, y, !b(x, y)); checkFalse(a == b); checkTrue(a != b); } } } static void testQueries() { for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 2) { int x = UnifInt<int>(0, g.size() - 1)(rng); int y = x; while(y == x) { y = UnifInt<int>(0, g.size() - 1)(rng); } g.addD(x, y); g.delD(y, x); checkFalse(g.isUndirected()); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); for(int x = 0; x < g.size(); ++x) { for(int y = x + 1; y < g.size(); ++y) { g.setD(y, x, g(x, y)); } } checkTrue(g.isUndirected()); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); verts.iterate([&](int a) { verts.iterate([&](int b) { if(a < b) { int r = UnifInt<int>(-1, 1)(rng); if(r >= 0) { g.addD(a, b); } if(r <= 0) { g.addD(b, a); } } }); }); checkTrue(g.isClique(verts)); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.delU(verts.nth(i), verts.nth(j)); checkFalse(g.isClique(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); verts.iterate([&](int a) { verts.iterate([&](int b) { if(a < b) { g.delU(a, b); } }); }); checkTrue(g.isIndependentSet(verts)); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.addD(verts.nth(i), verts.nth(j)); checkFalse(g.isIndependentSet(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); verts.iterate([&](int a) { verts.iterate([&](int b) { if(a < b) { g.addU(a, b); } }); }); checkTrue(g.isBidirectionalClique(verts)); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.delD(verts.nth(i), verts.nth(j)); checkFalse(g.isBidirectionalClique(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); verts.iterate([&](int a) { verts.iterate([&](int b) { if(a < b) { int r = UnifInt<int>(-1, 1)(rng); if(r >= 0) { g.delD(a, b); } if(r <= 0) { g.delD(b, a); } } }); }); checkTrue(g.isBidirectionalIndependentSet(verts)); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.addU(verts.nth(i), verts.nth(j)); checkFalse(g.isBidirectionalIndependentSet(verts)); } } } static void testOperations() { for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); { G h = g.inducedSubgraph(verts); checkEqual(h.size(), verts.count()); for(int i = 0; i < h.size(); ++i) { for(int j = 0; j < h.size(); ++j) { checkEqual(h(i, j), g(verts.nth(i), verts.nth(j))); } } } g.inducedSubgraphReSelectN(verts, [&](const auto& h) { checkEqual(h.size(), verts.count()); for(int i = 0; i < h.size(); ++i) { for(int j = 0; j < h.size(); ++j) { checkEqual(h(i, j), g(verts.nth(i), verts.nth(j))); } } }); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); int cc = UnifInt<int>(1, 5)(rng); vector<B> comps(cc); for(int i = 0; i < g.size(); ++i) { comps[UnifInt<int>(0, cc - 1)(rng)].add(i); } for(int i = 0; i < cc; ++i) { for(int j = i + 1; j < cc; ++j) { comps[i].iterate([&](int a) { comps[j].iterate([&](int b) { if(rng() & 1) { g.delD(a, b); } else { g.delD(b, a); } }); }); } } int nonEmptyCount = 0; for(B comp : comps) { if(comp.isNonEmpty()) { ++nonEmptyCount; } } B un; int count = 0; g.iterateBidirectionalComponents([&](B comp) { checkTrue(comp.isNonEmpty()); checkTrue(setIntersection(un, comp).isEmpty()); un = setUnion(un, comp); comp.iterate([&](int v) { checkTrue(isSubset(g.bidirectionalNeighbors(v), comp)); checkEqual(g.bidirectionalComponent(v), comp); }); ++count; }); checkEqual(un, g.vertexSet()); checkGreaterOrEqual(count, nonEmptyCount); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); int cc = UnifInt<int>(1, 5)(rng); vector<B> comps(cc); for(int i = 0; i < g.size(); ++i) { comps[UnifInt<int>(0, cc - 1)(rng)].add(i); } for(int i = 0; i < cc; ++i) { for(int j = i + 1; j < cc; ++j) { comps[i].iterate([&](int a) { comps[j].iterate([&](int b) { if(rng() & 1) { g.delD(a, b); } else { g.delD(b, a); } }); }); } } B verts = setIntersection(B::random(), g.vertexSet()); vector<B> a; g.iterateBidirectionalComponents(verts, [&](B comp) { a.push_back(comp); }); vector<B> b; g.inducedSubgraph(verts).iterateBidirectionalComponents([&](B comp) { b.push_back(B::unpack(comp, verts)); }); sort(a.begin(), a.end()); sort(b.begin(), b.end()); checkEqual(a, b); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); int cc = UnifInt<int>(1, 5)(rng); vector<B> comps(cc); for(int i = 0; i < g.size(); ++i) { comps[UnifInt<int>(0, cc - 1)(rng)].add(i); } for(int i = 0; i < cc; ++i) { for(int j = i + 1; j < cc; ++j) { comps[i].iterate([&](int a) { comps[j].iterate([&](int b) { g.delU(a, b); }); }); } } int nonEmptyCount = 0; for(B comp : comps) { if(comp.isNonEmpty()) { ++nonEmptyCount; } } B un; int count = 0; g.iterateComponents([&](B comp) { checkTrue(comp.isNonEmpty()); checkTrue(setIntersection(un, comp).isEmpty()); un = setUnion(un, comp); comp.iterate([&](int v) { checkTrue(isSubset(g.neighbors(v), comp)); checkEqual(g.component(v), comp); }); ++count; }); checkEqual(un, g.vertexSet()); checkGreaterOrEqual(count, nonEmptyCount); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); int cc = UnifInt<int>(1, 5)(rng); vector<B> comps(cc); for(int i = 0; i < g.size(); ++i) { comps[UnifInt<int>(0, cc - 1)(rng)].add(i); } for(int i = 0; i < cc; ++i) { for(int j = i + 1; j < cc; ++j) { comps[i].iterate([&](int a) { comps[j].iterate([&](int b) { if(rng() & 1) { g.delD(a, b); } else { g.delD(b, a); } }); }); } } B verts = setIntersection(B::random(), g.vertexSet()); vector<B> a; g.iterateComponents(verts, [&](B comp) { a.push_back(comp); }); vector<B> b; g.inducedSubgraph(verts).iterateComponents([&](B comp) { b.push_back(B::unpack(comp, verts)); }); sort(a.begin(), a.end()); sort(b.begin(), b.end()); checkEqual(a, b); } for(int t = 0; t < 100; ++t) { int n = UnifInt<int>(0, N)(rng); G g(n); for(int i = 1; i < n; ++i) { int j = UnifInt<int>(0, i - 1)(rng); g.addU(i, j); } for(int v = 0; v < n; ++v) { checkEqual(g.bidirectionalComponent(v), g.vertexSet()); } g = g.withShuffledVertices(); for(int v = 0; v < n; ++v) { checkEqual(g.bidirectionalComponent(v), g.vertexSet()); } } for(int t = 0; t < 100; ++t) { int n = UnifInt<int>(0, N)(rng); G g(n); for(int i = 1; i < n; ++i) { int j = UnifInt<int>(0, i - 1)(rng); switch(UnifInt<int>(0, 2)(rng)) { case 0: g.addD(i, j); break; case 1: g.addD(j, i); break; case 2: g.addU(i, j); break; } } for(int v = 0; v < n; ++v) { checkEqual(g.component(v), g.vertexSet()); } g = g.withShuffledVertices(); for(int v = 0; v < n; ++v) { checkEqual(g.component(v), g.vertexSet()); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); for(int v = 0; v < g.size(); ++v) { B verts = setIntersection(B::random(), g.vertexSet()).with(v); B reachable = g.reachableVertices(verts, v); checkTrue(isSubset(reachable, verts)); checkTrue(reachable.has(v)); reachable.iterate([&](int i) { setIntersection(g.edgesOut(i), verts).iterate([&](int j) { checkTrue(reachable.has(j)); }); if(i != v) { bool found = false; setIntersection(g.edgesIn(i), verts).iterate([&](int j) { if(reachable.has(j)) { found = true; } }); checkTrue(found); } }); int x = setIntersection(verts, B::range(v)).count(); checkEqual(reachable, B::unpack(g.inducedSubgraph(verts).reachableVertices(x), verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); for(int v = 0; v < g.size(); ++v) { B verts = setIntersection(B::random(), g.vertexSet()).with(v); B reachable = g.directedReachableVertices(verts, v); checkTrue(isSubset(reachable, verts)); checkTrue(reachable.has(v)); reachable.iterate([&](int i) { setIntersection(g.directedEdgesOut(i), verts).iterate([&](int j) { checkTrue(reachable.has(j)); }); if(i != v) { bool found = false; setIntersection(g.directedEdgesIn(i), verts).iterate([&](int j) { if(reachable.has(j)) { found = true; } }); checkTrue(found); } }); G subg = g.inducedSubgraph(verts); verts.iterate([&](int x) { checkEqual(reachable.has(x), g.isDirectedReachable(verts, v, x)); checkEqual(reachable.has(x), subg.isDirectedReachable(setIntersection(B::range(v), verts).count(), setIntersection(B::range(x), verts).count())); }); int x = setIntersection(verts, B::range(v)).count(); checkEqual(reachable, B::unpack(subg.directedReachableVertices(x), verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); G h = g.withShuffledVertices(); checkEqual(g.size(), h.size()); int n = g.size(); vector<int> inDegreesG(n); vector<int> outDegreesG(n); for(int i = 0; i < n; ++i) { inDegreesG[i] = g.edgesIn(i).count(); outDegreesG[i] = g.edgesOut(i).count(); } vector<int> inDegreesH(n); vector<int> outDegreesH(n); for(int i = 0; i < n; ++i) { inDegreesH[i] = h.edgesIn(i).count(); outDegreesH[i] = h.edgesOut(i).count(); } sort(inDegreesG.begin(), inDegreesG.end()); sort(outDegreesG.begin(), outDegreesG.end()); sort(inDegreesH.begin(), inDegreesH.end()); sort(outDegreesH.begin(), outDegreesH.end()); checkEqual(inDegreesG, inDegreesH); checkEqual(outDegreesG, outDegreesH); } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.delU(verts.nth(i), verts.nth(j)); checkFalse(g.isClique(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.addD(verts.nth(i), verts.nth(j)); checkFalse(g.isIndependentSet(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.delD(verts.nth(i), verts.nth(j)); checkFalse(g.isBidirectionalClique(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); B verts = setIntersection(B::random(), g.vertexSet()); int vc = verts.count(); if(vc >= 2) { int i = UnifInt<int>(0, vc - 1)(rng); int j = i; while(j == i) { j = UnifInt<int>(0, vc - 1)(rng); } g.addU(verts.nth(i), verts.nth(j)); checkFalse(g.isBidirectionalIndependentSet(verts)); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); stringstream ss; g.write(ss); ss.seekg(0); checkEqual(g, G::read(ss)); } } static void testChordal() { for(int t = 0; t < 500; ++t) { G g = randomGraph(); bool isChordal = g.isChordal(); checkEqual(isChordal, g.withShuffledVertices().isChordal()); if(isChordal) { vector<int> order = g.findPerfectEliminationOrderingInChordal(); checkEqual(order.size(), (size_t)g.size()); { vector<int> cmp(g.size()); g.findPerfectEliminationOrderingInChordal(cmp.data()); checkEqual(order, cmp); } { bool res; vector<int> cmp; tie(res, cmp) = g.tryFindPerfectEliminationOrdering(); checkTrue(res); checkEqual(order, cmp); } { bool res; vector<int> cmp(g.size()); res = g.tryFindPerfectEliminationOrdering(cmp.data()); checkTrue(res); checkEqual(order, cmp); } { vector<int> sortedOrder = order; sort(sortedOrder.begin(), sortedOrder.end()); vector<int> cmp(g.size()); for(int i = 0; i < g.size(); ++i) { cmp[i] = i; } checkEqual(sortedOrder, cmp); } B seen; for(int i = g.size() - 1; i >= 0; --i) { int v = order[i]; checkTrue(g.isClique(setIntersection(g.neighbors(v), seen))); seen.add(v); } } else { checkEqual(g.tryFindPerfectEliminationOrdering(), make_pair(false, vector<int>())); vector<int> ignore(g.size()); checkFalse(g.tryFindPerfectEliminationOrdering(ignore.data())); } } for(int t = 0; t < 100; ++t) { G g = randomGraph(); if(g.size() >= 4) { vector<int> perm(g.size()); for(int i = 0; i < g.size(); ++i) { perm[i] = i; } shuffle(perm.begin(), perm.end(), rng); int k = UnifInt<int>(4, g.size())(rng); for(int i = 0; i < k; ++i) { int j = (i + 1) % k; if(rng() & 1) { g.addD(perm[i], perm[j]); } else { g.addD(perm[j], perm[i]); } } for(int i = 0; i < k; ++i) { for(int j = i + 2; j < k; ++j) { if((j + 1) % k != i) { g.delU(perm[i], perm[j]); } } } checkFalse(g.isChordal()); } } for(int t = 0; t < 100; ++t) { G g; do { g = randomGraph(); } while(!g.isChordal()); B un; vector<B> cliques; g.iterateMaximalCliquesInChordal([&](B clique) { checkTrue(g.isClique(clique)); checkEqual(clique.isEmpty(), g.size() == 0); setDifference(g.vertexSet(), clique).iterate([&](int v) { checkFalse(g.isClique(clique.with(v))); }); un = setUnion(un, clique); cliques.push_back(clique); }); checkEqual(un, g.vertexSet()); sort(cliques.begin(), cliques.end()); for(int i = 1; i < (int)cliques.size(); ++i) { checkNotEqual(cliques[i - 1], cliques[i]); } if(g.size() <= 8) { vector<B> cmp; for(int c = 1; c < (1 << g.size()); ++c) { B cand = B::fromWord(c); if(g.isClique(cand)) { bool ok = true; setDifference(g.vertexSet(), cand).iterateWhile([&](int v) { if(g.isClique(cand.with(v))) { ok = false; return false; } else { return true; } }); if(ok) { cmp.push_back(cand); } } } sort(cmp.begin(), cmp.end()); checkEqual(cliques, cmp); } } for(int t = 0; t < 100; ++t) { int n = UnifInt<int>(0, min(N, 30))(rng); int e = 0; if(n > 0) { e = UnifInt<int>(n - 1, n * (n - 1) / 2)(rng); } G g = G::randomConnectedChordal(n, e); checkEqual(g.size(), n); int edgeCount = 0; for(int v = 0; v < n; ++v) { edgeCount += g.edgesIn(v).count(); } checkEqual(edgeCount, 2 * e); checkTrue(g.isUndirected()); checkTrue(g.isChordal()); if(n > 0) { checkEqual(g.component(0), g.vertexSet()); } } for(int t = 0; t < 100; ++t) { int n = UnifInt<int>(0, min(N, 30))(rng); int e = 0; if(n > 0) { e = UnifInt<int>(n - 1, n * (n - 1) / 2)(rng); } G g = G::randomConnectedChordal(n, e); auto decomp = g.findTreeDecompositionInChordal(); int size = decomp.structure.size(); checkTrue(decomp.structure.isUndirected()); for(int i = 0; i < size; ++i) { checkTrue(isSubset(decomp.cliques[i], B::range(n))); } G h(n); for(int i = 0; i < size; ++i) { decomp.cliques[i].iterate([&](int a) { decomp.cliques[i].iterate([&](int b) { if(a != b) { h.addD(a, b); } }); }); } checkEqual(g, h); for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { if(i != j) { checkFalse(isSubset(decomp.cliques[i], decomp.cliques[j])); } } } int edgeCount = 0; for(int i = 0; i < size; ++i) { edgeCount += decomp.structure.edgesOut(i).count(); } checkEqual(edgeCount, n == 0 ? 0 : 2 * (size - 1)); if(n != 0) { checkEqual(decomp.structure.component(0), B::range(size)); } for(int v = 0; v < n; ++v) { B c; for(int i = 0; i < size; ++i) { if(decomp.cliques[i].has(v)) { c.add(i); } } checkTrue(c.isNonEmpty()); checkEqual(decomp.structure.component(c, c.min()), c); } } } static void testConversions() { for(int t = 0; t < 100; ++t) { G graph = randomGraph(); GraphData graphData(graph); graphData.accessGraph<N>([&](auto graph2) { checkEqual(graph.size(), graph2.size()); for(int i = 0; i < graph.size(); ++i) { for(int j = 0; j < graph.size(); ++j) { checkEqual(graph(i, j), graph2(i, j)); } } }); } } static void testAll() { testConstructors(); testAccessors(); testComparisons(); testQueries(); testOperations(); testChordal(); testConversions(); } }; } int main() { test_selectGraphParam(); TestGraph<1>::testAll(); TestGraph<2>::testAll(); TestGraph<3>::testAll(); TestGraph<5>::testAll(); TestGraph<8>::testAll(); TestGraph<23>::testAll(); TestGraph<121>::testAll(); test_readGraph(); return 0; }
/** * @file config.hpp * * @brief This header contains important configuration information for setting * up the compilation environment. * * This header is included in almost all other libraries and is necessary for * detecting compiler/platform-specific features, such as available libraries * and intrinsic methods. * * @author Matthew Rodusek (matthew.rodusek@gmail.com) * @date April 01, 2015 */ /* * Change Log: * * September 03, 2015 * - Added compiler type trait intrinsics */ #ifndef VALKNUT_CORE_CONFIG_HPP_ #define VALKNUT_CORE_CONFIG_HPP_ #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // Prevent normal errors from being warned #if defined(__GNUC__) && (__GNUC__ >= 4) # pragma GCC system_header #endif //! //! @def VALKNUT_DEBUG //! @brief Debug build //! //! //! @def VALKNUT_RELEASE //! @brief Release Build //! //! //! @def VALKNUT_PRODUCTION //! @brief Production Build //! #if !defined(VALKNUT_DEBUG) && !defined(VALKNUT_PRODUCTION) && !defined(NDEBUG) # define VALKNUT_DEBUG 1 #else # define VALKNUT_RELEASE 1 #endif //! //! @def VALKNUT_NOOP() //! @brief Macro function indicating no operation will occur //! #ifndef VALKNUT_NOOP # define VALKNUT_NOOP() ((void)0) #endif #include "../../../include/valknut/core/internal/macros.hpp" #include "../../../include/valknut/core/internal/platform.hpp" #include "../../../include/valknut/core/internal/compiler.hpp" #include "../../../include/valknut/core/internal/compiler_traits.hpp" #include "../../../include/valknut/core/internal/library_export.hpp" #include "../../../include/valknut/core/internal/breakpoint.hpp" #include "../../../include/valknut/core/internal/version.hpp" //! //! @def VALKNUT_DEFINE_ENUM_BITWISE_OPERATORS( Type ) //! //! @brief Defines all bitwise operators globally so that enums of type @a Type //! can be used as flags without violating restrictions of enums //! #define VALKNUT_DEFINE_ENUM_BITWISE_OPERATORS( Type ) \ inline Type operator| ( Type lhs, Type rhs ) { return Type( int( lhs ) | int( rhs ) ); } \ inline Type operator& ( Type lhs, Type rhs ) { return Type( int( lhs ) & int( rhs ) ); } \ inline Type operator^ ( Type lhs, Type rhs ) { return Type( int( lhs ) ^ int( rhs ) ); } \ inline Type operator<< ( Type lhs, int rhs ) { return Type( int( lhs ) << rhs ); } \ inline Type operator>> ( Type lhs, int rhs ) { return Type( int( lhs ) >> rhs ); } \ inline Type& operator|= ( Type& lhs, Type rhs ) { return lhs = lhs | rhs; } \ inline Type& operator&= ( Type& lhs, Type rhs ) { return lhs = lhs & rhs; } \ inline Type& operator^= ( Type& lhs, Type rhs ) { return lhs = lhs ^ rhs; } \ inline Type& operator<<=( Type& lhs, int rhs ) { return lhs = lhs << rhs; } \ inline Type& operator>>=( Type& lhs, int rhs ) { return lhs = lhs >> rhs; } \ inline Type operator~ ( Type lhs ) { return Type( ~int( lhs ) ); } //! //! @def VALKNUT_DEFINE_ENUM_ARITHMETIC_OPERATORS( Type ) //! //! @brief Defines all bitwise operators globally so that enums of type @a Type //! can be used as flags without violating restrictions of enums //! #define VALKNUT_DEFINE_ENUM_ARITHMETIC_OPERATORS( Type ) \ inline Type operator+ ( Type lhs, Type rhs ) { return Type( int( lhs ) + int( rhs ) ); } \ inline Type operator- ( Type lhs, Type rhs ) { return Type( int( lhs ) - int( rhs ) ); } \ inline Type operator* ( Type lhs, Type rhs ) { return Type( int( lhs ) * int( rhs ) ); } \ inline Type operator/ ( Type lhs, Type rhs ) { return Type( int( lhs ) / int( rhs ) ); } \ inline Type operator% ( Type lhs, Type rhs ) { return Type( int( lhs ) % int( rhs ) ); } \ inline Type& operator+=( Type& lhs, Type rhs ) { return lhs = lhs + rhs; } \ inline Type& operator-=( Type& lhs, Type rhs ) { return lhs = lhs - rhs; } \ inline Type& operator*=( Type& lhs, Type rhs ) { return lhs = lhs * rhs; } \ inline Type& operator/=( Type& lhs, Type rhs ) { return lhs = lhs / rhs; } \ inline Type& operator%=( Type& lhs, Type rhs ) { return lhs = lhs % rhs; } \ inline Type operator+ ( Type lhs ) { return lhs; } \ inline Type operator- ( Type lhs ) { return Type(- int(lhs) ); } //! //! @def VALKNUT_DEFINE_ENUM_INCREMENT_OPERATORS( Type ) //! //! @brief Defines all bitwise operators globally so that enums of type @a Type //! can easily be incremented and decremented while still being enums //! #define VALKNUT_DEFINE_ENUM_INCREMENT_OPERATORS( Type ) \ inline Type &operator++( Type &a ) { return a = Type( int( a ) + 1 ); } \ inline Type &operator--( Type &a ) { return a = Type( int( a ) - 1 ); } \ inline Type operator++( Type &a, int ) { Type t = a; ++a; return t; } \ inline Type operator--( Type &a, int ) { Type t = a; --a; return t; } /// /// @namespace valknut /// /// @brief The main namespace for the Real library /// /// This is the main library used through the entire framework. All API calls, /// types, structures, and templates will exist in here somewhere. /// namespace valknut{ /// /// @namespace valknut::detail /// /// @brief Private details namespace used for creating compound utilities /// /// This is primarily used for things like nested recursive templates, /// or method implementations that require multiple implementations later /// simplified elsewhere. /// /// Things in the detail namespace should never be called directly, as they /// are methods to be called by the main real api; and thus should be considered /// private /// namespace detail{} //--------------------------------------------------------------------------- /// /// @namespace valknut::internal /// /// @brief Private internal namespace use for abstracting hardware/platform /// differences to the main API /// /// This namespace differs from details in that it is only used to hide /// platform-specific implementations from the user, that will later be called /// by one of the main API instructions. /// /// Examples of objects that exist in this namespace are Threads (win/posix/c++11), /// sockets (winsock, posix sockets), file systems, etc. /// /// Like the details namespace, functions in ::internal should never be called /// directly, but instead the appropriate API functions in real will call them /// namespace internal{} //--------------------------------------------------------------------------- /// /// @namespace valknut::sse /// /// @brief Public namespace used for SSE-centric mathematic objects. /// /// This namespace, only found in the math module, contains mathematical /// models and objects designed for SSE instructions specifically. /// namespace sse{} //--------------------------------------------------------------------------- /// /// @namespace valknut::gl /// /// @brief Public namespace for abstracting the OpenGL workflow into the /// engine. /// /// All methods in this namespace only work with platforms supporting /// OpenGL (Which should, realistically, be all platforms compiled on) /// namespace gl{} //--------------------------------------------------------------------------- /// /// @namespace valknut::dx /// /// @brief Future namespace reserved for DirectX graphics, similar /// to valknut::gl. /// namespace dx{} } #endif /* VALKNUT_CORE_CONFIG_HPP_ */
#pragma once #include <memory> #include <vector> #include <bitset> #include <map> #include <initializer_list> #include <set> //#include <experimental/generator> #include <tuple> #include <type_traits> #include <array> #include <functional> #include <utility> #include <cstddef> #include <stack> #include <algorithm> //namespace std { template <typename T> using generator = std::experimental::generator<T>; } #define NOMINMAX #include <Windows.h> #include <TaskSystem/TaskSystem.h> class Scene; // TYPE TRAITS template <typename T> using store_of = typename T::TSTORE; template <typename T> using element_of = typename T::TELEMENT; struct Entity { uint64_t id; }; using EntityRef = uint64_t; using ComponentRef = uint64_t; using ComponentMap = std::bitset<64>; template <typename T, typename R = void> using enable_if_component = std::enable_if_t<T::ID >= 0, R>; template <typename T, typename R = void> using enable_if_resource = std::enable_if_t<T::RID >= 0, R>; #include "./Components/ComponentList.h" // STORES #include "./Stores/BaseStore.h" #include "./Stores/DenseStore.h" #include "./Stores/SingletonStore.h" // STORES JOINS struct join { template <typename TEntities, typename TF, typename... TArgs> static void run(const TEntities& entities, const TF& f, TArgs&... stores) { call(entities, f, stores.iter()...); } private: template <typename T> static void inc(T& t, ptrdiff_t diff) { t += diff; } template <typename TEntities, typename TF, typename... TArgs> static void call(const TEntities& entities, const TF& f, TArgs... iters) { EntityRef last = 0; for (auto&& ref : entities) { auto diff = ptrdiff_t(ref - last); last = ref; (inc(iters, diff), ...); f((*iters)...); } } }; // ENTITY MANAGER #include "EntityManager.h" // Components #include "./Components/Components.h" using copy_function = void(*)(void*,void*); struct CopyRecord { void* src; void* dst; copy_function f; }; #include "ComponentManager.h" #include "./Systems/BaseSystem.h" #include "./Systems/System.h" #include "./Systems/SystemManager.h" #include "./Entities/EntityBuilder.h" template <typename T> struct AnimRecord { bool enabled; T* data; void* dst; copy_function f; Task<100>* when_finished; }; struct InterpolationLerp { static const uint32_t ID = 0; float start; float end; float duration; float t; float value; }; template <typename TContainer, typename TKey, typename F> void use_remove(TContainer& container, const TKey& key, const F& f) { auto it = container.find(key); if (it == container.end()) return; // use f(it->second); // remove container.erase(it); } template <typename TContainer, typename TKey, typename TValue> TValue move_remove(TContainer& container, const TKey& key) { auto it = container.find(key); if (it == container.end()) return; // move TValue v = std::move(it->second); //remove container.erase(it); return v; } class AnimManager { public: void schedule(uint32_t id, uint32_t type, void* data, bool enabled, Task<100>* t, void* dst, copy_function f) { if (type == InterpolationLerp::ID) { auto d = new AnimRecord<InterpolationLerp>{ enabled, (InterpolationLerp*)data, dst, f, t }; waiting.insert({ id, {type, (void*)d} }); } } void start(uint32_t id) { use_remove(waiting, id, [&](auto&& record) { if (record.type == InterpolationLerp::ID) { lerps.push_back(*(AnimRecord<InterpolationLerp>*)(record.data)); } delete record.data; }); } void update(float dt) { run_lerps(dt); } static InterpolationLerp lerp(float duration, float start, float end) { return { start, end, duration, 0, start }; } private: template<typename T> static void copy_impl(void* src, void* dst) { *(T*)dst = *(T*)src; } template<class T, typename U> std::ptrdiff_t member_offset(U T::* member) { return reinterpret_cast<std::ptrdiff_t>( &(reinterpret_cast<T const volatile*>(NULL)->*member) ); } void run_lerps(float dt) { for (auto&& r : lerps) { auto& l = *r.data; if (!r.enabled) continue; if (!r.when_finished->is_enabled()) { if (r.when_finished->duration <= 0) { l.t = l.duration; l.value = l.end; r.f(&l.value, r.dst); r.enabled = false; } } else { l.t = l.duration - (r.when_finished->duration / 1000.0f); l.value = l.start + (l.t * ((l.end - l.start) / l.duration)); r.f(&l.value, r.dst); } } auto it = std::remove_if(lerps.begin(), lerps.end(), [](auto&& l) { return !l.enabled; }); lerps.erase(it, lerps.end()); } std::vector<AnimRecord<InterpolationLerp>> lerps; struct BuildRecord { uint32_t type; void* data; }; std::map<uint32_t, BuildRecord> waiting; }; class AnimBuilder { public: AnimBuilder() { stack.push(&root); } template <typename T> AnimBuilder& then(const T& data, bool push = true) { auto* current = stack.top(); auto* d = new T{}; *d = data; current->children.push_back({ T::ID, data.duration, d, {}}); if (push) stack.push(&current->children.back()); return *this; } AnimBuilder& pop() { stack.pop(); return *this; } Task<100>& start(TaskSystem<100, 100>& tsys, AnimManager& anims, void* dst, copy_function f, Task<100>* after = nullptr) { if (after == nullptr) { auto t = tsys.make_task(true); after = t.task; } return start_impl(tsys, anims, root, *after, dst, f); } private: struct AnimNode { uint32_t type; float duration; void* data; std::vector<AnimNode> children; }; Task<100>& start_impl(TaskSystem<100, 100>& tsys, AnimManager& anims, AnimNode& cur, Task<100>& tcur, void* dst, copy_function f) { auto tall = tsys.make_task(); tsys.then(tcur, tall); for (auto& child : cur.children) { auto tchild = tsys.make_duration((uint64_t)(child.duration * 1000.0f)); tsys.then(tcur, tchild); tsys.then(tchild, tall); anims.schedule(tchild.task->id, child.type, child.data, true, tchild.task, dst, f); auto& tgrand_child = start_impl(tsys, anims, child, tchild, dst, f); tsys.then(tgrand_child, tall); } return tall; } AnimNode root; std::stack<AnimNode*> stack; }; // OOB Resources struct DeltaTimeComponent { RESOURCE(0, DeltaTimeComponent); float dt; }; #include "Scene.h"
#include <iostream> #include "mazeObj.h" #include <GLUT/glut.h> #include <unistd.h> #include <map> #include "parser.h" #include <vector> #include <stack> #include <stdlib.h> #include "rsdgMission.h" #include "tsp.h" #include <unistd.h> #include <string> int argC; char** argV; /* maze configuration */ int maze_row; int maze_col; maze* curMazeptr; maze curMaze; vector<pair<int, int> > obstacles; vector<pair<int, int> > routes; map<int,int> colormap; pair<int, int> orig; pair<int, int> dest; bool solved; bool onetime; float pt_len; int curCell; string cur_fileName; int algo; void generateNewmap(); void searchPath(); void increCur(); void showAll(); /* rsdg configuration*/ bool verbose; bool local; bool coke; bool pepsi; int cokePref; int pepsiPref; int totalbudget; class robotRSDG: public rsdgMission{ public: virtual void updateBudget(){ setBudget(totalbudget-curCell); } }; string inputFile; string outputFile; map<string,string> path; stack<string> finished; // a stack where the top() is the latest finished target bool done;//when robot returns to the starting point, the 'fakerobot' will return string currentJob; //current target string preJob; rsdgPara* paraCoke; rsdgPara* paraPepsi; const string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); return buf; } pair<int,int> getPos(string name){ if(name=="s") return make_pair(55,1); if(name=="b1") return make_pair(curMaze.cokeCans[0].first,curMaze.cokeCans[0].second); if(name=="b2") return make_pair(curMaze.cokeCans[1].first,curMaze.cokeCans[1].second); if(name=="b3") return make_pair(curMaze.pepsiCans[0].first,curMaze.pepsiCans[0].second); if(name=="b4") return make_pair(curMaze.pepsiCans[1].first,curMaze.pepsiCans[1].second); } void setAlgo(int op){ if(op=='f') algo = FORWARD; if(op=='a') algo = ADAPTIVE; if(op=='b') algo = BACKWARD; } /* process menu option 'op' */ void menu(int op) { switch(op) { case 's': searchPath(); break; case 'n': generateNewmap(); break; case 'f': case 'a': case 'b': setAlgo(op); break; case 'Q': case 'q': exit(0); } } /* executed when a regular key is pressed */ void keyboardDown(unsigned char key, int x, int y) { switch(key) { case 'q': exit(0); break; case 's': searchPath(); break; case 'n': generateNewmap(); break; case 'c': increCur(); break; case 'r': showAll(); break; } } /* executed when a regular key is released */ void keyboardUp(unsigned char key, int x, int y) { } /* executed when a special key is pressed */ void keyboardSpecialDown(int k, int x, int y) { } /* executed when a special key is released */ void keyboardSpecialUp(int k, int x, int y) { } /* executed when button 'button' is put into state 'state' at screen position ('x', 'y') */ void mouseClick(int button, int state, int x, int y) { } /* executed when the mouse moves to position ('x', 'y') */ void mouseMotion(int x, int y) { } /*function to paint a point on canvas */ void paintPoint(int x, int y, int plane, int color){ switch(color){ case 0://obstacle glColor3f(0.0f,0.0f,0.0f); break; case 1://empty glColor3f(1.0f,1.0f,1.0f); break; case 2://coke glColor3f(1.0f, 0.0f, 0.0f); break; case 3://pepsi glColor3f(0.0f, 0.0f, 1.0f); break; case 4://fog glColor3f(0.752941f,0.752941f,0.752941f); break; case 5://path glColor3f(0.0f,1.0f,0.0f); break; case 6://start glColor3f(1.0f,0.0f,1.0f); break; } if(plane == 0)//paint left glRectf(-1 + pt_len*x, -1+pt_len*y*2, -1+pt_len*(x+1), -1+pt_len*(y+1)*2); if(plane == 1)//paint right glRectf(-1 + pt_len*x +1, -1+pt_len*y*2, -1+pt_len*(x+1)+1, -1+pt_len*(y+1)*2); return; } void paintNeighbors(int x, int y){ int l,r,u,d; l=curMaze.get(x,y-1); r=curMaze.get(x,y+1); u=curMaze.get(x-1,y); d=curMaze.get(x+1,y); if(l!=-1)paintPoint(x,y-1,1,colormap[l]); if(r!=-1)paintPoint(x,y+1,1,colormap[r]); if(u!=-1)paintPoint(x-1,y,1,colormap[u]); if(d!=-1)paintPoint(x+1,y,1,colormap[d]); } /* render the scene */ void draw() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0f,0.0f,1.0f); obstacles = curMaze.getObstacles(); orig = curMaze.getMission().first; dest = curMaze.getMission().second; glClear(GL_COLOR_BUFFER_BIT); //set the empty spaces for(int i = 0; i<maze_row; i++){ for(int j = 0; j<maze_col; j++){ paintPoint(i,j,0,1); } } //set the player-view spaces for(int i = 0; i<maze_row; i++){ for(int j = 0; j<maze_col; j++){ paintPoint(i,j,1,4); } } //set the obstacles for(int i = 0; i<obstacles.size(); i++){ int x = obstacles[i].first; int y = obstacles[i].second; paintPoint(x,y,0,0); // paintPoint(x,y,1); } //set the cans and starting points for(int i = 0; i<curMaze.cokeCans.size(); i++){ paintPoint(curMaze.cokeCans[i].first,curMaze.cokeCans[i].second, 0,2); paintPoint(curMaze.cokeCans[i].first,curMaze.cokeCans[i].second, 1,2); } for(int i = 0; i<curMaze.pepsiCans.size(); i++){ paintPoint(curMaze.pepsiCans[i].first,curMaze.pepsiCans[i].second, 0,3); paintPoint(curMaze.pepsiCans[i].first,curMaze.pepsiCans[i].second, 1,3); } //paint the path if(solved){ if(onetime){//showall for(int i = 0; i<curCell; i++){ //paint the neighbours paintNeighbors(routes[i].first,routes[i].second); paintPoint(routes[i].first, routes[i].second,0,5); paintPoint(routes[i].first, routes[i].second,1,5); } }else{ for(int i = 0; i<routes.size(); i++){ paintPoint(routes[i].first, routes[i].second,0,5); } } paintPoint(routes[curCell].first, routes[curCell].second,0,5); paintPoint(routes[curCell].first, routes[curCell].second,1,5); } paintPoint(55,1,0,6); paintPoint(55,1,1,6); glFlush(); } /* executed when program is idle */ void idle() { } /*initialize the canvas for maze*/ void init_canvas(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutInitWindowSize(800, 400); glutInitWindowPosition(100, 50); glutCreateWindow("1aze Painting Canvas"); /*register the key operations*/ glutKeyboardFunc(keyboardDown); /*register the menu*/ int subMenu = glutCreateMenu(menu); glutAddMenuEntry("Quit", 'q'); glutAddMenuEntry("Generate new Maze", 'n'); glutAddMenuEntry("search",'s'); glutAddMenuEntry("test",'t'); int algoMenu = glutCreateMenu(menu); glutAddMenuEntry("Forward",'f'); glutAddMenuEntry("Backward", 'b'); glutAddMenuEntry("Adaptive",'a'); glutCreateMenu(menu); glutAddSubMenu("SubMenu", subMenu); glutAddSubMenu("Algo",algoMenu); glutAddMenuEntry("Quit", 'q'); glutAttachMenu(GLUT_RIGHT_BUTTON); glutDisplayFunc(&draw); glutMainLoop(); } void generateNewmap(){ curCell=0; std::cout<<"generating new map"<<std::endl; rsdg->reset(); rsdg->setBudget(totalbudget); solved = false; delete(curMazeptr); curMazeptr = new maze(maze_row,maze_col); curMaze = *curMazeptr; curMaze.setObstacle(); updateXML(rsdg); curMaze.setOrig(55,1); rsdg->reconfig(); usleep(100000); int destx = getPos(path["s"]).first; int desty = getPos(path["s"]).second; curMaze.setDest(destx,desty); curMaze.printMaze(cur_fileName); preJob = "s"; currentJob=path["s"]; cout<<"COKE:"<<curMaze.cokeCans[0].first<<","<<curMaze.cokeCans[0].second<<" "<<curMaze.cokeCans[1].first<<","<<curMaze.cokeCans[1].second<<endl; cout<<"PEPSI:"<<curMaze.pepsiCans[0].first<<","<<curMaze.pepsiCans[0].second<<" "<<curMaze.pepsiCans[1].first<<","<<curMaze.pepsiCans[1].second<<endl; glutPostRedisplay(); // glutMainLoop(); } void showAll(){ onetime = false; curCell = routes.size()-1; std::cout<<"curCell:"<<curCell<<std::endl; glutPostRedisplay(); } void increCur(){ if(currentJob=="s"){ done = true; } onetime = true; curCell++; glutPostRedisplay(); if(routes[curCell].first==getPos(currentJob).first && routes[curCell].second==getPos(currentJob).second){ if(done){ cout<<"****FINISHED****"<<endl; return; } cout<<"reached"<<endl; rsdg->updateWeight(currentJob,preJob,0);//path cost = 0 rsdg->updateWeight(currentJob,0); rsdg->addConstraint(currentJob,true); rsdg->addConstraint(currentJob,preJob,true); rsdg->reconfig(); usleep(100000); curMaze.setOrig(getPos(currentJob).first,getPos(currentJob).second); preJob = currentJob; currentJob=path[currentJob]; curMaze.setDest(getPos(currentJob).first,getPos(currentJob).second); curMaze.printMaze(cur_fileName); searchPath(); } } void searchPath(){ std::cout<<"searching for path"<<std::endl; cout<<"curTarget:"<<currentJob<<endl; curMaze.searchRoute("mazeFile.txt",algo); vector<pair<int,int>> newroutes = curMaze.getRoute(); routes.reserve(routes.size()+newroutes.size()); routes.insert(routes.end(),newroutes.begin(),newroutes.end()); if(curMaze.solved()){ std::cout<<"routes found"<<endl; solved = true; }else{ solved = false; std::cout<<"no routes"<<endl; } //curCell=0; } void updateXML(rsdgMission* rsdg){ map<string,pair<int,int>> location; location["s"]=make_pair(55,1); location["b1"]=make_pair(curMaze.cokeCans[0].first,curMaze.cokeCans[0].second); location["b2"]=make_pair(curMaze.cokeCans[1].first,curMaze.cokeCans[1].second); location["b3"]=make_pair(curMaze.pepsiCans[0].first,curMaze.pepsiCans[0].second); location["b4"]=make_pair(curMaze.pepsiCans[1].first,curMaze.pepsiCans[1].second); auto it = location.begin(); while(it!=location.end()){ string source = it->first; pair<int,int> sLoc = it->second; auto cur=it; cur++; while(cur!=location.end()){ string dest = cur->first; pair<int,int> dLoc = cur->second; double dist = abs(dLoc.first-sLoc.first)+abs(dLoc.second-sLoc.second);//manhattan dist rsdg->updateWeight(source,dest,dist); rsdg->updateWeight(dest,source,dist);//update 2 edges cout<<"updated "<<source<<":"<<sLoc.first<<" "<<sLoc.second<<" "<<dest<<":"<<dLoc.first<<" "<<dLoc.second<<" "<<dist<<endl; rsdg->printProb(outputFile); cur++; } it++; } return; } /* initialize GLUT settings, register callbacks, enter main loop */ int main(int argc, char** argv) { argC = argc; argV = argv; local = false; if(argc<2){ cokePref=1; pepsiPref=1; }else{ for(int i = 1; i<argc; i++){ string arg = argv[i]; if(arg=="-coke"){ cokePref=atoi(argv[++i]); } if(arg=="-pepsi"){ pepsiPref=atoi(argv[++i]); } if(arg=="-xml"){ inputFile = argv[++i]; } if(arg=="-b"){ totalbudget = atoi(argv[++i]); } if(arg=="-v"){ verbose = true; } if(arg=="-l"){ local = true; } } } /* rsdg init */ done = false; outputFile = "./problem.lp"; //push starting point to the finished stack finished.push("s"); currentJob="s"; //setup RSDG rsdg = setupRSDG();//distance here is not correct rsdg->setBudget(totalbudget); /* maze init */ colormap[0] = 1; colormap[1] = 0; colormap[2] = 2; colormap[3] = 3; colormap[4] = 4; colormap[5] = 5; colormap[6] = 6; solved = false; curCell = -1; // initialize the canvas for maze maze_row = 101; maze_col = 101; pt_len = 1.0 / maze_row; cur_fileName = "mazeFile.txt"; curMazeptr = new maze(maze_row,maze_col); curMaze = *curMazeptr; curMaze.setObstacle(); curMaze.printMaze(cur_fileName); init_canvas(argc,argv); rsdg->stopSolver(); rsdg->cancel(); return 0; } /* code for RSDG */ void cmdGenerator(){ string cur = finished.top(); string nextStep = path[cur]; cout<<"*******CMD:GO AND FETCH "<<nextStep<<"***********"<<endl; } // the actual job that the robot going and fetching the ball(can) void* robotJob(void* arg){ string pre = currentJob; currentJob = path[currentJob]; if(currentJob=="s"){//next step is to go home done = true; sleep(5);//spending 5 seconds to go home return NULL; } cout<<"*******GRABING...********"<<endl; while(true){ if(routes.size()>1){ if(routes[curCell].first==getPos(currentJob).first && routes[curCell].second==getPos(currentJob).second)break; } usleep(100000); } finished.push(currentJob); if(verbose)cout<<"pre:"<<pre<<" cur:"<<currentJob<<endl; // after finished the current job, robot sets the weight of this node and the edge to it to be 0 // to ensure the next solution will also choose this rsdg->updateWeight(currentJob,pre,0);//path cost = 0 rsdg->updateWeight(currentJob,0);//current destination = 0 return NULL; } // a master robot thread that acts as controller void* robot (void* arg){ while(!done){ cmdGenerator();//generate the command //start the thread to go and fetch the ball pthread_t goNfetch; pthread_create(&goNfetch, NULL,&robotJob, NULL); pthread_join(goNfetch,NULL); rsdg->reconfig();//everytime when finished a task, it does a reconfiguration sleep(1); } cout<<"*******MISSION ACCOMPLISHED******"<<endl; return NULL; } //init RSDG //for a result like a$b, it means 'a' depends on 'b', in the robot case, go from 'b' to 'a' rsdgMission* setupRSDG(){ cout<<"setting up RSDG"<<endl; paraCoke = new rsdgPara(); paraPepsi = new rsdgPara(); rsdgMission* res = new robotRSDG(); res->regService("ball1","b1",&ball1Fun,true); res->regService("ball2","b2",&ball2Fun,true); res->regService("ball3","b3",&ball3Fun,true); res->regService("ball4","b4",&ball4Fun,true); res->regService("start","s",&start,true); res->generateProb(inputFile); res->setBudget(totalbudget); res->addConstraint("s",true);//tell the RSDG that the starting point has to be chosen res->updateMV("ball1",cokePref,false);//ball1 is a pepsi res->updateMV("ball2",cokePref,false);//ball2 is a coke res->updateMV("ball3",pepsiPref,false);//ball3 is a pepsi res->updateMV("ball4",pepsiPref,false);//ball4 is a coke res->updateMV("start",0,false); res->setSolver(local); res->printProb(outputFile);//for validating res->setupSolverFreq(0);//check solver manually return res; } void* start(void* arg){ if(currentJob=="s")cout<<"*******STARTING...*******"<<endl; cout<<"curTarget:"<<currentJob<<endl; vector<string> dep = rsdg->getDep("s"); if(dep.size()==0){ if(verbose)cout<<"no dependence"<<endl; return NULL; } string from = dep[0]; if("s"==path[from])return NULL; path[from]="s"; if(verbose)cout<<"from "<<from<<" to s"<<endl; return NULL; } void* ball1Fun (void* arg){ vector<string> dep = rsdg->getDep("b1"); if(dep.size()==0){ if(verbose)cout<<"no dependence"<<endl; return NULL; } string from = dep[0]; if("b1"==path[from])return NULL; path[from]="b1"; if(verbose)cout<<"from "<<from<<"to b1"<<endl; return NULL; } void* ball2Fun (void* arg){ vector<string> dep = rsdg->getDep("b2"); if(dep.size()==0){ if(verbose)cout<<"no dependence"<<endl; return NULL; } string from = dep[0]; if("b2"==path[from])return NULL; path[from]="b2"; if(verbose)cout<<"from "<<from<<"to b2"<<endl; return NULL; } void* ball3Fun (void* arg){ vector<string> dep = rsdg->getDep("b3"); if(dep.size()==0){ if(verbose)cout<<"no dependence"<<endl; return NULL; } string from = dep[0]; if("b3"==path[from])return NULL; path[from]="b3"; if(verbose)cout<<"from "<<from<<"to b3"<<endl; return NULL; } void* ball4Fun (void* arg){ vector<string> dep = rsdg->getDep("b4"); if(dep.size()==0){ if(verbose)cout<<"no dependence"<<endl; return NULL; } string from = dep[0]; if("b4"==path[from])return NULL; path[from]="b4"; if(verbose)cout<<"from "<<from<<"to b4"<<endl; return NULL; }
#pragma once #include "iPlayer.h" class cPlayer : public iPlayer { public: cPlayer(iUser* user); virtual ~cPlayer(); virtual bool IsReadyToPlay(); virtual bool IsBankrupty(); virtual bool Debit(unsigned int money); virtual bool Withdraw(unsigned int money); private: unsigned int m_money; bool m_isReady; iUser* m_user; };
#include<iostream> using namespace std; class area{ int len; int br; public: void setdim(){ cout<<"Enter the length of rectangle : "; cin>>len; cout<<"Enter the Breadth of rectangle : "; cin>>br; } int getArea(){ return (len*br); } }; int main(){ area a; a.setdim(); cout<<"Area of rectangle : "<<a.getArea()<<"\n"; return 0; }
#include "newhoug.h"
#ifndef _UpdateTableUserCountProc_H #define _UpdateTableUserCountProc_H #include "CDLSocketHandler.h" #include "IProcess.h" class UpdateTableUserCountProc :public IProcess { public: UpdateTableUserCountProc(); virtual ~UpdateTableUserCountProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt ) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt ) ; }; #endif
//no attachments on either of the M16A2s. class M16A2_DZ : M16A2 { magazines[] = { 30Rnd_556x45_Stanag, 30Rnd_556x45_G36, 100Rnd_556x45_BetaCMag, 20Rnd_556x45_Stanag, 60Rnd_556x45_Stanag_Taped }; class Attachments { Attachment_M203 = "M16A2_GL_DZ"; }; }; class M16A2_GL_DZ : M16A2GL { magazines[] = { 30Rnd_556x45_Stanag, 30Rnd_556x45_G36, 100Rnd_556x45_BetaCMag, 20Rnd_556x45_Stanag, 60Rnd_556x45_Stanag_Taped }; class ItemActions { class RemoveGL { text = $STR_DZ_ATT_M203_RMVE; script = "; ['Attachment_M203',_id,'M16A2_DZ'] call player_removeAttachment"; }; }; }; //ice apo resistance mod m16 class M16A2_Rusty_DZ : M16A2 { class FlashLight { color[] = {0.9, 0.9, 0.7, 0.9}; ambient[] = {0.1, 0.1, 0.1, 1.0}; position = "flash dir"; direction = "flash"; angle = 30; scale[] = {1, 1, 0.5}; brightness = 0.1; }; scope = 2; picture = "\ice_apo_weapons\Data\m16_ca.paa"; model = "\ice_apo_weapons\M16_proxy"; displayName = $STR_DZE_WPN_M16RUSTY_NAME; descriptionShort = $STR_DZE_WPN_M16RUSTY_DESC; selectionFireAnim = "zasleh"; magazines[] = { 30Rnd_556x45_Stanag, 30Rnd_556x45_G36, 100Rnd_556x45_BetaCMag, 20Rnd_556x45_Stanag, 60Rnd_556x45_Stanag_Taped }; class Library { libTextDesc = "This M16 rifle is in a very bad shape."; }; };
#include "stack.hpp" void Stack::push(int value) { pushBack(value); } void Stack::pop() { popBack(); } void Stack::printStack() { printVector(); }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int len[1111111]; int s[1111111]; int mi[7], ma[7]; LL c[14]; vector<int> bysum[7][77]; vector<int> bysum2[7][77]; void Calc(LL x) { x--; if (x < 10) { cout << x << endl; return; } for (int i = 1; i < 14; ++i) { if (x >= c[i]) { x -= c[i]; continue; } if ((i & 1) == 0) { int ii = i >> 1; for (int j = mi[ii]; j <= ma[ii]; ++j) { if (x >= bysum2[ii][s[j]].size()) { x -= bysum2[ii][s[j]].size(); } else { cout << j << bysum2[ii][s[j]][x] << endl; return; } } throw 2; } else { int ii = i >> 1; for (int j = mi[ii]; j <= ma[ii]; ++j) { if (x >= bysum2[ii][s[j]].size() * 10) { x -= bysum2[ii][s[j]].size() * 10; } else { int bs = bysum2[ii][s[j]].size(); cout << j << x / bs << bysum2[ii][s[j]][x % bs] << endl; return; } } throw 3; } } throw 4; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); len[0] = 0; s[0] = 0; for (int i = 1; i < 1000000; ++i) { len[i] = len[i / 10] + 1; s[i] = s[i / 10] + i % 10; bysum[len[i]][s[i]].push_back(i); for (int j = len[i]; j < 7; ++j) bysum2[j][s[i]].push_back(i); } // int tc = 0; // for (int i = 0; i < 7; ++i) for (int j = 0; j < 77; ++j) tc += bysum[i][j].capacity() + bysum2[i][j].capacity(); // cerr << tc*4 / (1024*1024) << endl; mi[1] = 1; ma[1] = 9; for (int i = 2; i < 7; ++i) mi[i] = mi[i - 1] * 10, ma[i] = ma[i - 1] * 10 + 9; c[1] = 10; for (int i = 1; i <= 6; ++i) { for (int j = 1; j <= i * 9; ++j) { c[i + i] += LL(bysum[i][j].size()) * bysum2[i][j].size(); c[i + i + 1] += LL(bysum[i][j].size()) * bysum2[i][j].size() * 10; } } int T; cin >> T; while (T--) { LL x; cin >> x; Calc(x); } // cerr << clock() << endl; return 0; }
#include "logger.hpp" #include "graphics.hpp" #include "views/widget.hpp" #include "controller.hpp" #ifndef _WIN32 #include <unistd.h> //let mingw handle it if needed #endif #include <cmath> #include <cassert> #include <iostream> #include <vector> #include <chrono> #include <deque> #include <array> #include <cstring> #include <utility> #include <memory> #include "SDL.h" #include "SDL_ttf.h" //XXX- REMOVE ASAP #include "LRUCache.hpp" #include "Surface.hpp" #include "Texture.hpp" #include "Window.hpp" //#define TEMP_FONT_PATH "../resources/font/UbuntuMono-R.ttf" #define TEMP_FONT_PATH "../resources/font/Anonymous_Pro.ttf" #define NUMBER_OF_TILES 255 #define STRING_CACHE_SIZE 128 using namespace std; using namespace chrono; using namespace SDL; using NativeKeyboardKey = unsigned long; struct Graphics_SDL : Graphics { Graphics_SDL(); public: // Graphics interface Methods void drawString(int x, int y, const std::string& str, bool must_kern = false, Context gc = Context::WHITE); void drawChar(int x, int y, char str, Context gc = Context::WHITE); void handle_events(struct Controller*); void repaint(); void destroy(); private: // Initialization methods void version_check(); void init_window(); void init_renderer(); void init_font(); void log_stats(); private: // Internal use methods inline void throw_sdl_error(const std::string& desc); inline void throw_ttf_error(const std::string& desc); KeyboardKey map_key(NativeKeyboardKey key); void LoadText(const std::string& font_file); // Data int s; SDL::Window win; SDL::Renderer ren; Texture main_texture; Texture ttf_texture; unsigned int tiles_per_row; TTF_Font* best_font; SDL_Color font_color; Logger graphics_log; LRUCache<std::string, SDL_Texture*> string_texture_cache; }; void FreeSDLTexture(SDL_Texture** tex) { SDL_DestroyTexture(*tex); } void Graphics_SDL::throw_sdl_error(const std::string& desc) { auto err = SDL_GetError(); graphics_log.Write("%s\n%s", desc.c_str(), err); throw std::runtime_error(err); } void Graphics_SDL::throw_ttf_error(const std::string& desc) { auto err = TTF_GetError(); graphics_log.Write("%s\n%s", desc.c_str(), err); throw std::runtime_error(err); } Graphics_SDL::Graphics_SDL() : font_color({ 255, 255, 255, 0 }), graphics_log("graphics.txt") , string_texture_cache(STRING_CACHE_SIZE, FreeSDLTexture) { graphics_log.Write("Initializing graphics file for SDL"); version_check(); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) throw_sdl_error("Error initializing SDL."); if (TTF_Init()) throw_ttf_error("Error initializing TTF."); //// Initialize the window width = 80; height = 40; try { //to-do: center on screen win = SDL::CreateWindow("", 100, 100, width * FONT_WIDTH, height * FONT_HEIGHT, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); //// Initialize the renderer ren = win.CreateRenderer(-1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); } catch (std::exception const& e) { graphics_log.Write("%s", e.what()); throw; } log_stats(); init_font(); } void Graphics_SDL::destroy() { if (destroyed) return; if (!best_font) TTF_CloseFont(best_font); SDL_Quit(); destroyed = true; } void Graphics_SDL::version_check() { SDL_version compiled, linked; SDL_VERSION(&compiled); SDL_GetVersion(&linked); graphics_log.Write("SDL Version compiled against: %d.%d.%d", compiled.major, compiled.minor, compiled.patch); graphics_log.Write("SDL Version linked against: %d.%d.%d", linked.major, linked.minor, linked.patch); } void Graphics_SDL::init_font() { graphics_log.Write("Loading font:"); graphics_log.Write(TEMP_FONT_PATH); best_font = TTF_OpenFont(TEMP_FONT_PATH, FONT_HEIGHT); if (best_font == nullptr) throw_ttf_error("Failed to load font."); LoadText(TEMP_FONT_PATH); } void Graphics_SDL::log_stats() { //debug times. //following is not supported on SDL 2.0.0 // graphics_log->Write("%s. We have %i MB of RAM","Finished initializing graphics for SDL!",SDL_GetSystemRAM()); // Check drivers int num_drivers = SDL_GetNumVideoDrivers(); if (num_drivers < 0) throw_sdl_error("Unable to determine drivers."); graphics_log.Write("We have %i drivers available", num_drivers); for (int driX = 0; driX < num_drivers; ++driX) { graphics_log.Write("%i: %s", driX, SDL_GetVideoDriver(driX)); } graphics_log.Write("Current driver is: %s", SDL_GetCurrentVideoDriver()); // Check renderers SDL_RendererInfo ren_info; memset(&ren_info, 0, sizeof(ren_info)); int num_render = SDL_GetNumRenderDrivers(); if (num_render < 0) throw_sdl_error("Unable to determine renderers."); graphics_log.Write("We have %i renderers available", num_render); for(int driR = 0; driR < num_render; ++driR) { if (SDL_GetRenderDriverInfo(driR, &ren_info)) { // Nonfatal error. graphics_log.Write("%i:%s\n%s", driR, "Failed to get any info.", SDL_GetError()); } else { graphics_log.Write("%i: Name:%s\n Flags: %i\n Num of Texture Formats: %i\n Max_Wid: %i\n Max_H: %i", driR, ren_info.name, ren_info.flags, ren_info.num_texture_formats, ren_info.max_texture_width, ren_info.max_texture_height); for (unsigned int driF = 0; driF < ren_info.num_texture_formats; ++driF) { uint32_t inf = ren_info.texture_formats[driF]; graphics_log.Write("\n\tFormat:%i\n\tPixelFlag:%i\n\tPixelType:%i\n\tPixelOrder:%i\n\tPixelLayout:%i\n\tBitsPerPixel:%i\n\tBytesPerPixel:%i\n\tPixelFormatIndexed:%s\n\tPixelFormatAlpha:%s\n\tFourCC:%s", driF, SDL_PIXELFLAG(inf), SDL_PIXELTYPE(inf), SDL_PIXELORDER(inf), SDL_PIXELLAYOUT(inf), SDL_BITSPERPIXEL(inf), SDL_BYTESPERPIXEL(inf), SDL_ISPIXELFORMAT_INDEXED(inf) ? "True" : "False", SDL_ISPIXELFORMAT_ALPHA(inf) ? "True" : "False", SDL_ISPIXELFORMAT_FOURCC(inf) ? "True" : "False"); } } } SDL_GetRendererInfo(ren.get(), &ren_info); graphics_log.Write("Current renderer is: %s", ren_info.name); } void Graphics_SDL::LoadText(const std::string&) { //to-do: refactor this in a slightly different architecture. const int number_of_tiles = NUMBER_OF_TILES; // gk: make as close to square // ras: I'm very skeptical about this calculation... const int rows = 1 + (const int)sqrt((float)number_of_tiles); tiles_per_row = rows; int tile_texture_width = rows * FONT_WIDTH; int tile_texture_height = rows * FONT_HEIGHT; SDL_Rect copy_dimension; copy_dimension.w = FONT_WIDTH; copy_dimension.h = FONT_HEIGHT; Surface ttf_surface = Surface(SDL_CreateRGBSurface(0, tile_texture_width, tile_texture_height, 32, 0, 0, 0, 0)); if (!ttf_surface.get()) throw_sdl_error("Could not create character surface."); //temporary before choosing a tile\font for (int count = 0; count < number_of_tiles; ++count) { Surface surf = Surface(TTF_RenderGlyph_Shaded(best_font, (uint16_t)count, font_color, { 0, 0, 0, 0 })); if (surf.get()) { //if we draw the right character copy_dimension.x = (count % rows) * FONT_WIDTH; copy_dimension.y = (count / rows) * FONT_HEIGHT; if (SDL_BlitSurface(surf.get(), NULL, ttf_surface.get(), &copy_dimension)) throw_sdl_error("Could not blit character"); } else { // TODO: What does this even mean???? } } //send the big one over ttf_texture = ren.CreateTextureFromSurface(ttf_surface.get()); if (SDL_SaveBMP(ttf_surface.get(), "font_tilemap.bmp")) { graphics_log.Write("Could not save bitmap of font tilemap.\n%s", SDL_GetError()); } } KeyboardKey Graphics_SDL::map_key(NativeKeyboardKey key) { switch (key) { case SDLK_ESCAPE: return KEY_Escape; case SDLK_SPACE: return KEY_space; case SDLK_LEFT: return KEY_Left; case SDLK_RIGHT: return KEY_Right; case SDLK_UP: return KEY_Up; case SDLK_DOWN: return KEY_Down; case SDLK_RETURN: return KEY_Return; case SDLK_DELETE: return KEY_Delete; case SDLK_TAB: return KEY_Tab; case SDLK_h: return KEY_h; case SDLK_u: return KEY_u; case SDLK_r: return KEY_r; case SDLK_a: return KEY_a; case SDLK_q: return KEY_q; case SDLK_e: return KEY_e; case SDLK_d: return KEY_d; case SDLK_s: return KEY_s; case SDLK_w: return KEY_w; case SDLK_f: return KEY_f; case SDLK_PAGEUP: return KEY_Pageup; case SDLK_PAGEDOWN: return KEY_Pagedown; default: return KEY_Undefined; } } void Graphics_SDL::handle_events(Controller* c) { SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type){ case SDL_KEYDOWN: c->handle_keypress(map_key(event.key.keysym.sym)); break; case SDL_WINDOWEVENT: //window moved, max,min, etc if(event.window.event == SDL_WINDOWEVENT_RESIZED) { height = (0xffff & event.window.data2) / FONT_HEIGHT; width = (0xffff & event.window.data1) / FONT_WIDTH; //int old_size = (0xffff &event.window.data1); //int new_size = (0xffff &event.window.data2); } break; case SDL_QUIT: //send q to controller destroy(); return; break; default: break; // dog } } //all done with events! :) } //Note: Please do NOT request kerning for short-term strings. //Kerning implies the string to be cached. void Graphics_SDL::drawString(int x, int y, const string & str,bool must_kern, const Graphics_SDL::Context color) { if (must_kern == false) { SDL_SetTextureColorMod(ttf_texture.get(), color.red, color.green, color.blue); for (auto ch : str) drawChar(x++, y, ch, Context::DEFAULT); return; } //else SDL_Texture* retr_texture; if (string_texture_cache.get(str, &retr_texture) == false) { Surface my_font_surface = Surface(TTF_RenderText_Shaded(best_font, str.c_str(), font_color, { 0, 0, 0, 0 })); if (!my_font_surface.get()) //we tried return; Texture tex = ren.CreateTextureFromSurface(my_font_surface.get()); retr_texture = tex.get(); string_texture_cache.put(str, tex.release()); } int w = 0, h = 0; TTF_SizeText(best_font, str.c_str(), &w, &h); SDL_Rect dstRect = { x * FONT_WIDTH, y * FONT_HEIGHT, w, h }; SDL_SetTextureColorMod(retr_texture, color.red, color.green, color.blue); ren.RenderCopy(retr_texture, nullptr, &dstRect); } void Graphics_SDL::drawChar(int x, int y, char ch, const Graphics_SDL::Context color) { SDL_Rect dstRect = { x * FONT_WIDTH, y * FONT_HEIGHT, FONT_WIDTH, FONT_HEIGHT }; int x_cord = (ch % tiles_per_row) * FONT_WIDTH; int y_cord = (ch / tiles_per_row) * FONT_HEIGHT; SDL_Rect srcRect = { x_cord, y_cord, FONT_WIDTH, FONT_HEIGHT }; if (memcmp(&color, &Context::DEFAULT, sizeof(color))) SDL_SetTextureColorMod(ttf_texture.get(), color.red, color.green, color.blue); ren.RenderCopy(ttf_texture.get(), &srcRect, &dstRect); } void Graphics_SDL::repaint() { ren.RenderClear(); // SDL_RenderCopy(ren, main_texture, NULL,NULL); TBD for (auto p : c) p->render(*this, { 0, 0, getWidth(), getHeight() }); ren.RenderPresent(); } Graphics* new_graphics() { return new Graphics_SDL(); } //// Now for the plug functions void Graphics::drawString(int x, int y, const std::string& str, bool must_kern, Context gc) { return static_cast<Graphics_SDL*>(this)->drawString(x,y,str,must_kern,gc); } void Graphics::drawChar(int x, int y, char str, Context gc) { return static_cast<Graphics_SDL*>(this)->drawChar(x,y,str,gc); } void Graphics::handle_events(Controller* c) { return static_cast<Graphics_SDL*>(this)->handle_events(c); } void Graphics::repaint() { return static_cast<Graphics_SDL*>(this)->repaint(); } void Graphics::destroy() { return static_cast<Graphics_SDL*>(this)->destroy(); }
#pragma once #include <BWAPI.h> namespace DrawTools { void DrawUnitBoundingBoxes(); void DrawUnitCommands(); void DrawUnitHealthBars(); void DrawHealthBar(BWAPI::Unit unit, double ratio, BWAPI::Color color, int yOffset); void DrawAllRegions(); void DrawCircleAroundStart(); void DrawCircleAroundLocation(BWAPI::Position center); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef DESKTOP_SETTINGS_H #define DESKTOP_SETTINGS_H #include "adjunct/desktop_util/settings/SettingsType.h" #include "modules/util/OpHashTable.h" /** @brief class for maintaining which settings have changed */ class DesktopSettings : private OpINT32Set { public: void Add(SettingsType setting) {OpINT32Set::Add(setting);} BOOL IsChanged(SettingsType setting) const {return OpINT32Set::Contains(setting);} }; #endif // SETTINGS_H
// Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-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 _Storage_BucketOfPersistent_HeaderFile #define _Storage_BucketOfPersistent_HeaderFile #include <Standard_Integer.hxx> #include <Standard_Persistent.hxx> class Storage_Schema; class Storage_BucketOfPersistent; class Storage_BucketIterator; class Storage_Bucket { friend class Storage_BucketIterator; friend class Storage_Schema; friend class Storage_BucketOfPersistent; Standard_Persistent** mySpace; Standard_Integer mySpaceSize; Standard_Integer myCurrentSpace; void Append(Standard_Persistent *); Standard_Persistent* Value(const Standard_Integer theIndex) const; public: Storage_Bucket() : mySpace(0L), mySpaceSize(200000), myCurrentSpace(-1) { mySpace = (Standard_Persistent**)Standard::Allocate(sizeof(Standard_Persistent*) * mySpaceSize); } Storage_Bucket(const Standard_Integer theSpaceSize) : mySpace(0L), mySpaceSize(theSpaceSize), myCurrentSpace(-1) { mySpace = (Standard_Persistent**)Standard::Allocate(sizeof(Standard_Persistent*) * mySpaceSize); } void Clear(); ~Storage_Bucket(); }; class Storage_BucketOfPersistent { friend class Storage_BucketIterator; Storage_Bucket** myBuckets; Standard_Integer myNumberOfBucket; Standard_Integer myNumberOfBucketAllocated; Storage_Bucket* myCurrentBucket; Standard_Integer myCurrentBucketNumber; Standard_Integer myLength; Standard_Integer myBucketSize; public: Storage_BucketOfPersistent(const Standard_Integer theBucketSize = 300000, const Standard_Integer theBucketNumber = 100); Standard_Integer Length() const { return myLength; } void Append(const Handle(Standard_Persistent)& sp); Standard_Persistent* Value(const Standard_Integer theIndex); void Clear(); ~Storage_BucketOfPersistent() ; }; class Storage_BucketIterator { Storage_BucketOfPersistent *myBucket; Storage_Bucket *myCurrentBucket; Standard_Integer myCurrentBucketIndex; Standard_Integer myCurrentIndex; Standard_Integer myBucketNumber; Standard_Boolean myMoreObject; public: Storage_BucketIterator(Storage_BucketOfPersistent*); void Init(Storage_BucketOfPersistent*); void Reset(); Standard_Persistent* Value() const { if (myCurrentBucket) { return myCurrentBucket->mySpace[myCurrentIndex]; } else return 0L; } Standard_Boolean More() const { return myMoreObject; } void Next(); }; #endif
#include "core/pch.h" #ifdef M2_SUPPORT #include "quote.h" #include "adjunct/m2/src/engine/engine.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" OpQuoteBuffer::OpQuoteBuffer(OpString* destination, unsigned int buffer_size, unsigned int rollback_size) : m_tmp_buffer(OP_NEWA(uni_char, buffer_size+1)), m_tmp_buffer_pos(0), m_destination(destination), m_destination_length(destination ? destination->Length() : 0), m_buffer_size(buffer_size), m_rollback_size(rollback_size < buffer_size ? rollback_size : (buffer_size - 1)) { m_tmp_buffer[0] = m_tmp_buffer[m_buffer_size] = 0; } OpQuoteBuffer::~OpQuoteBuffer() { if (m_tmp_buffer) { m_tmp_buffer[m_tmp_buffer_pos]=0; m_destination->Append(m_tmp_buffer); //Append the remaining of m_tmp_buffer OP_DELETEA(m_tmp_buffer); } } OP_STATUS OpQuoteBuffer::Append(uni_char append_char) { if (!m_tmp_buffer) return OpStatus::ERR_NO_MEMORY; m_tmp_buffer[m_tmp_buffer_pos++]=append_char; if (m_tmp_buffer_pos==m_buffer_size) { int append_length = m_buffer_size-m_rollback_size; uni_char cTmp = m_tmp_buffer[append_length]; //Remember this char, so we can set it back after having zero-terminated it m_tmp_buffer[append_length]=0; //Allocate bulk of memory if needed if ((m_destination_length+append_length) >= m_destination->Capacity()) { if (m_destination->Reserve((m_destination_length+append_length)*2) == NULL) //Make room for twice the stringlength return OpStatus::ERR_NO_MEMORY; } //Append string m_destination->Append(m_tmp_buffer); m_destination_length += append_length; m_tmp_buffer[append_length]=cTmp; memmove(m_tmp_buffer, m_tmp_buffer+append_length, UNICODE_SIZE(m_rollback_size)); m_tmp_buffer_pos=m_rollback_size; } return OpStatus::OK; } OP_STATUS OpQuoteBuffer::Append(const OpStringC& append_string) { return Append(append_string.CStr(), append_string.Length()); } OP_STATUS OpQuoteBuffer::Append(const uni_char* append_string_ptr, int length) { OP_STATUS ret = OpStatus::OK; int i; for (i=0; i<length && ret==OpStatus::OK; i++) { ret = Append(*(append_string_ptr+i)); } return ret; } OP_STATUS OpQuoteBuffer::Delete(unsigned int delete_count) { if (delete_count>m_tmp_buffer_pos) return OpStatus::ERR_OUT_OF_RANGE; m_tmp_buffer_pos-=delete_count; return OpStatus::OK; } uni_char OpQuoteBuffer::Peek(unsigned int back_count) const { return back_count>=m_tmp_buffer_pos?(uni_char)0:m_tmp_buffer[m_tmp_buffer_pos-back_count-1]; } OpQuote::OpQuote(BOOL is_flowed, BOOL has_delsp, BOOL should_autowrap, unsigned int max_line_length, unsigned int max_quote_depth) : m_max_line_length(max_line_length), m_max_quote_depth(max_quote_depth), m_is_flowed(is_flowed), m_has_delsp(has_delsp), m_should_autowrap(should_autowrap) { if (!m_is_flowed) m_has_delsp = FALSE; if (m_max_line_length==0) m_max_line_length = 76; if (m_max_quote_depth>=m_max_line_length) //This should be rare... m_max_quote_depth=m_max_line_length-1; } OpQuote::~OpQuote() { } OP_STATUS OpQuote::QuoteAndWrapText(OpString& quoted_and_wrapped_text, const OpStringC& original_text, uni_char quote_char) { OP_STATUS ret; OpString quoted_text; quoted_and_wrapped_text.Empty(); if (original_text.IsEmpty()) return OpStatus::OK; ret = QuoteText(quoted_text, original_text, quote_char); if (ret==OpStatus::OK) { if (m_should_autowrap) { ret = WrapText(quoted_and_wrapped_text, quoted_text, TRUE /*there shouldn't be any nonquoted lines */); } else { ret = quoted_and_wrapped_text.Set(quoted_text); } } if (ret!=OpStatus::OK) quoted_and_wrapped_text.Empty(); return ret; } OP_STATUS OpQuote::QuoteText(OpString& quoted_text, const OpStringC& original_text, uni_char quote_char) { OP_STATUS ret = OpStatus::OK; quoted_text.Empty(); const uni_char* original_text_cstr = original_text.CStr(); unsigned int original_text_len = uni_strlen(original_text_cstr); unsigned int original_text_pos = 0; //Allocate buffer used to cache OpString::Append (prevent fragmentation) OpQuoteBuffer quote_buffer(&quoted_text, 1024, 3); //Buffer should keep 3 uni_char: reflow-space, CR and LF ret = quote_buffer.Validate(); if (ret!=OpStatus::OK) return ret; OpString snip_text; RETURN_IF_ERROR(g_languageManager->GetString(Str::S_STRIPPED_QUOTE, snip_text)); RETURN_IF_ERROR(snip_text.Append(UNI_L("\r\n"))); // Quote the text, line by line unsigned current_quote_depth; BOOL found_sig=FALSE, purging=FALSE; while (ret==OpStatus::OK && !found_sig && original_text_pos<=original_text_len) { if ((original_text_pos+3)<=original_text_len && original_text_cstr[original_text_pos]=='-' && original_text_cstr[original_text_pos+1]=='-' && original_text_cstr[original_text_pos+2]==' ' && (original_text_cstr[original_text_pos+3]=='\r' || original_text_cstr[original_text_pos+3]=='\n')) { found_sig=TRUE; break; } current_quote_depth = 0; while (original_text_cstr[original_text_pos+current_quote_depth]=='>') current_quote_depth++; if (current_quote_depth>=m_max_quote_depth && !purging) { ret = quote_buffer.Append(snip_text); } purging = current_quote_depth>=m_max_quote_depth; if (ret==OpStatus::OK) { if (purging) //Skip the current line of text { while (original_text_pos<=original_text_len && original_text_cstr[original_text_pos]!='\r' && original_text_cstr[original_text_pos]!='\n') original_text_pos++; //Skip line if (original_text_pos<=original_text_len && original_text_cstr[original_text_pos]=='\r') original_text_pos++; //Skip CR if (original_text_pos<=original_text_len && original_text_cstr[original_text_pos]=='\n') original_text_pos++; //Skip LF } else //Append this line to the buffer { if (quote_char) { ret = quote_buffer.Append(quote_char); if (ret==OpStatus::OK && original_text_cstr[original_text_pos]!='>' && original_text_cstr[original_text_pos]!='\r' && original_text_cstr[original_text_pos]!='\n') { ret = quote_buffer.Append(' '); } } if (ret==OpStatus::OK && original_text_pos<=original_text_len) { uni_char* line_end = uni_strpbrk((uni_char*)original_text_cstr+original_text_pos, UNI_L("\r\n")); if (!line_end) line_end = const_cast<uni_char*>(original_text_cstr+original_text_len); int tmp_text_len = line_end - (original_text_cstr+original_text_pos); while ((!m_is_flowed || !m_should_autowrap) && tmp_text_len>0 && *(original_text_cstr+original_text_pos+tmp_text_len-1)==' ') tmp_text_len--; if (tmp_text_len>0) { ret = quote_buffer.Append(original_text_cstr+original_text_pos, tmp_text_len); if (ret==OpStatus::OK && m_should_autowrap && m_is_flowed && !m_has_delsp && *(line_end-1)==' ') //If it was flowed, without extra delsp-char, append one. Don't worry about signature, we won't get here if current line is the delimiter { ret = quote_buffer.Append(' '); } } original_text_pos = line_end-original_text_cstr; if (*(original_text_cstr+original_text_pos)==0) original_text_pos++; //Quick hack to terminate at EOF } if (ret==OpStatus::OK && original_text_pos<=original_text_len && original_text_cstr[original_text_pos]=='\r') { ret = quote_buffer.Append(original_text_cstr[original_text_pos++]); } if (ret==OpStatus::OK && original_text_pos<=original_text_len && original_text_cstr[original_text_pos]=='\n') { ret = quote_buffer.Append(original_text_cstr[original_text_pos++]); } } } } // We have added delsp characters where necessary m_has_delsp = m_is_flowed; return ret; } OP_STATUS OpQuote::VerifyBufferCapacity(OpString& buffer, uni_char*& current_position, int needed, int grow_size) const { int used = current_position-buffer.CStr(); if (used < 0) { OP_ASSERT(0); return OpStatus::ERR; } if (needed <= (buffer.Capacity()-used)) return OpStatus::OK; if (!buffer.Reserve(buffer.Capacity()+needed+grow_size)) return OpStatus::ERR_NO_MEMORY; current_position = const_cast<uni_char*>(buffer.CStr())+used; return OpStatus::OK; } OP_STATUS OpQuote::WrapText(OpString& wrapped_text, const OpStringC& original_text, BOOL strip_nonquoted_flows) { wrapped_text.Empty(); if (original_text.IsEmpty()) return OpStatus::OK; //Nothing to do const int buffer_grow = 100+original_text.Length()/256; //Counter of how many characters we have to spare in the destination buffer (we need to realloc if this is negative) if (!wrapped_text.Reserve(original_text.Length()+buffer_grow+1)) return OpStatus::ERR_NO_MEMORY; uni_char* source = const_cast<uni_char*>(original_text.CStr()); uni_char* destination = const_cast<uni_char*>(wrapped_text.CStr()); // Optimization: Allocate variables used in the loop here to avoid unneeded allocation/deallocation OP_STATUS ret; int i, temp_length; uni_char* source_fragment_start = NULL; uni_char* source_fragment_end; uni_char current_char; BOOL start_of_destination_line; BOOL line_is_signature; int skipped_spaces; int destination_line_bytes; //Number of bytes copied to the current destination line. Must not exceed 998 int destination_line_halfwidths; //Logical width of text on line. Count CJK full-width as twice the width of latin characters. Should not exceed m_max_line_length int current_quote = 0, next_quote; BOOL needs_flow_char; //While-loop expects source to point to text after quote-levels. Adjust pointer and count quotes before we loop while (*source=='>') {source++; current_quote++;} if (current_quote>0 && *source==' ') source++; while (source && *source) { /* ** Start a new destination line */ destination_line_bytes = destination_line_halfwidths = 0; //Insert quote-chars if (current_quote > 0) { if ((ret=VerifyBufferCapacity(wrapped_text, destination, current_quote+1, buffer_grow)) != OpStatus::OK) return ret; for (i=0; i<current_quote; i++) *(destination++) = '>'; //current_quote will usually be small, so a memset would probably not be faster *(destination++) = ' '; destination_line_bytes = destination_line_halfwidths = current_quote + 1; //All of these are half-width } next_quote = current_quote; start_of_destination_line = TRUE; while (source && *source) { /* ** Find fragment */ source_fragment_start = source_fragment_end = source; //Skip whitespace at start of fragment while (*source_fragment_end==' ') { source_fragment_end++; destination_line_halfwidths++; } line_is_signature = FALSE; //Find end of fragment if (start_of_destination_line && current_quote==0 && //Signature? *source_fragment_start=='-' && *(source_fragment_start+1)=='-' && *(source_fragment_start+2)==' ' && (*(source_fragment_start+3)=='\r' || *(source_fragment_start+3)=='\n')) { source_fragment_end = source_fragment_start+3; destination_line_halfwidths = 3; line_is_signature = TRUE; } else { while ((current_char = *source_fragment_end) != 0) { //Are we at EOL/EOF? if (current_char=='\r' || current_char=='\n') { break; } destination_line_halfwidths += ((current_char>=0x3000 && current_char<=0xD7A3) || (current_char>=0xF900 && current_char<=0xFAFF) || (current_char>=0xFF01 && current_char<=0xFF64)) ? 2 : 1; //Hack to identify full-width characters // We want to break *after* SP, not before if (*source_fragment_end==0 || *++source_fragment_end==' ') { break; } } } skipped_spaces = 0; if (source_fragment_end!=source_fragment_start) { //Include whitespace after fragment while (*source_fragment_end==' ') { source_fragment_end++; destination_line_halfwidths++; } //We're at start of next fragment. Go one back (two if delsp=yes)(destination_line_halfwidths has not been adjusted for the last character, so no need to adjust that) source_fragment_end--; if (*source_fragment_end==' ' && (*(source_fragment_end+1)=='\r' || *(source_fragment_end+1)=='\n' || *(source_fragment_end+1)==0)) //Space at end of line? { if (current_quote==0 && !line_is_signature) { while (*source_fragment_end==' ') { source_fragment_end--; destination_line_halfwidths--; skipped_spaces++; } } else if (source_fragment_end!=source_fragment_start && !line_is_signature && m_has_delsp) { source_fragment_end--; destination_line_halfwidths--; skipped_spaces = 1; } } } else //Blank line, end-of-line, etc. Test for reflow { //Find next fragment and quote-level on next line next_quote = 0; source = source_fragment_end; if (*source=='\r') source++; if (*source=='\n') source++; while (*source=='>') {source++; next_quote++;} if (*source==' ' && next_quote>0) source++; BOOL signature = ((destination-wrapped_text.CStr())>=3 && *(destination-1)==' ' && *(destination-2)=='-' && *(destination-3)=='-' && ((destination-wrapped_text.CStr())==3 || (*(destination-4)=='\r' || *(destination-4)=='\n'))); //Strip whitespace at end of unquoted lines if requested, and always when quote-level changes if (!signature && ((current_quote==0 && strip_nonquoted_flows) || current_quote!=next_quote || start_of_destination_line)) { while (destination>wrapped_text.CStr() && *(destination-1)==' ') destination--; } if (!signature && destination>wrapped_text.CStr() && *(source_fragment_end-1)==' ' && next_quote==current_quote && current_quote>0) //Softwrap. Reflow! { continue; } else //Hardwrapped. End the destination line { break; } } //Copy fragment? if (start_of_destination_line || (destination_line_halfwidths+1) <= (int)m_max_line_length) //We have to add 1, in case this line will need to flow { if (start_of_destination_line) { //(RFC2646, §4.1, #1) if ((destination_line_bytes + (source_fragment_end-source_fragment_start+1) + 1) > 998) { source_fragment_end = source_fragment_start+(998-1-destination_line_bytes); } //(RFC2646, §4.1, #3) if (current_quote==0 && (*source_fragment_start==' ' || uni_strni_eq((const uni_char*)source_fragment_start, "FROM ", 5))) { if ((ret=VerifyBufferCapacity(wrapped_text, destination, 1, buffer_grow)) != OpStatus::OK) return ret; *destination++ = ' '; } } temp_length = source_fragment_end-source_fragment_start+1; if ((ret=VerifyBufferCapacity(wrapped_text, destination, temp_length, buffer_grow)) != OpStatus::OK) return ret; op_memcpy(destination, source_fragment_start, temp_length * sizeof(uni_char)); destination += temp_length; destination_line_bytes += temp_length; source = source_fragment_end+1+skipped_spaces; start_of_destination_line = FALSE; } else //we need to flow { break; } } /* ** End the destination line */ //We get here for 8 different reasons and expected behaviour: //1. Unquoted line where we have [atom][space][CRLF or EOF] Wrap (Trim user-inserted space) //2. Quoted line where we have [atom][space][CRLF or EOF] Flow, we have the flow char //3. Unquoted line where we have [atom][CRLF or EOF] Wrap //4. Quoted line where we have [atom][CRLF or EOF] Wrap, we do not have the flow char //5. Unquoted line where we have [atom][space][next atom] Flow, user wants a long line //6. Quoted line where we have [atom][space][next atom] Flow, content was a long line //7. Unquoted line where we have [first ~998 part of atom][next part of atom] Flow, user wrote a long word //8. Quoted line where we have [first ~998 part of atom][next part of atom] Flow, content was a long word //source_fragment_start points to first character of last [atom] (or CRLF/EOF) //source points to \0 if EOF if (*source || destination==wrapped_text.CStr()) { needs_flow_char = TRUE; if (!*source_fragment_start || *source_fragment_start=='\r' || *source_fragment_start=='\n') //Handle 1-4 on the list above { if (current_quote==0 || (destination!=wrapped_text.CStr() && *(destination-1)!=' ')) //Handle 1, 3 and 4 on the list above needs_flow_char = FALSE; } //Don't flow across quote-levels if (current_quote != next_quote) { current_quote = next_quote; needs_flow_char = FALSE; } //Insert hard or soft linefeed if ((ret=VerifyBufferCapacity(wrapped_text, destination, 3, buffer_grow)) != OpStatus::OK) return ret; if (needs_flow_char) { *destination++ = ' '; } *destination++ = '\r'; *destination++ = '\n'; } start_of_destination_line = TRUE; } //Terminate string if ((ret=VerifyBufferCapacity(wrapped_text, destination, 1, 1)) != OpStatus::OK) return ret; *destination++ = 0; return OpStatus::OK; } OP_STATUS OpQuote::UnwrapText(OpString& unwrapped_text, const OpStringC& original_text) { unwrapped_text.Empty(); if (original_text.IsEmpty()) return OpStatus::OK; //Nothing to do const int buffer_grow = 100; if (!unwrapped_text.Reserve(original_text.Length()+buffer_grow+1)) return OpStatus::ERR_NO_MEMORY; OP_STATUS ret; uni_char* line_start = const_cast<uni_char*>(original_text.CStr()); uni_char* line_end; uni_char* destination = const_cast<uni_char*>(unwrapped_text.CStr()); BOOL last_line_flowed = FALSE; int delsp_offset; while (line_start && *line_start) { line_end = uni_strpbrk(line_start, UNI_L("\r\n")); //If we go from flowed to wrapped state, make sure the linefeed is inserted if (*line_start=='>' && last_line_flowed) { if ((ret=VerifyBufferCapacity(unwrapped_text, destination, 2, buffer_grow)) != OpStatus::OK) //We will write two characters not present in the original string return ret; *destination++ = '\r'; *destination++ = '\n'; } if (!line_end) //We're at the end of the text. { if (*line_start==' ') line_start++; //Skip space-stuffing if ((ret=VerifyBufferCapacity(unwrapped_text, destination, uni_strlen(line_start), buffer_grow)) != OpStatus::OK) return ret; uni_strcpy(destination, line_start); return OpStatus::OK; } else //New line. Append the line to the end of destination buffer { if (line_end == line_start) { last_line_flowed = FALSE; } else if (*line_start=='>') //Quoted content should not be unwrapped { if ((ret=VerifyBufferCapacity(unwrapped_text, destination, (line_end-line_start), buffer_grow)) != OpStatus::OK) return ret; op_memcpy(destination, line_start, (line_end-line_start) * sizeof(uni_char)); destination += (line_end-line_start); line_start=line_end; last_line_flowed = FALSE; //In this function, we should never unflow quoted lines } else { delsp_offset = 0; if (*line_start==' ') line_start++; //Skip space-stuffing if (line_end>line_start && *(line_end-1)==' ' && !((line_end-line_start)==3 && uni_strncmp(line_start, UNI_L("-- "), 3)==0)) //Signature should not unwrap { last_line_flowed = TRUE; if (m_has_delsp) delsp_offset = 1; } else { last_line_flowed = FALSE; } if ((ret=VerifyBufferCapacity(unwrapped_text, destination, (line_end-line_start)-delsp_offset, buffer_grow)) != OpStatus::OK) return ret; op_memcpy(destination, line_start, ((line_end-line_start)-delsp_offset) * sizeof(uni_char)); destination += (line_end-line_start)-delsp_offset; if (last_line_flowed) //If we have unwrapped lines, skip whitespace and linefeed { if (*line_end=='\r') line_end++; if (*line_end=='\n') line_end++; } line_start=line_end; } if ((ret=VerifyBufferCapacity(unwrapped_text, destination, 2, buffer_grow)) != OpStatus::OK) return ret; if (*line_start=='\r') *destination++ = *line_start++; if (*line_start=='\n') *destination++ = *line_start++; } } if ((ret=VerifyBufferCapacity(unwrapped_text, destination, 1, 1)) != OpStatus::OK) //We will write one character not counted in the original string return ret; *destination = 0; //Just to be safe. It could get here without zero-terminator return OpStatus::OK; } #endif //M2_SUPPORT
#include "Warrior.h" const WeaponType Warrior::types[] = {WeaponType::sword, WeaponType::axe}; Warrior::Warrior(std::string name):Character() { this->setName(name); this->setHealth(28); this->setStrength(12); this->setDefense(7); this->setSpeed(7); this->setMovement(6); this->setSkill(8); this->setLuck(6); this->setMagic(0); this->setResistance(3); this->setExp(0); this->setLevel(1); Weapon *weapon = new Sword(); setWeapon(weapon); } Warrior::~Warrior() { std::cout << "Warrior Destructor" << std::endl; } Warrior::Warrior(const Warrior& other):Character(other) { this->setWeapon(other.getWeapon()); } Warrior& Warrior::operator=(const Warrior& rhs) { if(this==&rhs) return *this; Character::operator=(rhs); return *this; } bool Warrior::operator==(const Warrior* w)const { cout << "bonjour" << endl; return Character::operator==(w); } Warrior* Warrior::clone()const { return new Warrior(*this); } void Warrior::setWeapon(Weapon* weapon) { if (weapon->TYPE == types[0] || weapon->TYPE == types[1]) Character::setWeapon(weapon); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addHealth(){ int tmp= this->getHealth(); int ran=rand(); while (ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=55; } else{ max=65; } if((tmp>0) && (ran>=max)){ tmp++; } this->setHealth(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addStrength(){ int tmp= this->getStrength(); int ran = rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=45; } else{ max=35; } if((tmp>0) && (ran>=max)){ tmp++; } this->setStrength(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addDefense(){ int tmp= this->getDefense(); int ran= rand(); while(ran>100){ ran = rand(); } int max; if(this->getName()=="Kevin"){ max=65; } else{ max=75; } if((tmp>0) && (ran>=max)){ tmp++; } this->setDefense(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addSpeed(){ int tmp= this->getSpeed(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=85; } else{ max=95; } if((tmp>0) && (ran>=max)){ tmp++; } this->setSpeed(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addResistance(){ int tmp= this->getResistance(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=75; } else{ max=70; } if((tmp>0) && (ran>=max)){ tmp++; } this->setResistance(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addMagic(){ int tmp= this->getMagic(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=95; } else{ max=90; } if((tmp>0) && (ran>=max)){ tmp++; } this->setMagic(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addLuck(){ int tmp= this->getLuck(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=85; } else{ max=90; } if((tmp>0) && (ran>=max)){ tmp++; } this->setLuck(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Warrior::addSkill(){ int tmp= this->getSkill(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Kevin"){ max=75; } else{ max=80; } if((tmp>0) && (ran>=max)){ tmp++; } this->setSkill(tmp); }
#ifndef BUSINESSCHECKING_H #define BUSINESSCHECKING_H #include "Customer.h" #include "Account.h" using namespace std; //Initialize the class, functions and variables //Inherited from Account class class BusinessChecking:public Account { public: BusinessChecking(); BusinessChecking(string a_id, double a_bal, string a_date, Customer &a_cus); void monthly_fee(); protected: private: double charge_rate; }; #endif // BUSINESSCHECKING_H
/* * cDiInfo - An application to get information via the Windows SetupDi... APIs * Charles Machalow - MIT License - (C) 2016 * Core.h - Core SetupDi-interfacing header file */ #pragma once // Local includes #include "Attribute.h" #include "Enumerations.h" #include "Registry.h" #include "Strings.h" // STL includes #include <algorithm> #include <future> #include <map> #include <string> #include <vector> // WinApi Includes #include <Windows.h> #include <initguid.h> // Need this for the GUIDs to be generated #include <ks.h> // Needs to be before ksmedia.h #include <Ksmedia.h> // Needs to be before bdamedia.h #include <bdatypes.h> // Needs to be before bdamedia.h #include <avc.h> #include <Bdamedia.h> #include <Bthdef.h> #include <cfgmgr32.h> #include <DbgHelp.h> #include <Hidclass.h> #include <ioevent.h> #include <Ndisguid.h> #include <Ntddkbd.h> #include <Ntddmodm.h> #include <Ntddmou.h> #include <Ntddpar.h> #pragma warning ( push ) #pragma warning( disable: 4091 ) #include <Ntddscsi.h> // Disable the warning this throws #pragma warning( pop ) #include <Ntddstor.h> #include <Ntddvdeo.h> #include <PortableDevice.h> #define _NTSCSI_USER_MODE_ #include <scsi.h> #include <Sensors.h> #include <SetupAPI.h> #include <storduid.h> #include <usbioctl.h> #include <Usbiodef.h> #include <Wiaintfc.h> // This is missing from Ntddstor.h for some reason typedef struct _MEDIA_SERIAL_NUMBER_DATA { ULONG SerialNumberLength; ULONG Result; ULONG Reserved[2]; UCHAR SerialNumberData[1]; } MEDIA_SERIAL_NUMBER_DATA, *PMEDIA_SERIAL_NUMBER_DATA; // An AttributeMap is a map of string to string // name of attribute -> string of attribute value typedef std::map<std::string, std::string> AttributeMap; // Used to map a DeviceId to a SCSI Port typedef std::map<std::string, UINT16> DeviceIdToScsiPortMap; // Used to designate that we couldn't get this attribute #define UNAVAILABLE_ATTRIBUTE "<Attribute Unavailable>" // Used to designate an inability to find children #define NO_CHILDREN "<No Children Found>" // Used to designate an inability to find the parent #define NO_PARENT "<No Parent Found>" // Used to designate an inability to find siblings #define NO_SIBLINGS "<No Siblings Found>" // Used if no problem is detected #define NO_PROBLEM "<No Problem Detected>" // Used as a (sketchy) way of passing a DEVINST in a string vector #define DEVINFO_DATA_STRING "__devInfoDataString" // Possible aliases to SystemRoot #define SYSTEM_ROOT1 "\\SystemRoot\\System32" #define SYSTEM_ROOT2 "System32" // Here to avoid warnings from importing ntddser.h #define IOCTL_SERIAL_GET_COMMSTATUS 0x1b006c // Get an HDEVINFO for all classes HDEVINFO getAllClassesHDevInfo(); // Get an HDEVINFO for all interfaces of a given GUID HDEVINFO getInterfaceHDevInfo(GUID classGuid); // Takes a complete HDEVINFO, specific device PSP_DEV_INFO_DATA, DWORD property and TYPE // The TYPE is used to get a string representation of the given property bool getDevInfoProperty(HDEVINFO &devs, PSP_DEVINFO_DATA devInfo, DWORD property, TYPE retType, std::string name, std::string description, cdi::attr::Attribute &attr); // Takes a complete HDEVINFO, corresponding SP_DEVINFO_DATA. Returns True if we are able // to get driver information. If returning True, the PSP_DRVINFO_DATA is updated bool getDriverInfoData(HDEVINFO devs, SP_DEVINFO_DATA devInfo, PSP_DRVINFO_DATA driverInfoData); // Gets the Device Id for the given DEVINST std::string getDeviceId(DEVINST &devInst); // Takes a complete HDEVINFO and SP_DEVINFO_DATA and returns an AttributeSet // this is a collection of 'attributes' cdi::attr::AttributeSet getDeviceAttributeSet(HDEVINFO devs, SP_DEVINFO_DATA devInfo, DeviceIdToScsiPortMap &deviceIdToScsiPortMap); // Goes through all DevNode Propertiy Keys and add missing properties to the AttributeSet void addOtherDevNodeProperties(cdi::attr::AttributeSet &attributeSet, DEVINST devInst); // Goes through all resouce descriptors for the device and adds their info to the AttributeSet void addDeviceConfigurationAndResources(cdi::attr::AttributeSet &attributeSet, DEVINST devInst); // Goes through all resouce descriptors for the interface and adds their info to the AttributeSet void addInterfaceConfigurationAndResources(cdi::attr::AttributeSet &attributeSet); // Gets a vector of interfaces based on the given GUID. If the GUID is GUID_NULL, all DEVINTERFACE GUIDs will be used cdi::attr::AttributeSetVector getInterfaceAttributeSet(GUID classGuid); // Gets a vector of all devices and their AttributeSets cdi::attr::AttributeSetVector getAllDevicesAttributeSet(); // Gets a mapping from Device Id to SCSI Port DeviceIdToScsiPortMap getDeviceIdToScsiPortMap(); // Merges two AttributeSets. If anything differs adds on a new line cdi::attr::AttributeSet &mergeAttributeSets(cdi::attr::AttributeSet &oldSet, cdi::attr::AttributeSet &newSet); // Gets attributes via the DevicePath cdi::attr::AttributeSet getAttributeSetFromDevicePath(std::string DevicePath, std::map<std::string, std::string> &msDosDeviceNameToDriveLetterMap); // Gets a map from MSDosDeviceName to drive letter std::map<std::string, std::string> getMsDosDeviceNameToDriveLetterMap();
#pragma once class Collision { public: Collision(); ~Collision(); static bool IntersectTri(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 mousePos); static bool IntersectRayToLine(Ray ray, Vector2 start, Vector2 end, Vector2* outPos = NULL, Vector2* outNormal = NULL); };
\context Staff = "baritono" \with { \consists "Ambitus_engraver" } << \set Staff.instrumentName = "Barítono" \set Staff.shortInstrumentName = "B." \set Score.skipBars = ##t \set Staff.printKeyCancellation = ##f \new Voice \global \new Voice \globalTempo \context Voice = "voz-baritono" { \override Voice.TextScript #'padding = #2.0 \override MultiMeasureRest #'expand-limit = 1 \clef "treble_8" \key g \major R1 | g 4 g 8 g 4 g 4. | fis 4 e 8 d ~ d 2 | e 4 e 8 e 4 e 4. | %% 5 d 4 d 8 b, ~ b, 2 | c 4 c 8 c 4 c 4. | d 4 d 8 d 4 d 4. | c 2 d 4 fis | g 1 | %% 10 R1*7 | g 4 g 8 g 4 g 4. | fis 4 e 8 d ~ d 2 | e 4 e 8 e 4 e 4. | %% 20 d 4 d 8 b, ~ b, 2 | c 4 c 8 c 4 c 4. | d 4 d 8 d 4 d 4. | c 2 d 4 fis | g 1 | \bar "|." } % Voice \new Lyrics \lyricsto "voz-baritono" { ¡A -- le -- lu -- ya al crea -- dor, a -- le -- lu -- "ya al" sal -- va -- dor, a -- le -- lu -- ya, a -- le -- lu -- ya, a -- le -- lu -- ya! ¡A -- le -- lu -- ya al crea -- dor, a -- le -- lu -- "ya al" sal -- va -- dor, a -- le -- lu -- ya, a -- le -- lu -- ya, a -- le -- lu -- ya! } >> % Staff ends
#include "Arduino.h" #include "Wire.h" #define SWM_I2C_SDA 10 #define SWM_I2C_SCL 11 #define I2C_BITRATE 100000 /* 100Kbps */ #define I2C_TIMEOUT 100000 uint8_t TwoWire::rxBuffer[BUFFER_LENGTH]; uint8_t TwoWire::rxBufferIndex; uint8_t TwoWire::rxBufferLength = 0; uint8_t TwoWire::txBuffer[BUFFER_LENGTH]; uint8_t TwoWire::txBufferIndex; TwoWire::TwoWire() { /* Enable the two pins required for the SCL and SDA outputs */ LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 18); Board::assignMovablePin(7, 24, SWM_I2C_SDA); Board::assignMovablePin(8, 0, SWM_I2C_SCL); /* Enable Fast Mode Plus for I2C pins */ LPC_IOCON->PIO0_10 = (LPC_IOCON->PIO0_10 & ~0x300) | (2 << 8); LPC_IOCON->PIO0_11 = (LPC_IOCON->PIO0_11 & ~0x300) | (2 << 8); LPC_SYSCON->SYSAHBCLKCTRL &= ~(1 << 18); } void TwoWire::begin() { /* Enable the clock to the I2C peripheral */ LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 5); /* Reset I2C */ //LPC_SYSCON->PRESETCTRL &= ~(1 << 6); //LPC_SYSCON->PRESETCTRL |= (1 << 6); /* Allocate SRAM for the I2C ROM Driver */ ramI2C = (uint32_t*)malloc(LPC_I2CD_API->i2c_get_mem_size()); /* Create the I2C handle */ hI2C = LPC_I2CD_API->i2c_setup(LPC_I2C_BASE, ramI2C); /* Set the I2C operating frequency */ setClock(I2C_BITRATE); /* Enable I2C timeout */ LPC_I2CD_API->i2c_set_timeout(hI2C, I2C_TIMEOUT); } void TwoWire::setClock(uint32_t baudrate) { LPC_I2CD_API->i2c_set_bitrate(hI2C, SystemCoreClock, baudrate); } void TwoWire::beginTransmission(uint8_t address) { txBufferIndex = 0; /* the first byte of the send buffer must have the slave address in the most significant 7 bits and the least significant (R/W) bit = 0 */ write(address << 1); } size_t TwoWire::write(uint8_t value) { size_t bytes_written = 0; if (txBufferIndex < BUFFER_LENGTH) { txBuffer[txBufferIndex++] = value; bytes_written++; } return bytes_written; } size_t TwoWire::write(const uint8_t *data, size_t length) { size_t bytes_written; for (bytes_written = 0; length > 0 && txBufferIndex < BUFFER_LENGTH; length--) { txBuffer[txBufferIndex++] = *data++; bytes_written++; } return bytes_written; } void TwoWire::flush(void) { } uint8_t TwoWire::endTransmission(bool stop) { I2C_PARAM param; I2C_RESULT result; param.buffer_ptr_send = txBuffer; param.num_bytes_send = txBufferIndex; param.stop_flag = stop; /* The number of bytes to be transmitted should include the first byte of the buffer which is the slave address byte */ switch (LPC_I2CD_API->i2c_master_transmit_poll(hI2C, &param, &result)) { case LPC_OK : return 0; case ERR_I2C_NAK : return 3; default: return 4; } } uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity, bool stop) { /* In all the master mode routines, the transmit buffer’s first byte must be the slave address with the R/W bit set to “0”. To enable a master read, the receive buffer’s first byte must be the slave address with the R/W bit set to “1” */ rxBuffer[0] = (txBuffer[0] = (address << 1)) | 1; I2C_PARAM param; I2C_RESULT result; param.buffer_ptr_rec = rxBuffer; param.num_bytes_rec = quantity; param.stop_flag = stop; if (LPC_I2CD_API->i2c_master_receive_poll(hI2C, &param, &result) == LPC_OK) { rxBufferIndex = 1; rxBufferLength = result.n_bytes_recd; } else rxBufferLength = 0; return rxBufferLength; } int TwoWire::available(void) { return rxBufferLength; } int TwoWire::read(void) { int byte = EOF; if (rxBufferLength > 0) { byte = rxBuffer[rxBufferIndex++]; rxBufferLength--; } return byte; } int TwoWire::peek(void) { return (rxBufferLength > 0)? rxBuffer[rxBufferIndex] : EOF; } TwoWire Wire;
#include <iostream> #include <string> #include <vector> class QuickSort { public: QuickSort(); ~QuickSort(); void run(); void Sort(int *, int, int); void PrintArray(int *, int); };
// This file is part of HemeLB and is Copyright (C) // the HemeLB team and/or their institutions, as detailed in the // file AUTHORS. This software is provided under the terms of the // license in the file LICENSE. #ifndef HEMELB_LB_IOLETS_BOUNDARYVALUES_H #define HEMELB_LB_IOLETS_BOUNDARYVALUES_H #include "net/IOCommunicator.h" #include "net/IteratedAction.h" #include "lb/iolets/InOutLet.h" #include "geometry/LatticeData.h" #include "lb/iolets/BoundaryCommunicator.h" namespace hemelb { namespace lb { namespace iolets { class BoundaryValues : public net::IteratedAction { public: BoundaryValues(geometry::SiteType ioletType, geometry::LatticeData* latticeData, const std::vector<iolets::InOutLet*> &iolets, SimulationState* simulationState, const net::MpiCommunicator& comms, const util::UnitConverter& units); ~BoundaryValues(); void RequestComms(); void EndIteration(); void Reset(); void FinishReceive(); LatticeDensity GetBoundaryDensity(const int index); LatticeDensity GetDensityMin(int boundaryId); LatticeDensity GetDensityMax(int boundaryId); static proc_t GetBCProcRank(); iolets::InOutLet* GetLocalIolet(unsigned int index) { return iolets[localIoletIDs[index]]; } unsigned int GetLocalIoletCount() { return localIoletCount; } inline unsigned int GetTimeStep() const { return state->GetTimeStep(); } inline geometry::SiteType GetIoletType() const { return ioletType; } std::vector<int> localIoletIDs; private: bool IsIOletOnThisProc(geometry::SiteType ioletType, geometry::LatticeData* latticeData, int boundaryId); std::vector<int> GatherProcList(bool hasBoundary); void HandleComms(iolets::InOutLet* iolet); geometry::SiteType ioletType; int totalIoletCount; // Number of IOlets and vector of their indices for communication purposes int localIoletCount; //std::vector<int> localIoletIDs; // Has to be a vector of pointers for InOutLet polymorphism std::vector<iolets::InOutLet*> iolets; SimulationState* state; const util::UnitConverter& unitConverter; BoundaryCommunicator bcComms; } ; } } } #endif /* HEMELB_LB_IOLETS_BOUNDARYVALUES_H */