hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
11a57fafbdb38844f8d8e26d28cfe82dca09aabd
1,795
cpp
C++
Documents/RacimoAire/Libreria/LogsSystem/adminlogssystem.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/Libreria/LogsSystem/adminlogssystem.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/Libreria/LogsSystem/adminlogssystem.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
#include "adminlogssystem.h" AdminLogsSystem::AdminLogsSystem(QObject *parent): QObject(parent) { logsSystem = new LogsSystem; logsSystem->moveToThread(&logsSystemThread); connect(&logsSystemThread, &QThread::finished, logsSystem, &QObject::deleteLater); connect(this, &AdminLogsSystem::operate, logsSystem, &LogsSystem::doWork); connect(logsSystem, &LogsSystem::resultReady, this, &AdminLogsSystem::handleResults); connect(logsSystem, &LogsSystem::SignalTemperatura, this, &AdminLogsSystem::SlotTemperatura); connect(logsSystem, &LogsSystem::SignalRAM, this, &AdminLogsSystem::SlotRAM); connect(logsSystem, &LogsSystem::SignalProcesos, this, &AdminLogsSystem::SignalProcesos); connect(logsSystem, &LogsSystem::SignalSOCKET, this, &AdminLogsSystem::SignalSOCKET); connect(logsSystem, &LogsSystem::SignalStatusWIFI, this, &AdminLogsSystem::SignalStatusWIFI); connect(logsSystem, &LogsSystem::SignalEspacioDisco, this, &AdminLogsSystem::SlotEspacioDisco); logsSystemThread.start(); //initHilo(accion); } AdminLogsSystem::~AdminLogsSystem() { } void AdminLogsSystem::SlotTemperatura(float temperatura) { emit SignalTemperatura(temperatura); } void AdminLogsSystem::SlotRAM(QString RAM) { emit SignalRAM(RAM); } void AdminLogsSystem::SlotSOCKET(int SOCKET) { emit SignalSOCKET(SOCKET); } void AdminLogsSystem::SlotProcesos(int Procesos) { emit SignalProcesos(Procesos); } void AdminLogsSystem::SlotStatusWIFI(bool StatusWIFI) { emit SignalStatusWIFI(StatusWIFI); } void AdminLogsSystem::SlotEspacioDisco(QString EspacioDisco) { emit SignalEspacioDisco(EspacioDisco); } void AdminLogsSystem::initHilo(int accion) { emit operate(accion); } void AdminLogsSystem::handleResults(const QString &result) { }
26.397059
99
0.764345
JoseSalamancaCoy
11a64298cbde84e5a0cb590587e089bccab297c9
85
hpp
C++
libraries/appbase/include/appbase/version.hpp
cubetrain/CubeTrain
b930a3e88e941225c2c54219267f743c790e388f
[ "MIT" ]
null
null
null
libraries/appbase/include/appbase/version.hpp
cubetrain/CubeTrain
b930a3e88e941225c2c54219267f743c790e388f
[ "MIT" ]
null
null
null
libraries/appbase/include/appbase/version.hpp
cubetrain/CubeTrain
b930a3e88e941225c2c54219267f743c790e388f
[ "MIT" ]
null
null
null
#pragma once namespace appbase { extern const char* appbase_version_string; }
17
46
0.741176
cubetrain
11a96bea30f234550c1e85ed2eecb7fd4303fe4b
11,613
cpp
C++
src/base/event/Brent.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
1
2020-05-16T16:58:21.000Z
2020-05-16T16:58:21.000Z
src/base/event/Brent.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
src/base/event/Brent.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
//$Id: Brent.cpp 10052 2011-12-06 22:56:03Z djcinsb $ //------------------------------------------------------------------------------ // Brent //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under NASA Prime // Contract NNG10CP02C, Task Order 28 // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: Sep 20, 2011 // /** * Implementation of Brent's Method used in event location and, eventually, * stopping conditions */ //------------------------------------------------------------------------------ #include "Brent.hpp" #include "EventException.hpp" #include "RealUtilities.hpp" #include "MessageInterface.hpp" //#define DEBUG_BRENT //#define DEBUG_BRENT_BUFFER //#define DEBUG_BRACKETACCESS //------------------------------------------------------------------------------ // Brent() //------------------------------------------------------------------------------ /** * Default constructor */ //------------------------------------------------------------------------------ Brent::Brent() : RootFinder ("BrentsMethod"), bisectionUsed (true), epochOfStep (-1.0), step (0.0), oldCValue (-1.0) { bufferSize = 3; } //------------------------------------------------------------------------------ // ~Brent() //------------------------------------------------------------------------------ /** * Destructor */ //------------------------------------------------------------------------------ Brent::~Brent() { } //------------------------------------------------------------------------------ // Brent(const Brent & b) //------------------------------------------------------------------------------ /** * Copy constructor * * @param b The original being copied here */ //------------------------------------------------------------------------------ Brent::Brent(const Brent & b) : RootFinder (b), bisectionUsed (true), epochOfStep (-1.0), step (0.0), oldCValue (-1.0) { } //------------------------------------------------------------------------------ // Brent &operator =(const Brent & b) //------------------------------------------------------------------------------ /** * Assignment operator * * @param b The original being copied here * * @return this instance, set to match b. */ //------------------------------------------------------------------------------ Brent & Brent::operator =(const Brent & b) { if (this != &b) { RootFinder::operator =(b); bisectionUsed = true; epochOfStep = -1.0; step = 0.0; oldCValue = -1.0; } return *this; } //------------------------------------------------------------------------------ // bool Brent::Initialize(GmatEpoch t0, Real f0, GmatEpoch t1, Real f1) //------------------------------------------------------------------------------ /** * Prepares Brent's Method for use * * This method calls the RootFinder initialization to prepare the buffers for * use, then rearranges the buffers as needed and sets the third data point to * the first as needed by the algorithm. * * @param t0 The earlier epoch for the data. * @param f0 The function value at t0 * @param t1 The later epoch for the data. * @param f1 The function value at t1 * * @return true if initialization succeeds, false if it fails. */ //------------------------------------------------------------------------------ bool Brent::Initialize(GmatEpoch t0, Real f0, GmatEpoch t1, Real f1) { #ifdef DEBUG_BRENT MessageInterface::ShowMessage("Brent::Initialize(%15.9lf, %12lf, %15.9lf, " "%12lf) called\n", t0, f0, t1, f1); #endif if (f0 * f1 >= 0.0) throw EventException("Error initializing Brent's method; the solution is " "not bracketed"); bool retval = RootFinder::Initialize(t0, f0, t1, f1); if (retval) { if (buffer[0] < buffer[1]) { Swap(0, 1); } epochBuffer[2] = epochBuffer[0]; buffer[2] = buffer[0]; bisectionUsed = true; // Act as if bisection was used previously } #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Brent::Buffer Data:\n %15.9lf " "%.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif return retval; } //------------------------------------------------------------------------------ // void SetValue(GmatEpoch forEpoch, Real withValue) //------------------------------------------------------------------------------ /** * Adds a new data point to the algorithm, discarding the stale data * * @param forEpoch The epoch of the new data * @param withValue The new data value * * @return true on success. (This Brent's method override always returns true) */ //------------------------------------------------------------------------------ bool Brent::SetValue(GmatEpoch forEpoch, Real withValue) { #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Received data: %15.9lf %.12lf\n", forEpoch, withValue); MessageInterface::ShowMessage("Brent::SetValue Initial Buffer Data:\n " "%15.9lf %.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif bool retval = true; oldCValue = epochBuffer[2]; epochBuffer[2] = epochBuffer[1]; buffer[2] = buffer[1]; if (buffer[0] * withValue < 0.0) { epochBuffer[1] = forEpoch; buffer[1] = withValue; } else { epochBuffer[0] = forEpoch; buffer[0] = withValue; } if (GmatMathUtil::Abs(buffer[0]) < GmatMathUtil::Abs(buffer[1])) Swap(0,1); #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Brent::SetValue Updated Buffer Data:\n " "%15.9lf %.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif return retval; } //------------------------------------------------------------------------------ // Real FindStep() //------------------------------------------------------------------------------ /** * Finds the next step to take, given the data in the buffers. * * @param currentEpoch The epoch of the latest data in the buffers. If not set, * the return value is treated as absolute and the step is not converted * from days to seconds from the current epoch. * * @return The next step * * @todo Complete the implementation of Brent's algorithm. THe current code is * performing bisection. */ //------------------------------------------------------------------------------ Real Brent::FindStep(const GmatEpoch currentEpoch) { bool bisectOnly = false; if (bisectOnly) { epochOfStep = 0.5 * (epochBuffer[0] + epochBuffer[1]); } else { Real diffAB, diffAC, diffBC; diffAB = buffer[0] - buffer[1]; if ((buffer[0] != buffer[2]) && (buffer[1] != buffer[2])) { diffAC = buffer[0] - buffer[2]; diffBC = buffer[1] - buffer[2]; // Inverse quadratic interpolation epochOfStep = epochBuffer[0] * buffer[1] * buffer[2] / ((diffAB*diffAC)) + epochBuffer[1] * buffer[0] * buffer[2] / ((-diffAB*diffBC)) + epochBuffer[2] * buffer[0] * buffer[1] / ((diffAC*diffBC)); } else { // Secant method epochOfStep = epochBuffer[1] - buffer[1] * (epochBuffer[0] - epochBuffer[1])/diffAB; } // Figure out if we need to drop back to bisection Real delta = 1.0e-8; // Numerical tolerance for epochs; set to ~1 msec Real deltaC, bMinusC, sMinusB; deltaC = GmatMathUtil::Abs(epochBuffer[2] - oldCValue); bMinusC = GmatMathUtil::Abs(epochBuffer[1]-epochBuffer[2]); sMinusB = GmatMathUtil::Abs(epochOfStep - epochBuffer[1]); if ( ((epochOfStep >= (3.0 * epochBuffer[0] + epochBuffer[1]) / 4.0) && (epochOfStep <= epochBuffer[1])) || (bisectionUsed && (sMinusB >= bMinusC / 2.0)) || (!bisectionUsed && (sMinusB >= deltaC / 2.0)) || (bisectionUsed && (bMinusC < delta)) || (!bisectionUsed && deltaC < delta) ) { // Drop back to bisection. Sigh. epochOfStep = 0.5 * (epochBuffer[0] + epochBuffer[1]); bisectionUsed = true; } else bisectionUsed = false; } // Get the step in seconds to the epochOfStep if input in days was set if (currentEpoch != -1.0) step = (epochOfStep - currentEpoch) * GmatTimeConstants::SECS_PER_DAY; else step = epochOfStep; #ifdef DEBUG_BRENT MessageInterface::ShowMessage("Brent's Method: Current Epoch: %15.9lf, " "Epoch of Step: %15.9lf, step: %15.9lf\n", currentEpoch, epochOfStep, step); #endif return step; } //------------------------------------------------------------------------------ // Real GetStepMeasure() //------------------------------------------------------------------------------ /** * Retrieves the size of the epoch brackets * * @return The difference, in seconds, between the two epochs bracketing the * zero */ //------------------------------------------------------------------------------ Real Brent::GetStepMeasure() { GmatEpoch start, end; GetBrackets(start, end); return (end - start) * GmatTimeConstants::SECS_PER_DAY; } //------------------------------------------------------------------------------ // void GetBrackets(GmatEpoch &start, GmatEpoch &end) //------------------------------------------------------------------------------ /** * Retrieves the bracketing epochs from the epoch buffer. * * @param start The epoch earlier than the zero value * @param end The epoch later than the zero value */ //------------------------------------------------------------------------------ void Brent::GetBrackets(GmatEpoch &start, GmatEpoch &end) { Real val = GmatMathUtil::Abs(buffer[0]), temp; GmatEpoch locT = epochBuffer[0], t2, dt = 9.0e9; Integer found = 0; // Find the index of the closest to zero function value for (Integer i = 1; i < 3; ++i) { temp = GmatMathUtil::Abs(buffer[i]); if (temp < val) { val = temp; locT = epochBuffer[i]; found = i; } } // Find the index of the other side t2 = epochBuffer[0]; for (Integer i = 0; i < 3; ++i) { if (found != i) { if (buffer[found] * buffer[i] < 0.0) { if (GmatMathUtil::Abs(locT - epochBuffer[i]) < dt) t2 = epochBuffer[i]; } } } start = (locT < t2 ? locT : t2); end = (locT > t2 ? locT : t2); #ifdef DEBUG_BRACKETACCESS MessageInterface::ShowMessage("Buffer data:\n"); for (Integer i = 0; i < 3; ++i) MessageInterface::ShowMessage(" %.12lf %le\n", epochBuffer[i], buffer[i]); MessageInterface::ShowMessage("Bracketing epochs: [%.12lf %.12lf]\n", start, end); #endif }
31.557065
83
0.473607
ddj116
11a97bc5e1c85f39e68e8dc81a1208fca151da56
2,913
hpp
C++
src/include/ulib/stream/ITextStream.hpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/include/ulib/stream/ITextStream.hpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/include/ulib/stream/ITextStream.hpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
// // ulib - a collection of useful classes // Copyright (C) 2007,2008,2012,2014,2017,2020 Michael Fink // /// \file ITextStream.hpp text stream interface // #pragma once namespace Stream { /// text stream interface class ITextStream { public: /// text encoding that is possible for text files enum ETextEncoding { textEncodingNative, ///< native encoding; compiler options decide if ANSI or Unicode is used for output textEncodingAnsi, ///< ANSI text encoding; depends on the current codepage (not recommended) textEncodingUTF8, ///< UTF-8 encoding textEncodingUCS2, ///< UCS-2 encoding }; /// line ending mode used to detect lines or is used for writing enum ELineEndingMode { lineEndingCRLF, ///< a CR and LF char (\\r\\n) is used to separate lines; Win32-style lineEndingLF, ///< a LF char (\\n) is used to separate lines; Linux-style lineEndingCR, ///< a CR char (\\r) is used to separate lines; Mac-style lineEndingReadAny,///< when reading, any of the above line ending modes are detected when using ReadLine() lineEndingNative, ///< native mode is used }; /// ctor ITextStream(ETextEncoding textEncoding = textEncodingNative, ELineEndingMode lineEndingMode = lineEndingNative) :m_textEncoding(textEncoding), m_lineEndingMode(lineEndingMode) { } /// dtor virtual ~ITextStream() { // nothing to cleanup } // stream capabilities /// returns text encoding currently in use ETextEncoding TextEncoding() const { return m_textEncoding; } /// returns line ending mode currently in use ELineEndingMode LineEndingMode() const { return m_lineEndingMode; } /// returns true when stream can be read virtual bool CanRead() const = 0; /// returns true when stream can be written to virtual bool CanWrite() const = 0; /// returns true when the stream end is reached virtual bool AtEndOfStream() const = 0; // read support /// reads a single character virtual TCHAR ReadChar() = 0; /// reads a whole line using line ending settings virtual void ReadLine(CString& line) = 0; // write support /// writes text virtual void Write(const CString& text) = 0; /// writes endline character virtual void WriteEndline() = 0; /// writes a line void WriteLine(const CString& line) { Write(line); WriteEndline(); } /// flushes out text stream virtual void Flush() = 0; private: friend class TextStreamFilter; /// current text encoding ETextEncoding m_textEncoding; /// current line ending mode ELineEndingMode m_lineEndingMode; }; } // namespace Stream
28.558824
115
0.626502
vividos
11aa84f6e6eb99b64fb49789870d851fe33705be
1,362
cpp
C++
UnrealSandBox/Source/UnrealSandBox/Private/SampleSubSystem.cpp
y-akahori-ramen/UnrealSandBox
6198e16d857a6997d8809c48984c26a070cd6876
[ "Unlicense" ]
null
null
null
UnrealSandBox/Source/UnrealSandBox/Private/SampleSubSystem.cpp
y-akahori-ramen/UnrealSandBox
6198e16d857a6997d8809c48984c26a070cd6876
[ "Unlicense" ]
null
null
null
UnrealSandBox/Source/UnrealSandBox/Private/SampleSubSystem.cpp
y-akahori-ramen/UnrealSandBox
6198e16d857a6997d8809c48984c26a070cd6876
[ "Unlicense" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SampleSubSystem.h" #include "AsyncSample.h" //--------------------------------------------------------------------------------- // SampleSubSystem //--------------------------------------------------------------------------------- TStatId USampleSubSystem::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(SampleSubSystem, STATGROUP_Tickables); } void USampleSubSystem::Tick(float DeltaTime) { AsyncSample->Update(DeltaTime); } bool USampleSubSystem::IsTickable() const { return true; } ETickableTickType USampleSubSystem::GetTickableTickType() const { return IsTemplate() ? ETickableTickType::Never : ETickableTickType::Conditional; } void USampleSubSystem::StartAutoDeleteAsyncSample(float WaitSec) { AsyncSample->StartAutoDeleteAsync(WaitSec); } void USampleSubSystem::StartAsyncSample(float WaitSec) { AsyncSample->StartAsyncTask(WaitSec); } void USampleSubSystem::CheckAsyncTaskBehaviour() { AsyncSample->CheckAsyncTaskBehaviour(); } void USampleSubSystem::CancelAsyncSample() { AsyncSample->CancelAsyncTask(); } void USampleSubSystem::CheckAsyncCrash() { AsyncSample->CheckCrash(); } void USampleSubSystem::Initialize(FSubsystemCollectionBase& Collection) { Super::Initialize(Collection); AsyncSample = MakeShareable(new FAsyncSample()); }
22.327869
83
0.700441
y-akahori-ramen
11acb9ab7d7b558cb8d1d57f2fd725893e1f16e0
2,236
cpp
C++
examples/particleSim/Particle.cpp
nitro44x/mirror
545e609cd260579ec132f91788921ef4f9fa2049
[ "BSD-3-Clause" ]
null
null
null
examples/particleSim/Particle.cpp
nitro44x/mirror
545e609cd260579ec132f91788921ef4f9fa2049
[ "BSD-3-Clause" ]
null
null
null
examples/particleSim/Particle.cpp
nitro44x/mirror
545e609cd260579ec132f91788921ef4f9fa2049
[ "BSD-3-Clause" ]
null
null
null
#include "Particle.hpp" #include <device_launch_parameters.h> #include <mirror/simt_macros.hpp> #include <mirror/simt_allocator.hpp> #include <mirror/simt_vector.hpp> #include <mirror/simt_serialization.hpp> #include <mirror/simt_utilities.hpp> ParticleSquare::ParticleSquare(double L) : m_L(L) {} ParticleSquare::~ParticleSquare() { ; } HOSTDEVICE double ParticleSquare::area() const { return m_L * m_L; } HOSTDEVICE double ParticleSquare::mass() const { return 1.0; } HOST void ParticleSquare::write(mirror::serializer & io) const { io.write(m_L); } HOSTDEVICE void ParticleSquare::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_L); } HOSTDEVICE ParticleSquare::type_id_t ParticleSquare::type() const { return ParticleTypes::eParticleSquare; } ParticleCircle::ParticleCircle(double radius) : m_radius(radius) {} ParticleCircle::~ParticleCircle() { ; } HOSTDEVICE double ParticleCircle::area() const { return 3.1415 * m_radius * m_radius; } HOSTDEVICE double ParticleCircle::mass() const { return 1.0; } HOST void ParticleCircle::write(mirror::serializer & io) const { io.write(m_radius); } HOSTDEVICE void ParticleCircle::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_radius); } HOSTDEVICE ParticleCircle::type_id_t ParticleCircle::type() const { return ParticleTypes::eParticleCircle; } ParticleTriangle::ParticleTriangle(double base, double height) : m_base(base), m_height(height) {} ParticleTriangle::~ParticleTriangle() { ; } HOSTDEVICE double ParticleTriangle::area() const { return 0.5 * m_base * m_height; } HOSTDEVICE double ParticleTriangle::mass() const { return 1.0; } HOST void ParticleTriangle::write(mirror::serializer & io) const { io.write(m_base); io.write(m_height); } HOSTDEVICE void ParticleTriangle::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_base); io.read(startPosition, &m_height); } HOSTDEVICE ParticleTriangle::type_id_t ParticleTriangle::type() const { return ParticleTypes::eParticleTriangle; } size_t mirror::polymorphic_traits<Particle>::cache[enum_type::Max_];
30.216216
110
0.753131
nitro44x
11adc36baae639ef2d1a38bdb34760937cd7c580
1,959
cpp
C++
ECS/ECS/ECS.cpp
oWASDo/ECS
4131269889e13be7990e250b8b9376b9a16229a3
[ "MIT" ]
null
null
null
ECS/ECS/ECS.cpp
oWASDo/ECS
4131269889e13be7990e250b8b9376b9a16229a3
[ "MIT" ]
null
null
null
ECS/ECS/ECS.cpp
oWASDo/ECS
4131269889e13be7990e250b8b9376b9a16229a3
[ "MIT" ]
null
null
null
// ECS.cpp : Questo file contiene la funzione 'main', in cui inizia e termina l'esecuzione del programma. // #include <iostream> #include <vector> #include <time.h> #include "Heder/ECS_Context.h" #include "Heder/Component.h" class ClassTest { public: ClassTest(); ~ClassTest(); void Adding() { inttt += 5; } private: int inttt; }; ClassTest::ClassTest() { inttt = 5; } ClassTest::~ClassTest() { } using namespace std; int main() { size_t entttSNumber = 5; //Create ECS context ECS_Context* context = new ECS_Context(); for (int i = 0; i < entttSNumber; i++) { //Create entity context->CreateAndAddEntity(); //Link component to entity context->AddComponentToEntity<Integer>(context->GetEntity(i), Integer(0)); if (i % 2) { context->AddComponentToEntity<Boolean>(context->GetEntity(i), Boolean()); } } context->RemoveComponentToEntity<Integer>(context->GetEntity(3)); context->AddComponentToEntity<Integer>(context->GetEntity(3), Integer(0)); { std::vector< Integer*> ii; context->GetTypes<Integer>(ii); //___________________________________________________________ clock_t begin_time = clock(); for (size_t j = 0; j < ii.size(); j++) { ii[j]->integer += 5; } std::cout << "ecs time " << clock() - begin_time << std::endl; std::cout << "ecs time " << float(clock() - begin_time) << std::endl; ii.clear(); ii.shrink_to_fit(); //___________________________________________________________ std::list<ClassTest*> v; for (size_t i = 0; i < entttSNumber; i++) { v.emplace(v.end(), new ClassTest()); } clock_t begin_time0 = clock(); for (auto vEl : v) { vEl->Adding(); } std::cout << "class time " << clock() - begin_time << std::endl; std::cout << "class time " << float(clock() - begin_time0) << std::endl;; //___________________________________________________________ for (auto vEl : v) { delete vEl; } v.clear(); delete context; } }
18.481132
105
0.654416
oWASDo
11aea2549bf0a5d545908508a65fe7247dcfbdcb
11,430
cpp
C++
src/platform/DBlmdb.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
1
2019-05-20T01:00:40.000Z
2019-05-20T01:00:40.000Z
src/platform/DBlmdb.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
4
2018-05-07T07:15:53.000Z
2018-06-01T19:35:46.000Z
src/platform/DBlmdb.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
10
2018-05-09T10:45:07.000Z
2020-01-11T17:21:28.000Z
#include "DBlmdb.hpp" #include <boost/lexical_cast.hpp> #include <iostream> #include "PathTools.hpp" using namespace platform; #ifdef _WIN32 #pragma comment(lib, "ntdll.lib") // dependency of lmdb, here to avoid linker arguments #endif static void lmdb_check(int rc, const char *msg) { if (rc != MDB_SUCCESS) throw platform::lmdb::Error(msg + std::to_string(rc)); } platform::lmdb::Env::Env() { lmdb_check(::mdb_env_create(&handle), "mdb_env_create "); } platform::lmdb::Env::~Env() { ::mdb_env_close(handle); handle = nullptr; } platform::lmdb::Txn::Txn(Env &db_env) { lmdb_check(::mdb_txn_begin(db_env.handle, nullptr, 0, &handle), "mdb_txn_begin "); } void platform::lmdb::Txn::commit() { lmdb_check(::mdb_txn_commit(handle), "mdb_txn_commit "); handle = nullptr; } platform::lmdb::Txn::~Txn() { ::mdb_txn_abort(handle); handle = nullptr; } // ::mdb_dbi_close should never be called according to docs platform::lmdb::Dbi::Dbi(Txn &db_txn) { lmdb_check(::mdb_dbi_open(db_txn.handle, nullptr, 0, &handle), "mdb_dbi_open "); } bool platform::lmdb::Dbi::get(Txn &db_txn, MDB_val *const key, MDB_val *const data) { const int rc = ::mdb_get(db_txn.handle, handle, key, data); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw Error("mdb_get " + std::to_string(rc)); return (rc == MDB_SUCCESS); } platform::lmdb::Cur::Cur(Txn &db_txn, Dbi &db_dbi) { lmdb_check(::mdb_cursor_open(db_txn.handle, db_dbi.handle, &handle), "mdb_cursor_open "); } platform::lmdb::Cur::Cur(Cur &&other) noexcept { std::swap(handle, other.handle); } bool platform::lmdb::Cur::get(MDB_val *const key, MDB_val *const data, const MDB_cursor_op op) { const int rc = ::mdb_cursor_get(handle, key, data, op); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw Error("mdb_cursor_get" + std::to_string(rc)); return (rc == MDB_SUCCESS); } platform::lmdb::Cur::~Cur() { ::mdb_cursor_close(handle); handle = nullptr; } DBlmdb::DBlmdb(const std::string &full_path, uint64_t max_db_size) : full_path(full_path) { std::cout << "lmdb libversion=" << mdb_version(nullptr, nullptr, nullptr) << std::endl; lmdb_check(::mdb_env_set_mapsize(db_env.handle, max_db_size), "mdb_env_set_mapsize "); create_directories_if_necessary(full_path); lmdb_check(::mdb_env_open(db_env.handle, full_path.c_str(), MDB_NOMETASYNC, 0644), "mdb_env_open "); // MDB_NOMETASYNC - We agree to trade chance of losing 1 last transaction for 2x performance boost db_txn.reset(new lmdb::Txn(db_env)); db_dbi.reset(new lmdb::Dbi(*db_txn)); } size_t DBlmdb::test_get_approximate_size() const { MDB_stat sta{}; lmdb_check(::mdb_env_stat(db_env.handle, &sta), "mdb_env_stat "); return sta.ms_psize * (sta.ms_branch_pages + sta.ms_leaf_pages + sta.ms_overflow_pages); } size_t DBlmdb::get_approximate_items_count() const { MDB_stat sta{}; lmdb_check(::mdb_env_stat(db_env.handle, &sta), "mdb_env_stat "); return sta.ms_entries; } DBlmdb::Cursor::Cursor( lmdb::Cur &&cur, const std::string &prefix, const std::string &middle, size_t max_key_size, bool forward) : db_cur(std::move(cur)), prefix(prefix), forward(forward) { std::string start = prefix + middle; lmdb::Val itkey(start); if (forward) is_end = !db_cur.get(itkey, data, start.empty() ? MDB_FIRST : MDB_SET_RANGE); else { if (start.empty()) is_end = !db_cur.get(itkey, data, MDB_LAST); else { if (start.size() < max_key_size) start += std::string(max_key_size - start.size(), char(0xff)); itkey = lmdb::Val(start); is_end = !db_cur.get(itkey, data, MDB_SET_RANGE); is_end = !db_cur.get(itkey, data, is_end ? MDB_LAST : MDB_PREV); // If failed to find a key >= prefix, then it should be last in db } } check_prefix(itkey); } void DBlmdb::Cursor::next() { lmdb::Val itkey; is_end = !db_cur.get(itkey, &*data, forward ? MDB_NEXT : MDB_PREV); check_prefix(itkey); } void DBlmdb::Cursor::erase() { if (is_end) return; // Some precaution lmdb_check(::mdb_cursor_del(db_cur.handle, 0), "mdb_cursor_del "); next(); } void DBlmdb::Cursor::check_prefix(const lmdb::Val &itkey) { if (is_end || itkey.size() < prefix.size() || std::char_traits<char>::compare(prefix.data(), itkey.data(), prefix.size()) != 0) { is_end = true; data = lmdb::Val{}; suffix = std::string(); return; } suffix = std::string(itkey.data() + prefix.size(), itkey.size() - prefix.size()); } std::string DBlmdb::Cursor::get_value_string() const { return std::string(data.data(), data.size()); } common::BinaryArray DBlmdb::Cursor::get_value_array() const { return common::BinaryArray(data.data(), data.data() + data.size()); } DBlmdb::Cursor DBlmdb::begin(const std::string &prefix, const std::string &middle) const { int max_key_size = ::mdb_env_get_maxkeysize(db_env.handle); return Cursor(lmdb::Cur(*db_txn, *db_dbi), prefix, middle, max_key_size, true); } DBlmdb::Cursor DBlmdb::rbegin(const std::string &prefix, const std::string &middle) const { int max_key_size = ::mdb_env_get_maxkeysize(db_env.handle); return Cursor(lmdb::Cur(*db_txn, *db_dbi), prefix, middle, max_key_size, false); } void DBlmdb::commit_db_txn() { db_txn->commit(); db_txn.reset(); db_txn.reset(new lmdb::Txn(db_env)); } void DBlmdb::put(const std::string &key, const common::BinaryArray &value, bool nooverwrite) { lmdb::Val temp_value(value.data(), value.size()); const int rc = ::mdb_put(db_txn->handle, db_dbi->handle, lmdb::Val(key), temp_value, nooverwrite ? MDB_NOOVERWRITE : 0); if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw lmdb::Error("DBlmdb::put failed " + std::string(key.data(), key.size())); if (nooverwrite && rc == MDB_KEYEXIST) throw lmdb::Error( "DBlmdb::put failed or nooverwrite key already exists " + std::string(key.data(), key.size())); } void DBlmdb::put(const std::string &key, const std::string &value, bool nooverwrite) { lmdb::Val temp_value(value.data(), value.size()); const int rc = ::mdb_put(db_txn->handle, db_dbi->handle, lmdb::Val(key), temp_value, nooverwrite ? MDB_NOOVERWRITE : 0); if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw lmdb::Error("DBlmdb::put failed " + std::string(key.data(), key.size())); if (nooverwrite && rc == MDB_KEYEXIST) throw lmdb::Error( "DBlmdb::put failed or nooverwrite key already exists " + std::string(key.data(), key.size())); } bool DBlmdb::get(const std::string &key, common::BinaryArray &value) const { lmdb::Val val1; if (!db_dbi->get(*db_txn, lmdb::Val(key), val1)) return false; value.assign(val1.data(), val1.data() + val1.size()); return true; } bool DBlmdb::get(const std::string &key, std::string &value) const { lmdb::Val val1; if (!db_dbi->get(*db_txn, lmdb::Val(key), val1)) return false; value = std::string(val1.data(), val1.size()); return true; } bool DBlmdb::get(const std::string &key, Value &value) const { return db_dbi->get(*db_txn, lmdb::Val(key), value); } void DBlmdb::del(const std::string &key, bool mustexist) { const int rc = ::mdb_del(db_txn->handle, db_dbi->handle, lmdb::Val(key), nullptr); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw lmdb::Error("DBlmdb::del failed " + std::string(key.data(), key.size())); if (mustexist && rc == MDB_NOTFOUND) // Soemtimes lmdb returns 0 for non existing keys, we have to get our own check upwards throw lmdb::Error("DBlmdb::del key does not exist " + std::string(key.data(), key.size())); } std::string DBlmdb::to_ascending_key(uint32_t key) { char buf[32] = {}; sprintf(buf, "%08X", key); return std::string(buf); } uint32_t DBlmdb::from_ascending_key(const std::string &key) { return boost::lexical_cast<uint32_t>(std::stoull(key, nullptr, 16)); } std::string DBlmdb::clean_key(const std::string &key) { std::string result = key; for (char &ch : result) { unsigned char uch = ch; if (uch >= 128) uch -= 128; if (uch == 127) uch = 'F'; if (uch < 32) uch = '0' + uch; ch = uch; } return result; } void DBlmdb::delete_db(const std::string &path) { std::remove((path + "/data.mdb").c_str()); std::remove((path + "/lock.mdb").c_str()); std::remove(path.c_str()); } void DBlmdb::run_tests() { delete_db("temp_db"); { DBlmdb db("temp_db"); db.put("history/ha", "ua", false); db.put("history/hb", "ub", false); db.put("history/hc", "uc", false); db.put("unspent/ua", "ua", false); db.put("unspent/ub", "ub", false); db.put("unspent/uc", "uc", false); std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- all keys backward --" << std::endl; for (auto cur = db.rbegin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- history forward --" << std::endl; for (auto cur = db.begin("history/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- history backward --" << std::endl; for (auto cur = db.rbegin("history/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- unspent forward --" << std::endl; for (auto cur = db.begin("unspent/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- unspent backward --" << std::endl; for (auto cur = db.rbegin("unspent/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- alpha forward --" << std::endl; for (auto cur = db.begin("alpha/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- alpha backward --" << std::endl; for (auto cur = db.rbegin("alpha/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- zero forward --" << std::endl; for (auto cur = db.begin("zero/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- zero backward --" << std::endl; for (auto cur = db.rbegin("zero/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } int c = 0; std::cout << "-- deleting c=2 iterating forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); ++c) { if (c == 2) { std::cout << "deleting " << cur.get_suffix() << std::endl; cur.erase(); } else { std::cout << cur.get_suffix() << std::endl; cur.next(); } } std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } c = 0; std::cout << "-- deleting c=2 iterating backward --" << std::endl; for (auto cur = db.rbegin(std::string()); !cur.end(); ++c) { if (c == 2) { std::cout << "deleting " << cur.get_suffix() << std::endl; cur.erase(); } else { std::cout << cur.get_suffix() << std::endl; cur.next(); } } std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } } delete_db("temp_db"); }
35.830721
117
0.626859
mygirl8893
11aeb2e0187ebf1b723e15db231e4c8d20237da0
3,315
cpp
C++
aws-cpp-sdk-dynamodb/source/model/AutoScalingSettingsDescription.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-dynamodb/source/model/AutoScalingSettingsDescription.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-dynamodb/source/model/AutoScalingSettingsDescription.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/dynamodb/model/AutoScalingSettingsDescription.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DynamoDB { namespace Model { AutoScalingSettingsDescription::AutoScalingSettingsDescription() : m_minimumUnits(0), m_minimumUnitsHasBeenSet(false), m_maximumUnits(0), m_maximumUnitsHasBeenSet(false), m_autoScalingDisabled(false), m_autoScalingDisabledHasBeenSet(false), m_autoScalingRoleArnHasBeenSet(false), m_scalingPoliciesHasBeenSet(false) { } AutoScalingSettingsDescription::AutoScalingSettingsDescription(JsonView jsonValue) : m_minimumUnits(0), m_minimumUnitsHasBeenSet(false), m_maximumUnits(0), m_maximumUnitsHasBeenSet(false), m_autoScalingDisabled(false), m_autoScalingDisabledHasBeenSet(false), m_autoScalingRoleArnHasBeenSet(false), m_scalingPoliciesHasBeenSet(false) { *this = jsonValue; } AutoScalingSettingsDescription& AutoScalingSettingsDescription::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("MinimumUnits")) { m_minimumUnits = jsonValue.GetInt64("MinimumUnits"); m_minimumUnitsHasBeenSet = true; } if(jsonValue.ValueExists("MaximumUnits")) { m_maximumUnits = jsonValue.GetInt64("MaximumUnits"); m_maximumUnitsHasBeenSet = true; } if(jsonValue.ValueExists("AutoScalingDisabled")) { m_autoScalingDisabled = jsonValue.GetBool("AutoScalingDisabled"); m_autoScalingDisabledHasBeenSet = true; } if(jsonValue.ValueExists("AutoScalingRoleArn")) { m_autoScalingRoleArn = jsonValue.GetString("AutoScalingRoleArn"); m_autoScalingRoleArnHasBeenSet = true; } if(jsonValue.ValueExists("ScalingPolicies")) { Array<JsonView> scalingPoliciesJsonList = jsonValue.GetArray("ScalingPolicies"); for(unsigned scalingPoliciesIndex = 0; scalingPoliciesIndex < scalingPoliciesJsonList.GetLength(); ++scalingPoliciesIndex) { m_scalingPolicies.push_back(scalingPoliciesJsonList[scalingPoliciesIndex].AsObject()); } m_scalingPoliciesHasBeenSet = true; } return *this; } JsonValue AutoScalingSettingsDescription::Jsonize() const { JsonValue payload; if(m_minimumUnitsHasBeenSet) { payload.WithInt64("MinimumUnits", m_minimumUnits); } if(m_maximumUnitsHasBeenSet) { payload.WithInt64("MaximumUnits", m_maximumUnits); } if(m_autoScalingDisabledHasBeenSet) { payload.WithBool("AutoScalingDisabled", m_autoScalingDisabled); } if(m_autoScalingRoleArnHasBeenSet) { payload.WithString("AutoScalingRoleArn", m_autoScalingRoleArn); } if(m_scalingPoliciesHasBeenSet) { Array<JsonValue> scalingPoliciesJsonList(m_scalingPolicies.size()); for(unsigned scalingPoliciesIndex = 0; scalingPoliciesIndex < scalingPoliciesJsonList.GetLength(); ++scalingPoliciesIndex) { scalingPoliciesJsonList[scalingPoliciesIndex].AsObject(m_scalingPolicies[scalingPoliciesIndex].Jsonize()); } payload.WithArray("ScalingPolicies", std::move(scalingPoliciesJsonList)); } return payload; } } // namespace Model } // namespace DynamoDB } // namespace Aws
24.738806
126
0.762594
Neusoft-Technology-Solutions
11afd35840a70a13c2cda758bb4e90d370e3391a
1,578
cpp
C++
src/AdcNode.cpp
elbowz/yahnc
5ffe8adcad19f25b31a252f330fe8e29d1891b4f
[ "MIT" ]
null
null
null
src/AdcNode.cpp
elbowz/yahnc
5ffe8adcad19f25b31a252f330fe8e29d1891b4f
[ "MIT" ]
null
null
null
src/AdcNode.cpp
elbowz/yahnc
5ffe8adcad19f25b31a252f330fe8e29d1891b4f
[ "MIT" ]
null
null
null
#include "AdcNode.hpp" extern int __get_adc_mode(); /** * TODO: * * manage status topic: isnan(ESP.getVcc()) => setProperty(cStatusTopic).send("error") * note: check what happen when no wire is connected to ADC pin */ AdcNode::AdcNode(const char *id, const char *name, uint32_t readInterval, float sendOnChangeAbs, const SensorBase<float>::ReadMeasurementFunc &readMeasurementFunc, const SensorBase<float>::SendMeasurementFunc &sendMeasurementFunc, const SensorBase<float>::OnChangeFunc &onChangeFunc) : BaseNode(id, name, "adc"), SensorBase(id, readInterval, 0, sendOnChangeAbs, readMeasurementFunc, sendMeasurementFunc, onChangeFunc) { // ADC pin used to measure VCC (e.g. on battery) // true if previously called macro ADC_MODE(ADC_VCC) mReadVcc = __get_adc_mode() == ADC_VCC; } void AdcNode::setup() { advertise(SensorBase::getName()) .setDatatype("float") .setFormat("0:1.00") .setUnit(cUnitVolt); } void AdcNode::loop() { SensorBase::loop(); } float AdcNode::readMeasurement() { if (mReadMeasurementFunc) { return mReadMeasurementFunc(); } return static_cast<float>(mReadVcc ? ESP.getVcc() : analogRead(A0)) / 1024.0f; } void AdcNode::sendMeasurement(float value) const { if (mSendMeasurementFunc) { return mSendMeasurementFunc(value); } if (Homie.isConnected()) { setProperty(SensorBase::getName()).send(String(value)); } }
27.684211
116
0.63815
elbowz
11afe1e7174228a8b182b569ed15320b2d4342fb
19,394
cpp
C++
mlir/lib/Support/Timing.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
mlir/lib/Support/Timing.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
mlir/lib/Support/Timing.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===- Timing.cpp - Execution time measurement facilities -----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Facilities to measure and provide statistics on execution time. // //===----------------------------------------------------------------------===// #include "mlir/Support/Timing.h" #include "mlir/Support/ThreadLocalCache.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/RWMutex.h" #include "llvm/Support/Threading.h" #include "llvm/Support/raw_ostream.h" #include <atomic> #include <chrono> using namespace mlir; using namespace detail; using DisplayMode = DefaultTimingManager::DisplayMode; constexpr llvm::StringLiteral kTimingDescription = "... Execution time report ..."; //===----------------------------------------------------------------------===// // TimingManager //===----------------------------------------------------------------------===// namespace mlir { namespace detail { /// Private implementation details of the `TimingManager`. class TimingManagerImpl { public: // Identifier allocator, map, and mutex for thread safety. llvm::BumpPtrAllocator identifierAllocator; llvm::StringSet<llvm::BumpPtrAllocator &> identifiers; llvm::sys::SmartRWMutex<true> identifierMutex; /// A thread local cache of identifiers to reduce lock contention. ThreadLocalCache<llvm::StringMap<llvm::StringMapEntry<llvm::NoneType> *>> localIdentifierCache; TimingManagerImpl() : identifiers(identifierAllocator) {} }; } // namespace detail } // namespace mlir TimingManager::TimingManager() : impl(std::make_unique<TimingManagerImpl>()) {} TimingManager::~TimingManager() {} /// Get the root timer of this timing manager. Timer TimingManager::getRootTimer() { auto rt = rootTimer(); return rt.hasValue() ? Timer(*this, rt.getValue()) : Timer(); } /// Get the root timer of this timing manager wrapped in a `TimingScope`. TimingScope TimingManager::getRootScope() { return TimingScope(getRootTimer()); } //===----------------------------------------------------------------------===// // Identifier uniquing //===----------------------------------------------------------------------===// /// Return an identifier for the specified string. TimingIdentifier TimingIdentifier::get(StringRef str, TimingManager &tm) { // Check for an existing instance in the local cache. auto &impl = *tm.impl; auto *&localEntry = (*impl.localIdentifierCache)[str]; if (localEntry) return TimingIdentifier(localEntry); // Check for an existing identifier in read-only mode. { llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex); auto it = impl.identifiers.find(str); if (it != impl.identifiers.end()) { localEntry = &*it; return TimingIdentifier(localEntry); } } // Acquire a writer-lock so that we can safely create the new instance. llvm::sys::SmartScopedWriter<true> contextLock(impl.identifierMutex); auto it = impl.identifiers.insert(str).first; localEntry = &*it; return TimingIdentifier(localEntry); } //===----------------------------------------------------------------------===// // Helpers for time record printing //===----------------------------------------------------------------------===// namespace { /// Simple record class to record timing information. struct TimeRecord { TimeRecord(double wall = 0.0, double user = 0.0) : wall(wall), user(user) {} TimeRecord &operator+=(const TimeRecord &other) { wall += other.wall; user += other.user; return *this; } TimeRecord &operator-=(const TimeRecord &other) { wall -= other.wall; user -= other.user; return *this; } /// Print the current time record to 'os', with a breakdown showing /// contributions to the give 'total' time record. void print(raw_ostream &os, const TimeRecord &total) { if (total.user != total.wall) os << llvm::format(" %8.4f (%5.1f%%)", user, 100.0 * user / total.user); os << llvm::format(" %8.4f (%5.1f%%) ", wall, 100.0 * wall / total.wall); } double wall, user; }; } // namespace /// Utility to print a single line entry in the timer output. static void printTimeEntry(raw_ostream &os, unsigned indent, StringRef name, TimeRecord time, TimeRecord total) { time.print(os, total); os.indent(indent) << name << "\n"; } /// Utility to print the timer heading information. static void printTimeHeader(raw_ostream &os, TimeRecord total) { // Figure out how many spaces to description name. unsigned padding = (80 - kTimingDescription.size()) / 2; os << "===" << std::string(73, '-') << "===\n"; os.indent(padding) << kTimingDescription << '\n'; os << "===" << std::string(73, '-') << "===\n"; // Print the total time followed by the section headers. os << llvm::format(" Total Execution Time: %.4f seconds\n\n", total.wall); if (total.user != total.wall) os << " ----User Time----"; os << " ----Wall Time---- ----Name----\n"; } //===----------------------------------------------------------------------===// // Timer Implementation for DefaultTimingManager //===----------------------------------------------------------------------===// namespace { /// A timer used to sample execution time. /// /// Separately tracks wall time and user time to account for parallel threads of /// execution. Timers are intended to be started and stopped multiple times. /// Each start and stop will add to the timer's wall and user time. class TimerImpl { public: using ChildrenMap = llvm::MapVector<const void *, std::unique_ptr<TimerImpl>>; using AsyncChildrenMap = llvm::DenseMap<uint64_t, ChildrenMap>; TimerImpl(std::string &&name) : threadId(llvm::get_threadid()), name(name) {} /// Start the timer. void start() { startTime = std::chrono::steady_clock::now(); } /// Stop the timer. void stop() { auto newTime = std::chrono::steady_clock::now() - startTime; wallTime += newTime; userTime += newTime; } /// Create a child timer nested within this one. Multiple calls to this /// function with the same unique identifier `id` will return the same child /// timer. /// /// This function can be called from other threads, as long as this timer /// outlives any uses of the child timer on the other thread. TimerImpl *nest(const void *id, function_ref<std::string()> nameBuilder) { auto tid = llvm::get_threadid(); if (tid == threadId) return nestTail(children[id], std::move(nameBuilder)); std::unique_lock<std::mutex> lock(asyncMutex); return nestTail(asyncChildren[tid][id], std::move(nameBuilder)); } /// Tail-called from `nest()`. TimerImpl *nestTail(std::unique_ptr<TimerImpl> &child, function_ref<std::string()> nameBuilder) { if (!child) child = std::make_unique<TimerImpl>(nameBuilder()); return child.get(); } /// Finalize this timer and all its children. /// /// If this timer has async children, which happens if `nest()` was called /// from another thread, this function merges the async childr timers into the /// main list of child timers. /// /// Caution: Call this function only after all nested timers running on other /// threads no longer need their timers! void finalize() { addAsyncUserTime(); mergeAsyncChildren(); } /// Add the user time of all async children to this timer's user time. This is /// necessary since the user time already contains all regular child timers, /// but not the asynchronous ones (by the nesting nature of the timers). std::chrono::nanoseconds addAsyncUserTime() { auto added = std::chrono::nanoseconds(0); for (auto &child : children) added += child.second->addAsyncUserTime(); for (auto &thread : asyncChildren) { for (auto &child : thread.second) { child.second->addAsyncUserTime(); added += child.second->userTime; } } userTime += added; return added; } /// Ensure that this timer and recursively all its children have their async /// children folded into the main map of children. void mergeAsyncChildren() { for (auto &child : children) child.second->mergeAsyncChildren(); mergeChildren(std::move(asyncChildren)); assert(asyncChildren.empty()); } /// Merge multiple child timers into this timer. /// /// Children in `other` are added as children to this timer, or, if this timer /// already contains a child with the corresponding unique identifier, are /// merged into the existing child. void mergeChildren(ChildrenMap &&other) { if (children.empty()) { children = std::move(other); for (auto &child : children) child.second->mergeAsyncChildren(); } else { for (auto &child : other) mergeChild(child.first, std::move(child.second)); other.clear(); } } /// See above. void mergeChildren(AsyncChildrenMap &&other) { for (auto &thread : other) { mergeChildren(std::move(thread.second)); assert(thread.second.empty()); } other.clear(); } /// Merge a child timer into this timer for a given unique identifier. /// /// Moves all child and async child timers of `other` into this timer's child /// for the given unique identifier. void mergeChild(const void *id, std::unique_ptr<TimerImpl> &&other) { auto &into = children[id]; if (!into) { into = std::move(other); into->mergeAsyncChildren(); } else { into->wallTime = std::max(into->wallTime, other->wallTime); into->userTime += other->userTime; into->mergeChildren(std::move(other->children)); into->mergeChildren(std::move(other->asyncChildren)); other.reset(); } } /// Dump a human-readable tree representation of the timer and its children. /// This is useful for debugging the timing mechanisms and structure of the /// timers. void dump(raw_ostream &os, unsigned indent = 0, unsigned markThreadId = 0) { auto time = getTimeRecord(); os << std::string(indent * 2, ' ') << name << " [" << threadId << "]" << llvm::format(" %7.4f / %7.4f", time.user, time.wall); if (threadId != markThreadId && markThreadId != 0) os << " (*)"; os << "\n"; for (auto &child : children) child.second->dump(os, indent + 1, threadId); for (auto &thread : asyncChildren) for (auto &child : thread.second) child.second->dump(os, indent + 1, threadId); } /// Returns the time for this timer in seconds. TimeRecord getTimeRecord() { return TimeRecord( std::chrono::duration_cast<std::chrono::duration<double>>(wallTime) .count(), std::chrono::duration_cast<std::chrono::duration<double>>(userTime) .count()); } /// Print the timing result in list mode. void printAsList(raw_ostream &os, TimeRecord total) { // Flatten the leaf timers in the tree and merge them by name. llvm::StringMap<TimeRecord> mergedTimers; std::function<void(TimerImpl *)> addTimer = [&](TimerImpl *timer) { mergedTimers[timer->name] += timer->getTimeRecord(); for (auto &children : timer->children) addTimer(children.second.get()); }; addTimer(this); // Sort the timing information by wall time. std::vector<std::pair<StringRef, TimeRecord>> timerNameAndTime; for (auto &it : mergedTimers) timerNameAndTime.emplace_back(it.first(), it.second); llvm::array_pod_sort(timerNameAndTime.begin(), timerNameAndTime.end(), [](const std::pair<StringRef, TimeRecord> *lhs, const std::pair<StringRef, TimeRecord> *rhs) { return llvm::array_pod_sort_comparator<double>( &rhs->second.wall, &lhs->second.wall); }); // Print the timing information sequentially. for (auto &timeData : timerNameAndTime) printTimeEntry(os, 0, timeData.first, timeData.second, total); } /// Print the timing result in tree mode. void printAsTree(raw_ostream &os, TimeRecord total, unsigned indent = 0) { unsigned childIndent = indent; if (!hidden) { printTimeEntry(os, indent, name, getTimeRecord(), total); childIndent += 2; } for (auto &child : children) { child.second->printAsTree(os, total, childIndent); } } /// Print the current timing information. void print(raw_ostream &os, DisplayMode displayMode) { // Print the banner. auto total = getTimeRecord(); printTimeHeader(os, total); // Defer to a specialized printer for each display mode. switch (displayMode) { case DisplayMode::List: printAsList(os, total); break; case DisplayMode::Tree: printAsTree(os, total); break; } // Print the top-level time not accounted for by child timers, and the // total. auto rest = total; for (auto &child : children) rest -= child.second->getTimeRecord(); printTimeEntry(os, 0, "Rest", rest, total); printTimeEntry(os, 0, "Total", total, total); os.flush(); } /// The last time instant at which the timer was started. std::chrono::time_point<std::chrono::steady_clock> startTime; /// Accumulated wall time. If multiple threads of execution are merged into /// this timer, the wall time will hold the maximum wall time of each thread /// of execution. std::chrono::nanoseconds wallTime = std::chrono::nanoseconds(0); /// Accumulated user time. If multiple threads of execution are merged into /// this timer, each thread's user time is added here. std::chrono::nanoseconds userTime = std::chrono::nanoseconds(0); /// The thread on which this timer is running. uint64_t threadId; /// A descriptive name for this timer. std::string name; /// Whether to omit this timer from reports and directly show its children. bool hidden = false; /// Child timers on the same thread the timer itself. We keep at most one /// timer per unique identifier. ChildrenMap children; /// Child timers on other threads. We keep at most one timer per unique /// identifier. AsyncChildrenMap asyncChildren; /// Mutex for the async children. std::mutex asyncMutex; }; } // namespace //===----------------------------------------------------------------------===// // DefaultTimingManager //===----------------------------------------------------------------------===// namespace mlir { namespace detail { /// Implementation details of the `DefaultTimingManager`. class DefaultTimingManagerImpl { public: /// Whether we should do our work or not. bool enabled = false; /// The configured display mode. DisplayMode displayMode = DisplayMode::Tree; /// The stream where we should print our output. This will always be non-null. raw_ostream *output = &llvm::errs(); /// The root timer. std::unique_ptr<TimerImpl> rootTimer; }; } // namespace detail } // namespace mlir DefaultTimingManager::DefaultTimingManager() : impl(std::make_unique<DefaultTimingManagerImpl>()) { clear(); // initializes the root timer } DefaultTimingManager::~DefaultTimingManager() { print(); } /// Enable or disable execution time sampling. void DefaultTimingManager::setEnabled(bool enabled) { impl->enabled = enabled; } /// Return whether execution time sampling is enabled. bool DefaultTimingManager::isEnabled() const { return impl->enabled; } /// Change the display mode. void DefaultTimingManager::setDisplayMode(DisplayMode displayMode) { impl->displayMode = displayMode; } /// Return the current display mode; DefaultTimingManager::DisplayMode DefaultTimingManager::getDisplayMode() const { return impl->displayMode; } /// Change the stream where the output will be printed to. void DefaultTimingManager::setOutput(raw_ostream &os) { impl->output = &os; } /// Return the current output stream where the output will be printed to. raw_ostream &DefaultTimingManager::getOutput() const { assert(impl->output); return *impl->output; } /// Print and clear the timing results. void DefaultTimingManager::print() { if (impl->enabled) { impl->rootTimer->finalize(); impl->rootTimer->print(*impl->output, impl->displayMode); } clear(); } /// Clear the timing results. void DefaultTimingManager::clear() { impl->rootTimer = std::make_unique<TimerImpl>("root"); impl->rootTimer->hidden = true; } /// Debug print the timer data structures to an output stream. void DefaultTimingManager::dumpTimers(raw_ostream &os) { impl->rootTimer->dump(os); } /// Debug print the timers as a list. void DefaultTimingManager::dumpAsList(raw_ostream &os) { impl->rootTimer->finalize(); impl->rootTimer->print(os, DisplayMode::List); } /// Debug print the timers as a tree. void DefaultTimingManager::dumpAsTree(raw_ostream &os) { impl->rootTimer->finalize(); impl->rootTimer->print(os, DisplayMode::Tree); } Optional<void *> DefaultTimingManager::rootTimer() { if (impl->enabled) return impl->rootTimer.get(); return llvm::None; } void DefaultTimingManager::startTimer(void *handle) { static_cast<TimerImpl *>(handle)->start(); } void DefaultTimingManager::stopTimer(void *handle) { static_cast<TimerImpl *>(handle)->stop(); } void *DefaultTimingManager::nestTimer(void *handle, const void *id, function_ref<std::string()> nameBuilder) { return static_cast<TimerImpl *>(handle)->nest(id, std::move(nameBuilder)); } void DefaultTimingManager::hideTimer(void *handle) { static_cast<TimerImpl *>(handle)->hidden = true; } //===----------------------------------------------------------------------===// // DefaultTimingManager Command Line Options //===----------------------------------------------------------------------===// namespace { struct DefaultTimingManagerOptions { llvm::cl::opt<bool> timing{"mlir-timing", llvm::cl::desc("Display execution times"), llvm::cl::init(false)}; llvm::cl::opt<DisplayMode> displayMode{ "mlir-timing-display", llvm::cl::desc("Display method for timing data"), llvm::cl::init(DisplayMode::Tree), llvm::cl::values( clEnumValN(DisplayMode::List, "list", "display the results in a list sorted by total time"), clEnumValN(DisplayMode::Tree, "tree", "display the results ina with a nested tree view"))}; }; } // end anonymous namespace static llvm::ManagedStatic<DefaultTimingManagerOptions> options; void mlir::registerDefaultTimingManagerCLOptions() { // Make sure that the options struct has been constructed. *options; } void mlir::applyDefaultTimingManagerCLOptions(DefaultTimingManager &tm) { if (!options.isConstructed()) return; tm.setEnabled(options->timing); tm.setDisplayMode(options->displayMode); }
34.204586
80
0.637156
mkinsner
11b034306b11b95efa9bcd9811c5145ad39314a5
5,049
cpp
C++
3rdparty/stout/tests/lambda_tests.cpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
null
null
null
3rdparty/stout/tests/lambda_tests.cpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
null
null
null
3rdparty/stout/tests/lambda_tests.cpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
null
null
null
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License #include <gtest/gtest.h> #include <stout/lambda.hpp> #include <stout/numify.hpp> struct OnlyMoveable { OnlyMoveable() : i(-1) {} OnlyMoveable(int i) : i(i) {} OnlyMoveable(OnlyMoveable&& that) { *this = std::move(that); } OnlyMoveable(const OnlyMoveable&) = delete; OnlyMoveable& operator=(OnlyMoveable&& that) { i = that.i; j = that.j; that.valid = false; return *this; } OnlyMoveable& operator=(const OnlyMoveable&) = delete; int i; int j = 0; bool valid = true; }; std::vector<std::string> function() { return {"1", "2", "3"}; } TEST(LambdaTest, Map) { std::vector<int> expected = {1, 2, 3}; EXPECT_EQ( expected, lambda::map( [](std::string s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); EXPECT_EQ( expected, lambda::map( [](const std::string& s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); EXPECT_EQ( expected, lambda::map( [](std::string&& s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); std::vector<std::string> concat = {"11", "22", "33"}; EXPECT_EQ( concat, lambda::map( [](std::string&& s) { return s + s; }, function())); std::vector<OnlyMoveable> v; v.emplace_back(1); v.emplace_back(2); std::vector<OnlyMoveable> result = lambda::map( [](OnlyMoveable&& o) { o.j = o.i; return std::move(o); }, std::move(v)); for (const OnlyMoveable& o : result) { EXPECT_EQ(o.i, o.j); } } namespace { template <typename F, typename ...Args> auto callable(F&& f, Args&&... args) -> decltype(std::forward<F>(f)(std::forward<Args>(args)...), void(), std::true_type()); template <typename F> std::false_type callable(F&& f, ...); // Compile-time check that f cannot be called with specified arguments. // This is implemented by defining two callable function overloads and // differentiating on return type. The first overload is selected only // when call expression is valid, and it has return type of std::true_type, // while second overload is selected for everything else. template <typename F, typename ...Args> void EXPECT_CALL_INVALID(F&& f, Args&&... args) { static_assert( !decltype( callable(std::forward<F>(f), std::forward<Args>(args)...))::value, "call expression is expected to be invalid"); } } // namespace { namespace { int returnIntNoParams() { return 8; } void returnVoidStringParam(std::string s) {} void returnVoidStringCRefParam(const std::string& s) {} int returnIntOnlyMovableParam(OnlyMoveable o) { EXPECT_TRUE(o.valid); return 1; } } // namespace { // This is mostly a compile time test of lambda::partial, // verifying that it works for different types of expressions. TEST(PartialTest, Test) { // standalone functions auto p1 = lambda::partial(returnIntNoParams); int p1r1 = p1(); int p1r2 = std::move(p1)(); EXPECT_EQ(p1r1, p1r2); auto p2 = lambda::partial(returnVoidStringParam, ""); p2(); std::move(p2)(); auto p3 = lambda::partial(returnVoidStringParam, lambda::_1); p3(""); std::move(p3)(""); auto p4 = lambda::partial(&returnVoidStringCRefParam, lambda::_1); p4(""); std::move(p4)(""); auto p5 = lambda::partial(&returnIntOnlyMovableParam, lambda::_1); p5(OnlyMoveable()); p5(10); std::move(p5)(OnlyMoveable()); auto p6 = lambda::partial(&returnIntOnlyMovableParam, OnlyMoveable()); EXPECT_CALL_INVALID(p6); std::move(p6)(); // lambdas auto l1 = [](const OnlyMoveable& m) { EXPECT_TRUE(m.valid); }; auto pl1 = lambda::partial(l1, OnlyMoveable()); pl1(); pl1(); std::move(pl1)(); auto pl2 = lambda::partial([](OnlyMoveable&& m) { EXPECT_TRUE(m.valid); }, lambda::_1); pl2(OnlyMoveable()); pl2(OnlyMoveable()); std::move(pl2)(OnlyMoveable()); auto pl3 = lambda::partial([](OnlyMoveable&& m) { EXPECT_TRUE(m.valid); }, OnlyMoveable()); EXPECT_CALL_INVALID(pl3); std::move(pl3)(); // member functions struct Object { int method() { return 0; }; }; auto mp1 = lambda::partial(&Object::method, lambda::_1); mp1(Object()); std::move(mp1)(Object()); auto mp2 = lambda::partial(&Object::method, Object()); mp2(); std::move(mp2)(); }
22.44
76
0.614379
sagar8192
11b10e09b509c9d135985eb83d2c471ada9d4c63
9,218
cpp
C++
modules/gles3/functional/es3fSyncTests.cpp
omegaphora/external_deqp
8460b8642f48b81894c3cc6fc6d423811da60648
[ "Apache-2.0" ]
2
2016-12-27T00:57:00.000Z
2020-07-13T13:02:45.000Z
modules/gles3/functional/es3fSyncTests.cpp
omegaphora/external_deqp
8460b8642f48b81894c3cc6fc6d423811da60648
[ "Apache-2.0" ]
null
null
null
modules/gles3/functional/es3fSyncTests.cpp
omegaphora/external_deqp
8460b8642f48b81894c3cc6fc6d423811da60648
[ "Apache-2.0" ]
4
2016-04-27T21:12:29.000Z
2020-07-13T13:02:48.000Z
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Sync tests. *//*--------------------------------------------------------------------*/ #include "es3fSyncTests.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" #include "gluShaderProgram.hpp" #include "gluCallLogWrapper.hpp" #include "gluRenderContext.hpp" #include "glwEnums.hpp" #include "deRandom.hpp" #include "deStringUtil.hpp" #include "deString.h" #include <vector> using tcu::TestLog; namespace deqp { namespace gles3 { namespace Functional { using namespace glw; // GL types static const int NUM_CASE_ITERATIONS = 5; enum WaitCommand { COMMAND_WAIT_SYNC = 1 << 0, COMMAND_CLIENT_WAIT_SYNC = 1 << 1 }; enum CaseOptions { CASE_FLUSH_BEFORE_WAIT = 1 << 0, CASE_FINISH_BEFORE_WAIT = 1 << 1 }; class FenceSyncCase : public TestCase, private glu::CallLogWrapper { public: FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options); ~FenceSyncCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: FenceSyncCase (const FenceSyncCase& other); FenceSyncCase& operator= (const FenceSyncCase& other); int m_numPrimitives; deUint32 m_waitCommand; deUint32 m_waitFlags; deUint64 m_timeout; deUint32 m_caseOptions; glu::ShaderProgram* m_program; GLsync m_syncObject; int m_iterNdx; de::Random m_rnd; }; FenceSyncCase::FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options) : TestCase (context, name, description) , CallLogWrapper (context.getRenderContext().getFunctions(), context.getTestContext().getLog()) , m_numPrimitives (numPrimitives) , m_waitCommand (waitCommand) , m_waitFlags (waitFlags) , m_timeout (timeout) , m_caseOptions (options) , m_program (DE_NULL) , m_syncObject (DE_NULL) , m_iterNdx (0) , m_rnd (deStringHash(name)) { } FenceSyncCase::~FenceSyncCase (void) { FenceSyncCase::deinit(); } static void generateVertices (std::vector<float>& dst, int numPrimitives, de::Random& rnd) { int numVertices = 3*numPrimitives; dst.resize(numVertices * 4); for (int i = 0; i < numVertices; i++) { dst[i*4 ] = rnd.getFloat(-1.0f, 1.0f); // x dst[i*4 + 1] = rnd.getFloat(-1.0f, 1.0f); // y dst[i*4 + 2] = rnd.getFloat( 0.0f, 1.0f); // z dst[i*4 + 3] = 1.0f; // w } } void FenceSyncCase::init (void) { const char* vertShaderSource = "#version 300 es\n" "layout(location = 0) in mediump vec4 a_position;\n" "\n" "void main (void)\n" "{\n" " gl_Position = a_position;\n" "}\n"; const char* fragShaderSource = "#version 300 es\n" "layout(location = 0) out mediump vec4 o_color;\n" "\n" "void main (void)\n" "{\n" " o_color = vec4(0.25, 0.5, 0.75, 1.0);\n" "}\n"; DE_ASSERT(!m_program); m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(vertShaderSource, fragShaderSource)); if (!m_program->isOk()) { m_testCtx.getLog() << *m_program; TCU_FAIL("Failed to compile shader program"); } m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); // Initialize test result to pass. GLU_CHECK_MSG("Case initialization finished"); } void FenceSyncCase::deinit (void) { if (m_program) { delete m_program; m_program = DE_NULL; } if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; } } FenceSyncCase::IterateResult FenceSyncCase::iterate (void) { TestLog& log = m_testCtx.getLog(); std::vector<float> vertices; bool testOk = true; std::string header = "Case iteration " + de::toString(m_iterNdx+1) + " / " + de::toString(NUM_CASE_ITERATIONS); log << TestLog::Section(header, header); enableLogging(true); DE_ASSERT (m_program); glUseProgram (m_program->getProgram()); glEnable (GL_DEPTH_TEST); glClearColor (0.3f, 0.3f, 0.3f, 1.0f); glClearDepthf (1.0f); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Generate vertices glEnableVertexAttribArray (0); generateVertices (vertices, m_numPrimitives, m_rnd); glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, &vertices[0]); // Draw glDrawArrays(GL_TRIANGLES, 0, (int)vertices.size() / 4); log << TestLog::Message << "// Primitives drawn." << TestLog::EndMessage; // Create sync object m_syncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); GLU_CHECK_MSG ("Sync object created"); log << TestLog::Message << "// Sync object created." << TestLog::EndMessage; if (m_caseOptions & CASE_FLUSH_BEFORE_WAIT) glFlush(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT) glFinish(); // Wait for sync object GLenum waitValue = 0; if (m_waitCommand & COMMAND_WAIT_SYNC) { DE_ASSERT(m_timeout == GL_TIMEOUT_IGNORED); DE_ASSERT(m_waitFlags == 0); glWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glWaitSync called"); log << TestLog::Message << "// Wait command glWaitSync called with GL_TIMEOUT_IGNORED." << TestLog::EndMessage; } if (m_waitCommand & COMMAND_CLIENT_WAIT_SYNC) { waitValue = glClientWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glClientWaitSync called"); log << TestLog::Message << "// glClientWaitSync return value:" << TestLog::EndMessage; switch (waitValue) { case GL_ALREADY_SIGNALED: log << TestLog::Message << "// GL_ALREADY_SIGNALED" << TestLog::EndMessage; break; case GL_TIMEOUT_EXPIRED: log << TestLog::Message << "// GL_TIMEOUT_EXPIRED" << TestLog::EndMessage; break; case GL_CONDITION_SATISFIED: log << TestLog::Message << "// GL_CONDITION_SATISFIED" << TestLog::EndMessage; break; case GL_WAIT_FAILED: log << TestLog::Message << "// GL_WAIT_FAILED" << TestLog::EndMessage; testOk = false; break; default: log << TestLog::EndSection; TCU_FAIL("// Illegal return value!"); } } glFinish(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT && waitValue != GL_ALREADY_SIGNALED) { testOk = false; log << TestLog::Message << "// Expected glClientWaitSync to return GL_ALREADY_SIGNALED." << TestLog::EndMessage; } // Delete sync object if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; GLU_CHECK_MSG ("Sync object deleted"); log << TestLog::Message << "// Sync object deleted." << TestLog::EndMessage; } // Evaluate test result log << TestLog::Message << "// Test result: " << (testOk ? "Passed!" : "Failed!") << TestLog::EndMessage; if (!testOk) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); log << TestLog::EndSection; return STOP; } log << TestLog::Message << "// Sync objects created and deleted successfully." << TestLog::EndMessage << TestLog::EndSection; return (++m_iterNdx < NUM_CASE_ITERATIONS) ? CONTINUE : STOP; } SyncTests::SyncTests (Context& context) : TestCaseGroup(context, "fence_sync", "Fence Sync Tests") { } SyncTests::~SyncTests (void) { } void SyncTests::init (void) { // Fence sync tests. addChild(new FenceSyncCase(m_context, "wait_sync_smalldraw", "", 10, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "wait_sync_largedraw", "", 100000, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_largedraw", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_largedraw", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_auto", "", 100000, COMMAND_CLIENT_WAIT_SYNC, GL_SYNC_FLUSH_COMMANDS_BIT, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_manual", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FLUSH_BEFORE_WAIT)); addChild(new FenceSyncCase(m_context, "client_wait_sync_noflush", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_finish", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FINISH_BEFORE_WAIT)); } } // Functional } // gles3 } // deqp
30.523179
187
0.694294
omegaphora
11b14132983c8cefd81d2cca5b6ea937f71906f8
10,570
cpp
C++
sleuthkit-develop/framework/modules/c_TskHashLookupModule/TskHashLookupModule.cpp
ForensicTools/Hotaru-475_2141-Edwards
ac67b05a34e9dd1ed2d0654876372046248abc88
[ "MIT" ]
1
2019-03-28T07:31:25.000Z
2019-03-28T07:31:25.000Z
sleuthkit-develop/framework/modules/c_TskHashLookupModule/TskHashLookupModule.cpp
ForensicTools/Hotaru-475_2141-Edwards
ac67b05a34e9dd1ed2d0654876372046248abc88
[ "MIT" ]
null
null
null
sleuthkit-develop/framework/modules/c_TskHashLookupModule/TskHashLookupModule.cpp
ForensicTools/Hotaru-475_2141-Edwards
ac67b05a34e9dd1ed2d0654876372046248abc88
[ "MIT" ]
null
null
null
/* * The Sleuth Kit * * Contact: Brian Carrier [carrier <at> sleuthkit [dot] org] * Copyright (c) 2011-2012 Basis Technology Corporation. All Rights * reserved. * * This software is distributed under the Common Public License 1.0 */ /** \file TskHashLookupModule.cpp * Contains an implementation of a hash look up file analysis module that uses one or more * TSK hash database indexes to check a given file's MD5 hash against known bad file and * known file hash sets. Hash set hits are posted to the blackboard and the module can be * configured to issue a pipeline stop request if there is a hit. */ // System includes #include <string> #include <vector> #include <sstream> // Framework includes #include "tsk/framework/utilities/TskModuleDev.h" // Poco includes #include "Poco/StringTokenizer.h" namespace { const char *MODULE_NAME = "TskHashLookup"; const char *MODULE_DESCRIPTION = "Looks up a file's MD5 hash value in one or more hash databases that have been indexed using the Sleuth Kit's hfind tool"; const char *MODULE_VERSION = "1.0.0"; static bool issueStopRequestsOnHits = false; static TSK_HDB_INFO* knownHashDBInfo = NULL; static std::vector<TSK_HDB_INFO*> knownBadHashDBInfos; } /** * Helper function to open the index file for a TSK-indexed hash database. * * @param hashDatabasePath The path to a TSK-indexed hash database file. * @param option The option argument associated with the file, * for logging purposes. * @return A TSK_HDB_INFO pointer if the index file is * successfully opened, NULL otherwise. */ static TSK_HDB_INFO* openHashDatabaseIndexFile(const std::string& hashDatabasePath, const std::string& option) { // Was the hash database path specified? if (hashDatabasePath.empty()) { std::wstringstream msg; msg << L"TskHashLookupModule::initialize - missing hash database path for " << option.c_str() << L" option."; LOGERROR(msg.str()); return NULL; } // Get a hash database info record for the hash database. std::vector<TSK_TCHAR> hashDbPath(hashDatabasePath.length() + 1); std::copy(hashDatabasePath.begin(), hashDatabasePath.end(), hashDbPath.begin()); hashDbPath[hashDatabasePath.length()] = '\0'; TSK_HDB_INFO* hashDBInfo = tsk_hdb_open(&hashDbPath[0], TSK_HDB_OPEN_IDXONLY); if (!hashDBInfo) { std::wstringstream msg; msg << L"TskHashLookupModule::initialize - failed to hash database info record for '" << hashDatabasePath.c_str() << L"'"; LOGERROR(msg.str()); return NULL; } // Is there an MD5 index? if (!tsk_hdb_has_idx(hashDBInfo, TSK_HDB_HTYPE_MD5_ID)) { std::wstringstream msg; msg << L"TskHashLookupModule::initialize - failed to find MD5 index for '" << hashDatabasePath.c_str() << L"'"; LOGERROR(msg.str()); return NULL; } return hashDBInfo; } extern "C" { /** * Module identification function. * * @return The name of the module. */ TSK_MODULE_EXPORT const char *name() { return MODULE_NAME; } /** * Module identification function. * * @return A description of the module. */ TSK_MODULE_EXPORT const char *description() { return MODULE_DESCRIPTION; } /** * Module identification function. * * @return The version of the module. */ TSK_MODULE_EXPORT const char *version() { return MODULE_VERSION; } /** * Module initialization function. * * @param args A semicolon delimited list of arguments: * -k <path> The path of a TSK-indexed hash database for a known files * hash set. * -b <path> The path of a TSK-indexed hash database for a known bad * files hash set. Multiple known bad hash sets may be * specified. * -s A flag directing the module to issue a pipeline stop * request if a hash set hit occurs. * @return TskModule::OK if initialization succeeded, otherwise TskModule::FAIL. */ TskModule::Status TSK_MODULE_EXPORT initialize(const char* arguments) { std::string args(arguments); // At least one hash database path must be provided. if (args.empty()) { LOGERROR(L"TskHashLookupModule::initialize - passed empty argument string."); return TskModule::FAIL; } // Parse and process the arguments. Poco::StringTokenizer tokenizer(args, ";"); std::vector<std::string> argsVector(tokenizer.begin(), tokenizer.end()); for (std::vector<std::string>::const_iterator it = argsVector.begin(); it < argsVector.end(); ++it) { if ((*it).find("-s") == 0) { issueStopRequestsOnHits = true; } else if ((*it).find("-k") == 0) { // Only one known files hash set may be specified. if (knownHashDBInfo) { LOGERROR(L"TskHashLookupModule::initialize - multiple known hash databases specified, only one is allowed."); return TskModule::FAIL; } knownHashDBInfo = openHashDatabaseIndexFile((*it).substr(3), "-k"); if (!knownHashDBInfo) return TskModule::FAIL; } else if ((*it).find("-b") == 0) { // Any number of known bad files hash sets may be specified. TSK_HDB_INFO* hashDBInfo = openHashDatabaseIndexFile((*it).substr(3), "-b"); if (hashDBInfo) knownBadHashDBInfos.push_back(hashDBInfo); else return TskModule::FAIL; } else { LOGERROR(L"TskHashLookupModule::initialize - unrecognized option in argument string."); return TskModule::FAIL; } } // At least one hash database file path must be provided. if (!knownHashDBInfo && knownBadHashDBInfos.empty()) { LOGERROR(L"TskHashLookupModule::initialize - no hash database paths specified in argument string."); return TskModule::FAIL; } return TskModule::OK; } /** * Module execution function. Receives a pointer to a file the module is to * process. The file is represented by a TskFile interface which is queried * to get the MD5 hash of the file. The hash is then used do a lookup in * the hash database. If the lookup succeeds, a request to terminate * processing of the file is issued. * * @param pFile File for which the hash database lookup is to be performed. * @returns TskModule::FAIL if an error occurs, otherwise TskModule::OK * or TskModule::STOP. TskModule::STOP is returned if the look * up succeeds and the module is configured to request a * pipeline stop when a hash set hit occurs. */ TskModule::Status TSK_MODULE_EXPORT run(TskFile * pFile) { // Received a file to analyze? if (pFile == NULL) { LOGERROR(L"TskHashLookupModule::run passed NULL file pointer."); return TskModule::FAIL; } // Need at least one hash database index file to run. if (!knownHashDBInfo && knownBadHashDBInfos.empty()) { LOGERROR(L"TskHashLookupModule::run - no hash database index files to search."); return TskModule::FAIL; } // Check for hash set hits. TskBlackboard &blackBoard = TskServices::Instance().getBlackboard(); TskImgDB& imageDB = TskServices::Instance().getImgDB(); bool hashSetHit = false; try { std::string md5 = pFile->getHash(TskImgDB::MD5); // Check for known bad files hash set hits. If a hit occurs, mark the file as IMGDB_FILES_KNOWN_BAD // and post the hit to the blackboard. for (std::vector<TSK_HDB_INFO*>::iterator it = knownBadHashDBInfos.begin(); it < knownBadHashDBInfos.end(); ++it) { if (tsk_hdb_lookup_str(*it, md5.c_str(), TSK_HDB_FLAG_QUICK, NULL, NULL)) { if (!hashSetHit) { imageDB.updateKnownStatus(pFile->getId(), TskImgDB::IMGDB_FILES_KNOWN_BAD); hashSetHit = true; } TskBlackboardArtifact artifact = blackBoard.createArtifact(pFile->getId(), TSK_HASHSET_HIT); TskBlackboardAttribute attribute(TSK_SET_NAME, "TskHashLookupModule", "", (*it)->db_name); artifact.addAttribute(attribute); } } // If there were no known bad file hits, check for a known file hash set hit. if a hit occurs, // mark the file as IMGDB_FILES_KNOWN and post the hit to the blackboard. if (knownHashDBInfo && !hashSetHit && tsk_hdb_lookup_str(knownHashDBInfo, md5.c_str(), TSK_HDB_FLAG_QUICK, NULL, NULL)) { imageDB.updateKnownStatus(pFile->getId(), TskImgDB::IMGDB_FILES_KNOWN); hashSetHit = true; TskBlackboardArtifact artifact = blackBoard.createArtifact(pFile->getId(), TSK_HASHSET_HIT); TskBlackboardAttribute attribute(TSK_SET_NAME, "TskHashLookupModule", "", knownHashDBInfo->db_name); artifact.addAttribute(attribute); } } catch (TskException& ex) { std::wstringstream msg; msg << L"TskHashLookupModule::run - error on lookup for file id " << pFile->getId() << L": " << ex.what(); LOGERROR(msg.str()); return TskModule::FAIL; } return hashSetHit && issueStopRequestsOnHits ? TskModule::STOP : TskModule::OK; } /** * Module cleanup function that closes the hash database index files. * * @returns TskModule::OK */ TskModule::Status TSK_MODULE_EXPORT finalize() { if (knownHashDBInfo != NULL) tsk_hdb_close(knownHashDBInfo); // Closes the index file and frees the memory for the TSK_HDB_INFO struct. for (std::vector<TSK_HDB_INFO*>::iterator it = knownBadHashDBInfos.begin(); it < knownBadHashDBInfos.end(); ++it) tsk_hdb_close(*it); // Closes the index file and frees the memory for the TSK_HDB_INFO struct. return TskModule::OK; } }
39.886792
159
0.613718
ForensicTools
11b81cd2f6dc35ce782342449966f5893f99bdb2
1,330
cpp
C++
tests/network_common.cpp
Andrei-Masilevich/barbacoa-server-lib
2eda2fab20c6c1d5a8a78b71952ca61330d04878
[ "MIT" ]
null
null
null
tests/network_common.cpp
Andrei-Masilevich/barbacoa-server-lib
2eda2fab20c6c1d5a8a78b71952ca61330d04878
[ "MIT" ]
null
null
null
tests/network_common.cpp
Andrei-Masilevich/barbacoa-server-lib
2eda2fab20c6c1d5a8a78b71952ca61330d04878
[ "MIT" ]
null
null
null
#include "network_common.h" #include <server_lib/platform_config.h> #if defined(SERVER_LIB_PLATFORM_LINUX) #include <sys/socket.h> #include <netinet/ip.h> #include <sys/types.h> #endif namespace server_lib { namespace tests { uint16_t basic_network_fixture::get_free_port() { int result = 0; #if defined(SERVER_LIB_PLATFORM_LINUX) int max_loop = 5; int socket_fd = -1; while (result < 1024 && --max_loop > 0) { struct sockaddr_in sin; socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd == -1) return -1; sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(socket_fd, (struct sockaddr*)&sin, sizeof(struct sockaddr_in)) == -1) break; socklen_t len = sizeof(sin); if (getsockname(socket_fd, (struct sockaddr*)&sin, &len) == -1) break; result = sin.sin_port; close(socket_fd); socket_fd = -1; } if (socket_fd > 0) close(socket_fd); #endif if (result < 1024) return get_default_port(); return static_cast<uint16_t>(result); } } // namespace tests } // namespace server_lib
27.142857
90
0.566917
Andrei-Masilevich
11b84455382fe2f87c88031e8a87b9b3cd4897ac
549
cpp
C++
etc/cpsco2019-s1/e/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
3
2019-06-25T06:17:38.000Z
2019-07-13T15:18:51.000Z
etc/cpsco2019-s1/e/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
etc/cpsco2019-s1/e/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
#include "template.hpp" int main() { ll(N, Q); vll(A, N); vll(L, R, X, Q); set<ll> S; each(a, A) { if (S.count(a)) { S.erase(a); } else { S.insert(a); } } rep(i, Q) { ll ans = 0; ll c = 0; vi D; for (auto j = S.lower_bound(L[i]); j != S.end() and *j <= R[i]; ++j) { ans ^= *j; D.push_back(*j); ++c; } each(d, D) { S.erase(d); } out(ans); if (c & 1) { if (S.count(X[i])) { S.erase(X[i]); } else { S.insert(X[i]); } } } }
15.685714
74
0.369763
wotsushi
11b9d47dd38ffb40e49306220e5122fc23a174a0
1,016
hpp
C++
src/View/HeatMapView.hpp
dlasalle/matrixinspector
7fc1b0065c2ea2cd01de58a96c2ffa99a9c2659e
[ "MIT" ]
2
2018-02-04T21:10:14.000Z
2018-02-13T15:24:28.000Z
src/View/HeatMapView.hpp
dlasalle/matrixinspector
7fc1b0065c2ea2cd01de58a96c2ffa99a9c2659e
[ "MIT" ]
15
2017-09-05T20:55:04.000Z
2018-12-21T09:12:21.000Z
src/View/HeatMapView.hpp
dlasalle/matrixinspector
7fc1b0065c2ea2cd01de58a96c2ffa99a9c2659e
[ "MIT" ]
null
null
null
/** * @file HeatMapView.hpp * @brief The HeatMapView class. * @author Dominique LaSalle <dominique@solidlake.com> * Copyright 2017 * @version 1 */ #ifndef MATRIXINSPECTOR_VIEW_HEATMAPVIEW_HPP #define MATRIXINSPECTOR_VIEW_HEATMAPVIEW_HPP #include "View.hpp" #include "HeatMap.hpp" namespace MatrixInspector { class HeatMapView : public View { public: HeatMapView( wxFrame * parent); ~HeatMapView(); void draw() override; void refresh() override; private: HeatMap m_heatmap; GLuint m_glTexture; wxPoint m_mousePos; float m_zoom; float m_originX; float m_originY; void onMouseMove( wxMouseEvent& event); void onKey( wxKeyEvent& event); void onWheel( wxMouseEvent& event); void releaseTexture(); // disable copying HeatMapView( HeatMapView const & rhs); HeatMapView& operator=( HeatMapView const & rhs); wxDECLARE_EVENT_TABLE(); }; } #endif
10.924731
54
0.642717
dlasalle
11c00bff40ff159536879b93113910f5696ed572
14,020
cpp
C++
src/third_party/xhp/xhp/fastpath.cpp
burhan/hiphop-php
6e02d7072a02fbaad1856878c2515e35f7e529f0
[ "PHP-3.01", "Zend-2.0" ]
10
2019-01-20T18:09:28.000Z
2021-06-17T01:29:31.000Z
src/third_party/xhp/xhp/fastpath.cpp
burhan/hiphop-php
6e02d7072a02fbaad1856878c2515e35f7e529f0
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
src/third_party/xhp/xhp/fastpath.cpp
burhan/hiphop-php
6e02d7072a02fbaad1856878c2515e35f7e529f0
[ "PHP-3.01", "Zend-2.0" ]
4
2015-01-15T00:04:16.000Z
2020-07-26T09:03:34.000Z
/* Generated by re2c 0.13.5 on Thu May 27 03:14:47 2010 */ #line 1 "fastpath.re" /* +----------------------------------------------------------------------+ | XHP | +----------------------------------------------------------------------+ | Copyright (c) 2009 - 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE.PHP, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "fastpath.hpp" #include <stdio.h> #include <stdlib.h> #include <string.h> bool xhp_fastpath(const char* yy, const size_t len, const xhp_flags_t &flags) { const char* YYMARKER = NULL; char* heredoc_marker = NULL; size_t heredoc_marker_len = NULL; bool result = false; enum { HTML, PHP, HEREDOC, HEREDOC_START, COMMENT_EOL, COMMENT_BLOCK } state = flags.eval ? PHP : HTML; #define YYCURSOR yy #define YYCTYPE char #define YYGETCONDITION() state #define YYFILL(ii) #define YYDEBUG(s, c) printf("%03d: %c [%d]\n", s, c, c) for (;;) { const char* yystart = yy; #line 48 "fastpath.cpp" { YYCTYPE yych; unsigned int yyaccept = 0; switch (YYGETCONDITION()) { case COMMENT_BLOCK: goto yyc_COMMENT_BLOCK; case COMMENT_EOL: goto yyc_COMMENT_EOL; case HEREDOC: goto yyc_HEREDOC; case HEREDOC_START: goto yyc_HEREDOC_START; case HTML: goto yyc_HTML; case PHP: goto yyc_PHP; } /* *********************************** */ yyc_COMMENT_BLOCK: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy6; case '*': goto yy4; default: goto yy2; } yy2: ++YYCURSOR; #line 141 "fastpath.re" { continue; } #line 74 "fastpath.cpp" yy4: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '/': goto yy8; default: goto yy5; } yy5: #line 55 "fastpath.re" { continue; } #line 84 "fastpath.cpp" yy6: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 92 "fastpath.cpp" yy8: ++YYCURSOR; #line 142 "fastpath.re" { state = PHP; continue; } #line 100 "fastpath.cpp" /* *********************************** */ yyc_COMMENT_EOL: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy18; case '\n': goto yy14; case '\r': goto yy16; case '?': goto yy17; default: goto yy12; } yy12: ++YYCURSOR; yy13: #line 55 "fastpath.re" { continue; } #line 117 "fastpath.cpp" yy14: ++YYCURSOR; yy15: #line 132 "fastpath.re" { state = PHP; continue; } #line 126 "fastpath.cpp" yy16: yych = *++YYCURSOR; switch (yych) { case '\n': goto yy22; default: goto yy15; } yy17: yych = *++YYCURSOR; switch (yych) { case '>': goto yy20; default: goto yy13; } yy18: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 146 "fastpath.cpp" yy20: ++YYCURSOR; #line 136 "fastpath.re" { state = HTML; continue; } #line 154 "fastpath.cpp" yy22: ++YYCURSOR; yych = *YYCURSOR; goto yy15; /* *********************************** */ yyc_HEREDOC: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy29; case '\n': case '\r': goto yy27; default: goto yy25; } yy25: ++YYCURSOR; yych = *YYCURSOR; goto yy34; yy26: #line 117 "fastpath.re" { continue; } #line 178 "fastpath.cpp" yy27: ++YYCURSOR; yych = *YYCURSOR; goto yy32; yy28: #line 120 "fastpath.re" { if (strncmp(yy, heredoc_marker, heredoc_marker_len) == 0 && ( yy[heredoc_marker_len] == ';' || yy[heredoc_marker_len] == '\r' || yy[heredoc_marker_len] == '\n') ) { free(heredoc_marker); heredoc_marker = NULL; state = PHP; } continue; } #line 196 "fastpath.cpp" yy29: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 204 "fastpath.cpp" yy31: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy32: switch (yych) { case '\n': case '\r': goto yy31; default: goto yy28; } yy33: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy34: switch (yych) { case 0x00: case '\n': case '\r': goto yy26; default: goto yy33; } /* *********************************** */ yyc_HEREDOC_START: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy41; case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\t': case '\n': case '\v': case '\f': case '\r': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '^': case '`': case '{': case '|': case '}': case '~': goto yy37; default: goto yy39; } yy37: ++YYCURSOR; #line 55 "fastpath.re" { continue; } #line 311 "fastpath.cpp" yy39: ++YYCURSOR; yych = *YYCURSOR; goto yy44; yy40: #line 108 "fastpath.re" { heredoc_marker_len = yy - yystart; heredoc_marker = (char*)malloc(heredoc_marker_len + 1); memcpy(heredoc_marker, yystart, heredoc_marker_len); heredoc_marker[heredoc_marker_len] = 0; state = HEREDOC; continue; } #line 326 "fastpath.cpp" yy41: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 334 "fastpath.cpp" yy43: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy44: switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\t': case '\n': case '\v': case '\f': case '\r': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '^': case '`': case '{': case '|': case '}': case '~': goto yy40; default: goto yy43; } /* *********************************** */ yyc_HTML: YYFILL(7); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy50; case '<': goto yy49; default: goto yy47; } yy47: ++YYCURSOR; yy48: #line 55 "fastpath.re" { continue; } #line 421 "fastpath.cpp" yy49: yych = *++YYCURSOR; switch (yych) { case '%': goto yy52; case '?': goto yy54; default: goto yy48; } yy50: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 436 "fastpath.cpp" yy52: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '=': goto yy64; default: goto yy53; } yy53: #line 67 "fastpath.re" { if (flags.asp_tags) { state = PHP; } continue; } #line 451 "fastpath.cpp" yy54: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '=': goto yy58; case 'P': case 'p': goto yy56; default: goto yy55; } yy55: #line 61 "fastpath.re" { if (flags.short_tags) { state = PHP; } continue; } #line 469 "fastpath.cpp" yy56: yych = *++YYCURSOR; switch (yych) { case 'H': case 'h': goto yy59; default: goto yy57; } yy57: YYCURSOR = YYMARKER; goto yy55; yy58: yych = *++YYCURSOR; goto yy55; yy59: yych = *++YYCURSOR; switch (yych) { case 'P': case 'p': goto yy60; default: goto yy57; } yy60: yych = *++YYCURSOR; switch (yych) { case '\t': case '\n': case ' ': goto yy61; case '\r': goto yy63; default: goto yy57; } yy61: ++YYCURSOR; yy62: #line 57 "fastpath.re" { state = PHP; continue; } #line 507 "fastpath.cpp" yy63: yych = *++YYCURSOR; switch (yych) { case '\n': goto yy61; default: goto yy62; } yy64: ++YYCURSOR; yych = *YYCURSOR; goto yy53; /* *********************************** */ yyc_PHP: YYFILL(8); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy81; case '"': goto yy69; case '#': goto yy70; case '%': goto yy72; case '&': goto yy73; case '\'': goto yy74; case ')': goto yy75; case '/': goto yy76; case ':': goto yy77; case '<': goto yy78; case '?': goto yy79; case 'B': case 'b': goto yy80; default: goto yy67; } yy67: ++YYCURSOR; yy68: #line 55 "fastpath.re" { continue; } #line 543 "fastpath.cpp" yy69: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy68; goto yy84; yy70: ++YYCURSOR; yy71: #line 86 "fastpath.re" { state = COMMENT_EOL; continue; } #line 557 "fastpath.cpp" yy72: yych = *++YYCURSOR; switch (yych) { case '>': goto yy115; default: goto yy68; } yy73: yych = *++YYCURSOR; switch (yych) { case '#': goto yy107; default: goto yy68; } yy74: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy68; goto yy87; yy75: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy113; case '[': goto yy107; default: goto yy68; } yy76: yych = *++YYCURSOR; switch (yych) { case '*': goto yy110; case '/': goto yy112; case '>': goto yy107; default: goto yy68; } yy77: yych = *++YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy107; case ':': goto yy108; default: goto yy68; } yy78: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '/': goto yy94; case '<': goto yy96; default: goto yy68; } yy79: yych = *++YYCURSOR; switch (yych) { case '>': goto yy92; default: goto yy68; } yy80: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '"': goto yy83; case '\'': goto yy86; default: goto yy68; } yy81: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 691 "fastpath.cpp" yy83: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy84: switch (yych) { case 0x00: goto yy85; case '"': goto yy89; case '\\': goto yy91; default: goto yy83; } yy85: YYCURSOR = YYMARKER; switch (yyaccept) { case 0: goto yy68; case 1: goto yy95; } yy86: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy87: switch (yych) { case 0x00: goto yy85; case '\'': goto yy89; case '\\': goto yy88; default: goto yy86; } yy88: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; goto yy86; yy89: ++YYCURSOR; #line 85 "fastpath.re" { continue; } #line 729 "fastpath.cpp" yy91: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; goto yy83; yy92: ++YYCURSOR; #line 74 "fastpath.re" { state = HTML; continue; } #line 742 "fastpath.cpp" yy94: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case 'S': case 's': goto yy100; default: goto yy95; } yy95: #line 103 "fastpath.re" { result = true; break; } #line 757 "fastpath.cpp" yy96: yych = *++YYCURSOR; switch (yych) { case '<': goto yy97; default: goto yy85; } yy97: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; switch (yych) { case '\t': case ' ': case '"': case '\'': goto yy97; default: goto yy99; } yy99: #line 94 "fastpath.re" { state = HEREDOC_START; continue; } #line 781 "fastpath.cpp" yy100: yych = *++YYCURSOR; switch (yych) { case 'C': case 'c': goto yy101; default: goto yy85; } yy101: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy102; default: goto yy85; } yy102: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy103; default: goto yy85; } yy103: yych = *++YYCURSOR; switch (yych) { case 'P': case 'p': goto yy104; default: goto yy85; } yy104: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy105; default: goto yy85; } yy105: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy105; case '>': goto yy92; default: goto yy85; } yy107: yych = *++YYCURSOR; goto yy95; yy108: ++YYCURSOR; #line 98 "fastpath.re" { continue; } #line 836 "fastpath.cpp" yy110: ++YYCURSOR; #line 90 "fastpath.re" { state = COMMENT_BLOCK; continue; } #line 844 "fastpath.cpp" yy112: yych = *++YYCURSOR; goto yy71; yy113: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy113; case '[': goto yy107; default: goto yy85; } yy115: ++YYCURSOR; #line 78 "fastpath.re" { if (flags.asp_tags) { state = PHP; } continue; } #line 869 "fastpath.cpp" } #line 146 "fastpath.re" } if (heredoc_marker) { free(heredoc_marker); } return result; }
15.968109
81
0.555563
burhan
11c856e5b8f6ef982b1e821a187aca4b82ca19d3
3,677
cpp
C++
Plugins/Mipf_Plugin_ASM/GenerateTrainingSetView.cpp
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
4
2017-04-13T06:01:49.000Z
2019-12-04T07:23:53.000Z
Plugins/Mipf_Plugin_ASM/GenerateTrainingSetView.cpp
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
1
2017-10-27T02:00:44.000Z
2017-10-27T02:00:44.000Z
Plugins/Mipf_Plugin_ASM/GenerateTrainingSetView.cpp
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
2
2017-09-06T01:59:07.000Z
2019-12-04T07:23:54.000Z
#include "GenerateTrainingSetView.h" //qt #include <QFileDialog> //qf #include "iqf_main.h" //mipf #include "MitkMain/IQF_MitkIO.h" #include "MitkMain/IQF_MitkDataManager.h" #include "ITKImageTypeDef.h" //itk #include <itkImage.h> #include <itkChangeInformationImageFilter.h> //mitk #include "mitkImage.h" #include "mitkImageCast.h" #include "mitkDataNode.h" #include "mitkRenderingManager.h" #include "ITK_Helpers.h" GenerateTrainingSetView::GenerateTrainingSetView(QF::IQF_Main* pMain, QWidget* parent) :QWidget(parent), m_pMain(pMain) { m_ui.setupUi(this); m_ui.ImageList->setHeaderLabels(QStringList() << "Name" << "Path"); connect(m_ui.DataDirBrowseBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::DataDirBrowseFile); connect(m_ui.OutputDirBrowseBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::OutputDirBrowseFile); connect(m_ui.ApplyBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::Apply); } GenerateTrainingSetView::~GenerateTrainingSetView() { } void GenerateTrainingSetView::DataDirBrowseFile() { QString dirStr = QFileDialog::getExistingDirectory(this, "Select An Directory."); if (dirStr.isEmpty()) { return; } m_ui.DataDirLE->setText(dirStr); QDir dir(dirStr); QFileInfoList files = dir.entryInfoList(QDir::Files, QDir::Name); m_ui.ImageList->clear(); QList<QTreeWidgetItem*> items; foreach(QFileInfo fileInfo, files) { QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << fileInfo.fileName() << fileInfo.filePath()); items.append(item); } m_ui.ImageList->addTopLevelItems(items); } void GenerateTrainingSetView::OutputDirBrowseFile() { QString dirStr = QFileDialog::getExistingDirectory(this, "Select An Directory."); if (dirStr.isEmpty()) { return; } m_ui.OutputDirLE->setText(dirStr); } template <class TImageType> void CreateBaseImage(TImageType* input, TImageType*output) { } void GenerateTrainingSetView::Apply() { IQF_MitkDataManager* pDataManager = (IQF_MitkDataManager*)m_pMain->GetInterfacePtr(QF_MitkMain_DataManager); IQF_MitkIO* pIO = (IQF_MitkIO*)m_pMain->GetInterfacePtr(QF_MitkMain_IO); for (int i=0;i<m_ui.ImageList->topLevelItemCount();i++) { QString resultName = QString("TrainData%1").arg(i); mitk::DataNode* node = pIO->Load(m_ui.ImageList->topLevelItem(i)->text(1).toStdString().c_str()); if (!node) { return; } mitk::Image* mitkImage = dynamic_cast<mitk::Image*>(node->GetData()); UChar3DImageType::Pointer itkImage; mitk::CastToItkImage(mitkImage, itkImage); UChar3DImageType::Pointer output = UChar3DImageType::New(); int size[3] = { 256,128,256 }; double spacing[3] = {2,4,2}; ITKHelpers::ExtractCentroidImageWithGivenSize(itkImage.GetPointer(), output.GetPointer(), size, spacing); typedef itk::ChangeInformationImageFilter< UChar3DImageType > CenterFilterType; CenterFilterType::Pointer center = CenterFilterType::New(); center->CenterImageOn(); center->SetInput(output); center->Update(); mitk::Image::Pointer image; mitk::CastToMitkImage(center->GetOutput(), image); mitk::DataNode::Pointer on = mitk::DataNode::New(); on->SetData(image); on->SetName(resultName.toStdString().c_str()); pDataManager->GetDataStorage()->Add(on); pDataManager->GetDataStorage()->Remove(node); ITKHelpers::SaveImage(center->GetOutput(), m_ui.OutputDirLE->text().append("/%1.mha").arg(resultName).toStdString()); } }
30.139344
125
0.689693
linson7017
11c990bba3548437b8697512c79b1e1ee915992f
310
cpp
C++
imposc-service/imposc-cpp/charts/src/charts.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
null
null
null
imposc-service/imposc-cpp/charts/src/charts.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
1
2021-03-22T17:27:17.000Z
2021-07-02T07:31:39.000Z
imposc-service/imposc-cpp/charts/src/charts.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
null
null
null
#include "charts.hpp" #include "forcing_phase.hpp" #include "gnuplot_if.hpp" using namespace dynamics; namespace charts { void plot_impacts(const std::vector<Impact> &impacts, const std::string &outfile, const Parameters &params) { do_plot( {prepare_plot(impacts, "", "dots")}, outfile, params); } }
20.666667
108
0.722581
FelixDux
11c9f91d07c85dee71b7c0636643cac4ca80b346
14,275
cpp
C++
src/kits/midi2/MidiRosterLooper.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
3
2018-05-21T15:32:32.000Z
2019-03-21T13:34:55.000Z
src/kits/midi2/MidiRosterLooper.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/kits/midi2/MidiRosterLooper.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
/* * Copyright 2006, Haiku. * * Copyright (c) 2002-2004 Matthijs Hollemans * Distributed under the terms of the MIT License. * * Authors: * Matthijs Hollemans */ #include <kits/debug/Debug.h> #include <MidiConsumer.h> #include <MidiProducer.h> #include <MidiRoster.h> #include <MidiRosterLooper.h> #include <protocol.h> using namespace BPrivate; BMidiRosterLooper::BMidiRosterLooper() : BLooper("MidiRosterLooper") { fInitLock = -1; fRoster = NULL; fWatcher = NULL; } BMidiRosterLooper::~BMidiRosterLooper() { StopWatching(); if (fInitLock >= B_OK) { delete_sem(fInitLock); } // At this point, our list may still contain endpoints with a // zero reference count. These objects are proxies for remote // endpoints, so we can safely delete them. If the list also // contains endpoints with a non-zero refcount (which can be // either remote or local), we will output a warning message. // It would have been better to jump into the debugger, but I // did not want to risk breaking any (misbehaving) old apps. for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->fRefCount > 0) { fprintf( stderr, "[midi] WARNING: Endpoint %" B_PRId32 " (%p) has " "not been Release()d properly (refcount = %" B_PRId32 ")\n", endp->ID(), endp, endp->fRefCount); } else { delete endp; } } } bool BMidiRosterLooper::Init(BMidiRoster* roster_) { ASSERT(roster_ != NULL) fRoster = roster_; // We create a semaphore with a zero count. BMidiRoster's // MidiRoster() method will try to acquire this semaphore, // but blocks because the count is 0. When we receive the // "app registered" message in our MessageReceived() hook, // we release the semaphore and MidiRoster() will unblock. fInitLock = create_sem(0, "InitLock"); if (fInitLock < B_OK) { WARN("Could not create semaphore") return false; } thread_id threadId = Run(); if (threadId < B_OK) { WARN("Could not start looper thread") return false; } return true; } BMidiEndpoint* BMidiRosterLooper::NextEndpoint(int32* id) { ASSERT(id != NULL) for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->ID() > *id) { if (endp->IsRemote() && endp->IsRegistered()) { *id = endp->ID(); return endp; } } } return NULL; } BMidiEndpoint* BMidiRosterLooper::FindEndpoint(int32 id) { for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->ID() == id) { return endp; } } return NULL; } void BMidiRosterLooper::AddEndpoint(BMidiEndpoint* endp) { ASSERT(endp != NULL) ASSERT(!fEndpoints.HasItem(endp)) // We store the endpoints sorted by ID, because that // simplifies the implementation of NextEndpoint(). // Although the midi_server assigns IDs in ascending // order, we can't assume that the mNEW messages also // are delivered in this order (mostly they will be). int32 t; for (t = CountEndpoints(); t > 0; --t) { BMidiEndpoint* other = EndpointAt(t - 1); if (endp->ID() > other->ID()) { break; } } fEndpoints.AddItem(endp, t); #ifdef DEBUG DumpEndpoints(); #endif } void BMidiRosterLooper::RemoveEndpoint(BMidiEndpoint* endp) { ASSERT(endp != NULL) ASSERT(fEndpoints.HasItem(endp)) fEndpoints.RemoveItem(endp); if (endp->IsConsumer()) { DisconnectDeadConsumer((BMidiConsumer*) endp); } else { DisconnectDeadProducer((BMidiProducer*) endp); } #ifdef DEBUG DumpEndpoints(); #endif } void BMidiRosterLooper::StartWatching(const BMessenger* watcher_) { ASSERT(watcher_ != NULL) StopWatching(); fWatcher = new BMessenger(*watcher_); AllEndpoints(); AllConnections(); } void BMidiRosterLooper::StopWatching() { delete fWatcher; fWatcher = NULL; } void BMidiRosterLooper::MessageReceived(BMessage* msg) { #ifdef DEBUG printf("IN "); msg->PrintToStream(); #endif switch (msg->what) { case MSG_APP_REGISTERED: OnAppRegistered(msg); break; case MSG_ENDPOINT_CREATED: OnEndpointCreated(msg); break; case MSG_ENDPOINT_DELETED: OnEndpointDeleted(msg); break; case MSG_ENDPOINT_CHANGED: OnEndpointChanged(msg); break; case MSG_ENDPOINTS_CONNECTED: OnConnectedDisconnected(msg); break; case MSG_ENDPOINTS_DISCONNECTED: OnConnectedDisconnected(msg); break; default: super::MessageReceived(msg); break; } } void BMidiRosterLooper::OnAppRegistered(BMessage* msg) { release_sem(fInitLock); } void BMidiRosterLooper::OnEndpointCreated(BMessage* msg) { int32 id; bool isRegistered; BString name; BMessage properties; bool isConsumer; if ((msg->FindInt32("midi:id", &id) == B_OK) && (msg->FindBool("midi:registered", &isRegistered) == B_OK) && (msg->FindString("midi:name", &name) == B_OK) && (msg->FindMessage("midi:properties", &properties) == B_OK) && (msg->FindBool("midi:consumer", &isConsumer) == B_OK)) { if (isConsumer) { int32 port; bigtime_t latency; if ((msg->FindInt32("midi:port", &port) == B_OK) && (msg->FindInt64("midi:latency", &latency) == B_OK)) { BMidiConsumer* cons = new BMidiConsumer(); cons->fName = name; cons->fId = id; cons->fIsRegistered = isRegistered; cons->fPort = port; cons->fLatency = latency; *(cons->fProperties) = properties; AddEndpoint(cons); return; } } else { // producer BMidiProducer* prod = new BMidiProducer(); prod->fName = name; prod->fId = id; prod->fIsRegistered = isRegistered; *(prod->fProperties) = properties; AddEndpoint(prod); return; } } WARN("Could not create proxy for remote endpoint") } void BMidiRosterLooper::OnEndpointDeleted(BMessage* msg) { int32 id; if (msg->FindInt32("midi:id", &id) == B_OK) { BMidiEndpoint* endp = FindEndpoint(id); if (endp != NULL) { RemoveEndpoint(endp); // If the client is watching, and the endpoint is // registered remote, we need to let it know that // the endpoint is now unregistered. if (endp->IsRemote() && endp->IsRegistered()) { if (fWatcher != NULL) { BMessage notify; notify.AddInt32("be:op", B_MIDI_UNREGISTERED); ChangeEvent(&notify, endp); } } // If the proxy object for this endpoint is no // longer being used, we can delete it. However, // if the refcount is not zero, we must defer // destruction until the client Release()'s the // object. We clear the "isRegistered" flag to // let the client know the object is now invalid. if (endp->fRefCount == 0) { delete endp; } else { // still being used endp->fIsRegistered = false; endp->fIsAlive = false; } return; } } WARN("Could not delete proxy for remote endpoint") } void BMidiRosterLooper::OnEndpointChanged(BMessage* msg) { int32 id; if (msg->FindInt32("midi:id", &id) == B_OK) { BMidiEndpoint* endp = FindEndpoint(id); if ((endp != NULL) && endp->IsRemote()) { ChangeRegistered(msg, endp); ChangeName(msg, endp); ChangeProperties(msg, endp); ChangeLatency(msg, endp); #ifdef DEBUG DumpEndpoints(); #endif return; } } WARN("Could not change endpoint attributes") } void BMidiRosterLooper::OnConnectedDisconnected(BMessage* msg) { int32 prodId, consId; if ((msg->FindInt32("midi:producer", &prodId) == B_OK) && (msg->FindInt32("midi:consumer", &consId) == B_OK)) { BMidiEndpoint* endp1 = FindEndpoint(prodId); BMidiEndpoint* endp2 = FindEndpoint(consId); if ((endp1 != NULL) && endp1->IsProducer()) { if ((endp2 != NULL) && endp2->IsConsumer()) { BMidiProducer* prod = (BMidiProducer*) endp1; BMidiConsumer* cons = (BMidiConsumer*) endp2; bool mustConnect = (msg->what == MSG_ENDPOINTS_CONNECTED); if (mustConnect) { prod->ConnectionMade(cons); } else { prod->ConnectionBroken(cons); } if (fWatcher != NULL) { ConnectionEvent(prod, cons, mustConnect); } #ifdef DEBUG DumpEndpoints(); #endif return; } } } WARN("Could not connect/disconnect endpoints") } void BMidiRosterLooper::ChangeRegistered(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) bool isRegistered; if (msg->FindBool("midi:registered", &isRegistered) == B_OK) { if (endp->fIsRegistered != isRegistered) { endp->fIsRegistered = isRegistered; if (fWatcher != NULL) { BMessage notify; if (isRegistered) { notify.AddInt32("be:op", B_MIDI_REGISTERED); } else { notify.AddInt32("be:op", B_MIDI_UNREGISTERED); } ChangeEvent(&notify, endp); } } } } void BMidiRosterLooper::ChangeName(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) BString name; if (msg->FindString("midi:name", &name) == B_OK) { if (endp->fName != name) { endp->fName = name; if ((fWatcher != NULL) && endp->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_NAME); notify.AddString("be:name", name); ChangeEvent(&notify, endp); } } } } void BMidiRosterLooper::ChangeProperties(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) BMessage properties; if (msg->FindMessage("midi:properties", &properties) == B_OK) { *(endp->fProperties) = properties; if ((fWatcher != NULL) && endp->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_PROPERTIES); notify.AddMessage("be:properties", &properties); ChangeEvent(&notify, endp); } } } void BMidiRosterLooper::ChangeLatency(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) bigtime_t latency; if (msg->FindInt64("midi:latency", &latency) == B_OK) { if (endp->IsConsumer()) { BMidiConsumer* cons = (BMidiConsumer*) endp; if (cons->fLatency != latency) { cons->fLatency = latency; if ((fWatcher != NULL) && cons->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_LATENCY); notify.AddInt64("be:latency", latency); ChangeEvent(&notify, endp); } } } } } void BMidiRosterLooper::AllEndpoints() { BMessage notify; for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsRemote() && endp->IsRegistered()) { notify.MakeEmpty(); notify.AddInt32("be:op", B_MIDI_REGISTERED); ChangeEvent(&notify, endp); } } } void BMidiRosterLooper::AllConnections() { for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsRemote() && endp->IsRegistered()) { if (endp->IsProducer()) { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->LockProducer()) { for (int32 k = 0; k < prod->CountConsumers(); ++k) { ConnectionEvent(prod, prod->ConsumerAt(k), true); } prod->UnlockProducer(); } } } } } void BMidiRosterLooper::ChangeEvent(BMessage* msg, BMidiEndpoint* endp) { ASSERT(fWatcher != NULL) ASSERT(msg != NULL) ASSERT(endp != NULL) msg->what = B_MIDI_EVENT; msg->AddInt32("be:id", endp->ID()); if (endp->IsConsumer()) { msg->AddString("be:type", "consumer"); } else { msg->AddString("be:type", "producer"); } fWatcher->SendMessage(msg); } void BMidiRosterLooper::ConnectionEvent( BMidiProducer* prod, BMidiConsumer* cons, bool mustConnect) { ASSERT(fWatcher != NULL) ASSERT(prod != NULL) ASSERT(cons != NULL) BMessage notify; notify.what = B_MIDI_EVENT; notify.AddInt32("be:producer", prod->ID()); notify.AddInt32("be:consumer", cons->ID()); if (mustConnect) { notify.AddInt32("be:op", B_MIDI_CONNECTED); } else { notify.AddInt32("be:op", B_MIDI_DISCONNECTED); } fWatcher->SendMessage(&notify); } void BMidiRosterLooper::DisconnectDeadConsumer(BMidiConsumer* cons) { ASSERT(cons != NULL) // Note: Rather than looping through each producer's list // of connected consumers, we let ConnectionBroken() tell // us whether the consumer really was connected. for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsProducer()) { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->ConnectionBroken(cons)) { if (cons->IsRemote() && (fWatcher != NULL)) { ConnectionEvent(prod, cons, false); } } } } } void BMidiRosterLooper::DisconnectDeadProducer(BMidiProducer* prod) { ASSERT(prod != NULL) // We don't need to lock or remove the consumers from // the producer's list of connections, because when this // function is called, we're destroying the object. if (prod->IsRemote() && (fWatcher != NULL)) { for (int32 t = 0; t < prod->CountConsumers(); ++t) { ConnectionEvent(prod, prod->ConsumerAt(t), false); } } } int32 BMidiRosterLooper::CountEndpoints() { return fEndpoints.CountItems(); } BMidiEndpoint* BMidiRosterLooper::EndpointAt(int32 index) { ASSERT(index >= 0 && index < CountEndpoints()) return (BMidiEndpoint*) fEndpoints.ItemAt(index); } #ifdef DEBUG void BMidiRosterLooper::DumpEndpoints() { if (Lock()) { printf("*** START DumpEndpoints\n"); for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); printf("\tendpoint %" B_PRId32 " (%p):\n", t, endp); printf( "\t\tid %" B_PRId32 ", name '%s', %s, %s, %s, %s, refcount %" B_PRId32 "\n", endp->ID(), endp->Name(), endp->IsConsumer() ? "consumer" : "producer", endp->IsRegistered() ? "registered" : "unregistered", endp->IsLocal() ? "local" : "remote", endp->IsValid() ? "valid" : "invalid", endp->fRefCount); printf("\t\tproperties: "); endp->fProperties->PrintToStream(); if (endp->IsConsumer()) { BMidiConsumer* cons = (BMidiConsumer*) endp; printf("\t\tport %" B_PRId32 ", latency %" B_PRIdBIGTIME "\n", cons->fPort, cons->fLatency); } else { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->LockProducer()) { printf("\t\tconnections:\n"); for (int32 k = 0; k < prod->CountConsumers(); ++k) { BMidiConsumer* cons = prod->ConsumerAt(k); printf("\t\t\tid %" B_PRId32 " (%p)\n", cons->ID(), cons); } prod->UnlockProducer(); } } } printf("*** END DumpEndpoints\n"); Unlock(); } } #endif
22.987118
76
0.654431
stasinek
11cbc1057bb0c26b128eb83d40b4b92d0f4b68cb
598
cpp
C++
source/code/programs/examples/sfml/f310_gamepads.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/programs/examples/sfml/f310_gamepads.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/programs/examples/sfml/f310_gamepads.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include <string> #include <iostream> #include <SFML/Window/Joystick.hpp> #include "code/utilities/peripheral/keyboard/F310_gamepad/functions/f310_gamepads_state_getter.hpp" #include "code/utilities/formats/json/converters/lib.hpp" #include "code/utilities/formats/json/converters/type_to_json_string.hpp", int main() { // i bought two Logitech Gamepad F310 controllers //this dumps their state in json while (true){ auto controllers = F310_Gamepads_State_Getter::Get(); std::cout << Type_To_Json_String::As_JSON_String(controllers) << std::endl; } return 0; }
33.222222
99
0.742475
luxe
11cd6fce1f1f0eeca2ec14e83242e44739043a7e
5,574
cpp
C++
src/ace/ACE_wrappers/ACEXML/examples/SAXPrint/SAXPrint_Handler.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/ACEXML/examples/SAXPrint/SAXPrint_Handler.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/ACEXML/examples/SAXPrint/SAXPrint_Handler.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
// -*- C++ -*- #include "SAXPrint_Handler.h" #include "ace/ACE.h" #include "ace/Log_Msg.h" #if !defined (__ACEXML_INLINE__) # include "SAXPrint_Handler.inl" #endif /* __ACEXML_INLINE__ */ ACEXML_SAXPrint_Handler::ACEXML_SAXPrint_Handler (const ACEXML_Char* filename) : indent_ (0), fileName_(ACE::strnew (filename)), locator_ (0) { // no-op } ACEXML_SAXPrint_Handler::~ACEXML_SAXPrint_Handler (void) { delete [] this->fileName_; } void ACEXML_SAXPrint_Handler::characters (const ACEXML_Char *cdata, size_t, size_t) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), cdata)); } void ACEXML_SAXPrint_Handler::endDocument (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); } void ACEXML_SAXPrint_Handler::endElement (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *qName) { this->dec_indent (); this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("</%s>"), qName)); } void ACEXML_SAXPrint_Handler::endPrefixMapping (const ACEXML_Char *) { // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event endPrefixMapping (%s) ***************\n"), // prefix)); } void ACEXML_SAXPrint_Handler::ignorableWhitespace (const ACEXML_Char * cdata, int, int) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), cdata)); // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event ignorableWhitespace () ***************\n"))); } void ACEXML_SAXPrint_Handler::processingInstruction (const ACEXML_Char *target, const ACEXML_Char *data) { this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("<?%s %s>\n"), target, data)); } void ACEXML_SAXPrint_Handler::setDocumentLocator (ACEXML_Locator * locator) { this->locator_ = locator; //ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event setDocumentLocator () ***************\n"))); } void ACEXML_SAXPrint_Handler::skippedEntity (const ACEXML_Char *name) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event skippedEntity (%s) ***************\n"), name)); } void ACEXML_SAXPrint_Handler::startDocument (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event startDocument () ***************\n"))); } void ACEXML_SAXPrint_Handler::startElement (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *qName, ACEXML_Attributes *alist) { this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("<%s"), qName)); if (alist != 0) for (size_t i = 0; i < alist->getLength (); ++i) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %s = \"%s\""), alist->getQName (i), alist->getValue (i))); } ACE_DEBUG ((LM_DEBUG, ACE_TEXT (">"))); this->inc_indent (); } void ACEXML_SAXPrint_Handler::startPrefixMapping (const ACEXML_Char * , const ACEXML_Char *) { // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event startPrefixMapping () ***************\n"))); // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("Prefix = %s, URI = %s\n"), prefix, uri)); } // *** Methods inherited from ACEXML_DTDHandler. void ACEXML_SAXPrint_Handler::notationDecl (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *) { // No-op. } void ACEXML_SAXPrint_Handler::unparsedEntityDecl (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *) { // No-op. } // Methods inherited from ACEXML_EnitityResolver. ACEXML_InputSource * ACEXML_SAXPrint_Handler::resolveEntity (const ACEXML_Char *, const ACEXML_Char *) { // No-op. return 0; } // Methods inherited from ACEXML_ErrorHandler. /* * Receive notification of a recoverable error. */ void ACEXML_SAXPrint_Handler::error (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::fatalError (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::warning (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::print_indent (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); for (size_t i = 0; i < this->indent_; ++i) ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" "))); }
25.568807
101
0.544492
wfnex
11cdb8d22ff907a9adfd4cb8c16720795a585bfb
2,463
cpp
C++
src/libs/wavm_common/WavmUtils.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/libs/wavm_common/WavmUtils.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/libs/wavm_common/WavmUtils.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: WavmUtils.cpp * Author: ubuntu * * Created on April 22, 2018, 5:42 PM */ #include <string> #include <iostream> #include "keto/common/Log.hpp" #include "keto/wavm_common/WavmUtils.hpp" namespace keto { namespace wavm_common { std::string WavmUtils::readCString(Runtime::MemoryInstance* memory,I32 stringAddress) { // Validate the path name and make a local copy of it. std::string returnString; int index = 0; while(true) { int c = Runtime::memoryRef<char>(memory,stringAddress + index); if(c == 0) { break; } else { returnString += c; } index ++; }; return returnString; } std::string WavmUtils::readTypeScriptString(Runtime::MemoryInstance* memory,I32 stringAddress) { // Validate the path name and make a local copy of it. std::string returnString; int size = Runtime::memoryRef<char>(memory,stringAddress); size += Runtime::memoryRef<char>(memory,stringAddress+1) * 100; size += Runtime::memoryRef<char>(memory,stringAddress+2) * 10000; for (int index = 0; index < (size * 2); index++) { if ((int)Runtime::memoryRef<char>(memory,stringAddress + 4 + index) != 0) { returnString += (int)Runtime::memoryRef<char>(memory,stringAddress + 4 + index); } } return returnString; } std::vector<char> WavmUtils::buildTypeScriptString(const std::string& value) { int currentValue = value.length(); std::vector<char> result; for (int count = 0 ; count < 4; count++) { int mod = currentValue % 100; result.push_back((char)mod); currentValue = currentValue / 100; } for (const char character : value) { result.push_back(character); result.push_back(0); } return result; } void WavmUtils::log(uint32_t intLevel,const std::string& msg) { switch(intLevel) { case 1 : KETO_LOG_DEBUG << msg; break; case 2 : KETO_LOG_INFO << msg; break; case 3 : KETO_LOG_WARNING << msg; break; case 4 : KETO_LOG_ERROR << msg; break; case 5 : KETO_LOG_FATAL << msg; break; }; } } }
26.202128
96
0.598051
burntjam
11d338cac985ed167a065d6e891f82926344834b
2,591
cpp
C++
src/Explosion/Box.cpp
crazytuzi/CyclonePhysics
4dd47779d425d9de45a125e948b690f0e8bd1f12
[ "MIT" ]
null
null
null
src/Explosion/Box.cpp
crazytuzi/CyclonePhysics
4dd47779d425d9de45a125e948b690f0e8bd1f12
[ "MIT" ]
null
null
null
src/Explosion/Box.cpp
crazytuzi/CyclonePhysics
4dd47779d425d9de45a125e948b690f0e8bd1f12
[ "MIT" ]
null
null
null
#include "Box.h" #include "gl/glut.h" Box::Box(): bIsOverlapping(false) { body = new cyclone::RigidBody(); } Box::~Box() { delete body; } void Box::Render() const { // Get the OpenGL transformation GLfloat mat[16]; body->GetGLTransform(mat); if (bIsOverlapping) { glColor3f(0.7f, 1.f, 0.7f); } else if (body->GetAwake()) { glColor3f(1.f, 0.7f, 0.7f); } else { glColor3f(0.7f, 0.7f, 1.f); } glPushMatrix(); glMultMatrixf(mat); glScalef(halfSize.x * 2, halfSize.y * 2, halfSize.z * 2); glutSolidCube(1.f); glPopMatrix(); } void Box::RenderShadow() const { // Get the OpenGL transformation GLfloat matrix[16]; body->GetGLTransform(matrix); glPushMatrix(); glScalef(1.f, 0.f, 1.f); glMultMatrixf(matrix); glScalef(halfSize.x * 2, halfSize.y * 2, halfSize.z * 2); glutSolidCube(1.f); glPopMatrix(); } void Box::SetState(const cyclone::Vector3& position, const cyclone::Quaternion& orientation, const cyclone::Vector3& extents, const cyclone::Vector3& velocity) { body->SetPosition(position); body->SetOrientation(orientation); body->SetVelocity(velocity); body->SetRotation(cyclone::Vector3()); halfSize = extents; const auto mass = halfSize.x * halfSize.y * halfSize.z * 8.f; body->SetMass(mass); cyclone::Matrix tensor; const auto squares = halfSize * halfSize; tensor.M[0][0] = 0.3f * mass * (squares.y + squares.z); tensor.M[0][1] = tensor.M[1][0] = 0.f; tensor.M[0][2] = tensor.M[2][0] = 0.f; tensor.M[1][1] = 0.3f * mass * (squares.x + squares.z); tensor.M[1][2] = tensor.M[2][1] = 0.f; tensor.M[2][2] = 0.3f * mass * (squares.x + squares.y); tensor.M[3][3] = 1.f; body->SetInertiaTensor(tensor); body->SetLinearDamping(0.95f); body->SetAngularDamping(0.8f); body->ClearAccumulators(); body->SetAcceleration(0.f, -10.f, 0.f); body->SetAwake(); body->CalculateDerivedData(); } void Box::Random(cyclone::Random* random) { if (random != nullptr) { const static cyclone::Vector3 minPosition(-5.f, 5.f, -5.f); const static cyclone::Vector3 maxPosition(5.f, 10.0, 5.f); const static cyclone::Vector3 minSize(0.5f, 0.5f, 0.5f); const static cyclone::Vector3 maxSize(4.5f, 1.5f, 1.5f); SetState(random->RandomVector(minPosition, maxPosition), random->RandomQuaternion(), random->RandomVector(minSize, maxSize), cyclone::Vector3()); } }
19.778626
92
0.599768
crazytuzi
11d37558fedac33083d61bec201f0ac6c03b20bb
1,189
cpp
C++
tests/Test_ValueWithError_Policy_make_value_cpp98.cpp
t-b/value-with-error
ede8325d3572ac53601d0d7aabc09518850c8455
[ "BSL-1.0" ]
2
2018-09-07T10:58:50.000Z
2021-09-16T01:09:50.000Z
tests/Test_ValueWithError_Policy_make_value_cpp98.cpp
t-b/value-with-error
ede8325d3572ac53601d0d7aabc09518850c8455
[ "BSL-1.0" ]
null
null
null
tests/Test_ValueWithError_Policy_make_value_cpp98.cpp
t-b/value-with-error
ede8325d3572ac53601d0d7aabc09518850c8455
[ "BSL-1.0" ]
null
null
null
#include "precompiled.hpp" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif // __clang__ #if defined __GNUC__ \ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \ && !defined __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #include <boost/test/unit_test.hpp> namespace error_propagation { class PolicyMock; } #define DEFAULT_POLICY_CLASS error_propagation::PolicyMock #include "ValueWithError.hpp" #include "PolicyMock.hpp" using namespace error_propagation; namespace { typedef ValueWithError<double,PolicyMock> VD; typedef ValueWithError<float,PolicyMock> VF; } // anonymous namespace BOOST_AUTO_TEST_SUITE(Test_ValueWithError_Policy) BOOST_AUTO_TEST_CASE(make_val) { VD a; a = make_value(1.0, 1.0); BOOST_CHECK(true); } BOOST_AUTO_TEST_SUITE_END() // Test_ValueWithError_Policy #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #if defined __GNUC__ \ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \ && !defined __clang__ #pragma GCC diagnostic pop #endif
22.865385
75
0.728343
t-b
11d4eec341bbb7075bece8c5ac3e4a2a5e54b0cb
659
hpp
C++
credits.hpp
jasonhutchens/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
4
2016-06-05T04:36:12.000Z
2016-08-21T20:11:49.000Z
credits.hpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
credits.hpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
//============================================================================== #ifndef ArseAbout #define ArseAbout #pragma once #include <context.hpp> //------------------------------------------------------------------------------ class Credits : public Context { public: Credits(); virtual ~Credits(); private: Credits( const Credits & ); Credits & operator=( const Credits & ); public: virtual void init(); virtual void fini(); virtual bool update( float dt ); virtual void render(); private: bool m_interact; }; #endif //==============================================================================
19.382353
80
0.402124
jasonhutchens
11d66497c73877e8fdacf4e7fb1b5382ef71af15
1,799
cpp
C++
C++/word-squares.cpp
bssrdf/LeetCode-5
746df5cff523361145a74d9d429dc541a7b99910
[ "MIT" ]
68
2018-01-13T07:15:37.000Z
2022-02-20T12:58:24.000Z
C++/word-squares.cpp
pnandini/LeetCode
e746c3298be96dec8e160da9378940568ef631b1
[ "MIT" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
C++/word-squares.cpp
pnandini/LeetCode
e746c3298be96dec8e160da9378940568ef631b1
[ "MIT" ]
63
2017-04-10T03:38:25.000Z
2022-03-17T23:24:51.000Z
// Time: O(n^2 * n!) // Space: O(n^2) class Solution { private: struct TrieNode { vector<int> indices; vector<TrieNode *> children; TrieNode() : children(26, nullptr) {} }; TrieNode *buildTrie(const vector<string>& words) { TrieNode *root = new TrieNode(); for (int j = 0; j < words.size(); ++j) { TrieNode* t = root; for (int i = 0; i < words[j].size(); ++i) { if (!t->children[words[j][i] - 'a']) { t->children[words[j][i] - 'a'] = new TrieNode(); } t = t->children[words[j][i] - 'a']; t->indices.push_back(j); } } return root; } public: vector<vector<string>> wordSquares(vector<string>& words) { vector<vector<string>> result; TrieNode *trie = buildTrie(words); vector<string> curr; for (const auto& s : words) { curr.emplace_back(s); wordSquaresHelper(words, trie, &curr, &result); curr.pop_back(); } return result; } private: void wordSquaresHelper(const vector<string>& words, TrieNode *trie, vector<string> *curr, vector<vector<string>> *result) { if (curr->size() >= words[0].length()) { return result->emplace_back(*curr); } TrieNode *node = trie; for (int i = 0; i < curr->size(); ++i) { if (!(node = node->children[(*curr)[i][curr->size()] - 'a'])) { return; } } for (const auto& i : node->indices) { curr->emplace_back(words[i]); wordSquaresHelper(words, trie, curr, result); curr->pop_back(); } } };
28.555556
93
0.473041
bssrdf
11d69bab9a3ef2f564faeda51e39c700146d5b6f
10,711
cpp
C++
sky/engine/platform/text/SegmentedString.cpp
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
1
2021-08-13T08:19:40.000Z
2021-08-13T08:19:40.000Z
sky/engine/platform/text/SegmentedString.cpp
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
null
null
null
sky/engine/platform/text/SegmentedString.cpp
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "flutter/sky/engine/platform/text/SegmentedString.h" namespace blink { unsigned SegmentedString::length() const { unsigned length = m_currentString.m_length; if (m_pushedChar1) { ++length; if (m_pushedChar2) ++length; } if (isComposite()) { Deque<SegmentedSubstring>::const_iterator it = m_substrings.begin(); Deque<SegmentedSubstring>::const_iterator e = m_substrings.end(); for (; it != e; ++it) length += it->m_length; } return length; } void SegmentedString::setExcludeLineNumbers() { m_currentString.setExcludeLineNumbers(); if (isComposite()) { Deque<SegmentedSubstring>::iterator it = m_substrings.begin(); Deque<SegmentedSubstring>::iterator e = m_substrings.end(); for (; it != e; ++it) it->setExcludeLineNumbers(); } } void SegmentedString::clear() { m_pushedChar1 = 0; m_pushedChar2 = 0; m_currentChar = 0; m_currentString.clear(); m_numberOfCharactersConsumedPriorToCurrentString = 0; m_numberOfCharactersConsumedPriorToCurrentLine = 0; m_currentLine = 0; m_substrings.clear(); m_closed = false; m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } void SegmentedString::append(const SegmentedSubstring& s) { ASSERT(!m_closed); if (!s.m_length) return; if (!m_currentString.m_length) { m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed(); m_currentString = s; updateAdvanceFunctionPointers(); } else { m_substrings.append(s); } m_empty = false; } void SegmentedString::prepend(const SegmentedSubstring& s) { ASSERT(!escaped()); ASSERT(!s.numberOfCharactersConsumed()); if (!s.m_length) return; // FIXME: We're assuming that the prepend were originally consumed by // this SegmentedString. We're also ASSERTing that s is a fresh // SegmentedSubstring. These assumptions are sufficient for our // current use, but we might need to handle the more elaborate // cases in the future. m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed(); m_numberOfCharactersConsumedPriorToCurrentString -= s.m_length; if (!m_currentString.m_length) { m_currentString = s; updateAdvanceFunctionPointers(); } else { // Shift our m_currentString into our list. m_substrings.prepend(m_currentString); m_currentString = s; updateAdvanceFunctionPointers(); } m_empty = false; } void SegmentedString::close() { // Closing a stream twice is likely a coding mistake. ASSERT(!m_closed); m_closed = true; } void SegmentedString::append(const SegmentedString& s) { ASSERT(!m_closed); if (s.m_pushedChar1) { Vector<UChar, 2> unconsumedData; unconsumedData.append(s.m_pushedChar1); if (s.m_pushedChar2) unconsumedData.append(s.m_pushedChar2); append(SegmentedSubstring(String(unconsumedData))); } append(s.m_currentString); if (s.isComposite()) { Deque<SegmentedSubstring>::const_iterator it = s.m_substrings.begin(); Deque<SegmentedSubstring>::const_iterator e = s.m_substrings.end(); for (; it != e; ++it) append(*it); } m_currentChar = m_pushedChar1 ? m_pushedChar1 : (m_currentString.m_length ? m_currentString.getCurrentChar() : 0); } void SegmentedString::prepend(const SegmentedString& s) { ASSERT(!escaped()); ASSERT(!s.escaped()); if (s.isComposite()) { Deque<SegmentedSubstring>::const_reverse_iterator it = s.m_substrings.rbegin(); Deque<SegmentedSubstring>::const_reverse_iterator e = s.m_substrings.rend(); for (; it != e; ++it) prepend(*it); } prepend(s.m_currentString); m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0; } void SegmentedString::advanceSubstring() { if (isComposite()) { m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed(); m_currentString = m_substrings.takeFirst(); // If we've previously consumed some characters of the non-current // string, we now account for those characters as part of the current // string, not as part of "prior to current string." m_numberOfCharactersConsumedPriorToCurrentString -= m_currentString.numberOfCharactersConsumed(); updateAdvanceFunctionPointers(); } else { m_currentString.clear(); m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } } String SegmentedString::toString() const { StringBuilder result; if (m_pushedChar1) { result.append(m_pushedChar1); if (m_pushedChar2) result.append(m_pushedChar2); } m_currentString.appendTo(result); if (isComposite()) { Deque<SegmentedSubstring>::const_iterator it = m_substrings.begin(); Deque<SegmentedSubstring>::const_iterator e = m_substrings.end(); for (; it != e; ++it) it->appendTo(result); } return result.toString(); } void SegmentedString::advance(unsigned count, UChar* consumedCharacters) { ASSERT_WITH_SECURITY_IMPLICATION(count <= length()); for (unsigned i = 0; i < count; ++i) { consumedCharacters[i] = currentChar(); advance(); } } void SegmentedString::advance8() { ASSERT(!m_pushedChar1); decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar8(); } void SegmentedString::advance16() { ASSERT(!m_pushedChar1); decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar16(); } void SegmentedString::advanceAndUpdateLineNumber8() { ASSERT(!m_pushedChar1); ASSERT(m_currentString.getCurrentChar() == m_currentChar); if (m_currentChar == '\n') { ++m_currentLine; m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1; } decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar8(); } void SegmentedString::advanceAndUpdateLineNumber16() { ASSERT(!m_pushedChar1); ASSERT(m_currentString.getCurrentChar() == m_currentChar); if (m_currentChar == '\n') { ++m_currentLine; m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1; } decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar16(); } void SegmentedString::advanceSlowCase() { if (m_pushedChar1) { m_pushedChar1 = m_pushedChar2; m_pushedChar2 = 0; if (m_pushedChar1) { m_currentChar = m_pushedChar1; return; } updateAdvanceFunctionPointers(); } else if (m_currentString.m_length) { if (!--m_currentString.m_length) advanceSubstring(); } else if (!isComposite()) { m_currentString.clear(); m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0; } void SegmentedString::advanceAndUpdateLineNumberSlowCase() { if (m_pushedChar1) { m_pushedChar1 = m_pushedChar2; m_pushedChar2 = 0; if (m_pushedChar1) { m_currentChar = m_pushedChar1; return; } updateAdvanceFunctionPointers(); } else if (m_currentString.m_length) { if (m_currentString.getCurrentChar() == '\n' && m_currentString.doNotExcludeLineNumbers()) { ++m_currentLine; // Plus 1 because numberOfCharactersConsumed value hasn't incremented yet; it does with m_length decrement below. m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1; } if (!--m_currentString.m_length) advanceSubstring(); else m_currentString.incrementAndGetCurrentChar(); // Only need the ++ } else if (!isComposite()) { m_currentString.clear(); m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0; } void SegmentedString::advanceEmpty() { ASSERT(!m_currentString.m_length && !isComposite()); m_currentChar = 0; } void SegmentedString::updateSlowCaseFunctionPointers() { m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceSlowCase; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceAndUpdateLineNumberSlowCase; } OrdinalNumber SegmentedString::currentLine() const { return OrdinalNumber::fromZeroBasedInt(m_currentLine); } OrdinalNumber SegmentedString::currentColumn() const { int zeroBasedColumn = numberOfCharactersConsumed() - m_numberOfCharactersConsumedPriorToCurrentLine; return OrdinalNumber::fromZeroBasedInt(zeroBasedColumn); } void SegmentedString::setCurrentPosition(OrdinalNumber line, OrdinalNumber columnAftreProlog, int prologLength) { m_currentLine = line.zeroBasedInt(); m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + prologLength - columnAftreProlog.zeroBasedInt(); } }
32.855828
132
0.690879
abarth
11dc5332d8f92aba3955636f5a6cc962047739e4
8,370
cpp
C++
src/AbstractTab.cpp
shtroizel/completable
f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048
[ "BSD-3-Clause" ]
null
null
null
src/AbstractTab.cpp
shtroizel/completable
f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048
[ "BSD-3-Clause" ]
null
null
null
src/AbstractTab.cpp
shtroizel/completable
f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2020, Eric Hyer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AbstractTab.h" #include <ncurses.h> #include "AbstractWindow.h" #include "EnablednessSetting.h" #include "Layer.h" #include "VisibilityAspect.h" #include "key_codes.h" AbstractTab::AbstractTab() : layers{ std::make_shared< matchable::MatchBox< Layer::Type, std::pair<std::vector<AbstractWindow *>, AbstractWindow *> > >() } { for (auto l : Layer::variants()) layers->mut_at(l).second = nullptr; EnablednessSetting::Borders::grab().add_enabledness_observer([&](){ draw(true); }); Tab::nil.set_AbstractTab(nullptr); } AbstractTab::~AbstractTab() { layers.reset(); active_tab() = nullptr; left_neighbor = Tab::nil; right_neighbor = Tab::nil; } void AbstractTab::add_window(AbstractWindow * win) { if (nullptr == win) return; layers->mut_at(win->get_layer()).first.push_back(win); win->add_tab(AccessKey_AbstractWindow_add_tab(), as_handle()); // guarantee active window by setting first window active if (layers->at(win->get_layer()).first.size() == 1) layers->mut_at(win->get_layer()).second = win; } void AbstractTab::resize() { if (is_active()) for (auto l : Layer::variants()) for (auto w : layers->mut_at(l).first) w->resize(); } void AbstractTab::draw(bool clear_first) { if (is_active()) { for (auto w : layers->mut_at(Layer::Bottom::grab()).first) w->draw(clear_first); if (layer_F_enabled) for (auto w : layers->mut_at(Layer::F::grab()).first) w->draw(clear_first); if (layer_Help_enabled) for (auto w : layers->mut_at(Layer::Help::grab()).first) w->draw(clear_first); } } void AbstractTab::set_active_tab(Tab::Type tab) { if (tab.is_nil()) return; if (nullptr != active_tab()) for (auto l : Layer::variants()) for (auto w : active_tab()->layers->mut_at(l).first) w->disable(VisibilityAspect::TabVisibility::grab()); AbstractWindow const * tab_act_win = tab.as_AbstractTab()->get_active_window(); // synce WindowVisibility aspect for Help layer, specifically: // // if help enabled for old tab then enable help for new tab if not already // and... // if help disabled for old tab then disable help for new tab if not already if (nullptr != active_tab() && nullptr != tab_act_win) { // if help enabled for old/current active_tab() if (nullptr != active_tab()->get_active_window() && active_tab()->get_active_window()->get_layer() == Layer::Help::grab()) { // then enable if help disabled for new active_tab() if (tab_act_win->get_layer() != Layer::Help::grab()) tab.as_AbstractTab()->on_COMMA(); } else // otherwise if help disabled for old/current active_tab() { // then disable if help enabled for new active_tab() if (tab_act_win->get_layer() == Layer::Help::grab()) tab.as_AbstractTab()->on_COMMA(); } } active_tab() = tab.as_AbstractTab(); // enable TabVisibility aspect for each window within each layer if (nullptr != active_tab()) for (auto l : Layer::variants()) for (auto w : active_tab()->layers->mut_at(l).first) w->enable(VisibilityAspect::TabVisibility::grab()); } Tab::Type AbstractTab::get_active_tab() { if (nullptr == active_tab()) return Tab::nil; return active_tab()->as_handle(); } void AbstractTab::set_active_window(AbstractWindow * win) { if (nullptr == win) return; // verify given window exists in the given layer { bool found = false; for (auto w : layers->at(win->get_layer()).first) { if (w == win) { found = true; break; } } if (!found) return; } // need to redraw both old and new active windows layers->mut_at(win->get_layer()).second->mark_dirty(); win->mark_dirty(); layers->mut_at(win->get_layer()).second = win; } AbstractWindow * AbstractTab::get_active_window() { if (layer_Help_enabled) return layers->mut_at(Layer::Help::grab()).second; if (layer_F_enabled) return layers->mut_at(Layer::F::grab()).second; return layers->mut_at(Layer::Bottom::grab()).second; } AbstractWindow * AbstractTab::get_active_window(Layer::Type layer) { return layers->mut_at(layer).second; } void AbstractTab::on_KEY(int key) { if (!is_active()) return; switch (key) { case KEY_F(1) : case KEY_F(2) : case KEY_F(3) : case KEY_F(4) : case KEY_F(5) : case KEY_F(6) : case KEY_F(7) : case KEY_F(8) : case KEY_F(9) : case KEY_F(10) : case KEY_F(11) : case KEY_F(12) : on_ANY_F(); return; case ',' : on_COMMA(); return; case SHIFT_LEFT : on_SHIFT_LEFT(); return; case SHIFT_RIGHT : on_SHIFT_RIGHT(); return; } auto active_win = get_active_window(); if (nullptr != active_win) { if (active_win->get_layer() == Layer::Help::grab()) { switch (key) { case KEY_LEFT : on_SHIFT_LEFT(); return; case KEY_RIGHT : on_SHIFT_RIGHT(); return; } } active_win->on_KEY(key); } } void AbstractTab::on_ANY_F() { if (layer_Help_enabled) return; if (layers->at(Layer::F::grab()).first.size() > 0) toggle_layer(Layer::F::grab(), layer_F_enabled); } void AbstractTab::on_COMMA() { toggle_layer(Layer::Help::grab(), layer_Help_enabled); } void AbstractTab::toggle_layer(Layer::Type layer, bool & layer_enabled) { if (layer_enabled) { // disable layer layer_enabled = false; for (auto w : layers->mut_at(layer).first) w->disable(VisibilityAspect::WindowVisibility::grab()); // mark other layers dirty for (auto l : Layer::variants()) if (l != layer) for (auto w : layers->mut_at(l).first) w->mark_dirty(); } else { // enable layer layer_enabled = true; for (auto w : layers->mut_at(layer).first) w->enable(VisibilityAspect::WindowVisibility::grab()); } } void AbstractTab::on_SHIFT_LEFT() { if (!left_neighbor.is_nil()) AbstractTab::set_active_tab(left_neighbor); } void AbstractTab::on_SHIFT_RIGHT() { if (!right_neighbor.is_nil()) AbstractTab::set_active_tab(right_neighbor); }
27
87
0.61362
shtroizel
11dd4cc7eea31c758a7d5706cb80cb0892be57b8
1,216
cpp
C++
libgpos/src/task/CAutoTraceFlag.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
28
2016-01-29T08:27:42.000Z
2021-03-11T01:42:33.000Z
libgpos/src/task/CAutoTraceFlag.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
22
2016-02-01T16:31:50.000Z
2017-07-13T13:25:53.000Z
libgpos/src/task/CAutoTraceFlag.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
23
2016-01-28T03:19:24.000Z
2021-05-28T07:32:51.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CAutoTraceFlag.cpp // // @doc: // Auto object to toggle TF in scope //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpos/task/CAutoTraceFlag.h" using namespace gpos; //--------------------------------------------------------------------------- // @function: // CAutoTraceFlag::CAutoTraceFlag // // @doc: // ctor // //--------------------------------------------------------------------------- CAutoTraceFlag::CAutoTraceFlag ( ULONG ulTrace, BOOL fVal ) : m_ulTrace(ulTrace), m_fOrig(false) { GPOS_ASSERT(NULL != ITask::PtskSelf()); m_fOrig = ITask::PtskSelf()->FTrace(m_ulTrace, fVal); } //--------------------------------------------------------------------------- // @function: // CAutoTraceFlag::~CAutoTraceFlag // // @doc: // dtor // //--------------------------------------------------------------------------- CAutoTraceFlag::~CAutoTraceFlag() { GPOS_ASSERT(NULL != ITask::PtskSelf()); // reset original value ITask::PtskSelf()->FTrace(m_ulTrace, m_fOrig); } // EOF
20.965517
77
0.409539
khannaekta
11e56d15b8518951eaa1e705fe1b4e6149fc0615
2,005
cpp
C++
mkra/src/module.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
mkra/src/module.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
mkra/src/module.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Author:liu.hao(33852613@163.com) Time:2021-4 info: ***************************************************************************************************/ #include <markcore.h> #include "mkLIRSReplacement.h" MK_DEFINE_MODULE_INSTANCE_VERSION(1, 0, 0); class mkLIRSReplacementOption : public mkIOption { public: virtual bool OnSetValue(const string& key, const string& value) { if("--lir_size" == key) { lir_size = std::stoi(value); return true; } if("--hir_Size" == key) { hir_Size = std::stoi(value); return true; } return false; } virtual void OnApply() { } public: int lir_size = 100; int hir_Size = 100; }; void mkIReplacementBuilder::PushOptions(const string& key, const string& value) { MK_CALL_ONCE_BEGIN g_switch->ClearOption<mkLIRSReplacementOption>(); MK_CALL_ONCE_END g_switch->SetOptions(key, value, false); } std::shared_ptr<mkIReplacement> mkIReplacementBuilder::LIRS(shared_ptr<mkIReplaceValueBuilder> pBuilder) { const auto& lir_size = g_switch->GetOption<mkLIRSReplacementOption>()->lir_size; const auto& hir_Size = g_switch->GetOption<mkLIRSReplacementOption>()->hir_Size; return make_shared<mkLIRSReplacement>(lir_size, hir_Size, pBuilder); }
27.465753
100
0.618953
unihykes
11e5f9bd49da4e120dce1a093ce869f80b8b0ece
24,133
cpp
C++
src/game/server/entities/triggers/CChangeLevel.cpp
GEEKiDoS/source-sdk-2013-mp
9c4d61d342a23d7da1a2b35e28423e205c11d7fa
[ "Unlicense" ]
1
2021-03-20T14:27:22.000Z
2021-03-20T14:27:22.000Z
src/game/server/entities/triggers/CChangeLevel.cpp
GEEKiDoS/source-sdk-2013-mp
9c4d61d342a23d7da1a2b35e28423e205c11d7fa
[ "Unlicense" ]
null
null
null
src/game/server/entities/triggers/CChangeLevel.cpp
GEEKiDoS/source-sdk-2013-mp
9c4d61d342a23d7da1a2b35e28423e205c11d7fa
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// #include "cbase.h" #include "ai_basenpc.h" #include "ai_behavior_lead.h" #include "entityapi.h" #include "saverestore.h" #include "saverestoretypes.h" #include "triggers.h" #include "entities/triggers/CChangeLevel.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar g_debug_transitions("g_debug_transitions", "0", FCVAR_NONE, "Set to 1 and restart the map to be warned if the map has no trigger_transition volumes. Set to 2 to see a dump of all entities & associated results during a transition."); LINK_ENTITY_TO_CLASS( trigger_changelevel, CChangeLevel ); // Global Savedata for changelevel trigger BEGIN_DATADESC( CChangeLevel ) DEFINE_AUTO_ARRAY( m_szMapName, FIELD_CHARACTER ), DEFINE_AUTO_ARRAY( m_szLandmarkName, FIELD_CHARACTER ), // DEFINE_FIELD( m_touchTime, FIELD_TIME ), // don't save // DEFINE_FIELD( m_bTouched, FIELD_BOOLEAN ), // Function Pointers DEFINE_FUNCTION( TouchChangeLevel ), DEFINE_INPUTFUNC( FIELD_VOID, "ChangeLevel", InputChangeLevel ), // Outputs DEFINE_OUTPUT( m_OnChangeLevel, "OnChangeLevel"), END_DATADESC() // // Cache user-entity-field values until spawn is called. // bool CChangeLevel::KeyValue( const char *szKeyName, const char *szValue ) { if (FStrEq(szKeyName, "map")) { if (strlen(szValue) >= cchMapNameMost) { Warning( "Map name '%s' too long (32 chars)\n", szValue ); Assert(0); } Q_strncpy(m_szMapName, szValue, sizeof(m_szMapName)); } else if (FStrEq(szKeyName, "landmark")) { if (strlen(szValue) >= cchMapNameMost) { Warning( "Landmark name '%s' too long (32 chars)\n", szValue ); Assert(0); } Q_strncpy(m_szLandmarkName, szValue, sizeof( m_szLandmarkName )); } else return BaseClass::KeyValue( szKeyName, szValue ); return true; } void CChangeLevel::Spawn( void ) { if ( FStrEq( m_szMapName, "" ) ) { Msg( "a trigger_changelevel doesn't have a map" ); } if ( FStrEq( m_szLandmarkName, "" ) ) { Msg( "trigger_changelevel to %s doesn't have a landmark", m_szMapName ); } InitTrigger(); if ( !HasSpawnFlags(SF_CHANGELEVEL_NOTOUCH) ) { SetTouch( &CChangeLevel::TouchChangeLevel ); } // Msg( "TRANSITION: %s (%s)\n", m_szMapName, m_szLandmarkName ); } void CChangeLevel::Activate( void ) { BaseClass::Activate(); if ( gpGlobals->eLoadType == MapLoad_NewGame ) { if ( HasSpawnFlags( SF_CHANGELEVEL_CHAPTER ) ) { VPhysicsInitStatic(); RemoveSolidFlags( FSOLID_NOT_SOLID | FSOLID_TRIGGER ); SetTouch( NULL ); return; } } // Level transitions will bust if they are in solid CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName ); if ( pLandmark ) { int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); if ( clusterIndex < 0 ) { Warning( "trigger_changelevel to map %s has a landmark embedded in solid!\n" "This will break level transitions!\n", m_szMapName ); } if ( g_debug_transitions.GetInt() ) { if ( !gEntList.FindEntityByClassname( NULL, "trigger_transition" ) ) { Warning( "Map has no trigger_transition volumes for landmark %s\n", m_szLandmarkName ); } } } m_bTouched = false; } static char st_szNextMap[cchMapNameMost]; static char st_szNextSpot[cchMapNameMost]; // Used to show debug for only the transition volume we're currently in static int g_iDebuggingTransition = 0; CBaseEntity *CChangeLevel::FindLandmark( const char *pLandmarkName ) { CBaseEntity *pentLandmark; pentLandmark = gEntList.FindEntityByName( NULL, pLandmarkName ); while ( pentLandmark ) { // Found the landmark if ( FClassnameIs( pentLandmark, "info_landmark" ) ) return pentLandmark; else pentLandmark = gEntList.FindEntityByName( pentLandmark, pLandmarkName ); } Warning( "Can't find landmark %s\n", pLandmarkName ); return NULL; } //----------------------------------------------------------------------------- // Purpose: Allows level transitions to be triggered by buttons, etc. //----------------------------------------------------------------------------- void CChangeLevel::InputChangeLevel( inputdata_t &inputdata ) { // Ignore changelevel transitions if the player's dead or attempting a challenge if ( gpGlobals->maxClients == 1 ) { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer && ( !pPlayer->IsAlive() || pPlayer->GetBonusChallenge() > 0 ) ) return; } ChangeLevelNow( inputdata.pActivator ); } //----------------------------------------------------------------------------- // Purpose: Performs the level change and fires targets. // Input : pActivator - //----------------------------------------------------------------------------- bool CChangeLevel::IsEntityInTransition( CBaseEntity *pEntity ) { int transitionState = InTransitionVolume(pEntity, m_szLandmarkName); if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT ) { return false; } // look for a landmark entity CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName ); if ( !pLandmark ) return false; // Check to make sure it's also in the PVS of landmark byte pvs[MAX_MAP_CLUSTERS/8]; int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs ); Vector vecSurroundMins, vecSurroundMaxs; pEntity->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); return engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) ); } void CChangeLevel::NotifyEntitiesOutOfTransition() { CBaseEntity *pEnt = gEntList.FirstEnt(); while ( pEnt ) { // Found the landmark if ( pEnt->ObjectCaps() & FCAP_NOTIFY_ON_TRANSITION ) { variant_t emptyVariant; if ( !(pEnt->ObjectCaps() & (FCAP_ACROSS_TRANSITION|FCAP_FORCE_TRANSITION)) || !IsEntityInTransition( pEnt ) ) { pEnt->AcceptInput( "OutsideTransition", this, this, emptyVariant, 0 ); } else { pEnt->AcceptInput( "InsideTransition", this, this, emptyVariant, 0 ); } } pEnt = gEntList.NextEnt( pEnt ); } } //------------------------------------------------------------------------------ // Purpose : Checks all spawned AIs and prints a warning if any are actively leading // Input : // Output : //------------------------------------------------------------------------------ void CChangeLevel::WarnAboutActiveLead( void ) { int i; CAI_BaseNPC * ai; CAI_BehaviorBase * behavior; for ( i = 0; i < g_AI_Manager.NumAIs(); i++ ) { ai = g_AI_Manager.AccessAIs()[i]; behavior = ai->GetRunningBehavior(); if ( behavior ) { if ( dynamic_cast<CAI_LeadBehavior *>( behavior ) ) { Warning( "Entity '%s' is still actively leading\n", STRING( ai->GetEntityName() ) ); } } } } void CChangeLevel::ChangeLevelNow( CBaseEntity *pActivator ) { CBaseEntity *pLandmark; levellist_t levels[16]; Assert(!FStrEq(m_szMapName, "")); // Don't work in deathmatch if ( g_pGameRules->IsDeathmatch() ) return; // Some people are firing these multiple times in a frame, disable if ( m_bTouched ) return; m_bTouched = true; CBaseEntity *pPlayer = (pActivator && pActivator->IsPlayer()) ? pActivator : UTIL_GetLocalPlayer(); int transitionState = InTransitionVolume(pPlayer, m_szLandmarkName); if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT ) { DevMsg( 2, "Player isn't in the transition volume %s, aborting\n", m_szLandmarkName ); return; } // look for a landmark entity pLandmark = FindLandmark( m_szLandmarkName ); if ( !pLandmark ) return; // no transition volumes, check PVS of landmark if ( transitionState == TRANSITION_VOLUME_NOT_FOUND ) { byte pvs[MAX_MAP_CLUSTERS/8]; int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs ); if ( pPlayer ) { Vector vecSurroundMins, vecSurroundMaxs; pPlayer->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); bool playerInPVS = engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) ); //Assert( playerInPVS ); if ( !playerInPVS ) { Warning( "Player isn't in the landmark's (%s) PVS, aborting\n", m_szLandmarkName ); #ifndef HL1_DLL // HL1 works even with these errors! return; #endif } } } WarnAboutActiveLead(); g_iDebuggingTransition = 0; st_szNextSpot[0] = 0; // Init landmark to NULL Q_strncpy(st_szNextSpot, m_szLandmarkName,sizeof(st_szNextSpot)); // This object will get removed in the call to engine->ChangeLevel, copy the params into "safe" memory Q_strncpy(st_szNextMap, m_szMapName, sizeof(st_szNextMap)); m_hActivator = pActivator; m_OnChangeLevel.FireOutput(pActivator, this); NotifyEntitiesOutOfTransition(); //// Msg( "Level touches %d levels\n", ChangeList( levels, 16 ) ); if ( g_debug_transitions.GetInt() ) { Msg( "CHANGE LEVEL: %s %s\n", st_szNextMap, st_szNextSpot ); } // If we're debugging, don't actually change level if ( g_debug_transitions.GetInt() == 0 ) { engine->ChangeLevel( st_szNextMap, st_szNextSpot ); } else { // Build a change list so we can see what would be transitioning CSaveRestoreData *pSaveData = SaveInit( 0 ); if ( pSaveData ) { g_pGameSaveRestoreBlockSet->PreSave( pSaveData ); pSaveData->levelInfo.connectionCount = BuildChangeList( pSaveData->levelInfo.levelList, MAX_LEVEL_CONNECTIONS ); g_pGameSaveRestoreBlockSet->PostSave(); } SetTouch( NULL ); } } // // GLOBALS ASSUMED SET: st_szNextMap // void CChangeLevel::TouchChangeLevel( CBaseEntity *pOther ) { CBasePlayer *pPlayer = ToBasePlayer(pOther); if ( !pPlayer ) return; if( pPlayer->IsSinglePlayerGameEnding() ) { // Some semblance of deceleration, but allow player to fall normally. // Also, disable controls. Vector vecVelocity = pPlayer->GetAbsVelocity(); vecVelocity.x *= 0.5f; vecVelocity.y *= 0.5f; pPlayer->SetAbsVelocity( vecVelocity ); pPlayer->AddFlag( FL_FROZEN ); return; } if ( !pPlayer->IsInAVehicle() && pPlayer->GetMoveType() == MOVETYPE_NOCLIP ) { DevMsg("In level transition: %s %s\n", st_szNextMap, st_szNextSpot ); return; } ChangeLevelNow( pOther ); } // Add a transition to the list, but ignore duplicates // (a designer may have placed multiple trigger_changelevels with the same landmark) int CChangeLevel::AddTransitionToList( levellist_t *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark ) { int i; if ( !pLevelList || !pMapName || !pLandmarkName || !pentLandmark ) return 0; // Ignore changelevels to the level we're ready in. Mapmakers love to do this! if ( stricmp( pMapName, STRING(gpGlobals->mapname) ) == 0 ) return 0; for ( i = 0; i < listCount; i++ ) { if ( pLevelList[i].pentLandmark == pentLandmark && stricmp( pLevelList[i].mapName, pMapName ) == 0 ) return 0; } Q_strncpy( pLevelList[listCount].mapName, pMapName, sizeof(pLevelList[listCount].mapName) ); Q_strncpy( pLevelList[listCount].landmarkName, pLandmarkName, sizeof(pLevelList[listCount].landmarkName) ); pLevelList[listCount].pentLandmark = pentLandmark; CBaseEntity *ent = CBaseEntity::Instance( pentLandmark ); Assert( ent ); pLevelList[listCount].vecLandmarkOrigin = ent->GetAbsOrigin(); return 1; } int BuildChangeList( levellist_t *pLevelList, int maxList ) { return CChangeLevel::ChangeList( pLevelList, maxList ); } struct collidelist_t { const CPhysCollide *pCollide; Vector origin; QAngle angles; }; // NOTE: This routine is relatively slow. If you need to use it for per-frame work, consider that fact. // UNDONE: Expand this to the full matrix of solid types on each side and move into enginetrace static bool TestEntityTriggerIntersection_Accurate(CBaseEntity *pTrigger, CBaseEntity *pEntity) { Assert(pTrigger->GetSolid() == SOLID_BSP); if (pTrigger->Intersects(pEntity)) // It touches one, it's in the volume { switch (pEntity->GetSolid()) { case SOLID_BBOX: { ICollideable *pCollide = pTrigger->CollisionProp(); Ray_t ray; trace_t tr; ray.Init(pEntity->GetAbsOrigin(), pEntity->GetAbsOrigin(), pEntity->WorldAlignMins(), pEntity->WorldAlignMaxs()); enginetrace->ClipRayToCollideable(ray, MASK_ALL, pCollide, &tr); if (tr.startsolid) return true; } break; case SOLID_BSP: case SOLID_VPHYSICS: { CPhysCollide *pTriggerCollide = modelinfo->GetVCollide(pTrigger->GetModelIndex())->solids[0]; Assert(pTriggerCollide); CUtlVector<collidelist_t> collideList; IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int physicsCount = pEntity->VPhysicsGetObjectList(pList, ARRAYSIZE(pList)); if (physicsCount) { for (int i = 0; i < physicsCount; i++) { const CPhysCollide *pCollide = pList[i]->GetCollide(); if (pCollide) { collidelist_t element; element.pCollide = pCollide; pList[i]->GetPosition(&element.origin, &element.angles); collideList.AddToTail(element); } } } else { vcollide_t *pVCollide = modelinfo->GetVCollide(pEntity->GetModelIndex()); if (pVCollide && pVCollide->solidCount) { collidelist_t element; element.pCollide = pVCollide->solids[0]; element.origin = pEntity->GetAbsOrigin(); element.angles = pEntity->GetAbsAngles(); collideList.AddToTail(element); } } for (int i = collideList.Count() - 1; i >= 0; --i) { const collidelist_t &element = collideList[i]; trace_t tr; physcollision->TraceCollide(element.origin, element.origin, element.pCollide, element.angles, pTriggerCollide, pTrigger->GetAbsOrigin(), pTrigger->GetAbsAngles(), &tr); if (tr.startsolid) return true; } } break; default: return true; } } return false; } int CChangeLevel::InTransitionVolume(CBaseEntity *pEntity, const char *pVolumeName) { CBaseEntity *pVolume; if (pEntity->ObjectCaps() & FCAP_FORCE_TRANSITION) return TRANSITION_VOLUME_PASSED; // If you're following another entity, follow it through the transition (weapons follow the player) pEntity = pEntity->GetRootMoveParent(); int inVolume = TRANSITION_VOLUME_NOT_FOUND; // Unless we find a trigger_transition, everything is in the volume pVolume = gEntList.FindEntityByName(NULL, pVolumeName); while (pVolume) { if (pVolume && FClassnameIs(pVolume, "trigger_transition")) { if (TestEntityTriggerIntersection_Accurate(pVolume, pEntity)) // It touches one, it's in the volume return TRANSITION_VOLUME_PASSED; inVolume = TRANSITION_VOLUME_SCREENED_OUT; // Found a trigger_transition, but I don't intersect it -- if I don't find another, don't go! } pVolume = gEntList.FindEntityByName(pVolume, pVolumeName); } return inVolume; } //------------------------------------------------------------------------------ // Builds the list of entities to save when moving across a transition //------------------------------------------------------------------------------ int CChangeLevel::BuildChangeLevelList(levellist_t *pLevelList, int maxList) { int nCount = 0; CBaseEntity *pentChangelevel = gEntList.FindEntityByClassname(NULL, "trigger_changelevel"); while (pentChangelevel) { CChangeLevel *pTrigger = dynamic_cast<CChangeLevel *>(pentChangelevel); if (pTrigger) { // Find the corresponding landmark CBaseEntity *pentLandmark = FindLandmark(pTrigger->m_szLandmarkName); if (pentLandmark) { // Build a list of unique transitions if (AddTransitionToList(pLevelList, nCount, pTrigger->m_szMapName, pTrigger->m_szLandmarkName, pentLandmark->edict())) { ++nCount; if (nCount >= maxList) // FULL!! break; } } } pentChangelevel = gEntList.FindEntityByClassname(pentChangelevel, "trigger_changelevel"); } return nCount; } //------------------------------------------------------------------------------ // Adds a single entity to the transition list, if appropriate. Returns the new count //------------------------------------------------------------------------------ int CChangeLevel::ComputeEntitySaveFlags(CBaseEntity *pEntity) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("Trying %s (%s): ", pEntity->GetClassname(), pEntity->GetDebugName()); } int caps = pEntity->ObjectCaps(); if (caps & FCAP_DONT_SAVE) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("IGNORED due to being marked \"Don't save\".\n"); } return 0; } // If this entity can be moved or is global, mark it int flags = 0; if (caps & FCAP_ACROSS_TRANSITION) { flags |= FENTTABLE_MOVEABLE; } if (pEntity->m_iGlobalname != NULL_STRING && !pEntity->IsDormant()) { flags |= FENTTABLE_GLOBAL; } if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE && !flags) { Msg("IGNORED, no across_transition flag & no globalname\n"); } return flags; } //------------------------------------------------------------------------------ // Adds a single entity to the transition list, if appropriate. Returns the new count //------------------------------------------------------------------------------ inline int CChangeLevel::AddEntityToTransitionList(CBaseEntity *pEntity, int flags, int nCount, CBaseEntity **ppEntList, int *pEntityFlags) { ppEntList[nCount] = pEntity; pEntityFlags[nCount] = flags; ++nCount; // If we're debugging, make it visible if (g_iDebuggingTransition) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { // In verbose mode we've already printed out what the entity is Msg("ADDED.\n"); } else { // In non-verbose mode, we just print this line Msg("ADDED %s (%s) to transition.\n", pEntity->GetClassname(), pEntity->GetDebugName()); } pEntity->m_debugOverlays |= (OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT); } return nCount; } //------------------------------------------------------------------------------ // Builds the list of entities to bring across a particular transition //------------------------------------------------------------------------------ int CChangeLevel::BuildEntityTransitionList(CBaseEntity *pLandmarkEntity, const char *pLandmarkName, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList) { int iEntity = 0; // Only show debug for the transition to the level we're going to if (g_debug_transitions.GetInt() && pLandmarkEntity->NameMatches(st_szNextSpot)) { g_iDebuggingTransition = g_debug_transitions.GetInt(); // Show us where the landmark entity is pLandmarkEntity->m_debugOverlays |= (OVERLAY_PIVOT_BIT | OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT); } else { g_iDebuggingTransition = 0; } // Follow the linked list of entities in the PVS of the transition landmark CBaseEntity *pEntity = NULL; while ((pEntity = UTIL_EntitiesInPVS(pLandmarkEntity, pEntity)) != NULL) { int flags = ComputeEntitySaveFlags(pEntity); if (!flags) continue; // Check to make sure the entity isn't screened out by a trigger_transition if (!InTransitionVolume(pEntity, pLandmarkName)) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("IGNORED, outside transition volume.\n"); } continue; } if (iEntity >= nMaxList) { Warning("Too many entities across a transition!\n"); Assert(0); return iEntity; } iEntity = AddEntityToTransitionList(pEntity, flags, iEntity, ppEntList, pEntityFlags); } return iEntity; } //------------------------------------------------------------------------------ // Tests bits in a bitfield //------------------------------------------------------------------------------ static inline bool IsBitSet(char *pBuf, int nBit) { return (pBuf[nBit >> 3] & (1 << (nBit & 0x7))) != 0; } static inline void Set(char *pBuf, int nBit) { pBuf[nBit >> 3] |= 1 << (nBit & 0x7); } //------------------------------------------------------------------------------ // Adds in all entities depended on by entities near the transition //------------------------------------------------------------------------------ #define MAX_ENTITY_BYTE_COUNT (NUM_ENT_ENTRIES >> 3) int CChangeLevel::AddDependentEntities(int nCount, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList) { char pEntitiesSaved[MAX_ENTITY_BYTE_COUNT]; memset(pEntitiesSaved, 0, MAX_ENTITY_BYTE_COUNT * sizeof(char)); // Populate the initial bitfield int i; for (i = 0; i < nCount; ++i) { // NOTE: Must use GetEntryIndex because we're saving non-networked entities int nEntIndex = ppEntList[i]->GetRefEHandle().GetEntryIndex(); // We shouldn't already have this entity in the list! Assert(!IsBitSet(pEntitiesSaved, nEntIndex)); // Mark the entity as being in the list Set(pEntitiesSaved, nEntIndex); } IEntitySaveUtils *pSaveUtils = GetEntitySaveUtils(); // Iterate over entities whose dependencies we've not yet processed // NOTE: nCount will change value during this loop in AddEntityToTransitionList for (i = 0; i < nCount; ++i) { CBaseEntity *pEntity = ppEntList[i]; // Find dependencies in the hash. int nDepCount = pSaveUtils->GetEntityDependencyCount(pEntity); if (!nDepCount) continue; CBaseEntity **ppDependentEntities = (CBaseEntity**)stackalloc(nDepCount * sizeof(CBaseEntity*)); pSaveUtils->GetEntityDependencies(pEntity, nDepCount, ppDependentEntities); for (int j = 0; j < nDepCount; ++j) { CBaseEntity *pDependent = ppDependentEntities[j]; if (!pDependent) continue; // NOTE: Must use GetEntryIndex because we're saving non-networked entities int nEntIndex = pDependent->GetRefEHandle().GetEntryIndex(); // Don't re-add it if it's already in the list if (IsBitSet(pEntitiesSaved, nEntIndex)) continue; // Mark the entity as being in the list Set(pEntitiesSaved, nEntIndex); int flags = ComputeEntitySaveFlags(pEntity); if (flags) { if (nCount >= nMaxList) { Warning("Too many entities across a transition!\n"); Assert(0); return false; } if (g_debug_transitions.GetInt()) { Msg("ADDED DEPENDANCY: %s (%s)\n", pEntity->GetClassname(), pEntity->GetDebugName()); } nCount = AddEntityToTransitionList(pEntity, flags, nCount, ppEntList, pEntityFlags); } else { Warning("Warning!! Save dependency is linked to an entity that doesn't want to be saved!\n"); } } } return nCount; } //------------------------------------------------------------------------------ // This builds the list of all transitions on this level and which entities // are in their PVS's and can / should be moved across. //------------------------------------------------------------------------------ // We can only ever move 512 entities across a transition #define MAX_ENTITY 512 // FIXME: This has grown into a complicated beast. Can we make this more elegant? int CChangeLevel::ChangeList(levellist_t *pLevelList, int maxList) { // Find all of the possible level changes on this BSP int count = BuildChangeLevelList(pLevelList, maxList); if (!gpGlobals->pSaveData || (static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)->NumEntities() == 0)) return count; CSave saveHelper(static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)); // For each level change, find nearby entities and save them int i; for (i = 0; i < count; i++) { CBaseEntity *pEntList[MAX_ENTITY]; int entityFlags[MAX_ENTITY]; // First, figure out which entities are near the transition CBaseEntity *pLandmarkEntity = CBaseEntity::Instance(pLevelList[i].pentLandmark); int iEntity = BuildEntityTransitionList(pLandmarkEntity, pLevelList[i].landmarkName, pEntList, entityFlags, MAX_ENTITY); // FIXME: Activate if we have a dependency problem on level transition // Next, add in all entities depended on by entities near the transition // iEntity = AddDependentEntities( iEntity, pEntList, entityFlags, MAX_ENTITY ); int j; for (j = 0; j < iEntity; j++) { // Mark entity table with 1<<i int index = saveHelper.EntityIndex(pEntList[j]); // Flag it with the level number saveHelper.EntityFlagsSet(index, entityFlags[j] | (1 << i)); } } return count; }
29.394641
239
0.667716
GEEKiDoS
eb1ca3d0f21e064375c746e348caf888f8eb7636
6,148
cpp
C++
ContextSensors/src/csd_calendar.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
ContextSensors/src/csd_calendar.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
ContextSensors/src/csd_calendar.cpp
crutchwalkfactory/jaikuengine-mobile-client
c47100ec009d47a4045b3d98addc9b8ad887b132
[ "MIT" ]
null
null
null
// Copyright (c) 2007-2009 Google Inc. // Copyright (c) 2006-2007 Jaiku Ltd. // Copyright (c) 2002-2006 Mika Raento and Renaud Petit // // This software is licensed at your choice under either 1 or 2 below. // // 1. MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // 2. Gnu General Public license 2.0 // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // // This file is part of the JaikuEngine mobile client. #include "csd_calendar.h" EXPORT_C const TTypeName& TBBCalendarEvent::Type() const { return KCalendarEventType; } EXPORT_C TBool TBBCalendarEvent::Equals(const MBBData* aRhs) const { const TBBCalendarEvent* rhs=bb_cast<TBBCalendarEvent>(aRhs); return (rhs && *this==*rhs); } EXPORT_C const TTypeName& TBBCalendarEvent::StaticType() { return KCalendarEventType; } EXPORT_C const MBBData* TBBCalendarEvent::Part(TUint aPartNo) const { switch(aPartNo) { case 0: return &iStartTime; case 1: return &iDescription; case 2: return &iEndTime; case 3: return &iEventId; default: return 0; } } _LIT(KDescription, "description"); _LIT(KStartTime, "start_time"); _LIT(KEndTime, "end_time"); _LIT(KEventId, "eventid"); EXPORT_C TBBCalendarEvent::TBBCalendarEvent(const TDesC& aName) : TBBCompoundData(aName), iDescription(KDescription), iStartTime(KStartTime), iEndTime(KEndTime), iEventId(KEventId) { } EXPORT_C bool TBBCalendarEvent::operator==(const TBBCalendarEvent& aRhs) const { return ( iDescription==aRhs.iDescription && iStartTime()==aRhs.iStartTime() && iEndTime()==aRhs.iEndTime() && iEventId()==aRhs.iEventId() ); } _LIT(KSemicolon, ";"); EXPORT_C const TDesC& TBBCalendarEvent::StringSep(TUint aBeforePart) const { if (aBeforePart>0 && aBeforePart<=3) return KSemicolon; else return KNullDesC; } EXPORT_C TBBCalendarEvent& TBBCalendarEvent::operator=(const TBBCalendarEvent& aRhs) { iDescription()=aRhs.iDescription(); iStartTime()=aRhs.iStartTime(); iEndTime()=aRhs.iEndTime(); iEventId()=aRhs.iEventId(); return *this; } EXPORT_C MBBData* TBBCalendarEvent::CloneL(const TDesC& Name) const { TBBCalendarEvent* ret=new (ELeave) TBBCalendarEvent(Name); *ret=*this; return ret; } EXPORT_C const TTypeName& TBBCalendar::Type() const { return KCalendarType; } EXPORT_C TBool TBBCalendar::Equals(const MBBData* aRhs) const { const TBBCalendar* rhs=bb_cast<TBBCalendar>(aRhs); return (rhs && *this==*rhs); } EXPORT_C const TTypeName& TBBCalendar::StaticType() { return KCalendarType; } EXPORT_C const MBBData* TBBCalendar::Part(TUint aPartNo) const { switch (aPartNo) { case 0: return &iPrevious; case 1: return &iCurrent; case 2: return &iNext; default: return 0; } } _LIT(KPrevious, "previous"); _LIT(KCurrent, "current"); _LIT(KNext, "next"); EXPORT_C TBBCalendar::TBBCalendar() : TBBCompoundData(KCalendar), iPrevious(KPrevious), iCurrent(KCurrent), iNext(KNext), iCreatedVersion(2), iUseVersion(2) { } EXPORT_C TBBCalendar::TBBCalendar(TUint aVersion) : TBBCompoundData(KCalendar), iPrevious(KPrevious), iCurrent(KCurrent), iNext(KNext), iCreatedVersion(aVersion), iUseVersion(2) { } EXPORT_C void TBBCalendar::InternalizeL(RReadStream& aStream) { iUseVersion=iCreatedVersion; TBBCompoundData::InternalizeL(aStream); iUseVersion=2; } EXPORT_C bool TBBCalendar::operator==(const TBBCalendar& aRhs) const { return ( iPrevious==aRhs.iPrevious && iCurrent==aRhs.iCurrent && iNext == aRhs.iNext ); } _LIT(KHash, "#"); EXPORT_C const TDesC& TBBCalendar::StringSep(TUint aBeforePart) const { if (aBeforePart>0 && aBeforePart<=2) return KHash; else return KNullDesC; } EXPORT_C TBBCalendar& TBBCalendar::operator=(const TBBCalendar& aRhs) { iPrevious=aRhs.iPrevious; iCurrent=aRhs.iCurrent; iNext = aRhs.iNext; return *this; } EXPORT_C MBBData* TBBCalendar::CloneL(const TDesC& ) const { TBBCalendar* ret=new (ELeave) TBBCalendar; *ret=*this; return ret; } EXPORT_C MNestedXmlHandler* TBBCalendar::FromXmlL(MNestedXmlHandler* aParent, CXmlParser* aParser, HBufC*& aBuf, TBool aCheckType) { MNestedXmlHandler* ret=TBBCompoundData::FromXmlL(aParent, aParser, aBuf, aCheckType); ret->iIgnoreOffset=ETrue; return ret; } EXPORT_C void TBBCalendar::IntoXmlL(MBBExternalizer* aBuf, TBool aIncludeType) const { TTimeIntervalSeconds offs=aBuf->iOffset; aBuf->iOffset=TTimeIntervalSeconds(0); TRAPD(err, TBBCompoundData::IntoXmlL(aBuf, aIncludeType)); aBuf->iOffset==offs; User::LeaveIfError(err); }
26.964912
98
0.74756
crutchwalkfactory
eb1ce47710b2db11e95553ba08515d320e18ad0a
453
cpp
C++
array/989_add_to_array_form_interger.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
1
2019-08-21T21:25:34.000Z
2019-08-21T21:25:34.000Z
array/989_add_to_array_form_interger.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
null
null
null
array/989_add_to_array_form_interger.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> addToArrayForm(vector<int>& A, int K) { vector<int> result; int i = A.size(); int carry = K; while(--i >= 0 || carry > 0) { if(i >= 0) carry += A[i]; result.push_back(carry % 10); carry /= 10; } reverse(result.begin(), result.end()); return result; } };
20.590909
54
0.399558
rspezialetti
eb1d8b56429200d4dab81c8a1cc8b6625a3a9458
20,074
cpp
C++
src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
1
2019-12-03T18:41:39.000Z
2019-12-03T18:41:39.000Z
src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
null
null
null
src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Onyxia SD%Complete: 95 SDComment: <Known bugs> Ground visual for Deep Breath effect; Not summoning whelps on phase 3 (lacks info) </Known bugs> SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptPCH.h" #include "onyxias_lair.h" enum eYells { SAY_AGGRO = -1249000, SAY_KILL = -1249001, SAY_PHASE_2_TRANS = -1249002, SAY_PHASE_3_TRANS = -1249003, EMOTE_BREATH = -1249004, }; enum eSpells { // Phase 1 spells SPELL_WING_BUFFET = 18500, SPELL_FLAME_BREATH = 18435, SPELL_CLEAVE = 68868, SPELL_TAIL_SWEEP = 68867, // Phase 2 spells SPELL_DEEP_BREATH = 23461, SPELL_FIREBALL = 18392, //Not much choise about these. We have to make own defintion on the direction/start-end point SPELL_BREATH_NORTH_TO_SOUTH = 17086, // 20x in "array" SPELL_BREATH_SOUTH_TO_NORTH = 18351, // 11x in "array" SPELL_BREATH_EAST_TO_WEST = 18576, // 7x in "array" SPELL_BREATH_WEST_TO_EAST = 18609, // 7x in "array" SPELL_BREATH_SE_TO_NW = 18564, // 12x in "array" SPELL_BREATH_NW_TO_SE = 18584, // 12x in "array" SPELL_BREATH_SW_TO_NE = 18596, // 12x in "array" SPELL_BREATH_NE_TO_SW = 18617, // 12x in "array" //SPELL_BREATH = 21131, // 8x in "array", different initial cast than the other arrays // Phase 3 spells SPELL_BELLOWING_ROAR = 18431, SPELL_LAIRGUARDCLEAVE = 15284, SPELL_LAIRGUARDBLASTNOVA = 68958, SPELL_LAIRGUARDIGNITE = 68960 }; struct sOnyxMove { uint32 uiLocId; uint32 uiLocIdEnd; uint32 uiSpellId; float fX, fY, fZ; }; static sOnyxMove aMoveData[]= { {0, 1, SPELL_BREATH_WEST_TO_EAST, -33.5561f, -182.682f, -56.9457f}, //west {1, 0, SPELL_BREATH_EAST_TO_WEST, -31.4963f, -250.123f, -55.1278f}, //east {2, 4, SPELL_BREATH_NW_TO_SE, 6.8951f, -180.246f, -55.896f}, //north-west {3, 5, SPELL_BREATH_NE_TO_SW, 10.2191f, -247.912f, -55.896f}, //north-east {4, 2, SPELL_BREATH_SE_TO_NW, -63.5156f, -240.096f, -55.477f}, //south-east {5, 3, SPELL_BREATH_SW_TO_NE, -58.2509f, -189.020f, -55.790f}, //south-west {6, 7, SPELL_BREATH_SOUTH_TO_NORTH, -65.8444f, -213.809f, -55.2985f}, //south {7, 6, SPELL_BREATH_NORTH_TO_SOUTH, 22.8763f, -217.152f, -55.0548f}, //north }; const Position MiddleRoomLocation = {-23.6155f, -215.357f, -55.7344f, 0.0f}; const Position Phase2Location = {-80.924f, -214.299f, -82.942f, 0.0f}; static Position aSpawnLocations[3]= { //Whelps {-30.127f, -254.463f, -89.440f, 0.0f}, {-30.817f, -177.106f, -89.258f, 0.0f}, //Lair Guard {-145.950f, -212.831f, -68.659f, 0.0f} }; class boss_onyxia : public CreatureScript { public: boss_onyxia() : CreatureScript("boss_onyxia") { } CreatureAI* GetAI(Creature* creature) const { return new boss_onyxiaAI (creature); } struct boss_onyxiaAI : public ScriptedAI { boss_onyxiaAI(Creature* creature) : ScriptedAI(creature), Summons(me) { m_instance = creature->GetInstanceScript(); Reset(); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_ID, 49560, true); // Death Grip jump effect } InstanceScript* m_instance; SummonList Summons; uint32 m_uiPhase; uint32 m_uiFlameBreathTimer; uint32 m_uiCleaveTimer; uint32 m_uiTailSweepTimer; uint32 m_uiWingBuffetTimer; uint32 m_uiMovePoint; uint32 m_uiMovementTimer; sOnyxMove* m_pPointData; uint32 m_uiFireballTimer; uint32 m_uiWhelpTimer; uint32 m_uiLairGuardTimer; uint32 m_uiDeepBreathTimer; uint32 m_uiBellowingRoarTimer; uint8 m_uiSummonWhelpCount; bool m_bIsMoving; void Reset() { if (!IsCombatMovement()) SetCombatMovement(true); m_uiPhase = PHASE_START; m_uiFlameBreathTimer = urand(10000, 20000); m_uiTailSweepTimer = urand(15000, 20000); m_uiCleaveTimer = urand(2000, 5000); m_uiWingBuffetTimer = urand(10000, 20000); m_uiMovePoint = urand(0, 5); m_uiMovementTimer = 14000; m_pPointData = GetMoveData(); m_uiFireballTimer = 15000; m_uiWhelpTimer = 60000; m_uiLairGuardTimer = 60000; m_uiDeepBreathTimer = 85000; m_uiBellowingRoarTimer = 30000; Summons.DespawnAll(); m_uiSummonWhelpCount = 0; m_bIsMoving = false; if (m_instance) { m_instance->SetData(DATA_ONYXIA, NOT_STARTED); m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); m_instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); me->SetInCombatWithZone(); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); if (m_instance) { m_instance->SetData(DATA_ONYXIA, IN_PROGRESS); m_instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } } void JustDied(Unit* /*killer*/) { if (m_instance) m_instance->SetData(DATA_ONYXIA, DONE); Summons.DespawnAll(); } void JustSummoned(Creature* summoned) { summoned->SetInCombatWithZone(); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) summoned->AI()->AttackStart(target); switch (summoned->GetEntry()) { case NPC_WHELP: ++m_uiSummonWhelpCount; break; case NPC_LAIRGUARD: summoned->setActive(true); break; } Summons.Summon(summoned); } void SummonedCreatureDespawn(Creature* summon) { Summons.Despawn(summon); } void KilledUnit(Unit* /*victim*/) { DoScriptText(SAY_KILL, me); } void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpell) { if (pSpell->Id == SPELL_BREATH_EAST_TO_WEST || pSpell->Id == SPELL_BREATH_WEST_TO_EAST || pSpell->Id == SPELL_BREATH_SE_TO_NW || pSpell->Id == SPELL_BREATH_NW_TO_SE || pSpell->Id == SPELL_BREATH_SW_TO_NE || pSpell->Id == SPELL_BREATH_NE_TO_SW) { m_pPointData = GetMoveData(); m_uiMovePoint = m_pPointData->uiLocIdEnd; me->SetSpeed(MOVE_FLIGHT, 1.5f); me->GetMotionMaster()->MovePoint(8, MiddleRoomLocation); } } void MovementInform(uint32 type, uint32 id) { if (type == POINT_MOTION_TYPE) { switch (id) { case 8: m_pPointData = GetMoveData(); if (m_pPointData) { me->SetSpeed(MOVE_FLIGHT, 1.0f); me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); } break; case 9: me->GetMotionMaster()->MoveChase(me->getVictim()); m_uiBellowingRoarTimer = 1000; break; case 10: me->SetFlying(true); me->GetMotionMaster()->MovePoint(11, Phase2Location.GetPositionX(), Phase2Location.GetPositionY(), Phase2Location.GetPositionZ()+25); me->SetSpeed(MOVE_FLIGHT, 1.0f); DoScriptText(SAY_PHASE_2_TRANS, me); if (m_instance) m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); m_uiWhelpTimer = 5000; m_uiLairGuardTimer = 15000; break; case 11: if (m_pPointData) me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); me->GetMotionMaster()->Clear(false); me->GetMotionMaster()->MoveIdle(); break; default: m_bIsMoving = false; break; } } } void SpellHitTarget(Unit* target, const SpellEntry* pSpell) { //Workaround - Couldn't find a way to group this spells (All Eruption) if (((pSpell->Id >= 17086 && pSpell->Id <= 17095) || (pSpell->Id == 17097) || (pSpell->Id >= 18351 && pSpell->Id <= 18361) || (pSpell->Id >= 18564 && pSpell->Id <= 18576) || (pSpell->Id >= 18578 && pSpell->Id <= 18607) || (pSpell->Id == 18609) || (pSpell->Id >= 18611 && pSpell->Id <= 18628) || (pSpell->Id >= 21132 && pSpell->Id <= 21133) || (pSpell->Id >= 21135 && pSpell->Id <= 21139) || (pSpell->Id >= 22191 && pSpell->Id <= 22202) || (pSpell->Id >= 22267 && pSpell->Id <= 22268)) && (target->GetTypeId() == TYPEID_PLAYER)) { if (m_instance) { m_instance->SetData(DATA_SHE_DEEP_BREATH_MORE, FAIL); } } } sOnyxMove* GetMoveData() { uint32 uiMaxCount = sizeof(aMoveData)/sizeof(sOnyxMove); for (uint32 i = 0; i < uiMaxCount; ++i) { if (aMoveData[i].uiLocId == m_uiMovePoint) return &aMoveData[i]; } return NULL; } void SetNextRandomPoint() { uint32 uiMaxCount = sizeof(aMoveData)/sizeof(sOnyxMove); uint32 iTemp = rand()%(uiMaxCount-1); if (iTemp >= m_uiMovePoint) ++iTemp; m_uiMovePoint = iTemp; } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; //Common to PHASE_START && PHASE_END if (m_uiPhase == PHASE_START || m_uiPhase == PHASE_END) { //Specific to PHASE_START || PHASE_END if (m_uiPhase == PHASE_START) { if (HealthBelowPct(60)) { SetCombatMovement(false); m_uiPhase = PHASE_BREATH; me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_EFFECT,SPELL_EFFECT_ATTACK_ME, true); me->GetMotionMaster()->MovePoint(10, Phase2Location); return; } } else { if (m_uiBellowingRoarTimer <= uiDiff) { DoCastVictim(SPELL_BELLOWING_ROAR); // Eruption GameObject* pFloor = NULL; Trinity::GameObjectInRangeCheck check(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 15); Trinity::GameObjectLastSearcher<Trinity::GameObjectInRangeCheck> searcher(me, pFloor, check); me->VisitNearbyGridObject(30, searcher); if (m_instance && pFloor) m_instance->SetData64(DATA_FLOOR_ERUPTION_GUID, pFloor->GetGUID()); m_uiBellowingRoarTimer = 30000; } else m_uiBellowingRoarTimer -= uiDiff; } if (m_uiFlameBreathTimer <= uiDiff) { DoCastVictim(SPELL_FLAME_BREATH); m_uiFlameBreathTimer = urand(10000, 20000); } else m_uiFlameBreathTimer -= uiDiff; if (m_uiTailSweepTimer <= uiDiff) { DoCastAOE(SPELL_TAIL_SWEEP); m_uiTailSweepTimer = urand(15000, 20000); } else m_uiTailSweepTimer -= uiDiff; if (m_uiCleaveTimer <= uiDiff) { DoCastVictim(SPELL_CLEAVE); m_uiCleaveTimer = urand(2000, 5000); } else m_uiCleaveTimer -= uiDiff; if (m_uiWingBuffetTimer <= uiDiff) { DoCastVictim(SPELL_WING_BUFFET); m_uiWingBuffetTimer = urand(15000, 30000); } else m_uiWingBuffetTimer -= uiDiff; DoMeleeAttackIfReady(); } else { if (HealthBelowPct(40)) { m_uiPhase = PHASE_END; if (m_instance) m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); DoScriptText(SAY_PHASE_3_TRANS, me); SetCombatMovement(true); me->SetFlying(false); m_bIsMoving = false; me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, false); me->ApplySpellImmune(0, IMMUNITY_EFFECT,SPELL_EFFECT_ATTACK_ME, false); me->GetMotionMaster()->MovePoint(9,me->GetHomePosition()); return; } if (m_uiDeepBreathTimer <= uiDiff) { if (!m_bIsMoving) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); DoScriptText(EMOTE_BREATH, me); DoCast(me, m_pPointData->uiSpellId); m_uiDeepBreathTimer = 70000; } } else m_uiDeepBreathTimer -= uiDiff; if (m_uiMovementTimer <= uiDiff) { if (!m_bIsMoving) { SetNextRandomPoint(); m_pPointData = GetMoveData(); if (!m_pPointData) return; me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); m_bIsMoving = true; m_uiMovementTimer = 25000; } } else m_uiMovementTimer -= uiDiff; if (m_uiFireballTimer <= uiDiff) { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() != POINT_MOTION_TYPE) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_FIREBALL); m_uiFireballTimer = 8000; } } else m_uiFireballTimer -= uiDiff; if (m_uiLairGuardTimer <= uiDiff) { me->SummonCreature(NPC_LAIRGUARD, aSpawnLocations[2].GetPositionX(), aSpawnLocations[2].GetPositionY(), aSpawnLocations[2].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); m_uiLairGuardTimer = 30000; } else m_uiLairGuardTimer -= uiDiff; if (m_uiWhelpTimer <= uiDiff) { me->SummonCreature(NPC_WHELP, aSpawnLocations[0].GetPositionX(), aSpawnLocations[0].GetPositionY(), aSpawnLocations[0].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_WHELP, aSpawnLocations[1].GetPositionX(), aSpawnLocations[1].GetPositionY(), aSpawnLocations[1].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); if (m_uiSummonWhelpCount >= RAID_MODE(20, 40)) { m_uiSummonWhelpCount = 0; m_uiWhelpTimer = 90000; } else m_uiWhelpTimer = 500; } else m_uiWhelpTimer -= uiDiff; } } }; }; class npc_onyxia_lairguard : public CreatureScript { public: npc_onyxia_lairguard() : CreatureScript("npc_onyxia_lairguard") { } CreatureAI* GetAI(Creature* creature) const { return new npc_onyxia_lairguardAI(creature); } struct npc_onyxia_lairguardAI : public ScriptedAI { npc_onyxia_lairguardAI(Creature* creature) : ScriptedAI(creature) { m_instance = creature->GetInstanceScript(); Reset(); } InstanceScript* m_instance; uint32 m_uiLairGuardCleaveTimer; bool novadone; bool ignitedone; void Reset() { novadone = false; ignitedone = false; m_uiLairGuardCleaveTimer = urand(5000, 10000); } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STAT_CASTING)) return; if (!ignitedone) { DoCast(me, SPELL_LAIRGUARDIGNITE); ignitedone = true; } if (!novadone && HealthBelowPct(25)) { DoCast(me, SPELL_LAIRGUARDBLASTNOVA, true); novadone = true; } if (m_uiLairGuardCleaveTimer <= uiDiff) { DoCast(me->getVictim(), SPELL_LAIRGUARDCLEAVE); m_uiLairGuardCleaveTimer = urand(5000, 10000); } else m_uiLairGuardCleaveTimer -= uiDiff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_onyxia() { new boss_onyxia(); new npc_onyxia_lairguard(); }
34.550775
192
0.506825
FrenchCORE
eb1e0ebbe1b88faf7c231da8b4c74218249a8e80
3,941
cpp
C++
src/core/technology.cpp
awlck/stellaris-stat-viewer
454d0286b07bcdf2b1b519d6a62ca9c569abc468
[ "Apache-2.0" ]
2
2019-05-28T13:43:33.000Z
2019-06-06T22:08:55.000Z
src/core/technology.cpp
awlck/stellaris-stat-viewer
454d0286b07bcdf2b1b519d6a62ca9c569abc468
[ "Apache-2.0" ]
8
2019-03-19T11:44:46.000Z
2019-06-03T11:43:07.000Z
src/core/technology.cpp
awlck/stellaris-stat-viewer
454d0286b07bcdf2b1b519d6a62ca9c569abc468
[ "Apache-2.0" ]
1
2020-03-08T21:02:35.000Z
2020-03-08T21:02:35.000Z
/* core/technology.cpp: Extracting technology information from an AST. * * Copyright 2019 Adrian "ArdiMaster" Welcker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "technology.h" #include "model_private_macros.h" #include "parser.h" using Parsing::AstNode; namespace Galaxy { Technology::Technology(QObject *parent) : QObject(parent) {} const QString &Technology::getName() const { return name; } const QStringList &Technology::getRequirements() const { return requirements; } bool Technology::getIsStartingTech() const { return isStartingTech; } bool Technology::getIsRare() const { return isRare; } bool Technology::getIsRepeatable() const { return isRepeatable; } bool Technology::getIsWeightZero() const { return isWeightZero; } const QList<WeightModifier>& Technology::getWeightModifyingTechs() const { return weightModifyingTechs; } int Technology::getTier() const { return tier; } TechArea Technology::getArea() const { return area; } Technology *Technology::createFromAst(const Parsing::AstNode *node, QObject *parent) { Technology *state = new Technology(parent); state->name = QString(node->myName); AstNode *areaNode = node->findChildWithName("area"); CHECK_PTR(areaNode); if (qstrcmp(areaNode->val.Str, "engineering") == 0) state->area = TechArea::Engineering; else if (qstrcmp(areaNode->val.Str, "society") == 0) state->area = TechArea::Society; else if (qstrcmp(areaNode->val.Str, "physics") == 0) state->area = TechArea::Physics; else { delete state; return nullptr; } AstNode *startTechNode = node->findChildWithName("start_tech"); state->isStartingTech = startTechNode ? startTechNode->val.Bool : false; AstNode *rareNode = node->findChildWithName("is_rare"); state->isRare = rareNode ? rareNode->val.Bool : false; state->isRepeatable = state->name.startsWith("tech_repeatable_"); if (!state->isRepeatable) { AstNode *tierNode = node->findChildWithName("tier"); CHECK_PTR(tierNode); state->tier = tierNode->val.Int; } else state->tier = -1; AstNode *prerequisitesNode = node->findChildWithName("prerequisites"); if (prerequisitesNode && prerequisitesNode->type == Parsing::NT_STRINGLIST) { ITERATE_CHILDREN(prerequisitesNode, aPrerequisite) { state->requirements.append(aPrerequisite->val.Str); } } AstNode *weightNode = node->findChildWithName("weight"); state->isWeightZero = !weightNode || (weightNode->type == Parsing::NT_INT && weightNode->val.Int == 0); AstNode *weightModifierNode = node->findChildWithName("weight_modifier"); if (weightModifierNode) { ITERATE_CHILDREN(weightModifierNode, modifier) { if (qstrcmp(modifier->myName, "modifier") == 0) { if (modifier->countChildren() != 2) continue; AstNode *factorNode = modifier->findChildWithName("factor"); AstNode *hasTechNode = modifier->findChildWithName("has_technology"); if (!factorNode || !hasTechNode) continue; if (hasTechNode->type != Parsing::NT_STRING) continue; switch (factorNode->type) { case Parsing::NT_INT: state->weightModifyingTechs.append({QString(hasTechNode->val.Str), (double) factorNode->val.Int}); break; case Parsing::NT_DOUBLE: state->weightModifyingTechs.append({QString(hasTechNode->val.Str), factorNode->val.Double}); break; default: continue; } } } } return state; } }
32.04065
105
0.710226
awlck
eb205bbca4f4e7a114831c2b60866cb1ce2789ad
9,561
cpp
C++
Interaction/mafDeviceButtonsPadMouse.cpp
FusionBox2/MAF2
b576955f4f6b954467021f12baedfebcaf79a382
[ "Apache-2.0" ]
1
2018-01-23T09:13:40.000Z
2018-01-23T09:13:40.000Z
Interaction/mafDeviceButtonsPadMouse.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
Interaction/mafDeviceButtonsPadMouse.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
3
2020-09-24T16:04:53.000Z
2020-09-24T16:50:30.000Z
/*========================================================================= Program: MAF2 Module: mafDeviceButtonsPadMouse Authors: Marco Petrone Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "mafDeviceButtonsPadMouse.h" #include "mafEventBase.h" #include "mafView.h" #include "mafSceneGraph.h" #include "mafRWIBase.h" #include "mafEventInteraction.h" #include "mmuIdFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" //------------------------------------------------------------------------------ // Events //------------------------------------------------------------------------------ // MAF_ID_IMP(mafDeviceButtonsPadMouse::MOUSE_2D_MOVE) // MAF_ID_IMP(mafDeviceButtonsPadMouse::MOUSE_CHAR_EVENT) // MAF_ID_IMP(mafDeviceButtonsPadMouse::MOUSE_DCLICK) //------------------------------------------------------------------------------ mafCxxTypeMacro(mafDeviceButtonsPadMouse) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ mafDeviceButtonsPadMouse::mafDeviceButtonsPadMouse() //------------------------------------------------------------------------------ { SetThreaded(0); m_LastPosition[0] = m_LastPosition[1] = 0; m_ButtonState[0] = m_ButtonState[1] = m_ButtonState[2] = 0; m_SelectedView = NULL; m_SelectedRWI = NULL; m_UpdateRwiInOnMoveFlag = false; m_CollaborateStatus = false; m_FromRemote = false; m_ButtonPressed = false; } //------------------------------------------------------------------------------ mafDeviceButtonsPadMouse::~mafDeviceButtonsPadMouse() //------------------------------------------------------------------------------ { } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::OnEvent(mafEventBase *event) //------------------------------------------------------------------------------ { assert(event); mafID id = event->GetId(); mafEventInteraction *e = mafEventInteraction::SafeDownCast(event); if (id == GetMouse2DMoveId()) { double pos[2]; e->Get2DPosition(pos); if (m_UpdateRwiInOnMoveFlag) { m_SelectedRWI = (mafRWIBase *)event->GetSender(); } SetLastPosition(pos[0],pos[1],e->GetModifiers()); } else if (id == GetButtonDownId() || id == GetMouseDClickId()) { // store the Selected RWI is needed for compounded view m_ButtonPressed = true; e->Get2DPosition(m_LastPosition); m_SelectedRWI = (mafRWIBase *)event->GetSender(); e->SetSender(this); InvokeEvent(e,MCH_INPUT); if (m_CollaborateStatus) { double disp[2]; e->Get2DPosition(disp); DisplayToNormalizedDisplay(disp); mafEventInteraction remoteEv; remoteEv.SetSender(this); remoteEv.SetId(id); remoteEv.SetButton(e->GetButton()); remoteEv.Set2DPosition(disp); remoteEv.SetModifiers(e->GetModifiers()); InvokeEvent(remoteEv,REMOTE_COMMAND_CHANNEL); } } else if (id == GetButtonUpId()) { m_ButtonPressed = false; e->Get2DPosition(m_LastPosition); e->SetSender(this); InvokeEvent(e,MCH_INPUT); if (m_CollaborateStatus) { double disp[2]; e->Get2DPosition(disp); DisplayToNormalizedDisplay(disp); mafEventInteraction remoteEv; remoteEv.SetSender(this); remoteEv.SetId(GetButtonUpId()); remoteEv.SetButton(e->GetButton()); remoteEv.Set2DPosition(disp); remoteEv.SetModifiers(e->GetModifiers()); InvokeEvent(remoteEv,REMOTE_COMMAND_CHANNEL); } } else if (id == VIEW_SELECT) { mafEvent *ev = mafEvent::SafeDownCast(event); if (ev) { m_SelectedView = ev->GetView(); } } else if (id == GetMouseCharEventId()) { mafEvent *ev = mafEvent::SafeDownCast(event); if (ev) { unsigned char key = (unsigned char)ev->GetArg(); mafEventInteraction ei(this,GetMouseCharEventId()); ei.SetKey(key); InvokeEvent(&ei,MCH_INPUT); } } } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::SetLastPosition(double x,double y,unsigned long modifiers) //------------------------------------------------------------------------------ { m_LastPosition[0] = x; m_LastPosition[1] = y; if (m_CollaborateStatus && m_SelectedRWI && !m_FromRemote && m_ButtonPressed) { double disp[2]; disp[0] = (double)x; disp[1] = (double)y; DisplayToNormalizedDisplay(disp); mafEventInteraction remoteEv; remoteEv.SetSender(this); remoteEv.SetId(GetMouse2DMoveId()); remoteEv.SetModifiers(modifiers); remoteEv.Set2DPosition(disp); InvokeEvent(remoteEv,REMOTE_COMMAND_CHANNEL); } m_FromRemote = false; // create a new event with last position mafEventInteraction e(this,GetMouse2DMoveId(),x,y); e.SetModifiers(modifiers); InvokeEvent(e,MCH_INPUT); } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::SendButtonEvent(mafEventInteraction *event) //------------------------------------------------------------------------------ { event->Set2DPosition(GetLastPosition()); Superclass::SendButtonEvent(event); } //------------------------------------------------------------------------------ vtkRenderer *mafDeviceButtonsPadMouse::GetRenderer() //------------------------------------------------------------------------------ { vtkRenderer *r = NULL; if (m_SelectedRWI) { r = m_SelectedRWI->FindPokedRenderer((int)m_LastPosition[0],(int)m_LastPosition[1]); } return r; } //------------------------------------------------------------------------------ mafView *mafDeviceButtonsPadMouse::GetView() //------------------------------------------------------------------------------ { return m_SelectedView; } //------------------------------------------------------------------------------ vtkRenderWindowInteractor *mafDeviceButtonsPadMouse::GetInteractor() //------------------------------------------------------------------------------ { if (m_SelectedRWI) return m_SelectedRWI->GetRenderWindow()->GetInteractor(); return (vtkRenderWindowInteractor *)NULL; } //------------------------------------------------------------------------------ mafRWIBase *mafDeviceButtonsPadMouse::GetRWI() //------------------------------------------------------------------------------ { return m_SelectedRWI; } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::DisplayToNormalizedDisplay(double display[2]) //------------------------------------------------------------------------------ { vtkRenderer *r = GetRenderer(); if (r == NULL) {return;} int *size; /* get physical window dimensions */ size = r->GetVTKWindow()->GetSize(); display[0] -= (size[0]*.5); display[1] -= (size[1]*.5); display[0] = display[0]/size[1]; display[1] = display[1]/size[1]; //r->DisplayToNormalizedDisplay(display[0],display[1]); } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::NormalizedDisplayToDisplay(double normalized[2]) //------------------------------------------------------------------------------ { vtkRenderer *r = GetRenderer(); if (r == NULL) {return;} int *size; /* get physical window dimensions */ size = r->GetVTKWindow()->GetSize(); normalized[0] = normalized[0]*size[1]; normalized[1] = normalized[1]*size[1]; normalized[0] += (size[0]*.5); normalized[1] += (size[1]*.5); // r->NormalizedDisplayToDisplay(normalized[0],normalized[1]); } //------------------------------------------------------------------------------ mafID mafDeviceButtonsPadMouse::GetMouse2DMoveId() //------------------------------------------------------------------------------ { static const mafID mouse2DMoveId = mmuIdFactory::GetNextId("MOUSE_2D_MOVE"); return mouse2DMoveId; } //------------------------------------------------------------------------------ mafID mafDeviceButtonsPadMouse::GetMouseCharEventId() //------------------------------------------------------------------------------ { static const mafID mouseCharEventId = mmuIdFactory::GetNextId("MOUSE_CHAR_EVENT"); return mouseCharEventId; } //------------------------------------------------------------------------------ mafID mafDeviceButtonsPadMouse::GetMouseDClickId() //------------------------------------------------------------------------------ { static const mafID mouseDClickId = mmuIdFactory::GetNextId("MOUSE_DCLICK"); return mouseDClickId; }
33.904255
89
0.494927
FusionBox2
eb27500b17c452bbb0018f17b819944c6051a4ad
86,599
cpp
C++
VirtualBox-5.0.0/src/VBox/VMM/VMMAll/CPUMAllRegs.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
1
2015-04-30T14:18:45.000Z
2015-04-30T14:18:45.000Z
VirtualBox-5.0.0/src/VBox/VMM/VMMAll/CPUMAllRegs.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
VirtualBox-5.0.0/src/VBox/VMM/VMMAll/CPUMAllRegs.cpp
egraba/vbox_openbsd
6cb82f2eed1fa697d088cecc91722b55b19713c2
[ "MIT" ]
null
null
null
/* $Id: CPUMAllRegs.cpp $ */ /** @file * CPUM - CPU Monitor(/Manager) - Getters and Setters. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_CPUM #include <VBox/vmm/cpum.h> #include <VBox/vmm/patm.h> #include <VBox/vmm/dbgf.h> #include <VBox/vmm/pdm.h> #include <VBox/vmm/pgm.h> #include <VBox/vmm/mm.h> #include <VBox/vmm/em.h> #if defined(VBOX_WITH_RAW_MODE) && !defined(IN_RING0) # include <VBox/vmm/selm.h> #endif #include "CPUMInternal.h" #include <VBox/vmm/vm.h> #include <VBox/err.h> #include <VBox/dis.h> #include <VBox/log.h> #include <VBox/vmm/hm.h> #include <VBox/vmm/tm.h> #include <iprt/assert.h> #include <iprt/asm.h> #include <iprt/asm-amd64-x86.h> #ifdef IN_RING3 #include <iprt/thread.h> #endif /** Disable stack frame pointer generation here. */ #if defined(_MSC_VER) && !defined(DEBUG) # pragma optimize("y", off) #endif AssertCompile2MemberOffsets(VM, cpum.s.HostFeatures, cpum.ro.HostFeatures); AssertCompile2MemberOffsets(VM, cpum.s.GuestFeatures, cpum.ro.GuestFeatures); /******************************************************************************* * Defined Constants And Macros * *******************************************************************************/ /** * Converts a CPUMCPU::Guest pointer into a VMCPU pointer. * * @returns Pointer to the Virtual CPU. * @param a_pGuestCtx Pointer to the guest context. */ #define CPUM_GUEST_CTX_TO_VMCPU(a_pGuestCtx) RT_FROM_MEMBER(a_pGuestCtx, VMCPU, cpum.s.Guest) /** * Lazily loads the hidden parts of a selector register when using raw-mode. */ #if defined(VBOX_WITH_RAW_MODE) && !defined(IN_RING0) # define CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(a_pVCpu, a_pSReg) \ do \ { \ if (!CPUMSELREG_ARE_HIDDEN_PARTS_VALID(a_pVCpu, a_pSReg)) \ cpumGuestLazyLoadHiddenSelectorReg(a_pVCpu, a_pSReg); \ } while (0) #else # define CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(a_pVCpu, a_pSReg) \ Assert(CPUMSELREG_ARE_HIDDEN_PARTS_VALID(a_pVCpu, a_pSReg)); #endif #ifdef VBOX_WITH_RAW_MODE_NOT_R0 /** * Does the lazy hidden selector register loading. * * @param pVCpu The current Virtual CPU. * @param pSReg The selector register to lazily load hidden parts of. */ static void cpumGuestLazyLoadHiddenSelectorReg(PVMCPU pVCpu, PCPUMSELREG pSReg) { Assert(!CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, pSReg)); Assert(!HMIsEnabled(pVCpu->CTX_SUFF(pVM))); Assert((uintptr_t)(pSReg - &pVCpu->cpum.s.Guest.es) < X86_SREG_COUNT); if (pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { /* V8086 mode - Tightly controlled environment, no question about the limit or flags. */ pSReg->Attr.u = 0; pSReg->Attr.n.u4Type = pSReg == &pVCpu->cpum.s.Guest.cs ? X86_SEL_TYPE_ER_ACC : X86_SEL_TYPE_RW_ACC; pSReg->Attr.n.u1DescType = 1; /* code/data segment */ pSReg->Attr.n.u2Dpl = 3; pSReg->Attr.n.u1Present = 1; pSReg->u32Limit = 0x0000ffff; pSReg->u64Base = (uint32_t)pSReg->Sel << 4; pSReg->ValidSel = pSReg->Sel; pSReg->fFlags = CPUMSELREG_FLAGS_VALID; /** @todo Check what the accessed bit should be (VT-x and AMD-V). */ } else if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) { /* Real mode - leave the limit and flags alone here, at least for now. */ pSReg->u64Base = (uint32_t)pSReg->Sel << 4; pSReg->ValidSel = pSReg->Sel; pSReg->fFlags = CPUMSELREG_FLAGS_VALID; } else { /* Protected mode - get it from the selector descriptor tables. */ if (!(pSReg->Sel & X86_SEL_MASK_OFF_RPL)) { Assert(!CPUMIsGuestInLongMode(pVCpu)); pSReg->Sel = 0; pSReg->u64Base = 0; pSReg->u32Limit = 0; pSReg->Attr.u = 0; pSReg->ValidSel = 0; pSReg->fFlags = CPUMSELREG_FLAGS_VALID; /** @todo see todo in iemHlpLoadNullDataSelectorProt. */ } else SELMLoadHiddenSelectorReg(pVCpu, &pVCpu->cpum.s.Guest, pSReg); } } /** * Makes sure the hidden CS and SS selector registers are valid, loading them if * necessary. * * @param pVCpu The current virtual CPU. */ VMM_INT_DECL(void) CPUMGuestLazyLoadHiddenCsAndSs(PVMCPU pVCpu) { CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.ss); } /** * Loads a the hidden parts of a selector register. * * @param pVCpu The current virtual CPU. */ VMM_INT_DECL(void) CPUMGuestLazyLoadHiddenSelectorReg(PVMCPU pVCpu, PCPUMSELREG pSReg) { CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, pSReg); } #endif /* VBOX_WITH_RAW_MODE_NOT_R0 */ /** * Obsolete. * * We don't support nested hypervisor context interrupts or traps. Life is much * simpler when we don't. It's also slightly faster at times. * * @param pVM Handle to the virtual machine. */ VMMDECL(PCCPUMCTXCORE) CPUMGetHyperCtxCore(PVMCPU pVCpu) { return CPUMCTX2CORE(&pVCpu->cpum.s.Hyper); } /** * Gets the pointer to the hypervisor CPU context structure of a virtual CPU. * * @param pVCpu Pointer to the VMCPU. */ VMMDECL(PCPUMCTX) CPUMGetHyperCtxPtr(PVMCPU pVCpu) { return &pVCpu->cpum.s.Hyper; } VMMDECL(void) CPUMSetHyperGDTR(PVMCPU pVCpu, uint32_t addr, uint16_t limit) { pVCpu->cpum.s.Hyper.gdtr.cbGdt = limit; pVCpu->cpum.s.Hyper.gdtr.pGdt = addr; } VMMDECL(void) CPUMSetHyperIDTR(PVMCPU pVCpu, uint32_t addr, uint16_t limit) { pVCpu->cpum.s.Hyper.idtr.cbIdt = limit; pVCpu->cpum.s.Hyper.idtr.pIdt = addr; } VMMDECL(void) CPUMSetHyperCR3(PVMCPU pVCpu, uint32_t cr3) { pVCpu->cpum.s.Hyper.cr3 = cr3; #ifdef IN_RC /* Update the current CR3. */ ASMSetCR3(cr3); #endif } VMMDECL(uint32_t) CPUMGetHyperCR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.cr3; } VMMDECL(void) CPUMSetHyperCS(PVMCPU pVCpu, RTSEL SelCS) { pVCpu->cpum.s.Hyper.cs.Sel = SelCS; } VMMDECL(void) CPUMSetHyperDS(PVMCPU pVCpu, RTSEL SelDS) { pVCpu->cpum.s.Hyper.ds.Sel = SelDS; } VMMDECL(void) CPUMSetHyperES(PVMCPU pVCpu, RTSEL SelES) { pVCpu->cpum.s.Hyper.es.Sel = SelES; } VMMDECL(void) CPUMSetHyperFS(PVMCPU pVCpu, RTSEL SelFS) { pVCpu->cpum.s.Hyper.fs.Sel = SelFS; } VMMDECL(void) CPUMSetHyperGS(PVMCPU pVCpu, RTSEL SelGS) { pVCpu->cpum.s.Hyper.gs.Sel = SelGS; } VMMDECL(void) CPUMSetHyperSS(PVMCPU pVCpu, RTSEL SelSS) { pVCpu->cpum.s.Hyper.ss.Sel = SelSS; } VMMDECL(void) CPUMSetHyperESP(PVMCPU pVCpu, uint32_t u32ESP) { pVCpu->cpum.s.Hyper.esp = u32ESP; } VMMDECL(void) CPUMSetHyperEDX(PVMCPU pVCpu, uint32_t u32ESP) { pVCpu->cpum.s.Hyper.esp = u32ESP; } VMMDECL(int) CPUMSetHyperEFlags(PVMCPU pVCpu, uint32_t Efl) { pVCpu->cpum.s.Hyper.eflags.u32 = Efl; return VINF_SUCCESS; } VMMDECL(void) CPUMSetHyperEIP(PVMCPU pVCpu, uint32_t u32EIP) { pVCpu->cpum.s.Hyper.eip = u32EIP; } /** * Used by VMMR3RawRunGC to reinitialize the general raw-mode context registers, * EFLAGS and EIP prior to resuming guest execution. * * All general register not given as a parameter will be set to 0. The EFLAGS * register will be set to sane values for C/C++ code execution with interrupts * disabled and IOPL 0. * * @param pVCpu The current virtual CPU. * @param u32EIP The EIP value. * @param u32ESP The ESP value. * @param u32EAX The EAX value. * @param u32EDX The EDX value. */ VMM_INT_DECL(void) CPUMSetHyperState(PVMCPU pVCpu, uint32_t u32EIP, uint32_t u32ESP, uint32_t u32EAX, uint32_t u32EDX) { pVCpu->cpum.s.Hyper.eip = u32EIP; pVCpu->cpum.s.Hyper.esp = u32ESP; pVCpu->cpum.s.Hyper.eax = u32EAX; pVCpu->cpum.s.Hyper.edx = u32EDX; pVCpu->cpum.s.Hyper.ecx = 0; pVCpu->cpum.s.Hyper.ebx = 0; pVCpu->cpum.s.Hyper.ebp = 0; pVCpu->cpum.s.Hyper.esi = 0; pVCpu->cpum.s.Hyper.edi = 0; pVCpu->cpum.s.Hyper.eflags.u = X86_EFL_1; } VMMDECL(void) CPUMSetHyperTR(PVMCPU pVCpu, RTSEL SelTR) { pVCpu->cpum.s.Hyper.tr.Sel = SelTR; } VMMDECL(void) CPUMSetHyperLDTR(PVMCPU pVCpu, RTSEL SelLDTR) { pVCpu->cpum.s.Hyper.ldtr.Sel = SelLDTR; } /** @MAYBE_LOAD_DRx * Macro for updating DRx values in raw-mode and ring-0 contexts. */ #ifdef IN_RING0 # if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS) # ifndef VBOX_WITH_HYBRID_32BIT_KERNEL # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ if (!CPUMIsGuestInLongModeEx(&(a_pVCpu)->cpum.s.Guest)) \ a_fnLoad(a_uValue); \ else \ (a_pVCpu)->cpum.s.fUseFlags |= CPUM_SYNC_DEBUG_REGS_HYPER; \ } while (0) # else # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ /** @todo we're not loading the correct guest value here! */ \ a_fnLoad(a_uValue); \ } while (0) # endif # else # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ a_fnLoad(a_uValue); \ } while (0) # endif #elif defined(IN_RC) # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ if ((a_pVCpu)->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER) \ { a_fnLoad(a_uValue); } \ } while (0) #else # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) do { } while (0) #endif VMMDECL(void) CPUMSetHyperDR0(PVMCPU pVCpu, RTGCUINTREG uDr0) { pVCpu->cpum.s.Hyper.dr[0] = uDr0; MAYBE_LOAD_DRx(pVCpu, ASMSetDR0, uDr0); } VMMDECL(void) CPUMSetHyperDR1(PVMCPU pVCpu, RTGCUINTREG uDr1) { pVCpu->cpum.s.Hyper.dr[1] = uDr1; MAYBE_LOAD_DRx(pVCpu, ASMSetDR1, uDr1); } VMMDECL(void) CPUMSetHyperDR2(PVMCPU pVCpu, RTGCUINTREG uDr2) { pVCpu->cpum.s.Hyper.dr[2] = uDr2; MAYBE_LOAD_DRx(pVCpu, ASMSetDR2, uDr2); } VMMDECL(void) CPUMSetHyperDR3(PVMCPU pVCpu, RTGCUINTREG uDr3) { pVCpu->cpum.s.Hyper.dr[3] = uDr3; MAYBE_LOAD_DRx(pVCpu, ASMSetDR3, uDr3); } VMMDECL(void) CPUMSetHyperDR6(PVMCPU pVCpu, RTGCUINTREG uDr6) { pVCpu->cpum.s.Hyper.dr[6] = uDr6; } VMMDECL(void) CPUMSetHyperDR7(PVMCPU pVCpu, RTGCUINTREG uDr7) { pVCpu->cpum.s.Hyper.dr[7] = uDr7; #ifdef IN_RC MAYBE_LOAD_DRx(pVCpu, ASMSetDR7, uDr7); #endif } VMMDECL(RTSEL) CPUMGetHyperCS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.cs.Sel; } VMMDECL(RTSEL) CPUMGetHyperDS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ds.Sel; } VMMDECL(RTSEL) CPUMGetHyperES(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.es.Sel; } VMMDECL(RTSEL) CPUMGetHyperFS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.fs.Sel; } VMMDECL(RTSEL) CPUMGetHyperGS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.gs.Sel; } VMMDECL(RTSEL) CPUMGetHyperSS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ss.Sel; } VMMDECL(uint32_t) CPUMGetHyperEAX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.eax; } VMMDECL(uint32_t) CPUMGetHyperEBX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ebx; } VMMDECL(uint32_t) CPUMGetHyperECX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ecx; } VMMDECL(uint32_t) CPUMGetHyperEDX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.edx; } VMMDECL(uint32_t) CPUMGetHyperESI(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.esi; } VMMDECL(uint32_t) CPUMGetHyperEDI(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.edi; } VMMDECL(uint32_t) CPUMGetHyperEBP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ebp; } VMMDECL(uint32_t) CPUMGetHyperESP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.esp; } VMMDECL(uint32_t) CPUMGetHyperEFlags(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.eflags.u32; } VMMDECL(uint32_t) CPUMGetHyperEIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.eip; } VMMDECL(uint64_t) CPUMGetHyperRIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.rip; } VMMDECL(uint32_t) CPUMGetHyperIDTR(PVMCPU pVCpu, uint16_t *pcbLimit) { if (pcbLimit) *pcbLimit = pVCpu->cpum.s.Hyper.idtr.cbIdt; return pVCpu->cpum.s.Hyper.idtr.pIdt; } VMMDECL(uint32_t) CPUMGetHyperGDTR(PVMCPU pVCpu, uint16_t *pcbLimit) { if (pcbLimit) *pcbLimit = pVCpu->cpum.s.Hyper.gdtr.cbGdt; return pVCpu->cpum.s.Hyper.gdtr.pGdt; } VMMDECL(RTSEL) CPUMGetHyperLDTR(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ldtr.Sel; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR0(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[0]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR1(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[1]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR2(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[2]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[3]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR6(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[6]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR7(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[7]; } /** * Gets the pointer to the internal CPUMCTXCORE structure. * This is only for reading in order to save a few calls. * * @param pVCpu Handle to the virtual cpu. */ VMMDECL(PCCPUMCTXCORE) CPUMGetGuestCtxCore(PVMCPU pVCpu) { return CPUMCTX2CORE(&pVCpu->cpum.s.Guest); } /** * Queries the pointer to the internal CPUMCTX structure. * * @returns The CPUMCTX pointer. * @param pVCpu Handle to the virtual cpu. */ VMMDECL(PCPUMCTX) CPUMQueryGuestCtxPtr(PVMCPU pVCpu) { return &pVCpu->cpum.s.Guest; } VMMDECL(int) CPUMSetGuestGDTR(PVMCPU pVCpu, uint64_t GCPtrBase, uint16_t cbLimit) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (!HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT); # endif #endif pVCpu->cpum.s.Guest.gdtr.cbGdt = cbLimit; pVCpu->cpum.s.Guest.gdtr.pGdt = GCPtrBase; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_GDTR; return VINF_SUCCESS; /* formality, consider it void. */ } VMMDECL(int) CPUMSetGuestIDTR(PVMCPU pVCpu, uint64_t GCPtrBase, uint16_t cbLimit) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (!HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_TRPM_SYNC_IDT); # endif #endif pVCpu->cpum.s.Guest.idtr.cbIdt = cbLimit; pVCpu->cpum.s.Guest.idtr.pIdt = GCPtrBase; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_IDTR; return VINF_SUCCESS; /* formality, consider it void. */ } VMMDECL(int) CPUMSetGuestTR(PVMCPU pVCpu, uint16_t tr) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (!HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS); # endif #endif pVCpu->cpum.s.Guest.tr.Sel = tr; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_TR; return VINF_SUCCESS; /* formality, consider it void. */ } VMMDECL(int) CPUMSetGuestLDTR(PVMCPU pVCpu, uint16_t ldtr) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if ( ( ldtr != 0 || pVCpu->cpum.s.Guest.ldtr.Sel != 0) && !HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT); # endif #endif pVCpu->cpum.s.Guest.ldtr.Sel = ldtr; /* The caller will set more hidden bits if it has them. */ pVCpu->cpum.s.Guest.ldtr.ValidSel = 0; pVCpu->cpum.s.Guest.ldtr.fFlags = 0; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_LDTR; return VINF_SUCCESS; /* formality, consider it void. */ } /** * Set the guest CR0. * * When called in GC, the hyper CR0 may be updated if that is * required. The caller only has to take special action if AM, * WP, PG or PE changes. * * @returns VINF_SUCCESS (consider it void). * @param pVCpu Handle to the virtual cpu. * @param cr0 The new CR0 value. */ VMMDECL(int) CPUMSetGuestCR0(PVMCPU pVCpu, uint64_t cr0) { #ifdef IN_RC /* * Check if we need to change hypervisor CR0 because * of math stuff. */ if ( (cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP)) != (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP))) { if (!(pVCpu->cpum.s.fUseFlags & CPUM_USED_FPU)) { /* * We haven't saved the host FPU state yet, so TS and MT are both set * and EM should be reflecting the guest EM (it always does this). */ if ((cr0 & X86_CR0_EM) != (pVCpu->cpum.s.Guest.cr0 & X86_CR0_EM)) { uint32_t HyperCR0 = ASMGetCR0(); AssertMsg((HyperCR0 & (X86_CR0_TS | X86_CR0_MP)) == (X86_CR0_TS | X86_CR0_MP), ("%#x\n", HyperCR0)); AssertMsg((HyperCR0 & X86_CR0_EM) == (pVCpu->cpum.s.Guest.cr0 & X86_CR0_EM), ("%#x\n", HyperCR0)); HyperCR0 &= ~X86_CR0_EM; HyperCR0 |= cr0 & X86_CR0_EM; Log(("CPUM: New HyperCR0=%#x\n", HyperCR0)); ASMSetCR0(HyperCR0); } # ifdef VBOX_STRICT else { uint32_t HyperCR0 = ASMGetCR0(); AssertMsg((HyperCR0 & (X86_CR0_TS | X86_CR0_MP)) == (X86_CR0_TS | X86_CR0_MP), ("%#x\n", HyperCR0)); AssertMsg((HyperCR0 & X86_CR0_EM) == (pVCpu->cpum.s.Guest.cr0 & X86_CR0_EM), ("%#x\n", HyperCR0)); } # endif } else { /* * Already saved the state, so we're just mirroring * the guest flags. */ uint32_t HyperCR0 = ASMGetCR0(); AssertMsg( (HyperCR0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP)) == (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP)), ("%#x %#x\n", HyperCR0, pVCpu->cpum.s.Guest.cr0)); HyperCR0 &= ~(X86_CR0_TS | X86_CR0_EM | X86_CR0_MP); HyperCR0 |= cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP); Log(("CPUM: New HyperCR0=%#x\n", HyperCR0)); ASMSetCR0(HyperCR0); } } #endif /* IN_RC */ /* * Check for changes causing TLB flushes (for REM). * The caller is responsible for calling PGM when appropriate. */ if ( (cr0 & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE)) != (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE))) pVCpu->cpum.s.fChanged |= CPUM_CHANGED_GLOBAL_TLB_FLUSH; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CR0; /* * Let PGM know if the WP goes from 0 to 1 (netware WP0+RO+US hack) */ if (((cr0 ^ pVCpu->cpum.s.Guest.cr0) & X86_CR0_WP) && (cr0 & X86_CR0_WP)) PGMCr0WpEnabled(pVCpu); pVCpu->cpum.s.Guest.cr0 = cr0 | X86_CR0_ET; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCR2(PVMCPU pVCpu, uint64_t cr2) { pVCpu->cpum.s.Guest.cr2 = cr2; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCR3(PVMCPU pVCpu, uint64_t cr3) { pVCpu->cpum.s.Guest.cr3 = cr3; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CR3; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCR4(PVMCPU pVCpu, uint64_t cr4) { /* * The CR4.OSXSAVE bit is reflected in CPUID(1).ECX[27]. */ if ( (cr4 & X86_CR4_OSXSAVE) != (pVCpu->cpum.s.Guest.cr4 & X86_CR4_OSXSAVE) ) { PVM pVM = pVCpu->CTX_SUFF(pVM); if (cr4 & X86_CR4_OSXSAVE) CPUMSetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_OSXSAVE); else CPUMClearGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_OSXSAVE); } if ( (cr4 & (X86_CR4_PGE | X86_CR4_PAE | X86_CR4_PSE)) != (pVCpu->cpum.s.Guest.cr4 & (X86_CR4_PGE | X86_CR4_PAE | X86_CR4_PSE))) pVCpu->cpum.s.fChanged |= CPUM_CHANGED_GLOBAL_TLB_FLUSH; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CR4; pVCpu->cpum.s.Guest.cr4 = cr4; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEFlags(PVMCPU pVCpu, uint32_t eflags) { pVCpu->cpum.s.Guest.eflags.u32 = eflags; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEIP(PVMCPU pVCpu, uint32_t eip) { pVCpu->cpum.s.Guest.eip = eip; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEAX(PVMCPU pVCpu, uint32_t eax) { pVCpu->cpum.s.Guest.eax = eax; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEBX(PVMCPU pVCpu, uint32_t ebx) { pVCpu->cpum.s.Guest.ebx = ebx; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestECX(PVMCPU pVCpu, uint32_t ecx) { pVCpu->cpum.s.Guest.ecx = ecx; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEDX(PVMCPU pVCpu, uint32_t edx) { pVCpu->cpum.s.Guest.edx = edx; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestESP(PVMCPU pVCpu, uint32_t esp) { pVCpu->cpum.s.Guest.esp = esp; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEBP(PVMCPU pVCpu, uint32_t ebp) { pVCpu->cpum.s.Guest.ebp = ebp; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestESI(PVMCPU pVCpu, uint32_t esi) { pVCpu->cpum.s.Guest.esi = esi; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEDI(PVMCPU pVCpu, uint32_t edi) { pVCpu->cpum.s.Guest.edi = edi; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestSS(PVMCPU pVCpu, uint16_t ss) { pVCpu->cpum.s.Guest.ss.Sel = ss; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCS(PVMCPU pVCpu, uint16_t cs) { pVCpu->cpum.s.Guest.cs.Sel = cs; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestDS(PVMCPU pVCpu, uint16_t ds) { pVCpu->cpum.s.Guest.ds.Sel = ds; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestES(PVMCPU pVCpu, uint16_t es) { pVCpu->cpum.s.Guest.es.Sel = es; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestFS(PVMCPU pVCpu, uint16_t fs) { pVCpu->cpum.s.Guest.fs.Sel = fs; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestGS(PVMCPU pVCpu, uint16_t gs) { pVCpu->cpum.s.Guest.gs.Sel = gs; return VINF_SUCCESS; } VMMDECL(void) CPUMSetGuestEFER(PVMCPU pVCpu, uint64_t val) { pVCpu->cpum.s.Guest.msrEFER = val; } VMMDECL(RTGCPTR) CPUMGetGuestIDTR(PVMCPU pVCpu, uint16_t *pcbLimit) { if (pcbLimit) *pcbLimit = pVCpu->cpum.s.Guest.idtr.cbIdt; return pVCpu->cpum.s.Guest.idtr.pIdt; } VMMDECL(RTSEL) CPUMGetGuestTR(PVMCPU pVCpu, PCPUMSELREGHID pHidden) { if (pHidden) *pHidden = pVCpu->cpum.s.Guest.tr; return pVCpu->cpum.s.Guest.tr.Sel; } VMMDECL(RTSEL) CPUMGetGuestCS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cs.Sel; } VMMDECL(RTSEL) CPUMGetGuestDS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ds.Sel; } VMMDECL(RTSEL) CPUMGetGuestES(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.es.Sel; } VMMDECL(RTSEL) CPUMGetGuestFS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.fs.Sel; } VMMDECL(RTSEL) CPUMGetGuestGS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.gs.Sel; } VMMDECL(RTSEL) CPUMGetGuestSS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ss.Sel; } VMMDECL(RTSEL) CPUMGetGuestLDTR(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ldtr.Sel; } VMMDECL(RTSEL) CPUMGetGuestLdtrEx(PVMCPU pVCpu, uint64_t *pGCPtrBase, uint32_t *pcbLimit) { *pGCPtrBase = pVCpu->cpum.s.Guest.ldtr.u64Base; *pcbLimit = pVCpu->cpum.s.Guest.ldtr.u32Limit; return pVCpu->cpum.s.Guest.ldtr.Sel; } VMMDECL(uint64_t) CPUMGetGuestCR0(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr0; } VMMDECL(uint64_t) CPUMGetGuestCR2(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr2; } VMMDECL(uint64_t) CPUMGetGuestCR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr3; } VMMDECL(uint64_t) CPUMGetGuestCR4(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr4; } VMMDECL(uint64_t) CPUMGetGuestCR8(PVMCPU pVCpu) { uint64_t u64; int rc = CPUMGetGuestCRx(pVCpu, DISCREG_CR8, &u64); if (RT_FAILURE(rc)) u64 = 0; return u64; } VMMDECL(void) CPUMGetGuestGDTR(PVMCPU pVCpu, PVBOXGDTR pGDTR) { *pGDTR = pVCpu->cpum.s.Guest.gdtr; } VMMDECL(uint32_t) CPUMGetGuestEIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.eip; } VMMDECL(uint64_t) CPUMGetGuestRIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.rip; } VMMDECL(uint32_t) CPUMGetGuestEAX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.eax; } VMMDECL(uint32_t) CPUMGetGuestEBX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ebx; } VMMDECL(uint32_t) CPUMGetGuestECX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ecx; } VMMDECL(uint32_t) CPUMGetGuestEDX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.edx; } VMMDECL(uint32_t) CPUMGetGuestESI(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.esi; } VMMDECL(uint32_t) CPUMGetGuestEDI(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.edi; } VMMDECL(uint32_t) CPUMGetGuestESP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.esp; } VMMDECL(uint32_t) CPUMGetGuestEBP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ebp; } VMMDECL(uint32_t) CPUMGetGuestEFlags(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.eflags.u32; } VMMDECL(int) CPUMGetGuestCRx(PVMCPU pVCpu, unsigned iReg, uint64_t *pValue) { switch (iReg) { case DISCREG_CR0: *pValue = pVCpu->cpum.s.Guest.cr0; break; case DISCREG_CR2: *pValue = pVCpu->cpum.s.Guest.cr2; break; case DISCREG_CR3: *pValue = pVCpu->cpum.s.Guest.cr3; break; case DISCREG_CR4: *pValue = pVCpu->cpum.s.Guest.cr4; break; case DISCREG_CR8: { uint8_t u8Tpr; int rc = PDMApicGetTPR(pVCpu, &u8Tpr, NULL /* pfPending */, NULL /* pu8PendingIrq */); if (RT_FAILURE(rc)) { AssertMsg(rc == VERR_PDM_NO_APIC_INSTANCE, ("%Rrc\n", rc)); *pValue = 0; return rc; } *pValue = u8Tpr >> 4; /* bits 7-4 contain the task priority that go in cr8, bits 3-0*/ break; } default: return VERR_INVALID_PARAMETER; } return VINF_SUCCESS; } VMMDECL(uint64_t) CPUMGetGuestDR0(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[0]; } VMMDECL(uint64_t) CPUMGetGuestDR1(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[1]; } VMMDECL(uint64_t) CPUMGetGuestDR2(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[2]; } VMMDECL(uint64_t) CPUMGetGuestDR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[3]; } VMMDECL(uint64_t) CPUMGetGuestDR6(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[6]; } VMMDECL(uint64_t) CPUMGetGuestDR7(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[7]; } VMMDECL(int) CPUMGetGuestDRx(PVMCPU pVCpu, uint32_t iReg, uint64_t *pValue) { AssertReturn(iReg <= DISDREG_DR7, VERR_INVALID_PARAMETER); /* DR4 is an alias for DR6, and DR5 is an alias for DR7. */ if (iReg == 4 || iReg == 5) iReg += 2; *pValue = pVCpu->cpum.s.Guest.dr[iReg]; return VINF_SUCCESS; } VMMDECL(uint64_t) CPUMGetGuestEFER(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.msrEFER; } /** * Looks up a CPUID leaf in the CPUID leaf array, no subleaf. * * @returns Pointer to the leaf if found, NULL if not. * * @param pVM Pointer to the cross context VM structure. * @param uLeaf The leaf to get. */ PCPUMCPUIDLEAF cpumCpuIdGetLeaf(PVM pVM, uint32_t uLeaf) { unsigned iEnd = pVM->cpum.s.GuestInfo.cCpuIdLeaves; if (iEnd) { unsigned iStart = 0; PCPUMCPUIDLEAF paLeaves = pVM->cpum.s.GuestInfo.CTX_SUFF(paCpuIdLeaves); for (;;) { unsigned i = iStart + (iEnd - iStart) / 2U; if (uLeaf < paLeaves[i].uLeaf) { if (i <= iStart) return NULL; iEnd = i; } else if (uLeaf > paLeaves[i].uLeaf) { i += 1; if (i >= iEnd) return NULL; iStart = i; } else { if (RT_LIKELY(paLeaves[i].fSubLeafMask == 0 && paLeaves[i].uSubLeaf == 0)) return &paLeaves[i]; /* This shouldn't normally happen. But in case the it does due to user configuration overrids or something, just return the first sub-leaf. */ AssertMsgFailed(("uLeaf=%#x fSubLeafMask=%#x uSubLeaf=%#x\n", uLeaf, paLeaves[i].fSubLeafMask, paLeaves[i].uSubLeaf)); while ( paLeaves[i].uSubLeaf != 0 && i > 0 && uLeaf == paLeaves[i - 1].uLeaf) i--; return &paLeaves[i]; } } } return NULL; } /** * Looks up a CPUID leaf in the CPUID leaf array. * * @returns Pointer to the leaf if found, NULL if not. * * @param pVM Pointer to the cross context VM structure. * @param uLeaf The leaf to get. * @param uSubLeaf The subleaf, if applicable. Just pass 0 if it * isn't. * @param pfExactSubLeafHit Whether we've got an exact subleaf hit or not. */ PCPUMCPUIDLEAF cpumCpuIdGetLeafEx(PVM pVM, uint32_t uLeaf, uint32_t uSubLeaf, bool *pfExactSubLeafHit) { unsigned iEnd = pVM->cpum.s.GuestInfo.cCpuIdLeaves; if (iEnd) { unsigned iStart = 0; PCPUMCPUIDLEAF paLeaves = pVM->cpum.s.GuestInfo.CTX_SUFF(paCpuIdLeaves); for (;;) { unsigned i = iStart + (iEnd - iStart) / 2U; if (uLeaf < paLeaves[i].uLeaf) { if (i <= iStart) return NULL; iEnd = i; } else if (uLeaf > paLeaves[i].uLeaf) { i += 1; if (i >= iEnd) return NULL; iStart = i; } else { uSubLeaf &= paLeaves[i].fSubLeafMask; if (uSubLeaf == paLeaves[i].uSubLeaf) *pfExactSubLeafHit = true; else { /* Find the right subleaf. We return the last one before uSubLeaf if we don't find an exact match. */ if (uSubLeaf < paLeaves[i].uSubLeaf) while ( i > 0 && uLeaf == paLeaves[i - 1].uLeaf && uSubLeaf <= paLeaves[i - 1].uSubLeaf) i--; else while ( i + 1 < pVM->cpum.s.GuestInfo.cCpuIdLeaves && uLeaf == paLeaves[i + 1].uLeaf && uSubLeaf >= paLeaves[i + 1].uSubLeaf) i++; *pfExactSubLeafHit = uSubLeaf == paLeaves[i].uSubLeaf; } return &paLeaves[i]; } } } *pfExactSubLeafHit = false; return NULL; } /** * Gets a CPUID leaf. * * @param pVCpu Pointer to the VMCPU. * @param uLeaf The CPUID leaf to get. * @param uSubLeaf The CPUID sub-leaf to get, if applicable. * @param pEax Where to store the EAX value. * @param pEbx Where to store the EBX value. * @param pEcx Where to store the ECX value. * @param pEdx Where to store the EDX value. */ VMMDECL(void) CPUMGetGuestCpuId(PVMCPU pVCpu, uint32_t uLeaf, uint32_t uSubLeaf, uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx) { bool fExactSubLeafHit; PVM pVM = pVCpu->CTX_SUFF(pVM); PCCPUMCPUIDLEAF pLeaf = cpumCpuIdGetLeafEx(pVM, uLeaf, uSubLeaf, &fExactSubLeafHit); if (pLeaf) { AssertMsg(pLeaf->uLeaf == uLeaf, ("%#x\n", pLeaf->uLeaf, uLeaf)); if (fExactSubLeafHit) { *pEax = pLeaf->uEax; *pEbx = pLeaf->uEbx; *pEcx = pLeaf->uEcx; *pEdx = pLeaf->uEdx; /* * Deal with CPU specific information (currently only APIC ID). */ if (pLeaf->fFlags & (CPUMCPUIDLEAF_F_CONTAINS_APIC_ID | CPUMCPUIDLEAF_F_CONTAINS_OSXSAVE)) { if (uLeaf == 1) { /* EBX: Bits 31-24: Initial APIC ID. */ Assert(pVCpu->idCpu <= 255); AssertMsg((pLeaf->uEbx >> 24) == 0, ("%#x\n", pLeaf->uEbx)); /* raw-mode assumption */ *pEbx = (pLeaf->uEbx & UINT32_C(0x00ffffff)) | (pVCpu->idCpu << 24); /* ECX: Bit 27: CR4.OSXSAVE mirror. */ *pEcx = (pLeaf->uEcx & ~X86_CPUID_FEATURE_ECX_OSXSAVE) | (pVCpu->cpum.s.Guest.cr4 & X86_CR4_OSXSAVE ? X86_CPUID_FEATURE_ECX_OSXSAVE : 0); } else if (uLeaf == 0xb) { /* EDX: Initial extended APIC ID. */ AssertMsg(pLeaf->uEdx == 0, ("%#x\n", pLeaf->uEdx)); /* raw-mode assumption */ *pEdx = pVCpu->idCpu; } else if (uLeaf == UINT32_C(0x8000001e)) { /* EAX: Initial extended APIC ID. */ AssertMsg(pLeaf->uEax == 0, ("%#x\n", pLeaf->uEax)); /* raw-mode assumption */ *pEax = pVCpu->idCpu; } else AssertMsgFailed(("uLeaf=%#x\n", uLeaf)); } } /* * Out of range sub-leaves aren't quite as easy and pretty as we emulate * them here, but we do the best we can here... */ else { *pEax = *pEbx = *pEcx = *pEdx = 0; if (pLeaf->fFlags & CPUMCPUIDLEAF_F_INTEL_TOPOLOGY_SUBLEAVES) { *pEcx = uSubLeaf & 0xff; *pEdx = pVCpu->idCpu; } } } else { /* * Different CPUs have different ways of dealing with unknown CPUID leaves. */ switch (pVM->cpum.s.GuestInfo.enmUnknownCpuIdMethod) { default: AssertFailed(); case CPUMUNKNOWNCPUID_DEFAULTS: case CPUMUNKNOWNCPUID_LAST_STD_LEAF: /* ASSUME this is executed */ case CPUMUNKNOWNCPUID_LAST_STD_LEAF_WITH_ECX: /** @todo Implement CPUMUNKNOWNCPUID_LAST_STD_LEAF_WITH_ECX */ *pEax = pVM->cpum.s.GuestInfo.DefCpuId.uEax; *pEbx = pVM->cpum.s.GuestInfo.DefCpuId.uEbx; *pEcx = pVM->cpum.s.GuestInfo.DefCpuId.uEcx; *pEdx = pVM->cpum.s.GuestInfo.DefCpuId.uEdx; break; case CPUMUNKNOWNCPUID_PASSTHRU: *pEax = uLeaf; *pEbx = 0; *pEcx = uSubLeaf; *pEdx = 0; break; } } Log2(("CPUMGetGuestCpuId: uLeaf=%#010x/%#010x %RX32 %RX32 %RX32 %RX32\n", uLeaf, uSubLeaf, *pEax, *pEbx, *pEcx, *pEdx)); } /** * Sets a CPUID feature bit. * * @param pVM Pointer to the VM. * @param enmFeature The feature to set. */ VMMDECL(void) CPUMSetGuestCpuIdFeature(PVM pVM, CPUMCPUIDFEATURE enmFeature) { PCPUMCPUIDLEAF pLeaf; switch (enmFeature) { /* * Set the APIC bit in both feature masks. */ case CPUMCPUIDFEATURE_APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_APIC; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_AMD_FEATURE_EDX_APIC; pVM->cpum.s.GuestFeatures.fApic = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled APIC\n")); break; /* * Set the x2APIC bit in the standard feature mask. */ case CPUMCPUIDFEATURE_X2APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx |= X86_CPUID_FEATURE_ECX_X2APIC; pVM->cpum.s.GuestFeatures.fX2Apic = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled x2APIC\n")); break; /* * Set the sysenter/sysexit bit in the standard feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_SEP: if (!pVM->cpum.s.HostFeatures.fSysEnter) { AssertMsgFailed(("ERROR: Can't turn on SEP when the host doesn't support it!!\n")); return; } pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_SEP; pVM->cpum.s.GuestFeatures.fSysEnter = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled SYSENTER/EXIT\n")); break; /* * Set the syscall/sysret bit in the extended feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_SYSCALL: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fSysCall) { #if HC_ARCH_BITS == 32 /* X86_CPUID_EXT_FEATURE_EDX_SYSCALL not set it seems in 32-bit mode by Intel, even when the cpu is capable of doing so in 64-bit mode. Long mode requires syscall support. */ if (!pVM->cpum.s.HostFeatures.fLongMode) #endif { LogRel(("CPUM: WARNING! Can't turn on SYSCALL/SYSRET when the host doesn't support it!\n")); return; } } /* Valid for both Intel and AMD CPUs, although only in 64 bits mode for Intel. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_SYSCALL; pVM->cpum.s.GuestFeatures.fSysCall = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled SYSCALL/RET\n")); break; /* * Set the PAE bit in both feature masks. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_PAE: if (!pVM->cpum.s.HostFeatures.fPae) { LogRel(("CPUM: WARNING! Can't turn on PAE when the host doesn't support it!\n")); return; } pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_PAE; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_AMD_FEATURE_EDX_PAE; pVM->cpum.s.GuestFeatures.fPae = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled PAE\n")); break; /* * Set the LONG MODE bit in the extended feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_LONG_MODE: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fLongMode) { LogRel(("CPUM: WARNING! Can't turn on LONG MODE when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_LONG_MODE; pVM->cpum.s.GuestFeatures.fLongMode = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled LONG MODE\n")); break; /* * Set the NX/XD bit in the extended feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_NX: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fNoExecute) { LogRel(("CPUM: WARNING! Can't turn on NX/XD when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_NX; pVM->cpum.s.GuestFeatures.fNoExecute = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled NX\n")); break; /* * Set the LAHF/SAHF support in 64-bit mode. * Assumes the caller knows what it's doing! (host must support this) */ case CPUMCPUIDFEATURE_LAHF: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fLahfSahf) { LogRel(("CPUM: WARNING! Can't turn on LAHF/SAHF when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEcx = pLeaf->uEcx |= X86_CPUID_EXT_FEATURE_ECX_LAHF_SAHF; pVM->cpum.s.GuestFeatures.fLahfSahf = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled LAHF/SAHF\n")); break; /* * Set the page attribute table bit. This is alternative page level * cache control that doesn't much matter when everything is * virtualized, though it may when passing thru device memory. */ case CPUMCPUIDFEATURE_PAT: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_PAT; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_AMD_FEATURE_EDX_PAT; pVM->cpum.s.GuestFeatures.fPat = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled PAT\n")); break; /* * Set the RDTSCP support bit. * Assumes the caller knows what it's doing! (host must support this) */ case CPUMCPUIDFEATURE_RDTSCP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fRdTscP || pVM->cpum.s.u8PortableCpuIdLevel > 0) { if (!pVM->cpum.s.u8PortableCpuIdLevel) LogRel(("CPUM: WARNING! Can't turn on RDTSCP when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_RDTSCP; pVM->cpum.s.HostFeatures.fRdTscP = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled RDTSCP.\n")); break; /* * Set the Hypervisor Present bit in the standard feature mask. */ case CPUMCPUIDFEATURE_HVP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx |= X86_CPUID_FEATURE_ECX_HVP; pVM->cpum.s.GuestFeatures.fHypervisorPresent = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled Hypervisor Present bit\n")); break; /* * Set the MWAIT Extensions Present bit in the MWAIT/MONITOR leaf. * This currently includes the Present bit and MWAITBREAK bit as well. */ case CPUMCPUIDFEATURE_MWAIT_EXTS: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000005)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fMWaitExtensions) { LogRel(("CPUM: WARNING! Can't turn on MWAIT Extensions when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmStd[5].uEcx = pLeaf->uEcx |= X86_CPUID_MWAIT_ECX_EXT | X86_CPUID_MWAIT_ECX_BREAKIRQIF0; pVM->cpum.s.GuestFeatures.fMWaitExtensions = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled MWAIT Extensions.\n")); break; /* * OSXSAVE - only used from CPUMSetGuestCR4. */ case CPUMCPUIDFEATURE_OSXSAVE: AssertLogRelReturnVoid(pVM->cpum.s.HostFeatures.fXSaveRstor && pVM->cpum.s.HostFeatures.fOpSysXSaveRstor); pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); AssertLogRelReturnVoid(pLeaf); /* UNI: Special case for single CPU to make life simple for CPUMPatchHlpCpuId. */ if (pVM->cCpus == 1) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx |= X86_CPUID_FEATURE_ECX_OSXSAVE; /* SMP: Set flag indicating OSXSAVE updating (superfluous because of the APIC ID, but that's fine). */ else ASMAtomicOrU32(&pLeaf->fFlags, CPUMCPUIDLEAF_F_CONTAINS_OSXSAVE); break; default: AssertMsgFailed(("enmFeature=%d\n", enmFeature)); break; } for (VMCPUID i = 0; i < pVM->cCpus; i++) { PVMCPU pVCpu = &pVM->aCpus[i]; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CPUID; } } /** * Queries a CPUID feature bit. * * @returns boolean for feature presence * @param pVM Pointer to the VM. * @param enmFeature The feature to query. */ VMMDECL(bool) CPUMGetGuestCpuIdFeature(PVM pVM, CPUMCPUIDFEATURE enmFeature) { switch (enmFeature) { case CPUMCPUIDFEATURE_APIC: return pVM->cpum.s.GuestFeatures.fApic; case CPUMCPUIDFEATURE_X2APIC: return pVM->cpum.s.GuestFeatures.fX2Apic; case CPUMCPUIDFEATURE_SYSCALL: return pVM->cpum.s.GuestFeatures.fSysCall; case CPUMCPUIDFEATURE_SEP: return pVM->cpum.s.GuestFeatures.fSysEnter; case CPUMCPUIDFEATURE_PAE: return pVM->cpum.s.GuestFeatures.fPae; case CPUMCPUIDFEATURE_NX: return pVM->cpum.s.GuestFeatures.fNoExecute; case CPUMCPUIDFEATURE_LAHF: return pVM->cpum.s.GuestFeatures.fLahfSahf; case CPUMCPUIDFEATURE_LONG_MODE: return pVM->cpum.s.GuestFeatures.fLongMode; case CPUMCPUIDFEATURE_PAT: return pVM->cpum.s.GuestFeatures.fPat; case CPUMCPUIDFEATURE_RDTSCP: return pVM->cpum.s.GuestFeatures.fRdTscP; case CPUMCPUIDFEATURE_HVP: return pVM->cpum.s.GuestFeatures.fHypervisorPresent; case CPUMCPUIDFEATURE_MWAIT_EXTS: return pVM->cpum.s.GuestFeatures.fMWaitExtensions; case CPUMCPUIDFEATURE_OSXSAVE: case CPUMCPUIDFEATURE_INVALID: case CPUMCPUIDFEATURE_32BIT_HACK: break; } AssertFailed(); return false; } /** * Clears a CPUID feature bit. * * @param pVM Pointer to the VM. * @param enmFeature The feature to clear. */ VMMDECL(void) CPUMClearGuestCpuIdFeature(PVM pVM, CPUMCPUIDFEATURE enmFeature) { PCPUMCPUIDLEAF pLeaf; switch (enmFeature) { case CPUMCPUIDFEATURE_APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_FEATURE_EDX_APIC; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_AMD_FEATURE_EDX_APIC; pVM->cpum.s.GuestFeatures.fApic = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled APIC\n")); break; case CPUMCPUIDFEATURE_X2APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_FEATURE_ECX_X2APIC; pVM->cpum.s.GuestFeatures.fX2Apic = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled x2APIC\n")); break; case CPUMCPUIDFEATURE_PAE: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_FEATURE_EDX_PAE; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_AMD_FEATURE_EDX_PAE; pVM->cpum.s.GuestFeatures.fPae = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled PAE!\n")); break; case CPUMCPUIDFEATURE_PAT: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_FEATURE_EDX_PAT; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_AMD_FEATURE_EDX_PAT; pVM->cpum.s.GuestFeatures.fPat = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled PAT!\n")); break; case CPUMCPUIDFEATURE_LONG_MODE: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_EXT_FEATURE_EDX_LONG_MODE; pVM->cpum.s.GuestFeatures.fLongMode = 0; break; case CPUMCPUIDFEATURE_LAHF: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_EXT_FEATURE_ECX_LAHF_SAHF; pVM->cpum.s.GuestFeatures.fLahfSahf = 0; break; case CPUMCPUIDFEATURE_RDTSCP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_EXT_FEATURE_EDX_RDTSCP; pVM->cpum.s.GuestFeatures.fRdTscP = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled RDTSCP!\n")); break; case CPUMCPUIDFEATURE_HVP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_FEATURE_ECX_HVP; pVM->cpum.s.GuestFeatures.fHypervisorPresent = 0; break; case CPUMCPUIDFEATURE_MWAIT_EXTS: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000005)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[5].uEcx = pLeaf->uEcx &= ~(X86_CPUID_MWAIT_ECX_EXT | X86_CPUID_MWAIT_ECX_BREAKIRQIF0); pVM->cpum.s.GuestFeatures.fMWaitExtensions = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled MWAIT Extensions!\n")); break; /* * OSXSAVE - only used from CPUMSetGuestCR4. */ case CPUMCPUIDFEATURE_OSXSAVE: AssertLogRelReturnVoid(pVM->cpum.s.HostFeatures.fXSaveRstor && pVM->cpum.s.HostFeatures.fOpSysXSaveRstor); pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); AssertLogRelReturnVoid(pLeaf); /* UNI: Special case for single CPU to make life easy for CPUMPatchHlpCpuId. */ if (pVM->cCpus == 1) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_FEATURE_ECX_OSXSAVE; /* else: SMP: We never set the OSXSAVE bit and leaving the CONTAINS_OSXSAVE flag is fine. */ break; default: AssertMsgFailed(("enmFeature=%d\n", enmFeature)); break; } for (VMCPUID i = 0; i < pVM->cCpus; i++) { PVMCPU pVCpu = &pVM->aCpus[i]; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CPUID; } } /** * Gets the host CPU vendor. * * @returns CPU vendor. * @param pVM Pointer to the VM. */ VMMDECL(CPUMCPUVENDOR) CPUMGetHostCpuVendor(PVM pVM) { return (CPUMCPUVENDOR)pVM->cpum.s.HostFeatures.enmCpuVendor; } /** * Gets the CPU vendor. * * @returns CPU vendor. * @param pVM Pointer to the VM. */ VMMDECL(CPUMCPUVENDOR) CPUMGetGuestCpuVendor(PVM pVM) { return (CPUMCPUVENDOR)pVM->cpum.s.GuestFeatures.enmCpuVendor; } VMMDECL(int) CPUMSetGuestDR0(PVMCPU pVCpu, uint64_t uDr0) { pVCpu->cpum.s.Guest.dr[0] = uDr0; return CPUMRecalcHyperDRx(pVCpu, 0, false); } VMMDECL(int) CPUMSetGuestDR1(PVMCPU pVCpu, uint64_t uDr1) { pVCpu->cpum.s.Guest.dr[1] = uDr1; return CPUMRecalcHyperDRx(pVCpu, 1, false); } VMMDECL(int) CPUMSetGuestDR2(PVMCPU pVCpu, uint64_t uDr2) { pVCpu->cpum.s.Guest.dr[2] = uDr2; return CPUMRecalcHyperDRx(pVCpu, 2, false); } VMMDECL(int) CPUMSetGuestDR3(PVMCPU pVCpu, uint64_t uDr3) { pVCpu->cpum.s.Guest.dr[3] = uDr3; return CPUMRecalcHyperDRx(pVCpu, 3, false); } VMMDECL(int) CPUMSetGuestDR6(PVMCPU pVCpu, uint64_t uDr6) { pVCpu->cpum.s.Guest.dr[6] = uDr6; return VINF_SUCCESS; /* No need to recalc. */ } VMMDECL(int) CPUMSetGuestDR7(PVMCPU pVCpu, uint64_t uDr7) { pVCpu->cpum.s.Guest.dr[7] = uDr7; return CPUMRecalcHyperDRx(pVCpu, 7, false); } VMMDECL(int) CPUMSetGuestDRx(PVMCPU pVCpu, uint32_t iReg, uint64_t Value) { AssertReturn(iReg <= DISDREG_DR7, VERR_INVALID_PARAMETER); /* DR4 is an alias for DR6, and DR5 is an alias for DR7. */ if (iReg == 4 || iReg == 5) iReg += 2; pVCpu->cpum.s.Guest.dr[iReg] = Value; return CPUMRecalcHyperDRx(pVCpu, iReg, false); } /** * Recalculates the hypervisor DRx register values based on current guest * registers and DBGF breakpoints, updating changed registers depending on the * context. * * This is called whenever a guest DRx register is modified (any context) and * when DBGF sets a hardware breakpoint (ring-3 only, rendezvous). * * In raw-mode context this function will reload any (hyper) DRx registers which * comes out with a different value. It may also have to save the host debug * registers if that haven't been done already. In this context though, we'll * be intercepting and emulating all DRx accesses, so the hypervisor DRx values * are only important when breakpoints are actually enabled. * * In ring-0 (HM) context DR0-3 will be relocated by us, while DR7 will be * reloaded by the HM code if it changes. Further more, we will only use the * combined register set when the VBox debugger is actually using hardware BPs, * when it isn't we'll keep the guest DR0-3 + (maybe) DR6 loaded (DR6 doesn't * concern us here). * * In ring-3 we won't be loading anything, so well calculate hypervisor values * all the time. * * @returns VINF_SUCCESS. * @param pVCpu Pointer to the VMCPU. * @param iGstReg The guest debug register number that was modified. * UINT8_MAX if not guest register. * @param fForceHyper Used in HM to force hyper registers because of single * stepping. */ VMMDECL(int) CPUMRecalcHyperDRx(PVMCPU pVCpu, uint8_t iGstReg, bool fForceHyper) { PVM pVM = pVCpu->CTX_SUFF(pVM); /* * Compare the DR7s first. * * We only care about the enabled flags. GD is virtualized when we * dispatch the #DB, we never enable it. The DBGF DR7 value is will * always have the LE and GE bits set, so no need to check and disable * stuff if they're cleared like we have to for the guest DR7. */ RTGCUINTREG uGstDr7 = CPUMGetGuestDR7(pVCpu); if (!(uGstDr7 & (X86_DR7_LE | X86_DR7_GE))) uGstDr7 = 0; else if (!(uGstDr7 & X86_DR7_LE)) uGstDr7 &= ~X86_DR7_LE_ALL; else if (!(uGstDr7 & X86_DR7_GE)) uGstDr7 &= ~X86_DR7_GE_ALL; const RTGCUINTREG uDbgfDr7 = DBGFBpGetDR7(pVM); #ifdef IN_RING0 if (!fForceHyper && (pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER)) fForceHyper = true; #endif if (( HMIsEnabled(pVCpu->CTX_SUFF(pVM)) && !fForceHyper ? uDbgfDr7 : (uGstDr7 | uDbgfDr7)) & X86_DR7_ENABLED_MASK) { Assert(!CPUMIsGuestDebugStateActive(pVCpu)); #ifdef IN_RC bool const fHmEnabled = false; #elif defined(IN_RING3) bool const fHmEnabled = HMIsEnabled(pVM); #endif /* * Ok, something is enabled. Recalc each of the breakpoints, taking * the VM debugger ones of the guest ones. In raw-mode context we will * not allow breakpoints with values inside the hypervisor area. */ RTGCUINTREG uNewDr7 = X86_DR7_GE | X86_DR7_LE | X86_DR7_RA1_MASK; /* bp 0 */ RTGCUINTREG uNewDr0; if (uDbgfDr7 & (X86_DR7_L0 | X86_DR7_G0)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L0 | X86_DR7_G0 | X86_DR7_RW0_MASK | X86_DR7_LEN0_MASK); uNewDr0 = DBGFBpGetDR0(pVM); } else if (uGstDr7 & (X86_DR7_L0 | X86_DR7_G0)) { uNewDr0 = CPUMGetGuestDR0(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr0)) uNewDr0 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L0 | X86_DR7_G0 | X86_DR7_RW0_MASK | X86_DR7_LEN0_MASK); } else uNewDr0 = 0; /* bp 1 */ RTGCUINTREG uNewDr1; if (uDbgfDr7 & (X86_DR7_L1 | X86_DR7_G1)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L1 | X86_DR7_G1 | X86_DR7_RW1_MASK | X86_DR7_LEN1_MASK); uNewDr1 = DBGFBpGetDR1(pVM); } else if (uGstDr7 & (X86_DR7_L1 | X86_DR7_G1)) { uNewDr1 = CPUMGetGuestDR1(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr1)) uNewDr1 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L1 | X86_DR7_G1 | X86_DR7_RW1_MASK | X86_DR7_LEN1_MASK); } else uNewDr1 = 0; /* bp 2 */ RTGCUINTREG uNewDr2; if (uDbgfDr7 & (X86_DR7_L2 | X86_DR7_G2)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L2 | X86_DR7_G2 | X86_DR7_RW2_MASK | X86_DR7_LEN2_MASK); uNewDr2 = DBGFBpGetDR2(pVM); } else if (uGstDr7 & (X86_DR7_L2 | X86_DR7_G2)) { uNewDr2 = CPUMGetGuestDR2(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr2)) uNewDr2 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L2 | X86_DR7_G2 | X86_DR7_RW2_MASK | X86_DR7_LEN2_MASK); } else uNewDr2 = 0; /* bp 3 */ RTGCUINTREG uNewDr3; if (uDbgfDr7 & (X86_DR7_L3 | X86_DR7_G3)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L3 | X86_DR7_G3 | X86_DR7_RW3_MASK | X86_DR7_LEN3_MASK); uNewDr3 = DBGFBpGetDR3(pVM); } else if (uGstDr7 & (X86_DR7_L3 | X86_DR7_G3)) { uNewDr3 = CPUMGetGuestDR3(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr3)) uNewDr3 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L3 | X86_DR7_G3 | X86_DR7_RW3_MASK | X86_DR7_LEN3_MASK); } else uNewDr3 = 0; /* * Apply the updates. */ #ifdef IN_RC /* Make sure to save host registers first. */ if (!(pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HOST)) { if (!(pVCpu->cpum.s.fUseFlags & CPUM_USE_DEBUG_REGS_HOST)) { pVCpu->cpum.s.Host.dr6 = ASMGetDR6(); pVCpu->cpum.s.Host.dr7 = ASMGetDR7(); } pVCpu->cpum.s.Host.dr0 = ASMGetDR0(); pVCpu->cpum.s.Host.dr1 = ASMGetDR1(); pVCpu->cpum.s.Host.dr2 = ASMGetDR2(); pVCpu->cpum.s.Host.dr3 = ASMGetDR3(); pVCpu->cpum.s.fUseFlags |= CPUM_USED_DEBUG_REGS_HOST | CPUM_USE_DEBUG_REGS_HYPER | CPUM_USED_DEBUG_REGS_HYPER; /* We haven't loaded any hyper DRxes yet, so we'll have to load them all now. */ pVCpu->cpum.s.Hyper.dr[0] = uNewDr0; ASMSetDR0(uNewDr0); pVCpu->cpum.s.Hyper.dr[1] = uNewDr1; ASMSetDR1(uNewDr1); pVCpu->cpum.s.Hyper.dr[2] = uNewDr2; ASMSetDR2(uNewDr2); pVCpu->cpum.s.Hyper.dr[3] = uNewDr3; ASMSetDR3(uNewDr3); ASMSetDR6(X86_DR6_INIT_VAL); pVCpu->cpum.s.Hyper.dr[7] = uNewDr7; ASMSetDR7(uNewDr7); } else #endif { pVCpu->cpum.s.fUseFlags |= CPUM_USE_DEBUG_REGS_HYPER; if (uNewDr3 != pVCpu->cpum.s.Hyper.dr[3]) CPUMSetHyperDR3(pVCpu, uNewDr3); if (uNewDr2 != pVCpu->cpum.s.Hyper.dr[2]) CPUMSetHyperDR2(pVCpu, uNewDr2); if (uNewDr1 != pVCpu->cpum.s.Hyper.dr[1]) CPUMSetHyperDR1(pVCpu, uNewDr1); if (uNewDr0 != pVCpu->cpum.s.Hyper.dr[0]) CPUMSetHyperDR0(pVCpu, uNewDr0); if (uNewDr7 != pVCpu->cpum.s.Hyper.dr[7]) CPUMSetHyperDR7(pVCpu, uNewDr7); } } #ifdef IN_RING0 else if (CPUMIsGuestDebugStateActive(pVCpu)) { /* * Reload the register that was modified. Normally this won't happen * as we won't intercept DRx writes when not having the hyper debug * state loaded, but in case we do for some reason we'll simply deal * with it. */ switch (iGstReg) { case 0: ASMSetDR0(CPUMGetGuestDR0(pVCpu)); break; case 1: ASMSetDR1(CPUMGetGuestDR1(pVCpu)); break; case 2: ASMSetDR2(CPUMGetGuestDR2(pVCpu)); break; case 3: ASMSetDR3(CPUMGetGuestDR3(pVCpu)); break; default: AssertReturn(iGstReg != UINT8_MAX, VERR_INTERNAL_ERROR_3); } } #endif else { /* * No active debug state any more. In raw-mode this means we have to * make sure DR7 has everything disabled now, if we armed it already. * In ring-0 we might end up here when just single stepping. */ #if defined(IN_RC) || defined(IN_RING0) if (pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER) { # ifdef IN_RC ASMSetDR7(X86_DR7_INIT_VAL); # endif if (pVCpu->cpum.s.Hyper.dr[0]) ASMSetDR0(0); if (pVCpu->cpum.s.Hyper.dr[1]) ASMSetDR1(0); if (pVCpu->cpum.s.Hyper.dr[2]) ASMSetDR2(0); if (pVCpu->cpum.s.Hyper.dr[3]) ASMSetDR3(0); pVCpu->cpum.s.fUseFlags &= ~CPUM_USED_DEBUG_REGS_HYPER; } #endif pVCpu->cpum.s.fUseFlags &= ~CPUM_USE_DEBUG_REGS_HYPER; /* Clear all the registers. */ pVCpu->cpum.s.Hyper.dr[7] = X86_DR7_RA1_MASK; pVCpu->cpum.s.Hyper.dr[3] = 0; pVCpu->cpum.s.Hyper.dr[2] = 0; pVCpu->cpum.s.Hyper.dr[1] = 0; pVCpu->cpum.s.Hyper.dr[0] = 0; } Log2(("CPUMRecalcHyperDRx: fUseFlags=%#x %RGr %RGr %RGr %RGr %RGr %RGr\n", pVCpu->cpum.s.fUseFlags, pVCpu->cpum.s.Hyper.dr[0], pVCpu->cpum.s.Hyper.dr[1], pVCpu->cpum.s.Hyper.dr[2], pVCpu->cpum.s.Hyper.dr[3], pVCpu->cpum.s.Hyper.dr[6], pVCpu->cpum.s.Hyper.dr[7])); return VINF_SUCCESS; } /** * Set the guest XCR0 register. * * Will load additional state if the FPU state is already loaded (in ring-0 & * raw-mode context). * * @returns VINF_SUCCESS on success, VERR_CPUM_RAISE_GP_0 on invalid input * value. * @param pVCpu Pointer to the cross context VMCPU structure for the * calling EMT. * @param uNewValue The new value. * @thread EMT(pVCpu) */ VMM_INT_DECL(int) CPUMSetGuestXcr0(PVMCPU pVCpu, uint64_t uNewValue) { if ( (uNewValue & ~pVCpu->CTX_SUFF(pVM)->cpum.s.fXStateGuestMask) == 0 /* The X87 bit cannot be cleared. */ && (uNewValue & XSAVE_C_X87) /* AVX requires SSE. */ && (uNewValue & (XSAVE_C_SSE | XSAVE_C_YMM)) != XSAVE_C_YMM /* AVX-512 requires YMM, SSE and all of its three components to be enabled. */ && ( (uNewValue & (XSAVE_C_OPMASK | XSAVE_C_ZMM_HI256 | XSAVE_C_ZMM_16HI)) == 0 || (uNewValue & (XSAVE_C_SSE | XSAVE_C_YMM | XSAVE_C_OPMASK | XSAVE_C_ZMM_HI256 | XSAVE_C_ZMM_16HI)) == (XSAVE_C_SSE | XSAVE_C_YMM | XSAVE_C_OPMASK | XSAVE_C_ZMM_HI256 | XSAVE_C_ZMM_16HI) ) ) { pVCpu->cpum.s.Guest.aXcr[0] = uNewValue; /* If more state components are enabled, we need to take care to load them if the FPU/SSE state is already loaded. May otherwise leak host state to the guest. */ uint64_t fNewComponents = ~pVCpu->cpum.s.Guest.fXStateMask & uNewValue; if (fNewComponents) { #if defined(IN_RING0) || defined(IN_RC) if (pVCpu->cpum.s.fUseFlags & CPUM_USED_FPU) { if (pVCpu->cpum.s.Guest.fXStateMask != 0) /* Adding more components. */ ASMXRstor(pVCpu->cpum.s.Guest.CTX_SUFF(pXState), fNewComponents); else { /* We're switching from FXSAVE/FXRSTOR to XSAVE/XRSTOR. */ pVCpu->cpum.s.Guest.fXStateMask |= XSAVE_C_X87 | XSAVE_C_SSE; if (uNewValue & ~(XSAVE_C_X87 | XSAVE_C_SSE)) ASMXRstor(pVCpu->cpum.s.Guest.CTX_SUFF(pXState), uNewValue & ~(XSAVE_C_X87 | XSAVE_C_SSE)); } } #endif pVCpu->cpum.s.Guest.fXStateMask |= uNewValue; } return VINF_SUCCESS; } return VERR_CPUM_RAISE_GP_0; } /** * Tests if the guest has No-Execute Page Protection Enabled (NXE). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestNXEnabled(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_NXE); } /** * Tests if the guest has the Page Size Extension enabled (PSE). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestPageSizeExtEnabled(PVMCPU pVCpu) { /* PAE or AMD64 implies support for big pages regardless of CR4.PSE */ return !!(pVCpu->cpum.s.Guest.cr4 & (X86_CR4_PSE | X86_CR4_PAE)); } /** * Tests if the guest has the paging enabled (PG). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestPagingEnabled(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PG); } /** * Tests if the guest has the paging enabled (PG). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestR0WriteProtEnabled(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_WP); } /** * Tests if the guest is running in real mode or not. * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInRealMode(PVMCPU pVCpu) { return !(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE); } /** * Tests if the guest is running in real or virtual 8086 mode. * * @returns @c true if it is, @c false if not. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInRealOrV86Mode(PVMCPU pVCpu) { return !(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE) || pVCpu->cpum.s.Guest.eflags.Bits.u1VM; /** @todo verify that this cannot be set in long mode. */ } /** * Tests if the guest is running in protected or not. * * @returns true if in protected mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInProtectedMode(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE); } /** * Tests if the guest is running in paged protected or not. * * @returns true if in paged protected mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInPagedProtectedMode(PVMCPU pVCpu) { return (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG); } /** * Tests if the guest is running in long mode or not. * * @returns true if in long mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInLongMode(PVMCPU pVCpu) { return (pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA) == MSR_K6_EFER_LMA; } /** * Tests if the guest is running in PAE mode or not. * * @returns true if in PAE mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInPAEMode(PVMCPU pVCpu) { /* Intel mentions EFER.LMA and EFER.LME in different parts of their spec. We shall use EFER.LMA rather than EFER.LME as it reflects if the CPU has entered paging with EFER.LME set. */ return (pVCpu->cpum.s.Guest.cr4 & X86_CR4_PAE) && (pVCpu->cpum.s.Guest.cr0 & X86_CR0_PG) && !(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA); } /** * Tests if the guest is running in 64 bits mode or not. * * @returns true if in 64 bits protected mode, otherwise false. * @param pVCpu The current virtual CPU. */ VMMDECL(bool) CPUMIsGuestIn64BitCode(PVMCPU pVCpu) { if (!CPUMIsGuestInLongMode(pVCpu)) return false; CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); return pVCpu->cpum.s.Guest.cs.Attr.n.u1Long; } /** * Helper for CPUMIsGuestIn64BitCodeEx that handles lazy resolving of hidden CS * registers. * * @returns true if in 64 bits protected mode, otherwise false. * @param pCtx Pointer to the current guest CPU context. */ VMM_INT_DECL(bool) CPUMIsGuestIn64BitCodeSlow(PCPUMCTX pCtx) { return CPUMIsGuestIn64BitCode(CPUM_GUEST_CTX_TO_VMCPU(pCtx)); } #ifdef VBOX_WITH_RAW_MODE_NOT_R0 /** * * @returns @c true if we've entered raw-mode and selectors with RPL=1 are * really RPL=0, @c false if we've not (RPL=1 really is RPL=1). * @param pVCpu The current virtual CPU. */ VMM_INT_DECL(bool) CPUMIsGuestInRawMode(PVMCPU pVCpu) { return pVCpu->cpum.s.fRawEntered; } /** * Transforms the guest CPU state to raw-ring mode. * * This function will change the any of the cs and ss register with DPL=0 to DPL=1. * * @returns VBox status. (recompiler failure) * @param pVCpu Pointer to the VMCPU. * @see @ref pg_raw */ VMM_INT_DECL(int) CPUMRawEnter(PVMCPU pVCpu) { PVM pVM = pVCpu->CTX_SUFF(pVM); Assert(!pVCpu->cpum.s.fRawEntered); Assert(!pVCpu->cpum.s.fRemEntered); PCPUMCTX pCtx = &pVCpu->cpum.s.Guest; /* * Are we in Ring-0? */ if ( pCtx->ss.Sel && (pCtx->ss.Sel & X86_SEL_RPL) == 0 && !pCtx->eflags.Bits.u1VM) { /* * Enter execution mode. */ PATMRawEnter(pVM, pCtx); /* * Set CPL to Ring-1. */ pCtx->ss.Sel |= 1; if ( pCtx->cs.Sel && (pCtx->cs.Sel & X86_SEL_RPL) == 0) pCtx->cs.Sel |= 1; } else { # ifdef VBOX_WITH_RAW_RING1 if ( EMIsRawRing1Enabled(pVM) && !pCtx->eflags.Bits.u1VM && (pCtx->ss.Sel & X86_SEL_RPL) == 1) { /* Set CPL to Ring-2. */ pCtx->ss.Sel = (pCtx->ss.Sel & ~X86_SEL_RPL) | 2; if (pCtx->cs.Sel && (pCtx->cs.Sel & X86_SEL_RPL) == 1) pCtx->cs.Sel = (pCtx->cs.Sel & ~X86_SEL_RPL) | 2; } # else AssertMsg((pCtx->ss.Sel & X86_SEL_RPL) >= 2 || pCtx->eflags.Bits.u1VM, ("ring-1 code not supported\n")); # endif /* * PATM takes care of IOPL and IF flags for Ring-3 and Ring-2 code as well. */ PATMRawEnter(pVM, pCtx); } /* * Assert sanity. */ AssertMsg((pCtx->eflags.u32 & X86_EFL_IF), ("X86_EFL_IF is clear\n")); AssertReleaseMsg(pCtx->eflags.Bits.u2IOPL == 0, ("X86_EFL_IOPL=%d CPL=%d\n", pCtx->eflags.Bits.u2IOPL, pCtx->ss.Sel & X86_SEL_RPL)); Assert((pVCpu->cpum.s.Guest.cr0 & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE)) == (X86_CR0_PG | X86_CR0_PE | X86_CR0_WP)); pCtx->eflags.u32 |= X86_EFL_IF; /* paranoia */ pVCpu->cpum.s.fRawEntered = true; return VINF_SUCCESS; } /** * Transforms the guest CPU state from raw-ring mode to correct values. * * This function will change any selector registers with DPL=1 to DPL=0. * * @returns Adjusted rc. * @param pVCpu Pointer to the VMCPU. * @param rc Raw mode return code * @see @ref pg_raw */ VMM_INT_DECL(int) CPUMRawLeave(PVMCPU pVCpu, int rc) { PVM pVM = pVCpu->CTX_SUFF(pVM); /* * Don't leave if we've already left (in RC). */ Assert(!pVCpu->cpum.s.fRemEntered); if (!pVCpu->cpum.s.fRawEntered) return rc; pVCpu->cpum.s.fRawEntered = false; PCPUMCTX pCtx = &pVCpu->cpum.s.Guest; Assert(pCtx->eflags.Bits.u1VM || (pCtx->ss.Sel & X86_SEL_RPL)); AssertMsg(pCtx->eflags.Bits.u1VM || pCtx->eflags.Bits.u2IOPL < (unsigned)(pCtx->ss.Sel & X86_SEL_RPL), ("X86_EFL_IOPL=%d CPL=%d\n", pCtx->eflags.Bits.u2IOPL, pCtx->ss.Sel & X86_SEL_RPL)); /* * Are we executing in raw ring-1? */ if ( (pCtx->ss.Sel & X86_SEL_RPL) == 1 && !pCtx->eflags.Bits.u1VM) { /* * Leave execution mode. */ PATMRawLeave(pVM, pCtx, rc); /* Not quite sure if this is really required, but shouldn't harm (too much anyways). */ /** @todo See what happens if we remove this. */ if ((pCtx->ds.Sel & X86_SEL_RPL) == 1) pCtx->ds.Sel &= ~X86_SEL_RPL; if ((pCtx->es.Sel & X86_SEL_RPL) == 1) pCtx->es.Sel &= ~X86_SEL_RPL; if ((pCtx->fs.Sel & X86_SEL_RPL) == 1) pCtx->fs.Sel &= ~X86_SEL_RPL; if ((pCtx->gs.Sel & X86_SEL_RPL) == 1) pCtx->gs.Sel &= ~X86_SEL_RPL; /* * Ring-1 selector => Ring-0. */ pCtx->ss.Sel &= ~X86_SEL_RPL; if ((pCtx->cs.Sel & X86_SEL_RPL) == 1) pCtx->cs.Sel &= ~X86_SEL_RPL; } else { /* * PATM is taking care of the IOPL and IF flags for us. */ PATMRawLeave(pVM, pCtx, rc); if (!pCtx->eflags.Bits.u1VM) { # ifdef VBOX_WITH_RAW_RING1 if ( EMIsRawRing1Enabled(pVM) && (pCtx->ss.Sel & X86_SEL_RPL) == 2) { /* Not quite sure if this is really required, but shouldn't harm (too much anyways). */ /** @todo See what happens if we remove this. */ if ((pCtx->ds.Sel & X86_SEL_RPL) == 2) pCtx->ds.Sel = (pCtx->ds.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->es.Sel & X86_SEL_RPL) == 2) pCtx->es.Sel = (pCtx->es.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->fs.Sel & X86_SEL_RPL) == 2) pCtx->fs.Sel = (pCtx->fs.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->gs.Sel & X86_SEL_RPL) == 2) pCtx->gs.Sel = (pCtx->gs.Sel & ~X86_SEL_RPL) | 1; /* * Ring-2 selector => Ring-1. */ pCtx->ss.Sel = (pCtx->ss.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->cs.Sel & X86_SEL_RPL) == 2) pCtx->cs.Sel = (pCtx->cs.Sel & ~X86_SEL_RPL) | 1; } else { # endif /** @todo See what happens if we remove this. */ if ((pCtx->ds.Sel & X86_SEL_RPL) == 1) pCtx->ds.Sel &= ~X86_SEL_RPL; if ((pCtx->es.Sel & X86_SEL_RPL) == 1) pCtx->es.Sel &= ~X86_SEL_RPL; if ((pCtx->fs.Sel & X86_SEL_RPL) == 1) pCtx->fs.Sel &= ~X86_SEL_RPL; if ((pCtx->gs.Sel & X86_SEL_RPL) == 1) pCtx->gs.Sel &= ~X86_SEL_RPL; # ifdef VBOX_WITH_RAW_RING1 } # endif } } return rc; } #endif /* VBOX_WITH_RAW_MODE_NOT_R0 */ /** * Updates the EFLAGS while we're in raw-mode. * * @param pVCpu Pointer to the VMCPU. * @param fEfl The new EFLAGS value. */ VMMDECL(void) CPUMRawSetEFlags(PVMCPU pVCpu, uint32_t fEfl) { #ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (pVCpu->cpum.s.fRawEntered) PATMRawSetEFlags(pVCpu->CTX_SUFF(pVM), &pVCpu->cpum.s.Guest, fEfl); else #endif pVCpu->cpum.s.Guest.eflags.u32 = fEfl; } /** * Gets the EFLAGS while we're in raw-mode. * * @returns The eflags. * @param pVCpu Pointer to the current virtual CPU. */ VMMDECL(uint32_t) CPUMRawGetEFlags(PVMCPU pVCpu) { #ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (pVCpu->cpum.s.fRawEntered) return PATMRawGetEFlags(pVCpu->CTX_SUFF(pVM), &pVCpu->cpum.s.Guest); #endif return pVCpu->cpum.s.Guest.eflags.u32; } /** * Sets the specified changed flags (CPUM_CHANGED_*). * * @param pVCpu Pointer to the current virtual CPU. */ VMMDECL(void) CPUMSetChangedFlags(PVMCPU pVCpu, uint32_t fChangedFlags) { pVCpu->cpum.s.fChanged |= fChangedFlags; } /** * Checks if the CPU supports the XSAVE and XRSTOR instruction. * * @returns true if supported. * @returns false if not supported. * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMSupportsXSave(PVM pVM) { return pVM->cpum.s.HostFeatures.fXSaveRstor != 0; } /** * Checks if the host OS uses the SYSENTER / SYSEXIT instructions. * @returns true if used. * @returns false if not used. * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMIsHostUsingSysEnter(PVM pVM) { return RT_BOOL(pVM->cpum.s.fHostUseFlags & CPUM_USE_SYSENTER); } /** * Checks if the host OS uses the SYSCALL / SYSRET instructions. * @returns true if used. * @returns false if not used. * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMIsHostUsingSysCall(PVM pVM) { return RT_BOOL(pVM->cpum.s.fHostUseFlags & CPUM_USE_SYSCALL); } #ifdef IN_RC /** * Lazily sync in the FPU/XMM state. * * @returns VBox status code. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(int) CPUMHandleLazyFPU(PVMCPU pVCpu) { return cpumHandleLazyFPUAsm(&pVCpu->cpum.s); } #endif /* !IN_RC */ /** * Checks if we activated the FPU/XMM state of the guest OS. * @returns true if we did. * @returns false if not. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestFPUStateActive(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_USED_FPU); } /** * Checks if the guest debug state is active. * * @returns boolean * @param pVM Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestDebugStateActive(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_GUEST); } /** * Checks if the guest debug state is to be made active during the world-switch * (currently only used for the 32->64 switcher case). * * @returns boolean * @param pVM Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestDebugStateActivePending(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_SYNC_DEBUG_REGS_GUEST); } /** * Checks if the hyper debug state is active. * * @returns boolean * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMIsHyperDebugStateActive(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER); } /** * Checks if the hyper debug state is to be made active during the world-switch * (currently only used for the 32->64 switcher case). * * @returns boolean * @param pVM Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsHyperDebugStateActivePending(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_SYNC_DEBUG_REGS_HYPER); } /** * Mark the guest's debug state as inactive. * * @returns boolean * @param pVM Pointer to the VM. * @todo This API doesn't make sense any more. */ VMMDECL(void) CPUMDeactivateGuestDebugState(PVMCPU pVCpu) { Assert(!(pVCpu->cpum.s.fUseFlags & (CPUM_USED_DEBUG_REGS_GUEST | CPUM_USED_DEBUG_REGS_HYPER | CPUM_USED_DEBUG_REGS_HOST))); } /** * Get the current privilege level of the guest. * * @returns CPL * @param pVCpu Pointer to the current virtual CPU. */ VMMDECL(uint32_t) CPUMGetGuestCPL(PVMCPU pVCpu) { /* * CPL can reliably be found in SS.DPL (hidden regs valid) or SS if not. * * Note! We used to check CS.DPL here, assuming it was always equal to * CPL even if a conforming segment was loaded. But this truned out to * only apply to older AMD-V. With VT-x we had an ACP2 regression * during install after a far call to ring 2 with VT-x. Then on newer * AMD-V CPUs we have to move the VMCB.guest.u8CPL into cs.Attr.n.u2Dpl * as well as ss.Attr.n.u2Dpl to make this (and other) code work right. * * So, forget CS.DPL, always use SS.DPL. * * Note! The SS RPL is always equal to the CPL, while the CS RPL * isn't necessarily equal if the segment is conforming. * See section 4.11.1 in the AMD manual. * * Update: Where the heck does it say CS.RPL can differ from CPL other than * right after real->prot mode switch and when in V8086 mode? That * section says the RPL specified in a direct transfere (call, jmp, * ret) is not the one loaded into CS. Besides, if CS.RPL != CPL * it would be impossible for an exception handle or the iret * instruction to figure out whether SS:ESP are part of the frame * or not. VBox or qemu bug must've lead to this misconception. * * Update2: On an AMD bulldozer system here, I've no trouble loading a null * selector into SS with an RPL other than the CPL when CPL != 3 and * we're in 64-bit mode. The intel dev box doesn't allow this, on * RPL = CPL. Weird. */ uint32_t uCpl; if (pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE) { if (!pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { if (CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, &pVCpu->cpum.s.Guest.ss)) uCpl = pVCpu->cpum.s.Guest.ss.Attr.n.u2Dpl; else { uCpl = (pVCpu->cpum.s.Guest.ss.Sel & X86_SEL_RPL); #ifdef VBOX_WITH_RAW_MODE_NOT_R0 # ifdef VBOX_WITH_RAW_RING1 if (pVCpu->cpum.s.fRawEntered) { if ( uCpl == 2 && EMIsRawRing1Enabled(pVCpu->CTX_SUFF(pVM))) uCpl = 1; else if (uCpl == 1) uCpl = 0; } Assert(uCpl != 2); /* ring 2 support not allowed anymore. */ # else if (uCpl == 1) uCpl = 0; # endif #endif } } else uCpl = 3; /* V86 has CPL=3; REM doesn't set DPL=3 in V8086 mode. See @bugref{5130}. */ } else uCpl = 0; /* Real mode is zero; CPL set to 3 for VT-x real-mode emulation. */ return uCpl; } /** * Gets the current guest CPU mode. * * If paging mode is what you need, check out PGMGetGuestMode(). * * @returns The CPU mode. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(CPUMMODE) CPUMGetGuestMode(PVMCPU pVCpu) { CPUMMODE enmMode; if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) enmMode = CPUMMODE_REAL; else if (!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)) enmMode = CPUMMODE_PROTECTED; else enmMode = CPUMMODE_LONG; return enmMode; } /** * Figure whether the CPU is currently executing 16, 32 or 64 bit code. * * @returns 16, 32 or 64. * @param pVCpu The current virtual CPU. */ VMMDECL(uint32_t) CPUMGetGuestCodeBits(PVMCPU pVCpu) { if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) return 16; if (pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { Assert(!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)); return 16; } CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); if ( pVCpu->cpum.s.Guest.cs.Attr.n.u1Long && (pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)) return 64; if (pVCpu->cpum.s.Guest.cs.Attr.n.u1DefBig) return 32; return 16; } VMMDECL(DISCPUMODE) CPUMGetGuestDisMode(PVMCPU pVCpu) { if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) return DISCPUMODE_16BIT; if (pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { Assert(!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)); return DISCPUMODE_16BIT; } CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); if ( pVCpu->cpum.s.Guest.cs.Attr.n.u1Long && (pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)) return DISCPUMODE_64BIT; if (pVCpu->cpum.s.Guest.cs.Attr.n.u1DefBig) return DISCPUMODE_32BIT; return DISCPUMODE_16BIT; }
30.237081
133
0.601993
egraba
eb2a24dc18716cab6697c6fa3608c3806d954948
5,322
cc
C++
crosdns/hosts_modifier_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
crosdns/hosts_modifier_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
crosdns/hosts_modifier_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "crosdns/hosts_modifier.h" #include <string> #include <base/files/scoped_temp_dir.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <gtest/gtest.h> namespace crosdns { namespace { constexpr char kBaseFileContents[] = "# Example /etc/hosts file\n" "127.0.0.1 localhost\n"; constexpr char kFileModificationDelimeter[] = "\n#####DYNAMIC-CROSDNS-ENTRIES#####\n"; class HostsModifierTest : public ::testing::Test { public: HostsModifierTest() { CHECK(temp_dir_.CreateUniqueTempDir()); hosts_file_ = temp_dir_.GetPath().Append("hosts"); WriteHostsContents(kBaseFileContents); } HostsModifierTest(const HostsModifierTest&) = delete; HostsModifierTest& operator=(const HostsModifierTest&) = delete; ~HostsModifierTest() override = default; void WriteHostsContents(const std::string& file_contents) { EXPECT_EQ(file_contents.size(), base::WriteFile(hosts_file_, file_contents.c_str(), file_contents.size())); } std::string ReadHostsContents() const { std::string ret; EXPECT_TRUE(base::ReadFileToString(hosts_file_, &ret)); return ret; } HostsModifier* hosts_modifier() { return &hosts_modifier_; } base::FilePath hosts_file() const { return hosts_file_; } private: base::ScopedTempDir temp_dir_; base::FilePath hosts_file_; HostsModifier hosts_modifier_; }; } // namespace TEST_F(HostsModifierTest, InitSucceeds) { EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // The hosts file contents should be unchanged now. EXPECT_EQ(kBaseFileContents, ReadHostsContents()); } TEST_F(HostsModifierTest, InitFailsNonExistentFile) { EXPECT_TRUE(base::DeleteFile(hosts_file())); EXPECT_FALSE(hosts_modifier()->Init(hosts_file())); } TEST_F(HostsModifierTest, InitRemovesOldEntries) { std::string extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "1.2.3.4 example.com\n"; WriteHostsContents(extra_contents); EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // The hosts file contents should be the original contents up to our // delimeter. EXPECT_EQ(kBaseFileContents, ReadHostsContents()); } TEST_F(HostsModifierTest, SettingRemovingHostnames) { std::string err; EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // Valid hostname for default container. EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "100.115.92.24", "", &err)); // Valid hostnames for vm/container. EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "foo12.linux.test", "100.115.92.22", "", &err)); EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "penguin.termina.linux.test", "100.115.92.253", "", &err)); // Invalid hostnames. EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "google.com", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "localhost", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "-foo-local", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "foo..linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( ".linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE( hosts_modifier()->SetHostnameIpMapping("", "100.115.92.24", "", &err)); // Invalid IPs. EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "100.115.91.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping("penguin.linux.test", "8.8.8.8", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "101.115.92.24", "", &err)); // Verify the contents of the hosts file. We are assuming an ordered map is // used here (which it is in the code) to make analyzing the results easier. std::string extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "100.115.92.22 foo12.linux.test\n"; extra_contents += "100.115.92.24 penguin.linux.test\n"; extra_contents += "100.115.92.253 penguin.termina.linux.test\n"; EXPECT_EQ(extra_contents, ReadHostsContents()); // Removing an invalid hostname should fail. EXPECT_FALSE(hosts_modifier()->RemoveHostnameIpMapping("bar-local", &err)); EXPECT_FALSE(hosts_modifier()->RemoveHostnameIpMapping("google.com", &err)); // Removing a valid hostname should succeed. EXPECT_TRUE( hosts_modifier()->RemoveHostnameIpMapping("penguin.linux.test", &err)); EXPECT_TRUE( hosts_modifier()->RemoveHostnameIpMapping("foo12.linux.test", &err)); // Verify the contents of the hosts file again, there should be one entry // left. extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "100.115.92.253 penguin.termina.linux.test\n"; EXPECT_EQ(extra_contents, ReadHostsContents()); } } // namespace crosdns
37.744681
78
0.708568
dgreid
eb3217a3380b7b765ddf7ba8a8ee22cf96fa262b
2,662
cpp
C++
algorithms/binary_search_tree.cpp
sylveryte/algorithms-data-structure-cpp
3fc4690972fa061851f7a46a06797bf441043eda
[ "MIT" ]
null
null
null
algorithms/binary_search_tree.cpp
sylveryte/algorithms-data-structure-cpp
3fc4690972fa061851f7a46a06797bf441043eda
[ "MIT" ]
null
null
null
algorithms/binary_search_tree.cpp
sylveryte/algorithms-data-structure-cpp
3fc4690972fa061851f7a46a06797bf441043eda
[ "MIT" ]
null
null
null
/* * binary_search_tree.cpp * Copyright (C) 2020 sylveryte <sylveryte@archred> * * Distributed under terms of the MIT license. */ #include "binary_search_tree.h" #include "../sylvtools.cpp" int main(){ binary_search_tree b(21); b.insert(21); b.insert(1); b.insert(23); b.insert(233); b.insert(4); b.print_tree(); //to sort //yeah!! i'm amazing int a[13]={12,24,54,2,452,36,23,6,325732,45,2346234,23,1}; printa("before",a,13); binary_search_tree sor(12); for(int i=1;i<13;i++)sor.insert(a[i]); sor.print_tree(); sor.get_sorted_array(a); printa("after",a,13); return 0; } //implementations binary_search_tree::binary_search_tree(int value){ this -> head = new node(value); this -> size = 1; } void binary_search_tree::insert(int value){ node* node_ptr = this -> head; while(true) if(node_ptr -> value >= value){ //cout << "arg " << node_ptr-> value << " <= " << value << endl; //cout << "adding " << value << " to left" << endl; if( node_ptr -> leftchild == nullptr) { node_ptr -> leftchild = new node(value); node_ptr -> leftchild -> parent = node_ptr; this -> size++; break; } node_ptr = node_ptr -> leftchild; } else{ //cout << "arg " << node_ptr-> value << " > " << value << endl; //cout << "adding " << value << " to rigth" << endl; if( node_ptr -> rightchild == nullptr) { node_ptr -> rightchild = new node(value); node_ptr -> rightchild -> parent = node_ptr; this -> size++; break; } node_ptr = node_ptr -> rightchild; } } void binary_search_tree::inorder_traverse(int* a, node* n){ /* takes an empty array a and node from where sorted array needed. * fills array with ascending order node vallues (sorted array) using inorder_traverssal * */ if(n-> leftchild != nullptr)inorder_traverse(a,n->leftchild); a[this -> inorder_index++]=n->value; if(n-> rightchild != nullptr)inorder_traverse(a,n->rightchild); } void binary_search_tree::get_sorted_array(int* a){ this -> inorder_index = 0; inorder_traverse(a,this->head); } /* printing purpose */ void binary_search_tree::print_node(node* ptr){ if(ptr -> leftchild == nullptr && ptr -> rightchild == nullptr)return; cout << "|| " << ptr -> value << " : "; if(ptr->leftchild != nullptr){ cout << ptr-> leftchild-> value ; } cout<< " _ "; if(ptr->rightchild != nullptr){ cout << ptr-> rightchild-> value ; } cout << " ||" << endl; if(ptr->leftchild != nullptr)print_node(ptr->leftchild); if(ptr->rightchild != nullptr)print_node(ptr->rightchild); } void binary_search_tree::print_tree(){ cout << "Tree of size : " << this->size << endl; print_node(this->head); cout <<endl; }
25.84466
89
0.635988
sylveryte
eb33b183ed90e4998b9537607d6f85c34383b990
10,369
cpp
C++
Asteroid.cpp
timaeudg/3DAsteroids
d6d3047ee4375ce2ac54081ed0311bd73023b458
[ "BSD-2-Clause" ]
1
2015-05-04T07:04:04.000Z
2015-05-04T07:04:04.000Z
Asteroid.cpp
timaeudg/3DAsteroids
d6d3047ee4375ce2ac54081ed0311bd73023b458
[ "BSD-2-Clause" ]
null
null
null
Asteroid.cpp
timaeudg/3DAsteroids
d6d3047ee4375ce2ac54081ed0311bd73023b458
[ "BSD-2-Clause" ]
null
null
null
#include "Asteroid.h" #define REFINEMENT_LEVEL 2 #define BASE_RADIUS 1.9021f #define MAX_VELOCITY 0.05 #define MAX_ROTATION 5.0 float Asteroid::nextID = 1.0; Asteroid::Asteroid(){ Asteroid(glm::vec3(0), 0, 1.9021); } Asteroid::Asteroid(glm::vec3 startingPosition, int elementOffset, GLfloat radius) { this->radius = radius; setStartingPoint(startingPosition); this->elementOffset = elementOffset; alive = true; asteroidID = nextID; nextID += 1.0; generateAsteroidBase(); deformAndTransformBase(); calculateDeformedResultantRadius(); GLfloat xPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); GLfloat yPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); GLfloat zPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); velocityVector = glm::vec3(xPos, yPos, zPos); GLfloat xRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); GLfloat yRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); GLfloat zRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); this->rotationRates = glm::vec3(xRot, yRot, zRot); this->rotation = glm::mat4(1); } Asteroid::~Asteroid(void) { } vector<GLfloat> Asteroid::getNormals(){ return this->asteroidGLNormals; } vector<GLfloat> Asteroid::getVertices(){ return this->asteroidGLVertices; } vector<GLuint> Asteroid::getElementArray(){ return elements; } vector<GLfloat> Asteroid::getColors(){ return colors; } glm::vec3 Asteroid::getPosition(){ return this->position; } GLfloat Asteroid::getRadius(){ return this->radius; } bool Asteroid::isAlive(){ return alive; } void Asteroid::kill(){ this->alive = false; } float Asteroid::getID(){ return this->asteroidID; } void Asteroid::setStartingPoint(glm::vec3 startingPosition){ this->position = startingPosition; glm::vec3 translateVector = this->position; this->translation = glm::translate(glm::mat4(1), translateVector); } glm::mat4 Asteroid::getTransformMatrix(float bounds, bool pickingPass){ glm::mat4 S = glm::scale(glm::mat4(1), glm::vec3(radius / deformedResultantRadius, radius / deformedResultantRadius, radius / deformedResultantRadius)); if(!pickingPass){ this->position += velocityVector; glm::mat4 T = glm::translate(this->translation, velocityVector); this->translation = T; if(this->position.x + radius >= bounds || this->position.x - radius <= -bounds){ velocityVector = glm::vec3(-velocityVector.x, velocityVector.y, velocityVector.z); rotationRates = glm::vec3(rotationRates.x, -rotationRates.y, -rotationRates.z); } if(this->position.y + radius >= bounds || this->position.y - radius <= -bounds){ velocityVector = glm::vec3(velocityVector.x, -velocityVector.y, velocityVector.z); rotationRates = glm::vec3(-rotationRates.x, rotationRates.y, -rotationRates.z); } if(this->position.z + radius>= bounds || this->position.z - radius<= -bounds){ velocityVector = glm::vec3(velocityVector.x, velocityVector.y, -velocityVector.z); rotationRates = glm::vec3(-rotationRates.x, -rotationRates.y, rotationRates.z); } glm::mat4 R = glm::rotate(this->rotation, rotationRates.x, glm::vec3(1,0,0)); R = glm::rotate(R, rotationRates.y, glm::vec3(0,1,0)); R = glm::rotate(R, rotationRates.z, glm::vec3(0,0,1)); this->rotation = R; return T*R*S; } else { return this->translation * this->rotation * S; } } void Asteroid::generateAsteroidBase(){ if(this->asteroidPoints.size() == 0){ //We haven't made the base of the asteroid, so we need to createIcosahedronPoints(); createIcosahedronTriangles(); //Now we have the icosahedron, we should make it a bit better though for(int i = 0; i < REFINEMENT_LEVEL; i++){ deformAsteroid(&this->asteroidPoints); refineIcoSphere(); } } } void Asteroid::deformAndTransformBase(){ transformToGL(); vector<GLuint> elements = vector<GLuint>(); for(int i = 0; i < this->asteroidTriangles.size()*3; i++){ elements.push_back(i+this->elementOffset); } this->elements = elements; for(int i = 0; i < this->asteroidGLVertices.size(); i++){ this->colors.push_back(1.0f); this->colors.push_back(1.0f); this->colors.push_back(1.0f); } } void Asteroid::transformToGL(){ for(int i = 0; i < this->asteroidTriangles.size(); i++){ Triangle* tri = &this->asteroidTriangles[i]; tri->recalculateNormal(this->asteroidPoints[tri->p1Index], this->asteroidPoints[tri->p2Index], this->asteroidPoints[tri->p3Index]); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.b); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.b); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.b); for(int k = 0; k < 3; k++){ this->asteroidGLNormals.push_back(tri->normal.r); this->asteroidGLNormals.push_back(tri->normal.g); this->asteroidGLNormals.push_back(tri->normal.b); } } } void Asteroid::deformAsteroid(vector<Point>* points){ //srand(time(NULL)); for(int i = 0; i < points->size(); i++){ points->data()[i].moveInRandomDirection(1.0f); } } void Asteroid::createIcosahedronPoints(){ GLfloat reductionFactor = 1; GLfloat baseSize = 1; GLfloat t = (1.0 + sqrt(5.0)) / 2.0; t = reductionFactor * t; baseSize = baseSize * reductionFactor; this->asteroidPoints.push_back(Point(-baseSize, t, 0)); this->asteroidPoints.push_back(Point( baseSize, t, 0)); this->asteroidPoints.push_back(Point(-baseSize, -t, 0)); this->asteroidPoints.push_back(Point( baseSize, -t, 0)); this->asteroidPoints.push_back(Point( 0, -baseSize, t)); this->asteroidPoints.push_back(Point( 0, baseSize, t)); this->asteroidPoints.push_back(Point( 0, -baseSize, -t)); this->asteroidPoints.push_back(Point( 0, baseSize, -t)); this->asteroidPoints.push_back(Point( t, 0, -baseSize)); this->asteroidPoints.push_back(Point( t, 0, baseSize)); this->asteroidPoints.push_back(Point(-t, 0, -baseSize)); this->asteroidPoints.push_back(Point(-t, 0, baseSize)); } void Asteroid::createIcosahedronTriangles(){ this->asteroidTriangles.push_back(Triangle( 0, 11, 5)); this->asteroidTriangles.push_back(Triangle( 0, 5, 1)); this->asteroidTriangles.push_back(Triangle( 0, 1, 7)); this->asteroidTriangles.push_back(Triangle( 0, 7, 10)); this->asteroidTriangles.push_back(Triangle( 0, 10, 11)); this->asteroidTriangles.push_back(Triangle( 1, 5, 9)); this->asteroidTriangles.push_back(Triangle( 5, 11, 4)); this->asteroidTriangles.push_back(Triangle(11, 10, 2)); this->asteroidTriangles.push_back(Triangle(10, 7, 6)); this->asteroidTriangles.push_back(Triangle( 7, 1, 8)); this->asteroidTriangles.push_back(Triangle( 3, 9, 4)); this->asteroidTriangles.push_back(Triangle( 3, 4, 2)); this->asteroidTriangles.push_back(Triangle( 3, 2, 6)); this->asteroidTriangles.push_back(Triangle( 3, 6, 8)); this->asteroidTriangles.push_back(Triangle( 3, 8, 9)); this->asteroidTriangles.push_back(Triangle( 4, 9, 5)); this->asteroidTriangles.push_back(Triangle( 2, 4, 11)); this->asteroidTriangles.push_back(Triangle( 6, 2, 10)); this->asteroidTriangles.push_back(Triangle( 8, 6, 7)); this->asteroidTriangles.push_back(Triangle( 9, 8, 1)); } int Asteroid::calculateMiddlePoint(int p1, int p2, vector<Point>* points){ bool firstSmaller = p1 < p2; int64_t smallerIndex = firstSmaller ? p1 : p2; int64_t greaterIndex = firstSmaller ? p2 : p1; int64_t key = (smallerIndex << 32) + greaterIndex; map<int64_t, int>::iterator iter = middlePointCache.find(key); if(iter != middlePointCache.end()){ //We found the element return iter->second; } Point* first = &((*points)[p1]); Point* second = &((*points)[p2]); Point middlePoint = Point((first->coords.r + second->coords.r)/2.0, (first->coords.g + second->coords.g)/2.0, (first->coords.b + second->coords.b)/2.0); int index = affixVertex(middlePoint, *first, points); middlePointCache.insert(make_pair(key, index)); return index; } int Asteroid::affixVertex(Point middlePoint, Point derpPoint, vector<Point>* pointsVector){ double derpLength = sqrt(derpPoint.coords.r*derpPoint.coords.r + derpPoint.coords.g*derpPoint.coords.g + derpPoint.coords.b*derpPoint.coords.b); double length = sqrt(middlePoint.coords.r*middlePoint.coords.r + middlePoint.coords.g*middlePoint.coords.g + middlePoint.coords.b*middlePoint.coords.b); double ration = derpLength / length; //ration = 1 / length; //length = length/2; (*pointsVector).push_back(Point(middlePoint.coords.r * ration, middlePoint.coords.g * ration, middlePoint.coords.b * ration)); return (*pointsVector).size()-1; } void Asteroid::refineIcoSphere(){ vector<Triangle> refined = vector<Triangle>(); for(int i = 0; i < this->asteroidTriangles.size(); i++){ Triangle tri = this->asteroidTriangles[i]; int a = calculateMiddlePoint(tri.p1Index, tri.p2Index, &this->asteroidPoints); int b = calculateMiddlePoint(tri.p2Index, tri.p3Index, &this->asteroidPoints); int c = calculateMiddlePoint(tri.p3Index, tri.p1Index, &this->asteroidPoints); refined.push_back(Triangle(tri.p1Index, a, c)); refined.push_back(Triangle(tri.p2Index, b, a)); refined.push_back(Triangle(tri.p3Index, c, b)); refined.push_back(Triangle(a, b, c)); } this->asteroidTriangles = refined; } void Asteroid::calculateDeformedResultantRadius(){ GLfloat maxRadius = BASE_RADIUS; for(int i = 0; i < this->asteroidPoints.size(); i++){ Point p = this->asteroidPoints.data()[i]; GLfloat currentRadius = sqrt(p.coords.r*p.coords.r + p.coords.g*p.coords.g + p.coords.b*p.coords.g); if(currentRadius > maxRadius){ maxRadius = currentRadius; } } this->deformedResultantRadius = maxRadius; }
34.448505
153
0.710001
timaeudg
eb346af7783658da8c00b7985a993aa1b8fb67b2
13,440
cc
C++
puzzle/dance.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
1,418
2015-01-07T09:40:09.000Z
2022-03-29T08:37:02.000Z
puzzle/dance.cc
algoideas/recipes
77bc5cb180e49edb31983938386ef23f752e2d2f
[ "BSD-3-Clause" ]
44
2018-12-14T02:35:47.000Z
2021-02-06T09:12:10.000Z
KM/03code/cpp/chenshuo/recipes/puzzle/dance.cc
wangcy6/weekly
f249bed5cf5a2b14d798ac33086cea0c1efe432e
[ "Apache-2.0" ]
854
2015-01-03T11:56:10.000Z
2022-03-31T08:50:28.000Z
#include <assert.h> #include <memory.h> #include <stdio.h> #include <algorithm> #include <vector> #include <string> using namespace std; struct Node; typedef Node Column; struct Node { Node* left; Node* right; Node* up; Node* down; Column* col; int col_idx; const char* name; int size; }; const int kMaxNodes = 25 * 2 * 5 * 2; const int kMaxColumns = 5 * 2 * 5; struct Dance { Column* root_; int* inout_; Column* columns_[100]; vector<Node*> stack_; Node nodes_[kMaxNodes]; int cur_node_; int cnt_; Column* new_column(int n = 0) { assert(cur_node_ < kMaxNodes); Column* c = &nodes_[cur_node_++]; memset(c, 0, sizeof(Column)); c->left = c; c->right = c; c->up = c; c->down = c; c->col = c; c->col_idx = n; return c; } void append_column(int n) { assert(columns_[n] == NULL); Column* c = new_column(n); put_left(root_, c); columns_[n] = c; } Node* new_row(int col) { assert(columns_[col] != NULL); assert(cur_node_ < kMaxNodes); Node* r = &nodes_[cur_node_++]; memset(r, 0, sizeof(Node)); r->left = r; r->right = r; r->up = r; r->down = r; r->col_idx = col; r->col = columns_[col]; put_up(r->col, r); return r; } Dance() : inout_(NULL), cur_node_(0), cnt_(0) { stack_.reserve(100); root_ = new_column(); root_->left = root_->right = root_; memset(columns_, 0, sizeof(columns_)); setup(); } Column* get_min_column() { Column* c = root_->right; int min_size = c->size; if (min_size > 1) { for (Column* cc = c->right; cc != root_; cc = cc->right) { if (min_size > cc->size) { c = cc; min_size = cc->size; if (min_size <= 1) break; } } } return c; } void cover(Column* c) { c->right->left = c->left; c->left->right = c->right; for (Node* row = c->down; row != c; row = row->down) { for (Node* j = row->right; j != row; j = j->right) { j->down->up = j->up; j->up->down = j->down; j->col->size--; } } } void uncover(Column* c) { for (Node* row = c->up; row != c; row = row->up) { for (Node* j = row->left; j != row; j = j->left) { j->col->size++; j->down->up = j; j->up->down = j; } } c->right->left = c; c->left->right = c; } void put_left(Column* old, Column* nnew) { nnew->left = old->left; nnew->right = old; old->left->right = nnew; old->left = nnew; } void put_up(Column* old, Node* nnew) { nnew->up = old->up; nnew->down = old; old->up->down = nnew; old->up = nnew; old->size++; nnew->col = old; } bool solve() { if (root_->left == root_) { printf("found %d '0123456789|0123456789|0123456789|0123456789|0123456789|'\n", ++cnt_); for (size_t i = 0; i < stack_.size(); ++i) { Node* n = stack_[i]; printf(" node = '%s'\n", n->name); } return true; } Column* const col = get_min_column(); cover(col); for (Node* row = col->down; row != col; row = row->down) { stack_.push_back(row); for (Node* j = row->right; j != row; j = j->right) { cover(j->col); } if (solve()) { // return true; } stack_.pop_back(); for (Node* j = row->left; j != row; j = j->left) { uncover(j->col); } } uncover(col); return false; } void setup() { for (int i = 0; i < 5 * 2 * 5; ++i) { append_column(i); } const char* image[] = { // Nation | Color | Drink | Pet | Cigar // 5 - Eng 5 - Red 5 - Tea 5 - Dog 5 - Pall Mall // 6 - Swe 6 - Green 6 - Cof 6 - Bird 6 - Dunhill // 7 - Dan 7 - Yellow 7 - Milk 7 - Horse 7 - Blends // 8 - Nor 8 - Blue 8 - Beer 8 - Cat 8 - Blue Master // 9 - Gem 9 - White 9 - Water 9 - 9 - Prince // 0123456789|0123456789|0123456789|0123456789|0123456789|0123456789| // "1 1 | | | | |", // "1 1 | | | | |", // "1 1 | | | | |", "1 1 | 1 1 | | | |", // "1 1| | | | |", " 1 1 | 1 1 | | | |", " 1 1 | | | 1 1 | |", " 1 1 | | 1 1 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " 1 1 | 1 1 | | | |", " 1 1 | | | 1 1 | |", " 1 1 | | 1 1 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " 1 1 | 1 1 | | | |", " 1 1 | | | 1 1 | |", " 1 1 | | 1 1 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " 11 | 11 | | | |", " 1 1 | | | 11 | |", " 1 1 | | 11 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " |1 1 | | | |", " |11 1 1|1 1 | | |", " |1 1 | | 1 1 |1 1 |", " |1 1 | | | |", " |1 1| | | |", " | 1 1 | | | |", " | 11 1 1| 1 1 | | |", " | 1 1 | |1 | 1 1 |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | 1 1 | | | |", " | 11 1 1| 1 1 | | |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | 1 1 | | | |", " | 11 1 1| 1 1 | | |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | 11 | | | |", // " | 1 1 | 1 1 | | |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | |1 1 | | |", " | |1 1 | | |", // " | |1 1 | | |", " | |1 1 | |1 1 |", " | |1 1| | |", " | | 1 1 | | |", " | | 1 1 | | |", // " | | 1 1 | | |", " | | 1 1 | | 1 1 |", " | | 1 1| | |", " | | 1 1 | | |", " | | 1 1 | | |", " | | 1 1 | | |", " | | 1 1 | | |", " | | 1 1| | |", " | | 1 1 | | |", " | | 1 1 | | |", // " | | 1 1 | | |", " | | 1 1 | | 1 1 |", " | | 1 1| | |", " | | 11 | | |", " | | 1 1 | | |", // " | | 1 1 | | |", " | | 1 1 | | 1 1 |", " | | 1 1| | |", " | | |1 1 | |", " | | |1 1 |1 1 |", " | | |1 1 | |", " | | |1 1 | 1 1 |", " | | |1 1| |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | |", " | | | 1 1 |1 1 |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | 11 | |", " | | | 1 1 | 11 |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | |1 1 |", " | | | |1 1 |", " | | | |1 1 |", " | | | |1 1 |", " | | | |1 1|", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", " | | | | 11 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", NULL }; for (int line = 0; image[line] != NULL; ++line) { std::string thisLine(image[line]); std::string::iterator it = std::remove(thisLine.begin(), thisLine.end(), '|'); thisLine.erase(it, thisLine.end()); const char* row = thisLine.c_str(); const char* first = strchr(row, '1'); assert(first != NULL); Node* n0 = new_row(first - row); n0->name = image[line]; printf("\n%d: %d", line, first - row); const char* next = strchr(first+1, '1'); while (next) { Node* n = new_row(next - row); n->name = image[line]; printf(", %d", next - row); put_left(n0, n); next = strchr(next+1, '1'); } } printf("\n"); } }; int main() { Dance d; d.solve(); }
37.229917
93
0.210491
ririripley
eb35b6ab1b405a6864b888ba7b72b6525eadf4f9
1,411
cpp
C++
Assigment 13/a13_p7.cpp
UrfanAlvany/Programming-in-C-and-Cpp
e23a485d5ce302cbbc14bd67a0f656797c3f6af1
[ "MIT" ]
1
2022-01-02T16:02:09.000Z
2022-01-02T16:02:09.000Z
Assigment 13/a13_p7.cpp
UrfanAlvany/Programming-in-C-and-Cpp
e23a485d5ce302cbbc14bd67a0f656797c3f6af1
[ "MIT" ]
null
null
null
Assigment 13/a13_p7.cpp
UrfanAlvany/Programming-in-C-and-Cpp
e23a485d5ce302cbbc14bd67a0f656797c3f6af1
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include <string> using namespace std; class OwnException: public exception{ //class derived from exception private: string a; //declaring string public: OwnException(){ a = "Default case exception"; //when default thsi is printed } OwnException(const string& s){ this->a = a; } virtual const char* what() const throw(){ //overwriting what() return "OwnException"; } }; void types(int n){ switch(n){ case 1: //when parameter is 1 a is thrown throw 'a'; break; case 2: //when parameter is 2, 12 is thrown throw 12; break; case 3: //when parameter is 3, bool is true throw true; break; default: //default throw new OwnException; } return; } int main(){ try{ types(1); //try with parameter 1 } catch(char ch){ cerr<<"Exception caught in main: "<<ch<<endl; } try{ types(2); //try with parameter 2 } catch(int i){ cerr<<"Exception caught in main: "<<i<<endl; } try{ types(3); //try with parameter 3 } catch(bool t){ cerr<<"Exception caught in main: "<<t<<endl; } try{ types(4); //try with parameter 4 } catch(OwnException* m){ cerr<<"Exception caught in main: "<<m->what()<<endl; } return 1; }
20.75
68
0.554926
UrfanAlvany
eb36232e45bd0e485e485524f1039cc48db55613
6,137
cpp
C++
samples/tools/save_pose_into_pcd.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
samples/tools/save_pose_into_pcd.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
samples/tools/save_pose_into_pcd.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
/* * adds pose information given by pose_000x.txt into cloud_000x.pcd files (old dataset structure) * now we can use pcl_viewer *.pcd to show all point clouds in common coordinate system * * Created on: Dec 04, 2014 * Author: Thomas Faeulhammer * */ #include <v4r/io/filesystem.h> #include <v4r/io/eigen.h> #include <v4r/common/faat_3d_rec_framework_defines.h> #include <v4r/common/pcl_utils.h> #include <pcl/common/transforms.h> #include <pcl/console/parse.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <sstream> #include <boost/program_options.hpp> #include <glog/logging.h> namespace po = boost::program_options; typedef pcl::PointXYZRGB PointT; int main (int argc, char ** argv) { std::string input_dir, out_dir = "/tmp/clouds_with_pose/"; std::string cloud_prefix = "cloud_", pose_prefix = "pose_", indices_prefix = "object_indices_"; bool invert_pose = false; bool use_indices = false; po::options_description desc("Save camera pose given by seperate pose file directly into header of .pcd file\n======================================\n**Allowed options"); desc.add_options() ("help,h", "produce help message") ("input_dir,i", po::value<std::string>(&input_dir)->required(), "directory containing both .pcd and pose files") ("output_dir,o", po::value<std::string>(&out_dir)->default_value(out_dir), "output directory") ("use_indices,u", po::bool_switch(&use_indices), "if true, uses indices") ("invert_pose,t", po::bool_switch(&invert_pose), "if true, takes the inverse of the pose file (e.g. required for Willow Dataset)") ("cloud_prefix,c", po::value<std::string>(&cloud_prefix)->default_value(cloud_prefix)->implicit_value(""), "prefix of cloud names") ("pose_prefix,p", po::value<std::string>(&pose_prefix)->default_value(pose_prefix), "prefix of camera pose names (e.g. transformation_)") ("indices_prefix,d", po::value<std::string>(&indices_prefix)->default_value(indices_prefix), "prefix of object indices names") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return false; } try { po::notify(vm); } catch(std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl; return false; } std::vector< std::string> sub_folder_names = v4r::io::getFoldersInDirectory( input_dir ); if( sub_folder_names.empty() ) sub_folder_names.push_back(""); for (const std::string &sub_folder : sub_folder_names) { const std::string path_extended = input_dir + "/" + sub_folder; std::cout << "Processing all point clouds in folder " << path_extended; // const std::string search_pattern = ".*." + cloud_prefix + ".*.pcd"; const std::string search_pattern = ".*.pcd"; std::vector < std::string > cloud_files = v4r::io::getFilesInDirectory (path_extended, search_pattern, true); for (const std::string &cloud_file : cloud_files) { const std::string full_path = path_extended + "/" + cloud_file; const std::string out_fn = out_dir + "/" + sub_folder + "/" + cloud_file; // Loading file and corresponding indices file (if it exists) pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>); pcl::io::loadPCDFile (full_path, *cloud); if(use_indices) { // Check if indices file exist std::string indices_filename( cloud_file ); boost::replace_first (indices_filename, cloud_prefix, indices_prefix); if( v4r::io::existsFile( path_extended+"/"+indices_filename ) ) { pcl::PointCloud<IndexPoint> obj_indices_cloud; pcl::io::loadPCDFile(path_extended+"/"+indices_filename, obj_indices_cloud); pcl::PointIndices indices; indices.indices.resize(obj_indices_cloud.points.size()); for(size_t kk=0; kk < obj_indices_cloud.points.size(); kk++) indices.indices[kk] = obj_indices_cloud.points[kk].idx; pcl::copyPointCloud(*cloud, indices, *cloud); } else { boost::replace_last( indices_filename, ".pcd", ".txt"); if( v4r::io::existsFile( path_extended+"/"+indices_filename ) ) { std::vector<int> indices; int idx_tmp; std::ifstream mask_f( path_extended+"/"+indices_filename ); while (mask_f >> idx_tmp) indices.push_back(idx_tmp); mask_f.close(); pcl::copyPointCloud(*cloud, indices, *cloud); } else { std::cerr << "Indices file " << path_extended << "/" << indices_filename << " does not exist." << std::endl; } } } // Check if pose file exist std::string pose_fn( cloud_file ); boost::replace_first (pose_fn, cloud_prefix, pose_prefix); boost::replace_last (pose_fn, ".pcd", ".txt"); const std::string full_pose_path = input_dir + pose_fn; if( v4r::io::existsFile( full_pose_path ) ) { Eigen::Matrix4f global_trans = v4r::io::readMatrixFromFile(full_pose_path); if(invert_pose) global_trans = global_trans.inverse(); v4r::setCloudPose(global_trans, *cloud); v4r::io::createDirForFileIfNotExist(out_fn); pcl::io::savePCDFileBinary(out_fn, *cloud); } else std::cerr << "Pose file " << full_pose_path << " does not exist." << std::endl; } } }
42.618056
174
0.575363
ToMadoRe
eb3657cc9e281efeb7c55ddaac0e7294e6f34004
1,704
cpp
C++
src/PostProcessing/PostProcessing.cpp
ArjenSimons/RayTracing
3f2e8084fa61c7d2372b5a87d3f95901e8518524
[ "CC0-1.0" ]
2
2022-02-08T13:48:02.000Z
2022-02-08T13:48:05.000Z
src/PostProcessing/PostProcessing.cpp
ArjenSimons/RayTracing
3f2e8084fa61c7d2372b5a87d3f95901e8518524
[ "CC0-1.0" ]
null
null
null
src/PostProcessing/PostProcessing.cpp
ArjenSimons/RayTracing
3f2e8084fa61c7d2372b5a87d3f95901e8518524
[ "CC0-1.0" ]
1
2021-12-08T15:01:17.000Z
2021-12-08T15:01:17.000Z
#include "precomp.h" //TODO: Compute post processing effects on GPU void PostProcessing::Vignette(Color renderBuffer[SCRWIDTH][SCRHEIGHT], float2 uv[SCRWIDTH][SCRHEIGHT], float outerRadius, float smoothness, float intensity) { outerRadius = clamp(outerRadius, 0.0f, 1.0f); intensity = clamp(intensity, 0.0f, 1.0f); smoothness = max(0.0001f, smoothness); float innerRadius = outerRadius - smoothness; for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float2 p = uv[i][j] - .5f; float len = dot(p, p); float vignette = smoothstep(outerRadius, innerRadius, len) * intensity; renderBuffer[i][j] = renderBuffer[i][j] * vignette; } } void PostProcessing::GammaCorrection(Color renderBuffer[SCRWIDTH][SCRHEIGHT], float gamma) { float invGamma = 1 / gamma; for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float x = pow(renderBuffer[i][j].value.x, invGamma); float y = pow(renderBuffer[i][j].value.y, invGamma); float z = pow(renderBuffer[i][j].value.z, invGamma); renderBuffer[i][j] = float3(x, y, z); } } Color tempBuffer[SCRWIDTH][SCRHEIGHT]; void PostProcessing::ChromaticAberration(Color renderBuffer[SCRWIDTH][SCRHEIGHT], int2 redOffset, int2 greenOffset, int2 blueOffset) { for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float r = renderBuffer[i - redOffset.x][j - redOffset.y].value.x; float g = renderBuffer[i - greenOffset.x][j - greenOffset.y].value.y; float b = renderBuffer[i - blueOffset.x][j - blueOffset.y].value.z; tempBuffer[i][j] = float3(r, g, b); } for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { renderBuffer[i][j] = tempBuffer[i][j]; } }
32.150943
156
0.670775
ArjenSimons
eb370ea2aa213075b3b322b97a07bcc4b68d72a4
1,321
cpp
C++
src/cli/cmd/init.cpp
Jellonator/repaintbrush
742e5e4e004e11df1c0944a4df84c85408d08656
[ "MIT" ]
null
null
null
src/cli/cmd/init.cpp
Jellonator/repaintbrush
742e5e4e004e11df1c0944a4df84c85408d08656
[ "MIT" ]
null
null
null
src/cli/cmd/init.cpp
Jellonator/repaintbrush
742e5e4e004e11df1c0944a4df84c85408d08656
[ "MIT" ]
null
null
null
#include "init.h" #include <iostream> #include "../../core/project.h" namespace cli { const char* command_init_string = R"(Usage: repaintbrush init [-f] <directory> Create a new Repaintbrush project. Options: -f, --force Force the creation of a project)"; void command_init_func(ArgChain& args) { ArgBlock block = args.parse(1, false, { {"force", false, 'f'} }); args.assert_finished(); // block.assert_all_args(); fs::path path_base = "."; if (block.size() >= 1) { path_base = block[0]; } auto path_project = path_base / core::rbrush_folder_name; // Create project folder if (fs::exists(path_project)) { std::cout << "Could not create project; project already exists." << std::endl; return; } fs::create_directories(path_project); // Create version file fs::ofstream file_version(path_project / core::rbrush_version_name); file_version << core::version; file_version.close(); // Create project bool do_force = block.has_option("force"); auto project = core::Project::create(path_base, do_force); std::cout << "Successfully created project." << std::endl; } }
30.72093
76
0.57835
Jellonator
eb3a51106d19fbb4e22e1fbee95fce7ecda57c18
3,455
cc
C++
libgearman-server/plugins/queue/sqlite/queue.cc
jacklicn/gearmand
d867db9d35dc33e0b63a648f1623d6af649430db
[ "BSD-3-Clause" ]
5
2017-01-09T03:44:38.000Z
2021-10-04T07:18:04.000Z
libgearman-server/plugins/queue/sqlite/queue.cc
jacklicn/gearmand
d867db9d35dc33e0b63a648f1623d6af649430db
[ "BSD-3-Clause" ]
null
null
null
libgearman-server/plugins/queue/sqlite/queue.cc
jacklicn/gearmand
d867db9d35dc33e0b63a648f1623d6af649430db
[ "BSD-3-Clause" ]
12
2017-04-26T20:14:01.000Z
2019-06-18T14:45:06.000Z
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/ * Copyright (C) 2009 Cory Bennett * 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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @file * @brief libsqlite3 Queue Storage Definitions */ #include <gear_config.h> #include <libgearman-server/common.h> #include <libgearman-server/plugins/queue/sqlite/queue.h> #include <libgearman-server/plugins/queue/base.h> #include "libgearman-server/plugins/queue/sqlite/instance.hpp" /** Default values. */ #define GEARMAND_QUEUE_SQLITE_DEFAULT_TABLE "gearman_queue" namespace gearmand { namespace plugins { namespace queue { class Sqlite : public gearmand::plugins::Queue { public: Sqlite(); ~Sqlite(); gearmand_error_t initialize(); std::string schema; std::string table; private: bool _store_on_shutdown; }; Sqlite::Sqlite() : Queue("libsqlite3") { command_line_options().add_options() ("libsqlite3-db", boost::program_options::value(&schema), "Database file to use.") ("store-queue-on-shutdown", boost::program_options::bool_switch(&_store_on_shutdown)->default_value(false), "Store queue on shutdown.") ("libsqlite3-table", boost::program_options::value(&table)->default_value(GEARMAND_QUEUE_SQLITE_DEFAULT_TABLE), "Table to use.") ; } Sqlite::~Sqlite() { } gearmand_error_t Sqlite::initialize() { gearmand::queue::Instance* exec_queue= new gearmand::queue::Instance(schema, table); if (exec_queue == NULL) { return GEARMAND_MEMORY_ALLOCATION_FAILURE; } exec_queue->store_on_shutdown(_store_on_shutdown); gearmand_error_t rc; if ((rc= exec_queue->init()) != GEARMAND_SUCCESS) { delete exec_queue; return rc; } gearman_server_set_queue(Gearmand()->server, exec_queue); return rc; } void initialize_sqlite() { static Sqlite local_instance; } } // namespace queue } // namespace plugins } // namespace gearmand
29.033613
139
0.737482
jacklicn
eb3b6de90ed6b440dbd8facf8c75fb118ec889b3
2,623
cpp
C++
PSME/common/agent-framework/src/module/model/endpoint.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/common/agent-framework/src/module/model/endpoint.cpp
opencomputeproject/DM-Redfish-PSME
912f7b6abf5b5c2aae33c75497de4753281c6a51
[ "Apache-2.0" ]
null
null
null
PSME/common/agent-framework/src/module/model/endpoint.cpp
opencomputeproject/DM-Redfish-PSME
912f7b6abf5b5c2aae33c75497de4753281c6a51
[ "Apache-2.0" ]
1
2021-03-24T19:37:58.000Z
2021-03-24T19:37:58.000Z
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @section DESCRIPTION * * */ #include "agent-framework/module/model/endpoint.hpp" #include "agent-framework/module/constants/pnc.hpp" using namespace agent_framework::model; using namespace agent_framework::model::utils; const enums::Component Endpoint::component = enums::Component::Endpoint; const enums::CollectionName Endpoint::collection_name = enums::CollectionName::Endpoints; Endpoint::Endpoint(const std::string& parent_uuid, enums::Component parent_type) : Resource{parent_uuid, parent_type} {} Endpoint::~Endpoint() {} Json::Value Endpoint::to_json() const { Json::Value result; result[literals::Endpoint::PROTOCOL] = get_protocol(); result[literals::Endpoint::IDENTIFIERS] = get_identifiers().to_json(); result[literals::Endpoint::ENTITIES] = get_connected_entities().to_json(); result[literals::Endpoint::COLLECTIONS] = get_collections().to_json(); result[literals::Endpoint::STATUS] = get_status().to_json(); result[literals::Endpoint::OEM] = get_oem().to_json(); return result; } Endpoint Endpoint::from_json(const Json::Value& json) { Endpoint endpoint; endpoint.set_protocol(json[literals::Endpoint::PROTOCOL]); endpoint.set_connected_entities( ConnectedEntities::from_json(json[literals::Endpoint::ENTITIES])); endpoint.set_identifiers( Identifiers::from_json(json[literals::Endpoint::IDENTIFIERS])); endpoint.set_collections( Collections::from_json(json[literals::Endpoint::COLLECTIONS])); endpoint.set_status(attribute::Status::from_json(json[literals::Endpoint::STATUS])); endpoint.set_oem(attribute::Oem::from_json(json[literals::Endpoint::OEM])); return endpoint; } bool Endpoint::has_drive_entity(const std::string& drive_uuid) const { for (const auto& entity : m_connected_entities){ if (drive_uuid == entity.get_entity()) { return true; } } return false; }
34.973333
88
0.722836
opencomputeproject
eb3bc91aae54f8d6ea6c8eb6fbdefb56437e235f
773
cpp
C++
HackerEarth_problems/Best Index/solution.cpp
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
165
2020-10-03T08:01:11.000Z
2022-03-31T02:42:08.000Z
HackerEarth_problems/Best Index/solution.cpp
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
383
2020-10-03T07:39:11.000Z
2021-11-20T07:06:35.000Z
HackerEarth_problems/Best Index/solution.cpp
gbrls/CompetitiveCode
b6f1b817a655635c3c843d40bd05793406fea9c6
[ "MIT" ]
380
2020-10-03T08:05:04.000Z
2022-03-19T06:56:59.000Z
//correct solution #include <iostream> #include <cmath> #include <algorithm> using namespace std; int main() { int n, nt; long s = 0, m; cin >> n; int *a = new int[n];// dynamic array allocation long *b = new long[n]; for (int i = 0; i < n; i++) cin >> a[i]; b[0] = a[0]; for (int i = 1; i < n; i++) b[i] = a[i]+b[i-1];// store cumulative values of a for (int i = 0; i < n; i++) { nt = 2 * (n - i); nt = ((int)sqrt(1 + 4 * nt) - 1) / 2; nt = (nt * (nt + 1)) / 2;//find number of terms by ap series sum formula if(i == 0) { m = b[nt-1]; s = m; } else s = b[nt+i-1]-b[i-1];// find sum of the series with the help of cumulative values m = max(m, s);//store maximum sum in m s = 0;//reinitialize sum } cout << m; return 0; }
21.472222
85
0.52652
gbrls
eb3e3b028285fd8cf10cacbe7b65ee374e3951b2
2,605
cpp
C++
test/module/irohad/main/server_runner_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/irohad/main/server_runner_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/irohad/main/server_runner_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved. * http://soramitsu.co.jp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <boost/format.hpp> #include "endpoint.grpc.pb.h" // any gRPC service is required for test #include "main/server_runner.hpp" boost::format address{"0.0.0.0:%d"}; auto port_visitor = iroha::make_visitor( [](iroha::expected::Value<int> x) { return x.value; }, [](iroha::expected::Error<std::string> x) { return 0; }); /** * @given a running ServerRunner * @when another ServerRunner tries to run on the same port without port reuse * @then Result with error is returned */ TEST(ServerRunnerTest, SamePortNoReuse) { ServerRunner first_runner((address % 0).str()); auto first_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); auto result = first_runner.append(first_query_service).run(); auto port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); ServerRunner second_runner((address % port).str(), false); auto second_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); result = second_runner.append(second_query_service).run(); port = boost::apply_visitor(port_visitor, result); ASSERT_EQ(0, port); } /** * @given a running ServerRunner * @when another ServerRunner tries to run on the same port with port reuse * @then Result with port number is returned */ TEST(ServerRunnerTest, SamePortWithReuse) { ServerRunner first_runner((address % 0).str()); auto first_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); auto result = first_runner.append(first_query_service).run(); auto port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); ServerRunner second_runner((address % port).str(), true); auto second_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); result = second_runner.append(second_query_service).run(); port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); }
37.214286
78
0.727063
coderintherye
eb42761e063736a3933ea66ea966496641e9e621
4,847
cpp
C++
openwrt/package/utils/adbd/src/adb/adb_trace.cpp
yodaos-project/yodaos
d0d7bbc277c0fc1c64e2e0a1c82fe6e63f6eb954
[ "Apache-2.0" ]
1,144
2018-12-18T09:46:47.000Z
2022-03-07T14:51:46.000Z
openwrt/package/utils/adbd/src/adb/adb_trace.cpp
Rokid/YodaOS
d0d7bbc277c0fc1c64e2e0a1c82fe6e63f6eb954
[ "Apache-2.0" ]
16
2019-01-28T06:08:40.000Z
2019-12-04T10:26:41.000Z
openwrt/package/utils/adbd/src/adb/adb_trace.cpp
Rokid/YodaOS
d0d7bbc277c0fc1c64e2e0a1c82fe6e63f6eb954
[ "Apache-2.0" ]
129
2018-12-18T09:46:50.000Z
2022-03-30T07:30:13.000Z
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sysdeps.h" #include "adb_trace.h" #include <string> #include <unordered_map> #include <vector> #include <android-base/logging.h> #include <android-base/strings.h> #include "adb.h" #if !ADB_HOST #include <cutils/properties.h> #endif #if !defined(ADB_HOST) && defined(__ANDROID__) const char* adb_device_banner = "device"; static android::base::LogdLogger gLogdLogger; #else const char* adb_device_banner = "host"; #endif void AdbLogger(android::base::LogId id, android::base::LogSeverity severity, const char* tag, const char* file, unsigned int line, const char* message) { android::base::StderrLogger(id, severity, tag, file, line, message); #if !defined(ADB_HOST) && defined(__ANDROID__) gLogdLogger(id, severity, tag, file, line, message); #endif } #if !defined(ADB_HOST) && defined(__ANDROID__) static std::string get_log_file_name() { struct tm now; time_t t; tzset(); time(&t); localtime_r(&t, &now); char timestamp[PATH_MAX]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d-%H-%M-%S", &now); return android::base::StringPrintf("/data/adb/adb-%s-%d", timestamp, getpid()); } void start_device_log(void) { int fd = unix_open(get_log_file_name().c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0640); if (fd == -1) { return; } // Redirect stdout and stderr to the log file. dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); fprintf(stderr, "--- adb starting (pid %d) ---\n", getpid()); unix_close(fd); } #endif int adb_trace_mask; std::string get_trace_setting_from_env() { const char* setting = getenv("ADB_TRACE"); if (setting == nullptr) { setting = ""; } return std::string(setting); } #if !defined(ADB_HOST) && defined(__ANDROID__) std::string get_trace_setting_from_prop() { char buf[PROPERTY_VALUE_MAX]; property_get("persist.adb.trace_mask", buf, ""); return std::string(buf); } #endif std::string get_trace_setting() { #if !defined(ADB_HOST) && defined(__ANDROID__) return get_trace_setting_from_prop(); #else return get_trace_setting_from_env(); #endif } // Split the space separated list of tags from the trace setting and build the // trace mask from it. note that '1' and 'all' are special cases to enable all // tracing. // // adb's trace setting comes from the ADB_TRACE environment variable, whereas // adbd's comes from the system property persist.adb.trace_mask. static void setup_trace_mask() { const std::string trace_setting = get_trace_setting(); if (trace_setting.empty()) { return; } std::unordered_map<std::string, int> trace_flags = { {"1", 0}, {"all", 0}, {"adb", ADB}, {"sockets", SOCKETS}, {"packets", PACKETS}, {"rwx", RWX}, {"usb", USB}, {"sync", SYNC}, {"sysdeps", SYSDEPS}, {"transport", TRANSPORT}, {"jdwp", JDWP}, {"services", SERVICES}, {"auth", AUTH}, {"fdevent", FDEVENT}, {"shell", SHELL}}; std::vector<std::string> elements = android::base::Split(trace_setting, " "); for (const auto& elem : elements) { const auto& flag = trace_flags.find(elem); if (flag == trace_flags.end()) { LOG(ERROR) << "Unknown trace flag: " << elem; continue; } if (flag->second == 0) { // 0 is used for the special values "1" and "all" that enable all // tracing. adb_trace_mask = ~0; return; } else { adb_trace_mask |= 1 << flag->second; } } } void adb_trace_init(char** argv) { #if !defined(ADB_HOST) && defined(__ANDROID__) // Don't open log file if no tracing, since this will block // the crypto unmount of /data if (!get_trace_setting().empty()) { if (unix_isatty(STDOUT_FILENO) == 0) { start_device_log(); } } #endif android::base::InitLogging(argv, &AdbLogger); setup_trace_mask(); VLOG(ADB) << adb_version(); } void adb_trace_enable(AdbTrace trace_tag) { adb_trace_mask |= (1 << trace_tag); }
27.697143
81
0.626779
yodaos-project
eb445c2d12a3a6ef046a8123286c6f628b50caa7
2,402
cpp
C++
src/atlas/hlr/load_library.cpp
marovira/atlas
ccc9ec2449a9392e41a25a6c638302b940f5e5da
[ "MIT" ]
10
2016-11-30T08:44:55.000Z
2022-02-05T16:47:05.000Z
src/atlas/hlr/load_library.cpp
marovira/atlas
ccc9ec2449a9392e41a25a6c638302b940f5e5da
[ "MIT" ]
12
2016-01-13T20:31:11.000Z
2020-03-27T19:14:03.000Z
src/atlas/hlr/load_library.cpp
marovira/atlas
ccc9ec2449a9392e41a25a6c638302b940f5e5da
[ "MIT" ]
10
2016-01-07T16:22:36.000Z
2020-01-16T05:58:48.000Z
#include "load_library.hpp" #include <fmt/printf.h> #include <zeus/platform.hpp> #if defined(ZEUS_PLATFORM_WINDOWS) # define WIN32_LEAN_AND_MEAN # include <windows.h> #else # include <dlfcn.h> #endif namespace atlas::hlr { #if defined(ZEUS_PLATFORM_WINDOWS) void* load_library_handle(std::string const& library_name) { void* handle = LoadLibrary(library_name.c_str()); if (handle == nullptr) { auto error_code = GetLastError(); fmt::print(stderr, "error: LoadLibrary returned error code {}\n", error_code); } return handle; } void* load_raw_function_ptr(void* handle, std::string const& function_name) { if (handle == nullptr) { fmt::print(stderr, "error: null library handle\n"); return nullptr; } auto hmodule = reinterpret_cast<HMODULE>(handle); FARPROC prog_address = GetProcAddress(hmodule, function_name.c_str()); if (prog_address == nullptr) { auto error_code = GetLastError(); fmt::print(stderr, "error: GetProcAddress returned error code {}\n", error_code); } return prog_address; } void unload_library_handle(void* handle) { auto h = reinterpret_cast<HMODULE>(handle); FreeLibrary(h); } #else void* load_library_handle(std::string const& library_name) { void* handle = dlopen(library_name.c_str(), RTLD_LAZY); if (handle == nullptr) { auto error_message = dlerror(); fmt::print(stderr, "error: in dlopen: {}\n", error_message); } return handle; } void* load_raw_function_ptr(void* handle, std::string const& function_name) { if (handle == nullptr) { fmt::print(stderr, "error: null library handle\n"); return nullptr; } void* prog_address = dlsym(handle, function_name.c_str()); if (prog_address == nullptr) { auto error_message = dlerror(); fmt::print(stderr, "error: in dlsym: {}\n", error_message); } return prog_address; } void unload_library_handle(void* handle) { dlclose(handle); } #endif } // namespace atlas::hlr
25.827957
79
0.567027
marovira
eb491ccaace163d6b0096159a6c3b39ddb9a7d32
1,936
hxx
C++
ARCHIVE/BRAINSSurfaceTools/BRAINSSurfaceCommon/itkMeshFunction.hxx
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
null
null
null
ARCHIVE/BRAINSSurfaceTools/BRAINSSurfaceCommon/itkMeshFunction.hxx
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
null
null
null
ARCHIVE/BRAINSSurfaceTools/BRAINSSurfaceCommon/itkMeshFunction.hxx
pnlbwh/BRAINSTools
a2fe63ab5b795f03da140a4081d1fef6314dab95
[ "Apache-2.0" ]
1
2022-02-08T05:39:46.000Z
2022-02-08T05:39:46.000Z
/*========================================================================= * * Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering * The University of Iowa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMeshFunction_hxx #define __itkMeshFunction_hxx #include "itkMeshFunction.h" namespace itk { /** * Constructor */ template <typename TInputMesh, typename TOutput> MeshFunction<TInputMesh, TOutput>::MeshFunction() { m_Mesh = nullptr; } /** * Standard "PrintSelf" method */ template <typename TInputMesh, typename TOutput> void MeshFunction<TInputMesh, TOutput>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "InputMesh: " << m_Mesh.GetPointer() << std::endl; } /** * Initialize by setting the input mesh */ template <typename TInputMesh, typename TOutput> void MeshFunction<TInputMesh, TOutput>::SetInputMesh(const InputMeshType * ptr) { this->m_Mesh = ptr; if (ptr) { // FIXME Add here the point locator... } } /** * Return the input mesh */ template <typename TInputMesh, typename TOutput> const typename MeshFunction<TInputMesh, TOutput>::InputMeshType * MeshFunction<TInputMesh, TOutput>::GetInputMesh() const { return m_Mesh; } } // end namespace itk #endif
26.162162
97
0.667355
pnlbwh
eb4f27761aa97882b7e6444807a5bcd961b16082
2,710
cpp
C++
doc/snippets/MagnumMathAlgorithms.cpp
sjvs/mosra-magnum-copy
1f3d6fccbdfc8c30ed8cbd1453d51c0484efeb85
[ "MIT" ]
1
2019-11-24T11:34:13.000Z
2019-11-24T11:34:13.000Z
doc/snippets/MagnumMathAlgorithms.cpp
sjvs/mosra-magnum-copy
1f3d6fccbdfc8c30ed8cbd1453d51c0484efeb85
[ "MIT" ]
null
null
null
doc/snippets/MagnumMathAlgorithms.cpp
sjvs/mosra-magnum-copy
1f3d6fccbdfc8c30ed8cbd1453d51c0484efeb85
[ "MIT" ]
2
2019-11-24T11:34:17.000Z
2020-10-13T06:15:59.000Z
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <numeric> #include <vector> #include <Corrade/Containers/ArrayView.h> #include "Magnum/Magnum.h" #include "Magnum/Math/Algorithms/KahanSum.h" #include "Magnum/Math/Algorithms/Svd.h" #include "Magnum/Math/Packing.h" using namespace Magnum; using namespace Magnum::Math::Literals; int main() { { /* [kahanSum] */ std::vector<Float> data(100000000, 1.0f); Float a = std::accumulate(data.begin(), data.end(), 0.0f); // 1.667e7f Float b = Math::Algorithms::kahanSum(data.begin(), data.end()); // 1.000e8f /* [kahanSum] */ static_cast<void>(a); static_cast<void>(b); } { /* [kahanSum-iterative] */ Containers::ArrayView<UnsignedByte> pixels; Float sum = 0.0f, c = 0.0f; for(UnsignedByte pixel: pixels) { Float value = Math::unpack<Float>(pixel); sum = Math::Algorithms::kahanSum(&value, &value + 1, sum, &c); } /* [kahanSum-iterative] */ } { enum: std::size_t { cols = 3, rows = 4 }; /* [svd] */ Math::RectangularMatrix<cols, rows, Double> m; Math::RectangularMatrix<cols, rows, Double> uPart; Math::Vector<cols, Double> wDiagonal; Math::Matrix<cols, Double> v; std::tie(uPart, wDiagonal, v) = Math::Algorithms::svd(m); // Extend U Math::Matrix<rows, Double> u{Math::ZeroInit}; for(std::size_t i = 0; i != rows; ++i) u[i] = uPart[i]; // Diagonal W Math::RectangularMatrix<cols, rows, Double> w = Math::RectangularMatrix<cols, rows, Double>::fromDiagonal(wDiagonal); // u*w*v.transposed() == m /* [svd] */ static_cast<void>(w); } }
31.511628
78
0.702214
sjvs
eb50c5441889033f7de46f03dff5463bce5ed22b
1,783
cpp
C++
input.cpp
darkoppressor/opengl-pong
20bd2bcd7e8097c06bd734bdff52cbcb9b02e99b
[ "CC-BY-4.0" ]
null
null
null
input.cpp
darkoppressor/opengl-pong
20bd2bcd7e8097c06bd734bdff52cbcb9b02e99b
[ "CC-BY-4.0" ]
null
null
null
input.cpp
darkoppressor/opengl-pong
20bd2bcd7e8097c06bd734bdff52cbcb9b02e99b
[ "CC-BY-4.0" ]
null
null
null
/* Copyright (c) 2011 Kevin Wells */ /* OpenGL Pong may be freely redistributed. See license for details. */ #include "input.h" #include "variables.h" #include "quit.h" #include "sdl.h" #include "screen_draw.h" using namespace std; void input_game(){ while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_QUIT: quit_game(); break; } } Uint8 *keystates=SDL_GetKeyState(NULL);/**Get keystates.*/ /**Handle input.*/ if(keystates[SDLK_PAUSE]){ keystates[SDLK_PAUSE]=NULL; //pause(); } if(keystates[SDLK_f]){ keystates[SDLK_f]=NULL; option_frame_rate=!option_frame_rate; } if(keystates[SDLK_m]){ keystates[SDLK_m]=NULL; option_gamemode++; if(option_gamemode>2){ option_gamemode=0; } } if(keystates[SDLK_KP_PLUS]){ keystates[SDLK_KP_PLUS]=NULL; for(int i=0;i<1;i++){ balls.push_back(Ball()); } //if(balls.size()<1000000){ // balls.push_back(Ball()); //} } if(keystates[SDLK_KP_MINUS]){ keystates[SDLK_KP_MINUS]=NULL; if(balls.size()>1){ balls.pop_back(); } } if(option_gamemode==0){/**If we are in demo mode.*/ for(int i=0;i<paddles.size();i++){ paddles.at(i).human=false; } } if(option_gamemode==1){/**If we are in singleplayer mode.*/ paddles.at(0).human=true; paddles.at(1).human=false; } if(option_gamemode==2){/**If we are in humans only mode.*/ for(int i=0;i<paddles.size();i++){ paddles.at(i).human=true; } } for(int i=0;i<paddles.size();i++){ paddles.at(i).handle_input(); } }
25.471429
72
0.546831
darkoppressor
eb53ef71a732559eb4276b24987d810708931040
30
cpp
C++
Refureku/Library/Tests/AB.cpp
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
143
2020-04-07T21:38:21.000Z
2022-03-30T01:06:33.000Z
Refureku/Library/Tests/AB.cpp
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
7
2021-03-30T07:26:21.000Z
2022-03-28T16:31:02.000Z
Refureku/Library/Tests/AB.cpp
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
11
2020-06-06T09:45:12.000Z
2022-01-25T17:17:55.000Z
#include "Generated/AB.rfks.h"
30
30
0.766667
jsoysouvanh
eb55db2d10860204a0d7d4edebae5c61db156dd7
3,252
hpp
C++
distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/proposals_manager.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/proposals_manager.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/proposals_manager.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////// // distribution::survival::models::common::importance_sampling::proposals_manager.hpp // // // // Copyright 2009 Erwann Rogard. Distributed under the Boost // // Software License, Version 1.0. (See accompanying file // // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ///////////////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_PROPOSALS_MANAGER_HPP_ER_2009 #define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_PROPOSALS_MANAGER_HPP_ER_2009 #include <boost/typeof/typeof.hpp> #include <boost/fusion/include/make_map.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/statistics/detail/traits/remove_cvref.hpp> #include <boost/statistics/detail/distribution_common/meta/value.hpp> #include <boost/statistics/detail/distribution_common/meta/random/distribution.hpp> #include <boost/statistics/detail/distribution_common/meta/random/generator.hpp> namespace boost { namespace statistics{ namespace detail{ namespace distribution{ namespace survival { namespace importance_sampling{ template<typename D> class proposals_manager{ typedef typename distribution::meta::value<D>::type val_; typedef distribution::meta::random_distribution<D> meta_random_; typedef typename meta_random_::type random_; typedef typename random_::result_type par_value1_; typedef typename statistics::detail::traits::remove_cvref< par_value1_ >::type par_value_; public: proposals_manager(const D& dist):dist_(dist){} proposals_manager(const proposals_manager& that):dist_(that.dist_){} // Tags struct tag{ struct parameter{}; struct log_pdf{}; }; typedef typename tag::parameter tag_par_; typedef typename tag::log_pdf tag_lpdf_; typedef typename boost::fusion::map< boost::fusion::pair<tag_par_,par_value_>, boost::fusion::pair<tag_lpdf_,val_> > proposal_; typedef std::vector<proposal_> proposals_type; // Generate posterior sample const D& distribution()const{ return this->dist_; } template<typename U,typename N> void refresh(U& urng,N n){ BOOST_AUTO( gen, distribution::make_random_generator(urng,this->dist_) ); this->proposals_.clear(); this->proposals_.reserve(n); for(unsigned i = 0; i<n; i++) { par_value_ p = gen(); val_ lpdf = log_unnormalized_pdf(this->dist_,p); this->proposals_.push_back( boost::fusion::make_map<tag_par_,tag_lpdf_>(p,lpdf) ); } } const proposals_type& operator()()const{ return this->proposals_; } private: proposals_type proposals_; D dist_; }; }// importance_sampling }// survival }// distribution }// detail }// statistics }// boost #endif
35.347826
110
0.621464
rogard
eb55e082fd5281ba7b6dd6b8807f138828dd1685
8,236
cpp
C++
main.cpp
MinghuaShen/HLS
f53220ef475f15c2d11902d6f392b9cb783fd5b0
[ "MIT" ]
4
2020-03-14T05:11:57.000Z
2021-03-23T15:02:37.000Z
main.cpp
MinghuaShen/HLS
f53220ef475f15c2d11902d6f392b9cb783fd5b0
[ "MIT" ]
null
null
null
main.cpp
MinghuaShen/HLS
f53220ef475f15c2d11902d6f392b9cb783fd5b0
[ "MIT" ]
2
2018-07-26T15:52:39.000Z
2021-02-21T10:42:47.000Z
// Copyright (c) 2018 Hongzheng Chen // E-mail: chenhzh37@mail2.sysu.edu.cn // This is the implementation of Entropy-directed scheduling (EDS) algorithm for FPGA high-level synthesis. // This file is the main function of EDS. #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <chrono> // timing using Clock = std::chrono::high_resolution_clock; #include "graph.h" #include "graph.hpp" using namespace std; // Benchmarks for our experiments can be downloaded at // https://www.ece.ucsb.edu/EXPRESS/benchmark/ const vector<string> dot_file = { "", "hal", "horner_bezier_surf_dfg__12"/*c*/, "arf", "motion_vectors_dfg__7"/*c*/, "ewf", "fir2", "fir1", "h2v2_smooth_downsample_dfg__6", "feedback_points_dfg__7"/*c*/, "collapse_pyr_dfg__113"/*c*/, "cosine1", "cosine2", "write_bmp_header_dfg__7"/*c*/, "interpolate_aux_dfg__12"/*c*/, "matmul_dfg__3"/*c*/, "idctcol_dfg__3"/*c*/, "jpeg_idct_ifast_dfg__5"/*c*/, "jpeg_fdct_islow_dfg__6"/*c*/, "smooth_color_z_triangle_dfg__31"/*c*/, "invert_matrix_general_dfg__3"/*c*/, "dag_500", "dag_1000", "dag_1500" }; // if you need to load from other path, please modify here string path = "./Benchmarks/"; // default constraints for resource-constrained scheduling // these fine-tuned constraints are first presented in the paper below // ----------------------------------------------------------------- // @Article{ // Author = {G. Wang and W. Gong and B. DeRenzi and R. Kastner}, // title = {Ant Colony Optimizations for Resource- and Timing-Constrained Operation Scheduling}, // journal = {IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems (TCAD)}, // year = {2007} // } // ----------------------------------------------------------------- // const vector<map<string,int>> RC = { // {{"MUL",0 }, {"ALU",0 }},/*null*/ // {{"MUL",2 }, {"ALU",1 }},/*1*/ // {{"MUL",2 }, {"ALU",1 }},/*2*/ // {{"MUL",3 }, {"ALU",1 }},/*3*/ // {{"MUL",3 }, {"ALU",4 }},/*4*/ // {{"MUL",1 }, {"ALU",2 }},/*5*/ // {{"MUL",2 }, {"ALU",3 }},/*6*/ // {{"MUL",2 }, {"ALU",3 }},/*7*/ // {{"MUL",1 }, {"ALU",3 }},/*8*/ // {{"MUL",3 }, {"ALU",3 }},/*9*/ // {{"MUL",3 }, {"ALU",5 }},/*10*/ // {{"MUL",4 }, {"ALU",5 }},/*11*/ // {{"MUL",5 }, {"ALU",8 }},/*12*/ // {{"MUL",1 }, {"ALU",9 }},/*13*/ // {{"MUL",9 }, {"ALU",8 }},/*14*/ // {{"MUL",9 }, {"ALU",8 }},/*15*/ // {{"MUL",5 }, {"ALU",6 }},/*16*/ // {{"MUL",10}, {"ALU",9 }},/*17*/ // {{"MUL",5 }, {"ALU",7 }},/*18*/ // {{"MUL",8 }, {"ALU",9 }},/*19*/ // {{"MUL",15}, {"ALU",11}},/*20*/ // {{"MUL",5 }, {"ALU",9 }},/*21*/ // {{"MUL",6 }, {"ALU",12}},/*22*/ // {{"MUL",7 }, {"ALU",13}},/*23*/ // }; // Complex FU library const vector<map<string,int>> RC = { {{"MUL",0 }, {"ALU",0 }},/*null*/ {{"MUL",2 }, {"add",1 },{"sub",1},{"les",1}},/*1*/ {{"MUL",1 }, {"ADD",1 },{"LOD",1},{"STR",1}},/*2*/ {{"MUL",3 }, {"ADD",1 }},/*3*/ {{"MUL",3 }, {"LOD",1 },{"ADD",2},{"STR",1}},/*4*/ {{"MUL",1 }, {"ADD",2 }},/*5*/ {{"MUL",2 }, {"add",1 },{"exp",1},{"imp",2}},/*6*/ {{"MUL",2 }, {"ADD",2 },{"MemR",2},{"MemW",1}},/*7*/ {{"MUL",1 }, {"ADD",2 },{"ASR",1},{"STR",1},{"LOD",1}},/*8*/ {{"MUL",3 }, {"STR",2 },{"LOD",1},{"BGE",1},{"ADD",2}},/*9*/ {{"MUL",3 }, {"ADD",3 },{"SUB",1},{"STR",3},{"LSL",1},{"LOD",3},{"ASR",1}},/*10*/ {{"MUL",4 }, {"imp",6 },{"sub",1},{"exp",2},{"add",2}},/*11*/ {{"MUL",4 }, {"add",1 },{"exp",2},{"imp",2},{"sub",2}},/*12*/ {{"MUL",1 }, {"STR",3 },{"LSR",1},{"LOD",4},{"BNE",1},{"ASR",2},{"AND",2},{"ADD",4}},/*13*/ {{"MUL",9 }, {"ADD",4 },{"SUB",2},{"STR",2},{"LOD",5}},/*14*/ {{"MUL",8 }, {"STR",2 },{"LOD",3},{"ADD",3}},/*15*/ {{"MUL",4 }, {"SUB",2 },{"STR",2},{"LSL",1},{"LOD",2},{"ASR",2},{"ADD",2}},/*16*/ {{"MUL",4 }, {"SUB",1 },{"STR",2},{"LOD",4},{"ASR",1},{"ADD",4}},/*17*/ {{"MUL",4 }, {"SUB",2 },{"STR",2},{"LOD",4},{"ASR",1},{"ADD",4}},/*18*/ {{"MUL",8 }, {"SUB",3 },{"ADD",6},{"LOD",6}},/*19*/ {{"MUL",14}, {"SUB",3 },{"STR",3},{"NEG",2},{"LOD",8},{"ADD",8}},/*20*/ {{"MUL",5 }, {"add",9 }},/*21*/ {{"MUL",6 }, {"add",12}},/*22*/ {{"MUL",7 }, {"add",13}},/*23*/ }; void interactive() { while (1) { cout << "\nPlease enter the file num." << endl; for (int file_num = 1; file_num < dot_file.size(); ++file_num) cout << file_num << ": " << dot_file[file_num] << endl; int file_num; cin >> file_num; cout << "Begin reading dot file..." << endl; ifstream infile(path + dot_file[file_num] + ".dot"); if (infile) cout << "Read in dot file successfully!\n" << endl; else { cout << "Error: No such files!" << endl; return; } graph gp; vector<int> MODE; cout << "\nPlease enter the scheduling mode:" << endl; cout << "Time-constrained(TC):\t0 EDS\t1 IEDS\t2 ILP\t3 FDS\t4 LS" << endl; cout << "Resource-constrained(RC):\t10 EDS\t11 IEDS\t12 ILP\t13 FDS\t 14 LS" << endl; int mode; cin >> mode; MODE.push_back(mode); if (MODE[0] < 10) { double lc; cout << "Please enter the latency factor." << endl; cin >> lc; gp.setLC(lc); } else gp.setMAXRESOURCE(RC.at(file_num)); cout << "\nPlease enter the scheduling order:" << endl; cout << "0. Top-down\t 1.Bottom-up" << endl; cin >> mode; MODE.push_back(mode); gp.setMODE(MODE); gp.readFile(infile); if (MODE[0] == 2) { try{ system("md TC_ILP"); } catch(...){} char str[10]; snprintf(str,sizeof(str),"%.1f",gp.getLC()); ofstream outfile("./TC_ILP/"+dot_file[file_num]+"_"+string(str)+".lp"); gp.generateTC_ILP(outfile); outfile.close(); } else if (MODE[0] == 12) { try{ system("md RC_ILP"); } catch(...){} ofstream outfile("./RC_ILP/"+dot_file[file_num]+".lp"); gp.generateRC_ILP(outfile); outfile.close(); } else gp.mainScheduling(); infile.close(); } } // set these argv from cmd // argv[0] default file path: needn't give // argv[1] scheduling mode: // time-constrained(TC): 0 EDS 1 IEDS 2 ILP 3 FDS 4 LS // resource-constrained(RC): 10 EDS 11 IEDS 12 ILP 13 FDS 14 LS // ****** If the arguments below are not needed, you needn't type anything more. ****** // argv[2] latency factor (LC) or scheduling order // 0 top-down 1 bottom-up void commandline(char *argv[]) { vector<int> MODE; MODE.push_back(stoi(string(argv[1]))); // scheduling mode switch (MODE[0]) { case 0: case 1: case 3: case 4: MODE.push_back(stoi(string(argv[3])));break; case 10: case 11: case 13: case 14: MODE.push_back(stoi(string(argv[2])));break; case 2: MODE.push_back(stoi(string(argv[2])));break; case 12: MODE.push_back(stoi(string(argv[1])));break; default: cout << "Error: Mode wrong!" << endl;break; } for (int file_num = 1; file_num < dot_file.size(); ++file_num) { ifstream infile(path + dot_file[file_num] + ".dot"); if (!infile) { cout << "Error: No such files!" << endl; return; } graph gp; gp.setMODE(MODE); gp.setPRINT(0); gp.readFile(infile); if (MODE[0] >= 10) gp.setMAXRESOURCE(RC.at(file_num)); else gp.setLC(stod(string(argv[2]))); if (MODE[0] == 2) { try{ system("md TC_ILP"); } catch(...){} char str[10]; snprintf(str,sizeof(str),"%.1f",gp.getLC()); ofstream outfile("./TC_ILP/"+dot_file[file_num]+"_"+string(str)+".lp"); gp.generateTC_ILP(outfile); outfile.close(); } else if (MODE[0] == 12) { try{ system("md RC_ILP"); } catch(...){} ofstream outfile("./RC_ILP/"+dot_file[file_num]+".lp"); gp.generateRC_ILP(outfile); outfile.close(); } else { cout << "File # " << file_num << " (" << dot_file[file_num] << ") :" <<endl; gp.mainScheduling(1); } infile.close(); } } int main(int argc,char *argv[]) { if (argc == 1) // interactive interactive(); else // read from cmd commandline(argv); return 0; } // Some abbreviations appear in ExPRESS // 1.MUL // mul: multipy // div: divide // 2.ALU // imp: import // exp: export // MemR: memory read // MemW: memory write // str: store register // les: less // lod: load data into memory? // bge: ? // neg: negetive // add: add // sub: subtract // and: logical and // lsr: logical shift right // asr: arithmetic shift right // bne: Branch if Not Equal
28.013605
107
0.535697
MinghuaShen
eb55e8996c74598ea4e0bc198ce452ad1f246fe9
68,386
cpp
C++
DicomWebStorge/Orthanc-1.7.4/OrthancFramework/Sources/DicomParsing/DicomModification.cpp
a2609194449/Assistant-decision-making-system-for-gallbladder-cancer-
75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84
[ "MIT" ]
null
null
null
DicomWebStorge/Orthanc-1.7.4/OrthancFramework/Sources/DicomParsing/DicomModification.cpp
a2609194449/Assistant-decision-making-system-for-gallbladder-cancer-
75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84
[ "MIT" ]
null
null
null
DicomWebStorge/Orthanc-1.7.4/OrthancFramework/Sources/DicomParsing/DicomModification.cpp
a2609194449/Assistant-decision-making-system-for-gallbladder-cancer-
75a9d3432cb510ea94fa09cc9b440e8b8e7f0a84
[ "MIT" ]
null
null
null
/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017-2020 Osimis S.A., Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/>. **/ #include "../PrecompiledHeaders.h" #include "DicomModification.h" #include "../Compatibility.h" #include "../Logging.h" #include "../OrthancException.h" #include "../SerializationToolbox.h" #include "FromDcmtkBridge.h" #include "ITagVisitor.h" #include <memory> // For std::unique_ptr static const std::string ORTHANC_DEIDENTIFICATION_METHOD_2008 = "Orthanc " ORTHANC_VERSION " - PS 3.15-2008 Table E.1-1"; static const std::string ORTHANC_DEIDENTIFICATION_METHOD_2017c = "Orthanc " ORTHANC_VERSION " - PS 3.15-2017c Table E.1-1 Basic Profile"; namespace Orthanc { class DicomModification::RelationshipsVisitor : public ITagVisitor { private: DicomModification& that_; bool IsEnabled(const DicomTag& tag) const { return (!that_.IsCleared(tag) && !that_.IsRemoved(tag) && !that_.IsReplaced(tag)); } void RemoveIfEnabled(ParsedDicomFile& dicom, const DicomTag& tag) const { if (IsEnabled(tag)) { dicom.Remove(tag); } } public: explicit RelationshipsVisitor(DicomModification& that) : that_(that) { } virtual void VisitNotSupported(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr) { } virtual void VisitEmptySequence(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag) { } virtual void VisitBinary(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const void* data, size_t size) { } virtual void VisitIntegers(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const std::vector<int64_t>& values) { } virtual void VisitDoubles(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const std::vector<double>& value) { } virtual void VisitAttributes(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, const std::vector<DicomTag>& value) { } virtual Action VisitString(std::string& newValue, const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const std::string& value) { if (!IsEnabled(tag)) { return Action_None; } else if (parentTags.size() == 2 && parentTags[0] == DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_SEQUENCE && parentTags[1] == DICOM_TAG_RT_REFERENCED_STUDY_SEQUENCE && tag == DICOM_TAG_REFERENCED_SOP_INSTANCE_UID) { // in RT-STRUCT, this ReferencedSOPInstanceUID is actually referencing a StudyInstanceUID !! // (observed in many data sets including: https://wiki.cancerimagingarchive.net/display/Public/Lung+CT+Segmentation+Challenge+2017) // tested in test_anonymize_relationships_5 newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Study); return Action_Replace; } else if (tag == DICOM_TAG_FRAME_OF_REFERENCE_UID || tag == DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_UID || tag == DICOM_TAG_REFERENCED_SOP_INSTANCE_UID || tag == DICOM_TAG_RELATED_FRAME_OF_REFERENCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Instance); return Action_Replace; } else if (parentTags.size() == 1 && parentTags[0] == DICOM_TAG_CURRENT_REQUESTED_PROCEDURE_EVIDENCE_SEQUENCE && tag == DICOM_TAG_STUDY_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Study); return Action_Replace; } else if (parentTags.size() == 2 && parentTags[0] == DICOM_TAG_CURRENT_REQUESTED_PROCEDURE_EVIDENCE_SEQUENCE && parentTags[1] == DICOM_TAG_REFERENCED_SERIES_SEQUENCE && tag == DICOM_TAG_SERIES_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Series); return Action_Replace; } else if (parentTags.size() == 3 && parentTags[0] == DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_SEQUENCE && parentTags[1] == DICOM_TAG_RT_REFERENCED_STUDY_SEQUENCE && parentTags[2] == DICOM_TAG_RT_REFERENCED_SERIES_SEQUENCE && tag == DICOM_TAG_SERIES_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Series); return Action_Replace; } else if (parentTags.size() == 1 && parentTags[0] == DICOM_TAG_REFERENCED_SERIES_SEQUENCE && tag == DICOM_TAG_SERIES_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Series); return Action_Replace; } else { return Action_None; } } void RemoveRelationships(ParsedDicomFile& dicom) const { // Sequences containing the UID relationships RemoveIfEnabled(dicom, DICOM_TAG_REFERENCED_IMAGE_SEQUENCE); RemoveIfEnabled(dicom, DICOM_TAG_SOURCE_IMAGE_SEQUENCE); // Individual tags RemoveIfEnabled(dicom, DICOM_TAG_FRAME_OF_REFERENCE_UID); // The tags below should never occur at the first level of the // hierarchy, but remove them anyway RemoveIfEnabled(dicom, DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_UID); RemoveIfEnabled(dicom, DICOM_TAG_REFERENCED_SOP_INSTANCE_UID); RemoveIfEnabled(dicom, DICOM_TAG_RELATED_FRAME_OF_REFERENCE_UID); } }; bool DicomModification::CancelReplacement(const DicomTag& tag) { Replacements::iterator it = replacements_.find(tag); if (it != replacements_.end()) { delete it->second; replacements_.erase(it); return true; } else { return false; } } void DicomModification::ReplaceInternal(const DicomTag& tag, const Json::Value& value) { Replacements::iterator it = replacements_.find(tag); if (it != replacements_.end()) { delete it->second; it->second = NULL; // In the case of an exception during the clone it->second = new Json::Value(value); // Clone } else { replacements_[tag] = new Json::Value(value); // Clone } } void DicomModification::ClearReplacements() { for (Replacements::iterator it = replacements_.begin(); it != replacements_.end(); ++it) { delete it->second; } replacements_.clear(); } void DicomModification::MarkNotOrthancAnonymization() { Replacements::iterator it = replacements_.find(DICOM_TAG_DEIDENTIFICATION_METHOD); if (it != replacements_.end() && (it->second->asString() == ORTHANC_DEIDENTIFICATION_METHOD_2008 || it->second->asString() == ORTHANC_DEIDENTIFICATION_METHOD_2017c)) { delete it->second; replacements_.erase(it); } } void DicomModification::RegisterMappedDicomIdentifier(const std::string& original, const std::string& mapped, ResourceType level) { UidMap::const_iterator previous = uidMap_.find(std::make_pair(level, original)); if (previous == uidMap_.end()) { uidMap_.insert(std::make_pair(std::make_pair(level, original), mapped)); } } std::string DicomModification::MapDicomIdentifier(const std::string& original, ResourceType level) { std::string mapped; UidMap::const_iterator previous = uidMap_.find(std::make_pair(level, original)); if (previous == uidMap_.end()) { if (identifierGenerator_ == NULL) { mapped = FromDcmtkBridge::GenerateUniqueIdentifier(level); } else { if (!identifierGenerator_->Apply(mapped, original, level, currentSource_)) { throw OrthancException(ErrorCode_InternalError, "Unable to generate an anonymized ID"); } } uidMap_.insert(std::make_pair(std::make_pair(level, original), mapped)); } else { mapped = previous->second; } return mapped; } void DicomModification::MapDicomTags(ParsedDicomFile& dicom, ResourceType level) { std::unique_ptr<DicomTag> tag; switch (level) { case ResourceType_Study: tag.reset(new DicomTag(DICOM_TAG_STUDY_INSTANCE_UID)); break; case ResourceType_Series: tag.reset(new DicomTag(DICOM_TAG_SERIES_INSTANCE_UID)); break; case ResourceType_Instance: tag.reset(new DicomTag(DICOM_TAG_SOP_INSTANCE_UID)); break; default: throw OrthancException(ErrorCode_InternalError); } std::string original; if (!dicom.GetTagValue(original, *tag)) { original = ""; } std::string mapped = MapDicomIdentifier(Toolbox::StripSpaces(original), level); dicom.Replace(*tag, mapped, false /* don't try and decode data URI scheme for UIDs */, DicomReplaceMode_InsertIfAbsent, privateCreator_); } DicomModification::DicomModification() : removePrivateTags_(false), level_(ResourceType_Instance), allowManualIdentifiers_(true), keepStudyInstanceUid_(false), keepSeriesInstanceUid_(false), keepSopInstanceUid_(false), updateReferencedRelationships_(true), isAnonymization_(false), //privateCreator_("PrivateCreator"), identifierGenerator_(NULL) { } DicomModification::~DicomModification() { ClearReplacements(); } void DicomModification::Keep(const DicomTag& tag) { bool wasRemoved = IsRemoved(tag); bool wasCleared = IsCleared(tag); removals_.erase(tag); clearings_.erase(tag); bool wasReplaced = CancelReplacement(tag); if (tag == DICOM_TAG_STUDY_INSTANCE_UID) { keepStudyInstanceUid_ = true; } else if (tag == DICOM_TAG_SERIES_INSTANCE_UID) { keepSeriesInstanceUid_ = true; } else if (tag == DICOM_TAG_SOP_INSTANCE_UID) { keepSopInstanceUid_ = true; } else if (tag.IsPrivate()) { privateTagsToKeep_.insert(tag); } else if (!wasRemoved && !wasReplaced && !wasCleared) { LOG(WARNING) << "Marking this tag as to be kept has no effect: " << tag.Format(); } MarkNotOrthancAnonymization(); } void DicomModification::Remove(const DicomTag& tag) { removals_.insert(tag); clearings_.erase(tag); CancelReplacement(tag); privateTagsToKeep_.erase(tag); MarkNotOrthancAnonymization(); } void DicomModification::Clear(const DicomTag& tag) { removals_.erase(tag); clearings_.insert(tag); CancelReplacement(tag); privateTagsToKeep_.erase(tag); MarkNotOrthancAnonymization(); } bool DicomModification::IsRemoved(const DicomTag& tag) const { return removals_.find(tag) != removals_.end(); } bool DicomModification::IsCleared(const DicomTag& tag) const { return clearings_.find(tag) != clearings_.end(); } void DicomModification::Replace(const DicomTag& tag, const Json::Value& value, bool safeForAnonymization) { clearings_.erase(tag); removals_.erase(tag); privateTagsToKeep_.erase(tag); ReplaceInternal(tag, value); if (!safeForAnonymization) { MarkNotOrthancAnonymization(); } } bool DicomModification::IsReplaced(const DicomTag& tag) const { return replacements_.find(tag) != replacements_.end(); } const Json::Value& DicomModification::GetReplacement(const DicomTag& tag) const { Replacements::const_iterator it = replacements_.find(tag); if (it == replacements_.end()) { throw OrthancException(ErrorCode_InexistentItem); } else { return *it->second; } } std::string DicomModification::GetReplacementAsString(const DicomTag& tag) const { const Json::Value& json = GetReplacement(tag); if (json.type() != Json::stringValue) { throw OrthancException(ErrorCode_BadParameterType); } else { return json.asString(); } } void DicomModification::SetRemovePrivateTags(bool removed) { removePrivateTags_ = removed; if (!removed) { MarkNotOrthancAnonymization(); } } void DicomModification::SetLevel(ResourceType level) { uidMap_.clear(); level_ = level; if (level != ResourceType_Patient) { MarkNotOrthancAnonymization(); } } void DicomModification::SetupAnonymization2008() { // This is Table E.1-1 from PS 3.15-2008 - DICOM Part 15: Security and System Management Profiles // https://raw.githubusercontent.com/jodogne/dicom-specification/master/2008/08_15pu.pdf removals_.insert(DicomTag(0x0008, 0x0014)); // Instance Creator UID //removals_.insert(DicomTag(0x0008, 0x0018)); // SOP Instance UID => set in Apply() removals_.insert(DicomTag(0x0008, 0x0050)); // Accession Number removals_.insert(DicomTag(0x0008, 0x0080)); // Institution Name removals_.insert(DicomTag(0x0008, 0x0081)); // Institution Address removals_.insert(DicomTag(0x0008, 0x0090)); // Referring Physician's Name removals_.insert(DicomTag(0x0008, 0x0092)); // Referring Physician's Address removals_.insert(DicomTag(0x0008, 0x0094)); // Referring Physician's Telephone Numbers removals_.insert(DicomTag(0x0008, 0x1010)); // Station Name removals_.insert(DicomTag(0x0008, 0x1030)); // Study Description removals_.insert(DicomTag(0x0008, 0x103e)); // Series Description removals_.insert(DicomTag(0x0008, 0x1040)); // Institutional Department Name removals_.insert(DicomTag(0x0008, 0x1048)); // Physician(s) of Record removals_.insert(DicomTag(0x0008, 0x1050)); // Performing Physicians' Name removals_.insert(DicomTag(0x0008, 0x1060)); // Name of Physician(s) Reading Study removals_.insert(DicomTag(0x0008, 0x1070)); // Operators' Name removals_.insert(DicomTag(0x0008, 0x1080)); // Admitting Diagnoses Description //removals_.insert(DicomTag(0x0008, 0x1155)); // Referenced SOP Instance UID => RelationshipsVisitor removals_.insert(DicomTag(0x0008, 0x2111)); // Derivation Description //removals_.insert(DicomTag(0x0010, 0x0010)); // Patient's Name => cf. below (*) //removals_.insert(DicomTag(0x0010, 0x0020)); // Patient ID => cf. below (*) removals_.insert(DicomTag(0x0010, 0x0030)); // Patient's Birth Date removals_.insert(DicomTag(0x0010, 0x0032)); // Patient's Birth Time removals_.insert(DicomTag(0x0010, 0x0040)); // Patient's Sex removals_.insert(DicomTag(0x0010, 0x1000)); // Other Patient Ids removals_.insert(DicomTag(0x0010, 0x1001)); // Other Patient Names removals_.insert(DicomTag(0x0010, 0x1010)); // Patient's Age removals_.insert(DicomTag(0x0010, 0x1020)); // Patient's Size removals_.insert(DicomTag(0x0010, 0x1030)); // Patient's Weight removals_.insert(DicomTag(0x0010, 0x1090)); // Medical Record Locator removals_.insert(DicomTag(0x0010, 0x2160)); // Ethnic Group removals_.insert(DicomTag(0x0010, 0x2180)); // Occupation removals_.insert(DicomTag(0x0010, 0x21b0)); // Additional Patient's History removals_.insert(DicomTag(0x0010, 0x4000)); // Patient Comments removals_.insert(DicomTag(0x0018, 0x1000)); // Device Serial Number removals_.insert(DicomTag(0x0018, 0x1030)); // Protocol Name //removals_.insert(DicomTag(0x0020, 0x000d)); // Study Instance UID => set in Apply() //removals_.insert(DicomTag(0x0020, 0x000e)); // Series Instance UID => set in Apply() removals_.insert(DicomTag(0x0020, 0x0010)); // Study ID //removals_.insert(DicomTag(0x0020, 0x0052)); // Frame of Reference UID => cf. RelationshipsVisitor removals_.insert(DicomTag(0x0020, 0x0200)); // Synchronization Frame of Reference UID removals_.insert(DicomTag(0x0020, 0x4000)); // Image Comments removals_.insert(DicomTag(0x0040, 0x0275)); // Request Attributes Sequence removals_.insert(DicomTag(0x0040, 0xa124)); // UID removals_.insert(DicomTag(0x0040, 0xa730)); // Content Sequence removals_.insert(DicomTag(0x0088, 0x0140)); // Storage Media File-set UID //removals_.insert(DicomTag(0x3006, 0x0024)); // Referenced Frame of Reference UID => RelationshipsVisitor //removals_.insert(DicomTag(0x3006, 0x00c2)); // Related Frame of Reference UID => RelationshipsVisitor // Some more removals (from the experience of DICOM files at the CHU of Liege) removals_.insert(DicomTag(0x0010, 0x1040)); // Patient's Address removals_.insert(DicomTag(0x0032, 0x1032)); // Requesting Physician removals_.insert(DicomTag(0x0010, 0x2154)); // PatientTelephoneNumbers removals_.insert(DicomTag(0x0010, 0x2000)); // Medical Alerts // Set the DeidentificationMethod tag ReplaceInternal(DICOM_TAG_DEIDENTIFICATION_METHOD, ORTHANC_DEIDENTIFICATION_METHOD_2008); } void DicomModification::SetupAnonymization2017c() { /** * This is Table E.1-1 from PS 3.15-2017c (DICOM Part 15: Security * and System Management Profiles), "basic profile" column. It was * generated automatically with the * "../Resources/GenerateAnonymizationProfile.py" script. * https://raw.githubusercontent.com/jodogne/dicom-specification/master/2017c/part15.pdf **/ // TODO: (50xx,xxxx) with rule X // Curve Data // TODO: (60xx,3000) with rule X // Overlay Data // TODO: (60xx,4000) with rule X // Overlay Comments // Tag (0x0008, 0x0018) is set in Apply() /* U */ // SOP Instance UID // Tag (0x0008, 0x1140) => RelationshipsVisitor /* X/Z/U* */ // Referenced Image Sequence // Tag (0x0008, 0x1155) => RelationshipsVisitor /* U */ // Referenced SOP Instance UID // Tag (0x0008, 0x2112) => RelationshipsVisitor /* X/Z/U* */ // Source Image Sequence // Tag (0x0010, 0x0010) is set below (*) /* Z */ // Patient's Name // Tag (0x0010, 0x0020) is set below (*) /* Z */ // Patient ID // Tag (0x0020, 0x000d) is set in Apply() /* U */ // Study Instance UID // Tag (0x0020, 0x000e) is set in Apply() /* U */ // Series Instance UID // Tag (0x0020, 0x0052) => RelationshipsVisitor /* U */ // Frame of Reference UID // Tag (0x3006, 0x0024) => RelationshipsVisitor /* U */ // Referenced Frame of Reference UID // Tag (0x3006, 0x00c2) => RelationshipsVisitor /* U */ // Related Frame of Reference UID clearings_.insert(DicomTag(0x0008, 0x0020)); // Study Date clearings_.insert(DicomTag(0x0008, 0x0023)); /* Z/D */ // Content Date clearings_.insert(DicomTag(0x0008, 0x0030)); // Study Time clearings_.insert(DicomTag(0x0008, 0x0033)); /* Z/D */ // Content Time clearings_.insert(DicomTag(0x0008, 0x0050)); // Accession Number clearings_.insert(DicomTag(0x0008, 0x0090)); // Referring Physician's Name clearings_.insert(DicomTag(0x0008, 0x009c)); // Consulting Physician's Name clearings_.insert(DicomTag(0x0010, 0x0030)); // Patient's Birth Date clearings_.insert(DicomTag(0x0010, 0x0040)); // Patient's Sex clearings_.insert(DicomTag(0x0018, 0x0010)); /* Z/D */ // Contrast Bolus Agent clearings_.insert(DicomTag(0x0020, 0x0010)); // Study ID clearings_.insert(DicomTag(0x0040, 0x1101)); /* D */ // Person Identification Code Sequence clearings_.insert(DicomTag(0x0040, 0x2016)); // Placer Order Number / Imaging Service Request clearings_.insert(DicomTag(0x0040, 0x2017)); // Filler Order Number / Imaging Service Request clearings_.insert(DicomTag(0x0040, 0xa073)); /* D */ // Verifying Observer Sequence clearings_.insert(DicomTag(0x0040, 0xa075)); /* D */ // Verifying Observer Name clearings_.insert(DicomTag(0x0040, 0xa088)); // Verifying Observer Identification Code Sequence clearings_.insert(DicomTag(0x0040, 0xa123)); /* D */ // Person Name clearings_.insert(DicomTag(0x0070, 0x0001)); /* D */ // Graphic Annotation Sequence clearings_.insert(DicomTag(0x0070, 0x0084)); // Content Creator's Name removals_.insert(DicomTag(0x0000, 0x1000)); // Affected SOP Instance UID removals_.insert(DicomTag(0x0000, 0x1001)); /* TODO UID */ // Requested SOP Instance UID removals_.insert(DicomTag(0x0002, 0x0003)); /* TODO UID */ // Media Storage SOP Instance UID removals_.insert(DicomTag(0x0004, 0x1511)); /* TODO UID */ // Referenced SOP Instance UID in File removals_.insert(DicomTag(0x0008, 0x0014)); /* TODO UID */ // Instance Creator UID removals_.insert(DicomTag(0x0008, 0x0015)); // Instance Coercion DateTime removals_.insert(DicomTag(0x0008, 0x0021)); /* X/D */ // Series Date removals_.insert(DicomTag(0x0008, 0x0022)); /* X/Z */ // Acquisition Date removals_.insert(DicomTag(0x0008, 0x0024)); // Overlay Date removals_.insert(DicomTag(0x0008, 0x0025)); // Curve Date removals_.insert(DicomTag(0x0008, 0x002a)); /* X/D */ // Acquisition DateTime removals_.insert(DicomTag(0x0008, 0x0031)); /* X/D */ // Series Time removals_.insert(DicomTag(0x0008, 0x0032)); /* X/Z */ // Acquisition Time removals_.insert(DicomTag(0x0008, 0x0034)); // Overlay Time removals_.insert(DicomTag(0x0008, 0x0035)); // Curve Time removals_.insert(DicomTag(0x0008, 0x0058)); /* TODO UID */ // Failed SOP Instance UID List removals_.insert(DicomTag(0x0008, 0x0080)); /* X/Z/D */ // Institution Name removals_.insert(DicomTag(0x0008, 0x0081)); // Institution Address removals_.insert(DicomTag(0x0008, 0x0082)); /* X/Z/D */ // Institution Code Sequence removals_.insert(DicomTag(0x0008, 0x0092)); // Referring Physician's Address removals_.insert(DicomTag(0x0008, 0x0094)); // Referring Physician's Telephone Numbers removals_.insert(DicomTag(0x0008, 0x0096)); // Referring Physician Identification Sequence removals_.insert(DicomTag(0x0008, 0x009d)); // Consulting Physician Identification Sequence removals_.insert(DicomTag(0x0008, 0x0201)); // Timezone Offset From UTC removals_.insert(DicomTag(0x0008, 0x1010)); /* X/Z/D */ // Station Name removals_.insert(DicomTag(0x0008, 0x1030)); // Study Description removals_.insert(DicomTag(0x0008, 0x103e)); // Series Description removals_.insert(DicomTag(0x0008, 0x1040)); // Institutional Department Name removals_.insert(DicomTag(0x0008, 0x1048)); // Physician(s) of Record removals_.insert(DicomTag(0x0008, 0x1049)); // Physician(s) of Record Identification Sequence removals_.insert(DicomTag(0x0008, 0x1050)); // Performing Physicians' Name removals_.insert(DicomTag(0x0008, 0x1052)); // Performing Physician Identification Sequence removals_.insert(DicomTag(0x0008, 0x1060)); // Name of Physician(s) Reading Study removals_.insert(DicomTag(0x0008, 0x1062)); // Physician(s) Reading Study Identification Sequence removals_.insert(DicomTag(0x0008, 0x1070)); /* X/Z/D */ // Operators' Name removals_.insert(DicomTag(0x0008, 0x1072)); /* X/D */ // Operators' Identification Sequence removals_.insert(DicomTag(0x0008, 0x1080)); // Admitting Diagnoses Description removals_.insert(DicomTag(0x0008, 0x1084)); // Admitting Diagnoses Code Sequence removals_.insert(DicomTag(0x0008, 0x1110)); /* X/Z */ // Referenced Study Sequence removals_.insert(DicomTag(0x0008, 0x1111)); /* X/Z/D */ // Referenced Performed Procedure Step Sequence removals_.insert(DicomTag(0x0008, 0x1120)); // Referenced Patient Sequence removals_.insert(DicomTag(0x0008, 0x1195)); /* TODO UID */ // Transaction UID removals_.insert(DicomTag(0x0008, 0x2111)); // Derivation Description removals_.insert(DicomTag(0x0008, 0x3010)); /* TODO UID */ // Irradiation Event UID removals_.insert(DicomTag(0x0008, 0x4000)); // Identifying Comments removals_.insert(DicomTag(0x0010, 0x0021)); // Issuer of Patient ID removals_.insert(DicomTag(0x0010, 0x0032)); // Patient's Birth Time removals_.insert(DicomTag(0x0010, 0x0050)); // Patient's Insurance Plan Code Sequence removals_.insert(DicomTag(0x0010, 0x0101)); // Patient's Primary Language Code Sequence removals_.insert(DicomTag(0x0010, 0x0102)); // Patient's Primary Language Modifier Code Sequence removals_.insert(DicomTag(0x0010, 0x1000)); // Other Patient IDs removals_.insert(DicomTag(0x0010, 0x1001)); // Other Patient Names removals_.insert(DicomTag(0x0010, 0x1002)); // Other Patient IDs Sequence removals_.insert(DicomTag(0x0010, 0x1005)); // Patient's Birth Name removals_.insert(DicomTag(0x0010, 0x1010)); // Patient's Age removals_.insert(DicomTag(0x0010, 0x1020)); // Patient's Size removals_.insert(DicomTag(0x0010, 0x1030)); // Patient's Weight removals_.insert(DicomTag(0x0010, 0x1040)); // Patient Address removals_.insert(DicomTag(0x0010, 0x1050)); // Insurance Plan Identification removals_.insert(DicomTag(0x0010, 0x1060)); // Patient's Mother's Birth Name removals_.insert(DicomTag(0x0010, 0x1080)); // Military Rank removals_.insert(DicomTag(0x0010, 0x1081)); // Branch of Service removals_.insert(DicomTag(0x0010, 0x1090)); // Medical Record Locator removals_.insert(DicomTag(0x0010, 0x1100)); // Referenced Patient Photo Sequence removals_.insert(DicomTag(0x0010, 0x2000)); // Medical Alerts removals_.insert(DicomTag(0x0010, 0x2110)); // Allergies removals_.insert(DicomTag(0x0010, 0x2150)); // Country of Residence removals_.insert(DicomTag(0x0010, 0x2152)); // Region of Residence removals_.insert(DicomTag(0x0010, 0x2154)); // Patient's Telephone Numbers removals_.insert(DicomTag(0x0010, 0x2155)); // Patient's Telecom Information removals_.insert(DicomTag(0x0010, 0x2160)); // Ethnic Group removals_.insert(DicomTag(0x0010, 0x2180)); // Occupation removals_.insert(DicomTag(0x0010, 0x21a0)); // Smoking Status removals_.insert(DicomTag(0x0010, 0x21b0)); // Additional Patient's History removals_.insert(DicomTag(0x0010, 0x21c0)); // Pregnancy Status removals_.insert(DicomTag(0x0010, 0x21d0)); // Last Menstrual Date removals_.insert(DicomTag(0x0010, 0x21f0)); // Patient's Religious Preference removals_.insert(DicomTag(0x0010, 0x2203)); /* X/Z */ // Patient Sex Neutered removals_.insert(DicomTag(0x0010, 0x2297)); // Responsible Person removals_.insert(DicomTag(0x0010, 0x2299)); // Responsible Organization removals_.insert(DicomTag(0x0010, 0x4000)); // Patient Comments removals_.insert(DicomTag(0x0018, 0x1000)); /* X/Z/D */ // Device Serial Number removals_.insert(DicomTag(0x0018, 0x1002)); /* TODO UID */ // Device UID removals_.insert(DicomTag(0x0018, 0x1004)); // Plate ID removals_.insert(DicomTag(0x0018, 0x1005)); // Generator ID removals_.insert(DicomTag(0x0018, 0x1007)); // Cassette ID removals_.insert(DicomTag(0x0018, 0x1008)); // Gantry ID removals_.insert(DicomTag(0x0018, 0x1030)); /* X/D */ // Protocol Name removals_.insert(DicomTag(0x0018, 0x1400)); /* X/D */ // Acquisition Device Processing Description removals_.insert(DicomTag(0x0018, 0x2042)); /* TODO UID */ // Target UID removals_.insert(DicomTag(0x0018, 0x4000)); // Acquisition Comments removals_.insert(DicomTag(0x0018, 0x700a)); /* X/D */ // Detector ID removals_.insert(DicomTag(0x0018, 0x9424)); // Acquisition Protocol Description removals_.insert(DicomTag(0x0018, 0x9516)); /* X/D */ // Start Acquisition DateTime removals_.insert(DicomTag(0x0018, 0x9517)); /* X/D */ // End Acquisition DateTime removals_.insert(DicomTag(0x0018, 0xa003)); // Contribution Description removals_.insert(DicomTag(0x0020, 0x0200)); /* TODO UID */ // Synchronization Frame of Reference UID removals_.insert(DicomTag(0x0020, 0x3401)); // Modifying Device ID removals_.insert(DicomTag(0x0020, 0x3404)); // Modifying Device Manufacturer removals_.insert(DicomTag(0x0020, 0x3406)); // Modified Image Description removals_.insert(DicomTag(0x0020, 0x4000)); // Image Comments removals_.insert(DicomTag(0x0020, 0x9158)); // Frame Comments removals_.insert(DicomTag(0x0020, 0x9161)); /* TODO UID */ // Concatenation UID removals_.insert(DicomTag(0x0020, 0x9164)); /* TODO UID */ // Dimension Organization UID removals_.insert(DicomTag(0x0028, 0x1199)); /* TODO UID */ // Palette Color Lookup Table UID removals_.insert(DicomTag(0x0028, 0x1214)); /* TODO UID */ // Large Palette Color Lookup Table UID removals_.insert(DicomTag(0x0028, 0x4000)); // Image Presentation Comments removals_.insert(DicomTag(0x0032, 0x0012)); // Study ID Issuer removals_.insert(DicomTag(0x0032, 0x1020)); // Scheduled Study Location removals_.insert(DicomTag(0x0032, 0x1021)); // Scheduled Study Location AE Title removals_.insert(DicomTag(0x0032, 0x1030)); // Reason for Study removals_.insert(DicomTag(0x0032, 0x1032)); // Requesting Physician removals_.insert(DicomTag(0x0032, 0x1033)); // Requesting Service removals_.insert(DicomTag(0x0032, 0x1060)); /* X/Z */ // Requested Procedure Description removals_.insert(DicomTag(0x0032, 0x1070)); // Requested Contrast Agent removals_.insert(DicomTag(0x0032, 0x4000)); // Study Comments removals_.insert(DicomTag(0x0038, 0x0004)); // Referenced Patient Alias Sequence removals_.insert(DicomTag(0x0038, 0x0010)); // Admission ID removals_.insert(DicomTag(0x0038, 0x0011)); // Issuer of Admission ID removals_.insert(DicomTag(0x0038, 0x001e)); // Scheduled Patient Institution Residence removals_.insert(DicomTag(0x0038, 0x0020)); // Admitting Date removals_.insert(DicomTag(0x0038, 0x0021)); // Admitting Time removals_.insert(DicomTag(0x0038, 0x0040)); // Discharge Diagnosis Description removals_.insert(DicomTag(0x0038, 0x0050)); // Special Needs removals_.insert(DicomTag(0x0038, 0x0060)); // Service Episode ID removals_.insert(DicomTag(0x0038, 0x0061)); // Issuer of Service Episode ID removals_.insert(DicomTag(0x0038, 0x0062)); // Service Episode Description removals_.insert(DicomTag(0x0038, 0x0300)); // Current Patient Location removals_.insert(DicomTag(0x0038, 0x0400)); // Patient's Institution Residence removals_.insert(DicomTag(0x0038, 0x0500)); // Patient State removals_.insert(DicomTag(0x0038, 0x4000)); // Visit Comments removals_.insert(DicomTag(0x0040, 0x0001)); // Scheduled Station AE Title removals_.insert(DicomTag(0x0040, 0x0002)); // Scheduled Procedure Step Start Date removals_.insert(DicomTag(0x0040, 0x0003)); // Scheduled Procedure Step Start Time removals_.insert(DicomTag(0x0040, 0x0004)); // Scheduled Procedure Step End Date removals_.insert(DicomTag(0x0040, 0x0005)); // Scheduled Procedure Step End Time removals_.insert(DicomTag(0x0040, 0x0006)); // Scheduled Performing Physician Name removals_.insert(DicomTag(0x0040, 0x0007)); // Scheduled Procedure Step Description removals_.insert(DicomTag(0x0040, 0x000b)); // Scheduled Performing Physician Identification Sequence removals_.insert(DicomTag(0x0040, 0x0010)); // Scheduled Station Name removals_.insert(DicomTag(0x0040, 0x0011)); // Scheduled Procedure Step Location removals_.insert(DicomTag(0x0040, 0x0012)); // Pre-Medication removals_.insert(DicomTag(0x0040, 0x0241)); // Performed Station AE Title removals_.insert(DicomTag(0x0040, 0x0242)); // Performed Station Name removals_.insert(DicomTag(0x0040, 0x0243)); // Performed Location removals_.insert(DicomTag(0x0040, 0x0244)); // Performed Procedure Step Start Date removals_.insert(DicomTag(0x0040, 0x0245)); // Performed Procedure Step Start Time removals_.insert(DicomTag(0x0040, 0x0250)); // Performed Procedure Step End Date removals_.insert(DicomTag(0x0040, 0x0251)); // Performed Procedure Step End Time removals_.insert(DicomTag(0x0040, 0x0253)); // Performed Procedure Step ID removals_.insert(DicomTag(0x0040, 0x0254)); // Performed Procedure Step Description removals_.insert(DicomTag(0x0040, 0x0275)); // Request Attributes Sequence removals_.insert(DicomTag(0x0040, 0x0280)); // Comments on the Performed Procedure Step removals_.insert(DicomTag(0x0040, 0x0555)); // Acquisition Context Sequence removals_.insert(DicomTag(0x0040, 0x1001)); // Requested Procedure ID removals_.insert(DicomTag(0x0040, 0x1004)); // Patient Transport Arrangements removals_.insert(DicomTag(0x0040, 0x1005)); // Requested Procedure Location removals_.insert(DicomTag(0x0040, 0x1010)); // Names of Intended Recipient of Results removals_.insert(DicomTag(0x0040, 0x1011)); // Intended Recipients of Results Identification Sequence removals_.insert(DicomTag(0x0040, 0x1102)); // Person Address removals_.insert(DicomTag(0x0040, 0x1103)); // Person's Telephone Numbers removals_.insert(DicomTag(0x0040, 0x1104)); // Person's Telecom Information removals_.insert(DicomTag(0x0040, 0x1400)); // Requested Procedure Comments removals_.insert(DicomTag(0x0040, 0x2001)); // Reason for the Imaging Service Request removals_.insert(DicomTag(0x0040, 0x2008)); // Order Entered By removals_.insert(DicomTag(0x0040, 0x2009)); // Order Enterer Location removals_.insert(DicomTag(0x0040, 0x2010)); // Order Callback Phone Number removals_.insert(DicomTag(0x0040, 0x2011)); // Order Callback Telecom Information removals_.insert(DicomTag(0x0040, 0x2400)); // Imaging Service Request Comments removals_.insert(DicomTag(0x0040, 0x3001)); // Confidentiality Constraint on Patient Data Description removals_.insert(DicomTag(0x0040, 0x4005)); // Scheduled Procedure Step Start DateTime removals_.insert(DicomTag(0x0040, 0x4010)); // Scheduled Procedure Step Modification DateTime removals_.insert(DicomTag(0x0040, 0x4011)); // Expected Completion DateTime removals_.insert(DicomTag(0x0040, 0x4023)); /* TODO UID */ // Referenced General Purpose Scheduled Procedure Step Transaction UID removals_.insert(DicomTag(0x0040, 0x4025)); // Scheduled Station Name Code Sequence removals_.insert(DicomTag(0x0040, 0x4027)); // Scheduled Station Geographic Location Code Sequence removals_.insert(DicomTag(0x0040, 0x4028)); // Performed Station Name Code Sequence removals_.insert(DicomTag(0x0040, 0x4030)); // Performed Station Geographic Location Code Sequence removals_.insert(DicomTag(0x0040, 0x4034)); // Scheduled Human Performers Sequence removals_.insert(DicomTag(0x0040, 0x4035)); // Actual Human Performers Sequence removals_.insert(DicomTag(0x0040, 0x4036)); // Human Performers Organization removals_.insert(DicomTag(0x0040, 0x4037)); // Human Performers Name removals_.insert(DicomTag(0x0040, 0x4050)); // Performed Procedure Step Start DateTime removals_.insert(DicomTag(0x0040, 0x4051)); // Performed Procedure Step End DateTime removals_.insert(DicomTag(0x0040, 0x4052)); // Procedure Step Cancellation DateTime removals_.insert(DicomTag(0x0040, 0xa027)); // Verifying Organization removals_.insert(DicomTag(0x0040, 0xa078)); // Author Observer Sequence removals_.insert(DicomTag(0x0040, 0xa07a)); // Participant Sequence removals_.insert(DicomTag(0x0040, 0xa07c)); // Custodial Organization Sequence removals_.insert(DicomTag(0x0040, 0xa124)); /* TODO UID */ // UID removals_.insert(DicomTag(0x0040, 0xa171)); /* TODO UID */ // Observation UID removals_.insert(DicomTag(0x0040, 0xa172)); /* TODO UID */ // Referenced Observation UID (Trial) removals_.insert(DicomTag(0x0040, 0xa192)); // Observation Date (Trial) removals_.insert(DicomTag(0x0040, 0xa193)); // Observation Time (Trial) removals_.insert(DicomTag(0x0040, 0xa307)); // Current Observer (Trial) removals_.insert(DicomTag(0x0040, 0xa352)); // Verbal Source (Trial) removals_.insert(DicomTag(0x0040, 0xa353)); // Address (Trial) removals_.insert(DicomTag(0x0040, 0xa354)); // Telephone Number (Trial) removals_.insert(DicomTag(0x0040, 0xa358)); // Verbal Source Identifier Code Sequence (Trial) removals_.insert(DicomTag(0x0040, 0xa402)); /* TODO UID */ // Observation Subject UID (Trial) removals_.insert(DicomTag(0x0040, 0xa730)); // Content Sequence removals_.insert(DicomTag(0x0040, 0xdb0c)); /* TODO UID */ // Template Extension Organization UID removals_.insert(DicomTag(0x0040, 0xdb0d)); /* TODO UID */ // Template Extension Creator UID removals_.insert(DicomTag(0x0062, 0x0021)); /* TODO UID */ // Tracking UID removals_.insert(DicomTag(0x0070, 0x0086)); // Content Creator's Identification Code Sequence removals_.insert(DicomTag(0x0070, 0x031a)); /* TODO UID */ // Fiducial UID removals_.insert(DicomTag(0x0070, 0x1101)); /* TODO UID */ // Presentation Display Collection UID removals_.insert(DicomTag(0x0070, 0x1102)); /* TODO UID */ // Presentation Sequence Collection UID removals_.insert(DicomTag(0x0088, 0x0140)); /* TODO UID */ // Storage Media File-set UID removals_.insert(DicomTag(0x0088, 0x0200)); // Icon Image Sequence(see Note 12) removals_.insert(DicomTag(0x0088, 0x0904)); // Topic Title removals_.insert(DicomTag(0x0088, 0x0906)); // Topic Subject removals_.insert(DicomTag(0x0088, 0x0910)); // Topic Author removals_.insert(DicomTag(0x0088, 0x0912)); // Topic Keywords removals_.insert(DicomTag(0x0400, 0x0100)); // Digital Signature UID removals_.insert(DicomTag(0x0400, 0x0402)); // Referenced Digital Signature Sequence removals_.insert(DicomTag(0x0400, 0x0403)); // Referenced SOP Instance MAC Sequence removals_.insert(DicomTag(0x0400, 0x0404)); // MAC removals_.insert(DicomTag(0x0400, 0x0550)); // Modified Attributes Sequence removals_.insert(DicomTag(0x0400, 0x0561)); // Original Attributes Sequence removals_.insert(DicomTag(0x2030, 0x0020)); // Text String removals_.insert(DicomTag(0x3008, 0x0105)); // Source Serial Number removals_.insert(DicomTag(0x300a, 0x0013)); /* TODO UID */ // Dose Reference UID removals_.insert(DicomTag(0x300c, 0x0113)); // Reason for Omission Description removals_.insert(DicomTag(0x300e, 0x0008)); /* X/Z */ // Reviewer Name removals_.insert(DicomTag(0x4000, 0x0010)); // Arbitrary removals_.insert(DicomTag(0x4000, 0x4000)); // Text Comments removals_.insert(DicomTag(0x4008, 0x0042)); // Results ID Issuer removals_.insert(DicomTag(0x4008, 0x0102)); // Interpretation Recorder removals_.insert(DicomTag(0x4008, 0x010a)); // Interpretation Transcriber removals_.insert(DicomTag(0x4008, 0x010b)); // Interpretation Text removals_.insert(DicomTag(0x4008, 0x010c)); // Interpretation Author removals_.insert(DicomTag(0x4008, 0x0111)); // Interpretation Approver Sequence removals_.insert(DicomTag(0x4008, 0x0114)); // Physician Approving Interpretation removals_.insert(DicomTag(0x4008, 0x0115)); // Interpretation Diagnosis Description removals_.insert(DicomTag(0x4008, 0x0118)); // Results Distribution List Sequence removals_.insert(DicomTag(0x4008, 0x0119)); // Distribution Name removals_.insert(DicomTag(0x4008, 0x011a)); // Distribution Address removals_.insert(DicomTag(0x4008, 0x0202)); // Interpretation ID Issuer removals_.insert(DicomTag(0x4008, 0x0300)); // Impressions removals_.insert(DicomTag(0x4008, 0x4000)); // Results Comments removals_.insert(DicomTag(0xfffa, 0xfffa)); // Digital Signatures Sequence removals_.insert(DicomTag(0xfffc, 0xfffc)); // Data Set Trailing Padding // Set the DeidentificationMethod tag ReplaceInternal(DICOM_TAG_DEIDENTIFICATION_METHOD, ORTHANC_DEIDENTIFICATION_METHOD_2017c); } void DicomModification::SetupAnonymization(DicomVersion version) { isAnonymization_ = true; removals_.clear(); clearings_.clear(); ClearReplacements(); removePrivateTags_ = true; level_ = ResourceType_Patient; uidMap_.clear(); privateTagsToKeep_.clear(); switch (version) { case DicomVersion_2008: SetupAnonymization2008(); break; case DicomVersion_2017c: SetupAnonymization2017c(); break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } // Set the PatientIdentityRemoved tag ReplaceInternal(DicomTag(0x0012, 0x0062), "YES"); // (*) Choose a random patient name and ID std::string patientId = FromDcmtkBridge::GenerateUniqueIdentifier(ResourceType_Patient); ReplaceInternal(DICOM_TAG_PATIENT_ID, patientId); ReplaceInternal(DICOM_TAG_PATIENT_NAME, patientId); } void DicomModification::Apply(ParsedDicomFile& toModify) { // Check the request assert(ResourceType_Patient + 1 == ResourceType_Study && ResourceType_Study + 1 == ResourceType_Series && ResourceType_Series + 1 == ResourceType_Instance); if (IsRemoved(DICOM_TAG_PATIENT_ID) || IsRemoved(DICOM_TAG_STUDY_INSTANCE_UID) || IsRemoved(DICOM_TAG_SERIES_INSTANCE_UID) || IsRemoved(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest); } // Sanity checks at the patient level if (level_ == ResourceType_Patient && !IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, her PatientID is required to be modified"); } if (!allowManualIdentifiers_) { if (level_ == ResourceType_Patient && IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, the StudyInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Patient && IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, the SeriesInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Patient && IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, the SopInstanceUID cannot be manually modified"); } } // Sanity checks at the study level if (level_ == ResourceType_Study && IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a study, the parent PatientID cannot be manually modified"); } if (!allowManualIdentifiers_) { if (level_ == ResourceType_Study && IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a study, the SeriesInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Study && IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a study, the SopInstanceUID cannot be manually modified"); } } // Sanity checks at the series level if (level_ == ResourceType_Series && IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a series, the parent PatientID cannot be manually modified"); } if (level_ == ResourceType_Series && IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a series, the parent StudyInstanceUID cannot be manually modified"); } if (!allowManualIdentifiers_) { if (level_ == ResourceType_Series && IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a series, the SopInstanceUID cannot be manually modified"); } } // Sanity checks at the instance level if (level_ == ResourceType_Instance && IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying an instance, the parent PatientID cannot be manually modified"); } if (level_ == ResourceType_Instance && IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying an instance, the parent StudyInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Instance && IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying an instance, the parent SeriesInstanceUID cannot be manually modified"); } // (0) Create a summary of the source file, if a custom generator // is provided if (identifierGenerator_ != NULL) { toModify.ExtractDicomSummary(currentSource_, ORTHANC_MAXIMUM_TAG_LENGTH); } // (1) Make sure the relationships are updated with the ids that we force too // i.e: an RT-STRUCT is referencing its own StudyInstanceUID if (isAnonymization_ && updateReferencedRelationships_) { if (IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { std::string original; std::string replacement = GetReplacementAsString(DICOM_TAG_STUDY_INSTANCE_UID); toModify.GetTagValue(original, DICOM_TAG_STUDY_INSTANCE_UID); RegisterMappedDicomIdentifier(original, replacement, ResourceType_Study); } if (IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { std::string original; std::string replacement = GetReplacementAsString(DICOM_TAG_SERIES_INSTANCE_UID); toModify.GetTagValue(original, DICOM_TAG_SERIES_INSTANCE_UID); RegisterMappedDicomIdentifier(original, replacement, ResourceType_Series); } if (IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { std::string original; std::string replacement = GetReplacementAsString(DICOM_TAG_SOP_INSTANCE_UID); toModify.GetTagValue(original, DICOM_TAG_SOP_INSTANCE_UID); RegisterMappedDicomIdentifier(original, replacement, ResourceType_Instance); } } // (2) Remove the private tags, if need be if (removePrivateTags_) { toModify.RemovePrivateTags(privateTagsToKeep_); } // (3) Clear the tags specified by the user for (SetOfTags::const_iterator it = clearings_.begin(); it != clearings_.end(); ++it) { toModify.Clear(*it, true /* only clear if the tag exists in the original file */); } // (4) Remove the tags specified by the user for (SetOfTags::const_iterator it = removals_.begin(); it != removals_.end(); ++it) { toModify.Remove(*it); } // (5) Replace the tags for (Replacements::const_iterator it = replacements_.begin(); it != replacements_.end(); ++it) { toModify.Replace(it->first, *it->second, true /* decode data URI scheme */, DicomReplaceMode_InsertIfAbsent, privateCreator_); } // (6) Update the DICOM identifiers if (level_ <= ResourceType_Study && !IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { if (keepStudyInstanceUid_) { LOG(WARNING) << "Modifying a study while keeping its original StudyInstanceUID: This should be avoided!"; } else { MapDicomTags(toModify, ResourceType_Study); } } if (level_ <= ResourceType_Series && !IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { if (keepSeriesInstanceUid_) { LOG(WARNING) << "Modifying a series while keeping its original SeriesInstanceUID: This should be avoided!"; } else { MapDicomTags(toModify, ResourceType_Series); } } if (level_ <= ResourceType_Instance && // Always true !IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { if (keepSopInstanceUid_) { LOG(WARNING) << "Modifying an instance while keeping its original SOPInstanceUID: This should be avoided!"; } else { MapDicomTags(toModify, ResourceType_Instance); } } // (7) Update the "referenced" relationships in the case of an anonymization if (isAnonymization_) { RelationshipsVisitor visitor(*this); if (updateReferencedRelationships_) { toModify.Apply(visitor); } else { visitor.RemoveRelationships(toModify); } } } static bool IsDatabaseKey(const DicomTag& tag) { return (tag == DICOM_TAG_PATIENT_ID || tag == DICOM_TAG_STUDY_INSTANCE_UID || tag == DICOM_TAG_SERIES_INSTANCE_UID || tag == DICOM_TAG_SOP_INSTANCE_UID); } static void ParseListOfTags(DicomModification& target, const Json::Value& query, DicomModification::TagOperation operation, bool force) { if (!query.isArray()) { throw OrthancException(ErrorCode_BadRequest); } for (Json::Value::ArrayIndex i = 0; i < query.size(); i++) { if (query[i].type() != Json::stringValue) { throw OrthancException(ErrorCode_BadRequest); } std::string name = query[i].asString(); DicomTag tag = FromDcmtkBridge::ParseTag(name); if (!force && IsDatabaseKey(tag)) { throw OrthancException(ErrorCode_BadRequest, "Marking tag \"" + name + "\" as to be " + (operation == DicomModification::TagOperation_Keep ? "kept" : "removed") + " requires the \"Force\" option to be set to true"); } switch (operation) { case DicomModification::TagOperation_Keep: target.Keep(tag); VLOG(1) << "Keep: " << name << " " << tag; break; case DicomModification::TagOperation_Remove: target.Remove(tag); VLOG(1) << "Remove: " << name << " " << tag; break; default: throw OrthancException(ErrorCode_InternalError); } } } static void ParseReplacements(DicomModification& target, const Json::Value& replacements, bool force) { if (!replacements.isObject()) { throw OrthancException(ErrorCode_BadRequest); } Json::Value::Members members = replacements.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const std::string& name = members[i]; const Json::Value& value = replacements[name]; DicomTag tag = FromDcmtkBridge::ParseTag(name); if (!force && IsDatabaseKey(tag)) { throw OrthancException(ErrorCode_BadRequest, "Marking tag \"" + name + "\" as to be replaced " + "requires the \"Force\" option to be set to true"); } target.Replace(tag, value, false); VLOG(1) << "Replace: " << name << " " << tag << " == " << value.toStyledString(); } } static bool GetBooleanValue(const std::string& member, const Json::Value& json, bool defaultValue) { if (!json.isMember(member)) { return defaultValue; } else if (json[member].type() == Json::booleanValue) { return json[member].asBool(); } else { throw OrthancException(ErrorCode_BadFileFormat, "Member \"" + member + "\" should be a Boolean value"); } } void DicomModification::ParseModifyRequest(const Json::Value& request) { if (!request.isObject()) { throw OrthancException(ErrorCode_BadFileFormat); } bool force = GetBooleanValue("Force", request, false); if (GetBooleanValue("RemovePrivateTags", request, false)) { SetRemovePrivateTags(true); } if (request.isMember("Remove")) { ParseListOfTags(*this, request["Remove"], TagOperation_Remove, force); } if (request.isMember("Replace")) { ParseReplacements(*this, request["Replace"], force); } // The "Keep" operation only makes sense for the tags // StudyInstanceUID, SeriesInstanceUID and SOPInstanceUID. Avoid // this feature as much as possible, as this breaks the DICOM // model of the real world, except if you know exactly what // you're doing! if (request.isMember("Keep")) { ParseListOfTags(*this, request["Keep"], TagOperation_Keep, force); } // New in Orthanc 1.6.0 if (request.isMember("PrivateCreator")) { privateCreator_ = SerializationToolbox::ReadString(request, "PrivateCreator"); } } void DicomModification::ParseAnonymizationRequest(bool& patientNameReplaced, const Json::Value& request) { if (!request.isObject()) { throw OrthancException(ErrorCode_BadFileFormat); } bool force = GetBooleanValue("Force", request, false); // As of Orthanc 1.3.0, the default anonymization is done // according to PS 3.15-2017c Table E.1-1 (basic profile) DicomVersion version = DicomVersion_2017c; if (request.isMember("DicomVersion")) { if (request["DicomVersion"].type() != Json::stringValue) { throw OrthancException(ErrorCode_BadFileFormat); } else { version = StringToDicomVersion(request["DicomVersion"].asString()); } } SetupAnonymization(version); std::string patientName = GetReplacementAsString(DICOM_TAG_PATIENT_NAME); if (GetBooleanValue("KeepPrivateTags", request, false)) { SetRemovePrivateTags(false); } if (request.isMember("Remove")) { ParseListOfTags(*this, request["Remove"], TagOperation_Remove, force); } if (request.isMember("Replace")) { ParseReplacements(*this, request["Replace"], force); } if (request.isMember("Keep")) { ParseListOfTags(*this, request["Keep"], TagOperation_Keep, force); } patientNameReplaced = (IsReplaced(DICOM_TAG_PATIENT_NAME) && GetReplacement(DICOM_TAG_PATIENT_NAME) == patientName); // New in Orthanc 1.6.0 if (request.isMember("PrivateCreator")) { privateCreator_ = SerializationToolbox::ReadString(request, "PrivateCreator"); } } static const char* REMOVE_PRIVATE_TAGS = "RemovePrivateTags"; static const char* LEVEL = "Level"; static const char* ALLOW_MANUAL_IDENTIFIERS = "AllowManualIdentifiers"; static const char* KEEP_STUDY_INSTANCE_UID = "KeepStudyInstanceUID"; static const char* KEEP_SERIES_INSTANCE_UID = "KeepSeriesInstanceUID"; static const char* KEEP_SOP_INSTANCE_UID = "KeepSOPInstanceUID"; static const char* UPDATE_REFERENCED_RELATIONSHIPS = "UpdateReferencedRelationships"; static const char* IS_ANONYMIZATION = "IsAnonymization"; static const char* REMOVALS = "Removals"; static const char* CLEARINGS = "Clearings"; static const char* PRIVATE_TAGS_TO_KEEP = "PrivateTagsToKeep"; static const char* REPLACEMENTS = "Replacements"; static const char* MAP_PATIENTS = "MapPatients"; static const char* MAP_STUDIES = "MapStudies"; static const char* MAP_SERIES = "MapSeries"; static const char* MAP_INSTANCES = "MapInstances"; static const char* PRIVATE_CREATOR = "PrivateCreator"; // New in Orthanc 1.6.0 void DicomModification::Serialize(Json::Value& value) const { if (identifierGenerator_ != NULL) { throw OrthancException(ErrorCode_InternalError, "Cannot serialize a DicomModification with a custom identifier generator"); } value = Json::objectValue; value[REMOVE_PRIVATE_TAGS] = removePrivateTags_; value[LEVEL] = EnumerationToString(level_); value[ALLOW_MANUAL_IDENTIFIERS] = allowManualIdentifiers_; value[KEEP_STUDY_INSTANCE_UID] = keepStudyInstanceUid_; value[KEEP_SERIES_INSTANCE_UID] = keepSeriesInstanceUid_; value[KEEP_SOP_INSTANCE_UID] = keepSopInstanceUid_; value[UPDATE_REFERENCED_RELATIONSHIPS] = updateReferencedRelationships_; value[IS_ANONYMIZATION] = isAnonymization_; value[PRIVATE_CREATOR] = privateCreator_; SerializationToolbox::WriteSetOfTags(value, removals_, REMOVALS); SerializationToolbox::WriteSetOfTags(value, clearings_, CLEARINGS); SerializationToolbox::WriteSetOfTags(value, privateTagsToKeep_, PRIVATE_TAGS_TO_KEEP); Json::Value& tmp = value[REPLACEMENTS]; tmp = Json::objectValue; for (Replacements::const_iterator it = replacements_.begin(); it != replacements_.end(); ++it) { assert(it->second != NULL); tmp[it->first.Format()] = *it->second; } Json::Value& mapPatients = value[MAP_PATIENTS]; Json::Value& mapStudies = value[MAP_STUDIES]; Json::Value& mapSeries = value[MAP_SERIES]; Json::Value& mapInstances = value[MAP_INSTANCES]; mapPatients = Json::objectValue; mapStudies = Json::objectValue; mapSeries = Json::objectValue; mapInstances = Json::objectValue; for (UidMap::const_iterator it = uidMap_.begin(); it != uidMap_.end(); ++it) { Json::Value* tmp2 = NULL; switch (it->first.first) { case ResourceType_Patient: tmp2 = &mapPatients; break; case ResourceType_Study: tmp2 = &mapStudies; break; case ResourceType_Series: tmp2 = &mapSeries; break; case ResourceType_Instance: tmp2 = &mapInstances; break; default: throw OrthancException(ErrorCode_InternalError); } assert(tmp2 != NULL); (*tmp2) [it->first.second] = it->second; } } void DicomModification::UnserializeUidMap(ResourceType level, const Json::Value& serialized, const char* field) { if (!serialized.isMember(field) || serialized[field].type() != Json::objectValue) { throw OrthancException(ErrorCode_BadFileFormat); } Json::Value::Members names = serialized[field].getMemberNames(); for (Json::Value::Members::const_iterator it = names.begin(); it != names.end(); ++it) { const Json::Value& value = serialized[field][*it]; if (value.type() != Json::stringValue) { throw OrthancException(ErrorCode_BadFileFormat); } else { uidMap_[std::make_pair(level, *it)] = value.asString(); } } } DicomModification::DicomModification(const Json::Value& serialized) : identifierGenerator_(NULL) { removePrivateTags_ = SerializationToolbox::ReadBoolean(serialized, REMOVE_PRIVATE_TAGS); level_ = StringToResourceType(SerializationToolbox::ReadString(serialized, LEVEL).c_str()); allowManualIdentifiers_ = SerializationToolbox::ReadBoolean(serialized, ALLOW_MANUAL_IDENTIFIERS); keepStudyInstanceUid_ = SerializationToolbox::ReadBoolean(serialized, KEEP_STUDY_INSTANCE_UID); keepSeriesInstanceUid_ = SerializationToolbox::ReadBoolean(serialized, KEEP_SERIES_INSTANCE_UID); keepSopInstanceUid_ = SerializationToolbox::ReadBoolean(serialized, KEEP_SOP_INSTANCE_UID); updateReferencedRelationships_ = SerializationToolbox::ReadBoolean (serialized, UPDATE_REFERENCED_RELATIONSHIPS); isAnonymization_ = SerializationToolbox::ReadBoolean(serialized, IS_ANONYMIZATION); if (serialized.isMember(PRIVATE_CREATOR)) { privateCreator_ = SerializationToolbox::ReadString(serialized, PRIVATE_CREATOR); } SerializationToolbox::ReadSetOfTags(removals_, serialized, REMOVALS); SerializationToolbox::ReadSetOfTags(clearings_, serialized, CLEARINGS); SerializationToolbox::ReadSetOfTags(privateTagsToKeep_, serialized, PRIVATE_TAGS_TO_KEEP); if (!serialized.isMember(REPLACEMENTS) || serialized[REPLACEMENTS].type() != Json::objectValue) { throw OrthancException(ErrorCode_BadFileFormat); } Json::Value::Members names = serialized[REPLACEMENTS].getMemberNames(); for (Json::Value::Members::const_iterator it = names.begin(); it != names.end(); ++it) { DicomTag tag(0, 0); if (!DicomTag::ParseHexadecimal(tag, it->c_str())) { throw OrthancException(ErrorCode_BadFileFormat); } else { const Json::Value& value = serialized[REPLACEMENTS][*it]; replacements_.insert(std::make_pair(tag, new Json::Value(value))); } } UnserializeUidMap(ResourceType_Patient, serialized, MAP_PATIENTS); UnserializeUidMap(ResourceType_Study, serialized, MAP_STUDIES); UnserializeUidMap(ResourceType_Series, serialized, MAP_SERIES); UnserializeUidMap(ResourceType_Instance, serialized, MAP_INSTANCES); } }
45.228836
139
0.624514
a2609194449
eb56133760a6445cd88612e1a1f6e2143fa054ad
2,073
cc
C++
rdc_libs/bootstrap/src/RdcLibraryLoader.cc
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2020-09-10T02:04:00.000Z
2020-12-03T10:55:38.000Z
rdc_libs/bootstrap/src/RdcLibraryLoader.cc
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2022-03-29T00:32:43.000Z
2022-03-31T18:09:36.000Z
rdc_libs/bootstrap/src/RdcLibraryLoader.cc
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2020-09-15T08:05:43.000Z
2021-09-02T03:06:41.000Z
/* Copyright (c) 2020 - present Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "rdc_lib/RdcLibraryLoader.h" namespace amd { namespace rdc { RdcLibraryLoader::RdcLibraryLoader(): libHandler_(nullptr) { } rdc_status_t RdcLibraryLoader::load(const char* filename) { if (filename == nullptr) { return RDC_ST_FAIL_LOAD_MODULE; } if (libHandler_) { unload(); } std::lock_guard<std::mutex> guard(library_mutex_); libHandler_ = dlopen(filename, RTLD_LAZY); if (!libHandler_) { char* error = dlerror(); RDC_LOG(RDC_ERROR, "Fail to open " << filename <<": " << error); return RDC_ST_FAIL_LOAD_MODULE; } return RDC_ST_OK; } rdc_status_t RdcLibraryLoader::unload() { std::lock_guard<std::mutex> guard(library_mutex_); if (libHandler_) { dlclose(libHandler_); libHandler_ = nullptr; } return RDC_ST_OK; } RdcLibraryLoader::~RdcLibraryLoader() { unload(); } } // namespace rdc } // namespace amd
31.892308
78
0.71973
RadeonOpenCompute
eb5848561ecb03ba188cf8cd012b602444ff4f2c
3,898
hpp
C++
include/gtirb/Offset.hpp
clayne/gtirb
df9bf69537c36136d40fbff98588df37b8c5875f
[ "MIT" ]
230
2018-10-14T11:07:14.000Z
2022-03-31T21:25:43.000Z
include/gtirb/Offset.hpp
clayne/gtirb
df9bf69537c36136d40fbff98588df37b8c5875f
[ "MIT" ]
33
2018-10-25T15:48:48.000Z
2022-03-25T03:10:13.000Z
include/gtirb/Offset.hpp
clayne/gtirb
df9bf69537c36136d40fbff98588df37b8c5875f
[ "MIT" ]
33
2018-10-14T11:07:17.000Z
2022-03-31T16:12:00.000Z
//===- Offset.hpp ------------------------------------------------*- C++-*-===// // // Copyright (C) 2020 GrammaTech, Inc. // // This code is licensed under the MIT license. See the LICENSE file in the // project root for license terms. // // This project is sponsored by the Office of Naval Research, One Liberty // Center, 875 N. Randolph Street, Arlington, VA 22203 under contract # // N68335-17-C-0700. The content of the information does not necessarily // reflect the position or policy of the Government and no official // endorsement should be inferred. // //===----------------------------------------------------------------------===// #ifndef GTIRB_OFFSET_H #define GTIRB_OFFSET_H #include <gtirb/Context.hpp> #include <gtirb/Export.hpp> #include <boost/functional/hash.hpp> #include <cstdint> #include <functional> namespace gtirb { namespace proto { class Offset; } /// \class Offset /// /// \brief Describes a location inside a node (byte interval, block, etc). struct GTIRB_EXPORT_API Offset { /// \brief The UUID of the node. UUID ElementId; /// \brief The displacement from the start of the node, in bytes. uint64_t Displacement{0}; /// \brief Constructor using a ElemId uuid and a Displacement. Offset(const UUID& ElemId, uint64_t Disp) : ElementId(ElemId), Displacement(Disp) {} /// \brief Default constructor. Offset() = default; /// \brief Equality operator for \ref Offset. // Note: boost::uuid is not constexpr. friend bool operator==(const Offset& LHS, const Offset& RHS) noexcept { return LHS.ElementId == RHS.ElementId && LHS.Displacement == RHS.Displacement; } /// \brief Inequality operator for \ref Offset. friend bool operator!=(const Offset& LHS, const Offset& RHS) noexcept { return !operator==(LHS, RHS); } /// \brief Less-than operator for \ref Offset. friend constexpr bool operator<(const Offset& LHS, const Offset& RHS) noexcept { return std::tie(LHS.ElementId, LHS.Displacement) < std::tie(RHS.ElementId, RHS.Displacement); } /// \brief Greater-than operator for \ref Offset. friend constexpr bool operator>(const Offset& LHS, const Offset& RHS) noexcept { return operator<(RHS, LHS); } /// \brief Less-than-or-equal operator for \ref Offset. friend constexpr bool operator<=(const Offset& LHS, const Offset& RHS) noexcept { return !operator<(RHS, LHS); } /// \brief Greater-than-or-equal operator for \ref Offset. friend constexpr bool operator>=(const Offset& LHS, const Offset& RHS) noexcept { return !operator<(LHS, RHS); } private: /// @cond INTERNAL /// \brief The protobuf message type used for serializing Offset. using MessageType = proto::Offset; /// \brief Serialize into a protobuf message. /// /// \param[out] Message Serialize into this message. /// /// \return void void toProtobuf(MessageType* Message) const; /// \brief Construct a Offset from a protobuf message. /// /// \param C The Context in which the deserialized Offset will be /// held. /// \param Message The protobuf message from which to deserialize. /// /// \return true if the \ref Offset could be deserialized, false otherwise. bool fromProtobuf(Context& C, const MessageType& Message); /// @endcond // Enables serialization. friend bool fromProtobuf(Context&, Offset&, const MessageType&); }; } // namespace gtirb namespace std { /// \brief Hash operation for \ref Offset. template <> struct hash<gtirb::Offset> { size_t operator()(const gtirb::Offset& X) const { std::size_t Seed = 0; boost::hash_combine(Seed, X.ElementId); boost::hash_combine(Seed, X.Displacement); return Seed; } }; } // namespace std #endif // GTIRB_OFFSET_H
30.936508
80
0.641868
clayne
eb5a12a9b180d70b6a2446aa6be5f2a2d0c2431f
845
cxx
C++
panda/src/egg/eggMorphList.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/egg/eggMorphList.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/egg/eggMorphList.cxx
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file eggMorphList.cxx * @author drose * @date 2001-05-15 */ #include "eggMorphList.h" // Continue all of the vector import definitions. #define EXPCL EXPCL_PANDAEGG #define EXPTP EXPTP_PANDAEGG #define TYPE LVector3d #define NAME vector_LVector3d #include "vector_src.cxx" #define EXPCL EXPCL_PANDAEGG #define EXPTP EXPTP_PANDAEGG #define TYPE LVector2d #define NAME vector_LVector2d #include "vector_src.cxx" #define EXPCL EXPCL_PANDAEGG #define EXPTP EXPTP_PANDAEGG #define TYPE LVector4 #define NAME vector_LVector4 #include "vector_src.cxx"
24.142857
70
0.771598
sean5470
eb5aea67a93b7475845e8cbfad9baac236ded1f1
1,562
cpp
C++
codeforces/gym/2018 ICPC Asia Jakarta Regional Contest/g.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/gym/2018 ICPC Asia Jakarta Regional Contest/g.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/gym/2018 ICPC Asia Jakarta Regional Contest/g.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> bool check(int n, int m, vector<list<int> > iadj, vvb mat, vi dg, int k){ queue<ii> q; set<int> inq; for(int u=0; u<n; ++u){ for(int v=0; v<n; ++v){ } } while(!q.empty()){ int u = q.front(); q.pop(); inq.erase(u); for(auto it=iadj[u].begin(); it != iadj[u].end();){ int v = *it; if(dg[u] + dg[v] < k){ it++; continue; } m++; dg[u]++; dg[v]++; if(!inq.count(u)){ inq.ep(u); q.ep(u); } if(!inq.count(v)){ inq.ep(v); q.ep(v); } it = iadj[u].erase(it); } } return m == n*(n-1)/2; } int32_t main(){ desync(); int n, m; cin >> n >> m; vi dg(n); vvb mat(n, vb(n)); for(int i=0; i<m; ++i){ int u, v; cin >> u >> v; u--; v--; dg[u]++; dg[v]++; mat[u][v] = mat[v][u] = true; } vector<list<int> > iadj(n); for(int u=0; u<n; ++u){ for(int v=u+1; v<n; ++v){ if(mat[u][v]) continue; iadj[u].eb(v); } } int lo = 0, hi = 2*n, ans = hi; while(lo <= hi){ int mid = (lo+hi)/2; if(check(n, m, iadj, mat, dg, mid)){ ans = mid; lo = mid+1; } else hi = mid-1; } cout << ans << endl; return 0; }
19.525
73
0.330346
tysm
eb5ccf25184469d5927b99c6a64abd10df574cb7
1,032
cpp
C++
CodeChef/Easy/ROWCOLOP.cpp
ritwik1503/Competitive-Coding-1
ffefe5f8b299c623af1ef01bf024af339401de0b
[ "MIT" ]
29
2016-09-02T04:48:59.000Z
2016-09-08T18:13:05.000Z
CodeChef/Easy/ROWCOLOP.cpp
ritwik1503/Competitive-Coding-1
ffefe5f8b299c623af1ef01bf024af339401de0b
[ "MIT" ]
2
2016-09-02T05:20:02.000Z
2016-10-13T06:31:31.000Z
CodeChef/Easy/ROWCOLOP.cpp
ritwik1503/Competitive-Coding-1
ffefe5f8b299c623af1ef01bf024af339401de0b
[ "MIT" ]
7
2017-04-01T20:07:03.000Z
2020-10-16T12:28:54.000Z
#include "bits/stdc++.h" using namespace std; # define s(n) scanf("%d",&n) # define sc(n) scanf("%c",&n) # define sl(n) scanf("%lld",&n) # define sf(n) scanf("%lf",&n) # define ss(n) scanf("%s",n) #define R(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) # define INF (int)1e9 # define EPS 1e-9 # define MOD 1000000007 typedef long long ll; int main() { int t=1; // cin >> t; while(t--){ int n,m,r,x; s(n);s(m); char a[7]; int row[n], col[n]; fill_n(row,n,0); fill_n(col,n,0); R(i,m){ ss(a); s(r); s(x); if(a[0]=='R'){ row[r-1]+=x; } else col[r-1]+=x; } int max_row=0,max_col=0; R(i,n){ if(row[i]>max_row) max_row=row[i]; if(col[i]>max_col) max_col=col[i]; } printf("%d\n",max_row + max_col ); } return 0; }
19.846154
53
0.43314
ritwik1503
eb5d1fc687dd9ef164a10ff6717e6a05624e6fbb
115
cpp
C++
src/main/cpp/MathHelper.cpp
frcteam4458/2022-Command
131634be15ab6da2eed68c5b41dd87b3ee2ffe0a
[ "BSD-3-Clause" ]
1
2022-03-17T02:46:36.000Z
2022-03-17T02:46:36.000Z
src/main/cpp/MathHelper.cpp
frcteam4458/2022-Command
131634be15ab6da2eed68c5b41dd87b3ee2ffe0a
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/MathHelper.cpp
frcteam4458/2022-Command
131634be15ab6da2eed68c5b41dd87b3ee2ffe0a
[ "BSD-3-Clause" ]
null
null
null
#include <math.h> #include "MathHelper.h" double pythagorean(float a, float b) { return sqrt(a * a + b * b); }
16.428571
36
0.634783
frcteam4458
eb5e2fa8e5910376215e39bacf5aa4365e3f96b7
1,357
cpp
C++
ProjectEuler/ProjectEuler#12.cpp
ChameleonTartu/competitive_programming
f8658ba99e7d188c99692d03d52fe9652092ffc6
[ "Apache-2.0" ]
1
2016-08-19T12:14:07.000Z
2016-08-19T12:14:07.000Z
ProjectEuler/ProjectEuler#12.cpp
ChameleonTartu/competitive_programming
f8658ba99e7d188c99692d03d52fe9652092ffc6
[ "Apache-2.0" ]
null
null
null
ProjectEuler/ProjectEuler#12.cpp
ChameleonTartu/competitive_programming
f8658ba99e7d188c99692d03d52fe9652092ffc6
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <cstdio> using namespace std; const int MAX = 1001; int numberOfDivisors(int number) { int divisors = 2; for(int i = 2; i*i <= number; ++i) { if(number % i == 0) divisors += 2; if(i*i == number) --divisors; } return divisors; } int calculateDivisors(int naturalNumber) { int divisors; if(naturalNumber % 2 == 0 ) { divisors = numberOfDivisors(naturalNumber/2); divisors *= numberOfDivisors(naturalNumber + 1); } else { divisors = numberOfDivisors((naturalNumber + 1)/2); divisors *= numberOfDivisors(naturalNumber); } return divisors; } vector<int> maxDivisors(const int MAX) { vector<int> max_divisors(MAX, 0); max_divisors[1] = 3; int naturalNumber = 3, divisors; for(int i = 2; i < MAX; ++i) { divisors = calculateDivisors(naturalNumber); while(i >= divisors) divisors = calculateDivisors(++naturalNumber); int sum = naturalNumber*(naturalNumber + 1)/2; while(i < divisors && i < MAX) max_divisors[i++] = sum; --i; } return max_divisors; } int main() { vector<int> divisors = maxDivisors(MAX); int tests; cin >> tests; for(int i = 0; i < tests; ++i) { int n; cin >> n; cout << divisors[n] << endl; } return 0; }
23.807018
59
0.590273
ChameleonTartu
eb5f44879505186b144365e2bb621f38eae0cb2a
610
cpp
C++
test/test_uintwide_t_n_base.cpp
johnmcfarlane/wide-integer
731d4aca71ba3e668a9d069765bf221f74ae52f1
[ "BSL-1.0" ]
null
null
null
test/test_uintwide_t_n_base.cpp
johnmcfarlane/wide-integer
731d4aca71ba3e668a9d069765bf221f74ae52f1
[ "BSL-1.0" ]
1
2021-05-05T10:44:39.000Z
2021-05-09T20:30:03.000Z
test/test_uintwide_t_n_base.cpp
johnmcfarlane/wide-integer
731d4aca71ba3e668a9d069765bf221f74ae52f1
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2021. // Distributed under the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <test/test_uintwide_t_n_base.h> auto test_uintwide_t_n_base::my_random_generator() -> std::linear_congruential_engine<std::uint32_t, 48271, 0, 2147483647>& { static std::linear_congruential_engine<std::uint32_t, 48271, 0, 2147483647> my_generator; // NOLINT(cert-msc32-c,cert-msc51-cpp) return my_generator; }
38.125
130
0.665574
johnmcfarlane
eb6014a0629df68f0ee6dd3a1ef947149d4785e5
5,102
cpp
C++
third-party/llvm/llvm-src/tools/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
third-party/llvm/llvm-src/tools/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
11,789
2015-01-05T04:50:15.000Z
2022-03-31T23:39:19.000Z
third-party/llvm/llvm-src/tools/clang/lib/StaticAnalyzer/Frontend/AnalyzerHelpFlags.cpp
jhh67/chapel
f041470e9b88b5fc4914c75aa5a37efcb46aa08f
[ "ECL-2.0", "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===--- CheckerRegistration.cpp - Registration for the Analyzer Checkers -===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Defines the registration function for the analyzer checkers. // //===----------------------------------------------------------------------===// #include "clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h" #include "clang/Basic/Diagnostic.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" #include "clang/StaticAnalyzer/Frontend/FrontendActions.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/raw_ostream.h" #include <memory> using namespace clang; using namespace ento; void ento::printCheckerHelp(raw_ostream &out, CompilerInstance &CI) { out << "OVERVIEW: Clang Static Analyzer Checkers List\n\n"; out << "USAGE: -analyzer-checker <CHECKER or PACKAGE,...>\n\n"; auto CheckerMgr = std::make_unique<CheckerManager>( *CI.getAnalyzerOpts(), CI.getLangOpts(), CI.getDiagnostics(), CI.getFrontendOpts().Plugins); CheckerMgr->getCheckerRegistryData().printCheckerWithDescList( *CI.getAnalyzerOpts(), out); } void ento::printEnabledCheckerList(raw_ostream &out, CompilerInstance &CI) { out << "OVERVIEW: Clang Static Analyzer Enabled Checkers List\n\n"; auto CheckerMgr = std::make_unique<CheckerManager>( *CI.getAnalyzerOpts(), CI.getLangOpts(), CI.getDiagnostics(), CI.getFrontendOpts().Plugins); CheckerMgr->getCheckerRegistryData().printEnabledCheckerList(out); } void ento::printCheckerConfigList(raw_ostream &out, CompilerInstance &CI) { auto CheckerMgr = std::make_unique<CheckerManager>( *CI.getAnalyzerOpts(), CI.getLangOpts(), CI.getDiagnostics(), CI.getFrontendOpts().Plugins); CheckerMgr->getCheckerRegistryData().printCheckerOptionList( *CI.getAnalyzerOpts(), out); } void ento::printAnalyzerConfigList(raw_ostream &out) { // FIXME: This message sounds scary, should be scary, but incorrectly states // that all configs are super dangerous. In reality, many of them should be // accessible to the user. We should create a user-facing subset of config // options under a different frontend flag. out << R"( OVERVIEW: Clang Static Analyzer -analyzer-config Option List The following list of configurations are meant for development purposes only, as some of the variables they define are set to result in the most optimal analysis. Setting them to other values may drastically change how the analyzer behaves, and may even result in instabilities, crashes! USAGE: -analyzer-config <OPTION1=VALUE,OPTION2=VALUE,...> -analyzer-config OPTION1=VALUE, -analyzer-config OPTION2=VALUE, ... OPTIONS: )"; using OptionAndDescriptionTy = std::pair<StringRef, std::string>; OptionAndDescriptionTy PrintableOptions[] = { #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \ { \ CMDFLAG, \ llvm::Twine(llvm::Twine() + "(" + \ (StringRef(#TYPE) == "StringRef" ? "string" : #TYPE ) + \ ") " DESC \ " (default: " #DEFAULT_VAL ")").str() \ }, #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \ SHALLOW_VAL, DEEP_VAL) \ { \ CMDFLAG, \ llvm::Twine(llvm::Twine() + "(" + \ (StringRef(#TYPE) == "StringRef" ? "string" : #TYPE ) + \ ") " DESC \ " (default: " #SHALLOW_VAL " in shallow mode, " #DEEP_VAL \ " in deep mode)").str() \ }, #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def" #undef ANALYZER_OPTION #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE }; llvm::sort(PrintableOptions, [](const OptionAndDescriptionTy &LHS, const OptionAndDescriptionTy &RHS) { return LHS.first < RHS.first; }); for (const auto &Pair : PrintableOptions) { AnalyzerOptions::printFormattedEntry(out, Pair, /*InitialPad*/ 2, /*EntryWidth*/ 30, /*MinLineWidth*/ 70); out << "\n\n"; } }
43.982759
80
0.582321
jhh67
eb64843a7a0245f6a31e67e1ec16bfee4c59d291
3,287
cpp
C++
firmware/examples/FreeRTOS_Blinker/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
1
2018-07-07T01:41:34.000Z
2018-07-07T01:41:34.000Z
firmware/examples/FreeRTOS_Blinker/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
null
null
null
firmware/examples/FreeRTOS_Blinker/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
1
2018-09-19T01:58:48.000Z
2018-09-19T01:58:48.000Z
#include <cstdint> #include <cstdio> #include "FreeRTOS.h" #include "task.h" #include "config.hpp" #include "L0_LowLevel/LPC40xx.h" #include "L2_Utilities/debug_print.hpp" #include "L2_Utilities/macros.hpp" #include "L2_Utilities/rtos.hpp" namespace { void LedToggle(void * parameters) { DEBUG_PRINT("Setting up task..."); DEBUG_PRINT("Retrieving delay amount from parameters..."); auto delay = rtos::RetrieveParameter(parameters); DEBUG_PRINT("Initializing LEDs..."); LPC_IOCON->P1_1 &= ~(0b111); LPC_IOCON->P1_8 &= ~(0b111); LPC_GPIO1->DIR |= (1 << 1); LPC_GPIO1->PIN &= ~(1 << 1); LPC_GPIO1->DIR |= (1 << 8); LPC_GPIO1->PIN |= (1 << 8); DEBUG_PRINT("LEDs Initialized..."); DEBUG_PRINT("Toggling LEDs..."); // Loop blinks the LEDs back and forth at a rate that depends on the // pvParameter's value. while (true) { LPC_GPIO1->PIN ^= 0b0001'0000'0010; vTaskDelay(delay); } } constexpr uint32_t kButtonPinNumber = 14; constexpr uint32_t kLedNumber = 15; bool CheckSwitch3() { return (LPC_GPIO1->PIN & (1 << kButtonPinNumber)); } void ButtonReader(void * parameters) { SJ2_USED(parameters); DEBUG_PRINT("Setting up task..."); DEBUG_PRINT("Initializing LED3 and SW3..."); LPC_IOCON->P1_14 &= ~(0b111); LPC_IOCON->P1_15 &= ~(0b111); LPC_GPIO1->DIR &= ~(1 << kButtonPinNumber); LPC_GPIO1->DIR |= (1 << kLedNumber); LPC_GPIO1->PIN |= (1 << kLedNumber); DEBUG_PRINT("LED3 and SW3 Initialized..."); DEBUG_PRINT("Press and release SW3 to toggle LED3 state..."); bool button_pressed = false; // Loop detects when the button has been released and changes the LED state // accordingly. while (true) { if (CheckSwitch3()) { button_pressed = true; } else if (!CheckSwitch3() && button_pressed) { LPC_GPIO1->PIN ^= (1 << kLedNumber); button_pressed = false; } else { button_pressed = false; } vTaskDelay(50); } } } // namespace int main(void) { TaskHandle_t handle = NULL; DEBUG_PRINT("Creating Tasks ..."); // See https://www.freertos.org/a00125.html for the xTaskCreate API // See L2_Utilities/rtos.hpp for the rtos:: namespace utility functions xTaskCreate( LedToggle, // Make function LedToggle a task "LedToggle", // Give this task the name "LedToggle" rtos::StackSize(256), // Size of stack allocated to task rtos::PassParameter(100), // Parameter to be passed to task rtos::Priority::kLow, // Give this task low priority &handle); // Reference to the task xTaskCreate( ButtonReader, // Make function ButtonReader a task "ButtonReader", // Give this task the name "ButtonReader" rtos::StackSize(256), // Size of stack allocated to task rtos::kNoParameter, // Pass nothing to this task rtos::Priority::kMedium, // Give this task medium priority rtos::kNoHandle); // Do not supply a task handle DEBUG_PRINT("Starting Scheduler ..."); vTaskStartScheduler(); return 0; }
30.719626
79
0.604807
2721Aperez
eb64e5a936ee318daa6eff01efa950a25765212a
4,736
hpp
C++
mars/boost/range/algorithm/swap_ranges.hpp
jonetomtom/mars
3f11714e0aee826eb12bfd52496b59675125204a
[ "BSD-2-Clause", "Apache-2.0" ]
17,104
2016-12-28T07:45:54.000Z
2022-03-31T07:02:52.000Z
mars/boost/range/algorithm/swap_ranges.hpp
jonetomtom/mars
3f11714e0aee826eb12bfd52496b59675125204a
[ "BSD-2-Clause", "Apache-2.0" ]
964
2016-12-28T08:13:33.000Z
2022-03-31T13:36:40.000Z
mars/boost/range/algorithm/swap_ranges.hpp
pengjinning/mars
227aff64a5b819555091a7d6eae6727701e9fff0
[ "Apache-2.0", "BSD-2-Clause" ]
3,568
2016-12-28T07:47:46.000Z
2022-03-31T02:13:19.000Z
// Copyright Neil Groves 2009. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_ALGORITHM_SWAP_RANGES_HPP_INCLUDED #define BOOST_RANGE_ALGORITHM_SWAP_RANGES_HPP_INCLUDED #include <boost/assert.hpp> #include <boost/concept_check.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <boost/range/concepts.hpp> #include <boost/range/iterator.hpp> #include <algorithm> namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost { namespace range_detail { template<class Iterator1, class Iterator2> void swap_ranges_impl(Iterator1 it1, Iterator1 last1, Iterator2 it2, Iterator2 last2, single_pass_traversal_tag, single_pass_traversal_tag) { ignore_unused_variable_warning(last2); for (; it1 != last1; ++it1, ++it2) { BOOST_ASSERT( it2 != last2 ); std::iter_swap(it1, it2); } } template<class Iterator1, class Iterator2> void swap_ranges_impl(Iterator1 it1, Iterator1 last1, Iterator2 it2, Iterator2 last2, random_access_traversal_tag, random_access_traversal_tag) { ignore_unused_variable_warning(last2); BOOST_ASSERT( last2 - it2 >= last1 - it1 ); std::swap_ranges(it1, last1, it2); } template<class Iterator1, class Iterator2> void swap_ranges_impl(Iterator1 first1, Iterator1 last1, Iterator2 first2, Iterator2 last2) { swap_ranges_impl(first1, last1, first2, last2, BOOST_DEDUCED_TYPENAME iterator_traversal<Iterator1>::type(), BOOST_DEDUCED_TYPENAME iterator_traversal<Iterator2>::type()); } } // namespace range_detail namespace range { /// \brief template function swap_ranges /// /// range-based version of the swap_ranges std algorithm /// /// \pre SinglePassRange1 is a model of the SinglePassRangeConcept /// \pre SinglePassRange2 is a model of the SinglePassRangeConcept template< class SinglePassRange1, class SinglePassRange2 > inline SinglePassRange2& swap_ranges(SinglePassRange1& range1, SinglePassRange2& range2) { BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange1>)); BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange2>)); mars_boost::range_detail::swap_ranges_impl( mars_boost::begin(range1), mars_boost::end(range1), mars_boost::begin(range2), mars_boost::end(range2)); return range2; } /// \overload template< class SinglePassRange1, class SinglePassRange2 > inline SinglePassRange2& swap_ranges(const SinglePassRange1& range1, SinglePassRange2& range2) { BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange1>)); BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange2>)); mars_boost::range_detail::swap_ranges_impl( mars_boost::begin(range1), mars_boost::end(range1), mars_boost::begin(range2), mars_boost::end(range2)); return range2; } /// \overload template< class SinglePassRange1, class SinglePassRange2 > inline const SinglePassRange2& swap_ranges(SinglePassRange1& range1, const SinglePassRange2& range2) { BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange1>)); BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange2>)); mars_boost::range_detail::swap_ranges_impl( mars_boost::begin(range1), mars_boost::end(range1), mars_boost::begin(range2), mars_boost::end(range2)); return range2; } /// \overload template< class SinglePassRange1, class SinglePassRange2 > inline const SinglePassRange2& swap_ranges(const SinglePassRange1& range1, const SinglePassRange2& range2) { BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange1>)); BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange2>)); mars_boost::range_detail::swap_ranges_impl( mars_boost::begin(range1), mars_boost::end(range1), mars_boost::begin(range2), mars_boost::end(range2)); return range2; } } // namespace range using range::swap_ranges; } // namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost #endif // include guard
35.609023
81
0.699535
jonetomtom
eb69835c7702dde170dbc1a2588237ffc0688b75
10,953
cc
C++
core/src/CommonClient.cc
zzboy/aliyun-kms-cpp-sdk
95ff35e92212e9bc1331fc6760606aa08c93cb94
[ "Apache-2.0" ]
null
null
null
core/src/CommonClient.cc
zzboy/aliyun-kms-cpp-sdk
95ff35e92212e9bc1331fc6760606aa08c93cb94
[ "Apache-2.0" ]
null
null
null
core/src/CommonClient.cc
zzboy/aliyun-kms-cpp-sdk
95ff35e92212e9bc1331fc6760606aa08c93cb94
[ "Apache-2.0" ]
1
2019-10-14T10:37:47.000Z
2019-10-14T10:37:47.000Z
/* * Copyright 1999-2019 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/core/AlibabaCloud.h> #include <alibabacloud/core/CommonClient.h> #include <alibabacloud/core/location/LocationClient.h> #include <alibabacloud/core/SimpleCredentialsProvider.h> #include <ctime> #include <algorithm> #include <iomanip> #include <sstream> #include <alibabacloud/core/Utils.h> namespace AlibabaCloud { namespace { const std::string SERVICE_NAME = "Common"; } CommonClient::CommonClient(const Credentials &credentials, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_( std::make_shared<SimpleCredentialsProvider>(credentials)), signer_(std::make_shared<HmacSha1Signer>()) { } CommonClient::CommonClient( const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_(credentialsProvider), signer_(std::make_shared<HmacSha1Signer>()) { } CommonClient::CommonClient(const std::string &accessKeyId, const std::string &accessKeySecret, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_(std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret)), signer_(std::make_shared<HmacSha1Signer>()) { } CommonClient::~CommonClient() { } CommonClient::JsonOutcome CommonClient::makeRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { auto outcome = AttemptRequest(endpoint, msg, method); if (outcome.isSuccess()) return JsonOutcome(std::string(outcome.result().body(), outcome.result().bodySize())); else return JsonOutcome(outcome.error()); } CommonClient::CommonResponseOutcome CommonClient::commonResponse( const CommonRequest &request) const { auto outcome = makeRequest(request.domain(), request, request.httpMethod()); if (outcome.isSuccess()) return CommonResponseOutcome(CommonResponse(outcome.result())); else return CommonResponseOutcome(Error(outcome.error())); } void CommonClient::commonResponseAsync(const CommonRequest &request, const CommonResponseAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext> &context) const { auto fn = [this, request, handler, context]() { handler(this, request, commonResponse(request), context); }; asyncExecute(new Runnable(fn)); } CommonClient::CommonResponseOutcomeCallable CommonClient::commonResponseCallable(const CommonRequest &request) const { auto task = std::make_shared<std::packaged_task<CommonResponseOutcome()>>( [this, request]() { return this->commonResponse(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint, const ServiceRequest &msg, HttpRequest::Method method) const { return buildHttpRequest(endpoint, dynamic_cast<const CommonRequest &>(msg), method); } HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { if (msg.requestPattern() == CommonRequest::RpcPattern) return buildRpcHttpRequest(endpoint, msg, method); else return buildRoaHttpRequest(endpoint, msg, method); } HttpRequest CommonClient::buildRoaHttpRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { const Credentials credentials = credentialsProvider_->getCredentials(); Url url; if (msg.scheme().empty()) { url.setScheme("https"); } else { url.setScheme(msg.scheme()); } url.setHost(endpoint); url.setPath(msg.resourcePath()); auto params = msg.headerParameters(); std::map<std::string, std::string> queryParams; for (const auto &p : params) { if (!p.second.empty()) queryParams[p.first] = p.second; } if (!queryParams.empty()) { std::stringstream queryString; for (const auto &p : queryParams) { if (p.second.empty()) queryString << "&" << p.first; else queryString << "&" << p.first << "=" << p.second; } url.setQuery(queryString.str().substr(1)); } HttpRequest request(url); request.setMethod(method); if (msg.connectTimeout() != kInvalidTimeout) { request.setConnectTimeout(msg.connectTimeout()); } else { request.setConnectTimeout(configuration().connectTimeout()); } if (msg.readTimeout() != kInvalidTimeout) { request.setReadTimeout(msg.readTimeout()); } else { request.setReadTimeout(configuration().readTimeout()); } if (msg.headerParameter("Accept").empty()) { request.setHeader("Accept", "application/json"); } else { request.setHeader("Accept", msg.headerParameter("Accept")); } std::stringstream ss; ss << msg.contentSize(); request.setHeader("Content-Length", ss.str()); if (msg.headerParameter("Content-Type").empty()) { request.setHeader("Content-Type", "application/octet-stream"); } else { request.setHeader("Content-Type", msg.headerParameter("Content-Type")); } request.setHeader("Content-MD5", ComputeContentMD5(msg.content(), msg.contentSize())); request.setBody(msg.content(), msg.contentSize()); std::time_t t = std::time(nullptr); std::stringstream date; #if defined(__GNUG__) && __GNUC__ < 5 char tmbuff[26]; strftime(tmbuff, 26, "%a, %d %b %Y %T", std::gmtime(&t)); date << tmbuff << " GMT"; #else date << std::put_time(std::gmtime(&t), "%a, %d %b %Y %T GMT"); #endif request.setHeader("Date", date.str()); request.setHeader("Host", url.host()); request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR)); request.setHeader("x-acs-region-id", configuration().regionId()); if (!credentials.sessionToken().empty()) request.setHeader("x-acs-security-token", credentials.sessionToken()); request.setHeader("x-acs-signature-method", signer_->name()); request.setHeader("x-acs-signature-nonce", GenerateUuid()); request.setHeader("x-acs-signature-version", signer_->version()); request.setHeader("x-acs-version", msg.version()); std::stringstream plaintext; plaintext << HttpMethodToString(method) << "\n" << request.header("Accept") << "\n" << request.header("Content-MD5") << "\n" << request.header("Content-Type") << "\n" << request.header("Date") << "\n" << canonicalizedHeaders(request.headers()); if (!url.hasQuery()) plaintext << url.path(); else plaintext << url.path() << "?" << url.query(); std::stringstream sign; sign << "acs " << credentials.accessKeyId() << ":" << signer_->generate(plaintext.str(), credentials.accessKeySecret()); request.setHeader("Authorization", sign.str()); return request; } HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { const Credentials credentials = credentialsProvider_->getCredentials(); Url url; if (msg.scheme().empty()) { url.setScheme("https"); } else { url.setScheme(msg.scheme()); } url.setHost(endpoint); url.setPath(msg.resourcePath()); auto params = msg.queryParameters(); std::map<std::string, std::string> queryParams; for (const auto &p : params) { if (!p.second.empty()) queryParams[p.first] = p.second; } queryParams["AccessKeyId"] = credentials.accessKeyId(); queryParams["Format"] = "JSON"; queryParams["RegionId"] = configuration().regionId(); queryParams["SecurityToken"] = credentials.sessionToken(); queryParams["SignatureMethod"] = signer_->name(); queryParams["SignatureNonce"] = GenerateUuid(); queryParams["SignatureVersion"] = signer_->version(); std::time_t t = std::time(nullptr); std::stringstream ss; #if defined(__GNUG__) && __GNUC__ < 5 char tmbuff[26]; strftime(tmbuff, 26, "%FT%TZ", std::gmtime(&t)); ss << tmbuff; #else ss << std::put_time(std::gmtime(&t), "%FT%TZ"); #endif queryParams["Timestamp"] = ss.str(); queryParams["Version"] = msg.version(); std::stringstream plaintext; plaintext << HttpMethodToString(method) << "&" << UrlEncode(url.path()) << "&" << UrlEncode(canonicalizedQuery(queryParams)); queryParams["Signature"] = signer_->generate(plaintext.str(), credentials.accessKeySecret() + "&"); std::stringstream queryString; for (const auto &p : queryParams) queryString << "&" << p.first << "=" << UrlEncode(p.second); url.setQuery(queryString.str().substr(1)); HttpRequest request(url); if (msg.connectTimeout() != kInvalidTimeout) { request.setConnectTimeout(msg.connectTimeout()); } else { request.setConnectTimeout(configuration().connectTimeout()); } if (msg.readTimeout() != kInvalidTimeout) { request.setReadTimeout(msg.readTimeout()); } else { request.setReadTimeout(configuration().readTimeout()); } request.setMethod(method); request.setHeader("Host", url.host()); request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR)); return request; } } // namespace AlibabaCloud
32.598214
154
0.626221
zzboy
eb6ab78ef53d83c85753654fdcc9cb12b388a22b
1,844
hpp
C++
source/NanairoCore/Data/ray-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
30
2015-09-06T03:14:29.000Z
2021-06-18T11:00:19.000Z
source/NanairoCore/Data/ray-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
31
2016-01-14T14:50:34.000Z
2018-06-25T13:21:48.000Z
source/NanairoCore/Data/ray-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
6
2017-04-09T13:07:47.000Z
2021-05-29T21:17:34.000Z
/*! \file ray-inl.hpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef NANAIRO_RAY_INL_HPP #define NANAIRO_RAY_INL_HPP #include "ray.hpp" // Standard C++ library #include <array> #include <limits> // Zisc #include "zisc/math.hpp" // Nanairo #include "NanairoCore/nanairo_core_config.hpp" #include "NanairoCore/Geometry/point.hpp" #include "NanairoCore/Geometry/vector.hpp" namespace nanairo { /*! \details No detailed. */ inline Ray::Ray() noexcept : is_alive_{kFalse} { initialize(); } /*! \details No detailed. */ inline Ray::Ray(const Point3& origin, const Vector3& direction) noexcept : origin_{origin}, direction_{direction}, is_alive_{kTrue} { initialize(); } /*! \details No detailed. */ inline const Vector3& Ray::direction() const noexcept { return direction_; } /*! \details No detailed. */ inline bool Ray::isAlive() const noexcept { return is_alive_ == kTrue; } /*! */ inline Ray Ray::makeRay(const Point3& origin, const Vector3& direction) noexcept { Ray ray{origin, direction}; return ray; } /*! \details No detailed. */ inline const Point3& Ray::origin() const noexcept { return origin_; } /*! \details No detailed. */ inline void Ray::setDirection(const Vector3& direction) noexcept { direction_ = direction; } /*! \details No detailed. */ inline void Ray::setOrigin(const Point3& origin) noexcept { origin_ = origin; } /*! \details No detailed. */ inline void Ray::setAlive(const bool is_alive) noexcept { is_alive_ = is_alive ? kTrue : kFalse; } /*! */ inline void Ray::initialize() noexcept { // Avoid warnings static_cast<void>(padding_); } } // namespace nanairo #endif // NANAIRO_RAY_INL_HPP
14.076336
73
0.68167
byzin
eb6b45a66e05e793d0a5237a7a579b1d176ce255
181,258
cpp
C++
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/core/CSSGrammar.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/core/CSSGrammar.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/core/CSSGrammar.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
/* A Bison parser, made by GNU Bison 2.5. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2011 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "2.5" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 1 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Using locations. */ #define YYLSP_NEEDED 0 /* Substitute the variable and function names. */ #define yyparse cssyyparse #define yylex cssyylex #define yyerror cssyyerror #define yylval cssyylval #define yychar cssyychar #define yydebug cssyydebug #define yynerrs cssyynerrs /* Copy the first part of user declarations. */ /* Line 268 of yacc.c */ #line 1 "css/CSSGrammar.y" /* * Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com) * Copyright (C) 2008 Eric Seidel <eric@webkit.org> * Copyright (C) 2012 Intel Corporation. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "config.h" #include "CSSPropertyNames.h" #include "HTMLNames.h" #include "core/css/CSSKeyframeRule.h" #include "core/css/CSSKeyframesRule.h" #include "core/css/parser/BisonCSSParser.h" #include "core/css/CSSParserMode.h" #include "core/css/CSSPrimitiveValue.h" #include "core/css/CSSSelector.h" #include "core/css/CSSSelectorList.h" #include "core/css/MediaList.h" #include "core/css/MediaQueryExp.h" #include "core/css/StyleRule.h" #include "core/css/StyleSheetContents.h" #include "core/dom/Document.h" #include "wtf/FastMalloc.h" #include <stdlib.h> #include <string.h> using namespace WebCore; using namespace HTMLNames; #define YYMALLOC fastMalloc #define YYFREE fastFree #define YYENABLE_NLS 0 #define YYLTYPE_IS_TRIVIAL 1 #define YYMAXDEPTH 10000 #define YYDEBUG 0 #if YYDEBUG > 0 #define YYPRINT(File,Type,Value) if (isCSSTokenAString(Type)) YYFPRINTF(File, "%s", String((Value).string).utf8().data()) #endif /* Line 268 of yacc.c */ #line 142 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp" /* Enabling traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* Enabling the token table. */ #ifndef YYTOKEN_TABLE # define YYTOKEN_TABLE 0 #endif /* Tokens. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ enum yytokentype { TOKEN_EOF = 0, LOWEST_PREC = 258, UNIMPORTANT_TOK = 259, WHITESPACE = 260, SGML_CD = 261, INCLUDES = 262, DASHMATCH = 263, BEGINSWITH = 264, ENDSWITH = 265, CONTAINS = 266, STRING = 267, IDENT = 268, NTH = 269, HEX = 270, IDSEL = 271, IMPORT_SYM = 272, PAGE_SYM = 273, MEDIA_SYM = 274, SUPPORTS_SYM = 275, FONT_FACE_SYM = 276, CHARSET_SYM = 277, NAMESPACE_SYM = 278, VIEWPORT_RULE_SYM = 279, INTERNAL_DECLS_SYM = 280, INTERNAL_MEDIALIST_SYM = 281, INTERNAL_RULE_SYM = 282, INTERNAL_SELECTOR_SYM = 283, INTERNAL_VALUE_SYM = 284, INTERNAL_KEYFRAME_RULE_SYM = 285, INTERNAL_KEYFRAME_KEY_LIST_SYM = 286, INTERNAL_SUPPORTS_CONDITION_SYM = 287, KEYFRAMES_SYM = 288, WEBKIT_KEYFRAMES_SYM = 289, TOPLEFTCORNER_SYM = 290, TOPLEFT_SYM = 291, TOPCENTER_SYM = 292, TOPRIGHT_SYM = 293, TOPRIGHTCORNER_SYM = 294, BOTTOMLEFTCORNER_SYM = 295, BOTTOMLEFT_SYM = 296, BOTTOMCENTER_SYM = 297, BOTTOMRIGHT_SYM = 298, BOTTOMRIGHTCORNER_SYM = 299, LEFTTOP_SYM = 300, LEFTMIDDLE_SYM = 301, LEFTBOTTOM_SYM = 302, RIGHTTOP_SYM = 303, RIGHTMIDDLE_SYM = 304, RIGHTBOTTOM_SYM = 305, ATKEYWORD = 306, IMPORTANT_SYM = 307, MEDIA_ONLY = 308, MEDIA_NOT = 309, MEDIA_AND = 310, MEDIA_OR = 311, SUPPORTS_NOT = 312, SUPPORTS_AND = 313, SUPPORTS_OR = 314, REMS = 315, CHS = 316, QEMS = 317, EMS = 318, EXS = 319, PXS = 320, CMS = 321, MMS = 322, INS = 323, PTS = 324, PCS = 325, DEGS = 326, RADS = 327, GRADS = 328, TURNS = 329, MSECS = 330, SECS = 331, HERTZ = 332, KHERTZ = 333, DIMEN = 334, INVALIDDIMEN = 335, PERCENTAGE = 336, FLOATTOKEN = 337, INTEGER = 338, VW = 339, VH = 340, VMIN = 341, VMAX = 342, DPPX = 343, DPI = 344, DPCM = 345, FR = 346, URI = 347, FUNCTION = 348, ANYFUNCTION = 349, CUEFUNCTION = 350, NOTFUNCTION = 351, DISTRIBUTEDFUNCTION = 352, CALCFUNCTION = 353, HOSTFUNCTION = 354, HOSTCONTEXTFUNCTION = 355, UNICODERANGE = 356 }; #endif #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE { /* Line 293 of yacc.c */ #line 68 "css/CSSGrammar.y" bool boolean; char character; int integer; double number; CSSParserString string; StyleRuleBase* rule; // The content of the three below HeapVectors are guaranteed to be kept alive by // the corresponding m_parsedRules, m_floatingMediaQueryExpList, and m_parsedKeyFrames // lists in BisonCSSParser.h. WillBeHeapVector<RefPtrWillBeMember<StyleRuleBase> >* ruleList; WillBeHeapVector<OwnPtrWillBeMember<MediaQueryExp> >* mediaQueryExpList; WillBeHeapVector<RefPtrWillBeMember<StyleKeyframe> >* keyframeRuleList; CSSParserSelector* selector; Vector<OwnPtr<CSSParserSelector> >* selectorList; CSSSelector::MarginBoxType marginBox; CSSSelector::Relation relation; MediaQuerySet* mediaList; MediaQuery* mediaQuery; MediaQuery::Restrictor mediaQueryRestrictor; MediaQueryExp* mediaQueryExp; CSSParserValue value; CSSParserValueList* valueList; StyleKeyframe* keyframe; float val; CSSPropertyID id; CSSParserLocation location; /* Line 293 of yacc.c */ #line 312 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp" } YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define yystype YYSTYPE /* obsolescent; will be withdrawn */ # define YYSTYPE_IS_DECLARED 1 #endif /* Copy the second part of user declarations. */ /* Line 343 of yacc.c */ #line 98 "css/CSSGrammar.y" static inline int cssyyerror(void*, const char*) { return 1; } #if YYDEBUG > 0 static inline bool isCSSTokenAString(int yytype) { switch (yytype) { case IDENT: case STRING: case NTH: case HEX: case IDSEL: case DIMEN: case INVALIDDIMEN: case URI: case FUNCTION: case ANYFUNCTION: case HOSTFUNCTION: case HOSTCONTEXTFUNCTION: case NOTFUNCTION: case CALCFUNCTION: case UNICODERANGE: return true; default: return false; } } #endif inline static CSSParserValue makeOperatorValue(int value) { CSSParserValue v; v.id = CSSValueInvalid; v.isInt = false; v.unit = CSSParserValue::Operator; v.iValue = value; return v; } inline static CSSParserValue makeIdentValue(CSSParserString string) { CSSParserValue v; v.id = cssValueKeywordID(string); v.isInt = false; v.unit = CSSPrimitiveValue::CSS_IDENT; v.string = string; return v; } /* Line 343 of yacc.c */ #line 380 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp" #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #elif (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) typedef signed char yytype_int8; #else typedef short int yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(msgid) dgettext ("bison-runtime", msgid) # endif # endif # ifndef YY_ # define YY_(msgid) msgid # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(e) ((void) (e)) #else # define YYUSE(e) /* empty */ #endif /* Identity function, used to suppress warnings about constant conditions. */ #ifndef lint # define YYID(n) (n) #else #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static int YYID (int yyi) #else static int YYID (yyi) int yyi; #endif { return yyi; } #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's `empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0)) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (YYID (0)) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from FROM to TO. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(To, From, Count) \ __builtin_memcpy (To, From, (Count) * sizeof (*(From))) # else # define YYCOPY(To, From, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (To)[yyi] = (From)[yyi]; \ } \ while (YYID (0)) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 35 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 2129 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 122 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 139 /* YYNRULES -- Number of rules. */ #define YYNRULES 372 /* YYNRULES -- Number of states. */ #define YYNSTATES 708 /* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 356 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 120, 2, 121, 2, 2, 111, 108, 20, 114, 112, 118, 18, 117, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 17, 110, 2, 119, 116, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 19, 2, 109, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 113, 21, 107, 115, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106 }; #if YYDEBUG /* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in YYRHS. */ static const yytype_uint16 yyprhs[] = { 0, 0, 3, 7, 9, 11, 13, 15, 17, 19, 21, 23, 29, 35, 40, 45, 50, 56, 61, 66, 68, 71, 72, 74, 75, 78, 81, 83, 85, 87, 89, 91, 93, 95, 97, 98, 104, 107, 108, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 131, 134, 137, 139, 142, 143, 147, 150, 152, 154, 156, 158, 160, 162, 164, 166, 169, 172, 173, 177, 184, 191, 198, 199, 202, 204, 206, 207, 211, 218, 223, 225, 231, 233, 239, 240, 243, 246, 249, 253, 255, 260, 264, 265, 267, 269, 272, 274, 279, 285, 286, 287, 289, 293, 302, 304, 315, 316, 317, 319, 321, 323, 325, 329, 334, 339, 344, 349, 355, 357, 364, 375, 386, 387, 391, 395, 405, 407, 409, 411, 414, 415, 420, 426, 432, 435, 441, 444, 446, 449, 450, 461, 464, 468, 471, 472, 474, 479, 480, 488, 490, 492, 494, 496, 498, 500, 502, 504, 506, 508, 510, 512, 514, 516, 518, 520, 521, 530, 531, 540, 543, 546, 549, 554, 556, 557, 559, 561, 563, 564, 565, 566, 576, 577, 579, 586, 588, 591, 595, 599, 601, 604, 607, 609, 612, 614, 617, 621, 624, 626, 632, 634, 636, 638, 641, 643, 645, 647, 649, 651, 654, 657, 662, 671, 677, 687, 691, 693, 695, 697, 699, 701, 703, 705, 707, 710, 714, 719, 727, 733, 740, 745, 752, 760, 767, 772, 779, 784, 791, 796, 803, 808, 812, 813, 815, 818, 820, 824, 829, 836, 845, 852, 857, 861, 865, 868, 869, 872, 876, 880, 885, 890, 892, 896, 899, 903, 906, 909, 912, 916, 919, 922, 925, 929, 932, 935, 938, 941, 944, 947, 950, 953, 955, 957, 959, 961, 963, 965, 967, 969, 971, 973, 975, 977, 979, 981, 983, 985, 987, 989, 991, 993, 995, 997, 999, 1001, 1003, 1005, 1007, 1009, 1011, 1013, 1018, 1022, 1027, 1029, 1032, 1036, 1040, 1044, 1048, 1049, 1051, 1057, 1062, 1064, 1068, 1072, 1074, 1080, 1085, 1087, 1089, 1093, 1097, 1100, 1103, 1106, 1110, 1114, 1120, 1124, 1127, 1130, 1134, 1140, 1144, 1148, 1152, 1157, 1160, 1163, 1164, 1168, 1172, 1176, 1178, 1180, 1182, 1184, 1186, 1188, 1190, 1192, 1193, 1194, 1195, 1198, 1201, 1204, 1207, 1208, 1211, 1214 }; /* YYRHS -- A `-1'-separated list of the rules' RHS. */ static const yytype_int16 yyrhs[] = { 123, 0, -1, 139, 134, 140, -1, 127, -1, 124, -1, 130, -1, 128, -1, 129, -1, 125, -1, 126, -1, 131, -1, 32, 133, 141, 133, 0, -1, 35, 133, 186, 133, 0, -1, 36, 133, 187, 0, -1, 30, 204, 226, 0, -1, 34, 133, 233, 0, -1, 31, 133, 258, 162, 0, -1, 33, 133, 210, 0, -1, 37, 133, 174, 0, -1, 5, -1, 132, 5, -1, -1, 132, -1, -1, 134, 6, -1, 134, 5, -1, 107, -1, 0, -1, 108, -1, 0, -1, 109, -1, 0, -1, 110, -1, 0, -1, -1, 27, 133, 12, 133, 138, -1, 27, 246, -1, -1, 140, 143, 134, -1, 208, -1, 169, -1, 191, -1, 198, -1, 182, -1, 152, -1, 151, -1, 171, -1, 200, -1, -1, 142, 141, -1, 142, 250, -1, 145, -1, 145, 146, -1, -1, 145, 148, 134, -1, 142, 251, -1, 208, -1, 191, -1, 198, -1, 169, -1, 182, -1, 171, -1, 200, -1, 152, -1, 142, 147, -1, 142, 250, -1, -1, 149, 22, 133, -1, 150, 154, 133, 258, 162, 138, -1, 150, 154, 133, 258, 162, 253, -1, 28, 133, 153, 154, 133, 138, -1, -1, 13, 133, -1, 12, -1, 97, -1, -1, 17, 133, 233, -1, 111, 133, 13, 133, 155, 136, -1, 111, 1, 259, 136, -1, 156, -1, 157, 133, 60, 133, 156, -1, 133, -1, 133, 60, 133, 157, 133, -1, -1, 58, 133, -1, 59, 133, -1, 157, 133, -1, 159, 170, 158, -1, 160, -1, 160, 1, 257, 260, -1, 1, 257, 260, -1, -1, 163, -1, 161, -1, 164, 161, -1, 164, -1, 161, 112, 133, 258, -1, 164, 161, 112, 133, 258, -1, -1, -1, 133, -1, 166, 24, 133, -1, 168, 162, 206, 113, 165, 133, 144, 135, -1, 13, -1, 172, 25, 133, 174, 173, 113, 165, 133, 144, 135, -1, -1, -1, 178, -1, 175, -1, 176, -1, 177, -1, 62, 133, 178, -1, 178, 63, 133, 178, -1, 176, 63, 133, 178, -1, 178, 64, 133, 178, -1, 177, 64, 133, 178, -1, 111, 133, 174, 136, 133, -1, 179, -1, 111, 1, 257, 259, 136, 133, -1, 111, 133, 13, 133, 17, 133, 233, 230, 136, 133, -1, 111, 133, 13, 133, 17, 133, 1, 259, 136, 133, -1, -1, 180, 38, 133, -1, 180, 39, 133, -1, 181, 183, 167, 113, 165, 133, 258, 184, 135, -1, 13, -1, 12, -1, 185, -1, 185, 189, -1, -1, 185, 186, 133, 258, -1, 185, 189, 253, 133, 258, -1, 187, 113, 133, 226, 135, -1, 188, 133, -1, 187, 112, 133, 188, 133, -1, 202, 86, -1, 13, -1, 1, 260, -1, -1, 190, 23, 133, 192, 206, 113, 165, 204, 193, 135, -1, 13, 133, -1, 13, 223, 133, -1, 223, 133, -1, -1, 226, -1, 193, 194, 133, 226, -1, -1, 196, 195, 133, 113, 133, 226, 135, -1, 40, -1, 41, -1, 42, -1, 43, -1, 44, -1, 45, -1, 46, -1, 47, -1, 48, -1, 49, -1, 50, -1, 51, -1, 52, -1, 53, -1, 54, -1, 55, -1, -1, 197, 26, 167, 113, 165, 204, 226, 135, -1, -1, 199, 29, 167, 113, 165, 204, 226, 135, -1, 114, 133, -1, 115, 133, -1, 116, 133, -1, 117, 13, 117, 133, -1, 203, -1, -1, 118, -1, 114, -1, 133, -1, -1, -1, -1, 205, 210, 207, 206, 113, 165, 204, 226, 135, -1, -1, 211, -1, 210, 207, 112, 133, 209, 211, -1, 213, -1, 211, 5, -1, 211, 5, 213, -1, 211, 201, 213, -1, 21, -1, 20, 21, -1, 13, 21, -1, 215, -1, 215, 216, -1, 216, -1, 212, 215, -1, 212, 215, 216, -1, 212, 216, -1, 213, -1, 214, 133, 112, 133, 213, -1, 13, -1, 20, -1, 217, -1, 216, 217, -1, 16, -1, 15, -1, 218, -1, 220, -1, 224, -1, 18, 13, -1, 13, 133, -1, 19, 133, 219, 137, -1, 19, 133, 219, 221, 133, 222, 133, 137, -1, 19, 133, 212, 219, 137, -1, 19, 133, 212, 219, 221, 133, 222, 133, 137, -1, 19, 225, 137, -1, 119, -1, 7, -1, 8, -1, 9, -1, 10, -1, 11, -1, 13, -1, 12, -1, 17, 13, -1, 17, 257, 13, -1, 17, 17, 257, 13, -1, 17, 17, 100, 133, 214, 133, 136, -1, 17, 17, 100, 225, 136, -1, 17, 99, 133, 214, 133, 136, -1, 17, 99, 225, 136, -1, 17, 98, 133, 14, 133, 136, -1, 17, 98, 133, 202, 88, 133, 136, -1, 17, 98, 133, 13, 133, 136, -1, 17, 98, 225, 136, -1, 17, 101, 133, 213, 133, 136, -1, 17, 101, 225, 136, -1, 17, 104, 133, 214, 133, 136, -1, 17, 104, 225, 136, -1, 17, 105, 133, 214, 133, 136, -1, 17, 105, 225, 136, -1, 1, 257, 259, -1, -1, 228, -1, 227, 228, -1, 227, -1, 228, 110, 133, -1, 227, 228, 110, 133, -1, 229, 17, 133, 257, 233, 230, -1, 229, 17, 133, 257, 233, 230, 1, 259, -1, 229, 17, 133, 257, 1, 259, -1, 229, 1, 257, 259, -1, 1, 257, 259, -1, 257, 13, 133, -1, 57, 133, -1, -1, 13, 133, -1, 231, 13, 133, -1, 111, 133, 136, -1, 111, 133, 231, 136, -1, 111, 133, 234, 136, -1, 236, -1, 233, 235, 236, -1, 233, 236, -1, 1, 257, 259, -1, 117, 133, -1, 112, 133, -1, 237, 133, -1, 203, 237, 133, -1, 12, 133, -1, 13, 133, -1, 84, 133, -1, 203, 84, 133, -1, 97, 133, -1, 106, 133, -1, 15, 133, -1, 120, 133, -1, 238, 133, -1, 244, 133, -1, 121, 133, -1, 232, 133, -1, 88, -1, 87, -1, 86, -1, 70, -1, 71, -1, 72, -1, 73, -1, 74, -1, 75, -1, 76, -1, 77, -1, 78, -1, 79, -1, 80, -1, 81, -1, 82, -1, 83, -1, 68, -1, 67, -1, 69, -1, 65, -1, 66, -1, 89, -1, 90, -1, 91, -1, 92, -1, 93, -1, 94, -1, 95, -1, 96, -1, 98, 133, 233, 136, -1, 98, 133, 136, -1, 98, 133, 234, 136, -1, 237, -1, 203, 237, -1, 132, 114, 132, -1, 132, 118, 132, -1, 241, 20, 133, -1, 241, 117, 133, -1, -1, 5, -1, 111, 133, 243, 241, 136, -1, 111, 133, 234, 136, -1, 239, -1, 243, 240, 239, -1, 243, 240, 242, -1, 242, -1, 103, 133, 243, 241, 136, -1, 103, 133, 234, 136, -1, 56, -1, 196, -1, 247, 252, 248, -1, 1, 257, 260, -1, 252, 138, -1, 252, 253, -1, 181, 247, -1, 190, 23, 247, -1, 197, 26, 247, -1, 172, 25, 1, 257, 260, -1, 199, 29, 247, -1, 150, 247, -1, 28, 247, -1, 257, 245, 247, -1, 1, 257, 260, 252, 253, -1, 249, 252, 110, -1, 249, 252, 253, -1, 168, 162, 110, -1, 1, 257, 260, 252, -1, 249, 252, -1, 168, 162, -1, -1, 113, 259, 135, -1, 19, 259, 137, -1, 256, 259, 136, -1, 111, -1, 98, -1, 103, -1, 99, -1, 101, -1, 100, -1, 102, -1, 104, -1, -1, -1, -1, 259, 1, -1, 259, 253, -1, 259, 254, -1, 259, 255, -1, -1, 260, 1, -1, 260, 254, -1, 260, 255, -1 }; /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 374, 374, 375, 376, 377, 378, 379, 380, 381, 382, 386, 392, 398, 404, 410, 420, 426, 433, 439, 440, 444, 445, 448, 450, 451, 455, 456, 460, 461, 465, 466, 470, 471, 474, 476, 481, 484, 486, 493, 494, 495, 496, 497, 498, 499, 500, 501, 505, 511, 516, 523, 524, 528, 529, 535, 541, 542, 543, 544, 545, 546, 547, 548, 552, 556, 563, 569, 576, 579, 585, 592, 593, 597, 598, 602, 605, 611, 617, 623, 627, 634, 637, 643, 646, 649, 655, 658, 665, 666, 670, 677, 680, 684, 688, 692, 699, 703, 710, 716, 722, 728, 731, 737, 741, 747, 754, 761, 762, 763, 764, 768, 774, 777, 783, 786, 792, 795, 796, 803, 817, 824, 830, 833, 839, 845, 846, 850, 851, 856, 860, 864, 871, 877, 881, 888, 891, 903, 909, 915, 929, 933, 938, 942, 949, 950, 954, 954, 962, 965, 968, 971, 974, 977, 980, 983, 986, 989, 992, 995, 998, 1001, 1004, 1007, 1013, 1019, 1026, 1033, 1041, 1042, 1043, 1044, 1053, 1054, 1058, 1059, 1063, 1069, 1076, 1082, 1088, 1094, 1099, 1104, 1111, 1112, 1113, 1124, 1137, 1138, 1139, 1143, 1146, 1151, 1156, 1161, 1166, 1174, 1178, 1185, 1190, 1197, 1198, 1204, 1211, 1222, 1223, 1224, 1228, 1238, 1246, 1251, 1257, 1262, 1268, 1274, 1277, 1280, 1283, 1286, 1289, 1295, 1296, 1300, 1313, 1326, 1341, 1350, 1358, 1368, 1372, 1382, 1392, 1409, 1413, 1428, 1431, 1441, 1445, 1455, 1461, 1464, 1465, 1466, 1469, 1473, 1477, 1484, 1501, 1508, 1514, 1520, 1527, 1536, 1537, 1541, 1545, 1552, 1555, 1558, 1564, 1568, 1573, 1580, 1586, 1589, 1595, 1596, 1597, 1598, 1600, 1601, 1602, 1603, 1604, 1605, 1607, 1608, 1609, 1612, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1653, 1656, 1659, 1665, 1666, 1670, 1673, 1676, 1679, 1684, 1686, 1690, 1695, 1701, 1705, 1710, 1715, 1719, 1722, 1729, 1730, 1734, 1738, 1744, 1745, 1749, 1750, 1751, 1752, 1756, 1759, 1760, 1761, 1768, 1771, 1772, 1773, 1777, 1780, 1781, 1785, 1791, 1797, 1801, 1804, 1804, 1804, 1804, 1804, 1804, 1804, 1804, 1807, 1812, 1817, 1819, 1820, 1821, 1822, 1825, 1827, 1828, 1829 }; #endif #if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "TOKEN_EOF", "error", "$undefined", "LOWEST_PREC", "UNIMPORTANT_TOK", "WHITESPACE", "SGML_CD", "INCLUDES", "DASHMATCH", "BEGINSWITH", "ENDSWITH", "CONTAINS", "STRING", "IDENT", "NTH", "HEX", "IDSEL", "':'", "'.'", "'['", "'*'", "'|'", "IMPORT_SYM", "PAGE_SYM", "MEDIA_SYM", "SUPPORTS_SYM", "FONT_FACE_SYM", "CHARSET_SYM", "NAMESPACE_SYM", "VIEWPORT_RULE_SYM", "INTERNAL_DECLS_SYM", "INTERNAL_MEDIALIST_SYM", "INTERNAL_RULE_SYM", "INTERNAL_SELECTOR_SYM", "INTERNAL_VALUE_SYM", "INTERNAL_KEYFRAME_RULE_SYM", "INTERNAL_KEYFRAME_KEY_LIST_SYM", "INTERNAL_SUPPORTS_CONDITION_SYM", "KEYFRAMES_SYM", "WEBKIT_KEYFRAMES_SYM", "TOPLEFTCORNER_SYM", "TOPLEFT_SYM", "TOPCENTER_SYM", "TOPRIGHT_SYM", "TOPRIGHTCORNER_SYM", "BOTTOMLEFTCORNER_SYM", "BOTTOMLEFT_SYM", "BOTTOMCENTER_SYM", "BOTTOMRIGHT_SYM", "BOTTOMRIGHTCORNER_SYM", "LEFTTOP_SYM", "LEFTMIDDLE_SYM", "LEFTBOTTOM_SYM", "RIGHTTOP_SYM", "RIGHTMIDDLE_SYM", "RIGHTBOTTOM_SYM", "ATKEYWORD", "IMPORTANT_SYM", "MEDIA_ONLY", "MEDIA_NOT", "MEDIA_AND", "MEDIA_OR", "SUPPORTS_NOT", "SUPPORTS_AND", "SUPPORTS_OR", "REMS", "CHS", "QEMS", "EMS", "EXS", "PXS", "CMS", "MMS", "INS", "PTS", "PCS", "DEGS", "RADS", "GRADS", "TURNS", "MSECS", "SECS", "HERTZ", "KHERTZ", "DIMEN", "INVALIDDIMEN", "PERCENTAGE", "FLOATTOKEN", "INTEGER", "VW", "VH", "VMIN", "VMAX", "DPPX", "DPI", "DPCM", "FR", "URI", "FUNCTION", "ANYFUNCTION", "CUEFUNCTION", "NOTFUNCTION", "DISTRIBUTEDFUNCTION", "CALCFUNCTION", "HOSTFUNCTION", "HOSTCONTEXTFUNCTION", "UNICODERANGE", "'}'", "')'", "']'", "';'", "'('", "','", "'{'", "'+'", "'~'", "'>'", "'/'", "'-'", "'='", "'#'", "'%'", "$accept", "stylesheet", "internal_rule", "internal_keyframe_rule", "internal_keyframe_key_list", "internal_decls", "internal_value", "internal_medialist", "internal_selector", "internal_supports_condition", "space", "maybe_space", "maybe_sgml", "closing_brace", "closing_parenthesis", "closing_square_bracket", "semi_or_eof", "maybe_charset", "rule_list", "valid_rule", "before_rule", "rule", "block_rule_body", "block_rule_list", "block_rule_recovery", "block_valid_rule", "block_rule", "before_import_rule", "import_rule_start", "import", "namespace", "maybe_ns_prefix", "string_or_uri", "maybe_media_value", "media_query_exp", "media_query_exp_list", "maybe_and_media_query_exp_list", "maybe_media_restrictor", "valid_media_query", "media_query", "maybe_media_list", "media_list", "mq_list", "at_rule_body_start", "before_media_rule", "at_rule_header_end_maybe_space", "media_rule_start", "media", "medium", "supports", "before_supports_rule", "at_supports_rule_header_end", "supports_condition", "supports_negation", "supports_conjunction", "supports_disjunction", "supports_condition_in_parens", "supports_declaration_condition", "before_keyframes_rule", "keyframes_rule_start", "keyframes", "keyframe_name", "keyframes_rule", "keyframe_rule_list", "keyframe_rule", "key_list", "key", "keyframes_error_recovery", "before_page_rule", "page", "page_selector", "declarations_and_margins", "margin_box", "$@1", "margin_sym", "before_font_face_rule", "font_face", "before_viewport_rule", "viewport", "combinator", "maybe_unary_operator", "unary_operator", "maybe_space_before_declaration", "before_selector_list", "at_rule_header_end", "at_selector_end", "ruleset", "before_selector_group_item", "selector_list", "selector", "namespace_selector", "simple_selector", "simple_selector_list", "element_name", "specifier_list", "specifier", "class", "attr_name", "attrib", "match", "ident_or_string", "pseudo_page", "pseudo", "selector_recovery", "declaration_list", "decl_list", "declaration", "property", "prio", "ident_list", "track_names_list", "expr", "expr_recovery", "operator", "term", "unary_term", "function", "calc_func_term", "calc_func_operator", "calc_maybe_space", "calc_func_paren_expr", "calc_func_expr", "calc_function", "invalid_at", "at_rule_recovery", "at_rule_header_recovery", "at_rule_end", "regular_invalid_at_rule_header", "invalid_rule", "invalid_rule_header", "at_invalid_rule_header_end", "invalid_block", "invalid_square_brackets_block", "invalid_parentheses_block", "opening_parenthesis", "error_location", "location_label", "error_recovery", "rule_error_recovery", 0 }; #endif # ifdef YYPRINT /* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to token YYLEX-NUM. */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 58, 46, 91, 42, 124, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 125, 41, 93, 59, 40, 44, 123, 43, 126, 62, 47, 45, 61, 35, 37 }; # endif /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint16 yyr1[] = { 0, 122, 123, 123, 123, 123, 123, 123, 123, 123, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 132, 133, 133, 134, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, 139, 139, 139, 140, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141, 142, 143, 143, 144, 144, 145, 145, 146, 147, 147, 147, 147, 147, 147, 147, 147, 148, 148, 149, 150, 151, 151, 152, 153, 153, 154, 154, 155, 155, 156, 156, 157, 157, 158, 158, 159, 159, 159, 160, 160, 161, 161, 161, 162, 162, 163, 163, 163, 164, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 174, 174, 174, 175, 176, 176, 177, 177, 178, 178, 178, 179, 179, 180, 181, 181, 182, 183, 183, 184, 184, 185, 185, 185, 186, 187, 187, 188, 188, 189, 190, 191, 192, 192, 192, 192, 193, 193, 195, 194, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 197, 198, 199, 200, 201, 201, 201, 201, 202, 202, 203, 203, 204, 205, 206, 207, 208, 209, 210, 210, 211, 211, 211, 211, 212, 212, 212, 213, 213, 213, 213, 213, 213, 214, 214, 215, 215, 216, 216, 217, 217, 217, 217, 217, 218, 219, 220, 220, 220, 220, 220, 221, 221, 221, 221, 221, 221, 222, 222, 223, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 225, 226, 226, 226, 226, 227, 227, 228, 228, 228, 228, 228, 229, 230, 230, 231, 231, 232, 232, 232, 233, 233, 233, 234, 235, 235, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 237, 238, 238, 238, 239, 239, 240, 240, 240, 240, 241, 241, 242, 242, 243, 243, 243, 243, 244, 244, 245, 245, 246, 247, 248, 248, 249, 249, 249, 249, 249, 249, 249, 249, 250, 250, 250, 250, 251, 251, 251, 252, 253, 254, 255, 256, 256, 256, 256, 256, 256, 256, 256, 257, 258, 259, 259, 259, 259, 259, 260, 260, 260, 260 }; /* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 3, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 4, 4, 4, 5, 4, 4, 1, 2, 0, 1, 0, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 5, 2, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, 2, 1, 2, 0, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 0, 3, 6, 6, 6, 0, 2, 1, 1, 0, 3, 6, 4, 1, 5, 1, 5, 0, 2, 2, 2, 3, 1, 4, 3, 0, 1, 1, 2, 1, 4, 5, 0, 0, 1, 3, 8, 1, 10, 0, 0, 1, 1, 1, 1, 3, 4, 4, 4, 4, 5, 1, 6, 10, 10, 0, 3, 3, 9, 1, 1, 1, 2, 0, 4, 5, 5, 2, 5, 2, 1, 2, 0, 10, 2, 3, 2, 0, 1, 4, 0, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 8, 0, 8, 2, 2, 2, 4, 1, 0, 1, 1, 1, 0, 0, 0, 9, 0, 1, 6, 1, 2, 3, 3, 1, 2, 2, 1, 2, 1, 2, 3, 2, 1, 5, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 2, 4, 8, 5, 9, 3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 7, 5, 6, 4, 6, 7, 6, 4, 6, 4, 6, 4, 6, 4, 3, 0, 1, 2, 1, 3, 4, 6, 8, 6, 4, 3, 3, 2, 0, 2, 3, 3, 4, 4, 1, 3, 2, 3, 2, 2, 2, 3, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 3, 4, 1, 2, 3, 3, 3, 3, 0, 1, 5, 4, 1, 3, 3, 1, 5, 4, 1, 1, 3, 3, 2, 2, 2, 3, 3, 5, 3, 2, 2, 3, 5, 3, 3, 3, 4, 2, 2, 0, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2 }; /* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM. Performed when YYTABLE doesn't specify something else to do. Zero means the default is an error. */ static const yytype_uint16 yydefact[] = { 34, 0, 21, 21, 21, 21, 21, 21, 21, 21, 0, 4, 8, 9, 3, 6, 7, 5, 10, 23, 362, 19, 22, 0, 36, 350, 176, 0, 363, 177, 0, 0, 173, 173, 0, 1, 37, 369, 20, 21, 350, 362, 0, 0, 242, 0, 0, 0, 21, 21, 0, 0, 45, 44, 0, 0, 40, 46, 0, 0, 0, 43, 0, 41, 0, 42, 0, 47, 0, 39, 199, 204, 203, 362, 0, 0, 200, 188, 179, 182, 0, 184, 191, 193, 201, 205, 206, 207, 21, 21, 21, 300, 301, 298, 297, 299, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 21, 282, 281, 280, 302, 303, 304, 305, 306, 307, 308, 309, 21, 21, 21, 21, 21, 175, 174, 21, 21, 0, 21, 0, 260, 21, 21, 21, 136, 21, 0, 21, 0, 172, 0, 21, 0, 0, 108, 109, 110, 107, 117, 25, 24, 48, 0, 0, 331, 0, 364, 14, 243, 21, 362, 21, 21, 362, 21, 21, 0, 79, 21, 0, 0, 93, 0, 92, 0, 71, 0, 21, 73, 74, 21, 21, 178, 21, 21, 21, 126, 125, 21, 21, 21, 21, 179, 190, 362, 0, 0, 0, 0, 0, 0, 208, 362, 0, 0, 189, 17, 0, 185, 21, 21, 21, 0, 0, 199, 200, 194, 196, 192, 202, 268, 269, 274, 270, 272, 0, 0, 273, 0, 275, 278, 21, 21, 279, 15, 21, 21, 0, 262, 266, 276, 277, 0, 21, 21, 133, 135, 13, 0, 362, 0, 18, 21, 21, 21, 21, 0, 23, 370, 364, 355, 357, 359, 358, 360, 356, 361, 354, 371, 372, 364, 33, 32, 35, 364, 333, 334, 0, 21, 245, 364, 362, 252, 369, 84, 85, 364, 0, 86, 103, 21, 362, 21, 16, 94, 21, 0, 11, 67, 363, 101, 0, 0, 122, 123, 100, 0, 143, 0, 0, 178, 0, 0, 173, 0, 0, 0, 0, 0, 0, 0, 0, 0, 224, 364, 21, 0, 0, 0, 31, 30, 214, 21, 186, 168, 169, 170, 0, 187, 195, 29, 362, 28, 311, 0, 0, 21, 0, 0, 313, 323, 326, 319, 21, 257, 0, 0, 271, 267, 265, 264, 261, 12, 173, 0, 111, 364, 21, 0, 0, 0, 0, 0, 362, 0, 49, 0, 0, 0, 0, 0, 0, 0, 350, 50, 0, 38, 0, 0, 0, 365, 366, 367, 368, 246, 0, 0, 0, 0, 21, 21, 81, 87, 369, 363, 21, 72, 21, 0, 98, 106, 98, 21, 0, 178, 21, 98, 98, 0, 0, 0, 225, 21, 21, 0, 233, 197, 21, 229, 21, 235, 21, 237, 21, 239, 0, 209, 21, 0, 216, 217, 218, 219, 220, 215, 210, 21, 181, 21, 364, 310, 312, 0, 314, 328, 320, 0, 0, 0, 255, 21, 258, 259, 21, 0, 0, 0, 21, 113, 115, 112, 114, 369, 341, 340, 178, 0, 335, 0, 0, 0, 0, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 329, 330, 0, 352, 353, 27, 26, 351, 364, 254, 78, 75, 0, 21, 0, 96, 363, 0, 0, 21, 0, 21, 140, 21, 223, 0, 142, 21, 21, 98, 21, 227, 0, 0, 21, 0, 0, 0, 0, 212, 21, 0, 0, 171, 0, 0, 319, 0, 0, 324, 325, 21, 21, 327, 256, 134, 132, 21, 21, 116, 0, 346, 362, 336, 337, 339, 344, 345, 342, 0, 21, 0, 21, 0, 80, 0, 97, 70, 68, 69, 53, 98, 363, 141, 98, 0, 0, 21, 0, 232, 230, 0, 21, 228, 234, 236, 238, 0, 222, 221, 21, 183, 322, 0, 315, 316, 317, 318, 118, 0, 0, 369, 253, 364, 0, 77, 21, 0, 48, 21, 129, 21, 0, 0, 0, 226, 231, 0, 21, 0, 321, 364, 254, 343, 0, 0, 76, 82, 102, 0, 52, 23, 53, 0, 0, 0, 165, 167, 0, 198, 0, 211, 0, 0, 362, 64, 0, 63, 0, 59, 61, 60, 57, 58, 62, 56, 350, 65, 55, 54, 0, 124, 369, 21, 128, 0, 144, 180, 213, 21, 21, 369, 349, 348, 104, 0, 363, 21, 139, 21, 146, 120, 119, 0, 130, 363, 0, 21, 347, 131, 145, 0, 21, 0, 0, 147 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 22, 26, 36, 509, 347, 335, 277, 19, 155, 49, 260, 261, 619, 620, 642, 657, 643, 50, 51, 52, 53, 300, 184, 575, 171, 172, 406, 173, 174, 175, 176, 177, 178, 521, 54, 312, 55, 56, 294, 57, 382, 522, 147, 148, 149, 150, 151, 152, 59, 383, 61, 192, 645, 646, 139, 140, 141, 676, 384, 63, 418, 677, 691, 699, 503, 385, 65, 386, 67, 217, 142, 131, 27, 68, 305, 211, 69, 544, 78, 79, 80, 430, 431, 82, 83, 84, 85, 332, 86, 450, 602, 419, 87, 208, 42, 43, 44, 45, 573, 359, 132, 133, 349, 241, 134, 135, 136, 354, 461, 462, 355, 356, 137, 504, 24, 478, 158, 387, 388, 670, 40, 395, 396, 397, 274, 46, 47, 281, 156 }; /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ #define YYPACT_NINF -366 static const yytype_int16 yypact[] = { 795, 368, 45, 45, 45, 45, 45, 45, 45, 45, 76, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, 87, 100, -366, -366, -366, 303, -366, 820, 859, 1739, 183, 183, -4, -366, 277, -366, -366, 45, -366, -366, 127, 1838, 20, 62, 124, 271, 45, 45, 120, 229, -366, -366, 149, 252, -366, -366, 178, 283, 321, -366, 213, -366, 226, -366, 235, -366, 859, -366, 248, -366, -366, 444, 279, 505, 268, -366, 300, 228, 953, -366, 469, 469, -366, -366, -366, -366, 45, 45, 45, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, 45, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, 45, 45, 45, 45, 45, -366, -366, 45, 45, 1847, 45, 821, -366, 45, 45, 45, -366, 45, 266, 45, 219, -366, 21, 45, 38, 309, -366, 256, 251, 324, -366, -366, -366, 325, 633, 16, -366, 33, -366, -366, 221, 45, -366, 45, 45, -366, 45, 45, 80, -366, 45, 338, 44, 225, 364, -366, 361, 358, 376, 45, -366, -366, 45, 45, -366, 45, 45, 45, -366, -366, 45, 45, 45, 45, -366, -366, 289, 64, 638, 638, 638, 638, 379, -366, -366, 334, 30, -366, -366, 292, 859, 45, 45, 45, 393, 859, -366, -366, 469, 469, 469, -366, -366, -366, -366, -366, -366, 936, 1193, -366, 224, -366, -366, 45, 45, -366, -366, 45, 45, 1739, -366, -366, -366, -366, 409, 45, 45, -366, -366, -366, 311, -366, 237, -366, 45, 45, 45, 45, 1931, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, 1277, 45, -366, -366, -366, -366, -366, -366, -366, -366, 403, 367, -366, 45, -366, 45, -366, 323, 45, 229, -366, -366, -366, -366, 308, -4, -366, -366, -366, 326, 97, 329, 330, 292, 638, 425, 310, 82, 859, 82, 859, 82, 859, 82, 859, 82, -366, -366, 49, 268, 434, 448, -366, -366, -366, 45, -366, -366, -366, -366, 333, -366, 469, -366, -366, -366, -366, 682, 82, 45, 2033, 82, -366, -366, -366, 447, 45, -366, 230, 82, -366, -366, -366, -366, -366, -366, 183, 104, -366, -366, 45, 82, 311, 311, 311, 311, -366, 432, -366, 79, 728, 428, 305, 431, 436, 435, -366, -366, 1734, 277, 976, 1065, 1350, -366, -366, -366, -366, -366, 1293, 1036, 476, 1065, 45, 45, 405, -366, -366, -366, 45, -366, 45, 591, -366, -366, -366, 85, 454, -366, 45, -366, -366, 347, 859, 82, -366, 45, 45, 381, -366, -366, 45, -366, 45, -366, 45, -366, 45, -366, 854, -366, 45, 448, -366, -366, -366, -366, -366, -366, -366, 45, -366, 45, -366, -366, -366, 1193, -366, -366, 103, 108, 1979, 53, -366, 45, -366, -366, 45, 46, 1065, 458, 45, -366, -366, -366, -366, -366, -366, -366, 370, 70, -366, 262, 110, 110, -27, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, 477, -366, -366, -366, -366, -366, -366, 1565, -366, 472, 382, 45, 607, -366, -366, 16, 33, 45, 391, 45, -366, 45, -366, 394, -366, 45, 45, -366, 45, -366, 82, 82, 45, 166, 82, 166, 166, -366, 45, 400, 859, -366, 1424, 82, 447, 45, 45, -366, -366, 45, 45, -366, -366, -366, -366, 45, 45, -366, 398, -366, -366, -366, -366, -366, -366, -366, -366, 1367, 45, 1519, 45, 82, -366, 382, -366, -366, -366, -366, -366, -366, -366, -366, -366, 104, 104, 45, 166, -366, -366, 82, 45, -366, -366, -366, -366, 400, -366, -366, 45, 228, -366, 53, 87, 87, -366, -366, -366, 1136, 402, -366, -366, -366, 1739, -366, 45, 46, 72, 45, -366, 45, 46, 46, 104, -366, -366, 859, 45, 30, -366, -366, 1565, -366, 960, 1441, 1652, 367, -366, 1987, -366, -366, -366, 46, 159, 1854, -366, -366, 46, -366, 30, -366, 1065, 82, -366, -366, 477, -366, 614, -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, 277, 46, -366, -366, 45, 402, 1650, -366, -366, -366, 45, 45, -366, 6, -27, -366, 1497, -366, 45, -366, 45, -366, -366, -366, 1514, -366, -366, 1854, 45, 402, -366, -366, 406, 45, 104, 46, -366 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -366, -366, -366, -366, -366, -366, -366, -366, -366, -366, -330, -1, -246, -365, 276, -292, -125, -366, -366, 234, -104, -366, -123, -366, -366, -366, -366, -366, -241, -366, -118, -366, 227, -366, 14, -44, -366, -366, -366, 352, -54, -366, -366, -354, -366, -164, -236, -107, -366, -103, 510, -366, -205, -366, -366, -366, -168, -366, -366, 511, -97, -366, -366, -366, -99, 517, 184, -366, 531, -78, -366, -366, -366, -366, -112, 537, -73, 540, -71, -366, 255, -15, -239, -366, -255, 385, -59, -366, 516, 41, 383, -8, -83, 515, -25, -47, -366, 272, -366, 155, 0, 189, -366, -105, -339, -366, 566, -366, -24, -366, -366, -215, -195, -366, -121, -89, -366, 150, -366, 65, 151, 160, -366, -366, -366, 8, -366, -23, -22, -366, -30, -139, -133, -131, -366, -9, -290, -222, -260 }; /* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule which number is the opposite. If YYTABLE_NINF, syntax error. */ #define YYTABLE_NINF -363 static const yytype_int16 yytable[] = { 23, 186, 28, 29, 30, 31, 32, 33, 34, 25, 159, 37, 242, 412, 348, 390, 275, 143, 143, 380, 280, 251, 81, 272, 381, 273, 460, 401, 310, 468, 333, 313, 160, 275, 279, 352, 223, 360, 157, 253, 449, 391, 236, 21, -88, 295, 507, 179, 180, 372, 21, -21, 392, 344, 21, 221, 393, 222, 145, 422, 81, 523, 399, 164, 204, 206, 529, 530, 402, 21, 197, 564, -51, 553, 207, 21, 35, -21, -21, 165, 20, 290, 344, 568, 369, 21, 278, 224, 225, 226, 21, 182, 38, -21, 318, 320, 322, 324, 326, 505, -21, 414, 417, 558, -241, 41, 439, 146, -19, 227, 416, 20, 39, 38, 417, 21, 563, -362, 517, -178, 365, 228, 229, 230, 231, 232, 276, 161, 233, 234, 163, 237, -21, 247, 243, 244, 245, 166, 246, 334, 249, 353, 181, 276, 252, 254, 278, 516, 469, -21, 541, -88, -21, 508, -88, 284, -88, -88, 287, -127, 674, 346, 283, 527, 285, 286, 344, 288, 289, 291, 554, 292, 138, 185, 223, 223, 183, 589, -21, -51, 302, -21, -21, 303, 304, 511, 306, 307, 308, 316, 346, 309, 311, 309, 309, 343, 138, 328, 317, 319, 321, 323, 325, 187, 337, 472, 473, 474, 475, 342, 424, -241, 338, 339, 340, 351, 562, -19, 460, 606, 607, -19, 549, -21, 344, 345, 550, 242, 578, 621, 344, 546, 623, 212, 361, 362, 193, 357, 363, 364, 435, 182, 437, 464, 370, -173, 367, 368, 624, 625, 371, 389, 194, 167, 640, 373, 374, 375, 376, 648, 649, 547, 457, 20, 195, -83, -127, 21, 272, 197, 273, -91, 167, 127, 346, -21, 400, 128, 594, -21, 673, 398, 153, 154, -83, 679, 407, 650, 571, 209, 587, 588, 205, 405, 622, 408, 223, 127, 410, 145, 210, 128, 143, -241, 41, 250, 20, 686, 678, 255, 168, 169, 690, 433, 423, 257, -362, 190, 191, 256, 313, 188, 189, 426, 427, -2, 183, 479, 440, 168, 169, 282, 346, 190, 191, 451, 453, 296, 346, 653, 532, 707, 213, 214, 215, 216, 569, 329, 146, 456, 626, 293, 143, 636, 330, 77, 463, 485, 520, 702, 680, -95, 167, 170, 297, -91, 706, 353, 476, 20, 470, 299, 353, 21, -83, -21, 301, 179, 247, 248, -21, 581, 170, 272, 647, 273, 477, 258, 259, 315, 242, 481, 327, 637, 579, 580, 634, 671, 696, 262, 658, 638, 513, 514, 336, 660, 341, 701, 518, 366, 519, 654, 600, 601, 687, 524, 403, 263, 528, 168, 169, 413, 146, 695, 127, 534, 535, 404, 128, 272, 537, 273, 538, 20, 539, 409, 540, 21, 425, 415, 440, 351, 420, 421, -21, -21, 351, 441, 333, 543, 452, 545, 459, 480, 482, 443, 444, 445, 446, 447, 531, 198, 483, 556, 484, 515, 557, 526, -95, 536, 561, -95, 170, 635, -95, 560, -90, 262, 20, 306, 563, 311, 309, 309, 71, 72, 73, 74, 75, 574, 565, 566, 567, 170, 379, 263, 264, 265, 266, 267, 268, 269, 270, 272, 583, 273, 206, 586, 358, 271, 21, -350, 570, 242, 577, 278, 641, 242, -21, 704, 582, 672, 584, 659, 585, -21, -21, 411, 576, -21, 298, 590, 612, 618, 661, 593, 81, 689, 662, 58, 60, 599, 199, 200, 663, 201, 569, 675, 202, 203, 144, 467, 608, 609, 272, 613, 273, 334, 610, 611, 62, 635, 272, 664, 273, 692, 64, 448, 665, 66, 666, 614, 428, 616, 264, 265, 266, 267, 268, 269, 270, 314, 667, -90, 196, 603, -90, 271, -90, -90, 331, -91, 167, 629, 429, 220, 432, 542, 434, 630, 436, 631, 438, 442, -83, 525, 684, -89, 262, 162, 655, 551, 552, 605, -91, 167, 548, 639, 668, 669, 644, 651, 0, 0, 454, 455, 263, -83, 458, 652, 0, 143, 389, -332, 262, 465, 466, 0, 685, 206, 0, 0, 0, 21, 0, 0, 0, 683, 471, 168, 169, -21, 263, -21, -21, -21, -21, -21, -21, -21, 0, 0, 0, 0, 0, 700, 0, 0, 506, 0, 0, 0, 168, 169, 688, 0, 0, 0, 512, 0, 693, 694, 344, 0, 0, 0, 0, 0, 697, 0, 698, 0, 0, 0, 88, 89, 0, 90, 703, 0, 533, -91, 170, 705, -91, 264, 265, 266, 267, 268, 269, 270, 0, 0, -89, 0, 0, -89, 271, -89, -89, -91, 0, 0, -91, 170, 0, -91, 0, 167, 0, 264, 265, 266, 267, 268, 269, 270, 555, 0, -332, -83, 0, -332, 271, 559, -332, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 0, 0, 0, 124, 168, 169, 125, 0, 346, 0, 0, 126, 239, 0, 127, 0, 0, 240, 128, 0, 129, 130, 0, 0, 0, 0, 0, 0, 591, 592, 0, 595, 596, 597, 598, 0, 0, 0, 0, 238, 1, 604, 0, 2, 3, 4, 5, 6, 7, 8, 9, 88, 89, 0, 90, 0, -91, 170, 0, -91, -66, -138, -99, -105, -164, 0, 48, -166, 0, 617, 0, 0, -240, 394, 0, 0, -121, -121, 0, 0, 0, 0, 0, 0, 627, 0, 0, 628, 0, 0, 70, 263, 71, 72, 73, 74, 75, 76, 77, 632, 0, 0, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 0, 0, 0, 124, 0, 0, 125, 0, 0, 681, 682, 126, 239, 0, 127, 344, 345, 240, 128, 0, 129, 130, 0, 0, 0, 0, 0, 88, 89, 0, 90, 264, 265, 266, 267, 268, 269, 270, 0, -338, 262, -240, -240, 0, 271, 218, 278, 71, 72, 73, 74, 75, 219, 0, 0, 333, 394, 0, 263, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 263, 0, 0, 0, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 0, 510, 0, 124, 0, 0, 125, 0, 346, 0, 0, 126, 88, 89, 127, 90, 0, 0, 128, 0, 129, 130, 264, 265, 266, 267, 268, 269, 270, 344, 394, -338, 0, 0, -338, 271, 0, -338, 264, 265, 266, 267, 268, 269, 270, 0, 0, 0, 263, 334, 0, 271, 0, 278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 0, 633, 0, 124, 0, 0, 125, 0, 0, 0, 0, 126, 88, 89, 127, 90, 0, 0, 128, 0, 129, 130, 0, 0, 0, 0, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, 0, 346, 0, 0, 271, 0, 278, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 345, 0, 0, 0, 0, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 0, 0, 0, 124, 0, 0, 125, 0, 0, 0, 0, 126, 0, 0, 127, 0, 0, 0, 128, 0, 129, 130, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, -251, 394, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 0, 0, 0, -250, 394, 0, 263, 0, 0, 0, 0, 0, 0, 0, 350, 0, 0, 127, 0, 0, 0, 128, 263, 0, 0, 0, 0, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -251, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, -250, 0, 507, 394, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -249, 394, 263, 0, 0, 0, 0, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, -251, 0, 263, -251, 271, 0, 278, 264, 265, 266, 267, 268, 269, 270, 0, 0, -250, 0, 0, -250, 271, 0, 278, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, -249, 0, -263, 394, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -248, 394, 263, 0, 0, 0, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, 508, 0, 0, 263, 271, 0, 278, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, -249, 0, 0, -249, 271, 0, 278, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -248, -137, 262, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -350, 262, 263, 0, 0, -247, 615, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, 0, -263, 263, 0, 271, 0, 278, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, -248, 0, 0, -248, 271, 0, 278, 0, 0, 0, 0, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, -247, 0, 0, 88, 89, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, -137, 0, 0, 0, 271, 0, -137, 0, 264, 265, 266, 267, 268, 269, 270, 0, 0, -350, 572, 0, 0, 271, -247, -350, 0, -247, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 507, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 88, 89, 0, 90, 124, 0, 0, 125, 0, 0, 0, 0, 126, 239, 0, 127, 0, 0, 240, 128, 0, 129, 130, 0, 0, 0, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 88, 89, 0, 90, 124, 0, 508, 125, 0, 0, 0, 0, 126, 239, 0, 127, 0, 0, 240, 128, 0, 129, 130, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, -244, 41, 0, 0, 124, 0, 0, 125, 0, 0, 0, 0, 126, -362, 0, 127, -241, 41, 0, 128, 0, 129, 130, 0, 0, 0, 0, 0, 0, -362, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -244, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, -241, 0, 0, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 235, 377, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, -177, -244, -177, -177, -177, -177, -177, -177, -177, -66, -138, -99, -105, -164, 0, 378, -166, -241, 0, 0, 0, 0, 0, 0, 0, -121, -121, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, 656, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -177, 0, -177, -177, -177, -177, -177, -177, -177, -66, -138, -99, -105, -164, 0, 378, -166, 0, 0, 0, 0, 0, 0, 0, 0, -121, -121, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, -362, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 0, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 350, 0, 0, 127, 0, 0, 0, 128, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 0, 0, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121 }; #define yypact_value_is_default(yystate) \ ((yystate) == (-366)) #define yytable_value_is_error(yytable_value) \ YYID (0) static const yytype_int16 yycheck[] = { 1, 55, 3, 4, 5, 6, 7, 8, 9, 1, 40, 20, 133, 303, 229, 261, 0, 32, 33, 260, 159, 0, 30, 156, 260, 156, 356, 287, 192, 368, 0, 195, 41, 0, 159, 230, 83, 232, 39, 1, 332, 263, 131, 5, 0, 1, 0, 48, 49, 254, 5, 13, 274, 0, 5, 80, 278, 82, 62, 314, 68, 415, 284, 1, 73, 1, 420, 421, 290, 5, 21, 1, 0, 20, 75, 5, 0, 13, 14, 17, 1, 1, 0, 110, 252, 5, 113, 88, 89, 90, 5, 12, 5, 13, 199, 200, 201, 202, 203, 391, 62, 306, 17, 468, 0, 1, 328, 111, 5, 110, 13, 1, 12, 5, 17, 5, 110, 13, 408, 113, 241, 122, 123, 124, 125, 126, 110, 0, 129, 130, 110, 132, 62, 112, 135, 136, 137, 13, 139, 109, 141, 230, 22, 110, 145, 146, 113, 407, 370, 111, 442, 107, 88, 107, 110, 164, 112, 113, 167, 0, 1, 108, 163, 418, 165, 166, 0, 168, 169, 170, 117, 172, 13, 24, 221, 222, 97, 531, 114, 107, 181, 111, 118, 184, 185, 400, 187, 188, 189, 198, 108, 192, 193, 194, 195, 220, 13, 206, 199, 200, 201, 202, 203, 25, 212, 373, 374, 375, 376, 217, 315, 107, 213, 214, 215, 230, 476, 114, 548, 549, 550, 118, 114, 113, 0, 1, 118, 348, 518, 583, 0, 453, 586, 5, 235, 236, 23, 13, 239, 240, 323, 12, 325, 13, 253, 86, 247, 248, 587, 588, 13, 260, 26, 1, 619, 256, 257, 258, 259, 624, 625, 456, 351, 1, 29, 13, 107, 5, 401, 21, 401, 0, 1, 114, 108, 13, 285, 118, 112, 17, 645, 282, 5, 6, 13, 650, 295, 626, 510, 21, 529, 530, 13, 294, 584, 296, 343, 114, 299, 62, 0, 118, 317, 0, 1, 86, 1, 672, 647, 0, 58, 59, 677, 321, 315, 64, 13, 12, 13, 63, 484, 38, 39, 13, 14, 0, 97, 381, 329, 58, 59, 110, 108, 12, 13, 336, 345, 112, 108, 631, 423, 706, 114, 115, 116, 117, 485, 13, 111, 350, 589, 13, 367, 613, 20, 21, 357, 387, 412, 698, 652, 0, 1, 111, 0, 113, 705, 456, 377, 1, 371, 13, 461, 5, 13, 113, 0, 378, 112, 113, 12, 520, 111, 516, 623, 516, 378, 63, 64, 100, 511, 383, 13, 615, 519, 520, 611, 643, 688, 1, 641, 616, 403, 404, 112, 641, 13, 697, 409, 0, 411, 633, 12, 13, 674, 416, 13, 19, 419, 58, 59, 113, 111, 683, 114, 426, 427, 60, 118, 562, 431, 562, 433, 1, 435, 112, 437, 5, 13, 113, 441, 456, 113, 113, 12, 13, 461, 13, 0, 450, 117, 452, 5, 25, 23, 7, 8, 9, 10, 11, 113, 17, 26, 464, 29, 60, 467, 13, 107, 88, 471, 110, 111, 612, 113, 17, 0, 1, 1, 480, 110, 482, 483, 484, 15, 16, 17, 18, 19, 17, 482, 483, 484, 111, 260, 19, 98, 99, 100, 101, 102, 103, 104, 636, 113, 636, 1, 113, 232, 111, 5, 113, 504, 634, 515, 113, 620, 638, 13, 113, 521, 644, 523, 641, 525, 20, 21, 300, 514, 97, 178, 532, 562, 577, 641, 536, 544, 676, 641, 29, 29, 542, 98, 99, 641, 101, 685, 646, 104, 105, 33, 367, 553, 554, 687, 564, 687, 109, 559, 560, 29, 700, 695, 641, 695, 677, 29, 119, 641, 29, 641, 572, 317, 574, 98, 99, 100, 101, 102, 103, 104, 196, 641, 107, 68, 544, 110, 111, 112, 113, 207, 0, 1, 594, 318, 80, 320, 442, 322, 599, 324, 602, 326, 331, 13, 416, 660, 0, 1, 43, 634, 461, 461, 548, 0, 1, 456, 618, 641, 641, 621, 629, -1, -1, 348, 349, 19, 13, 352, 630, -1, 646, 641, 0, 1, 359, 360, -1, 668, 1, -1, -1, -1, 5, -1, -1, -1, 656, 372, 58, 59, 13, 19, 15, 16, 17, 18, 19, 20, 21, -1, -1, -1, -1, -1, 695, -1, -1, 392, -1, -1, -1, 58, 59, 675, -1, -1, -1, 402, -1, 681, 682, 0, -1, -1, -1, -1, -1, 689, -1, 691, -1, -1, -1, 12, 13, -1, 15, 699, -1, 424, 110, 111, 704, 113, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, -1, 110, 111, 112, 113, 107, -1, -1, 110, 111, -1, 113, -1, 1, -1, 98, 99, 100, 101, 102, 103, 104, 462, -1, 107, 13, -1, 110, 111, 469, 113, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, 103, 58, 59, 106, -1, 108, -1, -1, 111, 112, -1, 114, -1, -1, 117, 118, -1, 120, 121, -1, -1, -1, -1, -1, -1, 534, 535, -1, 537, 538, 539, 540, -1, -1, -1, -1, 0, 27, 547, -1, 30, 31, 32, 33, 34, 35, 36, 37, 12, 13, -1, 15, -1, 110, 111, -1, 113, 22, 23, 24, 25, 26, -1, 28, 29, -1, 575, -1, -1, 0, 1, -1, -1, 38, 39, -1, -1, -1, -1, -1, -1, 590, -1, -1, 593, -1, -1, 13, 19, 15, 16, 17, 18, 19, 20, 21, 605, -1, -1, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, 103, -1, -1, 106, -1, -1, 654, 655, 111, 112, -1, 114, 0, 1, 117, 118, -1, 120, 121, -1, -1, -1, -1, -1, 12, 13, -1, 15, 98, 99, 100, 101, 102, 103, 104, -1, 0, 1, 108, 109, -1, 111, 13, 113, 15, 16, 17, 18, 19, 20, -1, -1, 0, 1, -1, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 19, -1, -1, -1, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, 1, -1, 103, -1, -1, 106, -1, 108, -1, -1, 111, 12, 13, 114, 15, -1, -1, 118, -1, 120, 121, 98, 99, 100, 101, 102, 103, 104, 0, 1, 107, -1, -1, 110, 111, -1, 113, 98, 99, 100, 101, 102, 103, 104, -1, -1, -1, 19, 109, -1, 111, -1, 113, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, 1, -1, 103, -1, -1, 106, -1, -1, -1, -1, 111, 12, 13, 114, 15, -1, -1, 118, -1, 120, 121, -1, -1, -1, -1, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, -1, 108, -1, -1, 111, -1, 113, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, -1, -1, -1, -1, 103, -1, -1, 106, -1, -1, -1, -1, 111, -1, -1, 114, -1, -1, -1, 118, -1, 120, 121, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 0, 1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, -1, -1, -1, 0, 1, -1, 19, -1, -1, -1, -1, -1, -1, -1, 111, -1, -1, 114, -1, -1, -1, 118, 19, -1, -1, -1, -1, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 19, -1, -1, -1, -1, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, 19, 110, 111, -1, 113, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, -1, 110, 111, -1, 113, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 19, -1, -1, -1, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, -1, 19, 111, -1, 113, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, -1, 110, 111, -1, 113, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 19, -1, -1, 0, 1, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, -1, 108, 19, -1, 111, -1, 113, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, -1, 110, 111, -1, 113, -1, -1, -1, -1, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, -1, -1, 12, 13, -1, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, -1, -1, -1, 111, -1, 113, -1, 98, 99, 100, 101, 102, 103, 104, -1, -1, 107, 57, -1, -1, 111, 107, 113, -1, 110, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 0, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 12, 13, -1, 15, 103, -1, -1, 106, -1, -1, -1, -1, 111, 112, -1, 114, -1, -1, 117, 118, -1, 120, 121, -1, -1, -1, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 12, 13, -1, 15, 103, -1, 107, 106, -1, -1, -1, -1, 111, 112, -1, 114, -1, -1, 117, 118, -1, 120, 121, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 0, 1, -1, -1, 103, -1, -1, 106, -1, -1, -1, -1, 111, 13, -1, 114, 0, 1, -1, 118, -1, 120, 121, -1, -1, -1, -1, -1, -1, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 13, 107, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, -1, 28, 29, 107, -1, -1, -1, -1, -1, -1, -1, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13, -1, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, -1, 28, 29, -1, -1, -1, -1, -1, -1, -1, -1, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, -1, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 111, -1, -1, 114, -1, -1, -1, 118, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, -1, -1, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint16 yystos[] = { 0, 27, 30, 31, 32, 33, 34, 35, 36, 37, 123, 124, 125, 126, 127, 128, 129, 130, 131, 139, 1, 5, 132, 133, 246, 247, 133, 204, 133, 133, 133, 133, 133, 133, 133, 0, 134, 257, 5, 12, 252, 1, 226, 227, 228, 229, 257, 258, 28, 141, 149, 150, 151, 152, 166, 168, 169, 171, 172, 180, 181, 182, 190, 191, 197, 198, 199, 200, 205, 208, 13, 15, 16, 17, 18, 19, 20, 21, 210, 211, 212, 213, 215, 216, 217, 218, 220, 224, 12, 13, 15, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 103, 106, 111, 114, 118, 120, 121, 203, 232, 233, 236, 237, 238, 244, 13, 186, 187, 188, 202, 203, 187, 62, 111, 174, 175, 176, 177, 178, 179, 5, 6, 140, 260, 133, 248, 252, 257, 0, 228, 110, 1, 17, 13, 1, 58, 59, 111, 156, 157, 159, 160, 161, 162, 163, 164, 133, 133, 22, 12, 97, 154, 24, 162, 25, 38, 39, 12, 13, 183, 23, 26, 29, 210, 21, 17, 98, 99, 101, 104, 105, 257, 13, 1, 133, 225, 21, 0, 207, 5, 114, 115, 116, 117, 201, 13, 20, 215, 216, 216, 217, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 84, 237, 133, 0, 112, 117, 235, 236, 133, 133, 133, 133, 112, 113, 133, 86, 0, 133, 1, 133, 0, 63, 64, 63, 64, 142, 143, 1, 19, 98, 99, 100, 101, 102, 103, 104, 111, 254, 255, 256, 0, 110, 138, 113, 138, 253, 259, 110, 133, 257, 133, 133, 257, 133, 133, 1, 133, 133, 13, 170, 1, 112, 0, 161, 13, 153, 0, 133, 133, 133, 206, 133, 133, 133, 133, 167, 133, 167, 167, 207, 100, 257, 133, 225, 133, 225, 133, 225, 133, 225, 133, 225, 13, 257, 13, 20, 212, 219, 0, 109, 137, 112, 213, 133, 133, 133, 13, 213, 216, 0, 1, 108, 136, 233, 234, 111, 203, 234, 237, 239, 242, 243, 13, 136, 231, 234, 133, 133, 133, 133, 236, 0, 133, 133, 178, 257, 13, 174, 133, 133, 133, 133, 1, 28, 141, 150, 168, 172, 181, 190, 197, 199, 249, 250, 257, 134, 259, 259, 259, 1, 253, 254, 255, 133, 259, 257, 260, 259, 13, 60, 133, 158, 257, 133, 112, 133, 154, 258, 113, 174, 113, 13, 17, 192, 223, 113, 113, 206, 133, 225, 13, 13, 14, 202, 136, 213, 214, 136, 213, 136, 214, 136, 214, 136, 259, 133, 13, 219, 7, 8, 9, 10, 11, 119, 137, 221, 133, 117, 257, 136, 136, 133, 237, 136, 5, 132, 240, 241, 133, 13, 136, 136, 188, 226, 259, 133, 136, 178, 178, 178, 178, 257, 247, 247, 162, 25, 247, 23, 26, 29, 252, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 196, 245, 137, 136, 0, 107, 135, 1, 233, 136, 133, 133, 60, 260, 258, 133, 133, 162, 165, 173, 165, 133, 223, 13, 206, 133, 165, 165, 113, 214, 136, 133, 133, 88, 133, 133, 133, 133, 137, 221, 133, 209, 133, 259, 234, 243, 114, 118, 239, 242, 20, 117, 136, 133, 133, 135, 136, 17, 133, 260, 110, 1, 247, 247, 247, 110, 253, 247, 259, 57, 230, 17, 155, 156, 133, 258, 138, 138, 253, 133, 113, 133, 133, 113, 204, 204, 165, 133, 136, 136, 133, 112, 136, 136, 136, 136, 133, 12, 13, 222, 211, 136, 241, 132, 132, 133, 133, 133, 133, 252, 257, 133, 1, 133, 136, 157, 144, 145, 165, 258, 165, 226, 226, 204, 136, 136, 133, 222, 133, 136, 1, 233, 253, 260, 259, 233, 133, 135, 142, 146, 148, 133, 184, 185, 204, 135, 135, 226, 213, 133, 137, 259, 230, 1, 147, 150, 152, 168, 169, 171, 182, 191, 198, 200, 208, 249, 250, 251, 134, 144, 135, 1, 186, 189, 193, 226, 135, 137, 136, 136, 257, 162, 252, 135, 260, 133, 253, 135, 194, 196, 133, 133, 260, 258, 133, 133, 195, 252, 258, 226, 133, 113, 133, 226, 135 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab /* Like YYERROR except do call yyerror. This remains here temporarily to ease the transition to the new meaning of YYERROR, for GCC. Once GCC version 2 has supplanted version 1, this can go. However, YYFAIL appears to be in use. Nevertheless, it is formally deprecated in Bison 2.4.2's NEWS entry, where a plan to phase it out is discussed. */ #define YYFAIL goto yyerrlab #if defined YYFAIL /* This is here to suppress warnings from the GCC cpp's -Wunused-macros. Normally we don't worry about that warning, but some users do, and we want to make it easy for users to remove YYFAIL uses, which will produce warnings from Bison 2.5. */ #endif #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY && yylen == 1) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (1); \ goto yybackup; \ } \ else \ { \ yyerror (parser, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (YYID (0)) #define YYTERROR 1 #define YYERRCODE 256 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N]. If N is 0, then set CURRENT to the empty location which ends the previous symbol: RHS[0] (always defined). */ #define YYRHSLOC(Rhs, K) ((Rhs)[K]) #ifndef YYLLOC_DEFAULT # define YYLLOC_DEFAULT(Current, Rhs, N) \ do \ if (YYID (N)) \ { \ (Current).first_line = YYRHSLOC (Rhs, 1).first_line; \ (Current).first_column = YYRHSLOC (Rhs, 1).first_column; \ (Current).last_line = YYRHSLOC (Rhs, N).last_line; \ (Current).last_column = YYRHSLOC (Rhs, N).last_column; \ } \ else \ { \ (Current).first_line = (Current).last_line = \ YYRHSLOC (Rhs, 0).last_line; \ (Current).first_column = (Current).last_column = \ YYRHSLOC (Rhs, 0).last_column; \ } \ while (YYID (0)) #endif /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif /* YYLEX -- calling `yylex' with the right arguments. */ #ifdef YYLEX_PARAM # define YYLEX yylex (&yylval, YYLEX_PARAM) #else # define YYLEX yylex (&yylval, parser) #endif /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (YYID (0)) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, parser); \ YYFPRINTF (stderr, "\n"); \ } \ } while (YYID (0)) /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, BisonCSSParser* parser) #else static void yy_symbol_value_print (yyoutput, yytype, yyvaluep, parser) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; BisonCSSParser* parser; #endif { if (!yyvaluep) return; YYUSE (parser); # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # else YYUSE (yyoutput); # endif switch (yytype) { default: break; } } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, BisonCSSParser* parser) #else static void yy_symbol_print (yyoutput, yytype, yyvaluep, parser) FILE *yyoutput; int yytype; YYSTYPE const * const yyvaluep; BisonCSSParser* parser; #endif { if (yytype < YYNTOKENS) YYFPRINTF (yyoutput, "token %s (", yytname[yytype]); else YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep, parser); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) #else static void yy_stack_print (yybottom, yytop) yytype_int16 *yybottom; yytype_int16 *yytop; #endif { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (YYID (0)) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yy_reduce_print (YYSTYPE *yyvsp, int yyrule, BisonCSSParser* parser) #else static void yy_reduce_print (yyvsp, yyrule, parser) YYSTYPE *yyvsp; int yyrule; BisonCSSParser* parser; #endif { int yynrhs = yyr2[yyrule]; int yyi; unsigned long int yylno = yyrline[yyrule]; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi], &(yyvsp[(yyi + 1) - (yynrhs)]) , parser); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyvsp, Rule, parser); \ } while (YYID (0)) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static YYSIZE_T yystrlen (const char *yystr) #else static YYSIZE_T yystrlen (yystr) const char *yystr; #endif { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static char * yystpcpy (char *yydest, const char *yysrc) #else static char * yystpcpy (yydest, yysrc) char *yydest; const char *yysrc; #endif { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (0, yytname[yytoken]); YYSIZE_T yysize = yysize0; YYSIZE_T yysize1; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = 0; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - Assume YYFAIL is not used. It's too flawed to consider. See <http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html> for details. YYERROR is fine as it does not invoke this function. - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; yysize1 = yysize + yytnamerr (0, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ /*ARGSUSED*/ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, BisonCSSParser* parser) #else static void yydestruct (yymsg, yytype, yyvaluep, parser) const char *yymsg; int yytype; YYSTYPE *yyvaluep; BisonCSSParser* parser; #endif { YYUSE (yyvaluep); YYUSE (parser); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); switch (yytype) { default: break; } } /* Prevent warnings from -Wmissing-prototypes. */ #ifdef YYPARSE_PARAM #if defined __STDC__ || defined __cplusplus int yyparse (void *YYPARSE_PARAM); #else int yyparse (); #endif #else /* ! YYPARSE_PARAM */ #if defined __STDC__ || defined __cplusplus int yyparse (BisonCSSParser* parser); #else int yyparse (); #endif #endif /* ! YYPARSE_PARAM */ /*----------. | yyparse. | `----------*/ #ifdef YYPARSE_PARAM #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (void *YYPARSE_PARAM) #else int yyparse (YYPARSE_PARAM) void *YYPARSE_PARAM; #endif #else /* ! YYPARSE_PARAM */ #if (defined __STDC__ || defined __C99__FUNC__ \ || defined __cplusplus || defined _MSC_VER) int yyparse (BisonCSSParser* parser) #else int yyparse (parser) BisonCSSParser* parser; #endif #endif { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: `yyss': related to states. `yyvs': related to semantic values. Refer to the stacks thru separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yytoken = 0; yyss = yyssa; yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* Initialize stack pointers. Waste one element of value and location stack so that they stay on the same level as the state stack. The wasted elements are never initialized. */ yyssp = yyss; yyvsp = yyvs; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = YYLEX; } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; *++yyvsp = yylval; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: `$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 11: /* Line 1806 of yacc.c */ #line 386 "css/CSSGrammar.y" { parser->m_rule = (yyvsp[(3) - (5)].rule); } break; case 12: /* Line 1806 of yacc.c */ #line 392 "css/CSSGrammar.y" { parser->m_keyframe = (yyvsp[(3) - (5)].keyframe); } break; case 13: /* Line 1806 of yacc.c */ #line 398 "css/CSSGrammar.y" { parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList)); } break; case 14: /* Line 1806 of yacc.c */ #line 404 "css/CSSGrammar.y" { /* can be empty */ } break; case 15: /* Line 1806 of yacc.c */ #line 410 "css/CSSGrammar.y" { parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList)); int oldParsedProperties = parser->m_parsedProperties.size(); if (!parser->parseValue(parser->m_id, parser->m_important)) parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties); parser->m_valueList = nullptr; } break; case 16: /* Line 1806 of yacc.c */ #line 420 "css/CSSGrammar.y" { parser->m_mediaList = (yyvsp[(4) - (5)].mediaList); } break; case 17: /* Line 1806 of yacc.c */ #line 426 "css/CSSGrammar.y" { if (parser->m_selectorListForParseSelector) parser->m_selectorListForParseSelector->adoptSelectorVector(*(yyvsp[(3) - (4)].selectorList)); } break; case 18: /* Line 1806 of yacc.c */ #line 433 "css/CSSGrammar.y" { parser->m_supportsCondition = (yyvsp[(3) - (4)].boolean); } break; case 35: /* Line 1806 of yacc.c */ #line 476 "css/CSSGrammar.y" { if (parser->m_styleSheet) parser->m_styleSheet->parserSetEncodingFromCharsetRule((yyvsp[(3) - (5)].string)); parser->startEndUnknownRule(); } break; case 38: /* Line 1806 of yacc.c */ #line 486 "css/CSSGrammar.y" { if ((yyvsp[(2) - (3)].rule) && parser->m_styleSheet) parser->m_styleSheet->parserAppendRule((yyvsp[(2) - (3)].rule)); } break; case 48: /* Line 1806 of yacc.c */ #line 505 "css/CSSGrammar.y" { parser->startRule(); } break; case 49: /* Line 1806 of yacc.c */ #line 511 "css/CSSGrammar.y" { (yyval.rule) = (yyvsp[(2) - (2)].rule); parser->m_hadSyntacticallyValidCSSRule = true; parser->endRule(!!(yyval.rule)); } break; case 50: /* Line 1806 of yacc.c */ #line 516 "css/CSSGrammar.y" { (yyval.rule) = 0; parser->endRule(false); } break; case 53: /* Line 1806 of yacc.c */ #line 528 "css/CSSGrammar.y" { (yyval.ruleList) = 0; } break; case 54: /* Line 1806 of yacc.c */ #line 529 "css/CSSGrammar.y" { (yyval.ruleList) = parser->appendRule((yyvsp[(1) - (3)].ruleList), (yyvsp[(2) - (3)].rule)); } break; case 55: /* Line 1806 of yacc.c */ #line 535 "css/CSSGrammar.y" { parser->endRule(false); } break; case 64: /* Line 1806 of yacc.c */ #line 552 "css/CSSGrammar.y" { (yyval.rule) = (yyvsp[(2) - (2)].rule); parser->endRule(!!(yyval.rule)); } break; case 65: /* Line 1806 of yacc.c */ #line 556 "css/CSSGrammar.y" { (yyval.rule) = 0; parser->endRule(false); } break; case 66: /* Line 1806 of yacc.c */ #line 563 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::IMPORT_RULE); } break; case 67: /* Line 1806 of yacc.c */ #line 569 "css/CSSGrammar.y" { parser->endRuleHeader(); parser->startRuleBody(); } break; case 68: /* Line 1806 of yacc.c */ #line 576 "css/CSSGrammar.y" { (yyval.rule) = parser->createImportRule((yyvsp[(2) - (6)].string), (yyvsp[(5) - (6)].mediaList)); } break; case 69: /* Line 1806 of yacc.c */ #line 579 "css/CSSGrammar.y" { (yyval.rule) = 0; } break; case 70: /* Line 1806 of yacc.c */ #line 585 "css/CSSGrammar.y" { parser->addNamespace((yyvsp[(3) - (6)].string), (yyvsp[(4) - (6)].string)); (yyval.rule) = 0; } break; case 71: /* Line 1806 of yacc.c */ #line 592 "css/CSSGrammar.y" { (yyval.string).clear(); } break; case 75: /* Line 1806 of yacc.c */ #line 602 "css/CSSGrammar.y" { (yyval.valueList) = 0; } break; case 76: /* Line 1806 of yacc.c */ #line 605 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(3) - (3)].valueList); } break; case 77: /* Line 1806 of yacc.c */ #line 611 "css/CSSGrammar.y" { parser->tokenToLowerCase((yyvsp[(3) - (6)].string)); (yyval.mediaQueryExp) = parser->createFloatingMediaQueryExp((yyvsp[(3) - (6)].string), (yyvsp[(5) - (6)].valueList)); if (!(yyval.mediaQueryExp)) YYERROR; } break; case 78: /* Line 1806 of yacc.c */ #line 617 "css/CSSGrammar.y" { YYERROR; } break; case 79: /* Line 1806 of yacc.c */ #line 623 "css/CSSGrammar.y" { (yyval.mediaQueryExpList) = parser->createFloatingMediaQueryExpList(); (yyval.mediaQueryExpList)->append(parser->sinkFloatingMediaQueryExp((yyvsp[(1) - (1)].mediaQueryExp))); } break; case 80: /* Line 1806 of yacc.c */ #line 627 "css/CSSGrammar.y" { (yyval.mediaQueryExpList) = (yyvsp[(1) - (5)].mediaQueryExpList); (yyval.mediaQueryExpList)->append(parser->sinkFloatingMediaQueryExp((yyvsp[(5) - (5)].mediaQueryExp))); } break; case 81: /* Line 1806 of yacc.c */ #line 634 "css/CSSGrammar.y" { (yyval.mediaQueryExpList) = parser->createFloatingMediaQueryExpList(); } break; case 82: /* Line 1806 of yacc.c */ #line 637 "css/CSSGrammar.y" { (yyval.mediaQueryExpList) = (yyvsp[(4) - (5)].mediaQueryExpList); } break; case 83: /* Line 1806 of yacc.c */ #line 643 "css/CSSGrammar.y" { (yyval.mediaQueryRestrictor) = MediaQuery::None; } break; case 84: /* Line 1806 of yacc.c */ #line 646 "css/CSSGrammar.y" { (yyval.mediaQueryRestrictor) = MediaQuery::Only; } break; case 85: /* Line 1806 of yacc.c */ #line 649 "css/CSSGrammar.y" { (yyval.mediaQueryRestrictor) = MediaQuery::Not; } break; case 86: /* Line 1806 of yacc.c */ #line 655 "css/CSSGrammar.y" { (yyval.mediaQuery) = parser->createFloatingMediaQuery(parser->sinkFloatingMediaQueryExpList((yyvsp[(1) - (2)].mediaQueryExpList))); } break; case 87: /* Line 1806 of yacc.c */ #line 658 "css/CSSGrammar.y" { parser->tokenToLowerCase((yyvsp[(2) - (3)].string)); (yyval.mediaQuery) = parser->createFloatingMediaQuery((yyvsp[(1) - (3)].mediaQueryRestrictor), (yyvsp[(2) - (3)].string), parser->sinkFloatingMediaQueryExpList((yyvsp[(3) - (3)].mediaQueryExpList))); } break; case 89: /* Line 1806 of yacc.c */ #line 666 "css/CSSGrammar.y" { parser->reportError(parser->lastLocationLabel(), InvalidMediaQueryCSSError); (yyval.mediaQuery) = parser->createFloatingNotAllQuery(); } break; case 90: /* Line 1806 of yacc.c */ #line 670 "css/CSSGrammar.y" { parser->reportError(parser->lastLocationLabel(), InvalidMediaQueryCSSError); (yyval.mediaQuery) = parser->createFloatingNotAllQuery(); } break; case 91: /* Line 1806 of yacc.c */ #line 677 "css/CSSGrammar.y" { (yyval.mediaList) = parser->createMediaQuerySet(); } break; case 93: /* Line 1806 of yacc.c */ #line 684 "css/CSSGrammar.y" { (yyval.mediaList) = parser->createMediaQuerySet(); (yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(1) - (1)].mediaQuery))); } break; case 94: /* Line 1806 of yacc.c */ #line 688 "css/CSSGrammar.y" { (yyval.mediaList) = (yyvsp[(1) - (2)].mediaList); (yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(2) - (2)].mediaQuery))); } break; case 95: /* Line 1806 of yacc.c */ #line 692 "css/CSSGrammar.y" { (yyval.mediaList) = (yyvsp[(1) - (1)].mediaList); (yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery(parser->createFloatingNotAllQuery())); } break; case 96: /* Line 1806 of yacc.c */ #line 699 "css/CSSGrammar.y" { (yyval.mediaList) = parser->createMediaQuerySet(); (yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(1) - (4)].mediaQuery))); } break; case 97: /* Line 1806 of yacc.c */ #line 703 "css/CSSGrammar.y" { (yyval.mediaList) = (yyvsp[(1) - (5)].mediaList); (yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(2) - (5)].mediaQuery))); } break; case 98: /* Line 1806 of yacc.c */ #line 710 "css/CSSGrammar.y" { parser->startRuleBody(); } break; case 99: /* Line 1806 of yacc.c */ #line 716 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::MEDIA_RULE); } break; case 100: /* Line 1806 of yacc.c */ #line 722 "css/CSSGrammar.y" { parser->endRuleHeader(); } break; case 102: /* Line 1806 of yacc.c */ #line 731 "css/CSSGrammar.y" { (yyval.rule) = parser->createMediaRule((yyvsp[(2) - (8)].mediaList), (yyvsp[(7) - (8)].ruleList)); } break; case 104: /* Line 1806 of yacc.c */ #line 741 "css/CSSGrammar.y" { (yyval.rule) = parser->createSupportsRule((yyvsp[(4) - (10)].boolean), (yyvsp[(9) - (10)].ruleList)); } break; case 105: /* Line 1806 of yacc.c */ #line 747 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::SUPPORTS_RULE); parser->markSupportsRuleHeaderStart(); } break; case 106: /* Line 1806 of yacc.c */ #line 754 "css/CSSGrammar.y" { parser->endRuleHeader(); parser->markSupportsRuleHeaderEnd(); } break; case 111: /* Line 1806 of yacc.c */ #line 768 "css/CSSGrammar.y" { (yyval.boolean) = !(yyvsp[(3) - (3)].boolean); } break; case 112: /* Line 1806 of yacc.c */ #line 774 "css/CSSGrammar.y" { (yyval.boolean) = (yyvsp[(1) - (4)].boolean) && (yyvsp[(4) - (4)].boolean); } break; case 113: /* Line 1806 of yacc.c */ #line 777 "css/CSSGrammar.y" { (yyval.boolean) = (yyvsp[(1) - (4)].boolean) && (yyvsp[(4) - (4)].boolean); } break; case 114: /* Line 1806 of yacc.c */ #line 783 "css/CSSGrammar.y" { (yyval.boolean) = (yyvsp[(1) - (4)].boolean) || (yyvsp[(4) - (4)].boolean); } break; case 115: /* Line 1806 of yacc.c */ #line 786 "css/CSSGrammar.y" { (yyval.boolean) = (yyvsp[(1) - (4)].boolean) || (yyvsp[(4) - (4)].boolean); } break; case 116: /* Line 1806 of yacc.c */ #line 792 "css/CSSGrammar.y" { (yyval.boolean) = (yyvsp[(3) - (5)].boolean); } break; case 118: /* Line 1806 of yacc.c */ #line 796 "css/CSSGrammar.y" { parser->reportError((yyvsp[(3) - (6)].location), InvalidSupportsConditionCSSError); (yyval.boolean) = false; } break; case 119: /* Line 1806 of yacc.c */ #line 803 "css/CSSGrammar.y" { (yyval.boolean) = false; CSSPropertyID id = cssPropertyID((yyvsp[(3) - (10)].string)); if (id != CSSPropertyInvalid) { parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(7) - (10)].valueList)); int oldParsedProperties = parser->m_parsedProperties.size(); (yyval.boolean) = parser->parseValue(id, (yyvsp[(8) - (10)].boolean)); // We just need to know if the declaration is supported as it is written. Rollback any additions. if ((yyval.boolean)) parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties); } parser->m_valueList = nullptr; parser->endProperty((yyvsp[(8) - (10)].boolean), false); } break; case 120: /* Line 1806 of yacc.c */ #line 817 "css/CSSGrammar.y" { (yyval.boolean) = false; parser->endProperty(false, false, GeneralCSSError); } break; case 121: /* Line 1806 of yacc.c */ #line 824 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::KEYFRAMES_RULE); } break; case 122: /* Line 1806 of yacc.c */ #line 830 "css/CSSGrammar.y" { (yyval.boolean) = false; } break; case 123: /* Line 1806 of yacc.c */ #line 833 "css/CSSGrammar.y" { (yyval.boolean) = true; } break; case 124: /* Line 1806 of yacc.c */ #line 839 "css/CSSGrammar.y" { (yyval.rule) = parser->createKeyframesRule((yyvsp[(2) - (9)].string), parser->sinkFloatingKeyframeVector((yyvsp[(8) - (9)].keyframeRuleList)), (yyvsp[(1) - (9)].boolean) /* isPrefixed */); } break; case 128: /* Line 1806 of yacc.c */ #line 851 "css/CSSGrammar.y" { parser->clearProperties(); } break; case 129: /* Line 1806 of yacc.c */ #line 856 "css/CSSGrammar.y" { (yyval.keyframeRuleList) = parser->createFloatingKeyframeVector(); parser->resumeErrorLogging(); } break; case 130: /* Line 1806 of yacc.c */ #line 860 "css/CSSGrammar.y" { (yyval.keyframeRuleList) = (yyvsp[(1) - (4)].keyframeRuleList); (yyval.keyframeRuleList)->append((yyvsp[(2) - (4)].keyframe)); } break; case 131: /* Line 1806 of yacc.c */ #line 864 "css/CSSGrammar.y" { parser->clearProperties(); parser->resumeErrorLogging(); } break; case 132: /* Line 1806 of yacc.c */ #line 871 "css/CSSGrammar.y" { (yyval.keyframe) = parser->createKeyframe((yyvsp[(1) - (5)].valueList)); } break; case 133: /* Line 1806 of yacc.c */ #line 877 "css/CSSGrammar.y" { (yyval.valueList) = parser->createFloatingValueList(); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(1) - (2)].value))); } break; case 134: /* Line 1806 of yacc.c */ #line 881 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(1) - (5)].valueList); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(4) - (5)].value))); } break; case 135: /* Line 1806 of yacc.c */ #line 888 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (2)].integer) * (yyvsp[(2) - (2)].number)); } break; case 136: /* Line 1806 of yacc.c */ #line 891 "css/CSSGrammar.y" { if ((yyvsp[(1) - (1)].string).equalIgnoringCase("from")) (yyval.value).setFromNumber(0); else if ((yyvsp[(1) - (1)].string).equalIgnoringCase("to")) (yyval.value).setFromNumber(100); else { YYERROR; } } break; case 137: /* Line 1806 of yacc.c */ #line 903 "css/CSSGrammar.y" { parser->reportError(parser->lastLocationLabel(), InvalidKeyframeSelectorCSSError); } break; case 138: /* Line 1806 of yacc.c */ #line 909 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::PAGE_RULE); } break; case 139: /* Line 1806 of yacc.c */ #line 916 "css/CSSGrammar.y" { if ((yyvsp[(4) - (10)].selector)) (yyval.rule) = parser->createPageRule(parser->sinkFloatingSelector((yyvsp[(4) - (10)].selector))); else { // Clear properties in the invalid @page rule. parser->clearProperties(); // Also clear margin at-rules here once we fully implement margin at-rules parsing. (yyval.rule) = 0; } } break; case 140: /* Line 1806 of yacc.c */ #line 929 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, (yyvsp[(1) - (2)].string), parser->m_defaultNamespace)); (yyval.selector)->setForPage(); } break; case 141: /* Line 1806 of yacc.c */ #line 933 "css/CSSGrammar.y" { (yyval.selector) = (yyvsp[(2) - (3)].selector); (yyval.selector)->prependTagSelector(QualifiedName(nullAtom, (yyvsp[(1) - (3)].string), parser->m_defaultNamespace)); (yyval.selector)->setForPage(); } break; case 142: /* Line 1806 of yacc.c */ #line 938 "css/CSSGrammar.y" { (yyval.selector) = (yyvsp[(1) - (2)].selector); (yyval.selector)->setForPage(); } break; case 143: /* Line 1806 of yacc.c */ #line 942 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setForPage(); } break; case 146: /* Line 1806 of yacc.c */ #line 954 "css/CSSGrammar.y" { parser->startDeclarationsForMarginBox(); } break; case 147: /* Line 1806 of yacc.c */ #line 956 "css/CSSGrammar.y" { (yyval.rule) = parser->createMarginAtRule((yyvsp[(1) - (7)].marginBox)); } break; case 148: /* Line 1806 of yacc.c */ #line 962 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::TopLeftCornerMarginBox; } break; case 149: /* Line 1806 of yacc.c */ #line 965 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::TopLeftMarginBox; } break; case 150: /* Line 1806 of yacc.c */ #line 968 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::TopCenterMarginBox; } break; case 151: /* Line 1806 of yacc.c */ #line 971 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::TopRightMarginBox; } break; case 152: /* Line 1806 of yacc.c */ #line 974 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::TopRightCornerMarginBox; } break; case 153: /* Line 1806 of yacc.c */ #line 977 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::BottomLeftCornerMarginBox; } break; case 154: /* Line 1806 of yacc.c */ #line 980 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::BottomLeftMarginBox; } break; case 155: /* Line 1806 of yacc.c */ #line 983 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::BottomCenterMarginBox; } break; case 156: /* Line 1806 of yacc.c */ #line 986 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::BottomRightMarginBox; } break; case 157: /* Line 1806 of yacc.c */ #line 989 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::BottomRightCornerMarginBox; } break; case 158: /* Line 1806 of yacc.c */ #line 992 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::LeftTopMarginBox; } break; case 159: /* Line 1806 of yacc.c */ #line 995 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::LeftMiddleMarginBox; } break; case 160: /* Line 1806 of yacc.c */ #line 998 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::LeftBottomMarginBox; } break; case 161: /* Line 1806 of yacc.c */ #line 1001 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::RightTopMarginBox; } break; case 162: /* Line 1806 of yacc.c */ #line 1004 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::RightMiddleMarginBox; } break; case 163: /* Line 1806 of yacc.c */ #line 1007 "css/CSSGrammar.y" { (yyval.marginBox) = CSSSelector::RightBottomMarginBox; } break; case 164: /* Line 1806 of yacc.c */ #line 1013 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::FONT_FACE_RULE); } break; case 165: /* Line 1806 of yacc.c */ #line 1020 "css/CSSGrammar.y" { (yyval.rule) = parser->createFontFaceRule(); } break; case 166: /* Line 1806 of yacc.c */ #line 1026 "css/CSSGrammar.y" { parser->markViewportRuleBodyStart(); parser->startRuleHeader(CSSRuleSourceData::VIEWPORT_RULE); } break; case 167: /* Line 1806 of yacc.c */ #line 1034 "css/CSSGrammar.y" { (yyval.rule) = parser->createViewportRule(); parser->markViewportRuleBodyEnd(); } break; case 168: /* Line 1806 of yacc.c */ #line 1041 "css/CSSGrammar.y" { (yyval.relation) = CSSSelector::DirectAdjacent; } break; case 169: /* Line 1806 of yacc.c */ #line 1042 "css/CSSGrammar.y" { (yyval.relation) = CSSSelector::IndirectAdjacent; } break; case 170: /* Line 1806 of yacc.c */ #line 1043 "css/CSSGrammar.y" { (yyval.relation) = CSSSelector::Child; } break; case 171: /* Line 1806 of yacc.c */ #line 1044 "css/CSSGrammar.y" { if ((yyvsp[(2) - (4)].string).equalIgnoringCase("deep")) (yyval.relation) = CSSSelector::ShadowDeep; else YYERROR; } break; case 173: /* Line 1806 of yacc.c */ #line 1054 "css/CSSGrammar.y" { (yyval.integer) = 1; } break; case 174: /* Line 1806 of yacc.c */ #line 1058 "css/CSSGrammar.y" { (yyval.integer) = -1; } break; case 175: /* Line 1806 of yacc.c */ #line 1059 "css/CSSGrammar.y" { (yyval.integer) = 1; } break; case 176: /* Line 1806 of yacc.c */ #line 1063 "css/CSSGrammar.y" { parser->startProperty(); } break; case 177: /* Line 1806 of yacc.c */ #line 1069 "css/CSSGrammar.y" { parser->startRuleHeader(CSSRuleSourceData::STYLE_RULE); parser->startSelector(); } break; case 178: /* Line 1806 of yacc.c */ #line 1076 "css/CSSGrammar.y" { parser->endRuleHeader(); } break; case 179: /* Line 1806 of yacc.c */ #line 1082 "css/CSSGrammar.y" { parser->endSelector(); } break; case 180: /* Line 1806 of yacc.c */ #line 1088 "css/CSSGrammar.y" { (yyval.rule) = parser->createStyleRule((yyvsp[(2) - (9)].selectorList)); } break; case 181: /* Line 1806 of yacc.c */ #line 1094 "css/CSSGrammar.y" { parser->startSelector(); } break; case 182: /* Line 1806 of yacc.c */ #line 1099 "css/CSSGrammar.y" { (yyval.selectorList) = parser->reusableSelectorVector(); (yyval.selectorList)->shrink(0); (yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(1) - (1)].selector))); } break; case 183: /* Line 1806 of yacc.c */ #line 1104 "css/CSSGrammar.y" { (yyval.selectorList) = (yyvsp[(1) - (6)].selectorList); (yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(6) - (6)].selector))); } break; case 186: /* Line 1806 of yacc.c */ #line 1114 "css/CSSGrammar.y" { (yyval.selector) = (yyvsp[(3) - (3)].selector); CSSParserSelector* end = (yyval.selector); while (end->tagHistory()) end = end->tagHistory(); end->setRelation(CSSSelector::Descendant); if ((yyvsp[(1) - (3)].selector)->isContentPseudoElement()) end->setRelationIsAffectedByPseudoContent(); end->setTagHistory(parser->sinkFloatingSelector((yyvsp[(1) - (3)].selector))); } break; case 187: /* Line 1806 of yacc.c */ #line 1124 "css/CSSGrammar.y" { (yyval.selector) = (yyvsp[(3) - (3)].selector); CSSParserSelector* end = (yyval.selector); while (end->tagHistory()) end = end->tagHistory(); end->setRelation((yyvsp[(2) - (3)].relation)); if ((yyvsp[(1) - (3)].selector)->isContentPseudoElement()) end->setRelationIsAffectedByPseudoContent(); end->setTagHistory(parser->sinkFloatingSelector((yyvsp[(1) - (3)].selector))); } break; case 188: /* Line 1806 of yacc.c */ #line 1137 "css/CSSGrammar.y" { (yyval.string).clear(); } break; case 189: /* Line 1806 of yacc.c */ #line 1138 "css/CSSGrammar.y" { static const LChar star = '*'; (yyval.string).init(&star, 1); } break; case 191: /* Line 1806 of yacc.c */ #line 1143 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, (yyvsp[(1) - (1)].string), parser->m_defaultNamespace)); } break; case 192: /* Line 1806 of yacc.c */ #line 1146 "css/CSSGrammar.y" { (yyval.selector) = parser->rewriteSpecifiersWithElementName(nullAtom, (yyvsp[(1) - (2)].string), (yyvsp[(2) - (2)].selector)); if (!(yyval.selector)) YYERROR; } break; case 193: /* Line 1806 of yacc.c */ #line 1151 "css/CSSGrammar.y" { (yyval.selector) = parser->rewriteSpecifiersWithNamespaceIfNeeded((yyvsp[(1) - (1)].selector)); if (!(yyval.selector)) YYERROR; } break; case 194: /* Line 1806 of yacc.c */ #line 1156 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelectorWithTagName(parser->determineNameInNamespace((yyvsp[(1) - (2)].string), (yyvsp[(2) - (2)].string))); if (!(yyval.selector)) YYERROR; } break; case 195: /* Line 1806 of yacc.c */ #line 1161 "css/CSSGrammar.y" { (yyval.selector) = parser->rewriteSpecifiersWithElementName((yyvsp[(1) - (3)].string), (yyvsp[(2) - (3)].string), (yyvsp[(3) - (3)].selector)); if (!(yyval.selector)) YYERROR; } break; case 196: /* Line 1806 of yacc.c */ #line 1166 "css/CSSGrammar.y" { (yyval.selector) = parser->rewriteSpecifiersWithElementName((yyvsp[(1) - (2)].string), starAtom, (yyvsp[(2) - (2)].selector)); if (!(yyval.selector)) YYERROR; } break; case 197: /* Line 1806 of yacc.c */ #line 1174 "css/CSSGrammar.y" { (yyval.selectorList) = parser->createFloatingSelectorVector(); (yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(1) - (1)].selector))); } break; case 198: /* Line 1806 of yacc.c */ #line 1178 "css/CSSGrammar.y" { (yyval.selectorList) = (yyvsp[(1) - (5)].selectorList); (yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(5) - (5)].selector))); } break; case 199: /* Line 1806 of yacc.c */ #line 1185 "css/CSSGrammar.y" { if (parser->m_context.isHTMLDocument()) parser->tokenToLowerCase((yyvsp[(1) - (1)].string)); (yyval.string) = (yyvsp[(1) - (1)].string); } break; case 200: /* Line 1806 of yacc.c */ #line 1190 "css/CSSGrammar.y" { static const LChar star = '*'; (yyval.string).init(&star, 1); } break; case 202: /* Line 1806 of yacc.c */ #line 1198 "css/CSSGrammar.y" { (yyval.selector) = parser->rewriteSpecifiers((yyvsp[(1) - (2)].selector), (yyvsp[(2) - (2)].selector)); } break; case 203: /* Line 1806 of yacc.c */ #line 1204 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::Id); if (isQuirksModeBehavior(parser->m_context.mode())) parser->tokenToLowerCase((yyvsp[(1) - (1)].string)); (yyval.selector)->setValue((yyvsp[(1) - (1)].string)); } break; case 204: /* Line 1806 of yacc.c */ #line 1211 "css/CSSGrammar.y" { if ((yyvsp[(1) - (1)].string)[0] >= '0' && (yyvsp[(1) - (1)].string)[0] <= '9') { YYERROR; } else { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::Id); if (isQuirksModeBehavior(parser->m_context.mode())) parser->tokenToLowerCase((yyvsp[(1) - (1)].string)); (yyval.selector)->setValue((yyvsp[(1) - (1)].string)); } } break; case 208: /* Line 1806 of yacc.c */ #line 1228 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::Class); if (isQuirksModeBehavior(parser->m_context.mode())) parser->tokenToLowerCase((yyvsp[(2) - (2)].string)); (yyval.selector)->setValue((yyvsp[(2) - (2)].string)); } break; case 209: /* Line 1806 of yacc.c */ #line 1238 "css/CSSGrammar.y" { if (parser->m_context.isHTMLDocument()) parser->tokenToLowerCase((yyvsp[(1) - (2)].string)); (yyval.string) = (yyvsp[(1) - (2)].string); } break; case 210: /* Line 1806 of yacc.c */ #line 1246 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setAttribute(QualifiedName(nullAtom, (yyvsp[(3) - (4)].string), nullAtom)); (yyval.selector)->setMatch(CSSSelector::Set); } break; case 211: /* Line 1806 of yacc.c */ #line 1251 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setAttribute(QualifiedName(nullAtom, (yyvsp[(3) - (8)].string), nullAtom)); (yyval.selector)->setMatch((CSSSelector::Match)(yyvsp[(4) - (8)].integer)); (yyval.selector)->setValue((yyvsp[(6) - (8)].string)); } break; case 212: /* Line 1806 of yacc.c */ #line 1257 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setAttribute(parser->determineNameInNamespace((yyvsp[(3) - (5)].string), (yyvsp[(4) - (5)].string))); (yyval.selector)->setMatch(CSSSelector::Set); } break; case 213: /* Line 1806 of yacc.c */ #line 1262 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setAttribute(parser->determineNameInNamespace((yyvsp[(3) - (9)].string), (yyvsp[(4) - (9)].string))); (yyval.selector)->setMatch((CSSSelector::Match)(yyvsp[(5) - (9)].integer)); (yyval.selector)->setValue((yyvsp[(7) - (9)].string)); } break; case 214: /* Line 1806 of yacc.c */ #line 1268 "css/CSSGrammar.y" { YYERROR; } break; case 215: /* Line 1806 of yacc.c */ #line 1274 "css/CSSGrammar.y" { (yyval.integer) = CSSSelector::Exact; } break; case 216: /* Line 1806 of yacc.c */ #line 1277 "css/CSSGrammar.y" { (yyval.integer) = CSSSelector::List; } break; case 217: /* Line 1806 of yacc.c */ #line 1280 "css/CSSGrammar.y" { (yyval.integer) = CSSSelector::Hyphen; } break; case 218: /* Line 1806 of yacc.c */ #line 1283 "css/CSSGrammar.y" { (yyval.integer) = CSSSelector::Begin; } break; case 219: /* Line 1806 of yacc.c */ #line 1286 "css/CSSGrammar.y" { (yyval.integer) = CSSSelector::End; } break; case 220: /* Line 1806 of yacc.c */ #line 1289 "css/CSSGrammar.y" { (yyval.integer) = CSSSelector::Contain; } break; case 223: /* Line 1806 of yacc.c */ #line 1300 "css/CSSGrammar.y" { if ((yyvsp[(2) - (2)].string).isFunction()) YYERROR; (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PagePseudoClass); parser->tokenToLowerCase((yyvsp[(2) - (2)].string)); (yyval.selector)->setValue((yyvsp[(2) - (2)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type == CSSSelector::PseudoUnknown) YYERROR; } break; case 224: /* Line 1806 of yacc.c */ #line 1313 "css/CSSGrammar.y" { if ((yyvsp[(3) - (3)].string).isFunction()) YYERROR; (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); parser->tokenToLowerCase((yyvsp[(3) - (3)].string)); (yyval.selector)->setValue((yyvsp[(3) - (3)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type == CSSSelector::PseudoUnknown) { parser->reportError((yyvsp[(2) - (3)].location), InvalidSelectorPseudoCSSError); YYERROR; } } break; case 225: /* Line 1806 of yacc.c */ #line 1326 "css/CSSGrammar.y" { if ((yyvsp[(4) - (4)].string).isFunction()) YYERROR; (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoElement); parser->tokenToLowerCase((yyvsp[(4) - (4)].string)); (yyval.selector)->setValue((yyvsp[(4) - (4)].string)); // FIXME: This call is needed to force selector to compute the pseudoType early enough. CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type == CSSSelector::PseudoUnknown) { parser->reportError((yyvsp[(3) - (4)].location), InvalidSelectorPseudoCSSError); YYERROR; } } break; case 226: /* Line 1806 of yacc.c */ #line 1341 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoElement); (yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(5) - (7)].selectorList))); (yyval.selector)->setValue((yyvsp[(3) - (7)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type != CSSSelector::PseudoCue) YYERROR; } break; case 227: /* Line 1806 of yacc.c */ #line 1350 "css/CSSGrammar.y" { YYERROR; } break; case 228: /* Line 1806 of yacc.c */ #line 1358 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); (yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(4) - (6)].selectorList))); parser->tokenToLowerCase((yyvsp[(2) - (6)].string)); (yyval.selector)->setValue((yyvsp[(2) - (6)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type != CSSSelector::PseudoAny) YYERROR; } break; case 229: /* Line 1806 of yacc.c */ #line 1368 "css/CSSGrammar.y" { YYERROR; } break; case 230: /* Line 1806 of yacc.c */ #line 1372 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); (yyval.selector)->setArgument((yyvsp[(4) - (6)].string)); (yyval.selector)->setValue((yyvsp[(2) - (6)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type == CSSSelector::PseudoUnknown) YYERROR; } break; case 231: /* Line 1806 of yacc.c */ #line 1382 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); (yyval.selector)->setArgument(AtomicString::number((yyvsp[(4) - (7)].integer) * (yyvsp[(5) - (7)].number))); (yyval.selector)->setValue((yyvsp[(2) - (7)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type == CSSSelector::PseudoUnknown) YYERROR; } break; case 232: /* Line 1806 of yacc.c */ #line 1392 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); (yyval.selector)->setArgument((yyvsp[(4) - (6)].string)); parser->tokenToLowerCase((yyvsp[(2) - (6)].string)); (yyval.selector)->setValue((yyvsp[(2) - (6)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type == CSSSelector::PseudoUnknown) YYERROR; else if (type == CSSSelector::PseudoNthChild || type == CSSSelector::PseudoNthOfType || type == CSSSelector::PseudoNthLastChild || type == CSSSelector::PseudoNthLastOfType) { if (!isValidNthToken((yyvsp[(4) - (6)].string))) YYERROR; } } break; case 233: /* Line 1806 of yacc.c */ #line 1409 "css/CSSGrammar.y" { YYERROR; } break; case 234: /* Line 1806 of yacc.c */ #line 1413 "css/CSSGrammar.y" { if (!(yyvsp[(4) - (6)].selector)->isSimple()) YYERROR; else { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); Vector<OwnPtr<CSSParserSelector> > selectorVector; selectorVector.append(parser->sinkFloatingSelector((yyvsp[(4) - (6)].selector))); (yyval.selector)->adoptSelectorVector(selectorVector); parser->tokenToLowerCase((yyvsp[(2) - (6)].string)); (yyval.selector)->setValue((yyvsp[(2) - (6)].string)); } } break; case 235: /* Line 1806 of yacc.c */ #line 1428 "css/CSSGrammar.y" { YYERROR; } break; case 236: /* Line 1806 of yacc.c */ #line 1431 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); (yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(4) - (6)].selectorList))); parser->tokenToLowerCase((yyvsp[(2) - (6)].string)); (yyval.selector)->setValue((yyvsp[(2) - (6)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type != CSSSelector::PseudoHost) YYERROR; } break; case 237: /* Line 1806 of yacc.c */ #line 1441 "css/CSSGrammar.y" { YYERROR; } break; case 238: /* Line 1806 of yacc.c */ #line 1445 "css/CSSGrammar.y" { (yyval.selector) = parser->createFloatingSelector(); (yyval.selector)->setMatch(CSSSelector::PseudoClass); (yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(4) - (6)].selectorList))); parser->tokenToLowerCase((yyvsp[(2) - (6)].string)); (yyval.selector)->setValue((yyvsp[(2) - (6)].string)); CSSSelector::PseudoType type = (yyval.selector)->pseudoType(); if (type != CSSSelector::PseudoHostContext) YYERROR; } break; case 239: /* Line 1806 of yacc.c */ #line 1455 "css/CSSGrammar.y" { YYERROR; } break; case 241: /* Line 1806 of yacc.c */ #line 1464 "css/CSSGrammar.y" { (yyval.boolean) = false; } break; case 243: /* Line 1806 of yacc.c */ #line 1466 "css/CSSGrammar.y" { (yyval.boolean) = (yyvsp[(1) - (2)].boolean) || (yyvsp[(2) - (2)].boolean); } break; case 245: /* Line 1806 of yacc.c */ #line 1473 "css/CSSGrammar.y" { parser->startProperty(); (yyval.boolean) = (yyvsp[(1) - (3)].boolean); } break; case 246: /* Line 1806 of yacc.c */ #line 1477 "css/CSSGrammar.y" { parser->startProperty(); (yyval.boolean) = (yyvsp[(1) - (4)].boolean) || (yyvsp[(2) - (4)].boolean); } break; case 247: /* Line 1806 of yacc.c */ #line 1484 "css/CSSGrammar.y" { (yyval.boolean) = false; bool isPropertyParsed = false; if ((yyvsp[(1) - (6)].id) != CSSPropertyInvalid) { parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(5) - (6)].valueList)); int oldParsedProperties = parser->m_parsedProperties.size(); (yyval.boolean) = parser->parseValue((yyvsp[(1) - (6)].id), (yyvsp[(6) - (6)].boolean)); if (!(yyval.boolean)) { parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties); parser->reportError((yyvsp[(4) - (6)].location), InvalidPropertyValueCSSError); } else isPropertyParsed = true; parser->m_valueList = nullptr; } parser->endProperty((yyvsp[(6) - (6)].boolean), isPropertyParsed); } break; case 248: /* Line 1806 of yacc.c */ #line 1501 "css/CSSGrammar.y" { /* When we encounter something like p {color: red !important fail;} we should drop the declaration */ parser->reportError((yyvsp[(4) - (8)].location), InvalidPropertyValueCSSError); parser->endProperty(false, false); (yyval.boolean) = false; } break; case 249: /* Line 1806 of yacc.c */ #line 1508 "css/CSSGrammar.y" { parser->reportError((yyvsp[(4) - (6)].location), InvalidPropertyValueCSSError); parser->endProperty(false, false); (yyval.boolean) = false; } break; case 250: /* Line 1806 of yacc.c */ #line 1514 "css/CSSGrammar.y" { parser->reportError((yyvsp[(3) - (4)].location), PropertyDeclarationCSSError); parser->endProperty(false, false, GeneralCSSError); (yyval.boolean) = false; } break; case 251: /* Line 1806 of yacc.c */ #line 1520 "css/CSSGrammar.y" { parser->reportError((yyvsp[(2) - (3)].location), PropertyDeclarationCSSError); (yyval.boolean) = false; } break; case 252: /* Line 1806 of yacc.c */ #line 1527 "css/CSSGrammar.y" { (yyval.id) = cssPropertyID((yyvsp[(2) - (3)].string)); parser->setCurrentProperty((yyval.id)); if ((yyval.id) == CSSPropertyInvalid) parser->reportError((yyvsp[(1) - (3)].location), InvalidPropertyCSSError); } break; case 253: /* Line 1806 of yacc.c */ #line 1536 "css/CSSGrammar.y" { (yyval.boolean) = true; } break; case 254: /* Line 1806 of yacc.c */ #line 1537 "css/CSSGrammar.y" { (yyval.boolean) = false; } break; case 255: /* Line 1806 of yacc.c */ #line 1541 "css/CSSGrammar.y" { (yyval.valueList) = parser->createFloatingValueList(); (yyval.valueList)->addValue(makeIdentValue((yyvsp[(1) - (2)].string))); } break; case 256: /* Line 1806 of yacc.c */ #line 1545 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(1) - (3)].valueList); (yyval.valueList)->addValue(makeIdentValue((yyvsp[(2) - (3)].string))); } break; case 257: /* Line 1806 of yacc.c */ #line 1552 "css/CSSGrammar.y" { (yyval.value).setFromValueList(parser->sinkFloatingValueList(parser->createFloatingValueList())); } break; case 258: /* Line 1806 of yacc.c */ #line 1555 "css/CSSGrammar.y" { (yyval.value).setFromValueList(parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList))); } break; case 259: /* Line 1806 of yacc.c */ #line 1558 "css/CSSGrammar.y" { YYERROR; } break; case 260: /* Line 1806 of yacc.c */ #line 1564 "css/CSSGrammar.y" { (yyval.valueList) = parser->createFloatingValueList(); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(1) - (1)].value))); } break; case 261: /* Line 1806 of yacc.c */ #line 1568 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(1) - (3)].valueList); (yyval.valueList)->addValue(makeOperatorValue((yyvsp[(2) - (3)].character))); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(3) - (3)].value))); } break; case 262: /* Line 1806 of yacc.c */ #line 1573 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(1) - (2)].valueList); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(2) - (2)].value))); } break; case 263: /* Line 1806 of yacc.c */ #line 1580 "css/CSSGrammar.y" { parser->reportError((yyvsp[(2) - (3)].location), PropertyDeclarationCSSError); } break; case 264: /* Line 1806 of yacc.c */ #line 1586 "css/CSSGrammar.y" { (yyval.character) = '/'; } break; case 265: /* Line 1806 of yacc.c */ #line 1589 "css/CSSGrammar.y" { (yyval.character) = ','; } break; case 267: /* Line 1806 of yacc.c */ #line 1596 "css/CSSGrammar.y" { (yyval.value) = (yyvsp[(2) - (3)].value); (yyval.value).fValue *= (yyvsp[(1) - (3)].integer); } break; case 268: /* Line 1806 of yacc.c */ #line 1597 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).isInt = false; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).unit = CSSPrimitiveValue::CSS_STRING; } break; case 269: /* Line 1806 of yacc.c */ #line 1598 "css/CSSGrammar.y" { (yyval.value) = makeIdentValue((yyvsp[(1) - (2)].string)); } break; case 270: /* Line 1806 of yacc.c */ #line 1600 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_DIMENSION; } break; case 271: /* Line 1806 of yacc.c */ #line 1601 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(2) - (3)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_DIMENSION; } break; case 272: /* Line 1806 of yacc.c */ #line 1602 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_URI; } break; case 273: /* Line 1806 of yacc.c */ #line 1603 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_UNICODE_RANGE; } break; case 274: /* Line 1806 of yacc.c */ #line 1604 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; } break; case 275: /* Line 1806 of yacc.c */ #line 1605 "css/CSSGrammar.y" { (yyval.value).id = CSSValueInvalid; (yyval.value).string = CSSParserString(); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; } break; case 278: /* Line 1806 of yacc.c */ #line 1609 "css/CSSGrammar.y" { /* Handle width: %; */ (yyval.value).id = CSSValueInvalid; (yyval.value).isInt = false; (yyval.value).unit = 0; } break; case 280: /* Line 1806 of yacc.c */ #line 1616 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number)); (yyval.value).isInt = true; } break; case 281: /* Line 1806 of yacc.c */ #line 1617 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number)); } break; case 282: /* Line 1806 of yacc.c */ #line 1618 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PERCENTAGE); } break; case 283: /* Line 1806 of yacc.c */ #line 1619 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PX); } break; case 284: /* Line 1806 of yacc.c */ #line 1620 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_CM); } break; case 285: /* Line 1806 of yacc.c */ #line 1621 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_MM); } break; case 286: /* Line 1806 of yacc.c */ #line 1622 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_IN); } break; case 287: /* Line 1806 of yacc.c */ #line 1623 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PT); } break; case 288: /* Line 1806 of yacc.c */ #line 1624 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PC); } break; case 289: /* Line 1806 of yacc.c */ #line 1625 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DEG); } break; case 290: /* Line 1806 of yacc.c */ #line 1626 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_RAD); } break; case 291: /* Line 1806 of yacc.c */ #line 1627 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_GRAD); } break; case 292: /* Line 1806 of yacc.c */ #line 1628 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_TURN); } break; case 293: /* Line 1806 of yacc.c */ #line 1629 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_MS); } break; case 294: /* Line 1806 of yacc.c */ #line 1630 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_S); } break; case 295: /* Line 1806 of yacc.c */ #line 1631 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_HZ); } break; case 296: /* Line 1806 of yacc.c */ #line 1632 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_KHZ); } break; case 297: /* Line 1806 of yacc.c */ #line 1633 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_EMS); } break; case 298: /* Line 1806 of yacc.c */ #line 1634 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSParserValue::Q_EMS); } break; case 299: /* Line 1806 of yacc.c */ #line 1635 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_EXS); } break; case 300: /* Line 1806 of yacc.c */ #line 1636 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_REMS); if (parser->m_styleSheet) parser->m_styleSheet->parserSetUsesRemUnits(true); } break; case 301: /* Line 1806 of yacc.c */ #line 1641 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_CHS); } break; case 302: /* Line 1806 of yacc.c */ #line 1642 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VW); } break; case 303: /* Line 1806 of yacc.c */ #line 1643 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VH); } break; case 304: /* Line 1806 of yacc.c */ #line 1644 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VMIN); } break; case 305: /* Line 1806 of yacc.c */ #line 1645 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VMAX); } break; case 306: /* Line 1806 of yacc.c */ #line 1646 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DPPX); } break; case 307: /* Line 1806 of yacc.c */ #line 1647 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DPI); } break; case 308: /* Line 1806 of yacc.c */ #line 1648 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DPCM); } break; case 309: /* Line 1806 of yacc.c */ #line 1649 "css/CSSGrammar.y" { (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_FR); } break; case 310: /* Line 1806 of yacc.c */ #line 1653 "css/CSSGrammar.y" { (yyval.value).setFromFunction(parser->createFloatingFunction((yyvsp[(1) - (4)].string), parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList)))); } break; case 311: /* Line 1806 of yacc.c */ #line 1656 "css/CSSGrammar.y" { (yyval.value).setFromFunction(parser->createFloatingFunction((yyvsp[(1) - (3)].string), parser->sinkFloatingValueList(parser->createFloatingValueList()))); } break; case 312: /* Line 1806 of yacc.c */ #line 1659 "css/CSSGrammar.y" { YYERROR; } break; case 314: /* Line 1806 of yacc.c */ #line 1666 "css/CSSGrammar.y" { (yyval.value) = (yyvsp[(2) - (2)].value); (yyval.value).fValue *= (yyvsp[(1) - (2)].integer); } break; case 315: /* Line 1806 of yacc.c */ #line 1670 "css/CSSGrammar.y" { (yyval.character) = '+'; } break; case 316: /* Line 1806 of yacc.c */ #line 1673 "css/CSSGrammar.y" { (yyval.character) = '-'; } break; case 317: /* Line 1806 of yacc.c */ #line 1676 "css/CSSGrammar.y" { (yyval.character) = '*'; } break; case 318: /* Line 1806 of yacc.c */ #line 1679 "css/CSSGrammar.y" { (yyval.character) = '/'; } break; case 321: /* Line 1806 of yacc.c */ #line 1690 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(3) - (5)].valueList); (yyval.valueList)->insertValueAt(0, makeOperatorValue('(')); (yyval.valueList)->addValue(makeOperatorValue(')')); } break; case 322: /* Line 1806 of yacc.c */ #line 1695 "css/CSSGrammar.y" { YYERROR; } break; case 323: /* Line 1806 of yacc.c */ #line 1701 "css/CSSGrammar.y" { (yyval.valueList) = parser->createFloatingValueList(); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(1) - (1)].value))); } break; case 324: /* Line 1806 of yacc.c */ #line 1705 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(1) - (3)].valueList); (yyval.valueList)->addValue(makeOperatorValue((yyvsp[(2) - (3)].character))); (yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(3) - (3)].value))); } break; case 325: /* Line 1806 of yacc.c */ #line 1710 "css/CSSGrammar.y" { (yyval.valueList) = (yyvsp[(1) - (3)].valueList); (yyval.valueList)->addValue(makeOperatorValue((yyvsp[(2) - (3)].character))); (yyval.valueList)->stealValues(*((yyvsp[(3) - (3)].valueList))); } break; case 327: /* Line 1806 of yacc.c */ #line 1719 "css/CSSGrammar.y" { (yyval.value).setFromFunction(parser->createFloatingFunction((yyvsp[(1) - (5)].string), parser->sinkFloatingValueList((yyvsp[(3) - (5)].valueList)))); } break; case 328: /* Line 1806 of yacc.c */ #line 1722 "css/CSSGrammar.y" { YYERROR; } break; case 332: /* Line 1806 of yacc.c */ #line 1738 "css/CSSGrammar.y" { parser->reportError((yyvsp[(2) - (3)].location), InvalidRuleCSSError); } break; case 338: /* Line 1806 of yacc.c */ #line 1752 "css/CSSGrammar.y" { parser->reportError((yyvsp[(4) - (5)].location), InvalidSupportsConditionCSSError); parser->popSupportsRuleData(); } break; case 339: /* Line 1806 of yacc.c */ #line 1756 "css/CSSGrammar.y" { parser->markViewportRuleBodyEnd(); } break; case 342: /* Line 1806 of yacc.c */ #line 1761 "css/CSSGrammar.y" { parser->resumeErrorLogging(); parser->reportError((yyvsp[(1) - (3)].location), InvalidRuleCSSError); } break; case 343: /* Line 1806 of yacc.c */ #line 1768 "css/CSSGrammar.y" { parser->reportError((yyvsp[(2) - (5)].location), InvalidRuleCSSError); } break; case 347: /* Line 1806 of yacc.c */ #line 1777 "css/CSSGrammar.y" { parser->reportError((yyvsp[(2) - (4)].location), InvalidRuleCSSError); } break; case 350: /* Line 1806 of yacc.c */ #line 1785 "css/CSSGrammar.y" { parser->endInvalidRuleHeader(); } break; case 351: /* Line 1806 of yacc.c */ #line 1791 "css/CSSGrammar.y" { parser->invalidBlockHit(); } break; case 362: /* Line 1806 of yacc.c */ #line 1807 "css/CSSGrammar.y" { (yyval.location) = parser->currentLocation(); } break; case 363: /* Line 1806 of yacc.c */ #line 1812 "css/CSSGrammar.y" { parser->setLocationLabel(parser->currentLocation()); } break; /* Line 1806 of yacc.c */ #line 5051 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp" default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now `shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*------------------------------------. | yyerrlab -- here on detecting error | `------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (parser, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (parser, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, parser); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule which action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, parser); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } *++yyvsp = yylval; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined(yyoverflow) || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (parser, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, parser); } /* Do not reclaim the symbols of the rule which action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, parser); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif /* Make sure YYID is used. */ return YYID (yyresult); } /* Line 2067 of yacc.c */ #line 1832 "css/CSSGrammar.y"
34.303179
207
0.496155
jingcao80
eb6bd3304473cf8f613568de2e21de57eb3ddedd
8,122
cpp
C++
src/platform/osx/main_carbon_old.cpp
guitarpukpui/OpenLara
4b73fad5664eadfe8c27f4d32e656f55aeddd177
[ "BSD-2-Clause" ]
3,999
2016-09-07T15:36:25.000Z
2022-03-31T14:54:44.000Z
src/platform/osx/main_carbon_old.cpp
guitarpukpui/OpenLara
4b73fad5664eadfe8c27f4d32e656f55aeddd177
[ "BSD-2-Clause" ]
333
2016-08-23T10:03:40.000Z
2022-03-31T13:25:19.000Z
src/platform/osx/main_carbon_old.cpp
guitarpukpui/OpenLara
4b73fad5664eadfe8c27f4d32e656f55aeddd177
[ "BSD-2-Clause" ]
403
2016-10-31T15:11:02.000Z
2022-03-31T15:03:52.000Z
#include "game.h" bool isQuit = false; WindowRef window; AGLContext context; #define SND_SIZE 8192 static AudioQueueRef audioQueue; void soundFill(void* inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { void* frames = inBuffer->mAudioData; UInt32 count = inBuffer->mAudioDataBytesCapacity / 4; Sound::fill((Sound::Frame*)frames, count); inBuffer->mAudioDataByteSize = count * 4; AudioQueueEnqueueBuffer(audioQueue, inBuffer, 0, NULL); // TODO: mutex } void soundInit() { AudioStreamBasicDescription deviceFormat; deviceFormat.mSampleRate = 44100; deviceFormat.mFormatID = kAudioFormatLinearPCM; deviceFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; deviceFormat.mBytesPerPacket = 4; deviceFormat.mFramesPerPacket = 1; deviceFormat.mBytesPerFrame = 4; deviceFormat.mChannelsPerFrame = 2; deviceFormat.mBitsPerChannel = 16; deviceFormat.mReserved = 0; AudioQueueNewOutput(&deviceFormat, soundFill, NULL, NULL, NULL, 0, &audioQueue); for (int i = 0; i < 2; i++) { AudioQueueBufferRef mBuffer; AudioQueueAllocateBuffer(audioQueue, SND_SIZE, &mBuffer); soundFill(NULL, audioQueue, mBuffer); } AudioQueueStart(audioQueue, NULL); } // common input functions InputKey keyToInputKey(int code) { static const int codes[] = { 0x7B, 0x7C, 0x7E, 0x7D, 0x31, 0x24, 0x35, 0x38, 0x3B, 0x3A, 0x1D, 0x12, 0x13, 0x14, 0x15, 0x17, 0x16, 0x1A, 0x1C, 0x19, // 0..9 0x00, 0x0B, 0x08, 0x02, 0x0E, 0x03, 0x05, 0x04, 0x22, 0x26, 0x28, 0x25, 0x2E, // A..M 0x2D, 0x1F, 0x23, 0x0C, 0x0F, 0x01, 0x11, 0x20, 0x09, 0x0D, 0x07, 0x10, 0x06, // N..Z }; for (int i = 0; i < sizeof(codes) / sizeof(codes[0]); i++) if (codes[i] == code) return (InputKey)(ikLeft + i); return ikNone; } InputKey mouseToInputKey(int btn) { switch (btn) { case 1 : return ikMouseL; case 2 : return ikMouseR; case 3 : return ikMouseM; } return ikNone; } OSStatus eventHandler(EventHandlerCallRef handler, EventRef event, void* userData) { OSType eventClass = GetEventClass(event); UInt32 eventKind = GetEventKind(event); switch (eventClass) { case kEventClassWindow : switch (eventKind) { case kEventWindowClosed : isQuit = true; break; case kEventWindowBoundsChanged : { aglUpdateContext(context); Rect rect; GetWindowPortBounds(window, &rect); Core::width = rect.right - rect.left; Core::height = rect.bottom - rect.top; break; } } break; case kEventClassMouse : { EventMouseButton mouseButton; CGPoint mousePos; Rect wndRect; GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, NULL, sizeof(mousePos), NULL, &mousePos); GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL, sizeof(mouseButton), nil, &mouseButton); GetWindowBounds(window, kWindowContentRgn, &wndRect); mousePos.x -= wndRect.left; mousePos.y -= wndRect.top; vec2 pos(mousePos.x, mousePos.y); switch (eventKind) { case kEventMouseDown : case kEventMouseUp : { InputKey key = mouseToInputKey(mouseButton); Input::setPos(key, pos); Input::setDown(key, eventKind == kEventMouseDown); break; } case kEventMouseDragged : Input::setPos(ikMouseL, pos); break; } break; } case kEventClassKeyboard : { switch (eventKind) { case kEventRawKeyDown : case kEventRawKeyUp : { uint32 keyCode; if (GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, sizeof(keyCode), NULL, &keyCode) == noErr) Input::setDown(keyToInputKey(keyCode), eventKind != kEventRawKeyUp); break; } case kEventRawKeyModifiersChanged : { uint32 modifiers; if (GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(modifiers), NULL, &modifiers) == noErr) { Input::setDown(ikShift, modifiers & shiftKey); Input::setDown(ikCtrl, modifiers & controlKey); Input::setDown(ikAlt, modifiers & optionKey); } break; } } break; } } return CallNextEventHandler(handler, event); } int getTime() { UInt64 t; Microseconds((UnsignedWide*)&t); return int(t / 1000); } char *contentPath; int main() { // init window Rect rect = {0, 0, 720, 1280}; CreateNewWindow(kDocumentWindowClass, kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowFullZoomAttribute | kWindowResizableAttribute | kWindowStandardHandlerAttribute, &rect, &window); SetWTitle(window, "\pOpenLara"); // init OpenGL context GLint attribs[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_BUFFER_SIZE, 32, AGL_DEPTH_SIZE, 24, AGL_STENCIL_SIZE, 8, AGL_NONE }; AGLPixelFormat format = aglChoosePixelFormat(NULL, 0, (GLint*)&attribs); context = aglCreateContext(format, NULL); aglDestroyPixelFormat(format); aglSetDrawable(context, GetWindowPort(window)); aglSetCurrentContext(context); // get path to game content CFBundleRef bundle = CFBundleGetMainBundle(); CFURLRef bundleURL = CFBundleCopyBundleURL(bundle); CFStringRef pathStr = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle); contentPath = new char[1024]; CFStringGetFileSystemRepresentation(pathStr, contentPath, 1024); strcat(contentPath, "/Contents/Resources/"); soundInit(); Game::init(); // show window const int events[][2] = { { kEventClassWindow, kEventWindowClosed }, { kEventClassWindow, kEventWindowBoundsChanged }, { kEventClassKeyboard, kEventRawKeyDown }, { kEventClassKeyboard, kEventRawKeyUp }, { kEventClassKeyboard, kEventRawKeyModifiersChanged }, { kEventClassMouse, kEventMouseDown }, { kEventClassMouse, kEventMouseUp }, { kEventClassMouse, kEventMouseDragged }, }; InstallEventHandler(GetApplicationEventTarget(), (EventHandlerUPP)eventHandler, sizeof(events) / sizeof(events[0]), (EventTypeSpec*)&events, NULL, NULL); SelectWindow(window); ShowWindow(window); int lastTime = getTime(), fpsTime = lastTime + 1000, fps = 0; EventRecord event; while (!isQuit) if (!GetNextEvent(0xffff, &event)) { int time = getTime(); if (time <= lastTime) continue; float delta = (time - lastTime) * 0.001f; while (delta > EPS) { Core::deltaTime = min(delta, 1.0f / 30.0f); Game::update(); delta -= Core::deltaTime; } lastTime = time; Core::stats.dips = 0; Core::stats.tris = 0; Game::render(); aglSwapBuffers(context); if (fpsTime < getTime()) { LOG("FPS: %d DIP: %d TRI: %d\n", fps, Core::stats.dips, Core::stats.tris); fps = 0; fpsTime = getTime() + 1000; } else fps++; } Game::free(); delete[] contentPath; // TODO: sndFree aglSetCurrentContext(NULL); ReleaseWindow(window); return 0; }
34.270042
203
0.575967
guitarpukpui
eb71541b97afe7d8bded1d4c273baa49503822ee
22,796
cpp
C++
mllib/LogisticRegression.cpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
1
2019-01-23T02:10:10.000Z
2019-01-23T02:10:10.000Z
mllib/LogisticRegression.cpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
null
null
null
mllib/LogisticRegression.cpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
null
null
null
/* Edit by Christina */ #include "LogisticRegression.hpp" namespace husky{ namespace mllib{ /* train a logistic regression model with even weighted instances. */ void LogisticRegression::fit(const Instances& instances){ if(this->mode == MODE::GLOBAL){ global_fit(instances); } else if(this->mode == MODE::LOCAL){ local_fit(instances); } else{ throw std::invalid_argument("MODE " + std::to_string((int)mode) + " dosen't exit! Only 0(GLOBAL) and 1(LOCAL) mode are provided."); } } /* train a logistic regression model using instance weight, which is specified as a attribute list of original_instances, name of which is 'instance_weight_name'. */ void LogisticRegression::fit(const Instances& instances, std::string instance_weight_name){ if(this->mode == MODE::GLOBAL){ global_fit(instances, instance_weight_name); } else if(this->mode == MODE::LOCAL){ local_fit(instances, instance_weight_name); } else{ throw std::invalid_argument("MODE " + std::to_string((int)mode) + " dosen't exit! Only 0(GLOBAL) and 1(LOCAL) mode are provided."); } } /* train model in global mode. */ void LogisticRegression::global_fit(const Instances& instances){ const int num_attri = instances.numAttributes; matrix_double init_mat; for(int i = 1; i < this->class_num; i++){ init_mat.push_back(vec_double(num_attri + 1, 0.0)); } husky::lib::Aggregator<matrix_double> para_mat(init_mat, [](matrix_double& a, const matrix_double& b){ a += b;}, [num_attri, this](matrix_double& m){ m.clear(); for(int i = 1; i < this->class_num; i++){ m.push_back(vec_double(num_attri + 1, 0.0)); } }); husky::lib::Aggregator<double> global_squared_error(0.0, [](double& a, const double& b){ a += b;}, [](double& v){ v = 0; } ); global_squared_error.to_reset_each_iter(); auto& ac = husky::lib::AggregatorFactory::get_channel(); double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } matrix_double para_update; for(int i = 1; i < this->class_num; i++){ para_update.push_back(vec_double(num_attri + 1, 0.0)); } matrix_double para_old = para_mat.get_value(); vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {&ac}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num - 1; x++){ class_prob_tmp[x] = exp(para_old[x] * x_with_const_term); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and udpate with regularization auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; global_squared_error.update(class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ para_update[x] -= (eta * class_prob_tmp[x] * x_with_const_term); } }); //to do the division only once. para_update /= instances.numInstances; //add regularization double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = para_old[x].back(); para_old[x].back() = 0; para_update[x] -= (eta * alpha * para_old[x]); para_old[x].back() = tmp; } para_mat.update(para_update); double weighted_squared_error = global_squared_error.get_value() / instances.numInstances; //output the training infor. if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tGlobal averaged squared error: " + std::to_string(weighted_squared_error)); } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; husky::lib::AggregatorFactory::sync(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tParameters: " + matrix_to_str(para_mat.get_value())); } } this->param_matrix = para_mat.get_value(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } void LogisticRegression::global_fit(const Instances& instances, std::string instance_weight_name){ const int num_attri = instances.numAttributes; matrix_double init_mat; for(int i = 1; i < this->class_num; i++){ init_mat.push_back(vec_double(num_attri + 1, 0.0)); } husky::lib::Aggregator<matrix_double> para_mat(init_mat, [](matrix_double& a, const matrix_double& b){ a += b;}, [num_attri, this](matrix_double& m){ m.clear(); for(int i = 1; i < this->class_num; i++){ m.push_back(vec_double(num_attri + 1, 0.0)); } }); husky::lib::Aggregator<double> global_squared_error(0.0, [](double& a, const double& b){ a += b;}, [](double& v){ v = 0; } ); global_squared_error.to_reset_each_iter(); auto& ac = husky::lib::AggregatorFactory::get_channel(); auto& weight_attrList = instances.getAttrlist<double>(instance_weight_name); double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } matrix_double para_update; for(int i = 1; i < this->class_num; i++){ para_update.push_back(vec_double(num_attri + 1, 0.0)); } matrix_double para_old = para_mat.get_value(); vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {&ac}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num - 1; x++){ class_prob_tmp[x] = exp(x_with_const_term * para_old[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and udpate with regularization double weight = weight_attrList.get(instance); auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; global_squared_error.update(weight * class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ para_update[x] -= (weight * eta * class_prob_tmp[x] * x_with_const_term); } }); double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = para_old[x].back(); para_old[x].back() = 0; para_update[x] -= (eta * alpha * para_old[x]); para_old[x].back() = tmp; } para_mat.update(para_update); double weighted_squared_error = global_squared_error.get_value(); //output the training infor. if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tGlobal averaged squared error: " + std::to_string(weighted_squared_error)); } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; husky::lib::AggregatorFactory::sync(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tParameters: " + matrix_to_str(para_mat.get_value())); } } this->param_matrix = para_mat.get_value(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } /* train model in local mode. */ void LogisticRegression::local_fit(const Instances& instances){ int num_attri = instances.numAttributes; matrix_double param_update; for(int i = 1; i < this->class_num; i++){ param_matrix.push_back(vec_double(num_attri + 1, 0.0)); param_update.push_back(vec_double(num_attri + 1, 0.0)); } double weighted_squared_error = 0; double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //count how many instances in local machine int num_instances_local = 0; list_execute(instances.enumerator(),{},{}, [&num_instances_local](Instance& instance){ num_instances_local++; } ); //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ /* if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } */ //reset variables weighted_squared_error = 0; for(int i = 0; i < this->class_num-1; i++){ param_update[i].assign(num_attri + 1, 0.0); } vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num-1; x++ ){ class_prob_tmp[x] = exp(x_with_const_term * param_matrix[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and update auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; weighted_squared_error += (class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ param_update[x] -= (eta * class_prob_tmp[x] * x_with_const_term); } } ); //update parameters. param_update /= num_instances_local; //regularization term double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = param_matrix[x].back(); param_matrix[x].back() = 0; param_update[x] -= (eta * alpha * param_matrix[x]); param_matrix[x].back() = tmp; } param_matrix += param_update; weighted_squared_error /= num_instances_local; //output local error. if(husky::Context::get_global_tid() == 0){ husky::base::log_msg("Iter#" + std::to_string(iter) + "\n" + "Local averaged squared error: " + std::to_string(weighted_squared_error) + "\n" + "Parameters: " + matrix_to_str(param_matrix)); //std::cout<<"Parameters: " + matrix_to_str(param_matrix)<<std::endl; } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; } if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } void LogisticRegression::local_fit(const Instances& instances, std::string instance_weight_name){ int num_attri = instances.numAttributes; matrix_double param_update; for(int i = 1; i < this->class_num; i++){ param_matrix.push_back(vec_double(num_attri + 1, 0.0)); param_update.push_back(vec_double(num_attri + 1, 0.0)); } auto& weight_attrList = instances.getAttrlist<double>(instance_weight_name); double weighted_squared_error = 0; double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //count how many instances in local machine int num_instances_local = 0; list_execute(instances.enumerator(),{},{}, [&num_instances_local](Instance& instance){ num_instances_local++; } ); //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ /* if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } */ //reset variables weighted_squared_error = 0; for(int i = 0; i < this->class_num-1; i++){ param_update[i].assign(num_attri + 1, 0.0); } vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num-1; x++ ){ class_prob_tmp[x] = exp(x_with_const_term * param_matrix[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and update double weight = weight_attrList.get(instance); auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; weighted_squared_error += (weight * class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ param_update[x] -= (weight * eta * class_prob_tmp[x] * x_with_const_term); } } ); //regularization term double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = param_matrix[x].back(); param_matrix[x].back() = 0; param_update[x] -= (eta * alpha * param_matrix[x]); param_matrix[x].back() = tmp; } param_matrix += param_update; weighted_squared_error /= num_instances_local; //output local error. if(husky::Context::get_global_tid() == 0){ husky::base::log_msg("Iter#" + std::to_string(iter) + "\n" + "Local averaged squared error: " + std::to_string(weighted_squared_error) + "\n" + "Parameters: " + matrix_to_str(param_matrix)); } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; } if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } /* * predict #prediciton contains label and class_proba in it. */ AttrList<Instance, Prediction>& LogisticRegression::predict(const Instances& instances,std::string prediction_name){ if(this->mode == MODE::LOCAL){ throw std::invalid_argument("Prediciton is not provided after training in LOCAL mode!"); } AttrList<Instance, Prediction>& prediction = instances.enumerator().has_attrlist(prediction_name)? instances.getAttrlist<Prediction>(prediction_name) : instances.createAttrlist<Prediction>(prediction_name); list_execute(instances.enumerator(), [&prediction, this](Instance& instance) { vec_double feature_vector=instance.X; feature_vector.push_back(1); //calculate probability vec_double class_prob_tmp(class_num, 0.0); double sum_tmp = 0; for(int x = 0; x < class_num-1; x++ ){ class_prob_tmp[x] = exp(feature_vector * param_matrix[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //choose label with highest probability double max_p = 0; int label; for(int x = 0; x < class_num; x++){ if(class_prob_tmp[x] > max_p){ max_p = class_prob_tmp[x]; label = x; } } prediction.set(instance, Prediction(label, class_prob_tmp)); }); return prediction; } } }
41.372051
217
0.469995
Christina-hshi
eb71b86555363e03ff019f9cb0f704a08eee1358
993
cpp
C++
binarysearch.io/easy/Pattern-to-Word-Bijection.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
binarysearch.io/easy/Pattern-to-Word-Bijection.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
binarysearch.io/easy/Pattern-to-Word-Bijection.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Pattern to Word Bijection https://binarysearch.com/problems/Pattern-to-Word-Bijection Given two strings s and p, return whether s follows the pattern in p. That is, return whether each character in p can map to a non-empty word such that it maps to s. Constraints n ≤ 100,000 where n is the length of s Example 1 Input s = "hello world world world hello" p = "abbba" Output true Explanation We can map "a" = "hello" and "b" = "world". */ #include "solution.hpp" using namespace std; class Solution { public: bool solve(string s, string p) { unordered_map<string, int> m; istringstream iss(s); string ss; int i = 0; while(iss>>ss){ if(m.count(ss)) { if(m[ss]!=p[i]) return false; } else { for(auto& k: m) { if(k.second == p[i]) return false; } m[ss]=p[i]; } i++; } return true; } };
21.586957
165
0.548842
wingkwong
eb72e694c102b2bb60e3fe5302265c496d152d95
1,023
cpp
C++
coj.uci.cu/TobyandStrangeFunction.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
coj.uci.cu/TobyandStrangeFunction.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
coj.uci.cu/TobyandStrangeFunction.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://coj.uci.cu/contest/cproblem.xhtml?pid=3285&cid=1453 Name: Toby and Strange Function Date: 05/06/2015 */ #include <bits/stdc++.h> #define time alkjdhasjldh3289rhau9dty #define EPS 1e-9 #define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl const double PI = 2.0*acos(0.0); #define INF 1000000000 //#define MOD 1000000007ll //#define MAXN 10000100 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, ii> iii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iii> viii; ll n; string s; int main () { ios_base::sync_with_stdio(0); cin.tie(0); //cout<<fixed<<setprecision(7); cerr<<fixed<<setprecision(7); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) << 25 int tc, i, j; cin>>tc; while (tc--) { cin>>n>>s; n %= s.length(); for (i=(int)s.length()-n; i<s.length(); i++) cout<<s[i]; n = (int)s.length()-n; for (i=0; i<n; i++) cout<<s[i]; cout<<"\n"; } return 0; }
23.790698
130
0.601173
facug91
eb72f6cf6bc90672f7810f4002e36f7f24fc13fa
4,221
cpp
C++
src/Annoyme.cpp
dedeibel/annoyme
d1483f6ef2dd7bfd851f67a12154eaae08ab7a14
[ "BSD-3-Clause" ]
1
2016-05-08T14:05:15.000Z
2016-05-08T14:05:15.000Z
src/Annoyme.cpp
dedeibel/annoyme
d1483f6ef2dd7bfd851f67a12154eaae08ab7a14
[ "BSD-3-Clause" ]
null
null
null
src/Annoyme.cpp
dedeibel/annoyme
d1483f6ef2dd7bfd851f67a12154eaae08ab7a14
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2009, Benjamin Peter <BenjaminPeter@arcor.de> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author 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 Benjamin Peter ''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 Benjamin Peter BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <iostream> #include <map> #include <vector> #include <cstring> using namespace std; #include "exceptions.h" #include "config/Configuration.h" #include "config/BasicConfiguration.h" #include "config/AnnoymeConfiguration.h" // Input #include "Event.h" #include "InputEventReader.h" #include "InputEventReaderFactory.h" // Sound #include "Sample.h" #include "SoundOutput.h" #include "SoundOutputFactory.h" #include "SoundLoader.h" #include "SoundLoaderFactory.h" // Flow #include "SoundOutputAdapter.h" #include "InputEventHandler.h" #include "HandlerSoundOutput.h" #include "Dispatcher.h" #include "Annoyme.h" Annoyme::Annoyme() : m_input(0) , m_soundLoader(0) , m_soundOutput(0) , m_soundOutputAdapter(0) , m_inputEventHandler(0) , m_dispatcher(0) { } Annoyme::~Annoyme() { if (m_dispatcher != 0) delete m_dispatcher; if (m_inputEventHandler != 0) delete m_inputEventHandler; if (m_soundOutputAdapter != 0) delete m_soundOutputAdapter; if (m_soundOutput != 0) delete m_soundOutput; if (m_soundLoader != 0) delete m_soundLoader; if (m_input != 0) delete m_input; } void Annoyme::init() throw(AnnoymeException) { AnnoymeConfiguration::getInstance(); cout << "Creating key input reader.\n"; m_input = InputEventReaderFactory::getInstance()->getInputEventReader( AnnoymeConfiguration::value("input.reader")); cout << "Creating sound file loader.\n"; m_soundLoader = SoundLoaderFactory::getInstance()->getSoundLoader( AnnoymeConfiguration::value("sound.loader")); cout << "Creating sound output.\n"; m_soundOutput = SoundOutputFactory::getInstance()->getSoundOutput( AnnoymeConfiguration::value("sound.output"), AnnoymeConfiguration::value("sound.alsa.device")); cout << "Loading sound files.\n"; m_soundLoader->loadFiles(AnnoymeConfiguration::value("sample_theme")); cout << "Opening sound output.\n"; m_soundOutput->open(); cout << "Opening event input.\n"; m_input->open(); m_soundOutputAdapter = new SoundOutputAdapter(m_soundLoader, m_soundOutput); m_inputEventHandler = new HandlerSoundOutput(m_soundOutputAdapter); m_dispatcher = new Dispatcher(m_input, m_inputEventHandler); cout << "Initializing dispatcher.\n"; m_dispatcher->init(); } void Annoyme::run() { cout << "Starting dispatcher.\n"; m_dispatcher->run(); } void Annoyme::close() { if (m_dispatcher != 0) m_dispatcher->close(); if (m_input != 0) m_input->close(); if (m_soundOutput != 0) m_soundOutput->close(); }
32.976563
80
0.712627
dedeibel
eb73ab3a66218537f23186db3af24c050776d106
8,738
cpp
C++
cpp/OS/std/lang/String.cpp
mailmindlin/MMOS
a2e6c0afafe2c13f864c5620ea2a2707ab676767
[ "MIT" ]
null
null
null
cpp/OS/std/lang/String.cpp
mailmindlin/MMOS
a2e6c0afafe2c13f864c5620ea2a2707ab676767
[ "MIT" ]
null
null
null
cpp/OS/std/lang/String.cpp
mailmindlin/MMOS
a2e6c0afafe2c13f864c5620ea2a2707ab676767
[ "MIT" ]
null
null
null
/* * String.cpp * * Created on: Feb 19, 2015 * Author: mailmindlin */ #include "String.h" #include "../algorithm.h" #include "../limits.h" #include "../memory.h" #include "../Math.h" #include "../strlen.h" #include "Double.h" #include "Integer.h" #include "Long.h" String::String(const String& str) : size(str.length) { expand(); for (size_t i = 0; i < str.length(); i++) this->data[i] = str.data[i]; } String::String(const String& str, size_t pos, size_t len) : size(len) { expand(); for (size_t i = 0; i < len; i++) if ((this->data[i] = str.data[i + pos]) == 0) break; } String::String(const char* s) : size(strlen(s)) { expand(); for (size_t i = 0; i < length; i++) data[i] = s[i]; } String::String(const char* s, size_t n) : size(n) { expand(); for (size_t i = 0; i < n; i++) data[i] = s[i]; } String::String(size_t n, char c) : size(n) { expand(); for (size_t i = 0; i < length; i++) data[i] = c; } String::String(size_t length) : size(length) { expand(); } String& String::operator =(const String& str) { if (str == this) return this; String * result = new String(str); delete this; return result; } String& String::operator =(const char* s) { String * result = new String(s); delete this; return result; } String& String::operator =(char c) { String * result = new String(1, c); delete this; return result; } String& String::operator +(const char* c) { return new String(c); } String& String::operator +(const String& str) { return concat(str); } bool String::isEmpty() const { return length() == 0; } char String::charAt(unsigned int index) { return data[index]; } String::~String() { delete data; } String& String::concat(const char* c) { size_t len = strlen(c); String* result = new String(length() + len); for (size_t i = 0; i < length(); i++) result->data[i] = this->data[i]; for (size_t i = 0; i < len; i++) result->data[i + length()] = c[i]; return result; } String& String::concat(const String& str) { String* result = new String(length() + str.length()); for (size_t i = 0; i < length(); i++) result->data[i] = this->data[i]; for (size_t i = 0; i < str.length(); i++) result->data[i + length()] = str.data[i]; return result; } bool String::contains(const char* c) const { return indexOf(c) != SIZE_T_MAX; } bool String::contains(String& str) const { return indexOf(str) != SIZE_T_MAX; } bool String::endsWith(String& suffix) const { return indexOf(suffix) == length() - suffix.length(); } bool String::equals(Object o) const { if (o == this) return true; if (!o.instanceof<String>()) return false; String s = dynamic_cast<String>(o); if (s.length() != length()) return false; for (size_t i = 0; i < length(); i++) if (s.data[i] != data[i]) return false; return true; } bool String::equalsIgnoreCase(String& str) const { if (str == this) return true; if (str.length() != length()) return false; return str.toLowerCase().equals(toLowerCase()); } void String::getChars(size_t srcBegin, size_t srcEnd, char* dst, size_t dstBegin) const { const size_t delta = dstBegin - srcBegin; for (size_t i = srcBegin; i < srcEnd; i++) dst[i] = data[i + delta]; } size_t String::indexOf(char c) const { return indexOf(c, 0); } size_t String::indexOf(char c, size_t start) const { for (size_t i = 0; i < length(); i++) if (data[i] == c) return i; return SIZE_T_MAX; } size_t String::indexOf(String& str) const { return indexOf(str, 0); } size_t String::indexOf(String& str, size_t start) const { const size_t len = str.length(); for (size_t i = start; i < length() - len; i++) { bool match = true; for (size_t j = 0; match && j < len; j++) match = (data[i + j] == str.data[j]) && match; if (match) return i; } return SIZE_T_MAX; } size_t String::indexOf(const char* c) const { return indexOf(c, 0); } size_t String::indexOf(const char* c, size_t start) const { const size_t len = strlen(c); for (size_t i = start; i < length() - len; i++) { bool match = true; for (size_t j = 0; match && j < len; j++) match = (data[i + j] == c[j]) && match; if (match) return i; } return SIZE_T_MAX; } size_t String::lastIndexOf(char c) { return lastIndexOf(c, length()); } size_t String::lastIndexOf(char c, size_t fromIndex) { for (size_t i = fromIndex - 1; i > 0; i--) if (data[i] == c) return i; return SIZE_T_MAX; } size_t String::lastIndexOf(String& str) { return this->lastIndexOf(str, length()); } size_t String::lastIndexOf(String& str, size_t fromIndex) { for (size_t i = Math::min(fromIndex, length() - str.length()); i > 0; i--) { bool match = true; for (size_t j = 0; match && j < str.length(); j++) match = (data[i + j] == str.data[j]) && match; if (match) return i; } return SIZE_T_MAX; } size_t String::length() const { return size; } bool String::regionMatches(bool ignoreCase, size_t toffset, String& other, size_t oofset, size_t len) { if (ignoreCase) return substring(toffset, toffset + len).equalsIgnoreCase(other.substring(oofset, oofset + len)); else return substring(toffset, toffset + len).equals(other.substring(oofset, oofset + len)); } String& String::replace(char oldChar, char newChar) { String * result = new String(length()); for (size_t i = 0; i < length(); i++) result->data[i] = (data[i] == oldChar ? newChar : data[i]); return result; } String& String::replace(const char* target, const char* replacement) { String * result = this; const size_t targlen = strlen(target); const size_t repllen = strlen(replacement); int index; while ((index = result->indexOf(target)) > -1) { String*tmp = result; result = tmp->substring(0, index) + target + tmp->substring(index + repllen, tmp->length()); delete tmp; } if (result == this) result = new String(this); return result; } String& String::replace(String& target, String& replacement) { String * result = this; const size_t targlen = target.length(); const size_t repllen = replacement.length(); int index; while ((index = result->indexOf(target)) > -1) { String*tmp = result; result = tmp->substring(0, index) + target + tmp->substring(index + repllen, tmp->length()); delete tmp; } if (result == this) result = new String(this); return result; } bool String::startsWith(String& prefix) { return indexOf(prefix) == 0; } bool String::startsWith(String& prefix, size_t toffset) { return this->regionMatches(false, toffset, prefix, 0, prefix.length()); } char* String::subSequence(size_t beginIndex, size_t endIndex) { return substring(beginIndex, endIndex).toCharArray(); } String& String::substring(size_t beginIndex) { return substring(beginIndex, length()); } String& String::substring(size_t beginIndex, size_t endIndex) { String* result = new String(endIndex - beginIndex); for (size_t i = beginIndex; i < endIndex; i++) result->data[i - beginIndex] = data[i]; return result; } char* String::toCharArray() const { char* result = new char[length()]; Array::copy(this->data, result, 0, 0, length()); return result; } String& String::toLowerCase() const { String* result = new String(length()); for (size_t i = 0; i < length(); i++) result->data[i] = std::toLower(data[i]); return result; } String& String::toString() const { return &*this; } String& String::toUpperCase() const { String* result = new String(length()); for (size_t i = 0; i < length(); i++) result->data[i] = std::toUpper(data[i]); return result; } String& String::trim() const { size_t b = 0, e = 0; for (b = 0; b < length() && (data[b] == ' ' || data[b] == '\t' || data[b] == '\n'); b++) { } for (e = length() - 1; e > b && (data[e] == ' ' || data[e] == '\t' || data[e] == '\n'); e--) { } String* result = new String(e - b); Array::copy(data, result->data, b, 0, e - b); return result; } String& String::valueOf(bool b) { return new String(b ? "true" : "false"); } String& String::valueOf(char c) { return new String(c, 1); } String& String::valueOf(const char* c) { return new String(c); } String& String::valueOf(char* data, size_t offset, size_t count) { return new String(data, offset, count); } String& String::valueOf(double d, size_t radix) { return Double::stringFor(d, radix); } String& String::valueOf(double d) { return Double::stringFor(d); } String& String::valueOf(float f) { return &nullptr; //TODO finish } String& String::valueOf(int i, size_t radix) { return Integer::stringFor(i, radix); } String& String::valueOf(long l, size_t radix) { return Long::stringFor(l, radix); } String& String::valueOfPtr(const void* ptr) { return valueOf((int) ptr, 16); } String& String::valueOf(Object& obj) { return obj.toString(); } void String::expand() { data = new char[size]; }
23.177719
103
0.63859
mailmindlin
eb765ec6e408bf6b2d058d5fc59b6849a5233b36
4,254
hpp
C++
hostsvc/Connection.hpp
lishunan246/b
82023dee34b023dfbc3dd2f0381fdbd7e266604e
[ "BSD-2-Clause" ]
null
null
null
hostsvc/Connection.hpp
lishunan246/b
82023dee34b023dfbc3dd2f0381fdbd7e266604e
[ "BSD-2-Clause" ]
null
null
null
hostsvc/Connection.hpp
lishunan246/b
82023dee34b023dfbc3dd2f0381fdbd7e266604e
[ "BSD-2-Clause" ]
null
null
null
// // Created by lishunan on 4/19/16. // #ifndef HOSTSVC_RPCCHANNEL_H #define HOSTSVC_RPCCHANNEL_H #include "HostSvcCommon.hpp" #include <unordered_map> using namespace google::protobuf; namespace GkcHostSvc { using messageHandler = function<void(RPCResponse)>; class Connection : public protobuf::RpcChannel { private: std::condition_variable cv; std::mutex m; std::atomic<bool> connected{ false }; std::unordered_map<string, messageHandler> handlerMap; RPCResponse response1; int _clientID = -1; WebsocketClient _WSclient; shared_ptr < WebsocketConnecton> con; shared_ptr<thread> pthread; char pSend[1000]; public: static shared_ptr<Connection> create(const string &server) { return make_shared<Connection>(server); } void registerHandler(const string& s,messageHandler h) { handlerMap.insert({ s,h }); } Connection(const string &server) { _WSclient.init_asio(); _WSclient.start_perpetual(); _WSclient.set_access_channels(websocketpp::log::alevel::none); _WSclient.set_open_handler([this](websocketpp::connection_hdl hdl) { this->connected = true; cout << "connected" << endl; }); _WSclient.set_message_handler([this](websocketpp::connection_hdl hdl,WebsocketClient::message_ptr msg) { auto _respondString = msg->get_payload(); //cout << msg->get_opcode() << "opcode" << "received:" << _respondString.size() << endl; RPCResponse r; r.ParseFromString(_respondString); if(r.ispushmessage()) { cout << "received:"<<_respondString.size() << endl; auto tt = handlerMap.at(r.pushtype()); tt(r); } else { response1 = r; _clientID = r.clientid(); print(_clientID); println(" receive response"); cv.notify_one(); } }); #ifdef GKC_SSL _WSclient.set_tls_init_handler([this](websocketpp::connection_hdl hdl)->shared_ptr<asio::ssl::context> { auto ctx = make_shared<asio::ssl::context>(asio::ssl::context::sslv23_client); try { ctx->set_options(asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 | asio::ssl::context::single_dh_use); ctx->set_verify_mode(0); } catch (std::exception& e) { std::cout << e.what() << std::endl; } return ctx; }); string protocal = "wss://"; #else string protocal = "ws://"; #endif pthread=make_shared<thread>([this]() { cout << "running" << endl; _WSclient.run(); }); error_code ec; con = _WSclient.get_connection(protocal+server,ec); if(ec) { cout << "connection fail "+ec.message()<< endl; exit(1); } if (_WSclient.connect(con) != nullptr) { } else { cout << "error connection" << endl; } } Connection(const Connection &) = delete; Connection(Connection &&) = default; Connection &operator=(const Connection &) = delete; Connection &operator=(Connection &&) = default; int getClientID() { return _clientID; } ~Connection() { } void close() { con->close(websocketpp::close::status::normal,"quit"); _WSclient.stop_perpetual(); pthread->join(); pthread.reset(); } void CallMethod(const MethodDescriptor *method, RpcController *controller, const Message *request, Message *response, Closure *done) override{ std::unique_lock<std::mutex> lk(m); auto p = dynamic_cast<const RPCRequest *> (request); while (!connected) ; //cout << p->DebugString() << endl << p->ByteSize() << endl; p->SerializeToArray(pSend, sizeof pSend); auto messageSize = static_cast<size_t > (p->ByteSize()); auto ec = con->send(pSend, messageSize); if (ec) { cerr << "?" << ec.message() << endl; return; } cv.wait(lk); if(controller->Failed()) { cerr << controller->ErrorText(); } auto pLocalResponse = static_cast<RPCResponse *>(response); *pLocalResponse = response1; if (done != nullptr) done->Run(); lk.unlock(); } }; using pConnection=shared_ptr<Connection>; } #endif //HOSTSVC_RPCCHANNEL_H
24.448276
106
0.621533
lishunan246
eb781c081e36e72e1b02bb2962d3472c404f4ecd
20,939
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimController_ZoneControlTemperature_ThermostatThermalComfort.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimController_ZoneControlTemperature_ThermostatThermalComfort.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimController_ZoneControlTemperature_ThermostatThermalComfort.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimController_ZoneControlTemperature_ThermostatThermalComfort.hxx" #include "simcntrl_thermalcomfortcontrol_1_4_objecttype.hxx" namespace schema { namespace simxml { namespace MepModel { // SimController_ZoneControlTemperature_ThermostatThermalComfort // const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_AveragingMethod_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod () const { return this->SimCntrl_AveragingMethod_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_AveragingMethod_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod () { return this->SimCntrl_AveragingMethod_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod (const SimCntrl_AveragingMethod_type& x) { this->SimCntrl_AveragingMethod_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod (const SimCntrl_AveragingMethod_optional& x) { this->SimCntrl_AveragingMethod_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod (::std::auto_ptr< SimCntrl_AveragingMethod_type > x) { this->SimCntrl_AveragingMethod_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_SpecificPeopleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName () const { return this->SimCntrl_SpecificPeopleName_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_SpecificPeopleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName () { return this->SimCntrl_SpecificPeopleName_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName (const SimCntrl_SpecificPeopleName_type& x) { this->SimCntrl_SpecificPeopleName_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName (const SimCntrl_SpecificPeopleName_optional& x) { this->SimCntrl_SpecificPeopleName_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName (::std::auto_ptr< SimCntrl_SpecificPeopleName_type > x) { this->SimCntrl_SpecificPeopleName_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MinDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint () const { return this->SimCntrl_MinDry_BulbTempSetpoint_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MinDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint () { return this->SimCntrl_MinDry_BulbTempSetpoint_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint (const SimCntrl_MinDry_BulbTempSetpoint_type& x) { this->SimCntrl_MinDry_BulbTempSetpoint_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint (const SimCntrl_MinDry_BulbTempSetpoint_optional& x) { this->SimCntrl_MinDry_BulbTempSetpoint_ = x; } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MaxDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint () const { return this->SimCntrl_MaxDry_BulbTempSetpoint_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MaxDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint () { return this->SimCntrl_MaxDry_BulbTempSetpoint_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint (const SimCntrl_MaxDry_BulbTempSetpoint_type& x) { this->SimCntrl_MaxDry_BulbTempSetpoint_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint (const SimCntrl_MaxDry_BulbTempSetpoint_optional& x) { this->SimCntrl_MaxDry_BulbTempSetpoint_ = x; } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControlTypeScheduleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName () const { return this->SimCntrl_ThermalComfortControlTypeScheduleName_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControlTypeScheduleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName () { return this->SimCntrl_ThermalComfortControlTypeScheduleName_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName (const SimCntrl_ThermalComfortControlTypeScheduleName_type& x) { this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName (const SimCntrl_ThermalComfortControlTypeScheduleName_optional& x) { this->SimCntrl_ThermalComfortControlTypeScheduleName_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName (::std::auto_ptr< SimCntrl_ThermalComfortControlTypeScheduleName_type > x) { this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType () const { return this->SimCntrl_ThermalComfortControl_1_4_ObjectType_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType () { return this->SimCntrl_ThermalComfortControl_1_4_ObjectType_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType (const SimCntrl_ThermalComfortControl_1_4_ObjectType_type& x) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType (const SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& x) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType (::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_ObjectType_type > x) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_Name_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name () const { return this->SimCntrl_ThermalComfortControl_1_4_Name_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_Name_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name () { return this->SimCntrl_ThermalComfortControl_1_4_Name_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name (const SimCntrl_ThermalComfortControl_1_4_Name_type& x) { this->SimCntrl_ThermalComfortControl_1_4_Name_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name (const SimCntrl_ThermalComfortControl_1_4_Name_optional& x) { this->SimCntrl_ThermalComfortControl_1_4_Name_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name (::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_Name_type > x) { this->SimCntrl_ThermalComfortControl_1_4_Name_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace MepModel { // SimController_ZoneControlTemperature_ThermostatThermalComfort // SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort () : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (), SimCntrl_AveragingMethod_ (this), SimCntrl_SpecificPeopleName_ (this), SimCntrl_MinDry_BulbTempSetpoint_ (this), SimCntrl_MaxDry_BulbTempSetpoint_ (this), SimCntrl_ThermalComfortControlTypeScheduleName_ (this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this), SimCntrl_ThermalComfortControl_1_4_Name_ (this) { } SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort (const RefId_type& RefId) : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (RefId), SimCntrl_AveragingMethod_ (this), SimCntrl_SpecificPeopleName_ (this), SimCntrl_MinDry_BulbTempSetpoint_ (this), SimCntrl_MaxDry_BulbTempSetpoint_ (this), SimCntrl_ThermalComfortControlTypeScheduleName_ (this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this), SimCntrl_ThermalComfortControl_1_4_Name_ (this) { } SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort (const SimController_ZoneControlTemperature_ThermostatThermalComfort& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (x, f, c), SimCntrl_AveragingMethod_ (x.SimCntrl_AveragingMethod_, f, this), SimCntrl_SpecificPeopleName_ (x.SimCntrl_SpecificPeopleName_, f, this), SimCntrl_MinDry_BulbTempSetpoint_ (x.SimCntrl_MinDry_BulbTempSetpoint_, f, this), SimCntrl_MaxDry_BulbTempSetpoint_ (x.SimCntrl_MaxDry_BulbTempSetpoint_, f, this), SimCntrl_ThermalComfortControlTypeScheduleName_ (x.SimCntrl_ThermalComfortControlTypeScheduleName_, f, this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (x.SimCntrl_ThermalComfortControl_1_4_ObjectType_, f, this), SimCntrl_ThermalComfortControl_1_4_Name_ (x.SimCntrl_ThermalComfortControl_1_4_Name_, f, this) { } SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (e, f | ::xml_schema::flags::base, c), SimCntrl_AveragingMethod_ (this), SimCntrl_SpecificPeopleName_ (this), SimCntrl_MinDry_BulbTempSetpoint_ (this), SimCntrl_MaxDry_BulbTempSetpoint_ (this), SimCntrl_ThermalComfortControlTypeScheduleName_ (this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this), SimCntrl_ThermalComfortControl_1_4_Name_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::MepModel::SimController_ZoneControlTemperature::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimCntrl_AveragingMethod // if (n.name () == "SimCntrl_AveragingMethod" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_AveragingMethod_type > r ( SimCntrl_AveragingMethod_traits::create (i, f, this)); if (!this->SimCntrl_AveragingMethod_) { this->SimCntrl_AveragingMethod_.set (r); continue; } } // SimCntrl_SpecificPeopleName // if (n.name () == "SimCntrl_SpecificPeopleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_SpecificPeopleName_type > r ( SimCntrl_SpecificPeopleName_traits::create (i, f, this)); if (!this->SimCntrl_SpecificPeopleName_) { this->SimCntrl_SpecificPeopleName_.set (r); continue; } } // SimCntrl_MinDry_BulbTempSetpoint // if (n.name () == "SimCntrl_MinDry_BulbTempSetpoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimCntrl_MinDry_BulbTempSetpoint_) { this->SimCntrl_MinDry_BulbTempSetpoint_.set (SimCntrl_MinDry_BulbTempSetpoint_traits::create (i, f, this)); continue; } } // SimCntrl_MaxDry_BulbTempSetpoint // if (n.name () == "SimCntrl_MaxDry_BulbTempSetpoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimCntrl_MaxDry_BulbTempSetpoint_) { this->SimCntrl_MaxDry_BulbTempSetpoint_.set (SimCntrl_MaxDry_BulbTempSetpoint_traits::create (i, f, this)); continue; } } // SimCntrl_ThermalComfortControlTypeScheduleName // if (n.name () == "SimCntrl_ThermalComfortControlTypeScheduleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_ThermalComfortControlTypeScheduleName_type > r ( SimCntrl_ThermalComfortControlTypeScheduleName_traits::create (i, f, this)); if (!this->SimCntrl_ThermalComfortControlTypeScheduleName_) { this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (r); continue; } } // SimCntrl_ThermalComfortControl_1_4_ObjectType // if (n.name () == "SimCntrl_ThermalComfortControl_1_4_ObjectType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_ObjectType_type > r ( SimCntrl_ThermalComfortControl_1_4_ObjectType_traits::create (i, f, this)); if (!this->SimCntrl_ThermalComfortControl_1_4_ObjectType_) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (r); continue; } } // SimCntrl_ThermalComfortControl_1_4_Name // if (n.name () == "SimCntrl_ThermalComfortControl_1_4_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_Name_type > r ( SimCntrl_ThermalComfortControl_1_4_Name_traits::create (i, f, this)); if (!this->SimCntrl_ThermalComfortControl_1_4_Name_) { this->SimCntrl_ThermalComfortControl_1_4_Name_.set (r); continue; } } break; } } SimController_ZoneControlTemperature_ThermostatThermalComfort* SimController_ZoneControlTemperature_ThermostatThermalComfort:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimController_ZoneControlTemperature_ThermostatThermalComfort (*this, f, c); } SimController_ZoneControlTemperature_ThermostatThermalComfort& SimController_ZoneControlTemperature_ThermostatThermalComfort:: operator= (const SimController_ZoneControlTemperature_ThermostatThermalComfort& x) { if (this != &x) { static_cast< ::schema::simxml::MepModel::SimController_ZoneControlTemperature& > (*this) = x; this->SimCntrl_AveragingMethod_ = x.SimCntrl_AveragingMethod_; this->SimCntrl_SpecificPeopleName_ = x.SimCntrl_SpecificPeopleName_; this->SimCntrl_MinDry_BulbTempSetpoint_ = x.SimCntrl_MinDry_BulbTempSetpoint_; this->SimCntrl_MaxDry_BulbTempSetpoint_ = x.SimCntrl_MaxDry_BulbTempSetpoint_; this->SimCntrl_ThermalComfortControlTypeScheduleName_ = x.SimCntrl_ThermalComfortControlTypeScheduleName_; this->SimCntrl_ThermalComfortControl_1_4_ObjectType_ = x.SimCntrl_ThermalComfortControl_1_4_ObjectType_; this->SimCntrl_ThermalComfortControl_1_4_Name_ = x.SimCntrl_ThermalComfortControl_1_4_Name_; } return *this; } SimController_ZoneControlTemperature_ThermostatThermalComfort:: ~SimController_ZoneControlTemperature_ThermostatThermalComfort () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace MepModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
42.046185
195
0.723865
EnEff-BIM
eb781e552af0f6852b5b20040b828cf0b784c6d1
565
cpp
C++
Reverse a Linked List in groups of given size.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Reverse a Linked List in groups of given size.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
1
2021-10-01T18:00:09.000Z
2021-10-01T18:00:09.000Z
Reverse a Linked List in groups of given size.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
class Solution { public: int l(struct node* h){ int c; while(h){ h=h->next; ++c; } return c; } struct node *reverse (struct node *head, int k) { if(l(head)<k) return head; struct node *prev=0; struct node *next=0; struct node *curr=head; for(int i=0;i<k;i++){ next=curr->next; curr->next=prev; prev=curr; curr=next; } head->next=reverse(curr,k); return prev; } };
19.482759
51
0.424779
Subhash3
eb79e846435d4de4af5e754ac5f49b0460911081
2,122
cpp
C++
querier/BaseChunkSeriesSet.cpp
Jimx-/tsdb-fork
f92cfa0a998c03b3a2cb4c8e46990de8b47aae15
[ "Apache-2.0" ]
1
2020-06-04T06:56:40.000Z
2020-06-04T06:56:40.000Z
querier/BaseChunkSeriesSet.cpp
Jimx-/tsdb-fork
f92cfa0a998c03b3a2cb4c8e46990de8b47aae15
[ "Apache-2.0" ]
null
null
null
querier/BaseChunkSeriesSet.cpp
Jimx-/tsdb-fork
f92cfa0a998c03b3a2cb4c8e46990de8b47aae15
[ "Apache-2.0" ]
1
2020-06-04T03:35:58.000Z
2020-06-04T03:35:58.000Z
#include "querier/BaseChunkSeriesSet.hpp" #include "base/Logging.hpp" #include "index/PostingSet.hpp" #include <unordered_set> namespace tsdb { namespace querier { // BaseChunkSeriesSet loads the label set and chunk references for a postings // list from an index. It filters out series that have labels set that should be // unset // // The chunk pointer in ChunkMeta is not set // NOTE(Alec), BaseChunkSeriesSet fine-grained filters the chunks using // tombstone. BaseChunkSeriesSet::BaseChunkSeriesSet( const std::shared_ptr<block::IndexReaderInterface>& ir, const std::shared_ptr<tombstone::TombstoneReaderInterface>& tr, const std::set<tagtree::TSID>& list) : ir(ir), tr(tr), cm(new ChunkSeriesMeta()), err_(false) { p = std::make_unique<index::PostingSet>(list); } // next() always called before at(). const std::shared_ptr<ChunkSeriesMeta>& BaseChunkSeriesSet::at() const { return cm; } bool BaseChunkSeriesSet::next() const { if (err_) return false; while (p->next()) { auto tsid = p->at(); cm->clear(); cm->tsid = tsid; // Get labels and deque of ChunkMeta of the corresponding series. if (!ir->series(tsid, cm->chunks)) { // TODO, ErrNotFound // err_ = true; // return false; continue; } // Get Intervals from MemTombstones try { // LOG_INFO << ref; cm->intervals = tr->get(tsid); } catch (const std::out_of_range& e) { } if (!(cm->intervals).empty()) { std::vector<std::shared_ptr<chunk::ChunkMeta>>::iterator it = cm->chunks.begin(); while (it != cm->chunks.end()) { if (tombstone::is_subrange((*it)->min_time, (*it)->max_time, cm->intervals)) it = cm->chunks.erase(it); else ++it; } } return true; } return false; } bool BaseChunkSeriesSet::error() const { return err_; } } // namespace querier } // namespace tsdb
27.921053
80
0.582941
Jimx-
eb7a0116bdd5d901141b9585dff6b9973b0049f5
2,046
cc
C++
absl/base/internal/scoped_set_env.cc
abaskin/abseil-cpp
9e598094c380d79119c752d4a472c0765728ec81
[ "Apache-2.0" ]
null
null
null
absl/base/internal/scoped_set_env.cc
abaskin/abseil-cpp
9e598094c380d79119c752d4a472c0765728ec81
[ "Apache-2.0" ]
1
2020-02-17T08:25:41.000Z
2020-02-18T08:08:59.000Z
absl/base/internal/scoped_set_env.cc
abaskin/abseil-cpp
9e598094c380d79119c752d4a472c0765728ec81
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 The Abseil Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "absl/base/internal/scoped_set_env.h" #ifdef _WIN32 #include <windows.h> #endif #include <cstdlib> #include "absl/base/internal/raw_logging.h" namespace absl { inline namespace lts_2019_08_08 { namespace base_internal { namespace { #ifdef _WIN32 const int kMaxEnvVarValueSize = 1024; #endif void SetEnvVar(const char* name, const char* value) { #ifdef _WIN32 SetEnvironmentVariableA(name, value); #else if (value == nullptr) { ::unsetenv(name); } else { ::setenv(name, value, 1); } #endif } } // namespace ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value) : var_name_(var_name), was_unset_(false) { #ifdef _WIN32 char buf[kMaxEnvVarValueSize]; auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf)); ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size"); if (get_res == 0) { was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND); } else { old_value_.assign(buf, get_res); } SetEnvironmentVariableA(var_name_.c_str(), new_value); #else const char* val = ::getenv(var_name_.c_str()); if (val == nullptr) { was_unset_ = true; } else { old_value_ = val; } #endif SetEnvVar(var_name_.c_str(), new_value); } ScopedSetEnv::~ScopedSetEnv() { SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str()); } } // namespace base_internal } // inline namespace lts_2019_08_08 } // namespace absl
24.95122
78
0.716031
abaskin
eb7a76d2ad6529b513946bc8dbe3ed9c956e0114
703
hpp
C++
apps/src/videostitch-live-gui/src/videostitcher/liveaudioprocessordelay.hpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
apps/src/videostitch-live-gui/src/videostitcher/liveaudioprocessordelay.hpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
apps/src/videostitch-live-gui/src/videostitcher/liveaudioprocessordelay.hpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #pragma once #include "liveaudioprocessfactory.hpp" class LiveAudioProcessorDelay : public LiveAudioProcessFactory { public: explicit LiveAudioProcessorDelay(const VideoStitch::Ptv::Value* config); ~LiveAudioProcessorDelay() = default; QPixmap getIcon() const override; QString getDescription() const override; int getDelay() const; void setDelay(const int value); VideoStitch::Ptv::Value* serialize() const override; AudioProcessorConfigurationWidget* createConfigurationWidget(QWidget* parent) override; void serializeParameters(VideoStitch::Ptv::Value* value) override; private: int delay = 0; };
27.038462
89
0.773826
tlalexander
eb7a828f6a03fd1a6be50dea689839ce4e2ac816
915
hpp
C++
cpp/src/vcf/filterDescription.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
8
2018-10-08T15:47:21.000Z
2021-11-09T07:13:05.000Z
cpp/src/vcf/filterDescription.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
4
2018-11-05T09:16:27.000Z
2020-04-09T12:32:56.000Z
cpp/src/vcf/filterDescription.hpp
dylex/wecall
35d24cefa4fba549e737cd99329ae1b17dd0156b
[ "MIT" ]
4
2019-09-03T15:46:39.000Z
2021-06-04T07:28:33.000Z
// All content Copyright (C) 2018 Genomics plc #ifndef VCF_FILTERDESC_HPP #define VCF_FILTERDESC_HPP #include "common.hpp" #include <iostream> namespace wecall { namespace vcf { struct FilterDesc { /// Basic constructor from constituent data /// /// @param id Filter ID. /// @param description Filter description. FilterDesc( const std::string & id, const std::string & description ); /// Writes the filter to the output stream in the form of a VCF FILTER header line. /// /// @param out Output stream /// @param filterDesc Filter to be output /// @return Output stream friend std::ostream & operator<<( std::ostream & out, const FilterDesc & filterDesc ); friend bool operator<( const FilterDesc & lhs, const FilterDesc & rhs ); std::string id; std::string description; }; } } #endif
25.416667
94
0.628415
dylex
eb7d731262e2c5b0ac6a7e3f1d3fd9ff7f408dc8
11,378
cpp
C++
ftaction.cpp
sphinxlogic/shell32
ef38d3338afd575a2d456d737c7bd6a105392d88
[ "MIT" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/shell32/ftaction.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/shell32/ftaction.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "shellprv.h" #include "ids.h" #include "ftadv.h" #include "ftcmmn.h" #include "ftaction.h" #include "ftassoc.h" const static DWORD cs_rgdwHelpIDsArray[] = { // Context Help IDs IDC_FT_CMD_ACTION, IDH_FCAB_FT_CMD_ACTION, IDC_FT_CMD_EXETEXT, IDH_FCAB_FT_CMD_EXE, IDC_FT_CMD_EXE, IDH_FCAB_FT_CMD_EXE, IDC_FT_CMD_BROWSE, IDH_FCAB_FT_CMD_BROWSE, IDC_FT_CMD_DDEGROUP, IDH_FCAB_FT_CMD_USEDDE, IDC_FT_CMD_USEDDE, IDH_FCAB_FT_CMD_USEDDE, IDC_FT_CMD_DDEMSG, IDH_FCAB_FT_CMD_DDEMSG, IDC_FT_CMD_DDEAPP, IDH_FCAB_FT_CMD_DDEAPP, IDC_FT_CMD_DDEAPPNOT, IDH_FCAB_FT_CMD_DDEAPPNOT, IDC_FT_CMD_DDETOPIC, IDH_FCAB_FT_CMD_DDETOPIC, 0, 0 }; CFTActionDlg::CFTActionDlg(PROGIDACTION* pProgIDAction, LPTSTR pszProgIDDescr, BOOL fEdit) : CFTDlg((ULONG_PTR)cs_rgdwHelpIDsArray), _pProgIDAction(pProgIDAction), _pszProgIDDescr(pszProgIDDescr), _fEdit(fEdit) { } CFTActionDlg::~CFTActionDlg() { } /////////////////////////////////////////////////////////////////////////////// // Logic specific to our problem LRESULT CFTActionDlg::OnInitDialog(WPARAM wParam, LPARAM lParam) { DECLAREWAITCURSOR; SetWaitCursor(); if (_fEdit || _fShowAgain) { TCHAR szTitle[50 + MAX_PROGIDDESCR + 5]; TCHAR szTitleTemplate[50]; _fShowAgain = FALSE; if (LoadString(g_hinst, IDS_FT_EDITTITLE, szTitleTemplate, ARRAYSIZE(szTitleTemplate))) { StringCchPrintf(szTitle, ARRAYSIZE(szTitle), szTitleTemplate, _pszProgIDDescr); SetWindowText(_hwnd, szTitle); } SetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, _pProgIDAction->szAction); SetDlgItemText(_hwnd, IDC_FT_CMD_EXE, _pProgIDAction->szCmdLine); SetDlgItemText(_hwnd, IDC_FT_CMD_DDEMSG, _pProgIDAction->szDDEMsg); SetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPP, _pProgIDAction->szDDEApplication); SetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPPNOT, _pProgIDAction->szDDEAppNotRunning); SetDlgItemText(_hwnd, IDC_FT_CMD_DDETOPIC, _pProgIDAction->szDDETopic); CheckDlgButton(_hwnd, IDC_FT_CMD_USEDDE, _pProgIDAction->fUseDDE); _ResizeDlgForDDE(_pProgIDAction->fUseDDE); } else { CheckDlgButton(_hwnd, IDC_FT_CMD_USEDDE, FALSE); _ResizeDlgForDDE(FALSE); } Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_ACTION), MAX_ACTION - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_EXE), MAX_ACTIONCMDLINE - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEMSG), MAX_ACTIONDDEMSG - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPP), MAX_ACTIONAPPL - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPPNOT), MAX_ACTIONDDEAPPNOTRUN - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDETOPIC), MAX_ACTIONTOPIC - 1); ResetWaitCursor(); // Return TRUE so that system set focus return TRUE; } BOOL CFTActionDlg::_Validate() { BOOL bRet = TRUE; // Check the Action TCHAR szAction[MAX_ACTION]; if (!GetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, szAction, ARRAYSIZE(szAction)) || !*szAction) { ShellMessageBox(g_hinst, _hwnd, MAKEINTRESOURCE(IDS_FT_MB_NOACTION), MAKEINTRESOURCE(IDS_FT), MB_OK | MB_ICONSTOP); PostMessage(_hwnd, WM_CTRL_SETFOCUS, (WPARAM)0, (LPARAM)GetDlgItem(_hwnd, IDC_FT_CMD_ACTION)); bRet = FALSE; } if (bRet) { TCHAR szPath[MAX_PATH]; LPTSTR pszFileName = NULL; // Check for valid exe GetDlgItemText(_hwnd, IDC_FT_CMD_EXE, szPath, ARRAYSIZE(szPath)); PathRemoveArgs(szPath); PathUnquoteSpaces(szPath); pszFileName = PathFindFileName(szPath); if(!(*szPath) || !(PathIsExe(szPath)) || ((!(PathFileExists(szPath))) && (!(PathFindOnPath(pszFileName, NULL))))) { // Tell user that this exe is invalid ShellMessageBox(g_hinst, _hwnd, MAKEINTRESOURCE(IDS_FT_MB_EXETEXT), MAKEINTRESOURCE(IDS_FT), MB_OK | MB_ICONSTOP); PostMessage(_hwnd, WM_CTRL_SETFOCUS, (WPARAM)0, (LPARAM)GetDlgItem(_hwnd, IDC_FT_CMD_EXE)); bRet = FALSE; } } return bRet; } void CFTActionDlg::SetShowAgain() { _fShowAgain = TRUE; } BOOL _IsThereAnyPercentArgument(LPTSTR pszCommand) { BOOL fRet = FALSE; LPTSTR pszArgs = PathGetArgs(pszCommand); if (pszArgs && *pszArgs) { if (StrStr(pszArgs, TEXT("%"))) { fRet = TRUE; } } return fRet; } LRESULT CFTActionDlg::OnOK(WORD wNotif) { if (_Validate()) { GetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, _pProgIDAction->szAction, MAX_ACTION); // Is this a new action? if (!_fEdit) { // Yes, initialize the old action field StringCchCopy(_pProgIDAction->szOldAction, ARRAYSIZE(_pProgIDAction->szOldAction), _pProgIDAction->szAction); // Build the ActionReg StringCchCopy(_pProgIDAction->szActionReg, ARRAYSIZE(_pProgIDAction->szActionReg), _pProgIDAction->szAction); // Replace spaces with underscores LPTSTR psz = _pProgIDAction->szActionReg; while (*psz) { if (TEXT(' ') == *psz) { *psz = TEXT('_'); } psz = CharNext(psz); } StringCchCopy(_pProgIDAction->szOldActionReg, ARRAYSIZE(_pProgIDAction->szOldActionReg), _pProgIDAction->szActionReg); } GetDlgItemText(_hwnd, IDC_FT_CMD_EXE, _pProgIDAction->szCmdLine, MAX_ACTIONCMDLINE); GetDlgItemText(_hwnd, IDC_FT_CMD_DDEMSG, _pProgIDAction->szDDEMsg, MAX_ACTIONDDEMSG); GetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPP, _pProgIDAction->szDDEApplication, MAX_ACTIONAPPL); GetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPPNOT, _pProgIDAction->szDDEAppNotRunning, MAX_ACTIONDDEAPPNOTRUN); GetDlgItemText(_hwnd, IDC_FT_CMD_DDETOPIC, _pProgIDAction->szDDETopic, MAX_ACTIONTOPIC); _pProgIDAction->fUseDDE = IsDlgButtonChecked(_hwnd, IDC_FT_CMD_USEDDE); // Append %1 to action field, if required if (!_IsThereAnyPercentArgument(_pProgIDAction->szCmdLine)) { TCHAR* pszPercentToAppend; if (StrChr(_pProgIDAction->szCmdLine,TEXT('\\'))) { if (App_IsLFNAware(_pProgIDAction->szCmdLine)) pszPercentToAppend = TEXT(" \"%1\""); else pszPercentToAppend = TEXT(" %1"); } else { TCHAR szFullPathFileName[MAX_PATH]; // StringCchCopy(szFullPathFileName, ARRAYSIZE(szFullPathFileName), _pProgIDAction->szCmdLine); //PathFindOnPath: first param is the filename, if it is on the path // then it returns fully qualified, if not return false. //Second param is optional directory to look in first if (PathFindOnPath(szFullPathFileName, NULL)) { if (App_IsLFNAware(szFullPathFileName)) pszPercentToAppend = TEXT(" \"%1\""); else pszPercentToAppend = TEXT(" %1"); } else {//just in case, default to good old behavior. Should not come here because // ActionExeIsValid was done earlier pszPercentToAppend = TEXT(" %1"); } } //append... StringCchCat(_pProgIDAction->szCmdLine, ARRAYSIZE(_pProgIDAction->szCmdLine), pszPercentToAppend); } EndDialog(_hwnd, IDOK); } return FALSE; } LRESULT CFTActionDlg::OnCancel(WORD wNotif) { EndDialog(_hwnd, IDCANCEL); return FALSE; } LRESULT CFTActionDlg::OnUseDDE(WORD wNotif) { _ResizeDlgForDDE(IsDlgButtonChecked(_hwnd, IDC_FT_CMD_USEDDE)); return FALSE; } LRESULT CFTActionDlg::OnBrowse(WORD wNotif) { TCHAR szPath[MAX_PATH]; TCHAR szTitle[40]; TCHAR szEXE[MAX_PATH]; TCHAR szFilters[MAX_PATH]; LPTSTR psz; szPath[0] = 0; EVAL(LoadString(g_hinst, IDS_CAP_OPENAS, szTitle, ARRAYSIZE(szTitle))); EVAL(LoadString(g_hinst, IDS_FT_EXE, szEXE, ARRAYSIZE(szEXE))); // And we need to convert #'s to \0's... EVAL(LoadString(g_hinst, IDS_PROGRAMSFILTER, szFilters, ARRAYSIZE(szFilters))); psz = szFilters; while (*psz) { if (*psz == TEXT('#')) { LPTSTR pszT = psz; psz = CharNext(psz); *pszT = TEXT('\0'); } else psz = CharNext(psz); } if (GetFileNameFromBrowse(_hwnd, szPath, ARRAYSIZE(szPath), NULL, szEXE, szFilters, szTitle)) { PathQuoteSpaces(szPath); SetDlgItemText(_hwnd, IDC_FT_CMD_EXE, szPath); } return FALSE; } void CFTActionDlg::_ResizeDlgForDDE(BOOL fShow) { RECT rcDialog; RECT rcControl; GetWindowRect(_hwnd, &rcDialog); if(fShow) GetWindowRect(GetDlgItem(_hwnd, IDC_FT_CMD_DDEGROUP), &rcControl); else GetWindowRect(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE), &rcControl); // Hide/Show the windows to take care of the Tabbing. If we don't hide them then // we tab through the "visible" window outside of the dialog. ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEMSG), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPP), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPPNOT), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDETOPIC), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEGROUP), fShow); SetWindowPos(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW); MoveWindow(_hwnd, rcDialog.left, rcDialog.top, rcDialog.right - rcDialog.left, (rcControl.bottom - rcDialog.top) + 10, TRUE); SetFocus(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE)); } LRESULT CFTActionDlg::OnDestroy(WPARAM wParam, LPARAM lParam) { CFTDlg::OnDestroy(wParam, lParam); return FALSE; } /////////////////////////////////////////////////////////////////////////////// // Windows boiler plate code LRESULT CFTActionDlg::OnCommand(WPARAM wParam, LPARAM lParam) { LRESULT lRes = FALSE; switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_FT_CMD_USEDDE: // Resize Dialog to see/hide DDE controls lRes = OnUseDDE(GET_WM_COMMAND_CMD(wParam, lParam)); break; case IDC_FT_CMD_BROWSE: lRes = OnBrowse(GET_WM_COMMAND_CMD(wParam, lParam)); break; default: lRes = CFTDlg::OnCommand(wParam, lParam); break; } return lRes; }
32.323864
122
0.604939
sphinxlogic
eb7d97242833f1043f9e24cfe06fc026b99bf264
2,975
cpp
C++
source/Worker.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
source/Worker.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
source/Worker.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
/************************************************************************** Contains implementation for Worker class and its JobQueue subclass, which handle job queues and stealing. Author: Jake McLeman **************************************************************************/ #include <algorithm> #ifdef _DEBUG #include <assert.h> #endif #include "Job.h" #include "JobExceptions.h" #include "Manager.h" #include "Worker.h" namespace JobBot { Worker::Worker(Manager* aManager, Mode aMode, const Specialization& aSpecialization) : manager_(aManager), workerMode_(aMode), workerSpecialization_(aSpecialization), threadID_(std::this_thread::get_id()), keepWorking_(false), isWorking_(false) { } Worker::Specialization Worker::Specialization::None = { {JobType::Huge, JobType::Graphics, JobType::Misc, JobType::IO, JobType::Tiny}}; Worker::Specialization Worker::Specialization::IO = { {JobType::IO, JobType::Huge, JobType::Misc, JobType::Graphics, JobType::Tiny}}; Worker::Specialization Worker::Specialization::Graphics = { {JobType::Graphics, JobType::Tiny, JobType::Misc, JobType::Null, JobType::Null}}; Worker::Specialization Worker::Specialization::RealTime = { {JobType::Tiny, JobType::Misc, JobType::Graphics, JobType::Null, JobType::Null}}; void Worker::WorkWhileWaitingFor(Job* aWaitJob) { bool wasWorking = isWorking_; isWorking_ = true; aWaitJob->SetAllowCompletion(false); while (!aWaitJob->IsFinished()) { DoSingleJob(); } aWaitJob->SetAllowCompletion(true); isWorking_ = wasWorking; } void Worker::WorkWhileWaitingFor(std::atomic_bool& condition) { bool wasWorking = isWorking_; isWorking_ = true; while (!condition) { DoSingleJob(); } isWorking_ = wasWorking; } void Worker::Start() { keepWorking_ = true; DoWork(); } void Worker::Stop() { keepWorking_ = false; while (isWorking_) ; } void Worker::StopAfterCurrentTask() { keepWorking_ = false; } Worker::Mode Worker::GetMode() { return workerMode_; } std::thread::id Worker::GetThreadID() const { return threadID_; } bool Worker::IsWorking() const { return isWorking_; } void Worker::DoWork() { isWorking_ = true; while (keepWorking_) { DoSingleJob(); } isWorking_ = false; } void Worker::DoSingleJob() { static std::mutex waitMutex; Job* job = GetAJob(); #ifdef _DEBUG if (job != nullptr && job->GetUnfinishedJobCount() > 0) #else if (job != nullptr) #endif { job->Run(); } else { // If no job was found by any method, be a good citizen and step aside // so that other processes on CPU can happen if (workerMode_ == Mode::Volunteer) { std::this_thread::yield(); } else { std::unique_lock<std::mutex> uniqueWait(waitMutex); manager_->JobNotifier.wait(uniqueWait); } } } Job* Worker::GetAJob() { return manager_->RequestJob(workerSpecialization_); } }
21.557971
78
0.640672
jacobmcleman
eb84c978c897afc0f16982b1ed521bdb0a014a3a
6,080
cpp
C++
sobol-dpct/sobol.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
sobol-dpct/sobol.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
sobol-dpct/sobol.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
/* * Portions Copyright (c) 1993-2015 NVIDIA Corporation. All rights reserved. * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * * Portions Copyright (c) 2009 Mike Giles, Oxford University. All rights reserved. * Portions Copyright (c) 2008 Frances Y. Kuo and Stephen Joe. All rights reserved. * * Sobol Quasi-random Number Generator example * * Based on CUDA code submitted by Mike Giles, Oxford University, United Kingdom * http://people.maths.ox.ac.uk/~gilesm/ * * and C code developed by Stephen Joe, University of Waikato, New Zealand * and Frances Kuo, University of New South Wales, Australia * http://web.maths.unsw.edu.au/~fkuo/sobol/ * * For theoretical background see: * * P. Bratley and B.L. Fox. * Implementing Sobol's quasirandom sequence generator * http://portal.acm.org/citation.cfm?id=42288 * ACM Trans. on Math. Software, 14(1):88-100, 1988 * * S. Joe and F. Kuo. * Remark on algorithm 659: implementing Sobol's quasirandom sequence generator. * http://portal.acm.org/citation.cfm?id=641879 * ACM Trans. on Math. Software, 29(1):49-57, 2003 */ #include <CL/sycl.hpp> #include <dpct/dpct.hpp> #include <iostream> #include <stdexcept> #include <math.h> #include "sobol.h" #include "sobol_gold.h" #include "sobol_gpu.h" #define L1ERROR_TOLERANCE (1e-6) void printHelp(int argc, char *argv[]) { if (argc > 0) { std::cout << "\nUsage: " << argv[0] << " <options>\n\n"; } else { std::cout << "\nUsage: <program name> <options>\n\n"; } std::cout << "\t--vectors=M specify number of vectors (required)\n"; std::cout << "\t The generator will output M vectors\n\n"; std::cout << "\t--dimensions=N specify number of dimensions (required)\n"; std::cout << "\t Each vector will consist of N components\n\n"; std::cout << std::endl; } int main(int argc, char *argv[]) { dpct::device_ext &dev_ct1 = dpct::get_current_device(); sycl::queue &q_ct1 = dev_ct1.default_queue(); // We will generate n_vectors vectors of n_dimensions numbers int n_vectors = atoi(argv[1]); //100000; int n_dimensions = atoi(argv[2]); //100; // Allocate memory for the arrays std::cout << "Allocating CPU memory..." << std::endl; unsigned int *h_directions = 0; float *h_outputCPU = 0; float *h_outputGPU = 0; try { h_directions = new unsigned int [n_dimensions * n_directions]; h_outputCPU = new float [n_vectors * n_dimensions]; h_outputGPU = new float [n_vectors * n_dimensions]; } catch (std::exception e) { std::cerr << "Caught exception: " << e.what() << std::endl; std::cerr << "Unable to allocate CPU memory (try running with fewer vectors/dimensions)" << std::endl; exit(EXIT_FAILURE); } std::cout << "Allocating GPU memory..." << std::endl; unsigned int *d_directions; float *d_output; d_directions = sycl::malloc_device<unsigned int>(n_dimensions * n_directions, q_ct1); d_output = sycl::malloc_device<float>(n_vectors * n_dimensions, q_ct1); // Initialize the direction numbers (done on the host) std::cout << "Initializing direction numbers..." << std::endl; initSobolDirectionVectors(n_dimensions, h_directions); std::cout << "Executing QRNG on GPU..." << std::endl; q_ct1 .memcpy(d_directions, h_directions, n_dimensions * n_directions * sizeof(unsigned int)) .wait(); dev_ct1.queues_wait_and_throw(); sobolGPU(n_vectors, n_dimensions, d_directions, d_output); q_ct1 .memcpy(h_outputGPU, d_output, n_vectors * n_dimensions * sizeof(float)) .wait(); std::cout << std::endl; // Execute the QRNG on the host std::cout << "Executing QRNG on CPU..." << std::endl; sobolCPU(n_vectors, n_dimensions, h_directions, h_outputCPU); // Check the results std::cout << "Checking results..." << std::endl; float l1norm_diff = 0.0F; float l1norm_ref = 0.0F; float l1error; // Special case if n_vectors is 1, when the vector should be exactly 0 if (n_vectors == 1) { for (int d = 0, v = 0 ; d < n_dimensions ; d++) { float ref = h_outputCPU[d * n_vectors + v]; l1norm_diff += fabs(h_outputGPU[d * n_vectors + v] - ref); l1norm_ref += fabs(ref); } // Output the L1-Error l1error = l1norm_diff; if (l1norm_ref != 0) { std::cerr << "Error: L1-Norm of the reference is not zero (for single vector), golden generator appears broken\n"; } else { std::cout << "L1-Error: " << l1error << std::endl; } } else { for (int d = 0 ; d < n_dimensions ; d++) { for (int v = 0 ; v < n_vectors ; v++) { float ref = h_outputCPU[d * n_vectors + v]; l1norm_diff += fabs(h_outputGPU[d * n_vectors + v] - ref); l1norm_ref += fabs(ref); } } // Output the L1-Error l1error = l1norm_diff / l1norm_ref; if (l1norm_ref == 0) { std::cerr << "Error: L1-Norm of the reference is zero, golden generator appears broken\n"; } else { std::cout << "L1-Error: " << l1error << std::endl; } } // Cleanup and terminate std::cout << "Shutting down..." << std::endl; delete h_directions; delete h_outputCPU; delete h_outputGPU; sycl::free(d_directions, q_ct1); sycl::free(d_output, q_ct1); // Check pass/fail using L1 error if (l1error < L1ERROR_TOLERANCE) std::cout << "PASS" << std::endl; else std::cout << "FAIL" << std::endl; return 0; }
32
126
0.611184
jchlanda
eb86c4e92996f702e78ea1e988b8fd9beeb7c0e8
15,069
cpp
C++
test/unittests/unittest-latticeupdates.cpp
sjvs/andysim-helpme-copy
f34427c4c3073bb642af8078e80e759ac35e392d
[ "BSD-3-Clause" ]
null
null
null
test/unittests/unittest-latticeupdates.cpp
sjvs/andysim-helpme-copy
f34427c4c3073bb642af8078e80e759ac35e392d
[ "BSD-3-Clause" ]
null
null
null
test/unittests/unittest-latticeupdates.cpp
sjvs/andysim-helpme-copy
f34427c4c3073bb642af8078e80e759ac35e392d
[ "BSD-3-Clause" ]
null
null
null
// BEGINLICENSE // // This file is part of helPME, which is distributed under the BSD 3-clause license, // as described in the LICENSE file in the top level directory of this project. // // Author: Andrew C. Simmonett // // ENDLICENSE #include "catch.hpp" #include "helpme.h" TEST_CASE("check that updates of kappa and unit cell parameters give the correct behavior.") { constexpr double TOL = 1e-7; double ccelec = 332.0716; // Setup parameters and reference values. helpme::Matrix<double> coords( {{2.0, 2.0, 2.0}, {2.5, 2.0, 3.0}, {1.5, 2.0, 3.0}, {0.0, 0.0, 0.0}, {0.5, 0.0, 1.0}, {-0.5, 0.0, 1.0}}); helpme::Matrix<double> charges({-0.834, 0.417, 0.417, -0.834, 0.417, 0.417}); short nfftx = 20; short nffty = 21; short nfftz = 22; short splineOrder = 5; double refEnergy1 = 5.8537004; helpme::Matrix<double> refForces1({{-0.60004038, -0.74129836, 6.31176591}, {0.50238424, 0.44175023, -2.53478813}, {0.34430074, 0.54474056, -2.60670541}, {-1.14160970, -1.04857552, 5.07874657}, {0.40743265, 0.45709529, -3.21032689}, {0.48655356, 0.34618192, -3.03887422} }); helpme::Matrix<double> refVirial1({{0.61893621, 0.49018413, 0.54959991, 2.29084071, 2.35776919, -9.96248284}}); double refEnergy2 = 5.855746495; helpme::Matrix<double> refForces2({{-0.60245163, -0.73942661, 6.31413552}, {0.50396028, 0.44092114, -2.53631961}, {0.34571162, 0.54380710, -2.60819278}, {-1.14467175, -1.04727038, 5.08209801}, {0.40871507, 0.45630372, -3.21165662}, {0.48780357, 0.34545271, -3.04026873}}); helpme::Matrix<double> refVirial2({{0.61199705, 0.49055936, 0.54134312, 2.28222850, 2.36819958, -9.94504929}}); double refEnergy3 = 6.871736497; helpme::Matrix<double> refForces3({{-0.76684907, -0.94791216, 7.41216206}, {0.61560181, 0.54001262, -2.95904725}, {0.42875798, 0.68237489, -3.02853111}, {-1.40351882, -1.29196455, 5.91724551}, {0.52358846, 0.58722357, -3.77349856}, {0.60098832, 0.43008731, -3.56873433}}); helpme::Matrix<double> refVirial3({{0.69619831, 0.55213933, 0.60823304, 2.78138346, 2.86610280, -11.39571070}}); double refEnergy4 = 6.8718135; helpme::Matrix<double> refForces4({{-0.76682663, -0.79604124, 7.42058381}, {0.61559595, 0.45348406, -2.96384799}, {0.42875295, 0.57298883, -3.03458962}, {-1.40348529, -1.08508863, 5.92864929}, {0.52356758, 0.49320229, -3.77867550}, {0.60096417, 0.36124367, -3.57252549}}); helpme::Matrix<double> refVirial4({{0.69622261, 0.55220016, 0.60784358, 2.78135060, 2.86647846, -11.39584386}}); double refEnergy5 = 7.55899485; helpme::Matrix<double> refForces5({{-0.84350929, -0.87564537, 8.16264219}, {0.67715554, 0.49883247, -3.26023278}, {0.47162825, 0.63028771, -3.33804858}, {-1.54383381, -1.19359749, 6.52151422}, {0.57592433, 0.54252252, -4.15654305}, {0.66106059, 0.39736803, -3.92977804}}); helpme::Matrix<double> refVirial5({{0.76584487, 0.60742018, 0.66862794, 3.05948566, 3.15312630, -12.53542824}}); double refEnergy6 = 7.558688228; helpme::Matrix<double> refForces6({{-0.84303319, -0.87557676, 8.16169899}, {0.67691837, 0.49890558, -3.25971866}, {0.47193007, 0.63032536, -3.33749220}, {-1.54317624, -1.19339693, 6.52017613}, {0.57607320, 0.54246197, -4.15560408}, {0.66144590, 0.39732351, -3.92883941}}); helpme::Matrix<double> refVirial6({{0.76545755, 0.60761239, 0.66897556, 3.05912581, 3.15274330, -12.53308757}}); double refEnergy7 = 0.007626089169; helpme::Matrix<double> refForces7({{-0.00111343, -0.00115672, 0.00829002}, {0.00081670, 0.00059903, -0.00320443}, {0.00059187, 0.00079872, -0.00324183}, {-0.00187292, -0.00145863, 0.00637289}, {0.00076641, 0.00072244, -0.00423731}, {0.00081164, 0.00049523, -0.00397890}}); helpme::Matrix<double> refVirial7({{0.00068085, 0.00059011, 0.00057443, 0.00357792, 0.00368895, -0.01097979}}); SECTION("EFV routines") { double energy; helpme::Matrix<double> forces(6, 3); helpme::Matrix<double> virial(1, 6); auto pme = std::unique_ptr<PMEInstanceD>(new PMEInstanceD); pme->setup(1, 0.3, splineOrder, nfftx, nffty, nfftz, ccelec, 1); // Start with random setup forces.setZero(); virial.setZero(); pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); REQUIRE(forces.almostEquals(refForces1)); REQUIRE(virial.almostEquals(refVirial1)); // Call update with same parameters, to make sure everything's the same forces.setZero(); virial.setZero(); pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); REQUIRE(forces.almostEquals(refForces1)); REQUIRE(virial.almostEquals(refVirial1)); // Now change the parameters, and make sure it updates correctly forces.setZero(); virial.setZero(); pme->setLatticeVectors(21.5, 22.2, 20.1, 94, 91, 91, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy2).margin(TOL)); REQUIRE(forces.almostEquals(refForces2)); REQUIRE(virial.almostEquals(refVirial2)); // Back to the original setup forces.setZero(); virial.setZero(); pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); REQUIRE(forces.almostEquals(refForces1)); REQUIRE(virial.almostEquals(refVirial1)); // Same, but new kappa value forces.setZero(); virial.setZero(); pme->setup(1, 0.32, splineOrder, nfftx, nffty, nfftz, ccelec, 1); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy3).margin(TOL)); REQUIRE(forces.almostEquals(refForces3)); REQUIRE(virial.almostEquals(refVirial3)); // Adjust the grid slightly forces.setZero(); virial.setZero(); pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, ccelec, 1); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy4).margin(TOL)); REQUIRE(forces.almostEquals(refForces4)); REQUIRE(virial.almostEquals(refVirial4)); // Adjust the scale factor slightly forces.setZero(); virial.setZero(); pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy5).margin(TOL)); REQUIRE(forces.almostEquals(refForces5)); REQUIRE(virial.almostEquals(refVirial5)); // Adjust the scale factor slightly forces.setZero(); virial.setZero(); pme->setup(1, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy6).margin(TOL)); REQUIRE(forces.almostEquals(refForces6)); REQUIRE(virial.almostEquals(refVirial6)); // Change the physics from coulomb to some weird disperion forces.setZero(); virial.setZero(); pme->setup(6, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeEFVRec(0, charges, coords, forces, virial); REQUIRE(energy == Approx(refEnergy7).margin(TOL)); REQUIRE(forces.almostEquals(refForces7)); REQUIRE(virial.almostEquals(refVirial7)); } SECTION("EF routines") { double energy; helpme::Matrix<double> forces(6, 3); auto pme = std::unique_ptr<PMEInstanceD>(new PMEInstanceD); pme->setup(1, 0.3, splineOrder, nfftx, nffty, nfftz, ccelec, 1); // Start with random setup forces.setZero(); pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); REQUIRE(forces.almostEquals(refForces1)); // Call update with same parameters, to make sure everything's the same forces.setZero(); pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); REQUIRE(forces.almostEquals(refForces1)); // Now change the parameters, and make sure it updates correctly forces.setZero(); pme->setLatticeVectors(21.5, 22.2, 20.1, 94, 91, 91, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy2).margin(TOL)); REQUIRE(forces.almostEquals(refForces2)); // Back to the original setup forces.setZero(); pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); REQUIRE(forces.almostEquals(refForces1)); // Same, but new kappa value forces.setZero(); pme->setup(1, 0.32, splineOrder, nfftx, nffty, nfftz, ccelec, 1); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy3).margin(TOL)); REQUIRE(forces.almostEquals(refForces3)); // Adjust the grid slightly forces.setZero(); pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, ccelec, 1); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy4).margin(TOL)); REQUIRE(forces.almostEquals(refForces4)); // Adjust the scale factor slightly forces.setZero(); pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy5).margin(TOL)); REQUIRE(forces.almostEquals(refForces5)); // Adjust the scale factor slightly forces.setZero(); pme->setup(1, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy6).margin(TOL)); REQUIRE(forces.almostEquals(refForces6)); // Change the physics from coulomb to some weird disperion forces.setZero(); pme->setup(6, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeEFRec(0, charges, coords, forces); REQUIRE(energy == Approx(refEnergy7).margin(TOL)); REQUIRE(forces.almostEquals(refForces7)); } SECTION("E routines") { double energy; auto pme = std::unique_ptr<PMEInstanceD>(new PMEInstanceD); pme->setup(1, 0.3, splineOrder, nfftx, nffty, nfftz, ccelec, 1); // Start with random setup pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); // Call update with same parameters, to make sure everything's the same pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); // Now change the parameters, and make sure it updates correctly pme->setLatticeVectors(21.5, 22.2, 20.1, 94, 91, 91, PMEInstanceD::LatticeType::XAligned); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy2).margin(TOL)); // Back to the original setup pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy1).margin(TOL)); // Same, but new kappa value pme->setup(1, 0.32, splineOrder, nfftx, nffty, nfftz, ccelec, 1); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy3).margin(TOL)); // Adjust the grid slightly pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, ccelec, 1); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy4).margin(TOL)); // Adjust the scale factor slightly pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy5).margin(TOL)); // Adjust the scale factor slightly pme->setup(1, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy6).margin(TOL)); // Change the physics from coulomb to some weird disperion pme->setup(6, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1); energy = pme->computeERec(0, charges, coords); REQUIRE(energy == Approx(refEnergy7).margin(TOL)); } }
49.569079
116
0.585308
sjvs
eb88d9cdfe66817f340c9c4668261a9e17b791bb
1,152
cpp
C++
Platinum/2015-16/Open 2016/landscape.cpp
WilliamYue37/USACO
f18b222ff505e2640018288a608dbed6d24ae64a
[ "MIT" ]
null
null
null
Platinum/2015-16/Open 2016/landscape.cpp
WilliamYue37/USACO
f18b222ff505e2640018288a608dbed6d24ae64a
[ "MIT" ]
null
null
null
Platinum/2015-16/Open 2016/landscape.cpp
WilliamYue37/USACO
f18b222ff505e2640018288a608dbed6d24ae64a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ff first #define ss second typedef long long ll; typedef long double ld; typedef pair<int, int> pi; typedef pair<long long, long long> pl; const int MOD = 1e9 + 7; const ll INF = 1e18; const double EPS = 1e-6; int N; ll X, Y, Z; priority_queue<ll, vector<ll>, greater<ll>> extra, need; int main() { freopen("landscape.in", "r", stdin); freopen("landscape.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> X >> Y >> Z; ll ans = 0; for (int i = 0; i < N; ++i) { int A, B; cin >> A >> B; int delta = B - A; if (delta > 0) { for (int j = 0; j < delta; ++j) { ll cost = X; if (!extra.empty() && extra.top() + Z * i < X) { cost = extra.top() + Z * i; extra.pop(); } ans += cost; need.push(-cost - Z * i); } } else { for (int j = 0; j < -delta; ++j) { ll cost = Y; if (!need.empty() && need.top() + Z * i < Y) { cost = need.top() + Z * i; need.pop(); } ans += cost; extra.push(-cost - Z * i); } } } cout << ans << '\n'; return 0; }
20.571429
77
0.497396
WilliamYue37
eb8b5c76352ef063473998ece1318d1557ced8ba
4,163
cpp
C++
libraries/pg/source/FocusListLiftingStrategy.cpp
Noxsense/mCRL2
dd2fcdd6eb8b15af2729633041c2dbbd2216ad24
[ "BSL-1.0" ]
61
2018-05-24T13:14:05.000Z
2022-03-29T11:35:03.000Z
libraries/pg/source/FocusListLiftingStrategy.cpp
Noxsense/mCRL2
dd2fcdd6eb8b15af2729633041c2dbbd2216ad24
[ "BSL-1.0" ]
229
2018-05-28T08:31:09.000Z
2022-03-21T11:02:41.000Z
libraries/pg/source/FocusListLiftingStrategy.cpp
Noxsense/mCRL2
dd2fcdd6eb8b15af2729633041c2dbbd2216ad24
[ "BSL-1.0" ]
28
2018-04-11T14:09:39.000Z
2022-02-25T15:57:39.000Z
// Copyright (c) 2009-2013 University of Twente // Copyright (c) 2009-2013 Michael Weber <michaelw@cs.utwente.nl> // Copyright (c) 2009-2013 Maks Verver <maksverver@geocities.com> // Copyright (c) 2009-2013 Eindhoven University of Technology // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "mcrl2/pg/FocusListLiftingStrategy.h" /*! Credit for a vertex when it is put on the focus list. */ static const unsigned initial_credit = 2; /*! Credit increase when a vertex on the focus list is successfully lifted. */ static const unsigned credit_increase = 2; FocusListLiftingStrategy::FocusListLiftingStrategy( const ParityGame &game, bool alternate, verti max_size, std::size_t max_lifts ) : LiftingStrategy(), V_(game.graph().V()), max_lift_attempts_(max_lifts), phase_(1), num_lift_attempts_(0), lls_(game, alternate) { focus_list_.reserve(max_size); } void FocusListLiftingStrategy::lifted(verti vertex) { if (phase_ == 1) { lls_.lifted(vertex); if (focus_list_.size() < focus_list_.capacity()) { focus_list_.push_back(std::make_pair(vertex, initial_credit)); } } else /* phase_ == 2 */ { if (vertex == read_pos_->first) prev_lifted_ = true; } } verti FocusListLiftingStrategy::next() { verti res = phase_ == 1 ? phase1() : phase2(); ++num_lift_attempts_; return res; } verti FocusListLiftingStrategy::phase1() { if (focus_list_.size() == focus_list_.capacity() || num_lift_attempts_ >= V_) { if (focus_list_.empty()) { /* This can only happen if lls_.num_failed >= V too */ assert(lls_.next() == NO_VERTEX); return NO_VERTEX; } /* Switch to phase 2: */ phase_ = 2; num_lift_attempts_ = 0; read_pos_ = write_pos_ = focus_list_.begin(); mCRL2log(mcrl2::log::verbose) << "Switching to focus list of size " << focus_list_.size() << std::endl; return phase2(); } return lls_.next(); } verti FocusListLiftingStrategy::phase2() { if (num_lift_attempts_ > 0) { // Adjust previous vertex credit and move to next position focus_list::value_type prev = *read_pos_++; if (prev_lifted_) { prev.second += credit_increase; *write_pos_++ = prev; } else if (prev.second > 0) { prev.second /= 2; *write_pos_++ = prev; } // else, drop from list. } // Check if we've reached the end of the focus list; if so, restart: if (read_pos_ == focus_list_.end()) { focus_list_.erase(write_pos_, focus_list_.end()); read_pos_ = write_pos_ = focus_list_.begin(); } if (focus_list_.empty() || num_lift_attempts_ >= max_lift_attempts_) { if (focus_list_.empty()) { mCRL2log(mcrl2::log::verbose) << "Focus list exhausted." << std::endl; } else { mCRL2log(mcrl2::log::verbose) << "Maximum lift attempts (" << max_lift_attempts_ << ") on focus list reached." << std::endl; focus_list_.clear(); } /* Switch to phase 1 */ phase_ = 1; num_lift_attempts_ = 0; return phase1(); } // Return current item on the focus list prev_lifted_ = false; return read_pos_->first; } LiftingStrategy *FocusListLiftingStrategyFactory::create( const ParityGame &game, const SmallProgressMeasures &spm ) { (void)spm; // unused /* Ratio is absolute value if >1, or a fraction of the size of the game's vertex set if <= 1. */ verti V = game.graph().V(); verti max_size = (size_ratio_ > 1) ? static_cast<verti>(size_ratio_) : static_cast<verti>(size_ratio_*V); // XXX Ugly casting here if (max_size == 0) max_size = 1; if (max_size > V) max_size = V; verti max_lifts = (verti)(lift_ratio_ * max_size); return new FocusListLiftingStrategy( game, alternate_, max_size, max_lifts ); }
30.166667
136
0.617103
Noxsense
eb8bcd0a2f8df7ca38e42fd06ac2acd945613e79
984
cpp
C++
examples/code-samples/cpp/23_AddTags.cpp
MarkusRannare/modio-sdk
70220009ac6c375bebd4b807de1e7f8a19680a41
[ "MIT" ]
42
2017-11-14T19:45:20.000Z
2019-02-03T02:43:24.000Z
examples/code-samples/cpp/23_AddTags.cpp
MarkusRannare/modio-sdk
70220009ac6c375bebd4b807de1e7f8a19680a41
[ "MIT" ]
16
2019-05-09T02:14:02.000Z
2020-09-03T05:35:49.000Z
examples/code-samples/cpp/23_AddTags.cpp
MarkusRannare/modio-sdk
70220009ac6c375bebd4b807de1e7f8a19680a41
[ "MIT" ]
15
2019-07-15T04:26:01.000Z
2020-09-12T03:58:19.000Z
#include "modio.h" #include <iostream> int main(void) { modio::Instance modio_instance(MODIO_ENVIRONMENT_TEST, 7, "e91c01b8882f4affeddd56c96111977b"); volatile static bool finished = false; auto wait = [&]() { while (!finished) { modio_instance.sleep(10); modio_instance.process(); } }; auto finish = [&]() { finished = true; }; u32 mod_id; std::cout << "Enter the mod id: " << std::endl; std::cin >> mod_id; std::vector<std::string> tags; tags.push_back("Hard"); // We add tags to a mod by providing the tag names. Remember, they must be valid tags allowed by the parrent game modio_instance.addModTags(mod_id, tags, [&](const modio::Response &response) { std::cout << "Add tags response: " << response.code << std::endl; if (response.code == 201) { std::cout << "Tags added successfully" << std::endl; } finish(); }); wait(); std::cout << "Process finished" << std::endl; return 0; }
21.866667
115
0.619919
MarkusRannare
eb8cae61d7a8bba7c7cbd243a287ad68f817f9b9
5,983
cc
C++
src/samples/sample.cc
wjp-release/eventual
1e425cf54291c02663dfd3462093c0707cbe9690
[ "MIT" ]
1
2019-06-21T01:48:33.000Z
2019-06-21T01:48:33.000Z
src/samples/sample.cc
wjp-release/eventual
1e425cf54291c02663dfd3462093c0707cbe9690
[ "MIT" ]
null
null
null
src/samples/sample.cc
wjp-release/eventual
1e425cf54291c02663dfd3462093c0707cbe9690
[ "MIT" ]
null
null
null
#include "todo.hpp" #include "zero_copy_value.hpp" #include "sample.h" // dummy service routines that simulate background threads or threadpools that actually complete the async tasks void dummy_service_routine(todo td) { this_thread::sleep_for(chrono::milliseconds(200)); td.resolve(); td.wake(); } void dummy_service_routine_sometimes_reject(todo td) { this_thread::sleep_for(chrono::milliseconds(400)); if(u(e)<6){ td.resolve(); }else{ td.reject(); // 40% } td.wake(); } void dummy_error_handling(todo td) { this_thread::sleep_for(chrono::milliseconds(100)); td.finish(); td.wake(); } void ftp_conn_service(todo td) { dummy_service_routine(td); } void downloading_service(todo td) { dummy_service_routine(td); } void uncompressing_service(todo td) { dummy_service_routine(td); } void decoding_service(todo td) { dummy_service_routine_sometimes_reject(td); } void fwrite_service(todo td) { dummy_service_routine_sometimes_reject(td); } // style 1: // todo{job0}(job1)(job2)(job3)(job4,job3_err)[job4_err](); // 1. define jobs first // 2. chain functions with parentheses! {..}(..)(..)(..)[..] // 3. use an empty () to kick off the whole callback chain // {} captures init function for todo constructor // () captures both on_resolve & on_reject // [] captures on_reject only void test1() { auto job0=[](todo* self){ cout<<"job0 connect to ftp server \n"; ftp_conn_service(*self); }; auto job1=[](todo* self){ cout<<"job1 download file todo.zip \n"; downloading_service(*self); }; auto job2=[](todo* self){ cout<<"job2 unzip file todo.zip \n"; uncompressing_service(*self); }; auto job3=[](todo* self){ cout<<"job3 decipher file todo.data \n"; decoding_service(*self); }; auto job4=[](todo* self){ cout<<"job4 write file todo.new \n"; fwrite_service(*self); }; auto job3_err=[](todo* self){ cout<<"triggered by job3 decoding_service failure! \n"; cout<<"quit now\n"; dummy_error_handling(*self); }; auto job4_err=[](todo* self){ cout<<"triggered by job4 fwrite_service failure! \n"; cout<<"quit now\n"; dummy_error_handling(*self); }; todo{job0}(job1)(job2)(job3)(job4,job3_err)[job4_err](); } // style 2: // use methods rather than parenthese void test2() { todo td([](todo* self){ //func === std::function<void(todo*)> cout<<"job0 connect to ftp server \n"; ftp_conn_service(*self); }); td.then([](todo* self){ cout<<"job1 download file todo.zip \n"; downloading_service(*self); }).then([](todo* self){ //then(func,func) === operator(func,func); then(nullptr, func) === operator[func] cout<<"job2 unzip file todo.zip \n"; uncompressing_service(*self); }).then([](todo* self){ cout<<"job3 decipher file todo.data \n"; decoding_service(*self); }).then([](todo* self){ cout<<"job4 write file todo.new \n"; fwrite_service(*self); }, [](todo* self){ cout<<"triggered by job3 decoding_service failure! \n"; cout<<"quit now\n"; dummy_error_handling(*self); }).then(nullptr, [](todo* self){ cout<<"triggered by job4 fwrite_service failure! \n"; cout<<"quit now\n"; dummy_error_handling(*self); }); td.run(); // run() === operator() } // style 3: // all in one closure void test3() { todo { [](todo* self){ cout<<"job0 connect to ftp server \n"; ftp_conn_service(*self); } } ( [](todo* self){ cout<<"job1 download file todo.zip \n"; downloading_service(*self); } ) ( [](todo* self){ cout<<"job2 unzip file todo.zip \n"; uncompressing_service(*self); } ) ( [](todo* self){ cout<<"job3 decipher file todo.data \n"; decoding_service(*self); } ) ( [](todo* self){ cout<<"job4 write file todo.new \n"; fwrite_service(*self); }, [](todo* self){ cout<<"triggered by job3 decoding_service failure! \n"; cout<<"quit now\n"; dummy_error_handling(*self); } ) ( //c++ does not allow consequtive left square brackets here, so we have to use () with first arg set to nullptr nullptr, [](todo* self){ cout<<"triggered by job4 fwrite_service failure! \n"; cout<<"quit now\n"; dummy_error_handling(*self); } )(); } void test_zero_copy_value() { zero_copy_value a; cout<<"a empty: "<<a.empty()<<endl; //1 cout<<"a typename: "<<a.type()<<endl; //Dn zero_copy_value b(123); cout<<"b typename: "<<b.type()<<endl; //i cout<<"b data as int: "<<b.data<int>()<<endl; //123 zero_copy_value c(123.456); cout<<"c typename: "<<c.type()<<endl; //d cout<<"c data as double "<<c.data<double>()<<endl; zero_copy_value d = c; // ctor ref++ zero_copy_value e = c.copy(); // make a copy cout<<"c==d: "<<(c==d) <<endl; cout<<"e==c: "<<(c==e) <<endl; cout<<"e typename: "<<e.type()<<endl; //d cout<<"e data as double "<<e.data<double>()<<endl; zero_copy_value f = 100; // construct from a specific type cout<<"f typename: "<<f.type()<<endl; //i // cout<<"f data as double "<<f.data<double>()<<endl; //throw exception (should be int) f=e; //operator= lvalue ref cout<<"f typename: "<<f.type()<<endl; //i cout<<"f data as double "<<e.data<double>()<<endl; f=e.copy(); // operator= rvalue! cout<<"f typename: "<<f.type()<<endl; //i cout<<"f data as double "<<e.data<double>()<<endl; } int main() { promise1(); cout<<"sample ends\n"; cin.get(); cout<<"program ends\n"; return 0; }
27.444954
116
0.571118
wjp-release
eb9172f1e3acb18c6c71dec13b45b7688e73e744
4,904
cpp
C++
test/core/FilesystemDeviceCacheTest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
test/core/FilesystemDeviceCacheTest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
test/core/FilesystemDeviceCacheTest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include <cppunit/extensions/HelperMacros.h> #include <Poco/File.h> #include "cppunit/BetterAssert.h" #include "cppunit/FileTestFixture.h" #include "core/FilesystemDeviceCache.h" #include "model/DevicePrefix.h" using namespace Poco; namespace BeeeOn { class FilesystemDeviceCacheTest : public FileTestFixture { CPPUNIT_TEST_SUITE(FilesystemDeviceCacheTest); CPPUNIT_TEST(testPairUnpair); CPPUNIT_TEST(testPrepaired); CPPUNIT_TEST(testBatchPair); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void testPairUnpair(); void testNothingPrepaired(); void testPrepaired(); void testBatchPair(); private: FilesystemDeviceCache m_cache; }; CPPUNIT_TEST_SUITE_REGISTRATION(FilesystemDeviceCacheTest); void FilesystemDeviceCacheTest::setUp() { setUpAsDirectory(); m_cache.setCacheDir(testingPath().toString()); } void FilesystemDeviceCacheTest::tearDown() { // remove all created named mutexes for (const auto &prefix : DevicePrefix::all()) { File mutex("/tmp/" + prefix.toString() + ".mutex"); try { mutex.remove(); } catch (...) {} } } /** * @brief Test we can pair and unpair a device and such device can be * detected as paired. Paired device would always have a corresponding * file created in the filesystem. */ void FilesystemDeviceCacheTest::testPairUnpair() { const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE; const Path vdev(testingPath(), "vdev"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev); const Path a300000001020304(testingPath(), "vdev/0xa300000001020304"); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); m_cache.markPaired({0xa300000001020304}); CPPUNIT_ASSERT_FILE_EXISTS(vdev); CPPUNIT_ASSERT_FILE_EXISTS(a300000001020304); CPPUNIT_ASSERT_EQUAL(1, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(m_cache.paired({0xa300000001020304})); m_cache.markUnpaired({0xa300000001020304}); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); } /** * @brief Test we can pre-pair a set of devices by creating appropriate files * in the filesystem. Only such pre-paired devices are marked as paired. */ void FilesystemDeviceCacheTest::testPrepaired() { const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE; const Path vdev(testingPath(), "vdev"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev); CPPUNIT_ASSERT_NO_THROW(File(vdev).createDirectories()); const Path a3000000aaaaaaaa(testingPath(), "vdev/0xa3000000aaaaaaaa"); const Path a3000000bbbbbbbb(testingPath(), "vdev/0xa3000000bbbbbbbb"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_NO_THROW(File(a3000000aaaaaaaa).createFile()); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_NO_THROW(File(a3000000bbbbbbbb).createFile()); CPPUNIT_ASSERT_EQUAL(2, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(m_cache.paired({0xa3000000aaaaaaaa})); CPPUNIT_ASSERT(m_cache.paired({0xa3000000bbbbbbbb})); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); } /** * @brief Test pairing as a batch process. All already paired devices * should be removed and only the given set is to be paired. The pairing * status is visible when watching the filesystem. */ void FilesystemDeviceCacheTest::testBatchPair() { const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE; const Path vdev(testingPath(), "vdev"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev); const Path a3000000aaaaaaaa(testingPath(), "vdev/0xa3000000aaaaaaaa"); const Path a3000000bbbbbbbb(testingPath(), "vdev/0xa3000000bbbbbbbb"); const Path a300000001020304(testingPath(), "vdev/0xa300000001020304"); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); m_cache.markPaired(VDEV, {{0xa3000000aaaaaaaa}, {0xa3000000bbbbbbbb}}); CPPUNIT_ASSERT_FILE_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_FILE_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304); CPPUNIT_ASSERT_EQUAL(2, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(m_cache.paired({0xa3000000aaaaaaaa})); CPPUNIT_ASSERT(m_cache.paired({0xa3000000bbbbbbbb})); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); m_cache.markPaired(VDEV, {{0xa300000001020304}}); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_FILE_EXISTS(a300000001020304); CPPUNIT_ASSERT_EQUAL(1, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(!m_cache.paired({0xa3000000aaaaaaaa})); CPPUNIT_ASSERT(!m_cache.paired({0xa3000000bbbbbbbb})); CPPUNIT_ASSERT(m_cache.paired({0xa300000001020304})); m_cache.markPaired(VDEV, {}); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304); CPPUNIT_ASSERT_DIR_EMPTY(vdev); } }
29.365269
77
0.791191
jozhalaj
eb92150338c7ec78afe9c8e8ac711782083bc78a
1,094
cpp
C++
leetcode/1-bit-2-bit.cpp
Mantissa-23/miniprojects
552b1329cc44b5036d1bc8c12dc83b802b18da29
[ "MIT" ]
null
null
null
leetcode/1-bit-2-bit.cpp
Mantissa-23/miniprojects
552b1329cc44b5036d1bc8c12dc83b802b18da29
[ "MIT" ]
null
null
null
leetcode/1-bit-2-bit.cpp
Mantissa-23/miniprojects
552b1329cc44b5036d1bc8c12dc83b802b18da29
[ "MIT" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <vector> #include "doctest.h" #include "util.h" using namespace std; class Solution { public: bool isOneBitCharacter(vector<int>& bits) { if(bits.size() < 2) { return !bits[0]; } if(bits[bits.size() - 2] == 0) return true; else { int i = 0; while(i < bits.size() - 1) { if(bits[i] == 0) i++; else { i += 2; } } if(i == bits.size() - 1) return true; } return false; } }; TEST_CASE("tests") { Solution s; vector<int> input; bool soln; SUBCASE("1") { input = {1, 0, 0}; soln = true; } SUBCASE("2") { input = {1, 1, 1, 0}; soln = false; } SUBCASE("3") { input = {0, 1, 0}; soln = false; } SUBCASE("4") { input = {0, 1, 0, 0}; soln = true; } SUBCASE("5") { input = {1, 1, 0}; soln = true; } SUBCASE("6") { input = {1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0}; soln = false; } print_vector(input); CHECK(s.isOneBitCharacter(input) == soln); }
16.575758
58
0.47989
Mantissa-23
eb93ef22b348584b09ab725a4400cc139f13d3b9
57,609
cpp
C++
src/js/builtin/RegExp.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
149
2018-12-23T09:08:00.000Z
2022-02-02T09:18:38.000Z
src/js/builtin/RegExp.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
null
null
null
src/js/builtin/RegExp.cpp
fengjixuchui/blazefox
d5c732ac7305a79fe20704c2d134c130f14eca83
[ "MIT" ]
56
2018-12-23T18:11:40.000Z
2021-11-30T13:18:17.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "builtin/RegExp.h" #include "mozilla/CheckedInt.h" #include "mozilla/TypeTraits.h" #include "frontend/TokenStream.h" #include "irregexp/RegExpParser.h" #include "jit/InlinableNatives.h" #include "util/StringBuffer.h" #include "util/Unicode.h" #include "vm/JSContext.h" #include "vm/RegExpStatics.h" #include "vm/SelfHosting.h" #include "vm/JSObject-inl.h" #include "vm/NativeObject-inl.h" #include "vm/ObjectOperations-inl.h" #include "vm/UnboxedObject-inl.h" using namespace js; using mozilla::CheckedInt; using mozilla::IsAsciiDigit; using JS::CompileOptions; /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 16-25. */ bool js::CreateRegExpMatchResult(JSContext* cx, HandleString input, const MatchPairs& matches, MutableHandleValue rval) { MOZ_ASSERT(input); /* * Create the (slow) result array for a match. * * Array contents: * 0: matched string * 1..pairCount-1: paren matches * input: input string * index: start index for the match */ /* Get the templateObject that defines the shape and type of the output object */ JSObject* templateObject = cx->realm()->regExps.getOrCreateMatchResultTemplateObject(cx); if (!templateObject) { return false; } size_t numPairs = matches.length(); MOZ_ASSERT(numPairs > 0); /* Step 17. */ RootedArrayObject arr(cx, NewDenseFullyAllocatedArrayWithTemplate(cx, numPairs, templateObject)); if (!arr) { return false; } /* Steps 22-24. * Store a Value for each pair. */ for (size_t i = 0; i < numPairs; i++) { const MatchPair& pair = matches[i]; if (pair.isUndefined()) { MOZ_ASSERT(i != 0); /* Since we had a match, first pair must be present. */ arr->setDenseInitializedLength(i + 1); arr->initDenseElement(i, UndefinedValue()); } else { JSLinearString* str = NewDependentString(cx, input, pair.start, pair.length()); if (!str) { return false; } arr->setDenseInitializedLength(i + 1); arr->initDenseElement(i, StringValue(str)); } } /* Step 20 (reordered). * Set the |index| property. */ arr->setSlot(RegExpRealm::MatchResultObjectIndexSlot, Int32Value(matches[0].start)); /* Step 21 (reordered). * Set the |input| property. */ arr->setSlot(RegExpRealm::MatchResultObjectInputSlot, StringValue(input)); #ifdef DEBUG RootedValue test(cx); RootedId id(cx, NameToId(cx->names().index)); if (!NativeGetProperty(cx, arr, id, &test)) { return false; } MOZ_ASSERT(test == arr->getSlot(RegExpRealm::MatchResultObjectIndexSlot)); id = NameToId(cx->names().input); if (!NativeGetProperty(cx, arr, id, &test)) { return false; } MOZ_ASSERT(test == arr->getSlot(RegExpRealm::MatchResultObjectInputSlot)); #endif /* Step 25. */ rval.setObject(*arr); return true; } static int32_t CreateRegExpSearchResult(const MatchPairs& matches) { /* Fit the start and limit of match into a int32_t. */ uint32_t position = matches[0].start; uint32_t lastIndex = matches[0].limit; MOZ_ASSERT(position < 0x8000); MOZ_ASSERT(lastIndex < 0x8000); return position | (lastIndex << 15); } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-14, except 12.a.i, 12.c.i.1. */ static RegExpRunStatus ExecuteRegExpImpl(JSContext* cx, RegExpStatics* res, MutableHandleRegExpShared re, HandleLinearString input, size_t searchIndex, VectorMatchPairs* matches, size_t* endIndex) { RegExpRunStatus status = RegExpShared::execute(cx, re, input, searchIndex, matches, endIndex); /* Out of spec: Update RegExpStatics. */ if (status == RegExpRunStatus_Success && res) { if (matches) { if (!res->updateFromMatchPairs(cx, input, *matches)) { return RegExpRunStatus_Error; } } else { res->updateLazily(cx, input, re, searchIndex); } } return status; } /* Legacy ExecuteRegExp behavior is baked into the JSAPI. */ bool js::ExecuteRegExpLegacy(JSContext* cx, RegExpStatics* res, Handle<RegExpObject*> reobj, HandleLinearString input, size_t* lastIndex, bool test, MutableHandleValue rval) { RootedRegExpShared shared(cx, RegExpObject::getShared(cx, reobj)); if (!shared) { return false; } VectorMatchPairs matches; RegExpRunStatus status = ExecuteRegExpImpl(cx, res, &shared, input, *lastIndex, &matches, nullptr); if (status == RegExpRunStatus_Error) { return false; } if (status == RegExpRunStatus_Success_NotFound) { /* ExecuteRegExp() previously returned an array or null. */ rval.setNull(); return true; } *lastIndex = matches[0].limit; if (test) { /* Forbid an array, as an optimization. */ rval.setBoolean(true); return true; } return CreateRegExpMatchResult(cx, input, matches, rval); } static bool CheckPatternSyntaxSlow(JSContext* cx, HandleAtom pattern, RegExpFlag flags) { CompileOptions options(cx); frontend::TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr); return irregexp::ParsePatternSyntax(dummyTokenStream, cx->tempLifoAlloc(), pattern, flags & UnicodeFlag); } static RegExpShared* CheckPatternSyntax(JSContext* cx, HandleAtom pattern, RegExpFlag flags) { // If we already have a RegExpShared for this pattern/flags, we can // avoid the much slower CheckPatternSyntaxSlow call. if (RegExpShared* shared = cx->zone()->regExps().maybeGet(pattern, flags)) { #ifdef DEBUG // Assert the pattern is valid. if (!CheckPatternSyntaxSlow(cx, pattern, flags)) { MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed()); return nullptr; } #endif return shared; } if (!CheckPatternSyntaxSlow(cx, pattern, flags)) { return nullptr; } // Allocate and return a new RegExpShared so we will hit the fast path // next time. return cx->zone()->regExps().get(cx, pattern, flags); } /* * ES 2016 draft Mar 25, 2016 21.2.3.2.2. * * Steps 14-15 set |obj|'s "lastIndex" property to zero. Some of * RegExpInitialize's callers have a fresh RegExp not yet exposed to script: * in these cases zeroing "lastIndex" is infallible. But others have a RegExp * whose "lastIndex" property might have been made non-writable: here, zeroing * "lastIndex" can fail. We efficiently solve this problem by completely * removing "lastIndex" zeroing from the provided function. * * CALLERS MUST HANDLE "lastIndex" ZEROING THEMSELVES! * * Because this function only ever returns a user-provided |obj| in the spec, * we omit it and just return the usual success/failure. */ static bool RegExpInitializeIgnoringLastIndex(JSContext* cx, Handle<RegExpObject*> obj, HandleValue patternValue, HandleValue flagsValue) { RootedAtom pattern(cx); if (patternValue.isUndefined()) { /* Step 1. */ pattern = cx->names().empty; } else { /* Step 2. */ pattern = ToAtom<CanGC>(cx, patternValue); if (!pattern) { return false; } } /* Step 3. */ RegExpFlag flags = RegExpFlag(0); if (!flagsValue.isUndefined()) { /* Step 4. */ RootedString flagStr(cx, ToString<CanGC>(cx, flagsValue)); if (!flagStr) { return false; } /* Step 5. */ if (!ParseRegExpFlags(cx, flagStr, &flags)) { return false; } } /* Steps 7-8. */ RegExpShared* shared = CheckPatternSyntax(cx, pattern, flags); if (!shared) { return false; } /* Steps 9-12. */ obj->initIgnoringLastIndex(pattern, flags); obj->setShared(*shared); return true; } /* ES 2016 draft Mar 25, 2016 21.2.3.2.3. */ bool js::RegExpCreate(JSContext* cx, HandleValue patternValue, HandleValue flagsValue, MutableHandleValue rval) { /* Step 1. */ Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject)); if (!regexp) { return false; } /* Step 2. */ if (!RegExpInitializeIgnoringLastIndex(cx, regexp, patternValue, flagsValue)) { return false; } regexp->zeroLastIndex(cx); rval.setObject(*regexp); return true; } MOZ_ALWAYS_INLINE bool IsRegExpObject(HandleValue v) { return v.isObject() && v.toObject().is<RegExpObject>(); } /* ES6 draft rc3 7.2.8. */ bool js::IsRegExp(JSContext* cx, HandleValue value, bool* result) { /* Step 1. */ if (!value.isObject()) { *result = false; return true; } RootedObject obj(cx, &value.toObject()); /* Steps 2-3. */ RootedValue isRegExp(cx); RootedId matchId(cx, SYMBOL_TO_JSID(cx->wellKnownSymbols().match)); if (!GetProperty(cx, obj, obj, matchId, &isRegExp)) { return false; } /* Step 4. */ if (!isRegExp.isUndefined()) { *result = ToBoolean(isRegExp); return true; } /* Steps 5-6. */ ESClass cls; if (!GetClassOfValue(cx, value, &cls)) { return false; } *result = cls == ESClass::RegExp; return true; } /* ES6 B.2.5.1. */ MOZ_ALWAYS_INLINE bool regexp_compile_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); Rooted<RegExpObject*> regexp(cx, &args.thisv().toObject().as<RegExpObject>()); // Step 3. RootedValue patternValue(cx, args.get(0)); ESClass cls; if (!GetClassOfValue(cx, patternValue, &cls)) { return false; } if (cls == ESClass::RegExp) { // Step 3a. if (args.hasDefined(1)) { JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NEWREGEXP_FLAGGED); return false; } // Beware! |patternObj| might be a proxy into another compartment, so // don't assume |patternObj.is<RegExpObject>()|. For the same reason, // don't reuse the RegExpShared below. RootedObject patternObj(cx, &patternValue.toObject()); RootedAtom sourceAtom(cx); RegExpFlag flags; { // Step 3b. RegExpShared* shared = RegExpToShared(cx, patternObj); if (!shared) { return false; } sourceAtom = shared->getSource(); flags = shared->getFlags(); } // Step 5, minus lastIndex zeroing. regexp->initIgnoringLastIndex(sourceAtom, flags); } else { // Step 4. RootedValue P(cx, patternValue); RootedValue F(cx, args.get(1)); // Step 5, minus lastIndex zeroing. if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F)) { return false; } } // The final niggling bit of step 5. // // |regexp| is user-exposed, but if its "lastIndex" property hasn't been // made non-writable, we can still use a fast path to zero it. if (regexp->lookupPure(cx->names().lastIndex)->writable()) { regexp->zeroLastIndex(cx); } else { RootedValue zero(cx, Int32Value(0)); if (!SetProperty(cx, regexp, cx->names().lastIndex, zero)) { return false; } } args.rval().setObject(*regexp); return true; } static bool regexp_compile(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); /* Steps 1-2. */ return CallNonGenericMethod<IsRegExpObject, regexp_compile_impl>(cx, args); } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1. */ bool js::regexp_construct(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Steps 1. bool patternIsRegExp; if (!IsRegExp(cx, args.get(0), &patternIsRegExp)) { return false; } // We can delay step 3 and step 4a until later, during // GetPrototypeFromBuiltinConstructor calls. Accessing the new.target // and the callee from the stack is unobservable. if (!args.isConstructing()) { // Step 3.b. if (patternIsRegExp && !args.hasDefined(1)) { RootedObject patternObj(cx, &args[0].toObject()); // Step 3.b.i. RootedValue patternConstructor(cx); if (!GetProperty(cx, patternObj, patternObj, cx->names().constructor, &patternConstructor)) { return false; } // Step 3.b.ii. if (patternConstructor.isObject() && patternConstructor.toObject() == args.callee()) { args.rval().set(args[0]); return true; } } } RootedValue patternValue(cx, args.get(0)); // Step 4. ESClass cls; if (!GetClassOfValue(cx, patternValue, &cls)) { return false; } if (cls == ESClass::RegExp) { // Beware! |patternObj| might be a proxy into another compartment, so // don't assume |patternObj.is<RegExpObject>()|. RootedObject patternObj(cx, &patternValue.toObject()); RootedAtom sourceAtom(cx); RegExpFlag flags; RootedRegExpShared shared(cx); { // Step 4.a. shared = RegExpToShared(cx, patternObj); if (!shared) { return false; } sourceAtom = shared->getSource(); // Step 4.b. // Get original flags in all cases, to compare with passed flags. flags = shared->getFlags(); // If the RegExpShared is in another Zone, don't reuse it. if (cx->zone() != shared->zone()) { shared = nullptr; } } // Step 7. RootedObject proto(cx); if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) { return false; } Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto)); if (!regexp) { return false; } // Step 8. if (args.hasDefined(1)) { // Step 4.c / 21.2.3.2.2 RegExpInitialize step 4. RegExpFlag flagsArg = RegExpFlag(0); RootedString flagStr(cx, ToString<CanGC>(cx, args[1])); if (!flagStr) { return false; } if (!ParseRegExpFlags(cx, flagStr, &flagsArg)) { return false; } // Don't reuse the RegExpShared if we have different flags. if (flags != flagsArg) { shared = nullptr; } if (!(flags & UnicodeFlag) && flagsArg & UnicodeFlag) { // Have to check syntax again when adding 'u' flag. // ES 2017 draft rev 9b49a888e9dfe2667008a01b2754c3662059ae56 // 21.2.3.2.2 step 7. shared = CheckPatternSyntax(cx, sourceAtom, flagsArg); if (!shared) { return false; } } flags = flagsArg; } regexp->initAndZeroLastIndex(sourceAtom, flags, cx); if (shared) { regexp->setShared(*shared); } args.rval().setObject(*regexp); return true; } RootedValue P(cx); RootedValue F(cx); // Step 5. if (patternIsRegExp) { RootedObject patternObj(cx, &patternValue.toObject()); // Step 5.a. if (!GetProperty(cx, patternObj, patternObj, cx->names().source, &P)) { return false; } // Step 5.b. F = args.get(1); if (F.isUndefined()) { if (!GetProperty(cx, patternObj, patternObj, cx->names().flags, &F)) { return false; } } } else { // Steps 6.a-b. P = patternValue; F = args.get(1); } // Step 7. RootedObject proto(cx); if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) { return false; } Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto)); if (!regexp) { return false; } // Step 8. if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F)) { return false; } regexp->zeroLastIndex(cx); args.rval().setObject(*regexp); return true; } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1 * steps 4, 7-8. */ bool js::regexp_construct_raw_flags(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 2); MOZ_ASSERT(!args.isConstructing()); // Step 4.a. RootedAtom sourceAtom(cx, AtomizeString(cx, args[0].toString())); if (!sourceAtom) { return false; } // Step 4.c. int32_t flags = int32_t(args[1].toNumber()); // Step 7. RegExpObject* regexp = RegExpAlloc(cx, GenericObject); if (!regexp) { return false; } // Step 8. regexp->initAndZeroLastIndex(sourceAtom, RegExpFlag(flags), cx); args.rval().setObject(*regexp); return true; } MOZ_ALWAYS_INLINE bool IsRegExpPrototype(HandleValue v) { if (IsRegExpObject(v) || !v.isObject()) { return false; } // Note: The prototype shares its JSClass with instances. return StandardProtoKeyOrNull(&v.toObject()) == JSProto_RegExp; } // ES 2017 draft 21.2.5.4. MOZ_ALWAYS_INLINE bool regexp_global_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); // Steps 4-6. RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>(); args.rval().setBoolean(reObj->global()); return true; } bool js::regexp_global(JSContext* cx, unsigned argc, JS::Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 3.a. if (IsRegExpPrototype(args.thisv())) { args.rval().setUndefined(); return true; } // Steps 1-3. return CallNonGenericMethod<IsRegExpObject, regexp_global_impl>(cx, args); } // ES 2017 draft 21.2.5.5. MOZ_ALWAYS_INLINE bool regexp_ignoreCase_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); // Steps 4-6. RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>(); args.rval().setBoolean(reObj->ignoreCase()); return true; } bool js::regexp_ignoreCase(JSContext* cx, unsigned argc, JS::Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 3.a. if (IsRegExpPrototype(args.thisv())) { args.rval().setUndefined(); return true; } // Steps 1-3. return CallNonGenericMethod<IsRegExpObject, regexp_ignoreCase_impl>(cx, args); } // ES 2017 draft 21.2.5.7. MOZ_ALWAYS_INLINE bool regexp_multiline_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); // Steps 4-6. RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>(); args.rval().setBoolean(reObj->multiline()); return true; } bool js::regexp_multiline(JSContext* cx, unsigned argc, JS::Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 3.a. if (IsRegExpPrototype(args.thisv())) { args.rval().setUndefined(); return true; } // Steps 1-3. return CallNonGenericMethod<IsRegExpObject, regexp_multiline_impl>(cx, args); } // ES 2017 draft 21.2.5.10. MOZ_ALWAYS_INLINE bool regexp_source_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); // Step 5. RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>(); RootedAtom src(cx, reObj->getSource()); if (!src) { return false; } // Step 7. JSString* str = EscapeRegExpPattern(cx, src); if (!str) { return false; } args.rval().setString(str); return true; } static bool regexp_source(JSContext* cx, unsigned argc, JS::Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 3.a. if (IsRegExpPrototype(args.thisv())) { args.rval().setString(cx->names().emptyRegExp); return true; } // Steps 1-4. return CallNonGenericMethod<IsRegExpObject, regexp_source_impl>(cx, args); } // ES 2017 draft 21.2.5.12. MOZ_ALWAYS_INLINE bool regexp_sticky_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); // Steps 4-6. RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>(); args.rval().setBoolean(reObj->sticky()); return true; } bool js::regexp_sticky(JSContext* cx, unsigned argc, JS::Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 3.a. if (IsRegExpPrototype(args.thisv())) { args.rval().setUndefined(); return true; } // Steps 1-3. return CallNonGenericMethod<IsRegExpObject, regexp_sticky_impl>(cx, args); } // ES 2017 draft 21.2.5.15. MOZ_ALWAYS_INLINE bool regexp_unicode_impl(JSContext* cx, const CallArgs& args) { MOZ_ASSERT(IsRegExpObject(args.thisv())); // Steps 4-6. RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>(); args.rval().setBoolean(reObj->unicode()); return true; } bool js::regexp_unicode(JSContext* cx, unsigned argc, JS::Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); // Step 3.a. if (IsRegExpPrototype(args.thisv())) { args.rval().setUndefined(); return true; } // Steps 1-3. return CallNonGenericMethod<IsRegExpObject, regexp_unicode_impl>(cx, args); } const JSPropertySpec js::regexp_properties[] = { JS_SELF_HOSTED_GET("flags", "RegExpFlagsGetter", 0), JS_PSG("global", regexp_global, 0), JS_PSG("ignoreCase", regexp_ignoreCase, 0), JS_PSG("multiline", regexp_multiline, 0), JS_PSG("source", regexp_source, 0), JS_PSG("sticky", regexp_sticky, 0), JS_PSG("unicode", regexp_unicode, 0), JS_PS_END }; const JSFunctionSpec js::regexp_methods[] = { JS_SELF_HOSTED_FN(js_toSource_str, "RegExpToString", 0, 0), JS_SELF_HOSTED_FN(js_toString_str, "RegExpToString", 0, 0), JS_FN("compile", regexp_compile, 2,0), JS_SELF_HOSTED_FN("exec", "RegExp_prototype_Exec", 1,0), JS_SELF_HOSTED_FN("test", "RegExpTest" , 1,0), JS_SELF_HOSTED_SYM_FN(match, "RegExpMatch", 1,0), JS_SELF_HOSTED_SYM_FN(replace, "RegExpReplace", 2,0), JS_SELF_HOSTED_SYM_FN(search, "RegExpSearch", 1,0), JS_SELF_HOSTED_SYM_FN(split, "RegExpSplit", 2,0), JS_FS_END }; #define STATIC_PAREN_GETTER_CODE(parenNum) \ if (!res->createParen(cx, parenNum, args.rval())) \ return false; \ if (args.rval().isUndefined()) \ args.rval().setString(cx->runtime()->emptyString); \ return true /* * RegExp static properties. * * RegExp class static properties and their Perl counterparts: * * RegExp.input $_ * RegExp.lastMatch $& * RegExp.lastParen $+ * RegExp.leftContext $` * RegExp.rightContext $' */ #define DEFINE_STATIC_GETTER(name, code) \ static bool \ name(JSContext* cx, unsigned argc, Value* vp) \ { \ CallArgs args = CallArgsFromVp(argc, vp); \ RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \ if (!res) \ return false; \ code; \ } DEFINE_STATIC_GETTER(static_input_getter, return res->createPendingInput(cx, args.rval())) DEFINE_STATIC_GETTER(static_lastMatch_getter, return res->createLastMatch(cx, args.rval())) DEFINE_STATIC_GETTER(static_lastParen_getter, return res->createLastParen(cx, args.rval())) DEFINE_STATIC_GETTER(static_leftContext_getter, return res->createLeftContext(cx, args.rval())) DEFINE_STATIC_GETTER(static_rightContext_getter, return res->createRightContext(cx, args.rval())) DEFINE_STATIC_GETTER(static_paren1_getter, STATIC_PAREN_GETTER_CODE(1)) DEFINE_STATIC_GETTER(static_paren2_getter, STATIC_PAREN_GETTER_CODE(2)) DEFINE_STATIC_GETTER(static_paren3_getter, STATIC_PAREN_GETTER_CODE(3)) DEFINE_STATIC_GETTER(static_paren4_getter, STATIC_PAREN_GETTER_CODE(4)) DEFINE_STATIC_GETTER(static_paren5_getter, STATIC_PAREN_GETTER_CODE(5)) DEFINE_STATIC_GETTER(static_paren6_getter, STATIC_PAREN_GETTER_CODE(6)) DEFINE_STATIC_GETTER(static_paren7_getter, STATIC_PAREN_GETTER_CODE(7)) DEFINE_STATIC_GETTER(static_paren8_getter, STATIC_PAREN_GETTER_CODE(8)) DEFINE_STATIC_GETTER(static_paren9_getter, STATIC_PAREN_GETTER_CODE(9)) #define DEFINE_STATIC_SETTER(name, code) \ static bool \ name(JSContext* cx, unsigned argc, Value* vp) \ { \ RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \ if (!res) \ return false; \ code; \ return true; \ } static bool static_input_setter(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); if (!res) { return false; } RootedString str(cx, ToString<CanGC>(cx, args.get(0))); if (!str) { return false; } res->setPendingInput(str); args.rval().setString(str); return true; } const JSPropertySpec js::regexp_static_props[] = { JS_PSGS("input", static_input_getter, static_input_setter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("lastMatch", static_lastMatch_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("lastParen", static_lastParen_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("leftContext", static_leftContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("rightContext", static_rightContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$1", static_paren1_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$2", static_paren2_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$3", static_paren3_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$4", static_paren4_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$5", static_paren5_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$6", static_paren6_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$7", static_paren7_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$8", static_paren8_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSG("$9", static_paren9_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_PSGS("$_", static_input_getter, static_input_setter, JSPROP_PERMANENT), JS_PSG("$&", static_lastMatch_getter, JSPROP_PERMANENT), JS_PSG("$+", static_lastParen_getter, JSPROP_PERMANENT), JS_PSG("$`", static_leftContext_getter, JSPROP_PERMANENT), JS_PSG("$'", static_rightContext_getter, JSPROP_PERMANENT), JS_SELF_HOSTED_SYM_GET(species, "RegExpSpecies", 0), JS_PS_END }; template <typename CharT> static bool IsTrailSurrogateWithLeadSurrogateImpl(HandleLinearString input, size_t index) { JS::AutoCheckCannotGC nogc; MOZ_ASSERT(index > 0 && index < input->length()); const CharT* inputChars = input->chars<CharT>(nogc); return unicode::IsTrailSurrogate(inputChars[index]) && unicode::IsLeadSurrogate(inputChars[index - 1]); } static bool IsTrailSurrogateWithLeadSurrogate(HandleLinearString input, int32_t index) { if (index <= 0 || size_t(index) >= input->length()) { return false; } return input->hasLatin1Chars() ? IsTrailSurrogateWithLeadSurrogateImpl<Latin1Char>(input, index) : IsTrailSurrogateWithLeadSurrogateImpl<char16_t>(input, index); } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-14, except 12.a.i, 12.c.i.1. */ static RegExpRunStatus ExecuteRegExp(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex, VectorMatchPairs* matches, size_t* endIndex) { /* * WARNING: Despite the presence of spec step comment numbers, this * algorithm isn't consistent with any ES6 version, draft or * otherwise. YOU HAVE BEEN WARNED. */ /* Steps 1-2 performed by the caller. */ Handle<RegExpObject*> reobj = regexp.as<RegExpObject>(); RootedRegExpShared re(cx, RegExpObject::getShared(cx, reobj)); if (!re) { return RegExpRunStatus_Error; } RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); if (!res) { return RegExpRunStatus_Error; } RootedLinearString input(cx, string->ensureLinear(cx)); if (!input) { return RegExpRunStatus_Error; } /* Handled by caller */ MOZ_ASSERT(lastIndex >= 0 && size_t(lastIndex) <= input->length()); /* Steps 4-8 performed by the caller. */ /* Step 10. */ if (reobj->unicode()) { /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad * 21.2.2.2 step 2. * Let listIndex be the index into Input of the character that was * obtained from element index of str. * * In the spec, pattern match is performed with decoded Unicode code * points, but our implementation performs it with UTF-16 encoded * string. In step 2, we should decrement lastIndex (index) if it * points the trail surrogate that has corresponding lead surrogate. * * var r = /\uD83D\uDC38/ug; * r.lastIndex = 1; * var str = "\uD83D\uDC38"; * var result = r.exec(str); // pattern match starts from index 0 * print(result.index); // prints 0 * * Note: this doesn't match the current spec text and result in * different values for `result.index` under certain conditions. * However, the spec will change to match our implementation's * behavior. See https://github.com/tc39/ecma262/issues/128. */ if (IsTrailSurrogateWithLeadSurrogate(input, lastIndex)) { lastIndex--; } } /* Steps 3, 11-14, except 12.a.i, 12.c.i.1. */ RegExpRunStatus status = ExecuteRegExpImpl(cx, res, &re, input, lastIndex, matches, endIndex); if (status == RegExpRunStatus_Error) { return RegExpRunStatus_Error; } /* Steps 12.a.i, 12.c.i.i, 15 are done by Self-hosted function. */ return status; } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */ static bool RegExpMatcherImpl(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex, MutableHandleValue rval) { /* Execute regular expression and gather matches. */ VectorMatchPairs matches; /* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */ RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, &matches, nullptr); if (status == RegExpRunStatus_Error) { return false; } /* Steps 12.a, 12.c. */ if (status == RegExpRunStatus_Success_NotFound) { rval.setNull(); return true; } /* Steps 16-25 */ return CreateRegExpMatchResult(cx, string, matches, rval); } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */ bool js::RegExpMatcher(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 3); MOZ_ASSERT(IsRegExpObject(args[0])); MOZ_ASSERT(args[1].isString()); MOZ_ASSERT(args[2].isNumber()); RootedObject regexp(cx, &args[0].toObject()); RootedString string(cx, args[1].toString()); int32_t lastIndex; MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex)); /* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */ return RegExpMatcherImpl(cx, regexp, string, lastIndex, args.rval()); } /* * Separate interface for use by IonMonkey. * This code cannot re-enter Ion code. */ bool js::RegExpMatcherRaw(JSContext* cx, HandleObject regexp, HandleString input, int32_t maybeLastIndex, MatchPairs* maybeMatches, MutableHandleValue output) { // The MatchPairs will always be passed in, but RegExp execution was // successful only if the pairs have actually been filled in. if (maybeMatches && maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) { return CreateRegExpMatchResult(cx, input, *maybeMatches, output); } // |maybeLastIndex| only contains a valid value when the RegExp execution // was not successful. MOZ_ASSERT(maybeLastIndex >= 0); return RegExpMatcherImpl(cx, regexp, input, maybeLastIndex, output); } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. * This code is inlined in CodeGenerator.cpp generateRegExpSearcherStub, * changes to this code need to get reflected in there too. */ static bool RegExpSearcherImpl(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex, int32_t* result) { /* Execute regular expression and gather matches. */ VectorMatchPairs matches; /* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */ RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, &matches, nullptr); if (status == RegExpRunStatus_Error) { return false; } /* Steps 12.a, 12.c. */ if (status == RegExpRunStatus_Success_NotFound) { *result = -1; return true; } /* Steps 16-25 */ *result = CreateRegExpSearchResult(matches); return true; } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */ bool js::RegExpSearcher(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 3); MOZ_ASSERT(IsRegExpObject(args[0])); MOZ_ASSERT(args[1].isString()); MOZ_ASSERT(args[2].isNumber()); RootedObject regexp(cx, &args[0].toObject()); RootedString string(cx, args[1].toString()); int32_t lastIndex; MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex)); /* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */ int32_t result = 0; if (!RegExpSearcherImpl(cx, regexp, string, lastIndex, &result)) { return false; } args.rval().setInt32(result); return true; } /* * Separate interface for use by IonMonkey. * This code cannot re-enter Ion code. */ bool js::RegExpSearcherRaw(JSContext* cx, HandleObject regexp, HandleString input, int32_t lastIndex, MatchPairs* maybeMatches, int32_t* result) { MOZ_ASSERT(lastIndex >= 0); // The MatchPairs will always be passed in, but RegExp execution was // successful only if the pairs have actually been filled in. if (maybeMatches && maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) { *result = CreateRegExpSearchResult(*maybeMatches); return true; } return RegExpSearcherImpl(cx, regexp, input, lastIndex, result); } /* * ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2 * steps 3, 9-14, except 12.a.i, 12.c.i.1. */ bool js::RegExpTester(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 3); MOZ_ASSERT(IsRegExpObject(args[0])); MOZ_ASSERT(args[1].isString()); MOZ_ASSERT(args[2].isNumber()); RootedObject regexp(cx, &args[0].toObject()); RootedString string(cx, args[1].toString()); int32_t lastIndex; MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex)); /* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */ size_t endIndex = 0; RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, nullptr, &endIndex); if (status == RegExpRunStatus_Error) { return false; } if (status == RegExpRunStatus_Success) { MOZ_ASSERT(endIndex <= INT32_MAX); args.rval().setInt32(int32_t(endIndex)); } else { args.rval().setInt32(-1); } return true; } /* * Separate interface for use by IonMonkey. * This code cannot re-enter Ion code. */ bool js::RegExpTesterRaw(JSContext* cx, HandleObject regexp, HandleString input, int32_t lastIndex, int32_t* endIndex) { MOZ_ASSERT(lastIndex >= 0); size_t endIndexTmp = 0; RegExpRunStatus status = ExecuteRegExp(cx, regexp, input, lastIndex, nullptr, &endIndexTmp); if (status == RegExpRunStatus_Success) { MOZ_ASSERT(endIndexTmp <= INT32_MAX); *endIndex = int32_t(endIndexTmp); return true; } if (status == RegExpRunStatus_Success_NotFound) { *endIndex = -1; return true; } return false; } using CapturesVector = GCVector<Value, 4>; struct JSSubString { JSLinearString* base = nullptr; size_t offset = 0; size_t length = 0; JSSubString() = default; void initEmpty(JSLinearString* base) { this->base = base; offset = length = 0; } void init(JSLinearString* base, size_t offset, size_t length) { this->base = base; this->offset = offset; this->length = length; } }; static void GetParen(JSLinearString* matched, const JS::Value& capture, JSSubString* out) { if (capture.isUndefined()) { out->initEmpty(matched); return; } JSLinearString& captureLinear = capture.toString()->asLinear(); out->init(&captureLinear, 0, captureLinear.length()); } template <typename CharT> static bool InterpretDollar(JSLinearString* matched, JSLinearString* string, size_t position, size_t tailPos, Handle<CapturesVector> captures, JSLinearString* replacement, const CharT* replacementBegin, const CharT* currentDollar, const CharT* replacementEnd, JSSubString* out, size_t* skip) { MOZ_ASSERT(*currentDollar == '$'); /* If there is only a dollar, bail now. */ if (currentDollar + 1 >= replacementEnd) { return false; } /* ES 2016 draft Mar 25, 2016 Table 46. */ char16_t c = currentDollar[1]; if (IsAsciiDigit(c)) { /* $n, $nn */ unsigned num = JS7_UNDEC(c); if (num > captures.length()) { // The result is implementation-defined, do not substitute. return false; } const CharT* currentChar = currentDollar + 2; if (currentChar < replacementEnd) { c = *currentChar; if (IsAsciiDigit(c)) { unsigned tmpNum = 10 * num + JS7_UNDEC(c); // If num > captures.length(), the result is implementation-defined. // Consume next character only if num <= captures.length(). if (tmpNum <= captures.length()) { currentChar++; num = tmpNum; } } } if (num == 0) { // The result is implementation-defined. // Do not substitute. return false; } *skip = currentChar - currentDollar; MOZ_ASSERT(num <= captures.length()); GetParen(matched, captures[num -1], out); return true; } *skip = 2; switch (c) { default: return false; case '$': out->init(replacement, currentDollar - replacementBegin, 1); break; case '&': out->init(matched, 0, matched->length()); break; case '+': // SpiderMonkey extension if (captures.length() == 0) { out->initEmpty(matched); } else { GetParen(matched, captures[captures.length() - 1], out); } break; case '`': out->init(string, 0, position); break; case '\'': out->init(string, tailPos, string->length() - tailPos); break; } return true; } template <typename CharT> static bool FindReplaceLengthString(JSContext* cx, HandleLinearString matched, HandleLinearString string, size_t position, size_t tailPos, Handle<CapturesVector> captures, HandleLinearString replacement, size_t firstDollarIndex, size_t* sizep) { CheckedInt<uint32_t> replen = replacement->length(); JS::AutoCheckCannotGC nogc; MOZ_ASSERT(firstDollarIndex < replacement->length()); const CharT* replacementBegin = replacement->chars<CharT>(nogc); const CharT* currentDollar = replacementBegin + firstDollarIndex; const CharT* replacementEnd = replacementBegin + replacement->length(); do { JSSubString sub; size_t skip; if (InterpretDollar(matched, string, position, tailPos, captures, replacement, replacementBegin, currentDollar, replacementEnd, &sub, &skip)) { if (sub.length > skip) { replen += sub.length - skip; } else { replen -= skip - sub.length; } currentDollar += skip; } else { currentDollar++; } currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd); } while (currentDollar); if (!replen.isValid()) { ReportAllocationOverflow(cx); return false; } *sizep = replen.value(); return true; } static bool FindReplaceLength(JSContext* cx, HandleLinearString matched, HandleLinearString string, size_t position, size_t tailPos, Handle<CapturesVector> captures, HandleLinearString replacement, size_t firstDollarIndex, size_t* sizep) { return replacement->hasLatin1Chars() ? FindReplaceLengthString<Latin1Char>(cx, matched, string, position, tailPos, captures, replacement, firstDollarIndex, sizep) : FindReplaceLengthString<char16_t>(cx, matched, string, position, tailPos, captures, replacement, firstDollarIndex, sizep); } /* * Precondition: |sb| already has necessary growth space reserved (as * derived from FindReplaceLength), and has been inflated to TwoByte if * necessary. */ template <typename CharT> static void DoReplace(HandleLinearString matched, HandleLinearString string, size_t position, size_t tailPos, Handle<CapturesVector> captures, HandleLinearString replacement, size_t firstDollarIndex, StringBuffer &sb) { JS::AutoCheckCannotGC nogc; const CharT* replacementBegin = replacement->chars<CharT>(nogc); const CharT* currentChar = replacementBegin; MOZ_ASSERT(firstDollarIndex < replacement->length()); const CharT* currentDollar = replacementBegin + firstDollarIndex; const CharT* replacementEnd = replacementBegin + replacement->length(); do { /* Move one of the constant portions of the replacement value. */ size_t len = currentDollar - currentChar; sb.infallibleAppend(currentChar, len); currentChar = currentDollar; JSSubString sub; size_t skip; if (InterpretDollar(matched, string, position, tailPos, captures, replacement, replacementBegin, currentDollar, replacementEnd, &sub, &skip)) { sb.infallibleAppendSubstring(sub.base, sub.offset, sub.length); currentChar += skip; currentDollar += skip; } else { currentDollar++; } currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd); } while (currentDollar); sb.infallibleAppend(currentChar, replacement->length() - (currentChar - replacementBegin)); } static bool NeedTwoBytes(HandleLinearString string, HandleLinearString replacement, HandleLinearString matched, Handle<CapturesVector> captures) { if (string->hasTwoByteChars()) { return true; } if (replacement->hasTwoByteChars()) { return true; } if (matched->hasTwoByteChars()) { return true; } for (size_t i = 0, len = captures.length(); i < len; i++) { const Value& capture = captures[i]; if (capture.isUndefined()) { continue; } if (capture.toString()->hasTwoByteChars()) { return true; } } return false; } /* ES 2016 draft Mar 25, 2016 21.1.3.14.1. */ bool js::RegExpGetSubstitution(JSContext* cx, HandleArrayObject matchResult, HandleLinearString string, size_t position, HandleLinearString replacement, size_t firstDollarIndex, MutableHandleValue rval) { MOZ_ASSERT(firstDollarIndex < replacement->length()); // Step 1 (skipped). // Step 10 (reordered). uint32_t matchResultLength = matchResult->length(); MOZ_ASSERT(matchResultLength > 0); MOZ_ASSERT(matchResultLength == matchResult->getDenseInitializedLength()); const Value& matchedValue = matchResult->getDenseElement(0); RootedLinearString matched(cx, matchedValue.toString()->ensureLinear(cx)); if (!matched) { return false; } // Step 2. size_t matchLength = matched->length(); // Steps 3-5 (skipped). // Step 6. MOZ_ASSERT(position <= string->length()); uint32_t nCaptures = matchResultLength - 1; Rooted<CapturesVector> captures(cx, CapturesVector(cx)); if (!captures.reserve(nCaptures)) { return false; } // Step 7. for (uint32_t i = 1; i <= nCaptures; i++) { const Value& capture = matchResult->getDenseElement(i); if (capture.isUndefined()) { captures.infallibleAppend(capture); continue; } JSLinearString* captureLinear = capture.toString()->ensureLinear(cx); if (!captureLinear) { return false; } captures.infallibleAppend(StringValue(captureLinear)); } // Step 8 (skipped). // Step 9. CheckedInt<uint32_t> checkedTailPos(0); checkedTailPos += position; checkedTailPos += matchLength; if (!checkedTailPos.isValid()) { ReportAllocationOverflow(cx); return false; } uint32_t tailPos = checkedTailPos.value(); // Step 11. size_t reserveLength; if (!FindReplaceLength(cx, matched, string, position, tailPos, captures, replacement, firstDollarIndex, &reserveLength)) { return false; } StringBuffer result(cx); if (NeedTwoBytes(string, replacement, matched, captures)) { if (!result.ensureTwoByteChars()) { return false; } } if (!result.reserve(reserveLength)) { return false; } if (replacement->hasLatin1Chars()) { DoReplace<Latin1Char>(matched, string, position, tailPos, captures, replacement, firstDollarIndex, result); } else { DoReplace<char16_t>(matched, string, position, tailPos, captures, replacement, firstDollarIndex, result); } // Step 12. JSString* resultString = result.finishString(); if (!resultString) { return false; } rval.setString(resultString); return true; } bool js::GetFirstDollarIndex(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 1); JSString* str = args[0].toString(); // Should be handled in different path. MOZ_ASSERT(str->length() != 0); int32_t index = -1; if (!GetFirstDollarIndexRaw(cx, str, &index)) { return false; } args.rval().setInt32(index); return true; } template <typename TextChar> static MOZ_ALWAYS_INLINE int GetFirstDollarIndexImpl(const TextChar* text, uint32_t textLen) { const TextChar* end = text + textLen; for (const TextChar* c = text; c != end; ++c) { if (*c == '$') { return c - text; } } return -1; } int32_t js::GetFirstDollarIndexRawFlat(JSLinearString* text) { uint32_t len = text->length(); JS::AutoCheckCannotGC nogc; if (text->hasLatin1Chars()) { return GetFirstDollarIndexImpl(text->latin1Chars(nogc), len); } return GetFirstDollarIndexImpl(text->twoByteChars(nogc), len); } bool js::GetFirstDollarIndexRaw(JSContext* cx, JSString* str, int32_t* index) { JSLinearString* text = str->ensureLinear(cx); if (!text) { return false; } *index = GetFirstDollarIndexRawFlat(text); return true; } bool js::RegExpPrototypeOptimizable(JSContext* cx, unsigned argc, Value* vp) { // This can only be called from self-hosted code. CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 1); args.rval().setBoolean(RegExpPrototypeOptimizableRaw(cx, &args[0].toObject())); return true; } bool js::RegExpPrototypeOptimizableRaw(JSContext* cx, JSObject* proto) { AutoUnsafeCallWithABI unsafe; AutoAssertNoPendingException aanpe(cx); if (!proto->isNative()) { return false; } NativeObject* nproto = static_cast<NativeObject*>(proto); Shape* shape = cx->realm()->regExps.getOptimizableRegExpPrototypeShape(); if (shape == nproto->lastProperty()) { return true; } JSFunction* flagsGetter; if (!GetOwnGetterPure(cx, proto, NameToId(cx->names().flags), &flagsGetter)) { return false; } if (!flagsGetter) { return false; } if (!IsSelfHostedFunctionWithName(flagsGetter, cx->names().RegExpFlagsGetter)) { return false; } JSNative globalGetter; if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().global), &globalGetter)) { return false; } if (globalGetter != regexp_global) { return false; } JSNative ignoreCaseGetter; if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().ignoreCase), &ignoreCaseGetter)) { return false; } if (ignoreCaseGetter != regexp_ignoreCase) { return false; } JSNative multilineGetter; if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().multiline), &multilineGetter)) { return false; } if (multilineGetter != regexp_multiline) { return false; } JSNative stickyGetter; if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().sticky), &stickyGetter)) { return false; } if (stickyGetter != regexp_sticky) { return false; } JSNative unicodeGetter; if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().unicode), &unicodeGetter)) { return false; } if (unicodeGetter != regexp_unicode) { return false; } // Check if @@match, @@search, and exec are own data properties, // those values should be tested in selfhosted JS. bool has = false; if (!HasOwnDataPropertyPure(cx, proto, SYMBOL_TO_JSID(cx->wellKnownSymbols().match), &has)) { return false; } if (!has) { return false; } if (!HasOwnDataPropertyPure(cx, proto, SYMBOL_TO_JSID(cx->wellKnownSymbols().search), &has)) { return false; } if (!has) { return false; } if (!HasOwnDataPropertyPure(cx, proto, NameToId(cx->names().exec), &has)) { return false; } if (!has) { return false; } cx->realm()->regExps.setOptimizableRegExpPrototypeShape(nproto->lastProperty()); return true; } bool js::RegExpInstanceOptimizable(JSContext* cx, unsigned argc, Value* vp) { // This can only be called from self-hosted code. CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 2); args.rval().setBoolean(RegExpInstanceOptimizableRaw(cx, &args[0].toObject(), &args[1].toObject())); return true; } bool js::RegExpInstanceOptimizableRaw(JSContext* cx, JSObject* obj, JSObject* proto) { AutoUnsafeCallWithABI unsafe; AutoAssertNoPendingException aanpe(cx); RegExpObject* rx = &obj->as<RegExpObject>(); Shape* shape = cx->realm()->regExps.getOptimizableRegExpInstanceShape(); if (shape == rx->lastProperty()) { return true; } if (!rx->hasStaticPrototype()) { return false; } if (rx->staticPrototype() != proto) { return false; } if (!RegExpObject::isInitialShape(rx)) { return false; } cx->realm()->regExps.setOptimizableRegExpInstanceShape(rx->lastProperty()); return true; } /* * Pattern match the script to check if it is is indexing into a particular * object, e.g. 'function(a) { return b[a]; }'. Avoid calling the script in * such cases, which are used by javascript packers (particularly the popular * Dean Edwards packer) to efficiently encode large scripts. We only handle the * code patterns generated by such packers here. */ bool js::intrinsic_GetElemBaseForLambda(JSContext* cx, unsigned argc, Value* vp) { // This can only be called from self-hosted code. CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 1); JSObject& lambda = args[0].toObject(); args.rval().setUndefined(); if (!lambda.is<JSFunction>()) { return true; } RootedFunction fun(cx, &lambda.as<JSFunction>()); if (!fun->isInterpreted() || fun->isClassConstructor()) { return true; } JSScript* script = JSFunction::getOrCreateScript(cx, fun); if (!script) { return false; } jsbytecode* pc = script->code(); /* * JSOP_GETALIASEDVAR tells us exactly where to find the base object 'b'. * Rule out the (unlikely) possibility of a function with environment * objects since it would make our environment walk off. */ if (JSOp(*pc) != JSOP_GETALIASEDVAR || fun->needsSomeEnvironmentObject()) { return true; } EnvironmentCoordinate ec(pc); EnvironmentObject* env = &fun->environment()->as<EnvironmentObject>(); for (unsigned i = 0; i < ec.hops(); ++i) { env = &env->enclosingEnvironment().as<EnvironmentObject>(); } Value b = env->aliasedBinding(ec); pc += JSOP_GETALIASEDVAR_LENGTH; /* Look for 'a' to be the lambda's first argument. */ if (JSOp(*pc) != JSOP_GETARG || GET_ARGNO(pc) != 0) { return true; } pc += JSOP_GETARG_LENGTH; /* 'b[a]' */ if (JSOp(*pc) != JSOP_GETELEM) { return true; } pc += JSOP_GETELEM_LENGTH; /* 'return b[a]' */ if (JSOp(*pc) != JSOP_RETURN) { return true; } /* 'b' must behave like a normal object. */ if (!b.isObject()) { return true; } JSObject& bobj = b.toObject(); const Class* clasp = bobj.getClass(); if (!clasp->isNative() || clasp->getOpsLookupProperty() || clasp->getOpsGetProperty()) { return true; } args.rval().setObject(bobj); return true; } /* * Emulates `b[a]` property access, that is detected in GetElemBaseForLambda. * It returns the property value only if the property is data property and the * property value is a string. Otherwise it returns undefined. */ bool js::intrinsic_GetStringDataProperty(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); MOZ_ASSERT(args.length() == 2); RootedObject obj(cx, &args[0].toObject()); if (!obj->isNative()) { // The object is already checked to be native in GetElemBaseForLambda, // but it can be swapped to another class that is non-native. // Return undefined to mark failure to get the property. args.rval().setUndefined(); return true; } JSAtom* atom = AtomizeString(cx, args[1].toString()); if (!atom) { return false; } Value v; if (GetPropertyPure(cx, obj, AtomToId(atom), &v) && v.isString()) { args.rval().set(v); } else { args.rval().setUndefined(); } return true; }
30.352476
105
0.617091
fengjixuchui
eb94497f121080b88cab98d76dd3da6be810c9ef
1,059
cpp
C++
TrainingGround/src/assignment-3/main.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
15
2015-11-04T12:53:23.000Z
2021-08-10T09:53:12.000Z
TrainingGround/src/assignment-3/main.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
null
null
null
TrainingGround/src/assignment-3/main.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
6
2015-11-13T10:17:01.000Z
2020-05-14T07:25:48.000Z
#include "common.h" #include "LoadVehicle.h" #include "PassengerVehicle.h" #include "EmergencyEquipment.h" #include "EmergecyVehicle.h" #include "Decision.h" #include <list> using namespace std; // temparorily commented. /* int main() { // the vehicle list. Decision::VehicleList vehicleList; // create Vehicles. LoadVehicle * lv1 = new LoadVehicle ( "load1" ); vehicleList.push_back ( lv1 ); PassengerVehicle * pv1 = new PassengerVehicle ( "passenger1" ); vehicleList.push_back ( pv1 ); EmergecyVehicle * ev1 = new EmergecyVehicle ( "emergency1", "super", "buaa", 101 ); vehicleList.push_back ( ev1 ); // create Decison object. Decision decision ( vehicleList ); pc ("part 1"); decision.printVehiclesSpecifications(); cr; pc ("part 2"); decision.printEmergencyVehicles(); cr; pc ("part 3"); ps ( decision.numberLongDistanceEmergencyVehicles() ); cr; pc ("part 4"); ps ( decision.numBeds() ); cr; pc ("part 5"); ps ( decision.numPassengers() ); cr; // clear... delete lv1; delete pv1; delete ev1; return 0; } */
17.949153
84
0.68272
elloop
eb95266a0948bc9eeb811342cf7b0c16d3cba086
2,965
cpp
C++
src/blitzide2/FileView.cpp
blitz3d-ng/blitz3d-ng
adc829fb76e2c63612b50c725c0944b2b6b0ddaf
[ "Zlib" ]
53
2017-08-10T10:52:34.000Z
2021-12-09T18:03:30.000Z
src/blitzide2/FileView.cpp
kfprimm/blitz3d
adc829fb76e2c63612b50c725c0944b2b6b0ddaf
[ "Zlib" ]
21
2017-05-03T20:28:28.000Z
2022-03-25T12:11:00.000Z
src/blitzide2/FileView.cpp
kfprimm/blitz3d
adc829fb76e2c63612b50c725c0944b2b6b0ddaf
[ "Zlib" ]
8
2017-04-23T02:09:24.000Z
2022-02-01T21:17:27.000Z
#include "FileView.h" #include <wx/stc/stc.h> #include <wx/textfile.h> enum { MARGIN_LINE_NUMBERS }; static wxString keywordsList; static bool keywordsLoaded=false; // rgb_bkgrnd=RGB( 0x22,0x55,0x88 ); // rgb_string=RGB( 0x00,0xff,0x66 ); // rgb_ident=RGB( 0xff,0xff,0xff ); // rgb_keyword=RGB( 0xaa,0xff,0xff ); // rgb_comment=RGB( 0xff,0xee,0x00 ); // rgb_digit=RGB( 0x33,0xff,0xdd ); // rgb_default=RGB( 0xee,0xee,0xee ); extern wxString blitzpath; void FileView::LoadKeywords(){ if (!keywordsLoaded) { wxArrayString keywords; wxExecute( blitzpath + "/bin/blitzcc -k",keywords ); keywordsList = ""; wxArrayString::iterator it; for( it=keywords.begin();it<keywords.end();it++ ){ keywordsList << " " << (*it).Lower(); } keywordsLoaded = true; } } FileView::FileView( wxString &path,wxWindow *parent,wxWindowID id ):path(path),wxPanel( parent,id ){ LoadKeywords(); // Inconsolata, Monaco, Consolas, 'Courier New', Courier wxFont font; #ifdef __WXMSW__ font = wxFontInfo(12).FaceName("Consolas"); #else font = wxFontInfo(12).FaceName("Monaco"); #endif wxStyledTextCtrl* text = new wxStyledTextCtrl(this, wxID_ANY); if ( path.length()>0 ){ wxTextFile file; file.Open( path ); source.Clear(); while( !file.Eof() ) { source.Append( file.GetNextLine() ); source.Append( "\n" ); } file.Close(); text->SetText( source ); } text->StyleSetBackground( wxSTC_STYLE_DEFAULT, wxColour( 0x22,0x55,0x88 ) ); text->StyleSetForeground( wxSTC_STYLE_DEFAULT, wxColour( 0xee,0xee,0xee ) ); // text->StyleClearAll(); text->SetMarginWidth (MARGIN_LINE_NUMBERS, 25); text->SetCaretForeground( wxColour( 0xff,0xff,0xff ) ); text->SetCaretLineBackground( wxColour( 0x1e,0x4a,0x76 ) ); text->SetCaretLineVisible( true ); text->SetMarginType(MARGIN_LINE_NUMBERS, wxSTC_MARGIN_NUMBER); text->SetLexer(wxSTC_LEX_BLITZBASIC); text->StyleSetFont( wxSTC_STYLE_DEFAULT,font ); text->StyleSetForeground( wxSTC_STYLE_LINENUMBER, wxColour (0xee,0xee,0xee) ); text->StyleSetBackground( wxSTC_STYLE_LINENUMBER, wxColour (0x1e,0x4a,0x76) ); text->StyleSetBackground( wxSTC_B_DEFAULT, wxColour( 0x22,0x55,0x88 ) ); text->StyleSetForeground( wxSTC_B_DEFAULT, wxColour( 0xee,0xee,0xee ) ); text->StyleSetBackground( wxSTC_B_STRING, wxColour( 0x22,0x55,0x88 ) ); text->StyleSetForeground( wxSTC_B_STRING, wxColour( 0x00,0xff,0x66 ) ); text->StyleSetForeground( wxSTC_B_COMMENT, wxColour( 0xff,0xee,0x00 ) ); text->StyleSetForeground( wxSTC_B_KEYWORD, wxColour( 0xaa,0xff,0xff ) ); text->StyleSetForeground( wxSTC_B_NUMBER, wxColour( 0x33,0xff,0xdd ) ); text->SetKeyWords(0, keywordsList); wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); sizer->Add( text,1,wxEXPAND,0 ); SetSizer( sizer ); } bool FileView::Save(){ wxTextFile file( path ); file.Open(); file.AddLine( source ); file.Write(); file.Close(); return true; }
25.782609
100
0.696796
blitz3d-ng