text
stringlengths 8
6.88M
|
|---|
#ifndef FEK_LIB_HPP_GUARD_1851308033
#define FEK_LIB_HPP_GUARD_1851308033
int get_answer_of_life();
#endif
|
//===========================================================================
//! @file collision_2D.cpp
//! @brief 2D 当たり判定
//===========================================================================
//---------------------------------------------------------------------------
//! 2D 点vs点
//---------------------------------------------------------------------------
bool Collision2D::isHit(const Point2D& point1, const Point2D& point2)
{
Vector2 p1 = point1.getPosition();
Vector2 p2 = point2.getPosition();
Vector2 p = p1 - p2;
if(fabs(sqrtf(p.lengthSq())) < 0.0005f) {
return true;
}
return false;
}
//---------------------------------------------------------------------------
//! 2D 点vs円
//---------------------------------------------------------------------------
bool Collision2D::isHit(const Point2D& point, const Circle2D& circle, f32* pLength)
{
const Vector2 p1 = point.getPosition();
const Vector2 c1 = circle.getPosition();
Vector2 p = p1 - c1;
f32 lenghtSq = p.lengthSq();
f32 radius = circle.getRadius();
if(pLength != nullptr) {
*pLength = sqrtf(lenghtSq);
}
if(lenghtSq <= radius * radius) {
return true;
}
return false;
}
//---------------------------------------------------------------------------
//! 2D 円vs円
//---------------------------------------------------------------------------
bool Collision2D::isHit(const Circle2D& circle1, const Circle2D& circle2)
{
Vector2 c0 = circle1.getPosition();
Vector2 c1 = circle2.getPosition();
Vector2 p = c0 - c1;
f32 lenght = sqrtf(p.lengthSq());
f32 radius = circle1.getRadius() + circle2.getRadius();
f32 radiusSq = radius * radius;
if(lenght <= radiusSq) {
return true;
}
return false;
}
//---------------------------------------------------------------------------
//! 2D 線分vs線分
//---------------------------------------------------------------------------
bool Collision2D::isHit(const LineSegment2D& line1, const LineSegment2D& line2, Vector2* outHitPosition)
{
Vector2 startPos1 = line1.getPosition(0.0f);
Vector2 endPos1 = line1.getPosition(1.0f);
Vector2 startPos2 = line2.getPosition(0.0f);
Vector2 endPos2 = line2.getPosition(1.0f);
Vector2 v0 = endPos1 - startPos1;
Vector2 v1 = endPos2 - startPos2;
if(Vector2::cross(v0, v1) == 0.0f) {
return false;
}
Vector2 v2 = v1 - v0;
f32 cross0 = Vector2::cross(v2, v0);
f32 cross1 = Vector2::cross(v2, v1);
f32 t0 = cross1 / cross1;
f32 t1 = cross0 / cross1;
// クランプ
const f32 eps = 0.00001f;
if(t0 + eps < 0 || t0 - eps > 1 || t1 + eps < 0 || t1 - eps > 1) {
return false;
}
// 交差点
if(!outHitPosition) {
Vector2 hitPosition = startPos1 + v0;
hitPosition.x_ = hitPosition.x_ * t0;
hitPosition.y_ = hitPosition.y_ * t0;
*outHitPosition = hitPosition;
}
return false;
}
//---------------------------------------------------------------------------
//! 2D 矩形vs矩形
//---------------------------------------------------------------------------
bool Collision2D::isHit(const Rect2D& rect1, const Rect2D& rect2)
{
Vector2 p1 = rect1.getPosition();
Vector2 p2 = rect2.getPosition();
Vector2 size1 = rect1.getSize();
Vector2 size2 = rect2.getSize();
f32 px = fabs(p1.x_ - p2.x_);
f32 py = fabs(p1.y_ - p2.y_);
if(px < (size1.x_ + size2.x_) * 0.5f) {
if(py < (size1.y_ + size2.y_) * 0.5f) {
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
//! 2Dの円 と 3D座標を2D座標にしたもの (Matrix)
//---------------------------------------------------------------------------
bool Collision2D::isHit(const Circle2D& circle, const Matrix& matWorld, const Matrix& matView, const Matrix& matProj, f32* outLenght, Vector2* outScreenPosition)
{
Matrix world = matWorld;
//Matrix view = matView;
//Matrix proj = matProj;
// ↓↓が出来るの謎すぎる
//Matrix mat = matWorld0 * matView * matProj;
Matrix mat = world * matView * matProj;
// スクリーン行列作成
mat = mat * conversion2D(static_cast<f32>(GmRender()->getWidth()), static_cast<f32>(GmRender()->getHeight()));
f32 nearZ = 0.01f;
f32 farZ = 10000.0f;
f32 x = mat.m_[3][0];
f32 y = mat.m_[3][1];
f32 w = mat.m_[3][3];
// カメラ描画内に入っているか (奥行)
if(!(w >= nearZ && w <= farZ)) {
return false;
}
x = x / w;
y = y / w;
Point2D p{ {x,y} };
// 点vs円
if(isHit(p, circle, outLenght)) {
if(outScreenPosition) {
*outScreenPosition = p.getPosition();
}
return true;
}
return false;
}
//---------------------------------------------------------------------------
//! 2Dの円 と 3D座標を2D座標にしたもの (Vector3)
//---------------------------------------------------------------------------
bool Collision2D::isHit([[maybe_unused]] const Circle2D& circle0, [[maybe_unused]] const Vector3& position0, [[maybe_unused]] const Matrix& matView, [[maybe_unused]] const Matrix& matProj)
{
return false;
}
//---------------------------------------------------------------------------
//! 画面サイズのスクリーン行列を返す
//---------------------------------------------------------------------------
Matrix Collision2D::conversion2D(f32 w, f32 h)
{
const f32 halfW = w * 0.5f;
const f32 halfH = h * 0.5f;
Matrix matScreen;
matScreen.m_[0][0] = halfW;
matScreen.m_[0][1] = 0.0f;
matScreen.m_[0][2] = 0.0f;
matScreen.m_[0][3] = 0.0f;
matScreen.m_[1][0] = 0.0f;
matScreen.m_[1][1] = -halfH;
matScreen.m_[1][2] = 0.0f;
matScreen.m_[1][3] = 0.0f;
matScreen.m_[2][0] = 0.0f;
matScreen.m_[2][1] = 0.0f;
matScreen.m_[2][2] = 1.0f;
matScreen.m_[2][3] = 0.0f;
matScreen.m_[3][0] = halfW;
matScreen.m_[3][1] = halfH;
matScreen.m_[3][2] = 0.0f;
matScreen.m_[3][3] = 1.0f;
return matScreen;
}
|
#include "precompiled.h"
#include "texture/jstexture.h"
#include "texture/texturecache.h"
#include "script/script.h"
REGISTER_STARTUP_FUNCTION(jstexture, jstexture::init, 10);
namespace jstexture
{
JSBool jsflush(JSContext *cx, uintN argc, jsval *vp);
}
void jstexture::init()
{
script::gScriptEngine->AddFunction("system.render.texture.flush", 0, jstexture::jsflush);
}
JSBool jstexture::jsflush(JSContext *cx, uintN argc, jsval *vp)
{
texture::flush();
return JS_TRUE;
}
|
/**
* Copyright (c) 2020, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "help_text.hh"
#include "config.h"
help_text&
help_text::with_parameters(
const std::initializer_list<help_text>& params) noexcept
{
this->ht_parameters = params;
for (auto& param : this->ht_parameters) {
param.ht_context = help_context_t::HC_PARAMETER;
}
return *this;
}
help_text&
help_text::with_parameter(const help_text& ht) noexcept
{
this->ht_parameters.emplace_back(ht);
this->ht_parameters.back().ht_context = help_context_t::HC_PARAMETER;
return *this;
}
help_text&
help_text::with_result(const help_text& ht) noexcept
{
this->ht_results.emplace_back(ht);
this->ht_results.back().ht_context = help_context_t::HC_RESULT;
return *this;
}
help_text&
help_text::with_examples(
const std::initializer_list<help_example>& examples) noexcept
{
this->ht_example = examples;
return *this;
}
help_text&
help_text::with_example(const help_example& example) noexcept
{
this->ht_example.emplace_back(example);
return *this;
}
help_text&
help_text::with_enum_values(
const std::initializer_list<const char*>& enum_values) noexcept
{
this->ht_enum_values = enum_values;
return *this;
}
help_text&
help_text::with_tags(const std::initializer_list<const char*>& tags) noexcept
{
this->ht_tags = tags;
return *this;
}
help_text&
help_text::with_opposites(
const std::initializer_list<const char*>& opps) noexcept
{
this->ht_opposites = opps;
return *this;
}
void
help_text::index_tags()
{
for (const auto& tag : this->ht_tags) {
TAGGED.insert(std::make_pair(tag, this));
}
}
|
#include <string>
using namespace std;
class STRING {
string s1;
public:
STRING();
STRING(string);
string getS1();
void setS1(string);
string cadenaT(string);
string Asignacion(string);
string Imprimir(string);
};
|
#pragma once
#include <vector>
#include "Global.h"
#include "Bunny.h"
class Colony
{
friend class Bunny;
public:
Colony();
Bunny* addBunny(Bunny*);
void killOld();
void listColony();
void Cull();
void giveBirth();
void convertMutants();
void growOld();
bool Continue();
private:
int TOTAL_OLD = 0;
int TOTAL_CROWD = 0;
int TOTAL_BORN = 0;
std::vector<Bunny*> colony;
};
|
#include "stdio.h"
#include "stdlib.h"
int main(int argc, char* argv[])
{
int d = atoi(argv[1]);
FILE* f = fopen("test.pbrt","w");
fprintf(f, "LookAt 1.0 1.0 5 1.0 1.0 1.0 0 1 0\n");
fprintf(f, "Camera \"perspective\" \"float fov\" [28]\n");
fprintf(f, "Film \"image\" \"integer xresolution\" [400] \"integer yresolution\" [400]\"string filename\" \"fire-%d.exr\"\n", d);
fprintf(f, "Sampler \"bestcandidate\" \"integer pixelsamples\" [4]\n");
fprintf(f, "PixelFilter \"triangle\"\n");
fprintf(f, "VolumeIntegrator \"emission\" \"float stepsize\" [.025]\n");
fprintf(f, "WorldBegin\n");
fprintf(f, "Volume \"firevolumegrid\"\n");
fprintf(f, "\"point p0\" [ 0.010000 0.010000 0.010000 ] \"point p1\" [ 1.990000 1.990000 0.390000 ]\n");
fprintf(f, "\"string simFile\" \"sliceAnimation%d.bin\"\n", d);
fprintf(f, "\"color sigma_a\" [1 1 1] \"color sigma_s\" [0 0 0]\n");
fprintf(f, "Material \"matte\" \"color Kd\" [.57 .57 .6]\n");
fprintf(f, "Translate 0 -1 0\n");
fprintf(f, "Shape \"trianglemesh\" \"integer indices\" [0 1 2 2 3 0]\n");
fprintf(f, "\"point P\" [ -5 0 -5 5 0 -5 5 0 5 -5 0 5]\n");
fprintf(f, "Shape \"trianglemesh\" \"integer indices\" [0 1 2 2 3 0]\n");
fprintf(f, "\"point P\" [ -5 0 -1.7 5 0 -1.7 5 10 -1.7 -5 10 -1.7 ]\n");
fprintf(f, "WorldEnd\n");
fclose(f);
return 0;
}
|
#ifndef parametrecorbeilleediteur_h
#define parametrecorbeilleediteur_h
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSettings>
#include "mainwindow.h"
/** \file parametrecorbeilleediteur.h */
/**
* @class Editeur
*
* Editeur qui fait apparaître une fenêtre
* disposant d'un question à laquelle on répond par oui ou par non
*
* Cette classe est abstraite
*/
class Editeur : public QWidget {
Q_OBJECT
protected:
QLabel* question;
QPushButton* oui;
QPushButton* non;
QHBoxLayout* reponse;
QVBoxLayout* layout;
public:
/**
* @fn Editeur
* @param parent
* @brief constructeur
*/
Editeur (QWidget* parent =0);
public slots:
/**
* @fn clickOnOui
* @brief fonction qui se lance lorsqu'on appuie sur
* le bouton oui, c'est une fonction virtuelle pure
*/
virtual void clickOnOui() =0;
/**
* @fn clickOnNon
* @brief fonction qui se lance lorsqu'on appuie sur
* le bouton non, c'est une fonction virtuelle pure
*/
virtual void clickOnNon() =0;
private slots:
};
/** @class ParametreCorbeille
* @brief première classe qui hérite d'Editeur
* Elle affiche un message pour proposer à l'utilisateur de rentrer automatique
* le vidage de la corbeille chaque fois qu'on quitte l'application
*
*/
class ParametreCorbeille : public Editeur{
Q_OBJECT
public:
/**
* @fn ParametreCorbeille
* @param parent
* @brief constructeur
*/
ParametreCorbeille (QWidget* parent =0);
public slots:
/**
* @fn clickOnOui
* @brief l'object QSettings chargé d'enregistrer les
* préférences de l'utilisateur dispose d'un attribut "viderCorbeilleAuto" de type booléen
* qui passe à true, à chaque sortie de l'applicaiton, la corbeille est automatiquement vidée
*/
void clickOnOui();
/**
* @fn clickOnOui
* @brief l'object QSettings chargé d'enregistrer les
* préférences de l'utilisateur dispose d'un attribut "viderCorbeilleAuto" de type booléen
* qui passe à false, chaque fois que l'uilisateur quitte l'application, on lui propose de
* vider la corbeille
*/
void clickOnNon();
};
/**
* @class QuitterApp
*
* @brief Second éditeur qui hérite de Editeur,
* celui-ci va demander à l'utilisateur lorsqu'il sort de l'application s'il
* souhaite vider la corbeille ou non
*/
class QuitterApp : public Editeur {
Q_OBJECT
public :
/**
* @fn QuitterApp
* @brief constructeur
*/
QuitterApp(QWidget* =0);
public slots:
/**
* @fn clickOnOui
* @brief la corbeille est vidée
*
*/
void clickOnOui();
/**
* @fn clickOnNon
* @brief la corbeille n'est pas vidée
*/
void clickOnNon();
};
#endif
|
#include "main.hpp"
#include "Sampler.hpp"
#include "Clip.hpp"
#include "Mixer.hpp"
#include "Synth.hpp"
static int patestCallback( const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData ) {
Mixer *mix = (Mixer*)userData;
float* out = (float*)outputBuffer;
unsigned long i;
PaStreamCallbackResult finish = paContinue;
(void) inputBuffer;
(void) timeInfo;
(void) statusFlags;
for(i=0; i<framesPerBuffer;i++){
//if(mix->cursor < mix->sampleables[0]->len){
*out++ = mix->sample();//CH 1
*out++ = mix->sample();//CH 2
/*}else{
*out++ = 0;
finish = paAbort;
}*/
}
return finish;
}
static void StreamFinished( void* userData ){
printf( "Stream Completed.\n");
}
//*******************************************************************
int main(void)
{
PaStreamParameters outputParameters;
PaStream *stream;
PaError err;
int i;
/* init */
/*Clip clip1("res/alive01.wav", SAMPLE_RATE*NUM_SECONDS);
Clip clip2("res/alive02.wav", SAMPLE_RATE*NUM_SECONDS);
*/
Sampler** samptable =
(Sampler**)malloc(sizeof(Sampler*));
//samptable[0] = &clip1;
//samptable[1] = &clip2;*/
Synth ss(2*SAMPLE_RATE*NUM_SECONDS, 0.1, 40.0);
samptable[0] = &ss;
Mixer mainMix(samptable, 1);//2);
err = Pa_Initialize();
if( err != paNoError ) goto error;
outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
if (outputParameters.device == paNoDevice) {
fprintf(stderr,"Error: No default output device.\n");
goto error;
}
outputParameters.channelCount = 2; /* stereo output */
outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
printf("PortAudio Test. SR = %d, Channels = %i\n",
SAMPLE_RATE,outputParameters.channelCount);
err = Pa_OpenStream(
&stream,
NULL, /* no input */
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paClipOff, /* we won't output out of range samples so don't bother clipping them */
patestCallback,
&mainMix );
if( err != paNoError ) goto error;
err = Pa_SetStreamFinishedCallback( stream, &StreamFinished );
if( err != paNoError ) goto error;
err = Pa_StartStream( stream );
if( err != paNoError ) goto error;
printf("Play for %d seconds.\n", NUM_SECONDS );
Pa_Sleep( NUM_SECONDS * 1000 );
err = Pa_StopStream( stream );
if( err != paNoError ) goto error;
err = Pa_CloseStream( stream );
if( err != paNoError ) goto error;
Pa_Terminate();
printf("Test finished.\n");
return err;
error:
Pa_Terminate();
fprintf( stderr, "An error occured while using the portaudio stream\n" );
fprintf( stderr, "Error number: %d\n", err );
fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
return err;
}
|
#ifndef _SPATIAL_MATH_MATRIX_INL_
#define _SPATIAL_MATH_MATRIX_INL_
#include "sm_const.h"
#include "SM_Quaternion.h"
#include "SM_Math.h"
namespace sm
{
/************************************************************************/
/* Matrix2 */
/************************************************************************/
template <typename T>
Matrix2<T>::Matrix2()
{
c[0][0] = 1; c[0][1] = 0;
c[1][0] = 0; c[1][1] = 1;
}
template <typename T>
bool Matrix2<T>::operator == (const Matrix2<T>& b) const
{
return memcmp(x, b.x, sizeof(x)) == 0;
}
template <typename T>
bool Matrix2<T>::operator != (const Matrix2<T>& b) const
{
return !(*this == b);
}
/************************************************************************/
/* Matrix3 */
/************************************************************************/
template <typename T>
Matrix3<T>::Matrix3()
{
c[0][0] = 1; c[0][1] = 0; c[0][2] = 0;
c[1][0] = 0; c[1][1] = 1; c[1][2] = 0;
c[2][0] = 0; c[2][1] = 0; c[2][2] = 1;
}
template <typename T>
Matrix3<T>::Matrix3(const Matrix4<T>& m)
{
c[0][0] = m.c[0][0]; c[1][0] = m.c[1][0]; c[2][0] = m.c[2][0];
c[0][1] = m.c[0][1]; c[1][1] = m.c[1][1]; c[2][1] = m.c[2][1];
c[0][2] = m.c[0][2]; c[1][2] = m.c[1][2]; c[2][2] = m.c[2][2];
}
template <typename T>
Matrix3<T>::Matrix3(const Vector3<T>& x, const Vector3<T>& y, const Vector3<T>& z)
{
c[0][0] = x.x; c[0][1] = x.y; c[0][2] = x.z;
c[1][0] = y.x; c[1][1] = y.y; c[1][2] = y.z;
c[2][0] = z.x; c[2][1] = z.y; c[2][2] = z.z;
}
template <typename T>
bool Matrix3<T>::operator == (const Matrix3<T>& b) const
{
return memcmp(x, b.x, sizeof(x)) == 0;
}
template <typename T>
bool Matrix3<T>::operator != (const Matrix3<T>& b) const
{
return !(*this == b);
}
template <typename T>
T Matrix3<T>::Determinant() const
{
return c[0][0] * c[1][1] * c[2][2] +
c[0][1] * c[1][2] * c[2][0] +
c[0][2] * c[1][0] * c[2][1] -
c[0][2] * c[1][1] * c[2][0] -
c[0][1] * c[1][0] * c[2][2] -
c[0][0] * c[1][2] * c[2][1];
}
/************************************************************************/
/* Matrix4 */
/************************************************************************/
template <typename T>
Matrix4<T>::Matrix4()
{
Identity();
}
template <typename T>
Matrix4<T>::Matrix4(const Matrix3<T>& m)
{
c[0][0] = m.c[0][0]; c[0][1] = m.c[0][1]; c[0][2] = m.c[0][2]; c[0][3] = 0;
c[1][0] = m.c[1][0]; c[1][1] = m.c[1][1]; c[1][2] = m.c[1][2]; c[1][3] = 0;
c[2][0] = m.c[2][0]; c[2][1] = m.c[2][1]; c[2][2] = m.c[2][2]; c[2][3] = 0;
c[3][0] = 0; c[3][1] = 0; c[3][2] = 0; c[3][3] = 1;
}
template <typename T>
Matrix4<T>::Matrix4(const QuaternionT<T>& q)
{
// Calculate coefficients
T x2 = q.x + q.x, y2 = q.y + q.y, z2 = q.z + q.z;
T xx = q.x * x2, xy = q.x * y2, xz = q.x * z2;
T yy = q.y * y2, yz = q.y * z2, zz = q.z * z2;
T wx = q.w * x2, wy = q.w * y2, wz = q.w * z2;
c[0][0] = 1 - (yy + zz); c[1][0] = xy - wz;
c[2][0] = xz + wy; c[3][0] = 0;
c[0][1] = xy + wz; c[1][1] = 1 - (xx + zz);
c[2][1] = yz - wx; c[3][1] = 0;
c[0][2] = xz - wy; c[1][2] = yz + wx;
c[2][2] = 1 - (xx + yy); c[3][2] = 0;
c[0][3] = 0; c[1][3] = 0;
c[2][3] = 0; c[3][3] = 1;
}
template <typename T>
Matrix4<T>& Matrix4<T>::operator = (const Matrix4<T>& b)
{
memcpy(&x[0], &b.x[0], sizeof(x));
return *this;
}
template <typename T>
bool Matrix4<T>::operator == (const Matrix4<T>& b) const
{
return memcmp(x, b.x, sizeof(x)) == 0;
}
template <typename T>
bool Matrix4<T>::operator != (const Matrix4<T>& b) const
{
return !(*this == b);
}
template <typename T>
Matrix4<T> Matrix4<T>::operator * (const Matrix4<T>& m) const
{
Matrix4 mf;
mf.x[0] = x[0] * m.x[0] + x[4] * m.x[1] + x[8] * m.x[2] + x[12] * m.x[3];
mf.x[1] = x[1] * m.x[0] + x[5] * m.x[1] + x[9] * m.x[2] + x[13] * m.x[3];
mf.x[2] = x[2] * m.x[0] + x[6] * m.x[1] + x[10] * m.x[2] + x[14] * m.x[3];
mf.x[3] = x[3] * m.x[0] + x[7] * m.x[1] + x[11] * m.x[2] + x[15] * m.x[3];
mf.x[4] = x[0] * m.x[4] + x[4] * m.x[5] + x[8] * m.x[6] + x[12] * m.x[7];
mf.x[5] = x[1] * m.x[4] + x[5] * m.x[5] + x[9] * m.x[6] + x[13] * m.x[7];
mf.x[6] = x[2] * m.x[4] + x[6] * m.x[5] + x[10] * m.x[6] + x[14] * m.x[7];
mf.x[7] = x[3] * m.x[4] + x[7] * m.x[5] + x[11] * m.x[6] + x[15] * m.x[7];
mf.x[8] = x[0] * m.x[8] + x[4] * m.x[9] + x[8] * m.x[10] + x[12] * m.x[11];
mf.x[9] = x[1] * m.x[8] + x[5] * m.x[9] + x[9] * m.x[10] + x[13] * m.x[11];
mf.x[10] = x[2] * m.x[8] + x[6] * m.x[9] + x[10] * m.x[10] + x[14] * m.x[11];
mf.x[11] = x[3] * m.x[8] + x[7] * m.x[9] + x[11] * m.x[10] + x[15] * m.x[11];
mf.x[12] = x[0] * m.x[12] + x[4] * m.x[13] + x[8] * m.x[14] + x[12] * m.x[15];
mf.x[13] = x[1] * m.x[12] + x[5] * m.x[13] + x[9] * m.x[14] + x[13] * m.x[15];
mf.x[14] = x[2] * m.x[12] + x[6] * m.x[13] + x[10] * m.x[14] + x[14] * m.x[15];
mf.x[15] = x[3] * m.x[12] + x[7] * m.x[13] + x[11] * m.x[14] + x[15] * m.x[15];
return mf;
}
template <typename T>
Vector2<T> Matrix4<T>::operator * (const Vector2<T>& v) const
{
T x = c[0][0] * v.x + c[1][0] * v.y + c[3][0];
T y = c[0][1] * v.x + c[1][1] * v.y + c[3][1];
return Vector2<T>(x, y);
}
template <typename T>
Vector3<T> Matrix4<T>::operator * (const Vector3<T>& v) const
{
T x = c[0][0] * v.x + c[1][0] * v.y + c[2][0] * v.z + c[3][0];
T y = c[0][1] * v.x + c[1][1] * v.y + c[2][1] * v.z + c[3][1];
T z = c[0][2] * v.x + c[1][2] * v.y + c[2][2] * v.z + c[3][2];
T w = c[0][3] * v.x + c[1][3] * v.y + c[2][3] * v.z + c[3][3];
return Vector3<T>(x / w, y / w, z / w);
}
template <typename T>
Vector4<T> Matrix4<T>::operator * (const Vector4<T>& v) const
{
T x = c[0][0] * v.x + c[1][0] * v.y + c[2][0] * v.z + c[3][0] * v.w;
T y = c[0][1] * v.x + c[1][1] * v.y + c[2][1] * v.z + c[3][1] * v.w;
T z = c[0][2] * v.x + c[1][2] * v.y + c[2][2] * v.z + c[3][2] * v.w;
T w = c[0][3] * v.x + c[1][3] * v.y + c[2][3] * v.z + c[3][3] * v.w;
return Vector4<T>(x, y, z, w);
}
template <typename T>
void Matrix4<T>::Identity()
{
c[0][0] = 1; c[0][1] = 0; c[0][2] = 0; c[0][3] = 0;
c[1][0] = 0; c[1][1] = 1; c[1][2] = 0; c[1][3] = 0;
c[2][0] = 0; c[2][1] = 0; c[2][2] = 1; c[2][3] = 0;
c[3][0] = 0; c[3][1] = 0; c[3][2] = 0; c[3][3] = 1;
}
template <typename T>
void Matrix4<T>::Translate(T x, T y, T z)
{
*this = Translated(x, y, z) * *this;
}
template <typename T>
void Matrix4<T>::Rotate(T x, T y, T z)
{
*this = Rotated(x, y, z) * *this;
}
template <typename T>
void Matrix4<T>::Scale(T x, T y, T z)
{
*this = Scaled(x, y, z) * *this;
}
template <typename T>
void Matrix4<T>::Shear(T kx, T ky)
{
*this = Sheared(kx, ky) * *this;
}
template <typename T>
void Matrix4<T>::RotateZ(T degrees)
{
*this = RotatedZ(degrees) * *this;
}
template <typename T>
void Matrix4<T>::SetTransformation(T x, T y, T angle, T sx, T sy, T ox, T oy, T kx, T ky)
{
Identity();
T c = cos(angle), s = sin(angle);
// matrix multiplication carried out on paper:
// |1 x| |c -s | |sx | | 1 ky | |1 -ox|
// | 1 y| |s c | | sy | |kx 1 | | 1 -oy|
// | 1 | | 1 | | 1 | | 1 | | 1 |
// | 1| | 1| | 1| | 1| | 1 |
// move rotate scale skew origin
this->x[10] = this->x[15] = 1.0f;
this->x[0] = c * sx - ky * s * sy; // = a
this->x[1] = s * sx + ky * c * sy; // = b
this->x[4] = kx * c * sx - s * sy; // = c
this->x[5] = kx * s * sx + c * sy; // = d
this->x[12] = x - ox * this->x[0] - oy * this->x[4];
this->x[13] = y - ox * this->x[1] - oy * this->x[5];
}
template <typename T>
void Matrix4<T>::SetTransformation(const Vector3<T>& scale,
const Vector3<T>& rotation_origin,
const Vector4<T>& rotation_quaternion,
const Vector3<T>& translation)
{
Identity();
// scale
c[0][0] = scale.x;
c[1][1] = scale.x;
c[2][2] = scale.x;
// rotate
c[3][0] -= rotation_origin.x;
c[3][1] -= rotation_origin.y;
c[3][2] -= rotation_origin.z;
*this = (Matrix4<T>(QuaternionT<T>(
rotation_quaternion.x,
rotation_quaternion.y,
rotation_quaternion.z,
rotation_quaternion.w
))) * *this;
c[3][0] += rotation_origin.x;
c[3][1] += rotation_origin.y;
c[3][2] += rotation_origin.z;
// translate
c[3][0] += translation.x;
c[3][1] += translation.y;
c[3][2] += translation.z;
}
template <typename T>
Matrix4<T> Matrix4<T>::FastMul43(const Matrix4<T>& b)
{
// Note: m may not be the same as m1 or m2
Matrix4 m;
m.x[0] = x[0] * b.x[0] + x[4] * b.x[1] + x[8] * b.x[2];
m.x[1] = x[1] * b.x[0] + x[5] * b.x[1] + x[9] * b.x[2];
m.x[2] = x[2] * b.x[0] + x[6] * b.x[1] + x[10] * b.x[2];
m.x[3] = 0.0f;
m.x[4] = x[0] * b.x[4] + x[4] * b.x[5] + x[8] * b.x[6];
m.x[5] = x[1] * b.x[4] + x[5] * b.x[5] + x[9] * b.x[6];
m.x[6] = x[2] * b.x[4] + x[6] * b.x[5] + x[10] * b.x[6];
m.x[7] = 0.0f;
m.x[8] = x[0] * b.x[8] + x[4] * b.x[9] + x[8] * b.x[10];
m.x[9] = x[1] * b.x[8] + x[5] * b.x[9] + x[9] * b.x[10];
m.x[10] = x[2] * b.x[8] + x[6] * b.x[9] + x[10] * b.x[10];
m.x[11] = 0.0f;
m.x[12] = x[0] * b.x[12] + x[4] * b.x[13] + x[8] * b.x[14] + x[12] * b.x[15];
m.x[13] = x[1] * b.x[12] + x[5] * b.x[13] + x[9] * b.x[14] + x[13] * b.x[15];
m.x[14] = x[2] * b.x[12] + x[6] * b.x[13] + x[10] * b.x[14] + x[14] * b.x[15];
m.x[15] = 1.0f;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::Transposed() const
{
Matrix4<T> dst(*this);
for (int y = 0; y < 4; ++y ) {
for(int x = y + 1; x < 4; ++x ) {
T tmp = dst.c[x][y];
dst.c[x][y] = dst.c[y][x];
dst.c[y][x] = tmp;
}
}
return dst;
}
template <typename T>
T Matrix4<T>::Determinant() const
{
return
c[0][3]*c[1][2]*c[2][1]*c[3][0] - c[0][2]*c[1][3]*c[2][1]*c[3][0] - c[0][3]*c[1][1]*c[2][2]*c[3][0] + c[0][1]*c[1][3]*c[2][2]*c[3][0] +
c[0][2]*c[1][1]*c[2][3]*c[3][0] - c[0][1]*c[1][2]*c[2][3]*c[3][0] - c[0][3]*c[1][2]*c[2][0]*c[3][1] + c[0][2]*c[1][3]*c[2][0]*c[3][1] +
c[0][3]*c[1][0]*c[2][2]*c[3][1] - c[0][0]*c[1][3]*c[2][2]*c[3][1] - c[0][2]*c[1][0]*c[2][3]*c[3][1] + c[0][0]*c[1][2]*c[2][3]*c[3][1] +
c[0][3]*c[1][1]*c[2][0]*c[3][2] - c[0][1]*c[1][3]*c[2][0]*c[3][2] - c[0][3]*c[1][0]*c[2][1]*c[3][2] + c[0][0]*c[1][3]*c[2][1]*c[3][2] +
c[0][1]*c[1][0]*c[2][3]*c[3][2] - c[0][0]*c[1][1]*c[2][3]*c[3][2] - c[0][2]*c[1][1]*c[2][0]*c[3][3] + c[0][1]*c[1][2]*c[2][0]*c[3][3] +
c[0][2]*c[1][0]*c[2][1]*c[3][3] - c[0][0]*c[1][2]*c[2][1]*c[3][3] - c[0][1]*c[1][0]*c[2][2]*c[3][3] + c[0][0]*c[1][1]*c[2][2]*c[3][3];
}
template <typename T>
Matrix4<T> Matrix4<T>::Inverted() const
{
Matrix4<T> dst;
T d = Determinant();
if( d == 0 ) {
return dst;
}
d = 1.0f / d;
dst.c[0][0] = d * (c[1][2]*c[2][3]*c[3][1] - c[1][3]*c[2][2]*c[3][1] + c[1][3]*c[2][1]*c[3][2] - c[1][1]*c[2][3]*c[3][2] - c[1][2]*c[2][1]*c[3][3] + c[1][1]*c[2][2]*c[3][3]);
dst.c[0][1] = d * (c[0][3]*c[2][2]*c[3][1] - c[0][2]*c[2][3]*c[3][1] - c[0][3]*c[2][1]*c[3][2] + c[0][1]*c[2][3]*c[3][2] + c[0][2]*c[2][1]*c[3][3] - c[0][1]*c[2][2]*c[3][3]);
dst.c[0][2] = d * (c[0][2]*c[1][3]*c[3][1] - c[0][3]*c[1][2]*c[3][1] + c[0][3]*c[1][1]*c[3][2] - c[0][1]*c[1][3]*c[3][2] - c[0][2]*c[1][1]*c[3][3] + c[0][1]*c[1][2]*c[3][3]);
dst.c[0][3] = d * (c[0][3]*c[1][2]*c[2][1] - c[0][2]*c[1][3]*c[2][1] - c[0][3]*c[1][1]*c[2][2] + c[0][1]*c[1][3]*c[2][2] + c[0][2]*c[1][1]*c[2][3] - c[0][1]*c[1][2]*c[2][3]);
dst.c[1][0] = d * (c[1][3]*c[2][2]*c[3][0] - c[1][2]*c[2][3]*c[3][0] - c[1][3]*c[2][0]*c[3][2] + c[1][0]*c[2][3]*c[3][2] + c[1][2]*c[2][0]*c[3][3] - c[1][0]*c[2][2]*c[3][3]);
dst.c[1][1] = d * (c[0][2]*c[2][3]*c[3][0] - c[0][3]*c[2][2]*c[3][0] + c[0][3]*c[2][0]*c[3][2] - c[0][0]*c[2][3]*c[3][2] - c[0][2]*c[2][0]*c[3][3] + c[0][0]*c[2][2]*c[3][3]);
dst.c[1][2] = d * (c[0][3]*c[1][2]*c[3][0] - c[0][2]*c[1][3]*c[3][0] - c[0][3]*c[1][0]*c[3][2] + c[0][0]*c[1][3]*c[3][2] + c[0][2]*c[1][0]*c[3][3] - c[0][0]*c[1][2]*c[3][3]);
dst.c[1][3] = d * (c[0][2]*c[1][3]*c[2][0] - c[0][3]*c[1][2]*c[2][0] + c[0][3]*c[1][0]*c[2][2] - c[0][0]*c[1][3]*c[2][2] - c[0][2]*c[1][0]*c[2][3] + c[0][0]*c[1][2]*c[2][3]);
dst.c[2][0] = d * (c[1][1]*c[2][3]*c[3][0] - c[1][3]*c[2][1]*c[3][0] + c[1][3]*c[2][0]*c[3][1] - c[1][0]*c[2][3]*c[3][1] - c[1][1]*c[2][0]*c[3][3] + c[1][0]*c[2][1]*c[3][3]);
dst.c[2][1] = d * (c[0][3]*c[2][1]*c[3][0] - c[0][1]*c[2][3]*c[3][0] - c[0][3]*c[2][0]*c[3][1] + c[0][0]*c[2][3]*c[3][1] + c[0][1]*c[2][0]*c[3][3] - c[0][0]*c[2][1]*c[3][3]);
dst.c[2][2] = d * (c[0][1]*c[1][3]*c[3][0] - c[0][3]*c[1][1]*c[3][0] + c[0][3]*c[1][0]*c[3][1] - c[0][0]*c[1][3]*c[3][1] - c[0][1]*c[1][0]*c[3][3] + c[0][0]*c[1][1]*c[3][3]);
dst.c[2][3] = d * (c[0][3]*c[1][1]*c[2][0] - c[0][1]*c[1][3]*c[2][0] - c[0][3]*c[1][0]*c[2][1] + c[0][0]*c[1][3]*c[2][1] + c[0][1]*c[1][0]*c[2][3] - c[0][0]*c[1][1]*c[2][3]);
dst.c[3][0] = d * (c[1][2]*c[2][1]*c[3][0] - c[1][1]*c[2][2]*c[3][0] - c[1][2]*c[2][0]*c[3][1] + c[1][0]*c[2][2]*c[3][1] + c[1][1]*c[2][0]*c[3][2] - c[1][0]*c[2][1]*c[3][2]);
dst.c[3][1] = d * (c[0][1]*c[2][2]*c[3][0] - c[0][2]*c[2][1]*c[3][0] + c[0][2]*c[2][0]*c[3][1] - c[0][0]*c[2][2]*c[3][1] - c[0][1]*c[2][0]*c[3][2] + c[0][0]*c[2][1]*c[3][2]);
dst.c[3][2] = d * (c[0][2]*c[1][1]*c[3][0] - c[0][1]*c[1][2]*c[3][0] - c[0][2]*c[1][0]*c[3][1] + c[0][0]*c[1][2]*c[3][1] + c[0][1]*c[1][0]*c[3][2] - c[0][0]*c[1][1]*c[3][2]);
dst.c[3][3] = d * (c[0][1]*c[1][2]*c[2][0] - c[0][2]*c[1][1]*c[2][0] + c[0][2]*c[1][0]*c[2][1] - c[0][0]*c[1][2]*c[2][1] - c[0][1]*c[1][0]*c[2][2] + c[0][0]*c[1][1]*c[2][2]);
return dst;
}
template <typename T>
QuaternionT<T> Matrix4<T>::ToQuaternion() const
{
QuaternionT<T> q;
auto& a = this->c;
float trace = a[0][0] + a[1][1] + a[2][2]; // I removed + 1.0f; see discussion with Ethan
if( trace > 0 ) {// I changed M_EPSILON to 0
float s = 0.5f / sqrtf(trace+ 1.0f);
q.w = 0.25f / s;
q.x = ( a[1][2] - a[2][1] ) * s;
q.y = ( a[2][0] - a[0][2] ) * s;
q.z = ( a[0][1] - a[1][0] ) * s;
} else {
if ( a[0][0] > a[1][1] && a[0][0] > a[2][2] ) {
float s = 2.0f * sqrtf( 1.0f + a[0][0] - a[1][1] - a[2][2]);
q.w = (a[1][2] - a[2][1] ) / s;
q.x = 0.25f * s;
q.y = (a[1][0] + a[0][1] ) / s;
q.z = (a[2][0] + a[0][2] ) / s;
} else if (a[1][1] > a[2][2]) {
float s = 2.0f * sqrtf( 1.0f + a[1][1] - a[0][0] - a[2][2]);
q.w = (a[2][0] - a[0][2] ) / s;
q.x = (a[1][0] + a[0][1] ) / s;
q.y = 0.25f * s;
q.z = (a[2][1] + a[1][2] ) / s;
} else {
float s = 2.0f * sqrtf( 1.0f + a[2][2] - a[0][0] - a[1][1] );
q.w = (a[0][1] - a[1][0] ) / s;
q.x = (a[2][0] + a[0][2] ) / s;
q.y = (a[2][1] + a[1][2] ) / s;
q.z = 0.25f * s;
}
}
return q;
}
template <typename T>
Vector3<T> Matrix4<T>::GetTranslate() const
{
return Vector3<T>(c[3][0], c[3][1], c[3][2]);
}
template <typename T>
Vector3<T> Matrix4<T>::GetScale() const
{
Vector3<T> scale;
scale.x = sqrtf(c[0][0] * c[0][0] + c[0][1] * c[0][1] + c[0][2] * c[0][2]);
scale.y = sqrtf(c[1][0] * c[1][0] + c[1][1] * c[1][1] + c[1][2] * c[1][2]);
scale.z = sqrtf(c[2][0] * c[2][0] + c[2][1] * c[2][1] + c[2][2] * c[2][2]);
return scale;
}
template <typename T>
void Matrix4<T>::Decompose(Vector3<T>& trans, Vector3<T>& rot, Vector3<T>& scale) const
{
trans = GetTranslate();
scale = GetScale();
if( scale.x == 0 || scale.y == 0 || scale.z == 0 ) {
rot.x = 0;
rot.y = 0;
rot.z = 0;
return;
}
// Detect negative scale with determinant and flip one arbitrary axis
if(Determinant() < 0) {
scale.x = -scale.x;
}
// Combined rotation matrix YXZ
//
// Cos[y]*Cos[z]+Sin[x]*Sin[y]*Sin[z] Cos[z]*Sin[x]*Sin[y]-Cos[y]*Sin[z] Cos[x]*Sin[y]
// Cos[x]*Sin[z] Cos[x]*Cos[z] -Sin[x]
// -Cos[z]*Sin[y]+Cos[y]*Sin[x]*Sin[z] Cos[y]*Cos[z]*Sin[x]+Sin[y]*Sin[z] Cos[x]*Cos[y]
rot.x = asinf(-c[2][1] / scale.z);
// Special case: Cos[x] == 0 (when Sin[x] is +/-1)
T f = fabsf(c[2][1] / scale.z);
if(f > 0.999f && f < 1.001f) {
// Pin arbitrarily one of y or z to zero
// Mathematical equivalent of gimbal lock
rot.y = 0;
// Now: Cos[x] = 0, Sin[x] = +/-1, Cos[y] = 1, Sin[y] = 0
// => m[0][0] = Cos[z] and m[1][0] = Sin[z]
rot.z = atan2f(-c[1][0] / scale.y, c[0][0] / scale.x);
} else {
// Standard case
rot.y = atan2f(c[2][0] / scale.z, c[2][2] / scale.z);
rot.z = atan2f(c[0][1] / scale.x, c[1][1] / scale.y);
}
}
template <typename T>
Matrix4<T> Matrix4<T>::Translated(T x, T y, T z)
{
Matrix4 m;
m.x[12] = x;
m.x[13] = y;
m.x[14] = z;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::Scaled(T x, T y, T z)
{
Matrix4 m;
m.x[0] = x;
m.x[5] = y;
m.x[10] = z;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::Rotated(T x, T y, T z)
{
return Matrix4(QuaternionT<T>(x, y ,z));
}
template <typename T>
Matrix4<T> Matrix4<T>::RotatedX(T degrees)
{
T radians = degrees * SM_DEG_TO_RAD;
T s = sin(radians);
T c = cos(radians);
Matrix4 m;
m.x[5] = c; m.x[9] = s;
m.x[6] = -s; m.x[10] = c;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::RotatedY(T degrees)
{
T radians = degrees * SM_DEG_TO_RAD;
T s = sin(radians);
T c = cos(radians);
Matrix4 m;
m.x[0] = c; m.x[8] = -s;
m.x[2] = s; m.x[10] = c;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::RotatedZ(T degrees)
{
T radians = degrees * SM_DEG_TO_RAD;
T s = sin(radians);
T c = cos(radians);
Matrix4 m;
m.x[0] = c; m.x[4] = s;
m.x[1] = -s; m.x[5] = c;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::RotatedAxis(const Vector3<T>& axis, T angle)
{
T t = sin(angle * 0.5f);
T x = axis.x * t;
T y = axis.y * t;
T z = axis.z * t;
return Matrix4(QuaternionT<T>(x, y, z, cos(angle * 0.5f)));
}
template <typename T>
Matrix4<T> Matrix4<T>::Sheared(T kx, T ky)
{
Matrix4 m;
m.x[1] = ky;
m.x[4] = kx;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::SkewY(T sx, T sz)
{
mat4 m;
m.x[2] = sz;
m.x[8] = sx;
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::Perspective(T fovy, T aspect, T znear, T zfar)
{
assert(abs(aspect - std::numeric_limits<T>::epsilon()) > static_cast<T>(0));
Matrix4 m;
memset(m.x, 0, sizeof(m));
T const tan_half_fovy = static_cast<T>(tan(fovy / static_cast<T>(2) * SM_DEG_TO_RAD));
m.c[0][0] = static_cast<T>(1) / (aspect * tan_half_fovy);
m.c[1][1] = static_cast<T>(1) / (tan_half_fovy);
m.c[2][2] = - (zfar + znear) / (zfar - znear);
m.c[2][3] = - static_cast<T>(1);
m.c[3][2] = -(2 * zfar * znear) / (zfar - znear);
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::Orthographic(T l, T r, T b, T t, T n, T f)
{
Matrix4 m;
m.x[0] = 2 / (r - l);
m.x[5] = 2 / (t - b);
m.x[10] = - 2 / (f - n);
m.x[12] = -(r + l) / (r - l);
m.x[13] = -(t + b) / (t - b);
m.x[14] = -(f + n) / (f - n);
return m;
}
template <typename T>
Matrix4<T> Matrix4<T>::LookAt(const Vector3<T>& eye, const Vector3<T>& center, const Vector3<T>& up)
{
auto f = (center - eye).Normalized();
auto s = f.Cross(up).Normalized();
auto u = s.Cross(f);
Matrix4 m;
m.c[0][0] = s.x;
m.c[1][0] = s.y;
m.c[2][0] = s.z;
m.c[0][1] = u.x;
m.c[1][1] = u.y;
m.c[2][1] = u.z;
m.c[0][2] = -f.x;
m.c[1][2] = -f.y;
m.c[2][2] = -f.z;
m.c[3][0] = -s.Dot(eye);
m.c[3][1] = -u.Dot(eye);
m.c[3][2] = f.Dot(eye);
return m;
}
}
#endif // _SPATIAL_MATH_MATRIX_INL_
|
#include "IPCoverTiming.hh"
#include "ISocket.hh"
#include "IInput.hh"
#include "IOutput.hh"
#include "Defines.hh"
#include "Exception.hh"
#include "Packet.hh"
#include "CUIPHeader.hh"
#include "CUTCPHeader.hh"
#include <sstream>
#include <iostream>
#include <iomanip>
#include <unistd.h>
//Initialization of the ressources and properties of the Storage TTL algorithm
IPCoverTiming::IPCoverTiming()
: _socket(NULL), _input(NULL), _name("IPCoverTiming"), _argFormat(""), _description("Timing interval technique (transmit 1bit per packet)")
{
this->_packet = new Packet(new CUIPHeader, new CUTCPHeader);
}
IPCoverTiming::~IPCoverTiming()
{
//Delete the packet allocated
if (this->_packet)
delete this->_packet;
}
//Execute the algorithm for hiding data
bool IPCoverTiming::executeHiding()
{
char *data;
unsigned int sizeData;
unsigned int cpt = 0;
uint8_t value;
//Check the ressources
if ((!this->_socket) || (!this->_input))
throw Exception(ERROR_RESSOURCES);
if (!this->_packet)
throw Exception("Packet is not initialized.");
//Initialize all fields of headers within the packet
this->initPacket();
//Get the data input for hiding it within the field TTL
data = (char *)this->_input->getData();
sizeData = this->_input->getSizeData();
//Init
this->_socket->send(this->_packet->computeHeadersAndData(), this->_packet->getSizeHeadersAndData());
this->_packet->getIPHeader()->inc_id();
//Processing the data for sending
while (cpt < sizeData)
{
value = data[cpt];
if (!this->computeAndSendValue(value))
return (false);
++cpt;
}
return (true);
}
//Determine the TTL field and send the packet depending of the value specified
bool IPCoverTiming::computeAndSendValue(uint8_t value)
{
int cpt = 0;
//Check bit per bit
while (cpt < 8)
{
//Check bit per bit with a mask 128
if ((128 & value) != 0)
::usleep(1000);
//SHL instruction for the shift logical bit left
value = value << 1;
++cpt;
this->_socket->send(this->_packet->computeHeadersAndData(), this->_packet->getSizeHeadersAndData());
this->_packet->getIPHeader()->inc_id();
}
return (true);
}
//Execute the algorithm for recovering data
bool IPCoverTiming::executeRecovering()
{
int sizeReceiv = 0;
void *data;
bool initFinished = false;
uint8_t oneByte;
int cptByte = 0;
bool firstRound = true;
long int timeout = 0;
//Check the ressources
if ((!this->_socket) || (!this->_output))
throw Exception(ERROR_RESSOURCES);
while (42)
{
this->_socket->resetSockets(true);
if (this->_socket->select(&timeout) == -1)
throw Exception("Select has failed.");
if (initFinished)
{
if (timeout >= (TIMEOUT_INIT * TIMEOUT_PACKET))
{
this->_output->outputMemoryTimeout();
oneByte = 0;
cptByte = 0;
timeout = 0;
initFinished = false;
}
}
if (this->_socket->inputFdReadable())
return (true);
if (this->_socket->socketReadable())
{
if ((data = this->_socket->receive(&sizeReceiv)) == NULL)
return (false);
if (this->_packet->loadPacket(data, sizeReceiv))
{
//Check if the packet is a packet with data hiden
if (this->checkSource())
{
//Init algorithm
if (!initFinished)
{
initFinished = true;
if (firstRound)
{
std::cout << LISTEN_RECEPTBEGIN << std::endl;
firstRound = false;
}
else
std::cout << std::endl << LISTEN_RECEPTBEGIN << std::endl;
timeout = 0;
}
//Algorithm
else
{
oneByte = oneByte << 1;
if (timeout > 950)
oneByte += 1;
++cptByte;
if (cptByte >= 8)
{
cptByte = 0;
this->_output->outputData(&oneByte);
oneByte = 0;
}
}
timeout = 0;
}
}
}
}
return (true);
}
//Mutator method for the ressources of the algorithm
void IPCoverTiming::setRessources(ISocket *socket, IInput *input)
{
this->_socket = socket;
this->_input = input;
}
//Mutator method for the ressources of the algorithm
void IPCoverTiming::setRessources(ISocket *socket, IOutput *output)
{
this->_socket = socket;
this->_output = output;
}
//Check the syntax of the algorithm
bool IPCoverTiming::checkSyntax(std::vector<std::string> &args)
{
args.erase(args.begin());
return (true);
}
//Accessor method for the name of the algorithm
const std::string &IPCoverTiming::getName() const
{
return (this->_name);
}
//Accessor method for arguments format of the algorithm
const std::string &IPCoverTiming::getArgFormat() const
{
return (this->_argFormat);
}
//Accessor method for descritpion of the algorithm
const std::string &IPCoverTiming::getDescription() const
{
return (this->_description);
}
//Initialize all fields of headers within the packet
void IPCoverTiming::initPacket()
{
uint32_t myAddress = this->_socket->convertAddress("42.42.42.42");
//Initialization of the IP header
this->_packet->getIPHeader()->set_ihl(5);
this->_packet->getIPHeader()->set_version(4);
this->_packet->getIPHeader()->set_tos(0);
this->_packet->getIPHeader()->set_tot_len(this->_packet->getSizeHeadersAndData());
this->_packet->getIPHeader()->set_id(1);
this->_packet->getIPHeader()->set_frag_off(0);
this->_packet->getIPHeader()->set_ttl(64);
this->_packet->getIPHeader()->set_protocol(IPPROTO_TCP);
this->_packet->getIPHeader()->set_check(0);
this->_packet->getIPHeader()->set_saddr(myAddress);
this->_packet->getIPHeader()->set_daddr(this->_socket->getDestAddress());
this->_packet->getIPHeader()->set_check(this->_packet->checkSum((unsigned short *) this->_packet->computeHeadersAndData(), this->_packet->getIPHeader()->get_tot_len()));
//Initialization of the TCP header
this->_packet->getTCPHeader()->set_portSource(::htons(1337));
this->_packet->getTCPHeader()->set_portDest(::htons(this->_socket->getDestPort()));
this->_packet->getTCPHeader()->set_seq(0);
this->_packet->getTCPHeader()->set_ack_seq(0);
this->_packet->getTCPHeader()->set_doff(5);
this->_packet->getTCPHeader()->set_fin(0);
this->_packet->getTCPHeader()->set_syn(1);
this->_packet->getTCPHeader()->set_rst(0);
this->_packet->getTCPHeader()->set_psh(0);
this->_packet->getTCPHeader()->set_ack(0);
this->_packet->getTCPHeader()->set_urg(0);
this->_packet->getTCPHeader()->set_window(::htons(6666));
this->_packet->getTCPHeader()->set_check(0);
this->_packet->getTCPHeader()->set_urg_ptr(0);
this->_packet->getTCPHeader()->set_addressSource(myAddress);
this->_packet->getTCPHeader()->set_addressDest(this->_socket->getDestAddress());
this->_packet->getTCPHeader()->set_placeHolder(0);
this->_packet->getTCPHeader()->set_protocol(IPPROTO_TCP);
this->_packet->getTCPHeader()->set_tcpLength(::htons(this->_packet->getTCPHeader()->getSize()));
this->_packet->getTCPHeader()->set_check(this->_packet->checkSum((unsigned short *) this->_packet->getTCPHeaderAndData(), this->_packet->getTCPHeader()->getSize() + this->_packet->getSizeData()));
}
bool IPCoverTiming::checkSource()
{
uint32_t sourceAddress = this->_socket->convertAddress("42.42.42.42");
//Check of the IP header
if (this->_packet->getIPHeader()->get_ihl() != 5)
return (false);
if (this->_packet->getIPHeader()->get_version() != 4)
return (false);
if (this->_packet->getIPHeader()->get_protocol() != IPPROTO_TCP)
return (false);
if (this->_packet->getIPHeader()->get_saddr() != sourceAddress)
return (false);
//Check of the TCP header
if (this->_packet->getTCPHeader()->get_portSource() != ::htons(1337))
return (false);
if (this->_packet->getTCPHeader()->get_portDest() != ::htons(this->_socket->getDestPort()))
return (false);
if (this->_packet->getTCPHeader()->get_window() != ::htons(6666))
return (false);
if (this->_packet->getTCPHeader()->get_addressSource() != sourceAddress)
return (false);
if (this->_packet->getTCPHeader()->get_protocol() != IPPROTO_TCP)
return (false);
if (this->_packet->getTCPHeader()->get_tcpLength() != ::htons(this->_packet->getTCPHeader()->getSize()))
return (false);
return (true);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
**
** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/dom/src/domcore/node.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domcore/domdoc.h"
#include "modules/dom/src/domcore/docfrag.h"
#include "modules/dom/src/domcore/attr.h"
#include "modules/dom/src/domcore/comment.h"
#include "modules/dom/src/domcore/chardata.h"
#include "modules/dom/src/domcore/domxmldocument.h"
#include "modules/dom/src/domcore/entity.h"
#include "modules/dom/src/domcore/text.h"
#include "modules/dom/src/domhtml/htmldoc.h"
#include "modules/dom/src/domhtml/htmlcoll.h"
#include "modules/dom/src/domhtml/htmlelem.h"
#include "modules/dom/src/domevents/domevent.h"
#include "modules/dom/src/domevents/domeventdata.h"
#include "modules/dom/src/domevents/domeventthread.h"
#include "modules/dom/src/domevents/domeventtarget.h"
#include "modules/dom/src/domevents/domeventlistener.h"
#include "modules/dom/src/domevents/dommutationevent.h"
#include "modules/dom/src/domcss/cssstylesheet.h"
#include "modules/dom/src/domxpath/xpathnamespace.h"
#include "modules/dom/src/domxpath/xpathresult.h"
#include "modules/dom/src/domxpath/xpathevaluator.h"
#include "modules/dom/src/domxpath/xpathnsresolver.h"
#include "modules/dom/src/js/window.h"
#include "modules/dom/src/userjs/userjsmanager.h"
#include "modules/dom/src/domsvg/domsvgelementinstance.h"
#include "modules/doc/frm_doc.h"
#include "modules/dochand/fdelm.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/ecmascript_utils/esthread.h"
#include "modules/logdoc/datasrcelm.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/xmlenum.h"
#include "modules/probetools/probepoints.h"
#include "modules/util/tempbuf.h"
#include "modules/xmlutils/xmldocumentinfo.h"
#include "modules/xpath/xpath.h"
#if defined SVG_DOM
# include "modules/svg/SVGManager.h"
#endif
#ifdef DRAG_SUPPORT
# include "modules/pi/OpDragObject.h"
# include "modules/dragdrop/dragdrop_manager.h"
#endif // DRAG_SUPPORT
#ifdef DOM_EXPENSIVE_DEBUG_CODE
#include "modules/util/OpHashTable.h"
class DOM_NodeElm
{
public:
DOM_Node *node;
DOM_NodeElm *next;
unsigned signalled;
} *g_DOM_all_nodes;
static void
DOM_AddNode(DOM_Node *node)
{
DOM_NodeElm *elm = OP_NEW(DOM_NodeElm, ());
elm->node = node;
elm->next = g_DOM_all_nodes;
elm->signalled = FALSE;
g_DOM_all_nodes = elm;
}
static void
DOM_RemoveNode(DOM_Node *node)
{
DOM_NodeElm **elmp = &g_DOM_all_nodes;
BOOL found = FALSE;
while (*elmp)
{
if ((*elmp)->node == node)
{
found = TRUE;
DOM_NodeElm *discard = *elmp;
*elmp = (*elmp)->next;
OP_DELETE(discard);
if (!node->IsA(DOM_TYPE_DOCUMENT))
break;
}
else
{
if ((*elmp)->node->GetOwnerDocument() == node)
(*elmp)->node->SetOwnerDocument(NULL);
elmp = &(*elmp)->next;
}
}
OP_ASSERT(found);
}
OpGenericPointerSet g_DOM_element_with_node;
void
DOM_VerifyAllNodes()
{
DOM_NodeElm *iter = g_DOM_all_nodes;
while (iter)
{
if ((iter->signalled & 2) == 0)
if (iter->node->GetNodeType() == ELEMENT_NODE)
if (!iter->node->GetThisElement())
{
OP_ASSERT(FALSE);
iter->signalled |= 2;
}
if ((iter->signalled & 4) == 0)
if (HTML_Element *element = iter->node->GetThisElement())
if (OpStatus::IsError(g_DOM_element_with_node.Add(element)))
{
OP_ASSERT(FALSE);
iter->signalled |= 4;
}
iter = iter->next;
}
g_DOM_element_with_node.RemoveAll();
}
#endif // DOM_EXPENSIVE_DEBUG_CODE
OP_STATUS
DOM_Node::GetParentNode(DOM_Node *&node)
{
if (HTML_Element *this_element = GetThisElement())
if (HTML_Element *parent = this_element->ParentActual())
return GetEnvironment()->ConstructNode(node, parent, owner_document);
node = NULL;
return OpStatus::OK;
}
OP_STATUS
DOM_Node::GetFirstChild(DOM_Node *&node)
{
if (node_type == ATTRIBUTE_NODE)
RETURN_IF_ERROR(static_cast<DOM_Attr *>(this)->CreateValueTree(NULL));
if (HTML_Element *placeholder = GetPlaceholderElement())
if (HTML_Element *first_child = placeholder->FirstChildActual())
return GetEnvironment()->ConstructNode(node, first_child, owner_document);
node = NULL;
return OpStatus::OK;
}
OP_STATUS
DOM_Node::GetLastChild(DOM_Node *&node)
{
if (node_type == ATTRIBUTE_NODE)
RETURN_IF_ERROR(static_cast<DOM_Attr *>(this)->CreateValueTree(NULL));
if (HTML_Element *placeholder = GetPlaceholderElement())
if (HTML_Element *last_child = placeholder->LastChildActual())
return GetEnvironment()->ConstructNode(node, last_child, owner_document);
node = NULL;
return OpStatus::OK;
}
OP_STATUS
DOM_Node::GetPreviousSibling(DOM_Node *&node)
{
if (HTML_Element *this_element = GetThisElement())
if (HTML_Element *previous_sibling = this_element->PredActual())
return GetEnvironment()->ConstructNode(node, previous_sibling, owner_document);
node = NULL;
return OpStatus::OK;
}
OP_STATUS
DOM_Node::GetNextSibling(DOM_Node *&node)
{
if (HTML_Element *this_element = GetThisElement())
if (HTML_Element *next_sibling = this_element->SucActual())
return GetEnvironment()->ConstructNode(node, next_sibling, owner_document);
node = NULL;
return OpStatus::OK;
}
OP_STATUS
DOM_Node::GetPreviousNode(DOM_Node *&node)
{
if (HTML_Element *this_element = GetThisElement())
if (HTML_Element *previous_node = this_element->PrevActual())
return GetEnvironment()->ConstructNode(node, previous_node, owner_document);
node = NULL;
return OpStatus::OK;
}
OP_STATUS
DOM_Node::GetNextNode(DOM_Node *&node, BOOL skip_children)
{
HTML_Element *element = GetThisElement();
if (!element)
element = GetPlaceholderElement();
if (element)
{
HTML_Element *next_node;
if (skip_children || element->Type() == Markup::HTE_TEXTGROUP)
next_node = element->NextSiblingActual();
else
next_node = element->NextActual();
if (next_node)
return GetEnvironment()->ConstructNode(node, next_node, owner_document);
}
node = NULL;
return OpStatus::OK;
}
BOOL
DOM_Node::IsAncestorOf(DOM_Node *other)
{
if (this == other)
return TRUE;
else
{
HTML_Element *ancestor = GetPlaceholderElement();
HTML_Element *descendant = other->GetThisElement();
return ancestor && descendant && ancestor->IsAncestorOf(descendant);
}
}
OP_STATUS
DOM_Node::PutPrivate(int private_name, ES_Object *object)
{
SetIsSignificant();
return EcmaScript_Object::PutPrivate(private_name, object);
}
OP_STATUS
DOM_Node::PutPrivate(int private_name, DOM_Object *object)
{
return PutPrivate(private_name, *object);
}
OP_STATUS
DOM_Node::PutPrivate(int private_name, ES_Value &value)
{
SetIsSignificant();
return EcmaScript_Object::PutPrivate(private_name, value);
}
/* static */
BOOL
DOM_Node::ShouldBlockWaitingForStyle(FramesDocument* frames_doc, ES_Runtime* origining_runtime)
{
if (frames_doc && frames_doc->IsWaitingForStyles())
{
ES_Thread* thread = GetCurrentThread(origining_runtime);
while (thread)
{
if (thread->Type() == ES_THREAD_EVENT)
{
DOM_Event* event_object = static_cast<DOM_EventThread*>(thread)->GetEvent();
if (event_object->GetKnownType() == DOM_EVENT_CUSTOM && uni_str_eq(event_object->GetType(), "BeforeCSS"))
return FALSE; // Can't have BeforeCSS block waiting for style since that would mean waiting for itself.
break;
}
thread = thread->GetInterruptedThread();
}
return TRUE;
}
return FALSE;
}
/* static */
HTML_Element *
DOM_Node::GetEventTargetElement(HTML_Element *element)
{
#ifdef SVG_DOM
if (element->GetNsType() == NS_SVG)
// "shadow" nodes share event target with the real node
return g_svg_manager->GetEventTarget(element);
#endif // SVG_DOM
return element;
}
/* static */ HTML_Element *
DOM_Node::GetEventPathParent(HTML_Element *currentTarget, HTML_Element *target)
{
HTML_Element *parent;
#ifdef SVG_DOM
parent = currentTarget->Parent();
if (!parent || parent->GetInserted() != HE_INSERTED_BY_SVG)
#endif // SVG_DOM
{
// Find elements up the chain. Accepts visible nodes
// plus the HE_DOC_ROOT which represents the document
for (parent = currentTarget->Parent(); parent; parent = parent->Parent())
{
if (parent->Type() == Markup::HTE_DOC_ROOT || parent->IsIncludedActual() && !parent->IsText())
break;
}
}
return parent;
}
/* static */ HTML_Element *
DOM_Node::GetActualEventTarget(HTML_Element *element)
{
HTML_Element *parent = element;
while (parent && (parent->GetInserted() == HE_INSERTED_BY_LAYOUT || parent->IsText()))
parent = parent->Parent();
if (parent)
return parent;
else
return element;
}
/* static */
DOM_EventTarget *
DOM_Node::GetEventTargetFromElement(HTML_Element *element)
{
element = GetEventTargetElement(element);
if (DOM_Node* node = (DOM_Node *) element->GetESElement())
return node->GetEventTarget();
else
return NULL;
}
/* virtual */ DOM_EventTarget *
DOM_Node::FetchEventTarget()
{
#ifdef SVG_DOM
if (HTML_Element *this_element = GetThisElement())
{
HTML_Element *element = GetEventTargetElement(this_element);
if (element != this_element)
{
DOM_Node* node = (DOM_Node *) element->GetESElement();
if (node)
return node->FetchEventTarget();
else
return NULL;
}
}
#endif // SVG_DOM
return event_target;
}
/* virtual */ OP_STATUS
DOM_Node::CreateEventTarget()
{
#ifdef SVG_DOM
if (HTML_Element *this_element = GetThisElement())
{
HTML_Element *element = GetEventTargetElement(this_element);
if (element != this_element)
{
DOM_Node* node;
RETURN_IF_ERROR(GetEnvironment()->ConstructNode(node, element, owner_document));
return node->CreateEventTarget();
}
}
#endif // SVG_DOM
SetIsSignificant();
return DOM_EventTargetOwner::CreateEventTarget();
}
HTML_Element *
DOM_Node::GetThisElement()
{
if (node_type == ELEMENT_NODE)
return static_cast<DOM_Element *>(this)->GetThisElement();
else if (IsA(DOM_TYPE_CHARACTERDATA) || node_type == PROCESSING_INSTRUCTION_NODE)
return static_cast<DOM_CharacterData *>(this)->GetThisElement();
else if (IsA(DOM_TYPE_DOCUMENTTYPE))
return static_cast<DOM_DocumentType *>(this)->GetThisElement();
#ifdef SVG_DOM
else if(node_type == SVG_ELEMENTINSTANCE_NODE)
return static_cast<DOM_SVGElementInstance *>(this)->GetThisElement();
#endif // SVG_DOM
else
return NULL;
}
HTML_Element *
DOM_Node::GetPlaceholderElement()
{
if (node_type == ELEMENT_NODE)
return static_cast<DOM_Element *>(this)->GetThisElement();
else if (node_type == DOCUMENT_FRAGMENT_NODE)
return static_cast<DOM_DocumentFragment *>(this)->GetPlaceholderElement();
else if (node_type == DOCUMENT_NODE)
return static_cast<DOM_Document *>(this)->GetPlaceholderElement();
#ifdef DOM_SUPPORT_ENTITY
else if (node_type == ENTITY_NODE)
return static_cast<DOM_Entity *>(this)->GetPlaceholderElement();
#endif // DOM_SUPPORT_ENTITY
else if (node_type == ATTRIBUTE_NODE)
return static_cast<DOM_Attr *>(this)->GetPlaceholderElement();
return NULL;
}
BOOL
DOM_Node::IsReadOnly()
{
#ifdef DOM_SUPPORT_ENTITY
if (node_type == ENTITY_NODE)
return !static_cast<DOM_Entity *>(this)->IsBeingParsed();
#endif // DOM_SUPPORT_ENTITY
return FALSE;
}
LogicalDocument *
DOM_Node::GetLogicalDocument()
{
if (owner_document)
return owner_document->GetLogicalDocument();
else
{
OP_ASSERT(node_type == DOCUMENT_NODE);
return static_cast<DOM_Document *>(this)->GetLogicalDocument();
}
}
ES_GetState
DOM_Node::DOMSetElement(ES_Value *value, HTML_Element *element)
{
if (value)
if (element)
{
DOM_Document *document = owner_document;
if (!document)
{
OP_ASSERT(node_type == DOCUMENT_NODE);
document = (DOM_Document *) this;
}
DOM_Node *node;
GET_FAILED_IF_ERROR(GetEnvironment()->ConstructNode(node, element, document));
value->type = VALUE_OBJECT;
value->value.object = *node;
}
else
value->type = VALUE_NULL;
return GET_SUCCESS;
}
ES_GetState
DOM_Node::DOMSetParentNode(ES_Value *value)
{
if (value)
{
DOM_Node *node;
GET_FAILED_IF_ERROR(GetParentNode(node));
DOMSetObject(value, node);
}
return GET_SUCCESS;
}
ES_GetState
DOM_Node::GetStyleSheet(ES_Value *value, DOM_CSSRule *import_rule, DOM_Runtime *origining_runtime)
{
HTML_Element *element = GetThisElement();
if (element)
{
BOOL has_stylesheet = element->IsStyleElement();
if (!has_stylesheet && element->IsLinkElement())
{
if (element->Type() == HE_PROCINST)
has_stylesheet = TRUE;
else
{
const uni_char *rel = element->GetStringAttr(ATTR_REL);
if (rel)
{
unsigned kinds = LinkElement::MatchKind(rel);
has_stylesheet = (kinds & LINK_TYPE_STYLESHEET) != 0;
}
}
}
if (has_stylesheet)
{
if (value)
{
ES_GetState result = DOMSetPrivate(value, DOM_PRIVATE_sheet);
if (result != GET_FAILED)
return result;
DOM_CSSStyleSheet *stylesheet;
GET_FAILED_IF_ERROR(DOM_CSSStyleSheet::Make(stylesheet, this, import_rule));
GET_FAILED_IF_ERROR(PutPrivate(DOM_PRIVATE_sheet, *stylesheet));
DOMSetObject(value, stylesheet);
}
return GET_SUCCESS;
}
}
return GET_FAILED;
}
#ifdef DOM2_MUTATION_EVENTS
OP_STATUS DOM_Node::SendNodeInserted(ES_Thread *interrupt_thread)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
HTML_Element *this_element = GetThisElement();
if (environment->IsEnabled() && this_element)
{
BOOL has_nodeinserted_handlers = environment->HasEventHandlers(DOMNODEINSERTED);
BOOL has_nodeinsertedintodocument_handlers = environment->HasEventHandlers(DOMNODEINSERTEDINTODOCUMENT);
if (has_nodeinserted_handlers || has_nodeinsertedintodocument_handlers)
{
if (has_nodeinserted_handlers && environment->HasEventHandler(this_element, DOMNODEINSERTED))
{
DOM_Node *node;
RETURN_IF_ERROR(environment->ConstructNode(node, this_element->ParentActual(), owner_document));
RETURN_IF_ERROR(DOM_MutationEvent::SendNodeInserted(interrupt_thread, this, node));
}
if (has_nodeinsertedintodocument_handlers && GetIsInDocument())
{
HTML_Element *elm;
elm = this_element;
while (elm && this_element->IsAncestorOf(elm))
{
if (environment->HasEventHandler(elm, DOMNODEINSERTEDINTODOCUMENT))
{
DOM_Node *node;
RETURN_IF_ERROR(environment->ConstructNode(node, elm, owner_document));
RETURN_IF_ERROR(DOM_MutationEvent::SendNodeInsertedIntoDocument(interrupt_thread, node));
}
elm = (HTML_Element *) elm->Next();
}
}
}
}
return OpStatus::OK;
}
OP_STATUS DOM_Node::SendNodeRemoved(ES_Thread *interrupt_thread)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
HTML_Element *this_element = GetThisElement();
if (environment->IsEnabled() && this_element)
{
BOOL has_noderemove_handlers = environment->HasEventHandlers(DOMNODEREMOVED);
BOOL has_noderemovedfromdocument_handlers = environment->HasEventHandlers(DOMNODEREMOVEDFROMDOCUMENT);
if (has_noderemove_handlers || has_noderemovedfromdocument_handlers)
{
if (has_noderemove_handlers && environment->HasEventHandler(this_element, DOMNODEREMOVED))
{
DOM_Node *node;
RETURN_IF_ERROR(environment->ConstructNode(node, this_element->ParentActual(), owner_document));
RETURN_IF_ERROR(DOM_MutationEvent::SendNodeRemoved(interrupt_thread, this, node));
}
if (has_noderemovedfromdocument_handlers && GetIsInDocument())
{
HTML_Element *elm;
elm = this_element;
while (elm && this_element->IsAncestorOf(elm))
{
if (environment->HasEventHandler(elm, DOMNODEREMOVEDFROMDOCUMENT))
{
DOM_Node *node;
RETURN_IF_ERROR(environment->ConstructNode(node, elm, owner_document));
RETURN_IF_ERROR(DOM_MutationEvent::SendNodeRemovedFromDocument(interrupt_thread, node));
}
elm = (HTML_Element *) elm->Next();
}
}
}
}
return OpStatus::OK;
}
#endif /* DOM2_MUTATION_EVENTS */
BOOL DOM_Node::GetIsInDocument()
{
return owner_document ? owner_document->IsAncestorOf(this) : IsA(DOM_TYPE_DOCUMENT);
}
ES_GetState DOM_Node::GetBaseURI(ES_Value* value, ES_Runtime* origining_runtime)
{
if (value)
{
DOMSetNull(value);
/**
* Specification:
* http://www.whatwg.org/specs/web-apps/current-work/multipage/urls.html#document-base-url
* Lookup in order:
* - xml:base in current scope
* - <base> element
* - document url
*/
if (owner_document)
{
URL result;
if (LogicalDocument* logdoc = owner_document->GetLogicalDocument())
{
if (HTML_Element* elm = GetThisElement())
// lookup xml:base
result = elm->DeriveBaseUrl(logdoc);
if (result.IsEmpty() && logdoc->GetBaseURL())
// lookup <base> uri
result = *logdoc->GetBaseURL();
}
if (result.IsEmpty())
// use document url
result = owner_document->GetURL();
if (!result.IsEmpty())
{
OpString url_str;
GET_FAILED_IF_ERROR(result.GetAttribute(URL::KUniName, url_str));
TempBuffer *buffer = GetEmptyTempBuf();
GET_FAILED_IF_ERROR(buffer->Append(url_str.CStr()));
DOMSetString(value, buffer);
}
}
}
return GET_SUCCESS;
}
OP_STATUS DOM_Node::InsertChild(DOM_Node *child, DOM_Node *reference, DOM_Runtime *origining_runtime)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
HTML_Element *this_elm = GetPlaceholderElement();
HTML_Element *child_elm = child->GetThisElement();
HTML_Element *reference_elm = reference ? reference->GetThisElement() : NULL;
OP_ASSERT(this_elm);
/* The child should have been removed by the caller prior to calling
this function. */
OP_ASSERT(!child_elm->Parent());
DOM_EnvironmentImpl::CurrentState state(environment, origining_runtime);
RETURN_IF_ERROR(this_elm->DOMInsertChild(environment, child_elm, reference_elm));
if (node_type == DOCUMENT_NODE)
if (child->node_type == ELEMENT_NODE && ((DOM_Document *) this)->GetRootElement() != child)
{
OP_ASSERT(!((DOM_Document *) this)->GetRootElement());
((DOM_Document *) this)->SetRootElement((DOM_Element *) child);
}
else if (child->node_type == DOCUMENT_TYPE_NODE)
RETURN_IF_ERROR(((DOM_Document *) this)->UpdateXMLDocumentInfo());
return OpStatus::OK;
}
OP_STATUS
DOM_Node::RemoveFromParent(ES_Runtime *origining_runtime)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
HTML_Element *element = GetThisElement();
RETURN_IF_ERROR(environment->SignalOnBeforeRemove(GetThisElement(), static_cast<DOM_Runtime *>(origining_runtime)));
environment->SetCallMutationListeners(FALSE);
SetIsSignificant();
DOM_EnvironmentImpl::CurrentState state(environment, static_cast<DOM_Runtime *>(origining_runtime));
OP_STATUS status = element->DOMRemoveFromParent(environment);
environment->SetCallMutationListeners(TRUE);
RETURN_IF_ERROR(status);
if (owner_document->GetRootElement() == this)
owner_document->SetRootElement(NULL);
return OpStatus::OK;
}
int
DOM_Node::RemoveAllChildren(BOOL restarted, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
#ifdef DOM2_MUTATION_EVENTS
if (restarted)
{
int result = removeChild(this, NULL, -1, return_value, origining_runtime);
if (result != ES_VALUE)
return result;
}
BOOL has_mutation_listeners = FALSE;
if (environment->HasEventHandlers(DOMNODEREMOVED))
has_mutation_listeners = TRUE;
else if (environment->HasEventHandlers(DOMNODEREMOVEDFROMDOCUMENT) && GetOwnerDocument()->IsAncestorOf(this))
has_mutation_listeners = TRUE;
if (has_mutation_listeners)
{
DOM_Node *child;
CALL_FAILED_IF_ERROR(GetFirstChild(child));
while (child)
{
int result;
ES_Value arguments[1];
DOMSetObject(&arguments[0], child);
result = DOM_Node::removeChild(this, arguments, 1, return_value, origining_runtime);
if (result != ES_VALUE)
return result;
CALL_FAILED_IF_ERROR(GetFirstChild(child));
}
}
else
#endif // DOM2_MUTATION_EVENTS
{
if (HTML_Element *placeholder = GetPlaceholderElement())
{
OP_STATUS status = OpStatus::OK;
OpStatus::Ignore(status);
DOM_EnvironmentImpl::CurrentState state(environment, origining_runtime);
status = placeholder->DOMRemoveAllChildren(environment);
CALL_FAILED_IF_ERROR(status);
}
}
return ES_FAILED;
}
/* virtual */ DOM_Object *
DOM_Node::GetOwnerObject()
{
return this;
}
DOM_Node::DOM_Node(DOM_NodeType type)
: node_type(type),
is_significant(type == DOCUMENT_NODE || type == DOCUMENT_FRAGMENT_NODE || type == ATTRIBUTE_NODE ? 1 : 0),
have_native_property(0),
#ifdef USER_JAVASCRIPT
waiting_for_beforecss(FALSE),
#endif // USER_JAVASCRIPT
owner_document(NULL)
{
#ifdef DOM_EXPENSIVE_DEBUG_CODE
DOM_AddNode(this);
#endif // DOM_EXPENSIVE_DEBUG_CODE
#ifdef DOM_XPATH_REFERENCE_IMPLEMENTATION
document_order_index = ~0u;
#endif // DOM_XPATH_REFERENCE_IMPLEMENTATION
}
/* virtual */
DOM_Node::~DOM_Node()
{
#ifdef DOM_EXPENSIVE_DEBUG_CODE
DOM_RemoveNode(this);
#endif // DOM_EXPENSIVE_DEBUG_CODE
}
/* virtual */ void
DOM_Node::GCTrace()
{
GCTraceSpecial(FALSE);
}
/* virtual */ void
DOM_Node::GCTraceSpecial(BOOL via_tree)
{
if (!via_tree && owner_document && !owner_document->IsAncestorOf(this))
GCMark(owner_document);
GCMark(event_target);
}
/* static */ void
DOM_Node::GCMarkAndTrace(DOM_Runtime *runtime, DOM_Node *node, BOOL only_if_significant)
{
if (node)
{
if (!only_if_significant || node->GetIsSignificant())
runtime->GCMark(node, TRUE);
else
ES_Runtime::GCExcludeHostFromTrace(node);
node->GCTraceSpecial(TRUE);
}
}
void
DOM_Node::TraceElementTree(HTML_Element *element)
{
while (HTML_Element *parent = element->Parent())
element = parent;
do
if (DOM_Node *node = (DOM_Node *) element->GetESElement())
DOM_Node::GCMarkAndTrace(GetRuntime(), node, TRUE);
while ((element = (HTML_Element *) element->Next()) != NULL);
}
void
DOM_Node::FreeElementTree(HTML_Element *element)
{
OP_PROBE5(OP_PROBE_DOM_FREEELEMENTTREE);
while (element->Parent())
element = element->Parent();
GetEnvironment()->TreeDestroyed(element);
HTML_Element *iter = element;
while (iter)
{
if (DOM_Node *node = (DOM_Node *) iter->GetESElement())
{
DOM_NodeType node_type = node->GetNodeType();
if (node_type == ELEMENT_NODE)
static_cast<DOM_Element *>(node)->ClearThisElement();
else if (node_type == DOCUMENT_NODE)
static_cast<DOM_Document *>(node)->ClearPlaceholderElement();
else if (node_type == DOCUMENT_FRAGMENT_NODE)
static_cast<DOM_DocumentFragment *>(node)->ClearPlaceholderElement();
else if (node_type == ATTRIBUTE_NODE)
static_cast<DOM_Attr *>(node)->ClearPlaceholderElement();
else if (node_type == DOCUMENT_TYPE_NODE)
{
static_cast<DOM_DocumentType *>(node)->SetThisElement(NULL);
}
#ifdef DOM_SUPPORT_ENTITY
else if (node_type == ENTITY_NODE)
static_cast<DOM_Entity *>(node)->ClearPlaceholderElement();
#endif // DOM_SUPPORT_ENTITY
#ifdef SVG_DOM
else if (node_type == SVG_ELEMENTINSTANCE_NODE)
static_cast<DOM_SVGElementInstance *>(node)->ClearThisElement();
#endif // SVG_DOM
else
{
OP_ASSERT(node_type == TEXT_NODE || node_type == COMMENT_NODE || node_type == PROCESSING_INSTRUCTION_NODE || node_type == CDATA_SECTION_NODE);
static_cast<DOM_CharacterData *>(node)->ClearThisElement();
}
iter->SetESElement(NULL);
}
iter = (HTML_Element *) iter->Next();
}
if (GetRuntime()->InGC())
if (FramesDocument *frames_doc = GetRuntime()->GetFramesDocument())
frames_doc->SetDelayDocumentFinish(TRUE);
DOM_EnvironmentImpl *environment = GetEnvironment();
environment->SetCallMutationListeners(FALSE);
HTML_Element::DOMFreeElement(element, environment);
environment->SetCallMutationListeners(TRUE);
}
void
DOM_Node::FreeElement(HTML_Element *element)
{
if (!GetIsSignificant())
{
#ifdef _DEBUG
/* Check that there is at least one significant node in this subtree or
that the subtree is infact the document.
Note: at this point GetOwnerDocument() may point to a deleted object.
This can only happen if 'element' is in a detached subtree, since if
it was in the subtree rooted by the owner document, this node and its
element would have been decoupled when the owner document was
deleted. The usage of GetOwnerDocument() below should be safe, since
we're just using the pointer value, and the memory can't have been
reused to store a different document node yet, having been freed by
the same GC run and all. */
BOOL ok = FALSE;
HTML_Element *iter = element;
while (iter->Parent())
{
iter = iter->Parent();
if (iter->Type() == HE_DOC_ROOT && iter->GetESElement() == GetOwnerDocument())
{
ok = TRUE;
break;
}
}
if (!ok)
while (iter)
{
if (DOM_Node *node = (DOM_Node *) iter->GetESElement())
{
OP_ASSERT(GetOwnerDocument() == node->GetOwnerDocument());
if (node->GetIsSignificant())
{
ok = TRUE;
break;
}
}
iter = (HTML_Element *) iter->Next();
}
OP_ASSERT(ok);
#endif // _DEBUG
element->SetESElement(NULL);
}
else
FreeElementTree(element);
}
/* virtual */ void
DOM_Node::DOMChangeRuntime(DOM_Runtime *new_runtime)
{
DOM_Object::DOMChangeRuntime(new_runtime);
DOMChangeRuntimeOnPrivate(DOM_PRIVATE_sheet);
DOMChangeRuntimeOnPrivate(DOM_PRIVATE_style);
}
/* virtual */ void
DOM_Node::DOMChangeOwnerDocument(DOM_Document *new_ownerDocument)
{
SetOwnerDocument(new_ownerDocument);
}
/* virtual */ ES_GetState
DOM_Node::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_nodeType:
DOMSetNumber(value, node_type);
/* Put this constant value on the native object, 'caching' it there.
Should [[Put]] of "nodeType" be attempted, the operation will be
delegated to this host object, DOM_Node, which will issue a
DOMException. If the property has already been made special
(by definining a getter, say), do not overwrite. */
if (value && !GetRuntime()->IsSpecialProperty(*this, UNI_L("nodeType")))
GET_FAILED_IF_ERROR(GetRuntime()->PutName(GetNativeObject(), UNI_L("nodeType"), *value, PROP_READ_ONLY | PROP_HOST_PUT));
return GET_SUCCESS;
case OP_ATOM_nodeValue:
case OP_ATOM_parentNode:
case OP_ATOM_firstChild:
case OP_ATOM_lastChild:
case OP_ATOM_previousSibling:
case OP_ATOM_nextSibling:
case OP_ATOM_attributes:
case OP_ATOM_namespaceURI:
case OP_ATOM_prefix:
DOMSetNull(value);
return GET_SUCCESS;
case OP_ATOM_baseURI:
return GetBaseURI(value, origining_runtime);
case OP_ATOM_childNodes:
if (value)
{
ES_GetState result = DOMSetPrivate(value, DOM_PRIVATE_childNodes);
if (result != GET_FAILED)
return result;
else
{
DOM_Collection *collection;
DOM_SimpleCollectionFilter filter(CHILDNODES);
GET_FAILED_IF_ERROR(DOM_Collection::MakeNodeList(collection, GetEnvironment(), NULL, FALSE, FALSE, filter));
GET_FAILED_IF_ERROR(PutPrivate(DOM_PRIVATE_childNodes, *collection));
DOMSetObject(value, collection);
}
}
return GET_SUCCESS;
case OP_ATOM_ownerDocument:
DOMSetObject(value, owner_document);
return GET_SUCCESS;
case OP_ATOM_localName:
if (value)
if (node_type == ELEMENT_NODE)
{
TempBuffer *buffer = GetEmptyTempBuf();
const uni_char *localpart = static_cast<DOM_Element *>(this)->GetTagName(buffer, FALSE, FALSE);
if (!localpart)
return GET_NO_MEMORY;
DOMSetString(value, localpart);
}
else
DOMSetNull(value);
return GET_SUCCESS;
case OP_ATOM_sheet:
return GetStyleSheet(value, NULL, static_cast<DOM_Runtime *>(origining_runtime));
case OP_ATOM_textContent:
return GetTextContent(value);
}
return GET_FAILED;
}
ES_GetState
DOM_Node::GetTextContent(ES_Value* value)
{
if (value)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
HTML_Element *root = GetThisElement();
if (!root)
root = GetPlaceholderElement();
TempBuffer *buffer = GetEmptyTempBuf();
const uni_char *string_value = NULL;
BOOL first = TRUE;
if (root)
for (HTML_Element *iter = root, *stop = root->NextSiblingActual(); iter != stop;)
{
if (iter->IsText())
{
if (first)
{
if (!(string_value = iter->DOMGetContentsString(environment, buffer)))
return GET_NO_MEMORY;
first = FALSE;
}
else
{
if (string_value && buffer->Length() == 0)
GET_FAILED_IF_ERROR(buffer->Append(string_value));
string_value = NULL;
GET_FAILED_IF_ERROR(iter->DOMGetContents(environment, buffer));
}
iter = iter->NextSiblingActual();
}
else
iter = iter->NextActual();
}
if (string_value)
DOMSetString(value, string_value);
else
DOMSetString(value, buffer);
}
return GET_SUCCESS;
}
ES_PutState
DOM_Node::SetTextContent(ES_Value *value, DOM_Runtime *origining_runtime, ES_Object *restart_object)
{
if (value->type != VALUE_STRING)
return PUT_NEEDS_STRING;
while (1)
{
OP_BOOLEAN isRemoveChild = OpBoolean::IS_FALSE;
ES_Value arguments[1], return_value;
int result = ES_VALUE;
if (restart_object)
{
DOMSetObject(&return_value, restart_object);
ES_Value dummy;
isRemoveChild = origining_runtime->GetName(restart_object, UNI_L("isRemoveChild"), &dummy);
PUT_FAILED_IF_ERROR(isRemoveChild);
if (isRemoveChild == OpBoolean::IS_TRUE)
result = DOM_Node::removeChild(NULL, NULL, -1, &return_value, origining_runtime);
else
result = DOM_Node::appendChild(NULL, NULL, -1, &return_value, origining_runtime);
restart_object = NULL;
}
else
{
DOM_Node *child;
PUT_FAILED_IF_ERROR(GetFirstChild(child));
if (child)
{
DOMSetObject(&arguments[0], child);
result = DOM_Node::removeChild(this, arguments, 1, &return_value, origining_runtime);
isRemoveChild = OpBoolean::IS_TRUE;
}
else if (*value->value.string)
{
DOM_Text *text;
PUT_FAILED_IF_ERROR(DOM_Text::Make(text, this, value->value.string));
DOMSetObject(&arguments[0], text);
result = DOM_Node::appendChild(this, arguments, 1, &return_value, origining_runtime);
}
}
if (result == (ES_SUSPEND | ES_RESTART))
{
ES_Value dummy;
if (isRemoveChild == OpBoolean::IS_TRUE)
PUT_FAILED_IF_ERROR(origining_runtime->PutName(return_value.value.object, UNI_L("isRemoveChild"), dummy));
*value = return_value;
}
if (result != ES_VALUE)
return ConvertCallToPutName(result, value);
if (isRemoveChild == OpBoolean::IS_FALSE)
break;
}
return PUT_SUCCESS;
}
/* virtual */ ES_PutState
DOM_Node::PutName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime)
{
ES_PutState state = DOM_Object::PutName(property_name, property_code, value, origining_runtime);
if (state == PUT_FAILED && !HaveNativeProperty())
{
SetIsSignificant();
SetHaveNativeProperty();
return PUT_FAILED_DONT_CACHE;
}
return state;
}
/* virtual */ ES_PutState
DOM_Node::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_nodeType:
case OP_ATOM_parentNode:
case OP_ATOM_ownerDocument:
case OP_ATOM_nodeName:
case OP_ATOM_firstChild:
case OP_ATOM_lastChild:
case OP_ATOM_previousSibling:
case OP_ATOM_nextSibling:
case OP_ATOM_childNodes:
case OP_ATOM_attributes:
case OP_ATOM_namespaceURI:
case OP_ATOM_localName:
case OP_ATOM_sheet:
case OP_ATOM_children:
case OP_ATOM_parentElement:
case OP_ATOM_baseURI:
return PUT_READ_ONLY;
case OP_ATOM_nodeValue:
case OP_ATOM_prefix:
return PUT_SUCCESS;
case OP_ATOM_textContent:
if (value->type == VALUE_NULL)
DOMSetString(value);
return SetTextContent(value, (DOM_Runtime *) origining_runtime);
}
return PUT_FAILED;
}
/* virtual */ ES_PutState
DOM_Node::PutNameRestart(const uni_char *property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime, ES_Object *restart_object)
{
return DOM_Object::PutNameRestart(property_name, property_code, value, origining_runtime, restart_object);
}
/* virtual */ ES_PutState
DOM_Node::PutNameRestart(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime, ES_Object *restart_object)
{
OP_ASSERT(property_name == OP_ATOM_text || property_name == OP_ATOM_textContent);
if (property_name == OP_ATOM_textContent && value->type == VALUE_NULL)
DOMSetString(value);
return SetTextContent(value, (DOM_Runtime *) origining_runtime, restart_object);
}
#ifdef DOM_INSPECT_NODE_SUPPORT
OP_STATUS
DOM_Node::InspectNode(unsigned flags, DOM_Utils::InspectNodeCallback *callback)
{
HTML_Element *this_element = GetThisElement();
DOM_Document *document = GetOwnerDocument();
const uni_char *namespace_uri = NULL, *prefix = NULL, *localpart = NULL;
const uni_char *value = NULL;
int ns_idx;
TempBuffer value_buffer;
TempBuffer name_buffer;
BOOL has_children = FALSE;
callback->SetType(this, node_type);
switch (node_type)
{
case ELEMENT_NODE:
if (!(localpart = this_element->DOMGetElementName(GetEnvironment(), &name_buffer, ns_idx, TRUE)))
return OpStatus::ERR_NO_MEMORY;
GetThisElement()->DOMGetNamespaceData(GetEnvironment(), ns_idx, namespace_uri, prefix);
has_children = TRUE;
switch (this_element->Type())
{
case HE_FRAME:
case HE_OBJECT:
case HE_IFRAME:
RETURN_IF_MEMORY_ERROR(InspectFrameNode(callback));
break;
}
break;
case ATTRIBUTE_NODE:
namespace_uri = static_cast<DOM_Attr *>(this)->GetNsUri();
prefix = static_cast<DOM_Attr *>(this)->GetNsPrefix();
localpart = static_cast<DOM_Attr *>(this)->GetName();
value = static_cast<DOM_Attr *>(this)->GetValue();
break;
case PROCESSING_INSTRUCTION_NODE:
localpart = this_element->DOMGetPITarget(GetEnvironment());
/* fall through */
case TEXT_NODE:
case CDATA_SECTION_NODE:
case COMMENT_NODE:
RETURN_IF_ERROR(static_cast<DOM_CharacterData *>(this)->GetValue(&value_buffer));
value = value_buffer.GetStorage();
if (!value)
value = UNI_L("");
break;
case DOCUMENT_NODE:
has_children = TRUE;
RETURN_IF_MEMORY_ERROR(InspectDocumentNode(callback));
break;
case DOCUMENT_FRAGMENT_NODE:
has_children = TRUE;
break;
case DOCUMENT_TYPE_NODE:
if ((flags & DOM_Utils::INSPECT_BASIC) != 0)
callback->SetDocumentTypeInformation(this, static_cast<DOM_DocumentType *>(this)->GetName(), static_cast<DOM_DocumentType *>(this)->GetPublicId(), static_cast<DOM_DocumentType *>(this)->GetSystemId());
break;
default:
return OpStatus::OK;
}
if ((flags & DOM_Utils::INSPECT_BASIC) != 0)
{
if (localpart)
callback->SetName(this, namespace_uri, prefix, localpart);
if (value)
callback->SetValue(this, value);
}
if (node_type == ELEMENT_NODE && (flags & DOM_Utils::INSPECT_ATTRIBUTES) != 0)
RETURN_IF_ERROR(static_cast<DOM_Element *>(this)->InspectAttributes(callback));
if (GetThisElement() && document && (flags & DOM_Utils::INSPECT_PARENT) != 0)
if (HTML_Element *parent_element = GetThisElement()->ParentActual())
{
DOM_Node *parent_node;
RETURN_IF_ERROR(GetEnvironment()->ConstructNode(parent_node, parent_element, document));
callback->SetParent(this, parent_node);
}
if (has_children && document && (flags & DOM_Utils::INSPECT_CHILDREN) != 0)
{
HTML_Element *child_element = GetPlaceholderElement()->FirstChildActual();
while (child_element)
{
DOM_Node *child_node;
RETURN_IF_ERROR(GetEnvironment()->ConstructNode(child_node, child_element, document));
callback->AddChild(this, child_node);
child_element = child_element->SucActual();
}
}
return OpStatus::OK;
}
OP_STATUS
DOM_Node::InspectDocumentNode(DOM_Utils::InspectNodeCallback *callback)
{
DOM_Document *document = static_cast<DOM_Document *>(this);
FramesDocument *frm_doc = document->GetFramesDocument();
if (!frm_doc)
return OpStatus::ERR;
DocumentManager *docman = frm_doc->GetDocManager();
FramesDocument *pdoc = docman->GetParentDoc();
FramesDocElm *frame = docman->GetFrame();
if (!pdoc || !frame)
return OpStatus::ERR;
HTML_Element *element = frame->GetHtmlElement();
if (element)
{
RETURN_IF_ERROR(pdoc->ConstructDOMEnvironment());
DOM_EnvironmentImpl *environment = static_cast<DOM_EnvironmentImpl*>(pdoc->GetDOMEnvironment());
RETURN_IF_ERROR(environment->ConstructDocumentNode());
DOM_Document *doc = static_cast<DOM_Document*>(environment->GetDocument());
ES_Value value;
if (doc->DOMSetElement(&value, element) == GET_SUCCESS)
callback->SetDocumentInformation(this, DOM_Utils::GetDOM_Object(value.value.object));
}
return OpStatus::OK;
}
OP_STATUS
DOM_Node::InspectFrameNode(DOM_Utils::InspectNodeCallback *callback)
{
HTML_Element *this_element = GetThisElement();
DOM_ProxyEnvironment *frame_environment;
FramesDocument *frame_frames_doc;
DOM_Runtime *runtime = GetEnvironment()->GetDOMRuntime();
RETURN_IF_ERROR(this_element->DOMGetFrameProxyEnvironment(frame_environment, frame_frames_doc, GetEnvironment()));
if (frame_environment)
{
DOM_Object *content_document = NULL;
RETURN_IF_ERROR(static_cast<DOM_ProxyEnvironmentImpl *>(frame_environment)->GetProxyDocument(content_document, runtime));
callback->SetFrameInformation(this, content_document);
}
return OpStatus::OK;
}
#endif // DOM_INSPECT_NODE_SUPPORT
class DOM_Mutation_State
: public DOM_Object
{
public:
enum Point { ADOPT, REMOVE, INSERT, FINISHED } point;
DOM_Node *this_node, *new_node, *old_node, *extra_node;
ES_Value return_value;
DOM_Mutation_State(Point point, DOM_Node *this_node, DOM_Node *new_node, DOM_Node *old_node, DOM_Node *extra_node)
: point(point), this_node(this_node), new_node(new_node), old_node(old_node), extra_node(extra_node)
{
}
virtual void GCTrace()
{
GCMark(this_node);
GCMark(new_node);
GCMark(old_node);
GCMark(extra_node);
GCMark(return_value);
}
};
/* static */ int
DOM_Node::insertBefore(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_Mutation_State *state = NULL;
DOM_Mutation_State::Point point = DOM_Mutation_State::ADOPT;
DOM_Node *this_node;
DOM_Node *new_node;
DOM_Node *old_node;
if (argc >= 0)
{
DOM_THIS_OBJECT_EXISTING(this_node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("oO");
DOM_ARGUMENT_OBJECT_EXISTING(new_node, 0, DOM_TYPE_NODE, DOM_Node);
DOM_ARGUMENT_OBJECT_EXISTING(old_node, 1, DOM_TYPE_NODE, DOM_Node);
}
else
{
state = DOM_VALUE2OBJECT(*return_value, DOM_Mutation_State);
point = state->point;
this_object = this_node = state->this_node;
new_node = state->new_node;
old_node = state->old_node;
*return_value = state->return_value;
}
HTML_Element *this_elm = this_node->GetPlaceholderElement();
HTML_Element *new_elm = new_node->GetThisElement();
HTML_Element *old_elm = old_node ? old_node->GetThisElement() : NULL;
if (!new_elm && new_node->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
new_elm = ((DOM_DocumentFragment *) new_node)->GetPlaceholderElement();
if (!this_elm && this_node->GetNodeType() == DOCUMENT_NODE)
return DOM_CALL_DOMEXCEPTION(NO_MODIFICATION_ALLOWED_ERR);
if (!this_elm || !new_elm || new_elm->IsAncestorOf(this_elm))
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
if (this_node->IsReadOnly())
return DOM_CALL_DOMEXCEPTION(NO_MODIFICATION_ALLOWED_ERR);
if (this_node->GetNodeType() == DOCUMENT_NODE || this_node->GetNodeType() == ATTRIBUTE_NODE)
{
BOOL ok = TRUE, element_found = FALSE, doctype_found = FALSE, is_document = this_node->GetNodeType() == DOCUMENT_NODE;
DOM_Node *iter;
if (new_node->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
CALL_FAILED_IF_ERROR(new_node->GetFirstChild(iter));
else
iter = new_node;
while (iter)
{
BOOL ok0 = FALSE;
if (is_document)
switch (iter->GetNodeType())
{
case COMMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
ok0 = TRUE;
break;
case ELEMENT_NODE:
if (!element_found)
{
if (DOM_Element *element = ((DOM_Document *) this_node)->GetRootElement())
{
if (element == new_node)
ok0 = TRUE;
}
else
ok0 = TRUE;
element_found = TRUE;
}
break;
case TEXT_NODE:
CALL_FAILED_IF_ERROR(((DOM_Text *) new_node)->IsWhitespace(ok0));
break;
case DOCUMENT_TYPE_NODE:
if (!doctype_found)
{
ok0 = TRUE;
doctype_found = TRUE;
}
}
else
ok0 = iter->GetNodeType() == TEXT_NODE;
if (!ok0)
{
ok = FALSE;
break;
}
if (new_node->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
CALL_FAILED_IF_ERROR(iter->GetNextSibling(iter));
else
break;
}
if (!ok)
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
}
else if (new_node->GetNodeType() == DOCUMENT_TYPE_NODE)
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
if (new_elm->IsAncestorOf(this_elm))
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
if (old_node && (!old_elm || old_elm->ParentActual() != this_elm))
return DOM_CALL_DOMEXCEPTION(NOT_FOUND_ERR);
if (new_elm == old_elm)
{
DOMSetObject(return_value, new_node);
return ES_VALUE;
}
BOOL is_restarted = state != NULL;
#define IS_POINT(p) point == p
#define SET_POINT(p) if (state) state->point = p; point = p; is_restarted = FALSE
#define IS_RESTARTED (is_restarted)
if (IS_POINT(DOM_Mutation_State::ADOPT))
{
int result;
if (!IS_RESTARTED)
{
if (this_node->GetOwnerDocument() != new_node->GetOwnerDocument())
{
ES_Value arguments[1];
DOMSetObject(&arguments[0], new_node);
result = DOM_Document::adoptNode(this_node->GetOwnerDocument(), arguments, 1, return_value, origining_runtime);
}
else
result = ES_VALUE;
}
else
result = DOM_Document::adoptNode(NULL, NULL, -1, return_value, origining_runtime);
if (result == (ES_SUSPEND | ES_RESTART))
goto suspend;
if (result != ES_VALUE)
return result;
SET_POINT(DOM_Mutation_State::REMOVE);
}
if (new_node->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
{
while (1)
{
int result;
if (!IS_RESTARTED)
if (HTML_Element *elm = new_elm->FirstChild())
{
DOM_Node *node;
CALL_FAILED_IF_ERROR(this_node->GetEnvironment()->ConstructNode(node, elm, this_node->owner_document));
ES_Value arguments[2];
DOMSetObject(&arguments[0], node);
DOMSetObject(&arguments[1], old_node);
result = insertBefore(this_node, arguments, 2, return_value, origining_runtime);
}
else
break;
else
result = insertBefore(NULL, NULL, -1, return_value, origining_runtime);
if (result == (ES_SUSPEND | ES_RESTART))
goto suspend;
if (result != ES_VALUE)
return result;
is_restarted = FALSE;
}
}
else
{
if (IS_POINT(DOM_Mutation_State::REMOVE))
{
int result = ES_VALUE;
if (!IS_RESTARTED)
{
DOM_Node *new_parent;
CALL_FAILED_IF_ERROR(new_node->GetParentNode(new_parent));
if (new_parent)
{
ES_Value argument;
DOMSetObject(&argument, new_node);
result = removeChild(new_parent, &argument, 1, return_value, origining_runtime);
}
}
#ifdef DOM2_MUTATION_EVENTS
else
result = removeChild(NULL, NULL, -1, return_value, origining_runtime);
if (result == (ES_SUSPEND | ES_RESTART))
goto suspend;
#endif // DOM2_MUTATION_EVENTS
if (result != ES_VALUE)
return result;
SET_POINT(DOM_Mutation_State::INSERT);
}
if (IS_POINT(DOM_Mutation_State::INSERT))
{
CALL_FAILED_IF_ERROR(this_node->InsertChild(new_node, old_node, origining_runtime));
#ifdef DOM2_MUTATION_EVENTS
ES_Thread *thread = GetCurrentThread(origining_runtime);
CALL_FAILED_IF_ERROR(new_node->SendNodeInserted(thread));
if (thread && thread->IsBlocked())
{
SET_POINT(DOM_Mutation_State::FINISHED);
goto suspend;
}
#endif // DOM2_MUTATION_EVENTS
}
}
DOMSetObject(return_value, new_node);
return ES_VALUE;
#undef IS_POINT
#undef SET_POINT
#undef IS_RESTARTED
suspend:
if (!state)
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(state = OP_NEW(DOM_Mutation_State, (point, this_node, new_node, old_node, NULL)), this_node->GetRuntime()));
state->return_value = *return_value;
DOMSetObject(return_value, state);
return ES_SUSPEND | ES_RESTART;
}
/* static */ int
DOM_Node::replaceChild(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_Mutation_State *state = NULL;
DOM_Mutation_State::Point point = DOM_Mutation_State::REMOVE;
DOM_Node* this_node;
DOM_Node* new_node;
DOM_Node* old_node;
DOM_Node* extra_node;
if (argc >= 0)
{
DOM_THIS_OBJECT_EXISTING(this_node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("oo");
DOM_ARGUMENT_OBJECT_EXISTING(new_node, 0, DOM_TYPE_NODE, DOM_Node);
DOM_ARGUMENT_OBJECT_EXISTING(old_node, 1, DOM_TYPE_NODE, DOM_Node);
if (new_node->IsAncestorOf(this_node))
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
if (new_node->GetNodeType() == DOCUMENT_NODE || (new_node->GetNodeType() == DOCUMENT_TYPE_NODE && this_node->GetNodeType() != DOCUMENT_NODE))
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
CALL_FAILED_IF_ERROR(old_node->GetNextSibling(extra_node));
}
else
{
state = DOM_VALUE2OBJECT(*return_value, DOM_Mutation_State);
point = state->point;
this_object = this_node = state->this_node;
new_node = state->new_node;
old_node = state->old_node;
extra_node = state->extra_node;
*return_value = state->return_value;
}
#define IS_POINT(p) point == p
#define SET_POINT(p) if (state) state->point = p; point = p
#define IS_RESTARTED (state != NULL)
int result = ES_FAILED;
if (IS_POINT(DOM_Mutation_State::REMOVE))
{
if (!IS_RESTARTED)
{
ES_Value argument;
DOMSetObject(&argument, old_node);
result = removeChild(this_node, &argument, 1, return_value, origining_runtime);
}
#ifdef DOM2_MUTATION_EVENTS
else
result = removeChild(NULL, NULL, -1, return_value, origining_runtime);
if (result == (ES_SUSPEND | ES_RESTART))
goto suspend;
#endif // DOM2_MUTATION_EVENTS
if (result != ES_VALUE)
return result;
SET_POINT(DOM_Mutation_State::INSERT);
}
if (IS_POINT(DOM_Mutation_State::INSERT))
{
if (!IS_RESTARTED || result == ES_VALUE)
{
ES_Value arguments[2];
DOMSetObject(&arguments[0], new_node);
DOMSetObject(&arguments[1], extra_node);
result = insertBefore(this_node, arguments, 2, return_value, origining_runtime);
}
else
result = insertBefore(NULL, NULL, -1, return_value, origining_runtime);
if (result == (ES_SUSPEND | ES_RESTART))
goto suspend;
if (result != ES_VALUE)
return result;
DOMSetObject(return_value, old_node);
return result;
}
#undef IS_POINT
#undef SET_POINT
#undef IS_RESTARTED
suspend:
if (!state)
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(state = OP_NEW(DOM_Mutation_State, (point, this_node, new_node, old_node, extra_node)), this_node->GetRuntime()));
state->return_value = *return_value;
DOMSetObject(return_value, state);
return ES_SUSPEND | ES_RESTART;
}
/* static */ int
DOM_Node::appendChild(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
if (argc >= 0)
{
DOM_CHECK_ARGUMENTS("o");
ES_Value arguments[2];
arguments[0] = argv[0];
arguments[1].type = VALUE_NULL;
return insertBefore(this_object, arguments, 2, return_value, origining_runtime);
}
else
return insertBefore(NULL, NULL, -1, return_value, origining_runtime);
}
/* static */ int
DOM_Node::removeChild(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
#ifdef DOM2_MUTATION_EVENTS
DOM_Mutation_State *state = NULL;
#endif // DOM2_MUTATION_EVENTS
DOM_Node* this_node;
DOM_Node* old_node;
#ifdef DOM2_MUTATION_EVENTS
if (argc >= 0)
#endif // DOM2_MUTATION_EVENTS
{
DOM_THIS_OBJECT_EXISTING(this_node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("o");
DOM_ARGUMENT_OBJECT_EXISTING(old_node, 0, DOM_TYPE_NODE, DOM_Node);
if (this_node->GetEnvironment() != old_node->GetEnvironment())
return DOM_CALL_DOMEXCEPTION(NOT_FOUND_ERR);
if (this_node->IsReadOnly())
return DOM_CALL_DOMEXCEPTION(NO_MODIFICATION_ALLOWED_ERR);
/* Removing the root element from a displayed document would
require special handling (I think). */
//if (this_node->GetEnvironment()->GetDocument() == this_node)
// return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR);
}
#ifdef DOM2_MUTATION_EVENTS
else
{
state = DOM_VALUE2OBJECT(*return_value, DOM_Mutation_State);
this_object = this_node = state->this_node;
old_node = state->old_node;
}
#endif // DOM2_MUTATION_EVENTS
DOM_Node *parentNode;
CALL_FAILED_IF_ERROR(old_node->GetParentNode(parentNode));
if (parentNode != this_node)
return DOM_CALL_DOMEXCEPTION(NOT_FOUND_ERR);
#ifdef DOM2_MUTATION_EVENTS
if (!state)
{
ES_Thread *thread = GetCurrentThread(origining_runtime);
CALL_FAILED_IF_ERROR(old_node->SendNodeRemoved(thread));
if (thread && thread->IsBlocked())
{
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(state = OP_NEW(DOM_Mutation_State, (DOM_Mutation_State::REMOVE, this_node, NULL, old_node, NULL)), this_node->GetRuntime()));
DOMSetObject(return_value, state);
return ES_SUSPEND | ES_RESTART;
}
}
#endif // DOM2_MUTATION_EVENTS
CALL_FAILED_IF_ERROR(old_node->RemoveFromParent(origining_runtime));
DOMSetObject(return_value, old_node);
return ES_VALUE;
}
/* static */ int
DOM_Node::hasChildNodes(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
HTML_Element *placeholder = node->GetPlaceholderElement();
DOMSetBoolean(return_value, placeholder && placeholder->FirstChildActual());
return ES_VALUE;
}
/* static */ int
DOM_Node::cloneNode(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(this_node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("|b");
BOOL deep = argc == 0 || argv[0].value.boolean;
DOM_EnvironmentImpl *environment = this_node->GetEnvironment();
if (this_node->IsA(DOM_TYPE_ELEMENT) || this_node->IsA(DOM_TYPE_CHARACTERDATA) || this_node->IsA(DOM_TYPE_PROCESSINGINSTRUCTION) || this_node->IsA(DOM_TYPE_DOCUMENTTYPE))
{
HTML_Element *this_elm = this_node->GetThisElement();
HTML_Element *clone_elm;
DOM_Node *clone_node;
CALL_FAILED_IF_ERROR(HTML_Element::DOMCloneElement(clone_elm, this_node->GetEnvironment(), this_elm, deep));
CALL_FAILED_IF_ERROR(environment->ConstructNode(clone_node, clone_elm, this_node->owner_document));
DOMSetObject(return_value, clone_node);
return ES_VALUE;
}
else if (this_node->IsA(DOM_TYPE_DOCUMENTFRAGMENT))
{
HTML_Element *this_elm = ((DOM_DocumentFragment *) this_node)->GetPlaceholderElement();
DOM_DocumentFragment *clone_frag;
CALL_FAILED_IF_ERROR(DOM_DocumentFragment::Make(clone_frag, this_node));
if (deep)
{
HTML_Element *clone_elm;
CALL_FAILED_IF_ERROR(HTML_Element::DOMCloneElement(clone_elm, this_node->GetEnvironment(), this_elm, deep));
clone_frag->SetPlaceholderElement(clone_elm);
}
DOMSetObject(return_value, clone_frag);
return ES_VALUE;
}
else if (this_node->GetNodeType() == ATTRIBUTE_NODE)
{
DOM_Attr *clone_attr;
CALL_FAILED_IF_ERROR(((DOM_Attr *) this_node)->Clone(clone_attr));
DOMSetObject(return_value, clone_attr);
return ES_VALUE;
}
else if (this_node->GetNodeType() == DOCUMENT_NODE)
{
DOM_Document *this_doc = static_cast<DOM_Document *>(this_node);
// First create empty stub document
DOM_Document *clone_doc;
// To keep things simple: if the cloned document is totally empty,
// pretend we're supposed to do a shallow clone. Result would be the
// same either way, and the deep cloning code path needs a placeholder
// element.
if (!this_doc->GetPlaceholderElement())
deep = FALSE;
if (this_node->IsA(DOM_TYPE_HTML_DOCUMENT))
{
DOM_HTMLDocument *htmldocument;
CALL_FAILED_IF_ERROR(DOM_HTMLDocument::Make(htmldocument, this_doc->GetDOMImplementation(), !deep, FALSE));
clone_doc = htmldocument;
}
else
{
if (this_node->IsA(DOM_TYPE_XML_DOCUMENT))
CALL_FAILED_IF_ERROR(DOM_XMLDocument::Make(clone_doc, this_doc->GetDOMImplementation(), !deep));
else
{
BOOL is_xml = this_doc->IsXML();
CALL_FAILED_IF_ERROR(DOM_Document::Make(clone_doc, this_doc->GetDOMImplementation(), !deep, is_xml));
}
}
clone_doc->SetIsSignificant();
OP_ASSERT(clone_doc->GetRootElement() == NULL);
// Second, clone the tree.
if (deep)
{
HTML_Element *clone_elm;
CALL_FAILED_IF_ERROR(HTML_Element::DOMCloneElement(clone_elm, environment, this_doc->GetPlaceholderElement(), deep));
clone_doc->ResetPlaceholderElement(clone_elm);
// Find a proper root
OP_ASSERT(clone_doc->GetRootElement() == NULL);
HTML_Element *root_candidate = clone_elm->FirstChildActual();
DOM_Node *root_cand_elm;
while (root_candidate && !Markup::IsRealElement(root_candidate->Type()))
root_candidate = root_candidate->NextSiblingActual();
if (root_candidate)
{
CALL_FAILED_IF_ERROR(environment->ConstructNode(root_cand_elm, root_candidate, clone_doc));
OP_ASSERT(root_cand_elm->IsA(DOM_TYPE_ELEMENT));
CALL_FAILED_IF_ERROR(clone_doc->SetRootElement(static_cast<DOM_Element *>(root_cand_elm)));
}
// And deal with the doctype
if (this_node->GetHLDocProfile())
{
// On this document, doctype info is fetched from the HlDocprofile, which
// does not exist in the cloned document, so the doctype needs to be filled
DOM_Node *this_dt;
CALL_FAILED_IF_ERROR(this_doc->GetDocumentType(this_dt));
if (this_dt)
{
OP_ASSERT(this_dt->IsA(DOM_TYPE_DOCUMENTTYPE));
DOM_Node *clone_dt = NULL;
CALL_FAILED_IF_ERROR(clone_doc->GetDocumentType(clone_dt));
OP_ASSERT(clone_dt);
OP_ASSERT(clone_dt->IsA(DOM_TYPE_DOCUMENTTYPE));
static_cast<DOM_DocumentType *>(clone_dt)->CopyFrom(static_cast<DOM_DocumentType *>(this_dt));
clone_dt->SetIsSignificant();
}
}
}
DOMSetObject(return_value, clone_doc);
return ES_VALUE;
}
else
return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR);
}
#ifdef DOM2_MUTATION_EVENTS
class DOM_NormalizeState
: public DOM_Object
{
public:
enum Point { SEARCH, REMOVE_EMPTY, REMOVE_EMPTY_RESTARTED, REMOVE_SIBLINGS, REMOVE_SIBLINGS_RESTARTED } point;
DOM_Node *root, *current;
ES_Value return_value;
DOM_NormalizeState(DOM_Node *root)
: root(root), current(NULL)
{
}
virtual void GCTrace()
{
GCMark(root);
GCMark(current);
GCMark(return_value);
}
};
#endif // DOM2_MUTATION_EVENTS
/* static */ int
DOM_Node::normalize(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
#ifdef DOM2_MUTATION_EVENTS
DOM_NormalizeState *state = NULL;
DOM_NormalizeState::Point point = DOM_NormalizeState::SEARCH;
DOM_Node *root, *current;
if (argc >= 0)
{
DOM_THIS_OBJECT_EXISTING(root, DOM_TYPE_NODE, DOM_Node);
if (root->GetNodeType() == DOCUMENT_NODE || root->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
{
CALL_FAILED_IF_ERROR(root->GetFirstChild(current));
if (!current)
return ES_FAILED;
}
else if (root->GetNodeType() == ELEMENT_NODE)
current = root;
else
return ES_FAILED;
}
else
{
state = DOM_VALUE2OBJECT(*return_value, DOM_NormalizeState);
point = state->point;
this_object = root = state->root;
current = state->current;
*return_value = state->return_value;
if (current)
{
if (!root->IsAncestorOf(current))
if (root->GetNodeType() == DOCUMENT_NODE || root->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
{
CALL_FAILED_IF_ERROR(root->GetFirstChild(current));
if (!current)
return ES_FAILED;
}
else
current = root;
}
}
DOM_EnvironmentImpl *environment = root->GetEnvironment();
ES_Thread *thread = GetCurrentThread(origining_runtime);
HTML_Element *element = current ? current->GetThisElement() : NULL, *stop;
if (root->GetNodeType() == ELEMENT_NODE)
stop = ((DOM_Element *) root)->GetThisElement()->NextSiblingActual();
else
stop = NULL;
again:
while (point == DOM_NormalizeState::SEARCH)
{
if (element == stop || !element)
return ES_FAILED;
if (element->IsText() && !element->GetIsCDATA())
{
if (element->Type() == HE_TEXT && (!element->Content() || !*element->Content()))
{
CALL_FAILED_IF_ERROR(environment->ConstructNode(current, element, root->GetOwnerDocument()));
point = DOM_NormalizeState::REMOVE_EMPTY;
}
else
{
TempBuffer buffer;
HTML_Element *next_sibling = element->SucActual();
BOOL found = FALSE;
while (next_sibling && next_sibling->IsText() && !next_sibling->GetIsCDATA())
{
CALL_FAILED_IF_ERROR(next_sibling->DOMGetContents(environment, &buffer));
next_sibling = next_sibling->SucActual();
found = TRUE;
}
if (found)
{
CALL_FAILED_IF_ERROR(environment->ConstructNode(current, element, root->GetOwnerDocument()));
point = DOM_NormalizeState::REMOVE_SIBLINGS;
if (buffer.Length() > 0)
{
ES_Value arguments[1];
DOMSetString(&arguments[0], buffer.GetStorage());
int result = DOM_CharacterData::appendData(current, arguments, 1, return_value, origining_runtime);
if (result != ES_FAILED)
return result;
if (thread->IsBlocked())
goto suspend;
}
}
}
element = element->NextSiblingActual();
}
else
element = element->NextActual();
}
while (point != DOM_NormalizeState::SEARCH)
{
if (point == DOM_NormalizeState::REMOVE_EMPTY || point == DOM_NormalizeState::REMOVE_SIBLINGS)
{
HTML_Element *remove;
if (point == DOM_NormalizeState::REMOVE_EMPTY)
remove = current->GetThisElement();
else
{
remove = current->GetThisElement()->SucActual();
if (!remove || !remove->IsText() || remove->GetIsCDATA())
{
if (remove)
element = remove;
else if (current->GetThisElement()->IsText())
element = current->GetThisElement()->NextSiblingActual();
else
element = current->GetThisElement()->NextActual();
point = DOM_NormalizeState::SEARCH;
break;
}
}
DOM_Node *parent;
CALL_FAILED_IF_ERROR(environment->ConstructNode(parent, remove->ParentActual(), root->GetOwnerDocument()));
DOM_Node *sibling;
CALL_FAILED_IF_ERROR(environment->ConstructNode(sibling, remove, root->GetOwnerDocument()));
ES_Value arguments[1];
DOMSetObject(&arguments[0], sibling);
int result = removeChild(parent, arguments, 1, return_value, origining_runtime);
if (result == (ES_SUSPEND | ES_RESTART))
{
if (point == DOM_NormalizeState::REMOVE_EMPTY)
{
CALL_FAILED_IF_ERROR(current->GetNextNode(current));
point = DOM_NormalizeState::REMOVE_EMPTY_RESTARTED;
}
else
point = DOM_NormalizeState::REMOVE_SIBLINGS_RESTARTED;
goto suspend;
}
else if (result != ES_VALUE)
return result;
}
else
{
int result = removeChild(NULL, NULL, -1, return_value, origining_runtime);
if (result != ES_VALUE)
return result;
if (point == DOM_NormalizeState::REMOVE_SIBLINGS_RESTARTED)
point = DOM_NormalizeState::REMOVE_SIBLINGS;
}
if (point == DOM_NormalizeState::REMOVE_EMPTY || point == DOM_NormalizeState::REMOVE_EMPTY_RESTARTED)
point = DOM_NormalizeState::SEARCH;
}
goto again;
suspend:
if (!state)
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(state = OP_NEW(DOM_NormalizeState, (root)), root->GetRuntime()));
state->point = point;
state->current = current;
state->return_value = *return_value;
DOMSetObject(return_value, state);
return ES_SUSPEND | ES_RESTART;
#else // DOM2_MUTATION_EVENTS
DOM_THIS_OBJECT(this_node, DOM_TYPE_NODE, DOM_Node);
TempBuffer *buffer = this_node->GetTempBuf();
HTML_Element *element;
if (this_node->GetNodeType() == ELEMENT_NODE)
element = ((DOM_Element *) this_node)->GetThisElement();
else if (this_node->GetNodeType() == DOCUMENT_FRAGMENT_NODE)
element = ((DOM_DocumentFragment *) this_node)->GetPlaceholderElement();
else if (this_node->GetNodeType() == DOCUMENT_NODE && ((DOM_Document *) this_node)->GetRootElement())
element = ((DOM_Document *) this_node)->GetRootElement()->GetThisElement();
else
return ES_FAILED;
HTML_Element *stop = element->NextSiblingActual();
while (element != stop)
{
HTML_Element *next = element->IsText() ? element->NextSiblingActual() : element->NextActual();
if (element->IsText() && !element->GetIsCDATA())
if (element->Type() == HE_TEXT && (!element->Content() || !*element->Content()))
if (DOM_Node *node = (DOM_Node *) element->GetESElement())
node->RemoveFromParent(origining_runtime);
else
element->DOMRemoveFromParent(this_node->GetEnvironment());
else
{
buffer->Clear();
HTML_Element *current = element, *next_sibling = element->SucActual();
while (next_sibling && next_sibling->IsText() && !next_sibling->GetIsCDATA())
{
CALL_FAILED_IF_ERROR(current->DOMGetContents(this_node->GetEnvironment(), buffer));
current = next_sibling;
next_sibling = current->SucActual();
}
if (current != element)
{
next = current->NextSiblingActual();
CALL_FAILED_IF_ERROR(current->DOMGetContents(this_node->GetEnvironment(), buffer));
CALL_FAILED_IF_ERROR(element->SetText(buffer->GetStorage(), buffer->Length()));
HTML_Element *remove = element->SucActual();
while (remove != next_sibling)
{
HTML_Element *next = remove->SucActual();
if (DOM_Node *node = (DOM_Node *) remove->GetESElement())
node->RemoveFromParent(origining_runtime);
else
remove->DOMRemoveFromParent(this_node->GetEnvironment());
remove = next;
}
}
}
element = next;
}
return ES_FAILED;
#endif // DOM2_MUTATION_EVENTS
}
/* static */ int
DOM_Node::isSupported(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_NODE);
return DOM_DOMImplementation::accessFeature(NULL, argv, argc, return_value, origining_runtime, 0);
}
/* static */ int
DOM_Node::hasAttributes(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(this_node, DOM_TYPE_NODE, DOM_Node);
BOOL has_attributes;
if (this_node->GetNodeType() == ELEMENT_NODE)
has_attributes = this_node->GetThisElement()->DOMGetAttributeCount() > 0;
else
has_attributes = FALSE;
DOMSetBoolean(return_value, has_attributes);
return ES_VALUE;
}
/* static */ int
DOM_Node::isSameNode(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("o");
DOM_ARGUMENT_OBJECT(other, 0, DOM_TYPE_NODE, DOM_Node);
DOMSetBoolean(return_value, node == other);
return ES_VALUE;
}
/* static */ int
DOM_Node::isEqualNode(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("O");
DOM_ARGUMENT_OBJECT(other, 0, DOM_TYPE_NODE, DOM_Node);
if (other && !other->OriginCheck(origining_runtime))
return ES_EXCEPT_SECURITY;
BOOL are_equal;
if (!other || other == node)
// Catches null argument or self.
are_equal = other == node;
else
{
// Document nodes don't have a this_element, so need to retrieve the placeholder instead.
HTML_Element *left = node->GetThisElement();
if (!left)
left = node->GetPlaceholderElement();
HTML_Element *right = other->GetThisElement();
if (!right)
right = other->GetPlaceholderElement();
if (left && right)
{
BOOL case_sensitive = (node->GetHLDocProfile() && node->GetHLDocProfile()->IsXml()) ||
(other->GetHLDocProfile() && other->GetHLDocProfile()->IsXml()) ||
(node->GetOwnerDocument() && node->GetOwnerDocument()->IsXML()) ||
(other->GetOwnerDocument() && other->GetOwnerDocument()->IsXML());
OP_BOOLEAN status = HTML_Element::DOMAreEqualNodes(left, node->GetHLDocProfile(), right, other->GetHLDocProfile(), case_sensitive);
if (status == OpStatus::ERR_NO_MEMORY)
return ES_NO_MEMORY;
are_equal = status == OpBoolean::IS_TRUE;
}
else
{
OP_ASSERT(!"Can this ever happen?");
are_equal = FALSE;
}
}
DOMSetBoolean(return_value, are_equal);
return ES_VALUE;
}
/* static */ int
DOM_Node::dispatchEvent(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_OBJECT);
if (argc >= 0)
{
DOM_CHECK_ARGUMENTS("o");
DOM_ARGUMENT_OBJECT(event, 0, DOM_TYPE_EVENT, DOM_Event);
if (!this_object->OriginCheck(origining_runtime))
return ES_EXCEPT_SECURITY;
if (event->GetKnownType() == DOM_EVENT_NONE)
return DOM_CALL_EVENTEXCEPTION(UNSPECIFIED_EVENT_TYPE_ERR);
if (event->GetThread())
return DOM_CALL_EVENTEXCEPTION(DISPATCH_REQUEST_ERR);
#ifdef DRAG_SUPPORT
DOM_EventType type = event->GetKnownType();
if (event->IsA(DOM_TYPE_DRAGEVENT) && (type == ONDRAGENTER || type == ONDRAGOVER || type == ONDRAGLEAVE || type == ONDROP))
{
DOM_DragEvent *drag_event = static_cast<DOM_DragEvent*>(event);
OpDragObject *data_store = drag_event->GetDataStore();
if (data_store)
{
URL origin_url = origining_runtime->GetOriginURL();
// Do not allow to send the synthetic events to the disallowed target origin.
if (!DragDropManager::IsURLAllowed(data_store, origin_url))
return ES_FAILED;
}
}
#endif // DRAG_SUPPORT
DOM_EnvironmentImpl *environment = this_object->GetEnvironment();
#ifdef USER_JAVASCRIPT
if (this_object->IsA(DOM_TYPE_OPERA))
{
DOM_UserJSManager *user_js_manager = origining_runtime->GetEnvironment()->GetUserJSManager();
if (!user_js_manager || !user_js_manager->GetIsActive(origining_runtime))
return ES_FAILED;
}
#endif // USER_JAVASCRIPT
CALL_FAILED_IF_ERROR(this_object->CreateEventTarget());
// Checkboxes are checked before the click event is dispatched.
if (event->GetKnownType() == ONCLICK)
CALL_FAILED_IF_ERROR(DOM_HTMLElement::BeforeClick(this_object));
ES_Thread *interrupt_thread = GetCurrentThread(origining_runtime);
event->SetTarget(this_object);
event->SetSynthetic();
OP_BOOLEAN result = environment->SendEvent(event, interrupt_thread);
if (OpStatus::IsMemoryError(result))
return ES_NO_MEMORY;
else if (result == OpBoolean::IS_TRUE)
{
DOMSetObject(return_value, event);
return ES_SUSPEND | ES_RESTART;
}
else
{
event->SetTarget(NULL);
return ES_FAILED;
}
}
else
{
DOM_Event *event = DOM_VALUE2OBJECT(*return_value, DOM_Event);
DOMSetBoolean(return_value, !event->GetPreventDefault());
return ES_VALUE;
}
}
/* static */ int
DOM_Node::getFeature(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
int result = DOM_DOMImplementation::accessFeature(NULL, argv, argc, return_value, origining_runtime, 0);
if (result == ES_VALUE && return_value->value.boolean)
DOMSetObject(return_value, node);
else
DOMSetNull(return_value);
return result;
}
#define DOCUMENT_POSITION_DISCONNECTED 0x1
#define DOCUMENT_POSITION_PRECEDING 0x2
#define DOCUMENT_POSITION_FOLLOWING 0x4
#define DOCUMENT_POSITION_CONTAINS 0x8
#define DOCUMENT_POSITION_CONTAINED_BY 0x10
#define DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC 0x20
/**
* This method returns the parent node as needed by the compareDocumentNodePosition algorithm.
*/
static OP_STATUS GetNodeOrderParent(DOM_Node* node, DOM_Node*& out_root)
{
OP_ASSERT(node);
switch (node->GetNodeType())
{
case TEXT_NODE:
case CDATA_SECTION_NODE:
case COMMENT_NODE:
case DOCUMENT_TYPE_NODE:
case ELEMENT_NODE:
case PROCESSING_INSTRUCTION_NODE:
case ENTITY_REFERENCE_NODE:
return node->GetParentNode(out_root);
case ATTRIBUTE_NODE:
out_root = static_cast<DOM_Attr *>(node)->GetOwnerElement();
return OpStatus::OK;
case NOTATION_NODE:
case ENTITY_NODE:
return node->GetOwnerDocument()->GetDocumentType(out_root);
default:
OP_ASSERT(!"Not implemented");
case DOCUMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
break;
}
out_root = NULL;
return OpStatus::OK;
}
/**
* Returns the root and the depth of the node tree, counting only
* the nodes from the root to the node itself.
*
* A root node (or lonely node) is it's own root and has depth = 1
*/
static OP_STATUS GetNodeOrderRoot(DOM_Node* node, DOM_Node*& out_root, int& out_depth)
{
OP_ASSERT(node);
DOM_Node* next = node;
out_depth = 0;
do
{
OP_ASSERT(next);
node = next;
out_depth++;
RETURN_IF_ERROR(GetNodeOrderParent(node, next));
}
while (next);
OP_ASSERT(node);
out_root = node;
return OpStatus::OK;
}
static int GetNodeOrderStringCompare(const uni_char* ref_string, const uni_char* other_node_string)
{
if (ref_string)
{
// Let the namespace ones come after the namespace less ones
if (!other_node_string)
return -1;
return uni_strcmp(ref_string, other_node_string);
}
else if (other_node_string)
return 1;
// Same, same
return 0;
}
/* static */ int
DOM_Node::compareDocumentPosition(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(ref_node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("o");
DOM_ARGUMENT_OBJECT(other_node, 0, DOM_TYPE_NODE, DOM_Node);
// Same object?
// "If the two nodes being compared are the same node, then no flags are set on the return."
if (other_node == ref_node)
{
DOMSetNumber(return_value, 0);
return ES_VALUE;
}
// Same "tree"? Check by comparing roots
DOM_Node* other_node_root;
int other_node_depth;
CALL_FAILED_IF_ERROR(GetNodeOrderRoot(other_node, other_node_root, other_node_depth));
DOM_Node* ref_node_root;
int ref_node_depth;
CALL_FAILED_IF_ERROR(GetNodeOrderRoot(ref_node, ref_node_root, ref_node_depth));
if (other_node_root != ref_node_root)
{
// Different "subtrees". Compare pointers
int follow_flag = other_node_root < ref_node_root ? DOCUMENT_POSITION_FOLLOWING : DOCUMENT_POSITION_PRECEDING;
DOMSetNumber(return_value, follow_flag |
DOCUMENT_POSITION_DISCONNECTED |
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
return ES_VALUE;
}
// Find the common parent
int min_depth = MIN(other_node_depth, ref_node_depth);
int depth = other_node_depth;
DOM_Node* other_node_min_depth_parent = other_node;
while (depth > min_depth)
{
CALL_FAILED_IF_ERROR(GetNodeOrderParent(other_node_min_depth_parent, other_node_min_depth_parent));
depth--;
}
depth = ref_node_depth;
DOM_Node* ref_node_min_depth_parent = ref_node;
while (depth > min_depth)
{
CALL_FAILED_IF_ERROR(GetNodeOrderParent(ref_node_min_depth_parent, ref_node_min_depth_parent));
depth--;
}
// Two nodes at the same depth
DOM_Node* ref_node_parent = ref_node_min_depth_parent;
DOM_Node* ref_node_common_parent_child = ref_node_parent;
DOM_Node* other_node_parent = other_node_min_depth_parent;
DOM_Node* other_node_common_parent_child = other_node_min_depth_parent;
while (ref_node_parent != other_node_parent)
{
ref_node_common_parent_child = ref_node_parent;
other_node_common_parent_child = other_node_parent;
CALL_FAILED_IF_ERROR(GetNodeOrderParent(other_node_parent, other_node_parent));
CALL_FAILED_IF_ERROR(GetNodeOrderParent(ref_node_parent, ref_node_parent));
OP_ASSERT(other_node_parent);
OP_ASSERT(ref_node_parent);
}
DOM_Node* common_parent = other_node_parent;
OP_ASSERT(common_parent);
// Check if one contains the other
if (other_node == common_parent ||
ref_node == common_parent)
{
// Contained
// The container precedes the contained element
int following_flag = other_node == common_parent ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
int contained_flag = other_node == common_parent ? DOCUMENT_POSITION_CONTAINS : DOCUMENT_POSITION_CONTAINED_BY;
DOMSetNumber(return_value, following_flag | contained_flag);
return ES_VALUE;
}
// If we get here, then we have two nodes in the same tree, but in different parts of the tree.
// Compare the children to the common parent
HTML_Element* ref_node_elm_common_parent_child = ref_node_common_parent_child->GetThisElement();
HTML_Element* elm_common_parent_child = other_node_common_parent_child->GetThisElement();
if (ref_node_elm_common_parent_child && elm_common_parent_child &&
elm_common_parent_child->ParentActual() == ref_node_elm_common_parent_child->ParentActual())
{
OP_ASSERT(ref_node_elm_common_parent_child != elm_common_parent_child);
// See if elm_common_parent_child comes after ref_node_elm_common_parent_child
HTML_Element* suc = ref_node_elm_common_parent_child;
while (suc && suc != elm_common_parent_child)
{
suc = suc->SucActual();
}
if (suc)
{
// Found node after ref_node;
DOMSetNumber(return_value, DOCUMENT_POSITION_FOLLOWING);
}
else
{
// Didn't find node after ref_node so it must be before
DOMSetNumber(return_value, DOCUMENT_POSITION_PRECEDING);
}
return ES_VALUE;
}
// So one of the nodes isn't a child. A non-child comes before any child
if (ref_node_elm_common_parent_child || elm_common_parent_child)
{
if (!ref_node_elm_common_parent_child)
{
// ref_node isn't a child, so node must be a child and thus following ref_node
DOMSetNumber(return_value, DOCUMENT_POSITION_FOLLOWING);
}
else
{
// Or the other way around
DOMSetNumber(return_value, DOCUMENT_POSITION_PRECEDING);
}
return ES_VALUE;
}
// if both are non-children, then we compare nodeType
if (ref_node_common_parent_child->GetNodeType() != other_node_common_parent_child->GetNodeType())
{
// Different types
// "one determining node has a greater value of nodeType than the other,
// then the corresponding node precedes the other"
// So sorted in decreasing order
if (ref_node_common_parent_child->GetNodeType() > other_node_common_parent_child->GetNodeType())
{
DOMSetNumber(return_value, DOCUMENT_POSITION_FOLLOWING);
}
else
{
// Or the other way around
DOMSetNumber(return_value, DOCUMENT_POSITION_PRECEDING);
}
return ES_VALUE;
}
// Same nodeType but not children
// "then an implementation-dependent order between the
// determining nodes is returned. This order is stable"
if (ref_node_common_parent_child->GetNodeType() == ATTRIBUTE_NODE)
{
// Let's sort them by name
DOM_Attr* ref_attr = static_cast<DOM_Attr*>(ref_node_common_parent_child);
DOM_Attr* other_attr = static_cast<DOM_Attr*>(other_node_common_parent_child);
int order = GetNodeOrderStringCompare(ref_attr->GetNsUri(), other_attr->GetNsUri());
if (order == 0) // Same namespace, compare names
order = GetNodeOrderStringCompare(ref_attr->GetName(), other_attr->GetName());
OP_ASSERT(order != 0); // Or we have the same node which should have been caught earlier
if (order < 0)
DOMSetNumber(return_value, DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
else
DOMSetNumber(return_value, DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
return ES_VALUE;
}
// Not sure it's stable to compare DOM_Node pointers, but some fun must be left to the debugger (let it not be me!)
DOMSetNumber(return_value, (other_node < ref_node ? DOCUMENT_POSITION_FOLLOWING : DOCUMENT_POSITION_PRECEDING) |
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
return ES_VALUE;
// return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR);
}
int
DOM_Node::contains(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
// http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#dom-node-contains
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("O");
if (argv[0].type == VALUE_NULL || argv[0].type == VALUE_UNDEFINED)
DOMSetBoolean(return_value, FALSE);
else
{
DOM_ARGUMENT_OBJECT(child, 0, DOM_TYPE_NODE, DOM_Node);
DOMSetBoolean(return_value, node->IsAncestorOf(child));
}
return ES_VALUE;
}
/* static */ int
DOM_Node::accessEventListener(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_OBJECT);
if (!this_object->OriginCheck(origining_runtime))
return ES_EXCEPT_SECURITY;
DOM_EnvironmentImpl *environment = this_object->GetEnvironment();
DOM_CHECK_ARGUMENTS("sO|b");
if (argv[1].type != VALUE_OBJECT)
return ES_FAILED;
const uni_char *type = argv[0].value.string;
ES_Object *native_listener = argv[1].value.object;
BOOL useCapture = argc > 2 && argv[2].value.boolean;
#ifdef USER_JAVASCRIPT
if (this_object->IsA(DOM_TYPE_OPERA))
{
DOM_UserJSManager *user_js_manager = origining_runtime->GetEnvironment()->GetUserJSManager();
if (!user_js_manager || !user_js_manager->GetIsActive(origining_runtime))
return ES_FAILED;
}
#endif // USER_JAVASCRIPT
DOM_EventType known_type = DOM_Event::GetEventType(type, FALSE);
if (known_type == DOM_EVENT_NONE)
known_type = DOM_EVENT_CUSTOM;
CALL_FAILED_IF_ERROR(this_object->CreateEventTarget());
if (data == 0 || data == 2)
{
DOM_EventListener *listener = OP_NEW(DOM_EventListener, ());
#ifdef ECMASCRIPT_DEBUGGER
if (data == 0)
{
ES_Context *context = DOM_Object::GetCurrentThread(origining_runtime)->GetContext();
if (origining_runtime->IsContextDebugged(context))
{
ES_Runtime::CallerInformation call_info;
OP_STATUS status = ES_Runtime::GetCallerInformation(context, call_info);
if (OpStatus::IsSuccess(status))
listener->SetCallerInformation(call_info.script_guid, call_info.line_no);
}
}
#endif // ECMASCRIPT_DEBUGGER
if (!listener || OpStatus::IsMemoryError(listener->SetNative(environment, known_type, type, useCapture, FALSE, NULL, native_listener)))
{
OP_DELETE(listener);
return ES_NO_MEMORY;
}
DOM_EventTarget *event_target = this_object->GetEventTarget();
DOM_EventTarget::NativeIterator it = event_target->NativeListeners();
while (!it.AtEnd())
{
if (listener->CanOverride(const_cast<DOM_EventListener *>(it.Current())))
{
OP_DELETE(listener);
return ES_FAILED;
}
it.Next();
}
event_target->AddListener(listener);
}
else
{
DOM_EventListener listener;
CALL_FAILED_IF_ERROR(listener.SetNative(environment, known_type, type, useCapture, FALSE, NULL, native_listener));
this_object->GetEventTarget()->RemoveListener(&listener);
}
return ES_FAILED;
}
/* static */ int
DOM_Node::attachOrDetachEvent(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_CHECK_ARGUMENTS("so");
ES_Value new_argv[3];
new_argv[0] = argv[0];
new_argv[1] = argv[1];
DOMSetBoolean(&new_argv[2], FALSE);
if (new_argv[0].type == VALUE_STRING && uni_strni_eq(new_argv[0].value.string, "ON", 2))
new_argv[0].value.string += 2;
int result = DOM_Node::accessEventListener(this_object, new_argv, 3, return_value, origining_runtime, data);
if (data == 0 && result == ES_FAILED)
{
// attachEvent always returns true.
DOMSetBoolean(return_value, TRUE);
return ES_VALUE;
}
else
return result;
}
/* static */ int
DOM_Node::lookupNamespace(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
DOM_CHECK_ARGUMENTS("S");
const uni_char *argument = argv[0].type == VALUE_STRING ? argv[0].value.string : NULL;
HTML_Element *element = NULL;
switch (node->node_type)
{
case ATTRIBUTE_NODE:
if (DOM_Element *owner_element = ((DOM_Attr *) node)->GetOwnerElement())
element = owner_element->GetThisElement();
break;
case DOCUMENT_NODE:
if (DOM_Element *document_element = ((DOM_Document *) node)->GetRootElement())
element = document_element->GetThisElement();
break;
case ENTITY_NODE:
case DOCUMENT_TYPE_NODE:
case DOCUMENT_FRAGMENT_NODE:
case NOTATION_NODE:
break;
#ifdef DOM3_XPATH
case XPATH_NAMESPACE_NODE:
element = ((DOM_XPathNamespace *) node)->GetOwnerElement()->GetThisElement();
break;
#endif // DOM3_XPATH
default:
element = node->GetThisElement();
}
// 0, lookupPrefix(namespaceURI) : string
// 1, isDefaultNamespace(namespaceURI) : bool
// 2, lookupNamespaceURI(prefix) : string
if (!element)
if (data == 1)
DOMSetBoolean(return_value, FALSE);
else
DOMSetNull(return_value);
else if (data == 0)
{
const uni_char *prefix = element->DOMLookupNamespacePrefix(node->GetEnvironment(), argument);
if (prefix && *prefix)
DOMSetString(return_value, prefix);
else
DOMSetNull(return_value);
}
else
{
const uni_char *uri = element->DOMLookupNamespaceURI(node->GetEnvironment(), data == 1 ? NULL : argument);
if (data == 1)
// Both null, or both equal.
DOMSetBoolean(return_value, (!uri && (!argument || !*argument)) || (argument && uri && uni_str_eq(argument, uri)));
else if (uri)
DOMSetString(return_value, uri);
else
DOMSetNull(return_value);
}
return ES_VALUE;
}
#ifdef DOM3_XPATH
DOM_XPathResult_NodeList::DOM_XPathResult_NodeList(DOM_XPathResult *result)
: result(result)
{
}
/* virtual */ ES_GetState
DOM_XPathResult_NodeList::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_length)
{
DOMSetNumber(value, result->GetCount());
return GET_SUCCESS;
}
else
return GET_FAILED;
}
/* virtual */ ES_GetState
DOM_XPathResult_NodeList::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index >= 0 && (unsigned) property_index < result->GetCount())
{
DOMSetObject(value, result->GetNode(property_index));
return GET_SUCCESS;
}
else
return GET_FAILED;
}
/* virtual */ ES_PutState
DOM_XPathResult_NodeList::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
return property_name == OP_ATOM_length ? PUT_SUCCESS : PUT_FAILED;
}
/* virtual */ ES_PutState
DOM_XPathResult_NodeList::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
return PUT_SUCCESS;
}
/* virtual */ void
DOM_XPathResult_NodeList::GCTrace()
{
GCMark(result);
}
/* virtual */ ES_GetState
DOM_XPathResult_NodeList::GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime)
{
count = result->GetCount();
return GET_SUCCESS;
}
/* static */ int
DOM_XPathResult_NodeList::item(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT(nodelist, DOM_TYPE_XPATHRESULT_NODELIST, DOM_XPathResult_NodeList);
DOM_CHECK_ARGUMENTS("n");
double index = argv[0].value.number;
if (!op_isintegral(index) || index < 0. || index > (double) nodelist->result->GetCount())
DOMSetNull(return_value);
else
DOMSetObject(return_value, nodelist->result->GetNode(op_double2uint32(index)));
return ES_VALUE;
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_XPathResult_NodeList)
DOM_FUNCTIONS_FUNCTION(DOM_XPathResult_NodeList, DOM_XPathResult_NodeList::item, "item", "n")
DOM_FUNCTIONS_END(DOM_Node)
/* static */ int
DOM_Node::select(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_THIS_OBJECT(node, DOM_TYPE_NODE, DOM_Node);
DOM_Document *document;
if (node->IsA(DOM_TYPE_DOCUMENT))
document = (DOM_Document *) node;
else
document = node->GetOwnerDocument();
if (argc >= 0)
{
ES_Object *nsresolver = NULL;
if (argc == 1 || argc == 2 && (argv[1].type == VALUE_NULL || argv[1].type == VALUE_UNDEFINED))
{
DOM_CHECK_ARGUMENTS("s");
DOM_XPathNSResolver *xpathnsresolver;
DOM_Node *element;
if (node->IsA(DOM_TYPE_DOCUMENT))
element = ((DOM_Document *) node)->GetRootElement();
else
element = node;
if (element)
{
CALL_FAILED_IF_ERROR(DOM_XPathNSResolver::Make(xpathnsresolver, element));
nsresolver = *xpathnsresolver;
}
}
else if (argc == 2)
{
DOM_CHECK_ARGUMENTS("so");
nsresolver = argv[1].value.object;
}
else
return DOM_CALL_INTERNALEXCEPTION(WRONG_ARGUMENTS_ERR);
const uni_char *expression = argv[0].value.string;
/* Defined in xpathresult.cpp. */
extern double DOM_ExportXPathType(unsigned type);
ES_Value evalute_argv[5];
DOMSetString(&evalute_argv[0], expression);
DOMSetObject(&evalute_argv[1], node);
DOMSetObject(&evalute_argv[2], nsresolver);
DOMSetNumber(&evalute_argv[3], DOM_ExportXPathType(XPathExpression::Evaluate::NODESET_FLAG_ORDERED | (data == 0 ? XPathExpression::Evaluate::NODESET_SNAPSHOT : XPathExpression::Evaluate::NODESET_SINGLE)));
DOMSetNull(&evalute_argv[4]);
int result = DOM_XPathEvaluator::createExpressionOrEvaluate(document, evalute_argv, 5, return_value, origining_runtime, 1);
if (result != ES_VALUE)
return result;
}
else
{
int result = DOM_XPathEvaluator::createExpressionOrEvaluate(document, NULL, -1, return_value, origining_runtime, 1);
if (result != ES_VALUE)
return result;
}
DOM_HOSTOBJECT_SAFE(result, return_value->value.object, DOM_TYPE_XPATHRESULT, DOM_XPathResult);
if (!result)
return ES_FAILED;
else if (data == 0)
{
DOM_XPathResult_NodeList *nodelist;
CALL_FAILED_IF_ERROR(DOMSetObjectRuntime(nodelist = OP_NEW(DOM_XPathResult_NodeList, (result)), origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::XPATHRESULT_NODELIST_PROTOTYPE), "NodeList"));
DOMSetObject(return_value, nodelist);
}
else if (result->GetCount() != 0)
DOMSetObject(return_value, result->GetNode(0));
else
DOMSetNull(return_value);
return ES_VALUE;
}
#endif // DOM3_XPATH
#ifdef USER_JAVASCRIPT
ES_GetState
DOM_Node::GetCssContents(DOM_Node *node, ES_Value *value, DOM_Runtime *origining_runtime, TempBuffer* buffer)
{
#ifdef _DEBUG
// This function is only called from UserJSEvent.cssText, so the
// user js manager is ensured to be active.
DOM_UserJSManager *user_js_manager = origining_runtime->GetEnvironment()->GetUserJSManager();
OP_ASSERT(user_js_manager);
OP_ASSERT(user_js_manager->GetIsActive(origining_runtime));
#endif
if (!value)
return GET_SUCCESS;
HTML_Element *he = node->GetThisElement();
OP_ASSERT(he->IsLinkElement() || he->IsStyleElement());
if (he->IsLinkElement())
GET_FAILED_IF_ERROR(he->DOMGetDataSrcContents(node->GetEnvironment(), buffer));
else
GET_FAILED_IF_ERROR(he->DOMGetContents(node->GetEnvironment(), buffer));
DOM_Object::DOMSetString(value, buffer);
return GET_SUCCESS;
}
ES_PutState
DOM_Node::SetCssContents(DOM_Node *node, ES_Value *value, DOM_Runtime *origining_runtime)
{
#ifdef _DEBUG
// This function is only called from UserJSEvent.cssText, so the
// user js manager is ensured to be active.
DOM_UserJSManager *user_js_manager = origining_runtime->GetEnvironment()->GetUserJSManager();
OP_ASSERT(user_js_manager);
OP_ASSERT(user_js_manager->GetIsActive(origining_runtime));
#endif
HTML_Element *he = node->GetThisElement();
OP_ASSERT(he->IsLinkElement() || he->IsStyleElement());
if (value->type != VALUE_STRING)
return PUT_NEEDS_STRING;
if (he->Type() == HE_PROCINST)
{
DataSrc* src_head = he->GetDataSrc();
if (src_head)
{
URL src_origin = src_head->GetOrigin();
src_head->DeleteAll();
PUT_FAILED_IF_ERROR(src_head->AddSrc(value->value.string, uni_strlen(value->value.string), src_origin));
}
}
else if (he->IsStyleElement())
PUT_FAILED_IF_ERROR(node->SetTextContent(value, origining_runtime, NULL));
else // Link
{
DOM_EnvironmentImpl::CurrentState state(node->GetEnvironment(), origining_runtime);
PUT_FAILED_IF_ERROR(he->DOMSetContents(node->GetEnvironment(), value->value.string));
}
return PUT_SUCCESS;
};
#endif // USER_JAVASCRIPT
/* static */ void
DOM_Node::ConstructNodeObjectL(ES_Object *object, DOM_Runtime *runtime)
{
DOM_Object::PutNumericConstantL(object, "ELEMENT_NODE", ELEMENT_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "ATTRIBUTE_NODE", ATTRIBUTE_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "TEXT_NODE", TEXT_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "CDATA_SECTION_NODE", CDATA_SECTION_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "ENTITY_REFERENCE_NODE", ENTITY_REFERENCE_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "ENTITY_NODE", ENTITY_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "PROCESSING_INSTRUCTION_NODE", PROCESSING_INSTRUCTION_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "COMMENT_NODE", COMMENT_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_NODE", DOCUMENT_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_TYPE_NODE", DOCUMENT_TYPE_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_FRAGMENT_NODE", DOCUMENT_FRAGMENT_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "NOTATION_NODE", NOTATION_NODE, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_POSITION_DISCONNECTED", DOCUMENT_POSITION_DISCONNECTED, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_POSITION_PRECEDING", DOCUMENT_POSITION_PRECEDING, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_POSITION_FOLLOWING", DOCUMENT_POSITION_FOLLOWING, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_POSITION_CONTAINS", DOCUMENT_POSITION_CONTAINS, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_POSITION_CONTAINED_BY", DOCUMENT_POSITION_CONTAINED_BY, runtime);
DOM_Object::PutNumericConstantL(object, "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, runtime);
LEAVE_IF_ERROR(HideMSIEEventAPI(object, runtime));
}
/* static */ OP_STATUS
DOM_Node::HideMSIEEventAPI(ES_Object *object, DOM_Runtime *runtime)
{
/* Hide these MSIEisms to throw off sniffing scripts; a step towards
retiring them completely. */
ES_Value hidden_value;
OP_BOOLEAN result;
RETURN_IF_ERROR(result = runtime->GetName(object, UNI_L("attachEvent"), &hidden_value));
if (result == OpBoolean::IS_TRUE && hidden_value.type == VALUE_OBJECT)
ES_Runtime::MarkObjectAsHidden(hidden_value.value.object);
RETURN_IF_ERROR(result = runtime->GetName(object, UNI_L("detachEvent"), &hidden_value));
if (result == OpBoolean::IS_TRUE && hidden_value.type == VALUE_OBJECT)
ES_Runtime::MarkObjectAsHidden(hidden_value.value.object);
return OpStatus::OK;
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_Node)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::dispatchEvent, "dispatchEvent", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::insertBefore, "insertBefore", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::replaceChild, "replaceChild", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::removeChild, "removeChild", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::appendChild, "appendChild", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::hasChildNodes, "hasChildNodes", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::cloneNode, "cloneNode", "b-")
DOM_FUNCTIONS_FUNCTIONX(DOM_Node, DOM_Node::normalize, "normalize", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::isSupported, "isSupported", "sS-")
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::hasAttributes, "hasAttributes", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::isSameNode, "isSameNode", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::isEqualNode, "isEqualNode", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::getFeature, "getFeature", "s-")
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::compareDocumentPosition, "compareDocumentPosition", 0)
DOM_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node::contains, "contains", 0)
DOM_FUNCTIONS_END(DOM_Node)
DOM_FUNCTIONS_WITH_DATA_START(DOM_Node)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::accessEventListener, 0, "addEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::accessEventListener, 1, "removeEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::attachOrDetachEvent, 0, "attachEvent", "s-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::attachOrDetachEvent, 1, "detachEvent", "s-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::lookupNamespace, 0, "lookupPrefix", "S-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::lookupNamespace, 1, "isDefaultNamespace", "S-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::lookupNamespace, 2, "lookupNamespaceURI", "S-")
#ifdef DOM3_XPATH
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::select, 0, "selectNodes", "s-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_Node, DOM_Node::select, 1, "selectSingleNode", "s-")
#endif // DOM3_XPATH
DOM_FUNCTIONS_WITH_DATA_END(DOM_Node)
DOM_LIBRARY_FUNCTIONS_START(DOM_Node)
DOM_LIBRARY_FUNCTIONS_FUNCTION(DOM_Node, DOM_Node_normalize, "normalize")
DOM_LIBRARY_FUNCTIONS_END(DOM_Node)
|
#ifndef _CONTAINER_H
#define _CONTAINER_H
#include <iostream>
using namespace std;
template <typename T>
class container { // class template
public:
explicit container (const T &arg);
T increase ();
private:
T element;
};
/**
* The idea of C++ class template specialization is similar to
* function template overloading. It fixes the template code for
* certain data types that need to be handled differently than most
* data. For example, string or char data is not handled identically
* to true numeric datatypes, so a specialization of an ‘add’ template
* for strings or char data may need to work differently than it would
* for adding integers or numbers. After the template is specialized,
* all the member functions should be declared and defined for the
* specific data type.
*
* When a program instantiates a template with a given set of template
* arguments the compiler generates a new definition based on those
* template arguments. To override this, instead specify the
* definition the compiler uses for a given set of template
* arguments. This is called explicit specialization. A program can
* explicitly specialize any of the following:
* • Function or class template
* • Member function of a class template
* • Static data member of a class template
* • Member class of a class template
* • Member function template of a class template
* • Member class template of a class template
*
* The template<> prefix indicates that the following template
* declaration takes no template parameters. The declaration_name is
* the name of a previously declared template. Note that an explicit
* specialization can be forward-declared so the declaration_body is
* optional, at least until the specialization is referenced.
*/
//class template specialization:
template <>
class container <char *> {
public:
explicit container (char *arg): element (arg) {}
char *uppercase (); // note how we've added a totally new method!
private:
char *element;
};
/**
* Templates declared inside classes are called member templates, and
* they can be either member function templates or member class
* templates (nested classes).
*
* Member function (method) templates are template functions that are members
* of any class or templatize class and can't be virtual.
* Notice that member function templates (a templatize method of a class) are
* not the same as template members function (a normal method of template class).
*
* A template member is a member declared inside a class that templatize.
*/
template <typename T>
struct class_A {
explicit class_A(T *p): p_(p) {
cout << typeid(p).name() << endl;
}
// a template (data) member
T *p_;
// a template member function (can be virtual if necessary)
// a member function (method) that works on the template of a template class
void f(T *t) const {
// print the "name" of the types.
cout << typeid(t).name() << endl;
}
};
/**
* A "member function template" or (method) that is a template
* of a non template class can't be virtual
* parameters declared inside any class.
*
* Here's an example of a member function template in a non-template
* class.
*/
struct class_B {
// member function template (can't be virtual)
// any member function that declare as template
template <typename T>
void mf(T *t) {
// print the "name" of the type.
cout << typeid(t).name() << endl;
}
};
/**
* Here's an example of declaring a member function(method) template in a
* template class.
*/
template <typename T>
struct class_C {
// member function template (can't be virtual)
template <typename U>
void mf(U u, T *t) {
// print the "name" of the types.
cout << typeid(u).name() << endl;
cout << typeid(t).name() << endl;
}
// template member function (can be virtual if necessary)
void f(T *t) const {
// print the "name" of the types.
cout << typeid(t).name() << endl;
}
};
/**
* Define class Foo that defines operator++().
*/
class Foo {
public:
explicit Foo(int i): i_(i) {}
Foo operator++() {
cout << "Foo::operator++" << endl;
return Foo(++i_);
}
explicit operator int() const { return i_; }
private:
int i_;
};
ostream &operator<<(ostream &os, const Foo &foo) {
return os << int(foo);
}
/**
* Specialize container with a Foo.
*/
template<>
class container<Foo> {
public:
explicit container (Foo arg): element (arg) {}
Foo increase() {
cout << "container<Foo>::increase()" << endl;
return ++element;
}
private:
Foo element;
};
#include "container.cpp"
#endif /* _CONTAINER_H */
|
// AccelerationReader.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "AccelerationReader.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAccelerationReaderApp
BEGIN_MESSAGE_MAP(CAccelerationReaderApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, &CAccelerationReaderApp::OnAppAbout)
END_MESSAGE_MAP()
// CAccelerationReaderApp 构造
CAccelerationReaderApp::CAccelerationReaderApp()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CAccelerationReaderApp 对象
CAccelerationReaderApp theApp;
// CAccelerationReaderApp 初始化
BOOL CAccelerationReaderApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
// 若要创建主窗口,此代码将创建新的框架窗口
// 对象,然后将其设置为应用程序的主窗口对象
CMainFrame* pFrame = new CMainFrame;
if (!pFrame)
return FALSE;
m_pMainWnd = pFrame;
// 创建并加载框架及其资源
pFrame->LoadFrame(IDR_MAINFRAME,
WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL,
NULL);
// 唯一的一个窗口已初始化,因此显示它并对其进行更新
pFrame->ShowWindow(SW_SHOWMAXIMIZED);
pFrame->UpdateWindow();
// 仅当具有后缀时才调用 DragAcceptFiles
// 在 SDI 应用程序中,这应在 ProcessShellCommand 之后发生
return TRUE;
}
// CAccelerationReaderApp 消息处理程序
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// 用于运行对话框的应用程序命令
void CAccelerationReaderApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
// CAccelerationReaderApp 消息处理程序
|
// Data type used in grid
typedef int DataType;
#include <iostream>
#include <ostream>
struct STiming {
float method1;
float method2;
};
void generateInput(std::ostream &out, size_t gridSize, size_t kernelSize);
// Forward declarations
void readGrid(
DataType* hostGrid,
std::istream &input,
size_t rows, size_t cols,
size_t haloRows = 0,
size_t haloCols = 0);
void readGridCustomBorders(
DataType* hostGrid,
std::istream &input,
size_t rows, size_t cols,
size_t startX, size_t endX,
size_t startY, size_t endY);
void printGrid(
DataType* hostGrid,
std::ostream &output,
size_t rows, size_t cols,
size_t haloRows = 0,
size_t haloCols = 0);
void printGridCustomBorders(
DataType* hostGrid,
std::ostream &output,
size_t cols,
size_t startX, size_t endX,
size_t startY, size_t endY);
size_t ceilRound(size_t size, size_t blockSize);
bool areGridsEqual(DataType *grid1, DataType * grid2, size_t rows, size_t cols = 0);
|
//===========================================================================
//! @file gpu_shader.cpp
//! @brief シェーダー
//===========================================================================
namespace gpu::detail {
// 仮
static constexpr const char* g_filePath = "../../Application/asset/shader/";
//! カスタムインクルードクラス
class D3DInclude : public ID3DInclude
{
public:
HRESULT __stdcall Open([[maybe_unused]] D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, [[maybe_unused]] LPCVOID pParentData, LPCVOID* ppData, UINT* pBytes) override
{
std::string path = g_filePath;
path += pFileName;
std::ifstream file(path);
if(!file.is_open())
return S_OK;
_string = std::string{
std::istreambuf_iterator<char>{ file },
std::istreambuf_iterator<char>{}
};
*ppData = _string.c_str();
*pBytes = static_cast<UINT>(_string.size());
return S_OK;
}
HRESULT __stdcall Close([[maybe_unused]] LPCVOID pData) override
{
return S_OK;
}
private:
std::string _string;
};
} // namespace gpu::detail
namespace gpu {
//------------------------------------------------------------------------------------------------
//! HLSLシェーダーをコンパイル
//------------------------------------------------------------------------------------------------
ID3DBlob* compileShaderFromFile(const char* fileName, const char* functionName, const char* shaderModel)
{
const std::string addPath = detail::g_filePath;
const std::string filePath = addPath + fileName;
//---------------------------------------------------------------------------
// HLSLシェーダーソースコードをメモリに読み込み
//---------------------------------------------------------------------------
std::vector<char> shaderSource;
FILE* fp;
if(fopen_s(&fp, filePath.c_str(), "rb") != 0) {
MessageBox(NULL, "シェーダーの読み込みに失敗", nullptr, MB_OK);
return nullptr;
}
//---- ファイルサイズを取得
fseek(fp, 0, SEEK_END);
size_t fileSize = ftell(fp); // ファイルサイズ
fseek(fp, 0, SEEK_SET);
//---- ワーク領域を確保して読み込み
shaderSource.resize(fileSize); // ワーク領域の確保
if(shaderSource.empty()) {
fclose(fp);
return false;
}
fread(&shaderSource[0], fileSize, 1, fp); // 読み込み
fclose(fp);
//----------------------------------------------------------------------------------
// シェーダーコンパイラーのオプション設定
//----------------------------------------------------------------------------------
u32 flags = D3DCOMPILE_ENABLE_STRICTNESS;
//---- 行列の列優先・行優先
flags |= D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR; // 列優先(転置)
// flags |= D3DCOMPILE_PACK_MATRIX_ROW_MAJOR; // 行優先
//---- 分岐コードの生成制御(if, for文など)
// flags |= D3DCOMPILE_AVOID_FLOW_CONTROL; // 分岐しないフラットなコードを生成
flags |= D3DCOMPILE_PREFER_FLOW_CONTROL; // 動的分岐を含むコードを生成
//---- 最適化レべル(シェーダー性能とコンパイル時間に影響)
// flags |= D3DCOMPILE_OPTIMIZATION_LEVEL0; // 最適化なし
// flags |= D3DCOMPILE_OPTIMIZATION_LEVEL1; // ↑
// flags |= D3DCOMPILE_OPTIMIZATION_LEVEL2; // ↓
flags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; // 最大限の最適化
#if 0
//---- シェーダーにデバッグ情報を付加
// ※注意 Release版には含めないこと
flags |= D3DCOMPILE_DEBUG;
#endif
//----------------------------------------------------------------------------------
// HLSLソースコード内のdefineマクロ定義
//----------------------------------------------------------------------------------
std::array<D3D_SHADER_MACRO, 2> defineMacros = { { { "__WINDOWS__", "1" },
//---- 終端にnullptr指定しておく
{ nullptr, nullptr } } };
//----------------------------------------------------------------------------------
// HLSLシェーダーをコンパイル
//----------------------------------------------------------------------------------
HRESULT hr;
ID3DBlob* shaderBlob; // シェーダーバイナリ
detail::D3DInclude myInclude; // 使用しない場合は D3D_COMPILE_STANDARD_FILE_INCLUDE を設定すること
com_ptr<ID3DBlob> errorBlob; // エラーメッセージ出力用
hr = D3DCompile(&shaderSource[0], // [in] シェーダーソースコード
shaderSource.size(), // [in] シェーダーソースコードのサイズ
functionName, // [in] シェーダー名(エラーメッセージ内に出力される名前。任意)
&defineMacros[0], // [in] 外部から与えるプリプロセッサマクロ#define
&myInclude, // [in] インクルード#includeのカスタムハンドラ
functionName, // [in] 実行開始点の関数名
shaderModel, // [in] シェーダーモデル名 ("vs_4_0", "ps_4_0", "cs_5_0" etc...)
flags, // [in] オプションフラグ
0, // [in] エフェクトオプションフラグ(常に0)
&shaderBlob, // [out] コンパイルされたシェーダーバイナリ
&errorBlob); // [out] コンパイルエラーメッセージ
//----------------------------------------------------------------------------------
// コンパイルエラーの場合はエラーメッセージの内容を出力
//----------------------------------------------------------------------------------
if(errorBlob) {
// VisualStudio 「出力」ウィンドウに表示
OutputDebugString((const char*)errorBlob->GetBufferPointer());
// ポップアップでも表示
MessageBox(nullptr, (const char*)errorBlob->GetBufferPointer(), filePath.c_str(), MB_OK);
}
return shaderBlob;
}
//---------------------------------------------------------------------------
//! ShaderBase
//! シェーダーバイナリのアドレスを取得
//---------------------------------------------------------------------------
const void* ShaderBase::getShaderBinary() const
{
return shaderBinary_->GetBufferPointer();
}
//---------------------------------------------------------------------------
//! ShaderBase
//! シェーダーバイナリのサイズを取得
//---------------------------------------------------------------------------
size_t ShaderBase::getShaderBinarySize() const
{
return shaderBinary_->GetBufferSize();
}
//---------------------------------------------------------------------------
//! ShaderVs
//! コンストラクタ
//---------------------------------------------------------------------------
ShaderVs::ShaderVs(ID3DBlob* shaderBinary)
{
// シェーダーの作成
device::D3DDevice()->CreateVertexShader(shaderBinary->GetBufferPointer(),
shaderBinary->GetBufferSize(),
nullptr,
&shader_);
shaderBinary_ = shaderBinary;
}
//---------------------------------------------------------------------------
//! ShaderVs
//! D3Dシェーダーを取得
//---------------------------------------------------------------------------
ID3D11VertexShader* ShaderVs::get() const
{
return shader_.Get();
}
//---------------------------------------------------------------------------
//! ShaderVs
//! シェーダーの作成
//---------------------------------------------------------------------------
gpu::ShaderVs* ShaderVs::create(const std::string& fileName)
{
auto shaderBinary = compileShaderFromFile((fileName + ".fx").c_str(), "main", "vs_5_0"); // 頂点シェーダー
if(shaderBinary == nullptr) {
return nullptr;
}
return new gpu::ShaderVs(shaderBinary);
}
//---------------------------------------------------------------------------
//! ShaderPs
//! コンストラクタ
//---------------------------------------------------------------------------
ShaderPs::ShaderPs(ID3DBlob* shaderBinary)
{
device::D3DDevice()->CreatePixelShader(shaderBinary->GetBufferPointer(),
shaderBinary->GetBufferSize(),
nullptr,
&shader_);
shaderBinary_ = shaderBinary;
}
//---------------------------------------------------------------------------
//! ShaderPs
//! D3Dシェーダーを取得
//---------------------------------------------------------------------------
ID3D11PixelShader* ShaderPs::get() const
{
return shader_.Get();
}
//---------------------------------------------------------------------------
//! ShaderPs
//! シェーダーの作成
//---------------------------------------------------------------------------
gpu::ShaderPs* ShaderPs::create(const std::string& fileName)
{
auto shaderBinary = compileShaderFromFile((fileName + ".fx").c_str(), "main", "ps_5_0"); // ピクセルシェーダー
if(shaderBinary == nullptr) {
return nullptr;
}
return new gpu::ShaderPs(shaderBinary);
}
//---------------------------------------------------------------------------
//! ShaderGs
//! コンストラクタ
//---------------------------------------------------------------------------
ShaderGs::ShaderGs(ID3DBlob* shaderBinary)
{
device::D3DDevice()->CreateGeometryShader(shaderBinary->GetBufferPointer(),
shaderBinary->GetBufferSize(),
nullptr,
&shader_);
shaderBinary_ = shaderBinary;
}
//---------------------------------------------------------------------------
//! ShaderGs
//! D3Dシェーダーを取得
//---------------------------------------------------------------------------
ID3D11GeometryShader* ShaderGs::get() const
{
return shader_.Get();
}
//---------------------------------------------------------------------------
//! ShaderGs
//! シェーダー作成
//---------------------------------------------------------------------------
gpu::ShaderGs* ShaderGs::create(const std::string& fileName)
{
auto shaderBinary = compileShaderFromFile((fileName + ".fx").c_str(), "main", "gs_5_0"); // ピクセルシェーダー
if(shaderBinary == nullptr) {
return nullptr;
}
return new gpu::ShaderGs(shaderBinary);
}
//---------------------------------------------------------------------------
//! ShaderHs
//! コンストラクタ
//---------------------------------------------------------------------------
ShaderHs::ShaderHs(ID3DBlob* shaderBinary)
{
device::D3DDevice()->CreateHullShader(shaderBinary->GetBufferPointer(),
shaderBinary->GetBufferSize(),
nullptr,
&shader_);
shaderBinary_ = shaderBinary;
}
//---------------------------------------------------------------------------
//! ShaderDs
//! D3Dシェーダーを取得
//---------------------------------------------------------------------------
ID3D11HullShader* ShaderHs::get() const
{
return shader_.Get();
}
//---------------------------------------------------------------------------
//! ShaderHs
//! シェーダーの作成
//---------------------------------------------------------------------------
gpu::ShaderHs* ShaderHs::create(const std::string& fileName)
{
auto shaderBinary = compileShaderFromFile((fileName + ".fx").c_str(), "main", "hs_5_0"); // ピクセルシェーダー
if(shaderBinary == nullptr) {
return nullptr;
}
return new gpu::ShaderHs(shaderBinary);
}
//---------------------------------------------------------------------------
//! ShaderDs
//! コンストラクタ
//---------------------------------------------------------------------------
ShaderDs::ShaderDs(ID3DBlob* shaderBinary)
{
device::D3DDevice()->CreateDomainShader(shaderBinary->GetBufferPointer(),
shaderBinary->GetBufferSize(),
nullptr,
&shader_);
shaderBinary_ = shaderBinary;
}
//---------------------------------------------------------------------------
//! ShaderDs
//! D3Dシェーダーを取得
//---------------------------------------------------------------------------
ID3D11DomainShader* ShaderDs::get() const
{
return shader_.Get();
}
//---------------------------------------------------------------------------
//! ShaderDs
//! シェーダー作成
//---------------------------------------------------------------------------
gpu::ShaderDs* ShaderDs::create(const std::string& fileName)
{
auto shaderBinary = compileShaderFromFile((fileName + ".fx").c_str(), "main", "ds_5_0"); // ピクセルシェーダー
if(shaderBinary == nullptr) {
return nullptr;
}
return new gpu::ShaderDs(shaderBinary);
}
} // namespace gpu
|
/*
Date: 15-06-20
Name : Aman Jain
*/
#include<bits/stdc++.h>
using namespace std;
bool odd_cycle=false;
void dfs(vector<int> V[], int start, int parent, int color,int visited[]){
visited[start]=color;
// Color : // 0: Not visited // 1: Visited and color 1 // 2: Visited and color 2
vector<int> :: iterator itr;
for(itr= V[start].begin() ; itr!=V[start].end() ;++itr){
if(visited[*itr]==0){
dfs(V,*itr,start,3-color,visited);
}else if(visited[*itr]==color && *itr!=parent){
odd_cycle=true;
}
}
}
int main(){
int verti,edges;
cin>>verti>>edges;
vector<int> V[2*verti];
for(int i=0; i<edges; i++){
int x,y;
cin>>x>>y;
V[x].push_back(y);
V[y].push_back(x);
}
int visited[verti]={0};
dfs(V,1,-1,1,visited);
if(odd_cycle)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
|
// Created on: 1997-02-21
// Created by: Alexander BRIVIN
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _VrmlConverter_WFShape_HeaderFile
#define _VrmlConverter_WFShape_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_OStream.hxx>
class TopoDS_Shape;
class VrmlConverter_Drawer;
//! WFShape - computes the wireframe presentation of
//! compound set of faces, edges and vertices by
//! displaying a given number of U and/or V isoparametric
//! curves converts this one into VRML objects and writes (adds)
//! them into anOStream.
//! All requested properties of the representation are
//! specify in aDrawer.
//! This kind of the presentation is converted into
//! IndexedLineSet and PointSet ( VRML ).
class VrmlConverter_WFShape
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT static void Add (Standard_OStream& anOStream, const TopoDS_Shape& aShape, const Handle(VrmlConverter_Drawer)& aDrawer);
protected:
private:
};
#endif // _VrmlConverter_WFShape_HeaderFile
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
class A{
public:
int f();
int f(int x=0);
int f(int x=0,int y=0)
{
cout << "A" << endl;
}
int f(double x);
int f(double x=0.0,double y=0.0)
{
cout << "B" << endl;
}
};
int main()
{
A a;
a.f(1,1);
a.f(1,1.0);
return 0;
}
|
#include "stdafx.h"
#include "Gamepad.h"
// Link the 'Xinput' library - Important!
#pragma comment(lib, "Xinput.lib")
Gamepad::Gamepad(int a_iIndex)
{
m_State = GetState();
m_iGamepadIndex = a_iIndex - 1;
}
void Gamepad::Update()
{
m_State = GetState();
}
bool Gamepad::LStick_InDeadzone()
{
short sX = m_State.Gamepad.sThumbLX;
short sY = m_State.Gamepad.sThumbLY;
// X axis is outside of deadzone
if (sX > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ||
sX < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
return false;
// Y axis is outside of deadzone
if (sY > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE ||
sY < -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
return false;
// One (or both axes) axis is inside of deadzone
return true;
}
float Gamepad::LeftStick_X()
{
// Obtain X axis of left stick
short sX = m_State.Gamepad.sThumbLX;
// Return axis value, converted to a float
return (static_cast<float>(sX) / 32768.0f);
}
float Gamepad::LeftStick_Y()
{
short sY = m_State.Gamepad.sThumbLY;
// Return axis value, converted to a float
return (static_cast<float>(sY) / 32768.0f);
}
float Gamepad::LeftTrigger()
{
// Obtain value of left trigger
BYTE Trigger = m_State.Gamepad.bLeftTrigger;
if (Trigger > XINPUT_GAMEPAD_TRIGGER_THRESHOLD)
return Trigger / 255.0f;
return 0.0f; // Trigger was not pressed
}
XINPUT_STATE Gamepad::GetState()
{
// Temporary XINPUT_STATE to return
XINPUT_STATE GamepadState;
ZeroMemory(&GamepadState, sizeof(XINPUT_STATE));
XInputGetState(m_iGamepadIndex, &GamepadState);
return GamepadState;
}
int Gamepad::GetIndex()
{
return m_iGamepadIndex;
}
bool Gamepad::Connected()
{
ZeroMemory(&m_State, sizeof(XINPUT_STATE));
DWORD Result = XInputGetState(m_iGamepadIndex, &m_State);
if (Result == ERROR_SUCCESS)
return true;
else
return false;
}
|
#ifndef WALI_DOMAINS_DETAILS_SEM_ELEM_WRAPPER_HPP
#define WALI_DOMAINS_DETAILS_SEM_ELEM_WRAPPER_HPP
#include <algorithm>
#include <limits>
#include "wali/Common.hpp"
#include "wali/SemElem.hpp"
namespace wali {
namespace domains {
namespace details {
///////////////////////////////////////
struct Expr : Countable {
virtual ~Expr() {}
virtual sem_elem_t eval(sem_elem_t example) const = 0;
virtual bool is_concrete_one() const { return false; }
virtual bool is_concrete_zero() const { return false; }
virtual std::string to_string() const = 0;
virtual bool same_tree(ref_ptr<Expr> that) const = 0;
};
struct ExprZero : Expr {
virtual sem_elem_t eval(sem_elem_t example) const
{
return example->zero();
}
virtual bool is_concrete_zero() const { return true; }
virtual bool same_tree(ref_ptr<Expr> that) const
{
return that->is_concrete_zero();
}
virtual std::string to_string() const { return "0"; }
};
struct ExprOne : Expr {
virtual sem_elem_t eval(sem_elem_t example) const
{
return example->one();
}
virtual bool is_concrete_one() const { return true; }
virtual bool same_tree(ref_ptr<Expr> that) const
{
return that->is_concrete_one();
}
virtual std::string to_string() const { return "1"; }
};
struct ExprCombine : Expr {
ref_ptr<Expr> m_left, m_right;
ExprCombine(ref_ptr<Expr> l, ref_ptr<Expr> r)
: m_left(l), m_right(r)
{
fast_assert(!l->is_concrete_zero());
fast_assert(!r->is_concrete_zero());
}
virtual sem_elem_t eval(sem_elem_t example) const
{
return m_left->eval(example)->combine(m_right->eval(example));
}
virtual std::string to_string() const
{
return "(" + m_left->to_string() + " + " + m_right->to_string() + ")";
}
virtual bool same_tree(ref_ptr<Expr> that) const
{
ExprCombine* that_down = dynamic_cast<ExprCombine*>(that.get_ptr());
return
that_down != NULL
&& m_left->same_tree(that_down->m_left)
&& m_right->same_tree(that_down->m_right);
}
};
struct ExprExtend : Expr {
ref_ptr<Expr> m_left, m_right;
ExprExtend(ref_ptr<Expr> l, ref_ptr<Expr> r)
: m_left(l), m_right(r)
{
fast_assert(!l->is_concrete_zero());
fast_assert(!r->is_concrete_zero());
fast_assert(!l->is_concrete_one());
fast_assert(!r->is_concrete_one());
}
virtual sem_elem_t eval(sem_elem_t example) const
{
return m_left->eval(example)->extend(m_right->eval(example));
}
virtual std::string to_string() const
{
return "(" + m_left->to_string() + " * " + m_right->to_string() + ")";
}
virtual bool same_tree(ref_ptr<Expr> that) const
{
ExprExtend* that_down = dynamic_cast<ExprExtend*>(that.get_ptr());
return
that_down != NULL
&& m_left->same_tree(that_down->m_left)
&& m_right->same_tree(that_down->m_right);
}
};
///////////////////////////////////////
class SemElemWrapper
{
public:
// This is not really necessary here, but it will unify
// the interface with MinPlusInt, in case that ever seems
// beneficial...
typedef sem_elem_t value_type;
private:
// We need to be able to make 0 and 1 elements without knowing
// what kind of semiring we want. So we need special indications.
//
// But, we can also take an unknown zero and combine with an
// unknown one for example, so we really need a way to be able
// to express expressions of 0s and 1s.
//
// IMPORTANT NOTE: It is possible that 0 can be represented by
// both a ZERO kind as well as a NORMAL kind with a 0 m_value,
// and similar for 1.
//
// I think this is "necessary." If we replaced a concrete 0
// with the unknown 0, then if the user created a wrapper with
// concrete 0 and asked for the value, we wouldn't know what
// to give it.
ref_ptr<Expr> m_expr;
value_type m_value;
void assert_sane() const {
fast_assert(m_expr.is_valid() || m_value.is_valid());
fast_assert(!m_expr.is_valid() || !m_value.is_valid());
}
explicit SemElemWrapper (ref_ptr<Expr> expr)
: m_expr(expr)
, m_value()
{
fast_assert(expr.is_valid());
}
public:
SemElemWrapper (sem_elem_t v)
: m_expr()
, m_value(v)
{
fast_assert(v.is_valid());
}
// This is needed by boost::matrix:
// template<class T, class ALLOC>
// const typename identity_matrix<T, ALLOC>::value_type
// identity_matrix<T, ALLOC>::one_ (1);
// // ISSUE: need 'one'-traits here
//
// The zero element for identity_matrix and zero_matrix
// are constructed by default parameter, so this should be
// the only call to this function.
//
// Once the boost thing is resolved, this should become
// private. (Or really I should figure out how to make it
// a friend.)
explicit SemElemWrapper(int t)
: m_expr(t == 0
? static_cast<Expr*>(new ExprZero())
: static_cast<Expr*>(new ExprOne()))
, m_value()
{
fast_assert(t == 0 || t == 1);
assert_sane();
}
SemElemWrapper()
: m_expr(new ExprZero())
, m_value()
{}
SemElemWrapper(SemElemWrapper const & other)
: m_expr(other.m_expr)
, m_value(other.m_value)
{
assert_sane();
}
SemElemWrapper &
operator= (SemElemWrapper const & other) {
other.assert_sane();
m_expr = other.m_expr;
m_value = other.m_value;
return *this;
}
SemElemWrapper &
operator= (value_type v) {
assert_sane();
fast_assert(v.is_valid());
m_expr = NULL;
m_value = v;
return *this;
}
bool
operator== (SemElemWrapper const & that) const {
this->assert_sane();
that.assert_sane();
// Both are known values
if (this->m_value.is_valid() && that.m_value.is_valid()) {
return this->m_value->equal(that.m_value);
}
// Exactly one is a known value
if (this->m_value.is_valid()) {
sem_elem_t that_val = that.m_expr->eval(this->m_value);
return this->m_value->equal(that_val);
}
if (that.m_value.is_valid()) {
sem_elem_t this_val = this->m_expr->eval(that.m_value);
return this_val->equal(that.m_value);
}
// Both are unknown values
// Are they definitely the same?
if (this->m_expr->is_concrete_one() && that.m_expr->is_concrete_one()) {
return true;
}
if (this->m_expr->is_concrete_zero() && that.m_expr->is_concrete_zero()) {
return true;
}
// Are they definitely different?
if (this->m_expr->is_concrete_one() && that.m_expr->is_concrete_zero()) {
return false;
}
if (this->m_expr->is_concrete_zero() && that.m_expr->is_concrete_one()) {
return false;
}
// A single value is "definitely" different than a tree
if (this->m_expr->is_concrete_zero()
|| this->m_expr->is_concrete_one()
|| that.m_expr->is_concrete_zero()
|| that.m_expr->is_concrete_one())
{
return false;
}
fast_assert(false);
return false;
}
bool
operator!= (SemElemWrapper const & that) const {
return !(*this == that);
}
value_type
get_value() const {
assert_sane();
fast_assert(m_value.is_valid());
return m_value;
}
std::ostream&
print(std::ostream & os) const {
assert_sane();
if (m_value.is_valid()) {
return m_value->print(os);
}
else {
return os << "[unknown: " << m_expr->to_string() << "]";
}
}
SemElemWrapper
operator+ (SemElemWrapper const & that) const {
this->assert_sane();
that.assert_sane();
sem_elem_t this_val, that_val;
// Figure out the SemElem from this
if (this->m_value.is_valid()) {
this_val = this->m_value;
}
else if (that.m_value.is_valid()) {
this_val = this->m_expr->eval(that.m_value);
}
// Figure out the SemElem from that
if (that.m_value.is_valid()) {
that_val = that.m_value;
}
else if (this->m_value.is_valid()) {
that_val = that.m_expr->eval(this->m_value);
}
// If we have known values, then we can return
if (this_val.is_valid() && that_val.is_valid()) {
return SemElemWrapper(this_val->combine(that_val));
}
// Otherwise we build a new expression:
if (this->m_expr->is_concrete_zero()) {
return SemElemWrapper(that.m_expr);
}
else if (that.m_expr->is_concrete_zero()) {
return SemElemWrapper(this->m_expr);
}
else if (this->m_expr->same_tree(that.m_expr)) {
return SemElemWrapper(this->m_expr);
}
else {
// This case will sometimes be wrong...
return SemElemWrapper(
new ExprCombine(
this->m_expr,
that.m_expr));
}
}
void
operator+= (SemElemWrapper const & that) {
SemElemWrapper sum = *this + that;
*this = sum;
}
SemElemWrapper
operator* (SemElemWrapper const & that) const {
this->assert_sane();
that.assert_sane();
sem_elem_t this_val, that_val;
// Figure out the SemElem from this
if (this->m_value.is_valid()) {
this_val = this->m_value;
}
else if (that.m_value.is_valid()) {
this_val = this->m_expr->eval(that.m_value);
}
// Figure out the SemElem from that
if (that.m_value.is_valid()) {
that_val = that.m_value;
}
else if (this->m_value.is_valid()) {
that_val = that.m_expr->eval(this->m_value);
}
// If we have known values, then we can return
if (this_val.is_valid() && that_val.is_valid()) {
return SemElemWrapper(this_val->extend(that_val));
}
// Otherwise we build a new expression:
// 0*v or v*0 => 0
if (this->m_expr->is_concrete_zero()) {
return SemElemWrapper(this->m_expr);
}
else if (that.m_expr->is_concrete_zero()) {
return SemElemWrapper(that.m_expr);
}
// 1*v or v*1 => v
else if (this->m_expr->is_concrete_one()) {
return SemElemWrapper(that.m_expr);
}
else if (that.m_expr->is_concrete_one()) {
return SemElemWrapper(this->m_expr);
}
else {
return SemElemWrapper(
new ExprExtend(
this->m_expr,
that.m_expr));
}
}
void
operator*= (SemElemWrapper const & that) {
SemElemWrapper product = *this * that;
*this = product;
}
};
inline
std::ostream&
operator<< (std::ostream& os, SemElemWrapper const & that)
{
return that.print(os);
}
}
}
}
#endif /* WALI_DOMAINS_DETAILS_SEM_ELEM_WRAPPER_HPP */
// Yo, Emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// End:
|
/* XMRig
* Copyright (c) 2019 Spudz76 <https://github.com/Spudz76>
* Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/io/log/backends/ConsoleLog.h"
#include "base/io/log/Log.h"
#include "base/kernel/config/Title.h"
#include "base/tools/Handle.h"
#include <cstdio>
xmrig::ConsoleLog::ConsoleLog(const Title &title)
{
if (!isSupported()) {
Log::setColors(false);
return;
}
m_tty = new uv_tty_t;
if (uv_tty_init(uv_default_loop(), m_tty, 1, 0) < 0) {
Log::setColors(false);
return;
}
uv_tty_set_mode(m_tty, UV_TTY_MODE_NORMAL);
# ifdef XMRIG_OS_WIN
m_stream = reinterpret_cast<uv_stream_t*>(m_tty);
HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
if (handle != INVALID_HANDLE_VALUE) {
DWORD mode = 0;
if (GetConsoleMode(handle, &mode)) {
mode &= ~ENABLE_QUICK_EDIT_MODE;
SetConsoleMode(handle, mode | ENABLE_EXTENDED_FLAGS);
}
}
if (title.isEnabled()) {
SetConsoleTitleA(title.value());
}
# endif
}
xmrig::ConsoleLog::~ConsoleLog()
{
Handle::close(m_tty);
}
void xmrig::ConsoleLog::print(uint64_t, int, const char *line, size_t, size_t size, bool colors)
{
if (!m_tty || Log::isColors() != colors) {
return;
}
# ifdef XMRIG_OS_WIN
uv_buf_t buf = uv_buf_init(const_cast<char *>(line), static_cast<unsigned int>(size));
if (!isWritable()) {
fputs(line, stdout);
fflush(stdout);
}
else {
uv_try_write(m_stream, &buf, 1);
}
# else
fputs(line, stdout);
fflush(stdout);
# endif
}
bool xmrig::ConsoleLog::isSupported() const
{
const uv_handle_type type = uv_guess_handle(1);
return type == UV_TTY || type == UV_NAMED_PIPE;
}
#ifdef XMRIG_OS_WIN
bool xmrig::ConsoleLog::isWritable() const
{
if (!m_stream || uv_is_writable(m_stream) != 1) {
return false;
}
return isSupported();
}
#endif
|
/**
* Copyright (C) 2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "platforms/unix/base/x11/x11_informationbroker.h"
#include "platforms/utilix/x11_all.h"
#include "platforms/unix/base/x11/x11_globals.h"
#include "platforms/unix/base/x11/x11_opmessageloop.h"
#include "platforms/unix/base/x11/x11_opwindow.h"
#include "platforms/unix/base/x11/x11_widget.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick_toolkit/windows/DesktopWindow.h"
X11Client* X11Client::Instance()
{
static X11InformationBroker broker;
return &broker;
}
X11Types::Display* X11InformationBroker::GetDisplay()
{
return g_x11->GetDisplay();
}
int X11InformationBroker::GetScreenNumber(X11Types::Window window)
{
int screen = -1;
if (window)
{
XWindowAttributes attr;
if (XGetWindowAttributes(GetDisplay(), window, &attr))
screen = XScreenNumberOfScreen(attr.screen);
}
if (screen < 0)
return DefaultScreen(g_x11->GetDisplay());
return screen;
}
X11Types::Window X11InformationBroker::GetTopLevelWindow(OpWindow* window)
{
if (!window)
return None;
X11OpWindow* rootwindow = static_cast<X11OpWindow*>(window->GetRootWindow());
if (!rootwindow || !rootwindow->GetWidget())
return None;
return rootwindow->GetWidget()->GetWindowHandle();
}
void X11InformationBroker::GetKeyEventPlatformData(uni_char key, bool pressed, ShiftKeyState modifiers, UINT64& data1, UINT64& data2)
{
XEvent event = X11OpMessageLoop::Self()->GetPluginEvent(X11OpMessageLoop::KEY_EVENT);
data1 = event.xkey.state;
data2 = event.xkey.keycode;
}
|
#include "SM_MinBoundingBox.h"
#include "SM_Calc.h"
#include "SM_ConvexHull.h"
#include <assert.h>
namespace sm
{
// bounding:
// 1 2
// 0 3
bool MinBoundingBox::Do(const CU_VEC<vec2>& points, vec2 bounding[4])
{
// convex hull
CU_VEC<vec2> hull;
convex_hull(points, hull);
// normal
float xmin = FLT_MAX, xmax = -FLT_MAX,
ymin = FLT_MAX, ymax = -FLT_MAX;
for (int i = 0, n = hull.size(); i < n; ++i) {
const vec2& p = hull[i];
if (p.x < xmin) { xmin = p.x; }
if (p.x > xmax) { xmax = p.x; }
if (p.y < ymin) { ymin = p.y; }
if (p.y > ymax) { ymax = p.y; }
}
float area_min = (xmax - xmin) * (ymax - ymin);
bounding[0].Set(xmin, ymin);
bounding[1].Set(xmin, ymax);
bounding[2].Set(xmax, ymax);
bounding[3].Set(xmax, ymin);
// other dir
bool is_other_dir = false;
for (int i = 0, n = hull.size()-1; i < n; ++i) {
bool b = TextOtherDir(hull, hull[i], hull[i+1], area_min, bounding);
if (b) {
is_other_dir = b;
}
}
bool b = TextOtherDir(hull, hull[0], hull[hull.size()-1], area_min, bounding);
if (b) {
is_other_dir = b;
}
assert(is_turn_right(bounding[0], bounding[1], bounding[2]));
return b;
}
bool MinBoundingBox::TextOtherDir(const CU_VEC<vec2>& points,
const vec2& start, const vec2& end,
float& min_area, vec2 bounding[4])
{
float dx = start.x - end.x,
dy = start.y - end.y;
if (fabs(dx) < FLT_EPSILON ||
fabs(dy) < FLT_EPSILON) {
return false;
}
float k0 = dy / dx;
float b0_min, b0_max;
CalculateB(points, k0, b0_min, b0_max);
float e0 = (b0_max - b0_min) / sqrt(1+k0*k0);
float k1 = -1 / k0;
float b1_min, b1_max;
CalculateB(points, k1, b1_min, b1_max);
float e1 = (b1_max - b1_min) / sqrt(1+k1*k1);
float area = e0 * e1;
if (area < min_area) {
min_area = area;
if (k0 > 0) {
bounding[0].x = (b1_min - b0_min) / (k0 - k1);
bounding[1].x = (b1_min - b0_max) / (k0 - k1);
bounding[2].x = (b1_max - b0_max) / (k0 - k1);
bounding[3].x = (b1_max - b0_min) / (k0 - k1);
} else {
bounding[0].x = (b1_max - b0_min) / (k0 - k1);
bounding[1].x = (b1_max - b0_max) / (k0 - k1);
bounding[2].x = (b1_min - b0_max) / (k0 - k1);
bounding[3].x = (b1_min - b0_min) / (k0 - k1);
}
bounding[0].y = k0 * bounding[0].x + b0_min;
bounding[1].y = k0 * bounding[1].x + b0_max;
bounding[2].y = k0 * bounding[2].x + b0_max;
bounding[3].y = k0 * bounding[3].x + b0_min;
}
return true;
}
void MinBoundingBox::CalculateB(const CU_VEC<vec2>& points, float k,
float& b_min, float& b_max)
{
b_min = FLT_MAX;
b_max = -FLT_MAX;
for (int i = 0, n = points.size(); i < n; ++i) {
float b = points[i].y - k * points[i].x;
if (b < b_min) { b_min = b; }
if (b > b_max) { b_max = b; }
}
}
}
|
#pragma once
#include "window.h"
#include <algorithm>
#include <functional>
template <typename GAME>
class MainLoop
{
public:
MainLoop(float timeStepInSeconds)
{
if (timeStepInSeconds < 0.005f) {
throw std::runtime_error("200 fps is plenty. Don't be so darn greedy! =P");
}
const long long timeStepInMs = static_cast<long long>(timeStepInSeconds*1000.0f);
Window window;
window.open();
GAME game(window);
while (window.is_open()) {
const long long begin = get_ms_since_epoch();
game.onIteration(window, timeStepInSeconds);
window.swap_buffers();
window.tick();
const long long sleep = std::max(timeStepInMs - ((get_ms_since_epoch() - begin) / 1000000), 0LL);
Sleep(static_cast<int>(sleep));
}
}
private:
long long get_ms_since_epoch() const
{
FILETIME fileTime;
GetSystemTimeAsFileTime(&fileTime);
return static_cast<long long>(fileTime.dwLowDateTime) + (static_cast<long long>(fileTime.dwHighDateTime) << 32LL);
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef SVG_PATH_PARSER_H
#define SVG_PATH_PARSER_H
#ifdef SVG_SUPPORT
#include "modules/svg/src/OpBpath.h"
#include "modules/svg/src/parser/svgtokenizer.h"
class SVGPathParser
{
public:
/**
* Parse a string by extracting path segment from it and adding
* them to the OpBpath
*/
OP_STATUS ParsePath(const uni_char *input_string, unsigned str_len, OpBpath *path);
private:
BOOL GetNextSegment(SVGPathSeg &seg, SVGPathSeg::SVGPathSegType prev_path_seg_type);
BOOL GetNextCmdType(SVGPathSeg::SVGPathSegType &path_seg_type, BOOL& implicit);
void AddSegmentToPath(OpBpath *path, const SVGPathSeg& seg);
BOOL GetArcFlag();
double NextPathNumber();
SVGTokenizer tokenizer;
OpBpath *path;
OP_STATUS status;
};
#endif // SVG_SUPPORT
#endif // !SVG_PATH_PARSER_H
|
#pragma once
#include "light.h"
class PointLight : public Light
{
public:
PointLight(const Transform &t,const Point3f &pLight,const Color3f& I):Light(t),pLight(pLight),I(I){}
virtual Color3f Sample_Li(const Intersection &ref, const Point2f &xi,
Vector3f *wi, Float *pdf) const;
virtual bool getPosition(Point3f *wi) const;
virtual Float Pdf_Li(const Intersection &ref, const Vector3f &wi) const;
Color3f Sample_Li(const Intersection &ref, const Point2f &xi,
Vector3f *wi, Float *pdf,Intersection *lightsample) const;
const Point3f pLight;
const Color3f I;
};
#pragma once
|
#include "batch2Drenderer.h"
namespace sge { namespace graphics{
using namespace math;
Batch2DRenderer::Batch2DRenderer(){
init();
}
Batch2DRenderer::~Batch2DRenderer(){
delete m_IBO;
glDeleteBuffers(1, &m_VBO);
glDeleteVertexArrays(1, &m_VAO);
}
void Batch2DRenderer::init(){
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, RENDERER_BUFFER_SIZE, NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(SHADER_VERTEX_INDEX);
glEnableVertexAttribArray(SHADER_UV_INDEX);
glEnableVertexAttribArray(SHADER_TID_INDEX);
glEnableVertexAttribArray(SHADER_COLOR_INDEX);
glVertexAttribPointer(SHADER_VERTEX_INDEX, 3, GL_FLOAT, GL_FALSE, RENDERER_VERTEX_SIZE, (const GLvoid*) 0);
glVertexAttribPointer(SHADER_UV_INDEX, 2, GL_FLOAT, GL_FALSE, RENDERER_VERTEX_SIZE,(const GLvoid*) (offsetof(VertexData, VertexData::uv)));
glVertexAttribPointer(SHADER_TID_INDEX, 1, GL_FLOAT, GL_FALSE, RENDERER_VERTEX_SIZE,(const GLvoid*) (offsetof(VertexData, VertexData::tid)));
glVertexAttribPointer(SHADER_COLOR_INDEX, 4, GL_UNSIGNED_BYTE, GL_TRUE, RENDERER_VERTEX_SIZE, (const GLvoid*) (offsetof(VertexData, VertexData::color)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
int offset = 0;
GLushort* indices = new GLushort[RENDERER_INDICES_SIZE];
for(int i=0; i< RENDERER_INDICES_SIZE; i+=6){
indices[i + 0] = offset + 0;
indices[i + 1] = offset + 1;
indices[i + 2] = offset + 2;
indices[i + 3] = offset + 2;
indices[i + 4] = offset + 3;
indices[i + 5] = offset + 0;
offset += 4;
}
m_IBO = new IndexBuffer(indices, RENDERER_INDICES_SIZE);
glBindVertexArray(0);
}
void Batch2DRenderer::submit(const Renderable2D* renderable){
const math::vec3& position = renderable->getPosition();
const math::vec2& size = renderable->getSize();
const unsigned int color = renderable->getColor();
const std::vector<math::vec2>& uv = renderable->getUV();
const GLuint tid = renderable->getTID();
float ts = 0.0f;
if(tid>0){
bool found = false;
for(int i=0; i<m_TextureSlots.size(); i++ ){
if(m_TextureSlots[i] == tid){
ts = (float)(i+1);
found = true;
break;
}
}
if(!found){
if(m_TextureSlots.size() >= RENDERER_MAX_TEXTURES){
end();
flush();
begin();
}
m_TextureSlots.push_back(tid);
ts = (float)(m_TextureSlots.size());
}
}
m_Buffer->vertex = *m_TransformationBack *math::vec3(position.x, position.y, position.z);
m_Buffer->uv = uv[0];
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_Buffer->vertex = *m_TransformationBack*math::vec3(position.x, position.y + size.y, position.z);
m_Buffer->uv = uv[1];
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_Buffer->vertex = *m_TransformationBack*math::vec3(position.x + size.x, position.y + size.y, position.z);
m_Buffer->uv = uv[2];
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_Buffer->vertex = *m_TransformationBack*math::vec3(position.x + size.x, position.y, position.z);
m_Buffer->uv = uv[3];
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_IndexCount += 6;
glBindVertexArray(m_VAO);
}
void Batch2DRenderer::begin(){
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
m_Buffer = (VertexData*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
}
void Batch2DRenderer::drawString(const std::string &text, const math::vec2 &position, const Font &font, unsigned int color){
float ts = 0.0f;
bool found = false;
for(int i=0; i<m_TextureSlots.size(); i++ ){
if(m_TextureSlots[i] == font.getId()){
ts = (float)(i+1);
found = true;
break;
}
}
if(!found){
if(m_TextureSlots.size() >= RENDERER_MAX_TEXTURES){
end();
flush();
begin();
}
m_TextureSlots.push_back(font.getId());
ts = (float)(m_TextureSlots.size());
}
const math::vec2& scale = font.getScale();
float x = position.x;
ftgl::texture_font_t* ftFont = font.getFTFont();
for(int i=0; i<text.length(); i++){
char c = text[i];
texture_glyph_t* glyph = ftgl::texture_font_get_glyph(ftFont, &c);
if(glyph != NULL){
if(i>0){
float kerning = texture_glyph_get_kerning(glyph, &text[i-1]);
x += kerning / scale.x;
}
float x0 = x + glyph->offset_x / scale.x;
float y0 = position.y + glyph->offset_y / scale.y;
float x1 = x0 + glyph->width / scale.x;
float y1 = y0 - glyph->height / scale.y;
float u0 = glyph->s0;
float v0 = glyph->t0;
float u1 = glyph->s1;
float v1 = glyph->t1;
m_Buffer->vertex = *m_TransformationBack*math::vec3(x0,y0,0);
m_Buffer->uv = math::vec2(u0, v0);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_Buffer->vertex = *m_TransformationBack*math::vec3(x0,y1,0);
m_Buffer->uv = math::vec2(u0, v1);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_Buffer->vertex = *m_TransformationBack*math::vec3(x1,y1,0);
m_Buffer->uv = math::vec2(u1, v1);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_Buffer->vertex = *m_TransformationBack*math::vec3(x1,y0,0);
m_Buffer->uv = math::vec2(u1, v0);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_IndexCount += 6;
x+= glyph->advance_x / scale.x;
}
}
glBindVertexArray(m_VAO);
}
void Batch2DRenderer::end(){
glUnmapBuffer(GL_ARRAY_BUFFER);
glBindBuffer(GL_ARRAY_BUFFER,0);
}
void Batch2DRenderer::flush(){
for(int i =0; i<m_TextureSlots.size(); i++){
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, m_TextureSlots[i]);
}
m_IBO->bind();
glDrawElements(GL_TRIANGLES, m_IndexCount, GL_UNSIGNED_SHORT, NULL);
m_IBO->unbind();
glBindVertexArray(0);
m_IndexCount = 0;
m_TextureSlots.clear();
}
void Batch2DRenderer::drawLine(float x0, float y0, float x1, float y1, uint color, float thickness){
float ts = 0.0f;
vec2 normal = vec2(y1 - y0, -(x1 - x0)).normalise() * thickness;
vec3 vertex = *m_TransformationBack * vec3(x0 + normal.x, y0 + normal.y, 0.0f);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(0, 0);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
vertex = *m_TransformationBack * vec3(x1 + normal.x, y1 + normal.y, 0.0f);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(0, 1);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
vertex = *m_TransformationBack * vec3(x1 - normal.x, y1 - normal.y, 0.0f);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(1, 1);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
vertex = *m_TransformationBack * vec3(x0 - normal.x, y0 - normal.y, 0.0f);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(1, 0);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_IndexCount += 6;
}
void Batch2DRenderer::drawLine(const math::vec2& start, const math::vec2& end, uint color, float thickness){
drawLine(start.x, start.y, end.x, end.y, color, thickness);
}
void Batch2DRenderer::drawRect(float x, float y, float width, float height, uint color){
drawLine(x, y, x + width, y, color);
drawLine(x + width, y, x + width, y + height, color);
drawLine(x + width, y + height, x, y + height, color);
drawLine(x, y + height, x, y, color);
}
void Batch2DRenderer::drawRect(const math::vec2& position, const math::vec2& size, uint color){
drawRect(position.x, position.y, size.x, size.y, color);
}
void Batch2DRenderer::drawRect(const math::Rectangle& rectangle, uint color){
drawRect(rectangle.getMinimumBound(), rectangle.size * 2.0f, color);
}
void Batch2DRenderer::fillRect(float x, float y, float width, float height, uint color){
vec3 position(x, y, 0.0f);
vec2 size(width, height);
float ts = 0.0f;
vec3 vertex = *m_TransformationBack * position;
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(0, 0);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
vertex = *m_TransformationBack * vec3(position.x + size.x, position.y, position.z);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(0, 1);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
vertex = *m_TransformationBack * vec3(position.x + size.x, position.y + size.y, position.z);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(1, 1);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
vertex = *m_TransformationBack * vec3(position.x, position.y + size.y, position.z);
m_Buffer->vertex = vertex;
m_Buffer->uv = math::vec2(1, 0);
m_Buffer->tid = ts;
m_Buffer->color = color;
m_Buffer++;
m_IndexCount += 6;
}
void Batch2DRenderer::fillRect(const math::vec2& position, const math::vec2& size, uint color){
fillRect(position.x, position.y, size.x, size.y, color);
}
void Batch2DRenderer::fillRect(const math::Rectangle& rectangle, uint color){
fillRect(rectangle.getMinimumBound(), rectangle.size * 2.0f, color);
}
} }
|
#ifndef FUNKTION_H
#define FUNKTION_H
class CalculationException: public std::exception {
public:
virtual const char* what() const noexcept override = 0;
};
class Funktion
{
//1D
public:
double operator()(double x);
virtual double value(double x);
};
#endif // FUNKTION_H
|
#include "../headers/BinOpNode.hpp"
#include <string>
#include <sstream>
using namespace std;
BinOpNode::BinOpNode(Node *leftOperand, string Op, Node *rightOperand) {
this->leftOperand = leftOperand;
this->Op = Op;
if (Op == "<=" or Op == "<" or Op == "and" or Op == "=")
this->type = "bool";
else
this->type = "int32";
this->rightOperand = rightOperand;
}
void BinOpNode::printTree() {
printf("BinOp(%s", Op.c_str());
printf(",");
leftOperand->printTree();
printf(",");
rightOperand->printTree();
printf(")");
}
string BinOpNode::printCheck(ClassNode *classNode) {
string retString = "BinOp(" + Op + ", ";
if (leftOperand->printCheck(classNode).find("ErrorSemanticOneTime:") != string::npos)
return leftOperand->printCheck(classNode);
if (rightOperand->printCheck(classNode).find("ErrorSemanticOneTime:") != string::npos)
return rightOperand->printCheck(classNode);
if (leftOperand->getType() != rightOperand->getType() and rightOperand->getType() != "IO")
return "ErrorSemanticOneTime:" + to_string(this->nbLine - 1) + ":" +
to_string(this->nbColumn + leftOperand->getValue().size() + 2) +
": semantic error : cannot compare a value of type " + leftOperand->getType() + " and a value of type " +
rightOperand->getType() + ".";
retString += leftOperand->printCheck(classNode) + ", " + rightOperand->printCheck(classNode) + ")";
if (Op == "<=" or Op == "<" or Op == "and" or Op == "=") {
this->type = "bool";
retString += " : bool";
} else {
this->type = "int32";
retString += " : int32";
}
return retString;
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QPushButton>
#include<QRadioButton>
#include<QTime>
#include<cstdlib>
#include<QDebug>
#include<vector>
#include<sstream>
#include<string>
#include<QDir>
#include<QTableWidget>
#include<QTableWidgetItem>
#include<QString>
#include<QDialog>
#include<QScrollArea>
#include<QFile>
#include<QFileDialog>
#include<QFileInfo>
#include<QDateTime>
#include<QTextEdit>
#include<QTime>
#include<QByteArray>
#include<fstream>
#include<QDataStream>
#include<QPalette>
using namespace std;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void print(const vector <vector<int>> &num);
void createnum(QPushButton *newgame,QPushButton *btn);
private slots:
void on_exit_clicked();
void on_newgame_clicked();
void show_prodcut_sets(int row,int col);
void change_num(QString s,int row,int col);
void on_confirm_clicked();
void on_answer_clicked();
void on_tip_clicked();
void on_recall_2_clicked();
void on_save_clicked();
void on_clear_clicked();
void on_solve_clicked();
void on_user_defined_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
|
// Scintilla source code edit control
/** @file LexFSharp.cxx
** Lexer for F#
** Written by Zufu Liu <zufuliu@gmail.com> 2011/09
**/
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
using namespace Scintilla;
static inline bool IsFSOperator(int ch) {
return isoperator(ch) || (ch < 0x80 && (ch == '\'' || ch == '@' || ch == '$' || ch == '#' || ch == '`'));
}
#define LEX_FSHARP 22
#define LEX_CAML 54
#define LEX_MATH 64
/*static const char *const fsharpWordLists[] = {
"Primary keywords",
"Type Keywords",
"preprocessor",
"Attributes",
0
};*/
static void ColouriseFSharpDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) {
const WordList &keywords = *keywordLists[0];
const WordList &keywords2 = *keywordLists[1];
const WordList &keywords3 = *keywordLists[2];
const WordList &keywords4 = *keywordLists[3];
//const int lexType = styler.GetPropertyInt("lexer.lang.type", LEX_FSHARP);
int visibleChars = 0;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart) {
if (sc.state == SCE_FSHARP_STRING) {
sc.SetState(sc.state);
}
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
switch (sc.state) {
case SCE_FSHARP_OPERATOR:
sc.SetState(SCE_FSHARP_DEFAULT);
break;
case SCE_FSHARP_NUMBER:
if (!iswordstart(sc.ch)) { //
if ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'E' || sc.chPrev == 'e')) {
sc.Forward();
} else if (sc.ch == '.' && sc.chNext != '.') {
sc.ForwardSetState(SCE_FSHARP_DEFAULT);
} else {
sc.SetState(SCE_FSHARP_DEFAULT);
}
}
break;
case SCE_FSHARP_IDENTIFIER:
_label_identifier:
if (!iswordstart(sc.ch)) {
char s[128];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_FSHARP_KEYWORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_FSHARP_TYPEKEYWORD);
} else if (s[0] == '#' && keywords3.InList(&s[1])) {
sc.ChangeState(SCE_FSHARP_PREPROCESSOR);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_FSHARP_ATTRIBUTE);
}
sc.SetState(SCE_FSHARP_DEFAULT);
}
break;
case SCE_FSHARP_COMMENT:
if (sc.Match('*', ')')) {
sc.Forward();
sc.ForwardSetState(SCE_FSHARP_DEFAULT);
}
break;
case SCE_FSHARP_COMMENTLINE:
if (sc.atLineStart) {
visibleChars = 0;
sc.SetState(SCE_FSHARP_DEFAULT);
}
break;
case SCE_FSHARP_QUOTATION:
if (sc.Match('@', '>')) {
sc.Forward();
sc.ForwardSetState(SCE_FSHARP_DEFAULT);
}
break;
case SCE_FSHARP_CHARACTER:
case SCE_FSHARP_STRING:
case SCE_FSHARP_VERBATIM:
if (sc.atLineEnd) {
visibleChars = 0;
sc.ChangeState(SCE_FSHARP_STRINGEOL);
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if ((sc.state == SCE_FSHARP_CHARACTER && sc.ch == '\'')
|| ((sc.state == SCE_FSHARP_STRING || sc.state == SCE_FSHARP_VERBATIM) && sc.ch == '\"')) {
if (sc.chNext == 'B')
sc.Forward();
sc.ForwardSetState(SCE_FSHARP_DEFAULT);
}
break;
case SCE_FSHARP_STRINGEOL:
if (sc.atLineStart) {
sc.SetState(SCE_FSHARP_DEFAULT);
}
break;
}
// Determine if a new state should be entered.
if (sc.state == SCE_FSHARP_DEFAULT) {
if (sc.Match('(', '*')) {
sc.SetState(SCE_FSHARP_COMMENT);
sc.Forward();
} else if (sc.Match('/', '/')) {
sc.SetState(SCE_FSHARP_COMMENTLINE);
} else if (sc.ch == '@' && sc.chNext == '\"') {
sc.SetState(SCE_FSHARP_VERBATIM);
sc.Forward(2);
} else if (sc.ch == '\"') {
sc.SetState(SCE_FSHARP_STRING);
} else if (sc.ch == '\'' && (sc.chNext == '\\' || (sc.chNext != '\'' && sc.GetRelative(2) == '\''))) {
sc.SetState(SCE_FSHARP_CHARACTER);
} else if (sc.ch == '<' && sc.chNext == '@') {
sc.SetState(SCE_FSHARP_QUOTATION);
} else if (sc.ch == '0' && (sc.chNext == 'x' || sc.chNext == 'X')) {
sc.SetState(SCE_FSHARP_NUMBER);
sc.Forward();
} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {
sc.SetState(SCE_FSHARP_NUMBER);
} else if (sc.ch == '#' && visibleChars == 0) {
if (isspacechar(sc.chNext)) {
sc.SetState(SCE_FSHARP_PREPROCESSOR);
sc.ForwardSetState(SCE_FSHARP_DEFAULT);
} else if (iswordstart(sc.chNext)) {
sc.SetState(SCE_FSHARP_IDENTIFIER);
} else {
sc.SetState(SCE_FSHARP_OPERATOR);
}
} else if (sc.ch == '_' && !(iswordstart(sc.chPrev) || iswordstart(sc.chNext))) {
sc.SetState(SCE_FSHARP_OPERATOR);
} else if (iswordstart(sc.ch)) {
sc.SetState(SCE_FSHARP_IDENTIFIER);
} else if (IsFSOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_FSHARP_OPERATOR);
}
}
if (sc.atLineEnd) {
visibleChars = 0;
}
if (!isspacechar(sc.ch)) {
visibleChars++;
}
}
if (sc.state == SCE_FSHARP_IDENTIFIER)
goto _label_identifier;
sc.Complete();
}
#define IsFSLine(line, word) IsLexLineStartsWith(line, styler, word, true, SCE_FSHARP_KEYWORD)
#define IsCommentLine(line) IsLexCommentLine(line, styler, SCE_FSHARP_COMMENTLINE)
static inline bool IsStreamCommentStyle(int style) {
return style == SCE_FSHARP_COMMENT;
}
#define IsOpenLine(line) IsFSLine(line, "open")
static void FoldFSharpDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList, Accessor &styler) {
if (styler.GetPropertyInt("fold") == 0)
return;
//const int lexType = styler.GetPropertyInt("lexer.lang.type", LEX_FSHARP);
const bool foldComment = styler.GetPropertyInt("fold.comment", 1) != 0;
const bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor", 1) != 0;
//const bool foldCompact = styler.GetPropertyInt("fold.compact") != 0;
Sci_PositionU endPos = startPos + length;
//int visibleChars = 0;
Sci_Position lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (Sci_PositionU i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelNext++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
levelNext--;
}
}
if (foldComment && atEOL && IsCommentLine(lineCurrent)) {
if (!IsCommentLine(lineCurrent - 1) && IsCommentLine(lineCurrent + 1))
levelNext++;
else if (IsCommentLine(lineCurrent - 1) && !IsCommentLine(lineCurrent + 1))
levelNext--;
}
if (atEOL && IsOpenLine(lineCurrent)) {
if (!IsOpenLine(lineCurrent - 1) && IsOpenLine(lineCurrent + 1))
levelNext++;
else if (IsOpenLine(lineCurrent - 1) && !IsOpenLine(lineCurrent + 1))
levelNext--;
}
if (foldPreprocessor && styleNext == SCE_FSHARP_PREPROCESSOR) {
if (styler.Match(i, "#if")) {
levelNext++;
} else if (styler.Match(i, "#endif")) {
levelNext--;
}
}
if (style == SCE_FSHARP_OPERATOR) {
if (ch == '{' || ch == '[') {
levelNext++;
} else if (ch == '}' || ch == ']') {
levelNext--;
}
}
if (style == SCE_FSHARP_QUOTATION) {
if (ch == '<' && chNext == '@') {
levelNext++;
} else if (ch == '@' && chNext == '>') {
levelNext--;
}
}
//if (!isspacechar(ch))
// visibleChars++;
if (atEOL || (i == endPos-1)) {
int levelUse = levelCurrent;
int lev = levelUse | levelNext << 16;
//if (visibleChars == 0 && foldCompact)
// lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelCurrent = levelNext;
//visibleChars = 0;
}
}
}
LexerModule lmFSharp(SCLEX_FSHARP, ColouriseFSharpDoc, "fsharp", FoldFSharpDoc);
|
#include "EventSource.h"
#include "mutiplex/EventLoop.h"
#include "Debug.h"
namespace muti
{
EventSource::~EventSource()
{
disable_all();
}
void EventSource::enable_ops(uint32_t op)
{
interest_ops_ |= op;
if (interest_ops_) {
if (state_ == StateNoEvent) {
state_ = StateRegistered;
loop_->register_event(this);
}
else {
loop_->modify_event(this);
}
}
}
void EventSource::disable_ops(uint32_t op)
{
interest_ops_ &= ~op;
if (interest_ops_ == 0) {
loop_->unregister_event(this);
state_ = StateNoEvent;
}
else {
loop_->modify_event(this);
}
}
void EventSource::disable_all()
{
interest_ops_ = 0;
if (state_ == StateRegistered) {
loop_->unregister_event(this);
state_ = StateNoEvent;
}
}
}
|
#include<iostream>
using namespace std;
int main(){
// Write your code here
return 0;
}
|
#ifndef LAB1_MAIN_H
#define LAB1_MAIN_H
#include <iomanip>
#include <iostream>
#include <cmath>
#include "lagrange.h"
#include "quanc8.h"
#include "splines.h"
using namespace std;
const int POINTS_NUM = 11;
const double POINTS_STEP = 0.3;
enum Mode {
FUNCTION, LAGRANGE, SPLINE
};
double x[POINTS_NUM] = {};
double x_inter[POINTS_NUM] = {};
double f[POINTS_NUM] = {};
int main();
void doTask(int precision);
void doResearch(Mode mode);
double function(double x0);
double lagrange(double x0);
double spline(double x0);
#endif
|
#ifndef HYPERTEXT_HPP
#define HYPERTEXT_HPP
#include <string>
void printPageTop(const std::string&);
void printButton(const std::string&, const std::string&, const std::string&,
bool);
void printPageBottom();
#endif
|
#include "_pch.h"
#include "DGroupEditor.h"
#include "config.h"
using namespace wh;
using namespace wh::view;
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------
//DGroupEditor
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
DGroupEditor::DGroupEditor(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
:DlgBaseOkCancel(parent, id, title, pos, size, style, name), mModel(nullptr)
{
SetTitle("Редактирование информации о группе пользователей");
mPropGrid = new wxPropertyGrid(this, wxID_ANY, wxDefaultPosition,
wxDefaultSize, wxPG_DEFAULT_STYLE | wxPG_SPLITTER_AUTO_CENTER);
GetSizer()->Insert(0, mPropGrid, 1, wxALL | wxEXPAND, 0);
mPropGrid->Append(new wxStringProperty(L"Имя", wxPG_LABEL));
mPropGrid->Append(new wxStringProperty(L"Комментарий", wxPG_LABEL));
mPropGrid->Append(new wxStringProperty(L"ID", wxPG_LABEL))->Enable(false);
this->Layout();
}
//---------------------------------------------------------------------------
void DGroupEditor::GetData(rec::Role& rec) const
{
mPropGrid->CommitChangesFromEditor();
rec.mLabel = mPropGrid->GetPropertyByLabel("Имя")->GetValueAsString();
rec.mComment = mPropGrid->GetPropertyByLabel("Комментарий")->GetValueAsString();
rec.mID = mPropGrid->GetPropertyByLabel("ID")->GetValueAsString();
}
//---------------------------------------------------------------------------
void DGroupEditor::SetData(const rec::Role& rec)
{
mPropGrid->CommitChangesFromEditor();
mPropGrid->GetPropertyByLabel(L"Имя")->SetValueFromString(rec.mLabel);
mPropGrid->GetPropertyByLabel(L"Комментарий")->SetValueFromString(rec.mComment);
mPropGrid->GetPropertyByLabel(L"ID")->SetValueFromString(rec.mID);
}
//-----------------------------------------------------------------------------
void DGroupEditor::SetModel(std::shared_ptr<IModel>& newModel)
{
if (newModel != mModel)
{
mChangeConnection.disconnect();
mModel = std::dynamic_pointer_cast<T_Model>(newModel);
if (mModel)
{
auto funcOnChange = std::bind(&DGroupEditor::OnChangeModel,
this, std::placeholders::_1, std::placeholders::_2);
mChangeConnection = mModel->DoConnect(moAfterUpdate, funcOnChange);
OnChangeModel(mModel.get(), nullptr);
const auto& bg = whDataMgr::GetInstance()->mDbCfg->mBaseGroup->GetData();
if ((int)bg < (int)bgAdmin)
m_btnOK->Enable(false);
}//if (mModel)
}//if
}//SetModel
//---------------------------------------------------------------------------
void DGroupEditor::OnChangeModel(const IModel* model, const T_Model::T_Data* data)
{
if (mModel && mModel.get() == model)
{
const auto state = model->GetState();
const auto& rec = mModel->GetData();
SetData(rec);
}
}
//---------------------------------------------------------------------------
void DGroupEditor::UpdateModel()const
{
if (mModel)
{
auto rec = mModel->GetData();
GetData(rec);
mModel->SetData(rec);
}
}
//---------------------------------------------------------------------------
int DGroupEditor::ShowModal()
{
return DlgBaseOkCancel::ShowModal();
}
|
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define pb push_back
#define rep(i, begin, end) \
for (__typeof(end) i = (begin) - ((begin) > (end)); \
i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define db(x) cout << '>' << #x << ':' << x << endl;
#define sz(x) ((int)(x).size())
#define newl cout << "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<long long>
#define vvll vector<vll>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
ll tc, n, m, k;
const int mxN = 500 + 7;
const int mxM = 500;
ll vis[mxM];
ll mt[mxM];
vll g[mxN];
// cses school dance
// more kuhn optimization: cf blog
// https://codeforces.com/blog/entry/17023?locale=en
int dfs(ll u) {
if (vis[u])
return 0;
vis[u] = 1;
for (auto v1 : g[u]) {
if (mt[v1] == -1 || dfs(mt[v1])) {
mt[v1] = u;
return 1;
}
}
return 0;
}
int main() {
fast_io();
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
cin >> n >> m >> k;
rep(i, 0, k) {
ll u, v;
cin >> u >> v;
u--, v--;
g[u].pb(v);
}
int ans = 0;
memset(mt, -1, m*sizeof(ll) );
memset(vis, 0, n*sizeof(ll));
rep(u, 0, n) {
memset(vis, 0, n*sizeof(ll));
ans += dfs(u);
}
cout << ans;
newl;
rep(u, 0, m) {
if (~mt[u]) {
cout << mt[u] + 1 << " " << u + 1;
newl;
}
}
return 0;
}
|
#ifndef STEPPER_FACTORY_HPP
#define STEPPER_FACTORY_HPP
#include "../stepper/stepperbase.hpp"
#include "../stepper/verlet.hpp"
#include <cmath>
stepperbase* integratorFactory(const simulation& sim,const atom_list& atoms,forceeval& forcer)
{
stepperbase* integrator;
if(sim.integrator == "VERLET")
{
integrator = new verlet(forcer,atoms,sim);
}
else if(sim.integrator == "SI2A")
{
double a[2] = {0.5,0.5};
double b[2] = {0.0,1.0};
integrator = new sprk<2>(forcer, atoms,sim, a,b);
}
else if(sim.integrator == "SI3A")
{
double a[3] = {(2.0/3.0),
-(2.0/3.0),
1.0};
double b[3] = {(7.0/24.0),
(3.0/4.0),
(-1.0/24.0)};
integrator = new sprk<3>(forcer, atoms,sim, a,b);
}
else if(sim.integrator == "SI3B")
{
double a1 = 0.9196615230173999;
double a2 = 0.25/a1-a1/2;
double a[3] = {a1,a2,1.0-a1-a2};
double b[3] = {a[2],a[1],a[0]};
integrator = new sprk<3>(forcer, atoms,sim, a,b);
}
else if(sim.integrator == "SI4A")
{
double a1 = (2.0 + pow(2.0,(1.0/3.0)) + pow(2.0,(-1.0/3.0))) / 6.0;
double a2 = (1.0 + pow(2.0,(1.0/3.0)) - pow(2.0,(-1.0/3.0))) / 6.0;
double a[4] = {a1,a2,a1,a2};
double b3 = 1.0/(1.0 - pow(2.0,(2.0/3.0)));
double b2 = 1.0/(2.0 - pow(2.0,(1.0/3.0)));
double b[4] = {0.0,b2,b3,b2};
integrator = new sprk<4>(forcer, atoms,sim, a,b);
}
else if(sim.integrator == "SI4B")
{
double a[4] = {0.515352837431122936,
-0.085782019412973646,
0.441583023616466524,
0.128846158365384185};
double b[4] = {0.134496199277431089,
-0.224819803079420806,
0.756320000515668291,
0.334003603286321425};
integrator = new sprk<4>(forcer, atoms,sim, a,b);
}
else if(sim.integrator == "SI4C")
{
double a[5] = {0.205177661542290,
0.403021281604210,
-0.120920876338910,
0.512721933192410,
0.000000000000000};
double b[5] = {0.061758858135626,
0.338978026553640,
0.614791307175580,
-0.140548014659370,
0.125019822794530};
integrator = new sprk<5>(forcer, atoms,sim, a,b);
}
else if(sim.integrator == "SI6A")
{
double a1 = 0.78451361047756;
double a2 = 0.23557321335936;
double a3 =-1.17767998417890;
double a4 = 1.31518632068390;
double a[8] = {a1,a2,a3,a4,a3,a2,a1,0.0};
double b1 = 0.39225680523878;
double b2 = 0.51004341191846;
double b3 =-0.47105338540976;
double b4 = 0.06875316825252;
double b[8] = {b1,b2,b3,b4,b4,b3,b2,b1};
integrator = new sprk<8>(forcer, atoms,sim, a,b);
}
else
{
cerr << "Specified integration algorithm " << sim.integrator << " invalid." << endl;
exit(1);
}
return integrator;
}
#endif //STEPPER_FACTORY_HPP
|
#ifndef SIMULATION_H
#define SIMULATION_H
#include "StudentQueue.h"
#include "WindowLists.h"
#include "Statistics.h"
using namespace std;
class Simulation {
public:
Simulation();
void simulate();
~Simulation();
private:
int count;
Statistics* stats; // statistics
StudentQueue* sQ; //Student Queue
WindowLists* wQ; // Window Queue
Student s; // student
Window w; // window
void serviceStudents();
void setTotalSizes();
void serviceOneStudent();
};
#endif
|
#pragma once
#include "engine/graphics/PhysicsObject.hpp"
#include "engine/audio/AudioSource.hpp"
enum PlayerSpriteType{
HITMAN,
MAN_BLUE,
MAN_BROWN,
MAN_OLD,
ROBOT,
SOLDIER,
SURVIVOR,
WOMAN,
ZOMBIE
};
enum PlayerStanceType{
PISTOL_EQUIPPED,
EMPTY_HANDED,
RIFLE_EQUIPPED,
RELOADING,
OTHER_GUN_EQUIPPED,
STANDING
};
class Player : public KinematicBody{
private:
int dirX;
int dirY;
function <void(int x,int y, int speed, double angle, int damage, ThrowableType type)> spawnFunc;
void shoot(ThrowableType t);
int fireLock = 0;
int xMouse,yMouse;
int health = 100;
void resetRotation();
AudioSource* walkingSounds;
AudioSource* shootingSounds;
AudioSource* emptyMagSounds;
AudioSource* reloadingSounds;
AudioSource* slashingSounds;
void resetAudioSourcePosition();
PlayerSpriteType playerType;
public:
Player(int health, int x, int y, LTexture* pbt,SDL_Rect* pClip,function <void(int x,int y, int speed, double angle, int damage, ThrowableType type)> shootFunc, PlayerSpriteType type, bool IsOther = false);
Inventory* inventory = NULL;
bool isOther = false;
bool isReloading = false;
bool isDead = false;
int getHealth();
ProgressBar* reloadBar = NULL;
void damage(int x);
// send position,velocity and rotation
void sendUpdate(ClientNet* clientObj, ServerNet* serverObj);
void handleEvent( SDL_Event& e);
void resetCamera();
void playSoundIfWalked(bool isListener);
void playThrowableSound(ThrowableType t);
void resetClip();
void stopReloading();
void updateFireLock();
void free();
void stopMovement();
void allowMovement();
};
|
/*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL.
Additionally, 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 Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC 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.
*/
#ifndef MPICache_hpp
#define MPICache_hpp
#include <iostream>
#include <ostream>
#include <stdio.h>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <tuple>
#include <mpi.h>
#include "HCDS.hpp"
#include "Types.hpp"
#include "Constants.hpp"
#include "Pack.hpp"
#include "Data.hpp"
class AbstractDDS {
public:
virtual ~AbstractDDS(){
};
/**
* Hint that you might need a given item in the future. This does not protect the item from
* being purged before it is read.
*/
virtual void prefetch(int dbKey, Label key)=0;
/**
* Get an item. This does not release any reservation.
*/
virtual bool get(int dbKey, Label key, RawDataVector &data)=0;
/**
* Request an item and places a hold so it remains in store until it is released. Return the reservation ID.
*/
virtual uint64_t reserve(int dbKey, Label key)=0;
/**
* Count the number of items with a given key currently in store.
*/
virtual int count(int dbKey, Label key)=0;
/**
* Release a reservation.
*/
virtual bool release(uint64_t id)=0;
/**
* Put an element in the store
*/
virtual void put(int dbKey, Label key, RawDataVector &data)=0;
/**
* Return the keys of the items that are currently available.
*/
virtual std::set<Label> availableKeys(unsigned int dbKey)=0;
virtual void setMaximumBufferSize(uint64_t maxSize)=0;
virtual void serve()=0;
/**
* Perform an iteration of the communication/management layer. This should be constantly called.
*/
virtual int singleServe()=0;
virtual void printStatus()=0;
virtual void sync()=0;
};
#define DDS_GET 1
#define DDS_PREFETCH 2
#define DDS_PUT 3
#endif /* MPICache_hpp */
|
/*******************************************************************************
* filename: C_RandomPatternInitialiser.hpp
* description: Derived class for ranomdly initialising an ideal pattern
* author: Moritz Beber
* created: 2010-06-10
* copyright: Jacobs University Bremen. All rights reserved.
*******************************************************************************
*
******************************************************************************/
#ifndef _C_RANDOMPATTERNINITIALISER_HPP
#define _C_RANDOMPATTERNINITIALISER_HPP
/*******************************************************************************
* Includes
******************************************************************************/
// project
#include "C_PatternInitialiser.hpp"
/*******************************************************************************
* Declarations
******************************************************************************/
namespace rfn {
class RandomPatternInitialiser: public PatternInitialiser {
/* Derived From Singleton Pattern */
DECLARE_DERIVED_SINGLETON(PatternInitialiser, RandomPatternInitialiser)
public:
/* Member Functions */
// ideal pattern initialisation
virtual void init(ParameterManager* const parameters,
Matrix* const pattern);
}; // class RandomPatternInitialiser
} // namespace rfn
#endif // _C_RANDOMPATTERNINITIALISER_HPP
|
/* @author Aytaç Kahveci */
#ifndef KRLSTRUCT_H
#define KRLSTRUCT_H
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <algorithm>
template <class T>
class KRLStruct
{
public:
KRLStruct(){}
KRLStruct(std::vector<std::string> nodes)
{
nodes_ = nodes;
}
~KRLStruct(){}
/**
* The nodes
* @return the name of the variables that this struct contains
*/
std::vector<std::string> getNodes()
{
return nodes_;
}
};
#endif
|
#pragma once
#include <string>
#include "SDL_rect.h"
#include "SDL_pixels.h"
struct SDL_Texture;
class TextureManager;
class Texture
{
private:
SDL_Point size;
SDL_Texture * tex = nullptr;
public:
Texture();
Texture(SDL_Texture * tex);
~Texture();
void load(std::string filename);
void loadpart(std::string filename, SDL_Rect part);
void render(SDL_Point pos);
void render(SDL_Point pos, double theta);
void render(SDL_Point pos, SDL_Point spincenter, double theta);
friend TextureManager;
};
class TextureManager
{
public:
static void destroy();
static Texture * find(std::string name);
static void render(std::string name, SDL_Point pos);
static void render(std::string name, SDL_Point pos, double theta);
static void render(std::string name, SDL_Point pos, SDL_Point spincenter, double theta);
static void makeWord(std::string name, std::string text, std::string fontPath, int fontSize, SDL_Color forecolor, SDL_Color backcolor);
static void load(std::string name, std::string filename);
static void loadpart(std::string name, std::string filename, SDL_Rect part);
static void loadparts(std::string name, std::string filename, SDL_Point partsize, SDL_Point imagesize);
};
|
#pragma once
#include"QInt.h"
class Convert {
public :
static bool* DecToBin(QInt num);
static QInt BinToDec(bool* bin);
static QInt ToBu2(QInt num);
static string QIntToStringNumber(QInt num); //support cho ham xuat
static QInt StringNumberToQInt(string str); // support cho ham nhap
};
|
/* -*- mode: c++; indent-tabs-mode: nil; tab-width: 4; c-file-style: "stroustrup" -*- */
#ifdef ARCHITECTURE_SUPERH
class ES_CodeGenerator
{
public:
ES_CodeGenerator();
enum Condition
{
CONDITION_EQ, // equal (Z=1)
CONDITION_NE, // not equal (Z=0)
CONDITION_CS, // unsigned higher or same (C=1)
CONDITION_CC, // unsigned lower (C=0)
CONDITION_MI, // negative (N=1)
CONDITION_PL, // positive or zero (N=0)
CONDITION_VS, // overflow (V=1)
CONDITION_VC, // not overflow (V=0)
CONDITION_HI, // unsigned higher (C=1 and Z=0)
CONDITION_LS, // unsigned lower or same (C=0 and Z=1)
CONDITION_GE, // greater than or equal (V=N)
CONDITION_LT, // less than (V!=N)
CONDITION_GT, // greater than (Z=0 and V=N)
CONDITION_LE, // less than or equal (Z=1 and V!=N)
CONDITION_AL, // always
CONDITION_NV // never
};
enum Register
{
REG_R0,
REG_R1,
REG_R2,
REG_R3,
REG_R4,
REG_R5,
REG_R6,
REG_R7,
REG_R8,
REG_R9,
REG_R10,
REG_R11,
REG_R12,
REG_R13,
REG_R14,
REG_R15,
REG_SP = REG_R15
};
class Memory
{
public:
enum Type
{
TYPE_PLAIN,
/**< Base register, plain and simple. */
TYPE_AUTO_ADJUST,
/**< Base register is incremented before or decremented after
operation. */
TYPE_R0_ADDED,
/**< R0 is added to base register. */
TYPE_DISPLACEMENT
/**< Immediate displacement. */
};
explicit Memory(ES_CodeGenerator::Register base, Type type = TYPE_PLAIN) : base(base), type(type) {}
explicit Memory(ES_CodeGenerator::Register base, char displacement) : base(base), type(TYPE_DISPLACEMENT), displacement(displacement) {}
private:
friend class ES_CodeGenerator;
ES_CodeGenerator::Register base;
Type type;
int displacement;
};
enum OperandSize
{
OPSIZE_8,
OPSIZE_16,
OPSIZE_32
};
void MOV(char immediate, Register dst);
void MOV(Register src, Register dst);
void MOV(Memory src, Register dst, OperandSize opsize = OPSIZE_32);
void MOV(Register dst, Memory src, OperandSize opsize = OPSIZE_32);
void SUB(Register src, Register dst);
/**< Subtracts 'src' from 'dst' and stores result in 'dst'. */
void JSR(Register dst);
void RTS();
void NOP();
void PushPR(); /**< STS.L PR, @-R15 */
void PopPR(); /**< LDS.L @R15+, PR */
unsigned char *GetBuffer() { return buffer_base; }
unsigned GetBufferUsed() { return buffer - buffer_base; }
private:
void Reserve();
void Write(unsigned short codeword)
{
Reserve();
*buffer++ = codeword & 0xffu;
*buffer++ = (codeword >> 8) & 0xffu;
}
unsigned char *buffer_base, *buffer, *buffer_top;
};
#endif // ARCHITECTURE_SUPERH
|
#ifndef DICTIONNAIRE_H
#define DICTIONNAIRE_H
#include <QMessageBox>
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iterator>
#include <utility>
#include "hiragana.h"
#include "katakana.h"
#include "mot.h"
using std::vector;
using std::multimap;
using std::pair;
using std::iterator;
struct ModeMot
{
enum Enum
{
Hiragana,
Katakana,
Mot
};
};
struct ModeLoupe
{
enum Enum
{
Normal,
LoupeUniquement
};
};
class Dictionnaire
{
protected:
vector< Mot > vecteurHiragana_;
vector< Mot > vecteurHiraganaLoupe_;
vector< Mot > vecteurKatakana_;
vector< Mot > vecteurKatakanaLoupe_;
multimap< string, Mot > multimapMot_;
multimap< string, Mot > multimapMotLoupe_;
vector< Mot > vecteurPasOkHiragana_;
vector< Mot > vecteurPasOkHiraganaLoupe_;
vector< Mot > vecteurPasOkKatakana_;
vector< Mot > vecteurPasOkKatakanaLoupe_;
multimap< string, Mot > multimapPasOkMot_;
multimap< string, Mot > multimapPasOkMotLoupe_;
Mot * motCourant_;
vector< Mot > * ptVecteurCour_;
multimap< string, Mot > * ptMultimapCour_;
vector< Mot > * ptVecteur_;
multimap< string, Mot > * ptMultimap_;
vector< Mot > * ptVecteurPasOk_;
multimap< string, Mot > * ptMultimapPasOk_;
vector< Mot >::iterator iteVecteur_;
multimap< string, Mot >::iterator iteMultimap_;
int aleaPrec_;
bool ajouteLoupe_;
int nbErreur_;
public:
Dictionnaire();
virtual ~Dictionnaire();
void remiseAZero();
void remiseAZeroMot();
void remiseAZeroLoupe();
void ajouterHiragana( const string & inHiraKata, const string & inRoumaji );
void ajouterKatakana( const string & inHiraKata, const string & inRoumaji );
void ajouterMot( const string & inHiraKata, const string & inRoumaji , const vector< string > & inFr );
void ajouterHiragana( Mot & inMot );
void ajouterKatakana( Mot & inMot );
void ajouterMot( Mot & inMot );
void aleaHiragana( ModeLoupe::Enum inModeLoupe, const int inTypeParcours );
void aleaKatakana( ModeLoupe::Enum inModeLoupe, const int inTypeParcours );
void aleaMot( ModeLoupe::Enum inModeLoupe, const int inTypeParcours );
void messageFin();
Mot * nouveauMot( ModeMot::Enum inModeMot, ModeLoupe::Enum inModeLoupe,
const int inTypeParcours, const bool inPrecValide );
int existMulti( vector< string > & inSaisieFr );
void loupe( ModeMot::Enum inModeMot,
const bool inEnregistrLoupe,
unsigned int nbAjout );
unsigned int nbMotLoupes( ModeMot::Enum modeMot ) const;
std::vector< Mot > motLoupes() const;
friend std::ostream & operator<<( std::ostream & o, Dictionnaire & inDictionnaire );
};
#endif
|
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<bits/stdc++.h>
#include<queue>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j,k) for(i=j;i>=k;i--)
#define MAX2(a,b) (a)>(b)?(a):(b)
#define MAX3(a,b,c) (a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c))
#define MIN2(a,b) (a)<(b)?(a):(b)
#define MIN3(a,b,c) (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c))
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector< pair<int,int> > vii;
vector< vi > v(105);
vi out;
int visited[105];
void dfs(int i)
{
int j;
visited[i]=1;
FOR0(j,v[i].size())
{ if(visited[v[i][j]]!=1)
dfs(v[i][j]);
}
out.push_back(i);
}
int main()
{
int i,n,m,a,b;
while(1)
{
cin>>n>>m;
out.clear();
memset(visited,0,sizeof visited);
if(!n)break;
FOR0(i,n)
v[i].clear();
FOR0(i,m)
{
cin>>a>>b;
v[a-1].push_back(b-1);
}
FOR0(i,n)
{
if(visited[i]!=1)
dfs(i);
}
FORD(i,out.size()-1,0)
{cout<<out[i]+1;if(i!=0)cout<<" ";}
cout<<endl;
}
}
|
//easy way to understand sliding but use two hashmaps
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if(s.size() < p.size() || s.size() == 0 || p.size() == 0) return {};
vector<int> pdict(256);
vector<int> sdict(256);
vector<int> indices;
for(char c: p) ++pdict[c];
int start = 0, count = p.size();
for(int i = 0; i < s.size(); ++i){
char c = s[i];
++sdict[c];
if(sdict[c] <= pdict[c]) --count;
if(count == 0) indices.push_back(start);
if(i - start + 1 == p.size()){
char first = s[start];
if(sdict[first] <= pdict[first]) ++count;
--sdict[first];
++start;
}
}
return indices;
}
};
// use only one hashmap
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
if(s.size() < p.size() || s.size() == 0 || p.size() == 0) return {};
vector<int> dict(256);
vector<int> indices;
for(char c: p) ++dict[c];
int start = 0, end = 0, count = p.size();
while(end < s.size()){
if(dict[s[end]] > 0) --count;
--dict[s[end]];
++end;
if(count == 0) indices.push_back(start);
if(end - start == p.size()){
if(dict[s[start]] >= 0) ++count;
++dict[s[start]];
++start;
}
}
return indices;
}
};
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>
#include<string>
using namespace std;
class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
//简化版:递归分治法
vector<int> nums;
vector<char> flag;
vector<int> res;
istringstream s(expression);
int num;
char sign;
s >> num;
nums.push_back(num);
while (s >> sign)
{
flag.push_back(sign);
s >> num;
nums.push_back(num);
}
res=Recursion(nums,flag);
return res;
}
vector<int> Recursion(vector<int> nums,vector<char> flag)
{
vector<int> res;
if(nums.size()==1)
return vector<int>{nums[0]};
for(int i=0;i<flag.size();i++)
{
vector<int> nums1(nums.begin(),nums.begin()+i+1);
vector<int> nums2(nums.begin()+i+1,nums.end());
vector<char> flag1,flag2;
if(i>0)
flag1.insert(flag1.end(),flag.begin(),flag.begin()+i);
if(i<flag.size()-1)
flag2.insert(flag2.end(),flag.begin()+i+1,flag.end());
vector<int> res1,res2;
res1=Recursion(nums1,flag1);
res2=Recursion(nums2,flag2);
for(auto l:res1)
{
for(auto r:res2)
{
if(flag[i]=='+')
res.push_back(l+r);
else if(flag[i]=='-')
res.push_back(l-r);
else if(flag[i]=='*')
res.push_back(l*r);
}
}
}
return res;
}
};
class Solution1 {
public:
vector<int> diffWaysToCompute(string input) {
//基本思想:递归分治法,该问题牵涉到括号的组合问题,一般使用递归分治法。
//解法:碰到运算符号,递归求解前一半的值和后一半的值,然后根据运算符号,计算两者构成的值。
//技巧:使用istringstream提取出数字和运算符保存至num和flag
vector<int> nums;
vector<char> flag;
vector<int> res;
istringstream s(input);
int num;
char sign;
s >> num;
nums.push_back(num);
while (s >> sign)
{
flag.push_back(sign);
s >> num;
nums.push_back(num);
}
res = Recursion(nums,flag);
return res;
}
vector<int> Recursion(vector<int> nums, vector<char> flag)
{
vector<int> res;
//以运算符flag[i]为分割点,分割成前半部分数字nums1运算符flag1和后半部分数字nums2运算符flag2
for (int i = 0; i < flag.size(); i++)
{
vector<int> nums1;
vector<char> flag1;
vector<int> nums2;
vector<char> flag2;
for (int j = 0; j <= i; j++)
nums1.push_back(nums[j]);
for (int j = 0; j < i; j++)
flag1.push_back(flag[j]);
for (int j = i + 1; j < nums.size(); j++)
nums2.push_back(nums[j]);
for (int j = i + 1; j < flag.size(); j++)
flag2.push_back(flag[j]);
//递归求解前一半的值和后一半的值,然后根据运算符号,计算两者构成的值
vector<int> res1 = Recursion(nums1, flag1);
vector<int> res2 = Recursion(nums2, flag2);
for (auto r1 : res1)
{
for (auto r2 : res2)
{
if (flag[i] == '+')
res.push_back(r1 + r2);
else if (flag[i] == '-')
res.push_back(r1 - r2);
else
res.push_back(r1 * r2);
}
}
}
if (flag.empty())
res.push_back(nums[0]);
return res;
}
};
int main()
{
Solution solute;
string input = "2*3-4*5";
vector<int> res = solute.diffWaysToCompute(input);
for_each(res.begin(), res.end(), [](const auto v) {cout << v << endl; });
return 0;
}
|
// Created on: 1995-12-04
// Created by: Christian CAILLET
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XSControl_Utils_HeaderFile
#define _XSControl_Utils_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_CString.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HSequenceOfTransient.hxx>
#include <TColStd_HSequenceOfHAsciiString.hxx>
#include <TColStd_HSequenceOfHExtendedString.hxx>
#include <TopTools_HSequenceOfShape.hxx>
#include <TopAbs_ShapeEnum.hxx>
#include <TColStd_HSequenceOfInteger.hxx>
class Standard_Transient;
class TCollection_HAsciiString;
class TCollection_AsciiString;
class TCollection_HExtendedString;
class TCollection_ExtendedString;
class TopoDS_Shape;
//! This class provides various useful utility routines, to
//! facilitate handling of most common data structures :
//! transients (type, type name ...),
//! strings (ascii or extended, pointed or handled or ...),
//! shapes (reading, writing, testing ...),
//! sequences & arrays (of strings, of transients, of shapes ...),
//! ...
//!
//! Also it gives some helps on some data structures from XSTEP,
//! such as printing on standard trace file, recignizing most
//! currently used auxiliary types (Binder,Mapper ...)
class XSControl_Utils
{
public:
DEFINE_STANDARD_ALLOC
//! the only use of this, is to allow a frontal to get one
//! distinct "Utils" set per separate engine
Standard_EXPORT XSControl_Utils();
//! Just prints a line into the current Trace File. This allows to
//! better characterise the various trace outputs, as desired.
Standard_EXPORT void TraceLine (const Standard_CString line) const;
//! Just prints a line or a set of lines into the current Trace
//! File. <lines> can be a HAscii/ExtendedString (produces a print
//! without ending line) or a HSequence or HArray1 Of ..
//! (one new line per item)
Standard_EXPORT void TraceLines (const Handle(Standard_Transient)& lines) const;
Standard_EXPORT Standard_Boolean IsKind (const Handle(Standard_Transient)& item, const Handle(Standard_Type)& what) const;
//! Returns the name of the dynamic type of an object, i.e. :
//! If it is a Type, its Name
//! If it is a object not a type, the Name of its DynamicType
//! If it is Null, an empty string
//! If <nopk> is False (D), gives complete name
//! If <nopk> is True, returns class name without package
Standard_EXPORT Standard_CString TypeName (const Handle(Standard_Transient)& item, const Standard_Boolean nopk = Standard_False) const;
Standard_EXPORT Handle(Standard_Transient) TraValue (const Handle(Standard_Transient)& list, const Standard_Integer num) const;
Standard_EXPORT Handle(TColStd_HSequenceOfTransient) NewSeqTra() const;
Standard_EXPORT void AppendTra (const Handle(TColStd_HSequenceOfTransient)& seqval, const Handle(Standard_Transient)& traval) const;
Standard_EXPORT Standard_CString DateString (const Standard_Integer yy, const Standard_Integer mm, const Standard_Integer dd, const Standard_Integer hh, const Standard_Integer mn, const Standard_Integer ss) const;
Standard_EXPORT void DateValues (const Standard_CString text, Standard_Integer& yy, Standard_Integer& mm, Standard_Integer& dd, Standard_Integer& hh, Standard_Integer& mn, Standard_Integer& ss) const;
Standard_EXPORT Standard_CString ToCString (const Handle(TCollection_HAsciiString)& strval) const;
Standard_EXPORT Standard_CString ToCString (const TCollection_AsciiString& strval) const;
Standard_EXPORT Handle(TCollection_HAsciiString) ToHString (const Standard_CString strcon) const;
Standard_EXPORT TCollection_AsciiString ToAString (const Standard_CString strcon) const;
Standard_EXPORT Standard_ExtString ToEString (const Handle(TCollection_HExtendedString)& strval) const;
Standard_EXPORT Standard_ExtString ToEString (const TCollection_ExtendedString& strval) const;
Standard_EXPORT Handle(TCollection_HExtendedString) ToHString (const Standard_ExtString strcon) const;
Standard_EXPORT TCollection_ExtendedString ToXString (const Standard_ExtString strcon) const;
Standard_EXPORT Standard_ExtString AsciiToExtended (const Standard_CString str) const;
Standard_EXPORT Standard_Boolean IsAscii (const Standard_ExtString str) const;
Standard_EXPORT Standard_CString ExtendedToAscii (const Standard_ExtString str) const;
Standard_EXPORT Standard_CString CStrValue (const Handle(Standard_Transient)& list, const Standard_Integer num) const;
Standard_EXPORT Standard_ExtString EStrValue (const Handle(Standard_Transient)& list, const Standard_Integer num) const;
Standard_EXPORT Handle(TColStd_HSequenceOfHAsciiString) NewSeqCStr() const;
Standard_EXPORT void AppendCStr (const Handle(TColStd_HSequenceOfHAsciiString)& seqval, const Standard_CString strval) const;
Standard_EXPORT Handle(TColStd_HSequenceOfHExtendedString) NewSeqEStr() const;
Standard_EXPORT void AppendEStr (const Handle(TColStd_HSequenceOfHExtendedString)& seqval, const Standard_ExtString strval) const;
//! Converts a list of Shapes to a Compound (a kind of Shape)
Standard_EXPORT TopoDS_Shape CompoundFromSeq (const Handle(TopTools_HSequenceOfShape)& seqval) const;
//! Returns the type of a Shape : true type if <compound> is False
//! If <compound> is True and <shape> is a Compound, iterates on
//! its items. If all are of the same type, returns this type.
//! Else, returns COMPOUND. If it is empty, returns SHAPE
//! For a Null Shape, returns SHAPE
Standard_EXPORT TopAbs_ShapeEnum ShapeType (const TopoDS_Shape& shape, const Standard_Boolean compound) const;
//! From a Shape, builds a Compound as follows :
//! explores it level by level
//! If <explore> is False, only COMPOUND items. Else, all items
//! Adds to the result, shapes which comply to <type>
//! + if <type> is WIRE, considers free edges (and makes wires)
//! + if <type> is SHELL, considers free faces (and makes shells)
//! If <compound> is True, gathers items in compounds which
//! correspond to starting COMPOUND,SOLID or SHELL containers, or
//! items directly contained in a Compound
Standard_EXPORT TopoDS_Shape SortedCompound (const TopoDS_Shape& shape, const TopAbs_ShapeEnum type, const Standard_Boolean explore, const Standard_Boolean compound) const;
Standard_EXPORT TopoDS_Shape ShapeValue (const Handle(TopTools_HSequenceOfShape)& seqv, const Standard_Integer num) const;
Standard_EXPORT Handle(TopTools_HSequenceOfShape) NewSeqShape() const;
Standard_EXPORT void AppendShape (const Handle(TopTools_HSequenceOfShape)& seqv, const TopoDS_Shape& shape) const;
//! Creates a Transient Object from a Shape : it is either a Binder
//! (used by functions which require a Transient but can process
//! a Shape, such as viewing functions) or a HShape (according to hs)
//! Default is a HShape
Standard_EXPORT Handle(Standard_Transient) ShapeBinder (const TopoDS_Shape& shape, const Standard_Boolean hs = Standard_True) const;
//! From a Transient, returns a Shape.
//! In fact, recognizes ShapeBinder ShapeMapper and HShape
Standard_EXPORT TopoDS_Shape BinderShape (const Handle(Standard_Transient)& tr) const;
Standard_EXPORT Standard_Integer SeqLength (const Handle(Standard_Transient)& list) const;
Standard_EXPORT Handle(Standard_Transient) SeqToArr (const Handle(Standard_Transient)& seq, const Standard_Integer first = 1) const;
Standard_EXPORT Handle(Standard_Transient) ArrToSeq (const Handle(Standard_Transient)& arr) const;
Standard_EXPORT Standard_Integer SeqIntValue (const Handle(TColStd_HSequenceOfInteger)& list, const Standard_Integer num) const;
protected:
private:
};
#endif // _XSControl_Utils_HeaderFile
|
#include "core/pch.h"
#ifdef AUTO_UPDATE_SUPPORT
#ifdef AUTOUPDATE_PACKAGE_INSTALLATION
#include "adjunct/autoupdate/version_checker.h"
#include "adjunct/autoupdate/updater/audatafile_reader.h"
#include "adjunct/autoupdate/updatablefile.h"
VersionChecker::VersionChecker():
m_status(VCSNotInitialized),
m_autoupdate_xml(NULL),
m_status_xml_downloader(NULL),
m_listener(NULL),
m_autoupdate_server_url(NULL)
{
}
VersionChecker::~VersionChecker()
{
OP_DELETE(m_status_xml_downloader);
OP_DELETE(m_autoupdate_server_url);
OP_DELETE(m_autoupdate_xml);
}
OP_STATUS VersionChecker::Init(VersionCheckerListener* listener)
{
if (!listener)
return OpStatus::ERR;
if (m_status != VCSNotInitialized)
return OpStatus::ERR;
m_listener = listener;
m_status = VCSInitFailed;
OpAutoPtr<AutoUpdateXML> autoupdate_xml_guard(OP_NEW(AutoUpdateXML, ()));
OpAutoPtr<StatusXMLDownloader> status_xml_downloader_guard(OP_NEW(StatusXMLDownloader, ()));
OpAutoPtr<AutoUpdateServerURL> autoupdate_server_url_guard(OP_NEW(AutoUpdateServerURL, ()));
RETURN_OOM_IF_NULL(autoupdate_xml_guard.get());
RETURN_OOM_IF_NULL(status_xml_downloader_guard.get());
RETURN_OOM_IF_NULL(autoupdate_server_url_guard.get());
RETURN_IF_ERROR(autoupdate_xml_guard->Init());
RETURN_IF_ERROR(status_xml_downloader_guard->Init(StatusXMLDownloader::CheckTypeOther, this));
RETURN_IF_ERROR(autoupdate_server_url_guard->Init());
RETURN_IF_ERROR(m_data_file_reader.Init());
RETURN_IF_ERROR(m_data_file_reader.Load());
m_autoupdate_xml = autoupdate_xml_guard.release();
m_status_xml_downloader = status_xml_downloader_guard.release();
m_autoupdate_server_url = autoupdate_server_url_guard.release();
if (!CheckIsNeeded())
m_status = VCSCheckNotNeeded;
else
{
RETURN_IF_ERROR(ReadVersionOfExistingUpdate());
m_status = VCSCheckNotPerformed;
}
return OpStatus::OK;
}
OP_STATUS VersionChecker::GetDataFileLastModificationTime(time_t& result)
{
uni_char* updateFile = m_data_file_reader.GetUpdateFile();
RETURN_VALUE_IF_NULL(updateFile, OpStatus::ERR);
OP_STATUS retcode = OpStatus::OK;
OpFile opFile;
retcode = opFile.Construct(updateFile);
if (OpStatus::IsSuccess(retcode))
retcode = opFile.GetLastModified(result);
// AUDataFileReader uses a plain old "new []" to allocate the strings
delete [] updateFile;
return retcode;;
}
bool VersionChecker::CheckIsNeeded()
{
time_t fileModificationTime = 0;
RETURN_VALUE_IF_ERROR(GetDataFileLastModificationTime(fileModificationTime), true);
time_t currentTime = static_cast<UINT32>(g_op_time_info->GetTimeUTC() / 1000.0);
// It can happen when user modified date in the system
if (currentTime < fileModificationTime)
return true;
time_t updateAgeInDays = (currentTime - fileModificationTime) / (60 * 60 * 24);
if (static_cast<unsigned int>(updateAgeInDays) < MaxDownloadedPackageAgeDays)
return false;
return true;
}
OP_STATUS VersionChecker::ReadVersionOfExistingUpdate()
{
uni_char* versionString = m_data_file_reader.GetVersion();
uni_char* buildNumberString = m_data_file_reader.GetBuildNum();
// OperaVersion::Set() will return error if any of the pointers passed to the method is NULL
OP_STATUS result = m_downloaded_version.Set(versionString, buildNumberString);
// AUDataFileReader uses a plain old "new []" to allocate the strings.
delete [] versionString;
delete [] buildNumberString;
return result;
}
OP_STATUS VersionChecker::CheckRemoteVersion()
{
if (m_status != VCSCheckNotPerformed)
return OpStatus::ERR;
OP_ASSERT(m_autoupdate_server_url);
OP_ASSERT(m_autoupdate_xml);
OP_ASSERT(m_status_xml_downloader);
m_status = VCSCheckVersionFailed;
OpString url_string;
OpString8 xml_string;
RETURN_IF_ERROR(m_autoupdate_server_url->GetCurrentURL(url_string));
m_autoupdate_xml->ClearRequestItems();
// RT_Other ensures that this request is not identified as the "main" autoupdate, see DSK-344690
RETURN_IF_ERROR(m_autoupdate_xml->GetRequestXML(xml_string, AutoUpdateXML::UpdateLevelUpgradeCheck, AutoUpdateXML::RT_Other));
RETURN_IF_ERROR(m_status_xml_downloader->StartXMLRequest(url_string, xml_string));
m_status = VCSCheckInProgress;
return OpStatus::OK;
}
void VersionChecker::StatusXMLDownloaded(StatusXMLDownloader* downloader)
{
OP_ASSERT(m_listener);
OP_ASSERT(downloader);
OP_ASSERT(downloader == m_status_xml_downloader);
OP_ASSERT(m_status == VCSCheckInProgress);
UpdatablePackage* package = NULL;
UpdatableResource* resource = downloader->GetFirstResource();
while (resource)
{
if (resource->GetType() == UpdatableResource::RTPackage)
{
package = static_cast<UpdatablePackage*>(resource);
break;
}
resource = downloader->GetNextResource();
}
if (package)
{
OperaVersion package_version;
if (OpStatus::IsError(package->GetPackageVersion(package_version)))
m_status = VCSCheckVersionFailed;
else
{
if (package_version < m_downloaded_version)
m_status = VCSOlderUpdateAvailable;
else if (package_version > m_downloaded_version)
m_status = VCSNewerUpdateAvailable;
else if (package_version == m_downloaded_version)
m_status = VCSSameUpdateAvailable;
else
m_status = VCSCheckVersionFailed;
}
}
else
m_status = VCSNoUpdateAvailable;
m_listener->VersionCheckFinished();
}
void VersionChecker::StatusXMLDownloadFailed(StatusXMLDownloader* downloader, StatusXMLDownloader::DownloadStatus)
{
OP_ASSERT(m_listener);
OP_ASSERT(downloader);
OP_ASSERT(downloader == m_status_xml_downloader);
OP_ASSERT(m_status == VCSCheckInProgress);
m_status = VCSCheckVersionFailed;
m_listener->VersionCheckFinished();
}
#endif // AUTOUPDATE_PACKAGE_INSTALLATION
#endif // AUTO_UPDATE_SUPPORT
|
#include "quadtree.h"
#include <iostream>
#include <algorithm>
using namespace std;
namespace sbg {
}
|
#if 0
#include "stdio.h"
#include "windows.h"
//#include "ipTypes.h"
//#include "windef.h"
#include "ipHlpapi.h"
#include "tchar.h"
#pragma comment(lib,"iphlpapi.lib")
void GetLocalMAC(char * buf);
BOOL IsLocalAdapter(char *pAdapterName);
#define NET_CARD_KEY _T("System\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}")
#define TAR _T("{54E176A1-C087-4B3E-A969-3F4BE379F6C7}\\Connection")
//#define key _T("System\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\{54E176A1-C087-4B3E-A969-3F4BE379F6C7}\\Connection\\PnpInstanceID")
#define rootKey _T("System\\CurrentControlSet\\Control\\Network")
int main_sys(int argc, char* argv[])
{
char mac[1024];
GetLocalMAC(mac);
getchar();
return 1;
}
void GetLocalMAC(char *buf)
{
IP_ADAPTER_INFO *IpAdaptersInfo = NULL;
IP_ADAPTER_INFO *IpAdaptersInfoHead = NULL;
IpAdaptersInfo = (IP_ADAPTER_INFO *)GlobalAlloc(GPTR, sizeof(IP_ADAPTER_INFO));
if (IpAdaptersInfo == NULL)
{
return;
}
DWORD dwDataSize = sizeof(IP_ADAPTER_INFO);
DWORD dwRetVal = GetAdaptersInfo(IpAdaptersInfo, &dwDataSize);
if (ERROR_SUCCESS != dwRetVal)
{
GlobalFree(IpAdaptersInfo);
IpAdaptersInfo = NULL;
if (ERROR_BUFFER_OVERFLOW == dwRetVal)
{
IpAdaptersInfo = (IP_ADAPTER_INFO *)GlobalAlloc(GPTR, dwDataSize);
if (IpAdaptersInfo == NULL)
{
return;
}
if (ERROR_SUCCESS != GetAdaptersInfo(IpAdaptersInfo, &dwDataSize))
{
GlobalFree(IpAdaptersInfo);
return;
}
}
else
{
return;
}
}
//Save the head pointer of IP_ADAPTER_INFO structures list.
IpAdaptersInfoHead = IpAdaptersInfo;
do{
if (IsLocalAdapter(IpAdaptersInfo->AdapterName))
{
sprintf(buf, "%02x-%02x-%02x-%02x-%02x-%02x'\0'",
IpAdaptersInfo->Address[0],
IpAdaptersInfo->Address[1],
IpAdaptersInfo->Address[2],
IpAdaptersInfo->Address[3],
IpAdaptersInfo->Address[4],
IpAdaptersInfo->Address[5]);
printf("buf=%s", buf);
//break;
}
IpAdaptersInfo = IpAdaptersInfo->Next;
} while (IpAdaptersInfo);
if (IpAdaptersInfoHead != NULL)
{
GlobalFree(IpAdaptersInfoHead);
}
}
BOOL IsLocalAdapter(char *pAdapterName)
{
BOOL ret_value = FALSE;
CHAR szDataBuf[20480 + 1];
DWORD dwDataLen = 20480;
DWORD dwType = REG_SZ;
HKEY hNetKey = NULL;
HKEY hLocalNet = NULL;
if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, rootKey, 0, KEY_READ, &hNetKey))
return FALSE;
sprintf(szDataBuf, (LPCSTR)"%s\\Connection", (LPCSTR)pAdapterName);
/*if (ERROR_SUCCESS != RegOpenKeyEx(hNetKey, TAR, 0, KEY_READ, &hLocalNet))
{
RegCloseKey(hNetKey);
return FALSE;
}
if (ERROR_SUCCESS != RegQueryValueEx(hLocalNet, (LPCWSTR) "MediaSubType", 0, &dwType, (BYTE *)szDataBuf, &dwDataLen))
{
goto ret;
}
if (*((DWORD *)szDataBuf) != 0x01)
goto ret;
*/
dwDataLen = 20480;
int result = 0;
BYTE *desBuf=NULL;
IErrorInfo * errorInfo;
result = RegQueryValueEx(hNetKey, _T("Config"), 0, &dwType, desBuf, &dwDataLen);
printf("result=%d", result);
if (ERROR_SUCCESS != result)
{
goto ret;
}
printf("desBuf1=%s\n", desBuf);
if (strncmp((LPSTR)szDataBuf, "PCI", strlen("PCI")))
goto ret;
ret_value = TRUE;
ret:
RegCloseKey(hLocalNet);
RegCloseKey(hNetKey);
return ret_value;
}
#endif
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "utilities/constants.h"
#include "moreinfocomputer.h"
#include "editcomputer.h"
#include "moreinfopioneer.h"
#include "trashbinpioneers.h"
#include "trashbincomputers.h"
#include <QDebug>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow){
ui->setupUi(this);
// Pioneer dropdown lists:
ui->dropdown_pioneers_search_by->addItem("Name");
ui->dropdown_pioneers_search_by->addItem("Birth Year");
ui->dropdown_pioneers_order_by->addItem("Name");
ui->dropdown_pioneers_order_by->addItem("Birth Year");
ui->dropdown_pioneers_order_direction->addItem("Ascending");
ui->dropdown_pioneers_order_direction->addItem("Descending");
ui->dropdown_pioneers_filter_gender->addItem("No filter");
ui->dropdown_pioneers_filter_gender->addItem("Female");
ui->dropdown_pioneers_filter_gender->addItem("Male");
ui->dropdown_pioneers_filter_vital_status->addItem("No filter");
ui->dropdown_pioneers_filter_vital_status->addItem("Alive");
ui->dropdown_pioneers_filter_vital_status->addItem("Deceased");
// Computer dropdown lists:
ui->dropdown_computers_search_by->addItem("Name");
ui->dropdown_computers_search_by->addItem("Build Year");
ui->dropdown_computers_order_by->addItem("Name");
ui->dropdown_computers_order_by->addItem("Build Year");
ui->dropdown_computers_order_direction->addItem("Ascending");
ui->dropdown_computers_order_direction->addItem("Descending");
ui->dropdown_computers_filter_type->addItem("No filter");
ui->dropdown_computers_filter_type->addItem("Mechanical");
ui->dropdown_computers_filter_type->addItem("Electronic");
ui->dropdown_computers_filter_type->addItem("Transistor");
ui->dropdown_computers_filter_type->addItem("Other");
ui->dropdown_computers_filter_built->addItem("No filter");
ui->dropdown_computers_filter_built->addItem("Was built");
ui->dropdown_computers_filter_built->addItem("Was not built");
displayAllPioneers();
displayAllComputers();
}
MainWindow::~MainWindow(){
delete ui;
}
void MainWindow::displayAllPioneers(){
vector<Pioneer> pioneers = pioneerService.printQuery(getCurrentGenderPioneers(), getCurrentVitalStatusPioneers(), getCurrentOrderByPioneers(), getCurrentDirectionPioneers());
displayPioneers(pioneers);
}
void MainWindow::displayAllComputers(){
vector<Computer> computers = computerService.printQuery(getCurrentBuiltComputers(), getCurrentTypeComputers(), getCurrentOrderByComputers(), getCurrentDirectionComputers());
displayComputers(computers);
}
void MainWindow::displayPioneers(std::vector<Pioneer> pioneers){
ui->table_pioneers->clearContents();
ui->table_pioneers->setRowCount(pioneers.size());
if(pioneers.empty()){
disableButtonsForPioneer();
}
for(unsigned int row = 0; row < pioneers.size(); row++){
Pioneer currentPioneer = pioneers[row];
QString name = QString::fromStdString(currentPioneer.getName());
QString birthYear = QString::number(currentPioneer.getByear());
ui->table_pioneers->setItem(row, 0, new QTableWidgetItem(name));
ui->table_pioneers->setItem(row, 1, new QTableWidgetItem(birthYear));
}
currentlyDisplayedPioneers = pioneers;
}
void MainWindow::displayComputers(std::vector<Computer> computers){
ui->table_computers->clearContents();
ui->table_computers->setRowCount(computers.size());
if(computers.empty()){
disableButtonsForComputer();
}
for(unsigned int row = 0; row < computers.size(); row++){
Computer currentComputer = computers[row];
QString buildYear;
QString name = QString::fromStdString(currentComputer.getComputerName());
if(currentComputer.getBuildYear() == 0){
buildYear = QString::fromStdString("Not built");
}
else{
buildYear = QString::number(currentComputer.getBuildYear());
}
ui->table_computers->setItem(row, 0, new QTableWidgetItem(name));
ui->table_computers->setItem(row, 1, new QTableWidgetItem(buildYear));
}
currentlyDisplayedComputers = computers;
}
void MainWindow::on_input_search_pioneers_textChanged(){
string userInput = ui->input_search_pioneers->text().toStdString();
vector<Pioneer> pioneers = pioneerService.search(userInput, getCurrentSearchByPioneers(), getCurrentGenderPioneers(), getCurrentVitalStatusPioneers(), getCurrentOrderByPioneers(),getCurrentDirectionPioneers());
displayPioneers(pioneers);
}
void MainWindow::on_input_search_computers_textChanged(){
string userInput = ui->input_search_computers->text().toStdString();
vector<Computer> computers = computerService.search(userInput, getCurrentSearchByComputers(), getCurrentBuiltComputers(), getCurrentTypeComputers(), getCurrentOrderByComputers(), getCurrentDirectionComputers());
displayComputers(computers);
}
void MainWindow::on_dropdown_pioneers_order_by_currentIndexChanged(int /* unused */){
on_input_search_pioneers_textChanged();
}
void MainWindow::on_dropdown_pioneers_order_direction_currentIndexChanged(int /* unused */){
on_input_search_pioneers_textChanged();
}
void MainWindow::on_dropdown_pioneers_filter_gender_currentIndexChanged(int /* unused */){
on_input_search_pioneers_textChanged();
}
void MainWindow::on_dropdown_pioneers_filter_vital_status_currentIndexChanged(int /* unused */){
on_input_search_pioneers_textChanged();
}
void MainWindow::on_dropdown_computers_order_by_currentIndexChanged(int /* unused */){
on_input_search_computers_textChanged();
}
void MainWindow::on_dropdown_computers_order_direction_currentIndexChanged(int /* unused */){
on_input_search_computers_textChanged();
}
void MainWindow::on_dropdown_computers_filter_type_currentIndexChanged(int /* unused */){
on_input_search_computers_textChanged();
}
void MainWindow::on_dropdown_computers_filter_built_currentIndexChanged(int /* unused */){
on_input_search_computers_textChanged();
}
string MainWindow::getCurrentOrderByPioneers(){
string orderBy = ui->dropdown_pioneers_order_by->currentText().toStdString();
if(orderBy == "Name"){
return constants::NAME;
}
else if(orderBy == "Birth Year"){
return constants::BIRTH_YEAR;
}
else{
return constants::NAME;
}
}
string MainWindow::getCurrentOrderByComputers(){
string orderBy = ui->dropdown_computers_order_by->currentText().toStdString();
if(orderBy == "Name"){
return constants::COMP_NAME;
}
else if(orderBy == "Build Year"){
return constants::BUILD_YEAR;
}
else{
return constants::COMP_NAME;
}
}
string MainWindow::getCurrentDirectionPioneers(){
string direction = ui->dropdown_pioneers_order_direction->currentText().toStdString();
if(direction == "Ascending"){
return constants::ASC;
}
else if(direction == "Descending"){
return constants::DESC;
}
else{
return constants::ASC;
}
}
string MainWindow::getCurrentDirectionComputers(){
string direction = ui->dropdown_computers_order_direction->currentText().toStdString();
if(direction == "Ascending"){
return constants::ASC;
}
else if(direction == "Descending"){
return constants::DESC;
}
else{
return constants::ASC;
}
}
string MainWindow::getCurrentTypeComputers(){
string type = ui->dropdown_computers_filter_type->currentText().toStdString();
if(type == "No filter"){
return "";
}
else if(type == "Mechanical"){
return constants::MECHANICAL;
}
else if(type == "Electronic"){
return constants::ELECTRONIC;
}
else if(type == "Transistor"){
return constants::TRANSISTOR;
}
else if(type == "Other"){
return "other";
}
else{
return "";
}
}
string MainWindow::getCurrentBuiltComputers(){
string built = ui->dropdown_computers_filter_built->currentText().toStdString();
if(built == "No filter"){
return "";
}
else if(built == "Was built"){
return constants::DB_TRUE;
}
else if(built == "Was not built"){
return constants::DB_FALSE;
}
else{
return "";
}
}
string MainWindow::getCurrentSearchByComputers(){
string searchBy = ui->dropdown_computers_search_by->currentText().toStdString();
if(searchBy == "Name"){
return constants::COMP_NAME;
}
else if(searchBy == "Build Year"){
return constants::BUILD_YEAR;
}
else{
return constants::NAME;
}
}
string MainWindow::getCurrentGenderPioneers(){
string gender = ui->dropdown_pioneers_filter_gender->currentText().toStdString();
if(gender == "No filter"){
return "";
}
else if(gender == "Female"){
return constants::FEMALE;
}
else if(gender == "Male"){
return constants::MALE;
}
else{
return "";
}
}
string MainWindow::getCurrentVitalStatusPioneers(){
string vitalStats = ui->dropdown_pioneers_filter_vital_status->currentText().toStdString();
if(vitalStats == "No filter"){
return "";
}
else if(vitalStats == "Alive"){
return constants::IS_NULL;
}
else if(vitalStats == "Deceased"){
return constants::IS_NOT_NULL;
}
else{
return "";
}
}
string MainWindow::getCurrentSearchByPioneers(){
string searchBy = ui->dropdown_pioneers_search_by->currentText().toStdString();
if(searchBy == "Name"){
return constants::NAME;
}
else if(searchBy == "Birth Year"){
return constants::BIRTH_YEAR;
}
else{
return constants::NAME;
}
}
void MainWindow::on_button_pioneer_remove_clicked(){
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Message", "Are you sure?", QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes){
int currentlySelectedPioneerIndex = ui->table_pioneers->currentIndex().row();
Pioneer currentlySelectedPioneer = currentlyDisplayedPioneers[currentlySelectedPioneerIndex];
int pioID = currentlySelectedPioneer.getId();
relationService.removePioneerRelation(pioID);
pioneerService.pioneerToTrash(currentlySelectedPioneer);
ui->input_search_pioneers->setText("");
displayAllPioneers();
disableButtonsForPioneer();
}
else{
return;
}
}
void MainWindow::on_button_computer_remove_clicked(){
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Message", "Are you sure?", QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes){
int currentlySelectedComputerIndex = ui->table_computers->currentIndex().row();
Computer currentlySelectedComputer = currentlyDisplayedComputers[currentlySelectedComputerIndex];
computerService.computerToTrash(currentlySelectedComputer);
ui->input_search_computers->setText("");
displayAllComputers();
disableButtonsForComputer();
}
else{
return;
}
}
void MainWindow::on_table_pioneers_clicked(){
ui->button_pioneer_remove->setEnabled(true);
ui->pushButton_pioneers_more_info->setEnabled(true);
ui->pushButton_pioneers_edit->setEnabled(true);
}
void MainWindow::on_table_computers_clicked(const QModelIndex &/* unused */){
ui->button_computer_remove->setEnabled(true);
ui->pushButton_computers_more_info->setEnabled(true);
ui->pushButton_computers_edit->setEnabled(true);
}
void MainWindow::on_pushButton_pioneers_more_info_clicked(){
int currentlySelectedPioneerIndex = ui->table_pioneers->currentIndex().row();
currentlySelectedPio = currentlyDisplayedPioneers[currentlySelectedPioneerIndex];
MoreInfoPioneer temp;
temp.setPioneer(currentlySelectedPio);
temp.setModal(true);
temp.exec();
}
void MainWindow::on_pushButton_computers_more_info_clicked(){
int currentlySelectedComputerIndex = ui->table_computers->currentIndex().row();
currentlySelectedComp = currentlyDisplayedComputers[currentlySelectedComputerIndex];
MoreInfoComputer temp;
temp.setComputer(currentlySelectedComp);
temp.setModal(true);
temp.exec();
}
Pioneer MainWindow::returnCurrentlySelectedPioneer(){
QString name = QString::fromStdString(currentlySelectedPio.getName());
QString sex = QString::fromStdString(currentlySelectedPio.getSex());
QString birthYear = QString::number(currentlySelectedPio.getByear());
QString deathYear = QString::number(currentlySelectedPio.getDyear());
QString description = QString::fromStdString(currentlySelectedPio.getDescription());
return currentlySelectedPio;
}
Computer MainWindow::returnCurrentlySelectedComputer(){
QString name = QString::fromStdString(currentlySelectedComp.getComputerName());
QString type = QString::fromStdString(currentlySelectedComp.getComputerType());
QString wasbuilt = QString::fromStdString(currentlySelectedComp.getWasItBuilt());
QString dbuildyear = QString::number(currentlySelectedComp.getBuildYear());
QString description = QString::fromStdString(currentlySelectedComp.getComputerDescription());
return currentlySelectedComp;
}
void MainWindow::on_pushButton_pioneers_add_new_entry_clicked(){
AddPioneer addPio;
addPio.displayUnrelatedComputers(currentlyDisplayedComputers);
int returnValue = addPio.exec();
if (returnValue == 1){
displayAllPioneers();
ui->statusBar->showMessage("Pioneer has been added", 2000);
}
else{
ui->statusBar->showMessage("No pioneer was added", 2000);
}
}
void MainWindow::on_pushButton_computers_add_new_entry_clicked(){
addComputer addComp;
addComp.displayUnrelatedPioneers(currentlyDisplayedPioneers);
int returnValue = addComp.exec();
if (returnValue == 1){
displayAllComputers();
ui->statusBar->showMessage("Computer has been added", 2000);
}
else{
ui->statusBar->showMessage("No computer was added", 2000);
}
}
void MainWindow::on_pushButton_pioneers_edit_clicked()
{
int currentlySelectedPioneerIndex = ui->table_pioneers->currentIndex().row();
currentlySelectedPio = currentlyDisplayedPioneers[currentlySelectedPioneerIndex];
editPioneer editPio;
editPio.setPioneer(currentlySelectedPio);
editPio.setModal(true);
int returnValue = editPio.exec();
if (returnValue == 1){
displayAllPioneers();
disableButtonsForPioneer();
ui->statusBar->showMessage("Pioneer has been modified", 2000);
}
else{
ui->statusBar->showMessage("Pioneer has not been modified", 2000);
}
}
void MainWindow::on_pushButton_computers_edit_clicked(){
int currentlySelectedComputerIndex = ui->table_computers->currentIndex().row();
currentlySelectedComp = currentlyDisplayedComputers[currentlySelectedComputerIndex];
editComputer editComp;
editComp.setComputer(currentlySelectedComp);
editComp.setModal(true);
int returnValue2 = editComp.exec();
if (returnValue2 == 1){
displayAllComputers();
disableButtonsForComputer();
ui->statusBar->showMessage("Computer has been modified", 2000);
}
else{
ui->statusBar->showMessage("Computer was not modified", 2000);
}
}
void MainWindow::disableButtonsForPioneer(){
ui->button_pioneer_remove->setEnabled(false);
ui->pushButton_pioneers_more_info->setEnabled(false);
ui->pushButton_pioneers_edit->setEnabled(false);
}
void MainWindow::disableButtonsForComputer(){
ui->button_computer_remove->setEnabled(false);
ui->pushButton_computers_more_info->setEnabled(false);
ui->pushButton_computers_edit->setEnabled(false);
}
void MainWindow::on_trash_button_pioneers_clicked(){
TrashBinPioneers trash;
trash.exec();
displayAllPioneers();
}
void MainWindow::on_trash_button_computers_clicked(){
TrashBinComputers trash;
trash.exec();
displayAllComputers();
}
|
#include <iostream>
using namespace std;
int C;
void Soma()
{ int A, B;
A = 5;
B = 7;
C = A + B;
cout<<(C)<<endl;
}
int main()
{ int A, B;
A = 17;
B = 15;
Soma();
cout<<(A)<<endl;
cout<<(B)<<endl;
}
|
#include <string>
#include <iostream>
using namespace std;
int num_vk(const string &str)
{
int res=0;
for(unsigned int i=0; i<str.size()-1; ++i)
if(str[i]=='V' && str[i+1]=='K')
++res;
return res;
}
int main()
{
string str;
cin >> str;
int temp;
char temp_ch;
int largest=num_vk(str);
for(unsigned int i=0; i<str.size(); ++i)
{
temp_ch=str[i];
if(str[i]=='V')
str[i]='K';
else str[i]='V';
temp=num_vk(str);
if(temp>largest)
largest=temp;
str[i]=temp_ch;
}
cout << largest << endl;
return 0;
}
|
// Created by: Kirill GAVRILOV
// Copyright (c) 2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _OpenGl_BufferCompatT_HeaderFile
#define _OpenGl_BufferCompatT_HeaderFile
#include <NCollection_Buffer.hxx>
#include <OpenGl_Buffer.hxx>
//! Compatibility layer for old OpenGL without VBO.
//! Make sure to pass pointer from GetDataOffset() instead of NULL.
//! Method GetDataOffset() returns pointer to real data in this class
//! (while base class OpenGl_VertexBuffer always return NULL).
//!
//! Methods Bind()/Unbind() do nothing (do not affect OpenGL state)
//! and ::GetTarget() is never used.
//! For this reason there is no analog for OpenGl_IndexBuffer.
//! Just pass GetDataOffset() to glDrawElements() directly as last argument.
//!
//! Class overrides methods init() and subData() to copy data into own memory buffer.
//! Extra method initLink() might be used to pass existing buffer through handle without copying the data.
//!
//! Method Create() creates dummy identifier for this object which should NOT be passed to OpenGL functions.
template<class BaseBufferT>
class OpenGl_BufferCompatT : public BaseBufferT
{
public:
//! Create uninitialized VBO.
OpenGl_BufferCompatT()
{
//
}
//! Destroy object.
virtual ~OpenGl_BufferCompatT()
{
Release (NULL);
}
//! Return TRUE.
virtual bool IsVirtual() const Standard_OVERRIDE { return true; }
//! Creates VBO name (id) if not yet generated.
//! Data should be initialized by another method.
inline bool Create (const Handle(OpenGl_Context)& theGlCtx) Standard_OVERRIDE;
//! Destroy object - will release memory if any.
inline virtual void Release (OpenGl_Context* theGlCtx) Standard_OVERRIDE;
//! Bind this VBO.
virtual void Bind (const Handle(OpenGl_Context)& ) const Standard_OVERRIDE
{
//
}
//! Unbind this VBO.
virtual void Unbind (const Handle(OpenGl_Context)& ) const Standard_OVERRIDE
{
//
}
public: //! @name advanced methods
//! Initialize buffer with existing data.
//! Data will NOT be copied by this method!
inline bool initLink (const Handle(NCollection_Buffer)& theData,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const unsigned int theDataType);
//! Initialize buffer with new data (data will be copied).
inline virtual bool init (const Handle(OpenGl_Context)& theGlCtx,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const void* theData,
const unsigned int theDataType,
const Standard_Integer theStride) Standard_OVERRIDE;
//! Update part of the buffer with new data.
inline virtual bool subData (const Handle(OpenGl_Context)& theGlCtx,
const Standard_Integer theElemFrom,
const Standard_Integer theElemsNb,
const void* theData,
const unsigned int theDataType) Standard_OVERRIDE;
//! Read back buffer sub-range.
inline virtual bool getSubData (const Handle(OpenGl_Context)& theGlCtx,
const Standard_Integer theElemFrom,
const Standard_Integer theElemsNb,
void* theData,
const unsigned int theDataType) Standard_OVERRIDE;
protected:
Handle(NCollection_Buffer) myData; //!< buffer data
};
// =======================================================================
// function : Create
// purpose :
// =======================================================================
template<class BaseBufferT>
bool OpenGl_BufferCompatT<BaseBufferT>::Create (const Handle(OpenGl_Context)& )
{
if (BaseBufferT::myBufferId == OpenGl_Buffer::NO_BUFFER)
{
BaseBufferT::myBufferId = (unsigned int )-1; // dummy identifier...
myData = new NCollection_Buffer (Graphic3d_Buffer::DefaultAllocator());
}
return BaseBufferT::myBufferId != OpenGl_Buffer::NO_BUFFER;
}
// =======================================================================
// function : Release
// purpose :
// =======================================================================
template<class BaseBufferT>
void OpenGl_BufferCompatT<BaseBufferT>::Release (OpenGl_Context* )
{
if (BaseBufferT::myBufferId == OpenGl_Buffer::NO_BUFFER)
{
return;
}
BaseBufferT::myOffset = NULL;
BaseBufferT::myBufferId = OpenGl_Buffer::NO_BUFFER;
myData.Nullify();
}
// =======================================================================
// function : initLink
// purpose :
// =======================================================================
template<class BaseBufferT>
bool OpenGl_BufferCompatT<BaseBufferT>::initLink (const Handle(NCollection_Buffer)& theData,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const unsigned int theDataType)
{
if (theData.IsNull())
{
BaseBufferT::myOffset = NULL;
return false;
}
if (BaseBufferT::myBufferId == OpenGl_Buffer::NO_BUFFER)
{
BaseBufferT::myBufferId = (unsigned int )-1; // dummy identifier...
}
myData = theData;
BaseBufferT::myDataType = theDataType;
BaseBufferT::myComponentsNb = theComponentsNb;
BaseBufferT::myElemsNb = theElemsNb;
BaseBufferT::myOffset = myData->ChangeData();
return true;
}
// =======================================================================
// function : init
// purpose :
// =======================================================================
template<class BaseBufferT>
bool OpenGl_BufferCompatT<BaseBufferT>::init (const Handle(OpenGl_Context)& theCtx,
const unsigned int theComponentsNb,
const Standard_Integer theElemsNb,
const void* theData,
const unsigned int theDataType,
const Standard_Integer theStride)
{
if (!Create (theCtx))
{
BaseBufferT::myOffset = NULL;
return false;
}
BaseBufferT::myDataType = theDataType;
BaseBufferT::myComponentsNb = theComponentsNb;
BaseBufferT::myElemsNb = theElemsNb;
const size_t aNbBytes = size_t(BaseBufferT::myElemsNb) * theStride;
if (!myData->Allocate (aNbBytes))
{
BaseBufferT::myOffset = NULL;
return false;
}
BaseBufferT::myOffset = myData->ChangeData();
if (theData != NULL)
{
memcpy (myData->ChangeData(), theData, aNbBytes);
}
return true;
}
// =======================================================================
// function : subData
// purpose :
// =======================================================================
template<class BaseBufferT>
bool OpenGl_BufferCompatT<BaseBufferT>::subData (const Handle(OpenGl_Context)& ,
const Standard_Integer theElemFrom,
const Standard_Integer theElemsNb,
const void* theData,
const unsigned int theDataType)
{
if (!BaseBufferT::IsValid() || BaseBufferT::myDataType != theDataType
|| theElemFrom < 0 || ((theElemFrom + theElemsNb) > BaseBufferT::myElemsNb))
{
return false;
}
else if (theData == NULL)
{
return true;
}
const size_t aDataSize = BaseBufferT::sizeOfGlType (theDataType);
const size_t anOffset = size_t(theElemFrom) * size_t(BaseBufferT::myComponentsNb) * aDataSize;
const size_t aNbBytes = size_t(theElemsNb) * size_t(BaseBufferT::myComponentsNb) * aDataSize;
memcpy (myData->ChangeData() + anOffset, theData, aNbBytes);
return true;
}
// =======================================================================
// function : getSubData
// purpose :
// =======================================================================
template<class BaseBufferT>
bool OpenGl_BufferCompatT<BaseBufferT>::getSubData (const Handle(OpenGl_Context)& ,
const Standard_Integer theElemFrom,
const Standard_Integer theElemsNb,
void* theData,
const unsigned int theDataType)
{
if (!BaseBufferT::IsValid() || BaseBufferT::myDataType != theDataType
|| theElemFrom < 0 || ((theElemFrom + theElemsNb) > BaseBufferT::myElemsNb)
|| theData == NULL)
{
return false;
}
const size_t aDataSize = BaseBufferT::sizeOfGlType (theDataType);
const size_t anOffset = size_t(theElemFrom) * size_t(BaseBufferT::myComponentsNb) * aDataSize;
const size_t aNbBytes = size_t(theElemsNb) * size_t(BaseBufferT::myComponentsNb) * aDataSize;
memcpy (theData, myData->Data() + anOffset, aNbBytes);
return true;
}
#endif // _OpenGl_VertexBufferCompat_HeaderFile
|
#ifndef CLOGGER_H
#define CLOGGER_H
#include"cMap.h"
#include <vector>
#include <unordered_map>
#include"searchresult.h"
class cLogger
{
public:
float loglevel;
public:
cLogger();
virtual ~cLogger();
virtual bool getLog(const char* FileName) = 0;
virtual void saveLog() = 0;
virtual void writeToLogSummary(const SearchResult &sr)=0;
virtual void writeToLogPath(const SearchResult &sresult)=0;
virtual void writeToLogMap(const cMap &map, const SearchResult &sresult)=0;
virtual void writeToLogOpenClose(const std::vector<Node> &open, const std::vector<Node>& close)=0;
};
#endif
|
#include <sdl/window>
#include <sdl/renderer>
#include <SDL2/SDL_render.h>
#define LOG(...) fprintf(stdout, __VA_ARGS__)
namespace sdl {
namespace detail {
renderer::renderer(const window &_w):
id(0), flags(0), w(_w) {
}
renderer::~renderer() {
LOG("Destroy renderer %p\n", id);
SDL_DestroyRenderer(static_cast<SDL_Renderer*>(id));
}
renderer &renderer::software() {
flags |= SDL_RENDERER_SOFTWARE;
return *this;
}
renderer& renderer::accelerated() {
flags |= SDL_RENDERER_ACCELERATED;
return *this;
}
renderer& renderer::vsync() {
flags |= SDL_RENDERER_PRESENTVSYNC;
return *this;
}
renderer& renderer::target_texture() {
flags |= SDL_RENDERER_TARGETTEXTURE;
return *this;
}
renderer& renderer::create() {
id = SDL_CreateRenderer(static_cast<SDL_Window*>(w.id), -1, flags);
LOG("Create renderer %p\n", id);
return *this;
}
renderer& renderer::clear() {
SDL_RenderClear(static_cast<SDL_Renderer*>(id));
return *this;
}
renderer& renderer::present() {
SDL_RenderPresent(static_cast<SDL_Renderer*>(id));
return *this;
}
renderer& renderer::draw_color(const color &c) {
SDL_SetRenderDrawColor(static_cast<SDL_Renderer*>(id), c.r, c.g, c.b, c.a);
return *this;
}
renderer& renderer::draw_point(const point &pt) {
SDL_RenderDrawPoint(static_cast<SDL_Renderer*>(id), pt.x, pt.y);
return *this;
}
renderer& renderer::draw_line(const point &pt1, const point &pt2) {
SDL_RenderDrawLine(static_cast<SDL_Renderer*>(id), pt1.x, pt1.y, pt2.x, pt2.y);
return *this;
}
renderer& renderer::draw_rect(const rect &rc, const bool fill) {
if (fill)
SDL_RenderFillRect(static_cast<SDL_Renderer*>(id), reinterpret_cast<const SDL_Rect *>(&rc));
else
SDL_RenderDrawRect(static_cast<SDL_Renderer*>(id), reinterpret_cast<const SDL_Rect *>(&rc));
return *this;
}
} // namespace detail
} // namespace sdl
|
#ifndef MYQGRAPHICSVIEW_H
#define MYQGRAPHICSVIEW_H
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsEllipseItem>
#include <QMouseEvent>
#define PLANE_WIDTH 10
#define PLANE_HEIGHT 10
class MyQGraphicsView : public QGraphicsView
{
Q_OBJECT
public:
explicit MyQGraphicsView(QWidget *parent = 0);
QGraphicsScene *scene;
void StartGame(QGraphicsScene *scene, QGraphicsView *graphicsView, QFile *file);
void ChooseLevel(QGraphicsScene *scene, QGraphicsView *graphicsView);
void BackToGame(QGraphicsScene *scene, QGraphicsView *graphicsView);
void Completed();
signals:
void signal_moveToNextPosition();
public slots:
void mousePressEvent(QMouseEvent * e);
void mouseReleaseEvent(QMouseEvent *e);
//void mouseDoubleClickEvent(QMouseEvent * e);
void mouseMoveEvent(QMouseEvent * e);
void keyPressEvent(QKeyEvent *e);
void slot_timerOut();
};
#endif // MYQGRAPHICSVIEW_H
|
constexpr size_t kNumChars = '~' - ' ' + 1;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
std::array<int, kNumChars> last_seen;
for (int& x : last_seen) {
x = -1; // -1 signals unset.
}
int best = 0;
int begin = -1;
for (int i = 0; i < s.size(); ++i) {
size_t c_idx = s[i] - ' ';
assert(c_idx < last_seen.size());
if (last_seen[c_idx] != -1 && last_seen[c_idx] > begin) {
begin = last_seen[c_idx];
}
last_seen[c_idx] = i;
int l = i - begin;
if (l > best) {
best = l;
}
}
return best;
}
};
|
#ifndef HEAP_H
#define HEAP_H
#include "vertex_info.h"
#include <iostream>
#include <climits>
#include <utility>
#define INF 100000000
using namespace std;
typedef unsigned long ulong;
class gomila
{
pair<ulong,vertex_info> *elems; // first -> key; second -> value
ulong *key_mapping;
ulong max_velicina;
ulong velicina;
gomila(const gomila&);
gomila& operator=(const gomila&);
public:
gomila(ulong num_of_keys, vertex_info *values);
~gomila();
void napravi_gomilu();
pair<ulong,vertex_info> najmanji_element() { return elems[0]; }
void ukloni_najmanji();
void dodaj_element(ulong key, vertex_info value);
void azuriraj_vrijednost(ulong key, vertex_info new_value);
ulong parent(ulong indeks) { return (indeks-1)/2; }
ulong left_child(ulong indeks) { return 2*indeks + 1; }
ulong right_child(ulong indeks) { return 2*indeks + 2; }
bool has_parent(ulong indeks) { return indeks>0; }
bool has_left_child(ulong indeks) { return 2*indeks + 1 < velicina; }
bool has_right_child(ulong indeks) { return 2*indeks + 1 < velicina; }
bool is_root(ulong indeks) { return indeks==0; }
bool is_leaf(ulong indeks) { return indeks >= velicina/2; }
void up_heap(ulong indeks);
void down_heap(ulong indeks);
void swap_nodes(ulong indeks1, ulong indeks2);
pair<ulong,vertex_info>* vrati_pocetak() { return elems; }
ulong vrati_broj_elemenata() { return velicina; }
bool is_empty() { return velicina==0; }
ulong get_value(ulong indeks) { return elems[key_mapping[indeks]].second.value; }
ulong get_priority(ulong indeks) { return elems[key_mapping[indeks]].second.priority; }
ulong get_wanted_nodes(ulong indeks) { return elems[key_mapping[indeks]].second.wanted_nodes; }
vertex_info get_vertex_info(ulong indeks) { return elems[key_mapping[indeks]].second; }
void ispisi();
void foo();
string toString();
};
#endif // HEAP_H
|
#include "SignIn.h"
SignIn::SignIn(){
user_list=new User[Max];
count=0;
}
SignIn::SignIn(ifstream& infile){
infile.open("user_record.txt");
while(!infile){
infile.close();
cout<<"用户记录不存在!"<<endl;
string file_name;
cout<<"模拟登陆的用户记录文件路径为?";
getline(cin,file_name);
infile.open(file_name.c_str());
}
count=0;
string user_name,user_key;
user_list=new User[Max];
while(infile){
infile>>user_name;
infile>>user_key;
user_list[count].assign(user_name,user_key);
count++;
}
infile.close();
}
bool SignIn::recordFileRead(ifstream& infile){
infile.open("user_record.txt");
if(!infile){
infile.close();
cout<<"用户记录不存在!"<<endl;
return false;
}
count=0;
string user_name,user_key;
user_list=new User[Max];
while(infile){
infile>>user_name;
infile>>user_key;
user_list[count].assign(user_name,user_key);
count++;
}
infile.close();
return true;
}
bool SignIn::checkPresent(const User& new_user,int& position){
bool check_name, check_key;
for(int i=0;i<count;i++){
check_name = user_list[i].user_name == new_user.user_name;
check_key = user_list[i].user_key == new_user.user_key;
if(check_name&&check_key){
position=i;
return true;
}
}
return false;
}
Error_code SignIn::creatUser(const User& new_user){
if(count==Max){
return recordOverflow;
}
bool whether_present;
int position;
whether_present=checkPresent(new_user,position);
if(!whether_present){
user_list[count].assign(new_user.user_name,new_user.user_key);
count++;
return success;
}
else{
return alreadyPresent;
}
}
Error_code SignIn::deleteUser(const User& target_user){
if(count==0){
return recordUnderflow;
}
bool whether_present;
int position;
whether_present=checkPresent(target_user,position);
if(whether_present){
for(int i=position;i<count-1;i++){
user_list[i]=user_list[i+1];
}
count--;
return success;
}
else{
return notPresent;
}
}
Error_code SignIn::replaceUser(const User& target_user,const User& new_user){
if(count==0){
return recordUnderflow;
}
bool whether_present;
int position;
whether_present=checkPresent(target_user,position);
if(whether_present){
user_list[position].user_name=new_user.user_name;
user_list[position].user_key=new_user.user_key;
return success;
}
else{
return notPresent;
}
}
Error_code SignIn::loadIn(const User& target_user){
if(count==0){
return recordUnderflow;
}
bool whether_present;
int position;
whether_present=checkPresent(target_user,position);
if(whether_present){
if(user_list[position].user_key==target_user.user_key){
return success;
}
else{
return wrongPassword;
}
}
else{
return notPresent;
}
}
SignIn::~SignIn(){
delete[] user_list;
}
|
#include <iberbar/Lua/LuaDevice.h>
#include <iberbar/Lua/LuaCallback.h>
#include <iberbar/Lua/LoggingHelper.h>
#include <luaconf.h>
using namespace iberbar::Lua;
namespace iberbar
{
namespace Lua
{
CLuaDevice* g_pUniqueLuaDevice = nullptr;
}
}
iberbar::CLuaDevice::CLuaDevice()
: CRef()
, m_pLuaState( nullptr )
{
g_pUniqueLuaDevice = this;
}
iberbar::CLuaDevice::~CLuaDevice()
{
if ( m_pLuaState != nullptr )
{
lua_close( m_pLuaState );
m_pLuaState = nullptr;
}
g_pUniqueLuaDevice = nullptr;
}
void iberbar::CLuaDevice::Initial()
{
m_pLuaState = luaL_newstate();
luaL_openlibs( m_pLuaState );
//lua_pushcfunction( m_pLuaState, luaopen_io );
//lua_pushstring( m_pLuaState, LUA_IOLIBNAME );
//lua_pcall( m_pLuaState, 1, 0, 0 );
// 开启Lua回调模式
lua_pushstring( m_pLuaState, Lua::RefId_Mapping_Function );
lua_newtable( m_pLuaState );
lua_rawset( m_pLuaState, LUA_REGISTRYINDEX );
#ifdef _DEBUG
lua_newtable( m_pLuaState );
lua_setglobal( m_pLuaState, Lua::RefId_Mapping_Function_ExtParams );
#else
lua_pushstring( m_pLuaState, Lua::RefId_Mapping_Function_ExtParams );
lua_newtable( m_pLuaState );
lua_rawset( m_pLuaState, LUA_REGISTRYINDEX );
#endif
}
void iberbar::CLuaDevice::AddLuaPath( const char* path )
{
lua_getglobal( m_pLuaState, "package" );
lua_getfield( m_pLuaState, -1, "path" ); // get field "path" from table at top of stack (-1)
std::string cur_path = lua_tostring( m_pLuaState, -1 ); // grab path string from top of stack
cur_path.append( ";" ); // do your path magic here
cur_path.append( path );
lua_pop( m_pLuaState, 1 ); // get rid of the string on the stack we just pushed on line 5
lua_pushstring( m_pLuaState, cur_path.c_str() ); // push the new one
lua_setfield( m_pLuaState, -2, "path" ); // set the field "path" in table at -2 with value at top of stack
lua_pop( m_pLuaState, 1 ); // get rid of package table from top of stack
}
iberbar::CResult iberbar::CLuaDevice::ExecuteFile( const char* strFile )
{
const char* err = nullptr;
int nRet;
nRet = luaL_loadfile( m_pLuaState, strFile );
if ( nRet != 0 )
{
int type = lua_type( m_pLuaState, -1 );
err = lua_tostring( m_pLuaState, -1 );
Lua::CLoggingHelper::sLog( Logging::ULevel::Error, err );
lua_pop( m_pLuaState, 1 );
return MakeResult( ResultCode::Bad, err );
}
nRet = lua_pcall( m_pLuaState, 0, 0, 0 );
if ( nRet != 0 )
{
int type = lua_type( m_pLuaState, -1 );
err = lua_tostring( m_pLuaState, -1 );
Lua::CLoggingHelper::sLog( Logging::ULevel::Error, err );
//lua_pop( m_pLuaState, 1 );
lua_pop( m_pLuaState, 2 );
return MakeResult( ResultCode::Bad, err );
}
//lua_getglobal( m_pLuaState, "Main" );
//if ( lua_isfunction( m_pLuaState, -1 ) == false )
//{
// lua_pop( m_pLuaState, 1 );
//}
//else
//{
// int functionIndex = lua_gettop( m_pLuaState );
// int traceCallback = 0;
// lua_getglobal( m_pLuaState, "__G__TRACKBACK__" ); /* L: ... func arg1 arg2 ... G */
// if ( !lua_isfunction( m_pLuaState, -1 ) )
// {
// lua_pop( m_pLuaState, 1 ); /* L: ... func arg1 arg2 ... */
// }
// else
// {
// lua_rotate( m_pLuaState, functionIndex, 1 ); /* L: ... G func arg1 arg2 ... */
// traceCallback = functionIndex;
// }
// nRet = lua_pcall( m_pLuaState, 0, 0, traceCallback );
// if ( nRet != 0 )
// {
// int type = lua_type( m_pLuaState, -1 );
// err = lua_tostring( m_pLuaState, -1 );
// Lua::CLoggingHelper::sLog( Logging::ULevel::Error, err );
// //lua_pop( m_pLuaState, 1 );
// lua_pop( m_pLuaState, 2 );
// return MakeResult( ResultCode::Bad, err );
// }
//}
return CResult();
}
iberbar::CResult iberbar::CLuaDevice::ExecuteSource( const char* strSource )
{
const char* err = nullptr;
if ( luaL_dostring( m_pLuaState, strSource ) )
{
err = lua_tostring( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return MakeResult( ResultCode::Bad, err );
}
return CResult();
}
//void iberbar::CLuaDevice::ExecuteFunction( int nArgs )
//{
// int nFunctionIndex = -(nArgs+1);
// if ( lua_isfunction( m_pLuaState, nFunctionIndex ) == false )
// {
// lua_pop( m_pLuaState, 1 );
// return;
// }
//
// int nTraceCallback = 0;
// lua_getglobal( m_pLuaState, "__G__TRACKBACK__" );
// if ( !lua_isfunction( m_pLuaState, -1 ) )
// {
// lua_pop( m_pLuaState, 1 );
// }
// else
// {
// lua_rotate( m_pLuaState, nFunctionIndex, 1 );
// nTraceCallback = nFunctionIndex;
// }
// int nRet = lua_pcall( m_pLuaState, nArgs, 0, nTraceCallback );
// if ( nRet != 0 )
// {
// if ( nTraceCallback == 0 )
// {
// int type = lua_type( m_pLuaState, -1 );
// const char* err = lua_tostring( m_pLuaState, -1 );
// Lua::CLoggingHelper::sLog( Logging::ULevel::Error, err );
// lua_pop( m_pLuaState, 1 );
// }
// else
// {
// lua_pop( m_pLuaState, 2 );
// }
// }
//}
iberbar::CLuaDevice* iberbar::Lua::GetLuaDevice( lua_State* pLuaState )
{
if ( g_pUniqueLuaDevice && g_pUniqueLuaDevice->GetLuaState() == pLuaState )
return g_pUniqueLuaDevice;
return nullptr;
}
|
void initMQTT()
{
MQTT.setServer(BROKER_MQTT, BROKER_PORT);
MQTT.setCallback(mqtt_callback);
}
void mqtt_callback(char* topic, byte* payload, unsigned int length){
String msg;
//obtem a string do payload recebido
for(int i = 0; i < length; i++) {
char c = (char)payload[i];
msg += c;
}
StringSplitter *splitter = new StringSplitter(msg, ',', 3); // new StringSplitter(string_to_split, delimiter, limit)
int itemCount = splitter->getItemCount();
//Serial.println("Item count: " + String(itemCount));
String item[itemCount];
for(int i = 0; i < itemCount; i++){
item[i] = splitter->getItemAtIndex(i);
//Serial.println("Item @ index " + String(i) + ": " + String(item));
}
int pwmRed = map(item[0].toInt(),0,1023,0,255);
int pwmGreen = map(item[1].toInt(),0,1023,0,255);
int pwmBlue = map(item[2].toInt(),0,1023,0,255);
Serial.print("Mensagem Recebida: ");
Serial.println(msg);
Serial.print("RGB: ");
Serial.println(String(pwmRed) +","+String(pwmGreen)+ "," +String(pwmBlue));
setColor(pwmRed, pwmGreen, pwmBlue);
}
|
#ifndef __REPORTMODEL_H
#define __REPORTMODEL_H
#include "globaldata.h"
#include "ReportData.h"
#include "IModelWindow.h"
namespace wh{
//-----------------------------------------------------------------------------
class ReportModel : public IModelWindow
{
wxString mRepId;
sig::scoped_connection connListItemChange;
sig::scoped_connection connListItemRemove;
sig::scoped_connection connListItemUpdate;
rec::ReportTable mReportTable;
void DoUpdateView();
void BuildFilterTable(rec::ReportFilterTable& ft);
public:
ReportModel(const std::shared_ptr<wxString>& rep_id);
void Update();
void Execute(const std::vector<wxString>& filter_vec);
void Export();
sig::signal<void(const rec::ReportTable&)> sigExecuted;
sig::signal<void(const rec::ReportFilterTable&)> sigSetFilterTable;
sig::signal<void(const wxString&)> sigSetNote;
// IModelWindow
virtual void UpdateTitle()override;
virtual void Show()override;
virtual void Load(const boost::property_tree::wptree& page_val)override;
virtual void Save(boost::property_tree::wptree& page_val)override;
};
//---------------------------------------------------------------------------
} //namespace mvp{
#endif // __IMVP_H
|
#pragma once
#include "Block.h"
#include "rectangularvectors.h"
namespace WinTetris
{
class Square : public Block
{
public:
Square();
void Rotate() override;
};
}
|
#include <iostream>
using namespace std;
class batsman{
public:
int runs;
void set_runs(int r){
runs = r;
}
};
class kohli:public batsman
{
public:
void get_runs(){
cout << "Kohli scored :" << runs << endl;
}
};
class Dhoni:public batsman
{
public:
void get_runs(){
cout << "Dhoni scored :" << runs << endl;
}
};
int main(){
kohli k;
Dhoni D;
batsman *obj1 = &k;
batsman *obj2 = &D;
obj1 -> set_runs(10);
obj2 -> set_runs(100);
k.get_runs();
D.get_runs();
}
|
#include "collisiontester.h"
using namespace std;
|
#include "ImagePicker.h"
#ifdef Q_OS_ANDROID
#include <QAndroidJniEnvironment>
#include <QAndroidJniObject>
#include <QtAndroid>
#endif
namespace wpp {
namespace qt {
#ifndef Q_OS_IOS
ImagePicker::ImagePicker(QQuickItem *parent)
: QQuickItem(parent),
m_maxPick(-1),
m_delegate(0)
{
}
void ImagePicker::open()
{
#ifdef Q_OS_ANDROID
//if ( maxPick() != 1 )
{
/*
https://github.com/lovetuzitong/MultiImageSelector
// For multiple images
private static final RESULT_CODE_PICKER_IMAGES = 9000;
//Intent intent = new Intent(this, com.giljulio.imagepicker.ui.ImagePickerActivity.class);
Intent intent = new Intent(this); //this是当前activity
intent.setClassName("com.giljulio.imagepicker.ui", "ImagePickerActivity" );
// whether show camera
intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
// max select image amount
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
// select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
startActivityForResult(intent, RESULT_CODE_PICKER_IMAGES);
https://github.com/donglua/PhotoPicker
PhotoPickerIntent intent = new PhotoPickerIntent(MainActivity.this);
intent.setPhotoCount(9);
intent.setShowCamera(true);
startActivityForResult(intent, REQUEST_CODE);
*/
QAndroidJniObject activity = QtAndroid::androidActivity();
qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid();
//QAndroidJniObject Action__ACTION_MULTIPLE_PICK = QAndroidJniObject::getStaticObjectField(
// "com/luminous/pick/Action", "ACTION_MULTIPLE_PICK", "Ljava/lang/String;");
//qDebug() << __FUNCTION__ << "Action__ACTION_MULTIPLE_PICK.isValid()=" << Action__ACTION_MULTIPLE_PICK.isValid();
//QAndroidJniObject clsObj = activity.callObjectMethod("getClass","()Ljava/lang/Class;");
//qDebug() << __FUNCTION__ << "clsObj.isValid()=" << clsObj.isValid();
QAndroidJniEnvironment env;
//QAndroidJniObject clsObj( env->FindClass("com/giljulio/imagepicker/ui/ImagePickerActivity") );
//qDebug() << __FUNCTION__ << "clsObj.isValid()=" << clsObj.isValid();
//jclass cls = env->FindClass("com/giljulio/imagepicker/ui/ImagePickerActivity");
//qDebug() << __FUNCTION__ << "clsObj=" << (void*)cls;
//QAndroidJniObject ImagePickerActivity__class = QAndroidJniObject::getStaticObjectField(
// "java/lang/Class", "class", "Lcom/giljulio/imagepicker/ui/ImagePickerActivity;");
//qDebug() << __FUNCTION__ << "ImagePickerActivity__class.isValid()=" << ImagePickerActivity__class.isValid();
//QAndroidJniObject intent=QAndroidJniObject("android/content/Intent","()V");
//qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid();
QAndroidJniObject intent=QAndroidJniObject("me/iwf/photopicker/utils/PhotoPickerIntent","(Landroid/content/Context;)V",
activity.object<jobject>());
qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid();
/*QAndroidJniObject packageName = activity.callObjectMethod("getPackageName","()Ljava/lang/String;");
qDebug() << "packageName.isValid=" << packageName.isValid();
qDebug() << "packageName=" << packageName.toString();
QAndroidJniObject className=QAndroidJniObject::fromString("me.nereo.multi_image_selector.MultiImageSelectorActivity");
intent.callObjectMethod("setClassName","(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;",
packageName.object<jstring>(), className.object<jstring>());
*/
/*QAndroidJniObject MultiImageSelectorActivity__EXTRA_SHOW_CAMERA = QAndroidJniObject::getStaticObjectField(
"me/nereo/multi_image_selector/MultiImageSelectorActivity", "EXTRA_SHOW_CAMERA", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "MultiImageSelectorActivity__EXTRA_SHOW_CAMERA.isValid()=" << MultiImageSelectorActivity__EXTRA_SHOW_CAMERA.isValid();
intent.callObjectMethod("putExtra","(Ljava/lang/String;Z)Landroid/content/Intent;",
MultiImageSelectorActivity__EXTRA_SHOW_CAMERA.object<jstring>(), true);
QAndroidJniObject MultiImageSelectorActivity__EXTRA_SELECT_COUNT = QAndroidJniObject::getStaticObjectField(
"me/nereo/multi_image_selector/MultiImageSelectorActivity", "EXTRA_SELECT_COUNT", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "MultiImageSelectorActivity__EXTRA_SELECT_COUNT.isValid()=" << MultiImageSelectorActivity__EXTRA_SELECT_COUNT.isValid();
intent.callObjectMethod("putExtra","(Ljava/lang/String;I)Landroid/content/Intent;",
MultiImageSelectorActivity__EXTRA_SELECT_COUNT.object<jstring>(),
(jint)maxPick());
QAndroidJniObject MultiImageSelectorActivity__EXTRA_SELECT_MODE = QAndroidJniObject::getStaticObjectField(
"me/nereo/multi_image_selector/MultiImageSelectorActivity", "EXTRA_SELECT_MODE", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "MultiImageSelectorActivity__EXTRA_SELECT_MODE.isValid()=" << MultiImageSelectorActivity__EXTRA_SELECT_MODE.isValid();
jint MultiImageSelectorActivity__MODE_MULTI = QAndroidJniObject::getStaticField<jint>(
"me/nereo/multi_image_selector/MultiImageSelectorActivity", "MODE_MULTI");
intent.callObjectMethod("putExtra","(Ljava/lang/String;I)Landroid/content/Intent;",
MultiImageSelectorActivity__EXTRA_SELECT_MODE.object<jstring>(), MultiImageSelectorActivity__MODE_MULTI);
*/
qDebug() << __FUNCTION__ << ":maxPick()=" << maxPick();
if ( maxPick() >= 1 )
{
intent.callMethod<void>("setPhotoCount","(I)V", (jint)maxPick());
}
else
{
intent.callMethod<void>("setPhotoCount","(I)V", (jint)1000);
}
intent.callMethod<void>("setShowCamera","(Z)V", true);
/*QAndroidJniObject intent = QAndroidJniObject::callStaticObjectMethod(
"wpp/android/Misc", "createMultiImagePickerIntent", "(Landroid/content/Context;)Landroid/content/Intent;",
activity.object<jobject>());
qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid();*/
QtAndroid::startActivity(intent, 9000, this);
return ;
}
/*
if (Build.VERSION.SDK_INT <19){
Intent intent = new Intent();
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);***
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Pick a photo"),PICK_FROM_FILE);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);***
startActivityForResult(intent, PICK_FROM_FILE_KITKAT);
}
*/
QAndroidJniObject Intent__EXTRA_ALLOW_MULTIPLE = QAndroidJniObject::getStaticObjectField(
"android/content/Intent", "EXTRA_ALLOW_MULTIPLE", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "Intent__EXTRA_ALLOW_MULTIPLE.isValid()=" << Intent__EXTRA_ALLOW_MULTIPLE.isValid();
jint Build__VERSION__SDK_INT = QAndroidJniObject::getStaticField<jint>(
"android/os/Build$VERSION", "SDK_INT");
qDebug() << "Build__VERSION__SDK_INT=" << Build__VERSION__SDK_INT;
if ( Build__VERSION__SDK_INT < 19 )
{
QAndroidJniObject Intent__ACTION_GET_CONTENT = QAndroidJniObject::getStaticObjectField(
"android/content/Intent", "ACTION_GET_CONTENT", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "Intent__ACTION_GET_CONTENT.isValid()=" << Intent__ACTION_GET_CONTENT.isValid();
//QAndroidJniObject activity = QtAndroid::androidActivity();
//qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid();
QAndroidJniObject intent=QAndroidJniObject("android/content/Intent","()V");
qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid();
QAndroidJniObject imageTypeStr = QAndroidJniObject::fromString(QString("image/*"));
qDebug() << __FUNCTION__ << "imageTypeStr.isValid()=" << imageTypeStr.isValid();
intent.callObjectMethod("setType","(Ljava/lang/String;)Landroid/content/Intent;",
imageTypeStr.object<jobject>());
if ( maxPick() != 1 )
{
qDebug() << __FUNCTION__ << ":maxPack!=1: set EXTRA_ALLOW_MULTIPLE";
intent.callObjectMethod("putExtra","(Ljava/lang/String;Z)Landroid/content/Intent;",
Intent__EXTRA_ALLOW_MULTIPLE.object<jobject>(), true);
}
intent.callObjectMethod("setAction","(Ljava/lang/String;)Landroid/content/Intent;",
Intent__ACTION_GET_CONTENT.object<jobject>());
QAndroidJniObject chooseText = QAndroidJniObject::fromString(QString("Please pick on photo"));
qDebug() << __FUNCTION__ << "chooseText.isValid()=" << chooseText.isValid();
QAndroidJniObject chooserIntent = QAndroidJniObject::callStaticObjectMethod(
"android/content/Intent", "createChooser", "(Landroid/content/Intent;Ljava/lang/CharSequence;)Landroid/content/Intent;",
intent.object<jobject>(), chooseText.object<jobject>());
qDebug() << __FUNCTION__ << "chooserIntent.isValid()=" << chooserIntent.isValid();
int PICK_FROM_FILE = 2;
QtAndroid::startActivity(chooserIntent, PICK_FROM_FILE, this);
}
else
{
QAndroidJniObject Intent__ACTION_PICK = QAndroidJniObject::getStaticObjectField(
"android/content/Intent", "ACTION_PICK", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "Intent__ACTION_PICK.isValid()=" << Intent__ACTION_PICK.isValid();
QAndroidJniObject EXTERNAL_CONTENT_URI= QAndroidJniObject::getStaticObjectField(
"android/provider/MediaStore$Images$Media", "EXTERNAL_CONTENT_URI", "Landroid/net/Uri;");
qDebug() << __FUNCTION__ << "EXTERNAL_CONTENT_URI.isValid()=" << EXTERNAL_CONTENT_URI.isValid();
QAndroidJniObject intent=QAndroidJniObject("android/content/Intent",
"(Ljava/lang/String;Landroid/net/Uri;)V",
Intent__ACTION_PICK.object<jstring>(),
EXTERNAL_CONTENT_URI.object<jobject>()
);
qDebug() << __FUNCTION__ << "intent.isValid()=" << intent.isValid();
if ( maxPick() != 1 )
{
qDebug() << __FUNCTION__ << ":maxPack!=1: set EXTRA_ALLOW_MULTIPLE";
intent.callObjectMethod("putExtra","(Ljava/lang/String;Z)Landroid/content/Intent;",
Intent__EXTRA_ALLOW_MULTIPLE.object<jobject>(), true);
}
/*
QAndroidJniObject Intent__CATEGORY_OPENABLE = QAndroidJniObject::getStaticObjectField(
"android/content/Intent", "CATEGORY_OPENABLE", "Ljava/lang/String;");
qDebug() << __FUNCTION__ << "Intent__CATEGORY_OPENABLE.isValid()=" << Intent__CATEGORY_OPENABLE.isValid();
intent.callObjectMethod("addCategory","(Ljava/lang/String;)Landroid/content/Intent;",
Intent__CATEGORY_OPENABLE.object<jstring>());
QAndroidJniObject imageTypeStr = QAndroidJniObject::fromString(QString("image/*"));
qDebug() << __FUNCTION__ << "imageTypeStr.isValid()=" << imageTypeStr.isValid();
intent.callObjectMethod("setType","(Ljava/lang/String;)Landroid/content/Intent;",
imageTypeStr.object<jobject>());
*/
int PICK_FROM_FILE_KITKAT = 3;
QtAndroid::startActivity(intent, PICK_FROM_FILE_KITKAT, this);
}
#endif
}
#endif
#ifdef Q_OS_ANDROID
void ImagePicker::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject & data)
{
qDebug() << __FUNCTION__;
int PICK_FROM_FILE = 2;
int PICK_FROM_FILE_KITKAT = 3;
jint Activity__RESULT_OK = QAndroidJniObject::getStaticField<jint>(
"android/app/Activity", "RESULT_OK");
qDebug() << __FUNCTION__ <<":receiverRequestCode=" << receiverRequestCode
<< ",resultCode=" << resultCode
<< ",Activity__RESULT_OK=" << Activity__RESULT_OK;
if ( ( receiverRequestCode == PICK_FROM_FILE || receiverRequestCode == PICK_FROM_FILE_KITKAT
|| receiverRequestCode == 200
|| receiverRequestCode == 9000 )
&& resultCode == Activity__RESULT_OK )
{
if ( receiverRequestCode == 200 )
{
QAndroidJniEnvironment env;
QAndroidJniObject pathsJavaObj = data.callObjectMethod("getStringArrayExtra","(Ljava/lang/String;)[Ljava/lang/String;");
qDebug() << __FUNCTION__ << "pathsJavaObj.isValid()=" << pathsJavaObj.isValid();
jobjectArray pathArray = pathsJavaObj.object<jobjectArray>();
int stringCount = env->GetArrayLength(pathArray);
QStringList paths;
for (int i=0; i<stringCount; i++)
{
jstring string = (jstring) env->GetObjectArrayElement(pathArray, i);
const char *rawString = env->GetStringUTFChars(string, 0);
// Don't forget to call `ReleaseStringUTFChars` when you're done.
QString path(rawString);
qDebug() << "path[]=" << path;
paths.append(path);
env->ReleaseStringUTFChars(string, rawString);
}
emit this->accepted(paths);
}
else if ( receiverRequestCode == 9000 )//PhotoPicker
{
qDebug() << __FUNCTION__ << ":code=9000";
QAndroidJniEnvironment env;
QAndroidJniObject PhotoPickerActivity__KEY_SELECTED_PHOTOS
= QAndroidJniObject::getStaticObjectField(
"me/iwf/photopicker/PhotoPickerActivity", "KEY_SELECTED_PHOTOS", "Ljava/lang/String;");
qDebug() << "PhotoPickerActivity__KEY_SELECTED_PHOTOS.isValid()=" << PhotoPickerActivity__KEY_SELECTED_PHOTOS.isValid();
QAndroidJniObject photos = data.callObjectMethod("getStringArrayListExtra","(Ljava/lang/String;)Ljava/util/ArrayList;",
PhotoPickerActivity__KEY_SELECTED_PHOTOS.object<jstring>());
qDebug() << "photos.isValid()=" << photos.isValid();
QAndroidJniObject photosObjectArray = photos.callObjectMethod("toArray","()[Ljava/lang/Object;");
qDebug() << "photosObjectArray.isValid()=" << photosObjectArray.isValid();
jobjectArray pathArray = photosObjectArray.object<jobjectArray>();
int stringCount = env->GetArrayLength(pathArray);
qDebug() << "pathArray=" << (void*)pathArray;
qDebug() << "stringCount=" << stringCount;
QStringList paths;
for (int i=0; i<stringCount; i++)
{
qDebug() << "for pathArray...i=" << i;
jstring string = (jstring) env->GetObjectArrayElement(pathArray, i);
const char *rawString = env->GetStringUTFChars(string, 0);
// Don't forget to call `ReleaseStringUTFChars` when you're done.
qDebug() << "for pathArray...i=" << i << ":rawString=" << rawString;
QString path(rawString);
qDebug() << "path[]=" << path;
paths.append(path);
env->ReleaseStringUTFChars(string, rawString);
}
emit this->accepted(paths);
}
else
{
QAndroidJniEnvironment env;
QAndroidJniObject uri = data.callObjectMethod("getData","()Landroid/net/Uri;");
qDebug() << __FUNCTION__ << "uri.isValid()=" << uri.isValid();
qDebug() << __FUNCTION__ << "uri=" << uri.toString();
/*
url is like: "content://media/external/images/media/87332"
for KitKat(android 4.4), uri is like: "content://com.android.providers.media.documents/document/image:3951"
*/
QAndroidJniObject activity = QtAndroid::androidActivity();
qDebug() << __FUNCTION__ << "activity.isValid()=" << activity.isValid();
QAndroidJniObject contentResolver = activity.callObjectMethod("getContentResolver","()Landroid/content/ContentResolver;");
qDebug() << __FUNCTION__ << "contentResolver.isValid()=" << contentResolver.isValid();
/*if ( receiverRequestCode == PICK_FROM_FILE_KITKAT )
{
jint Intent__FLAG_GRANT_READ_URI_PERMISSION = QAndroidJniObject::getStaticField<jint>(
"android.content.Intent", "FLAG_GRANT_READ_URI_PERMISSION");
jint Intent__FLAG_GRANT_WRITE_URI_PERMISSION = QAndroidJniObject::getStaticField<jint>(
"android.content.Intent", "FLAG_GRANT_WRITE_URI_PERMISSION");
jint takeFlags = data.callMethod<jint>("getFlags","()I");
takeFlags = takeFlags & ( Intent__FLAG_GRANT_READ_URI_PERMISSION | Intent__FLAG_GRANT_WRITE_URI_PERMISSION );
contentResolver.callMethod<void>("takePersistableUriPermission","(Landroid/net/Uri;I)V",
uri.object<jobject>(), takeFlags);
}*/
/*
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
*/
QAndroidJniObject MediaStore_Images_Media_DATA
= QAndroidJniObject::getStaticObjectField(
"android/provider/MediaStore$MediaColumns", "DATA", "Ljava/lang/String;");
//"android/provider/MediaStore$Images$Media", "DATA", "Ljava/lang/String;");
qDebug() << "MediaStore_Images_Media_DATA.isValid()=" << MediaStore_Images_Media_DATA.isValid();
QAndroidJniObject nullObj;
jstring emptyJString = env->NewStringUTF("");
jobjectArray projection = (jobjectArray)env->NewObjectArray(
1,
env->FindClass("java/lang/String"),
emptyJString
);
jobject projection0 = env->NewStringUTF( MediaStore_Images_Media_DATA.toString().toStdString().c_str() );
env->SetObjectArrayElement(
projection, 0, projection0 );
// Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
QAndroidJniObject cursor = contentResolver.callObjectMethod("query",
"(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;",
uri.object<jobject>(), projection, nullObj.object<jstring>(), nullObj.object<jobjectArray>(), nullObj.object<jstring>());
qDebug() << __FUNCTION__ << "cursor.isValid()=" << cursor.isValid();
//int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
jint column_index = cursor.callMethod<jint>(
"getColumnIndexOrThrow","(Ljava/lang/String;)I", MediaStore_Images_Media_DATA.object<jstring>());
qDebug() << "column_index=" << column_index;
//cursor.moveToFirst();
cursor.callMethod<jboolean>("moveToFirst");
// String path = cursor.getString(column_index);
QAndroidJniObject path = cursor.callObjectMethod(
"getString",
"(I)Ljava/lang/String;", column_index );
qDebug() << __FUNCTION__ << "path.isValid()=" << path.isValid();
QString filePath = path.toString();
qDebug() << "filePath=" << filePath;
//cursor.close();
cursor.callMethod<jboolean>("close");
env->DeleteLocalRef(emptyJString);
env->DeleteLocalRef(projection);
env->DeleteLocalRef(projection0);
QStringList paths;
paths.append(filePath);
emit this->accepted(paths);
//m_imagePath = filePath;
//emit this->imagePathChanged();
}
}
}
#endif
}
}
|
#include <iostream>
using namespace std;
int main()
{
/*Initialization*/
int quantity = 0, price = 0, total_expense = 0, discount = 0, c = 1;
/*Loop until the user don't want to continue*/
while (c != 0)
{
cout << "Please Enter the Quantity and Price per Item. \n";
cout << "Quantity: ";
cin >> quantity;
cout << "Price: ";
cin >> price;
total_expense = total_expense + (price * quantity);
/*Check if the user is eligible for a discount*/
if (total_expense > 5000)
{
discount = total_expense * 0.1;
cout << "\nCongrats!!! You got a 10% discount on your shopping.\n";
cout << "\nTotal Expense : " << total_expense - discount << endl;
}
else
{
cout << "\nTotal Expense : " << total_expense << endl;
cout << "\nGet a 10% discount on spending more than 5000 bucks.\n";
}
cout << "\nDo you want to buy more items?\n"
<<"\nEnter 1 to continue shopping, or enter 0 if you are done!\n";
cin >> c;
}
cout << endl << "Thank You for shopping with us. Take Care!\n";
}
|
#ifndef __IOREQ_H__
#define __IOREQ_H__
#include "CmnHdr.h"
#include "LSocket.hpp"
#define BUFFER_SIZE 1024 * 4
class IOReq : public OVERLAPPED
{
public:
IOReq() {
ResetOverlapped();
}
~IOReq() {}
enum ReqType {
ReqType_Send,
ReqType_Recv,
};
bool Recv(LSocket socket) {
ResetOverlapped();
ZeroMemory(&(m_Data), sizeof(m_Data));
m_Type = ReqType_Recv;
m_Socket = socket;
m_WSABuffser.buf = m_Data;
m_WSABuffser.len = BUFFER_SIZE;
DWORD recvByte = 0;;
DWORD flag = 0;
int iRet = WSARecv(m_Socket.Get(), &m_WSABuffser, 1, &recvByte, &flag, this, NULL);
if (iRet == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) {
return false;
}
return true;
}
bool Send(LSocket socket, const char* pData, int len) {
ResetOverlapped();
ZeroMemory(&(m_Data), sizeof(m_Data));
memcpy(m_Data, pData, len);
m_Type = ReqType_Send;
m_Socket = socket;
m_WSABuffser.buf = m_Data;
m_WSABuffser.len = len;
DWORD sendByte = 0;
DWORD flag = 0;
int iRet = WSASend(m_Socket.Get(), &m_WSABuffser, 1, &sendByte, flag, this, NULL);
if (iRet == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) {
return false;
}
return true;
}
LSocket Socket() const {
return m_Socket;
}
ReqType Type() const {
return m_Type;
}
const char* data() const {
return m_Data;
}
private:
void ResetOverlapped() {
Internal = InternalHigh = 0;
Offset = OffsetHigh = 0;
hEvent = NULL;
}
private:
char m_Data[BUFFER_SIZE];
WSABUF m_WSABuffser;
LSocket m_Socket;
ReqType m_Type;
};
#endif // __IOREQ_H__
|
//
// Created by 송지원 on 2020/05/29.
//
#include <iostream>
using namespace std;
int N, M;
int r, c, d;
int input[50][50];
int dx[4] = {-1, 0, +1, 0};
int dy[4] = {0, +1, 0, -1};
int ANS = 1;
void solve() {
while (true) {
bool clean = false;
//내가 틀린 부분
// if(input[r][c] == 0) {
// clean = true;
// input[r][c] = 2;
// ANS++;
// }
for (int i=0; i<4; i++) {
int nd = (d + 3) % 4; // 그냥 "int nd = (d+3)%4;" 이렇게 해야함!!
int nx = r + dx[nd];
int ny = c + dy[nd];
d = nd; //내가 빼먹은 부분
if (input[nx][ny] == 0) {
input[nx][ny] = 2;
ANS++;
clean = true;
// d = nd; 여기가 아
r = nx;
c = ny;
break;
}
}
if (clean == false) {
int nx = r - dx[d];
int ny = c - dy[d];
if (input[nx][ny] == 1) { return; }
r = nx;
c = ny;
}
}
}
int main() {
scanf("%d %d", &N, &M);
scanf("%d%d%d", &r, &c, &d);
for (int i=0; i<N; i++) {
for (int j=0; j<M; j++) {
scanf("%d", &input[i][j]);
}
}
input[r][c] = 2;
solve();
printf("%d", ANS);
return 0;
}
|
#include "global.h"
ScreenResolution ScreenRes;
GLSL ColorProgram;
SDL_Window *SDLWindow;
Uint32 RunTime, Time, FrameTimeElapsed;
float PixelsPerSecond;
ResourceManager Resources;
|
#include "binary.h"
#include <cstring>
#include <sstream>
#include "stringValue.h"
#include "base64.h"
#include "utf8.h"
namespace json {
BinaryEncoding Binary::getEncoding() const {
return StringValue::getEncoding(s);
}
BinaryEncoding Binary::getEncoding(const IValue *v) {
return StringValue::getEncoding(v);
}
Binary Binary::decodeBinaryValue(const Value &s, BinaryEncoding encoding) {
StrViewA str = s.getString();
if (str.empty()) {
return Binary(json::string);
} else if ((s.flags() & binaryString) == 0) {
return Binary(encoding->decodeBinaryValue(str));
} else {
return Binary(s);
}
}
class DirectEncoding: public AbstractBinaryEncoder {
public:
using AbstractBinaryEncoder::encodeBinaryValue;
virtual Value decodeBinaryValue(const StrViewA &string) const override {
return string;
}
virtual void encodeBinaryValue(const BinaryView &binary, const WriteFn &fn) const override{
fn(StrViewA(binary));
}
virtual StrViewA getName() const override {
return "direct";
}
};
static DirectEncoding directEncodingVar;
BinaryEncoding directEncoding = &directEncodingVar;
static char hexchar[] = "0123456789ABCDEF";
static class UnhexChar {
public:
unsigned int operator[](char h) const {
if (isdigit(h)) return h-'0';
else if (h >= 'A' && h<='F') return h-'A'+10;
else if (h >= 'a' && h<='f') return h-'a'+10;
return 0;
}
} unhexchar;
class UrlEncoding: public AbstractBinaryEncoder {
public:
using AbstractBinaryEncoder::encodeBinaryValue;
virtual Value decodeBinaryValue(const StrViewA &string) const override {
std::size_t srclen = string.length;
std::size_t trglen = 0;
for (std::size_t i = 0; i < srclen; i++, trglen++)
if (string[i] == '%') i+=2;
RefCntPtr<StringValue> strVal = new(trglen) StringValue(urlEncoding,trglen, [&](char *c) {
for (std::size_t i = 0; i < srclen; i++)
if (string[i] == '%') {
if (i + 3 > srclen) {
return trglen-1;
} else {
unsigned char val = (unhexchar[string[i+1]] << 4) | (unhexchar[string[i+2]] & 0xF);
*c++ = val;
i+=2;
}
} else if (string[i] == '+') {
*c++ = ' ';
} else {
*c++ = string[i];
}
return trglen;
});
return PValue::staticCast(strVal);
}
virtual void encodeBinaryValue(const BinaryView &binary, const WriteFn &fn) const override{
for (unsigned char c : binary) {
if (c && (isalnum(c) || strchr("-_.!~*'()", c) != 0)) fn(StrViewA(reinterpret_cast<char *>(&c),1));
else {
char buff[3];
buff[0]='%';
buff[1]=hexchar[(c >> 4)];
buff[2]=hexchar[(c & 0xF)];
fn(StrViewA(buff,3));
}
}
}
virtual StrViewA getName() const override {
return "urlencoding";
}
};
Value AbstractBinaryEncoder::encodeBinaryValue(const BinaryView &binary) const {
std::ostringstream buffer;
encodeBinaryValue(binary,[&](StrViewA str){buffer << str;});
return Value(buffer.str());
}
class UTF8Encoding: public AbstractBinaryEncoder {
protected:
virtual Value decodeBinaryValue(const StrViewA &string) const override {
Utf8ToWide conv;
std::size_t needsz;
conv(fromString(string), WriteCounter<std::size_t>(needsz));
RefCntPtr<StringValue> strVal = new(needsz) StringValue(utf8encoding,needsz, [&](char *c) {
unsigned char *cc = reinterpret_cast<unsigned char *>(c);
conv(fromString(string),[&](int d){*cc++=static_cast<unsigned char>(d);});
return needsz;
});
return PValue::staticCast(strVal);
}
virtual void encodeBinaryValue(const BinaryView &binary, const WriteFn &fn) const override{
WideToUtf8 conv;
char buff[256];
int pos = 0;
conv(fromBinary(binary),[&](char c) {
buff[pos++] = c;
if (pos == sizeof(buff)) {
fn(StrViewA(buff,pos));
pos=0;
}
});
if (pos) fn(StrViewA(buff,pos));
}
Value encodeBinaryValue(const BinaryView &binary) const override {
WideToUtf8 conv;
std::size_t needsz;
conv(fromBinary(binary), WriteCounter<std::size_t>(needsz));
RefCntPtr<StringValue> strVal = new(needsz) StringValue(nullptr,needsz, [&](char *c) {
conv(fromBinary(binary),[&](char d){*c++=d;});
return needsz;
});
return PValue::staticCast(strVal);
}
virtual StrViewA getName() const override {
return "utf8encoding";
}
};
static Base64Encoding base64Var;
static Base64EncodingUrl base64UrlVar;
static UrlEncoding urlEncodingVar;
static UTF8Encoding utf8encodingVar;
BinaryEncoding base64 = &base64Var;
BinaryEncoding base64url = &base64UrlVar;
BinaryEncoding urlEncoding = &urlEncodingVar;
BinaryEncoding defaultBinaryEncoding = &base64Var;
BinaryEncoding utf8encoding = &utf8encodingVar;
}
|
#include <iostream>
/* Exercise 2.41 - use this Sales_data class (struct) to rewrite the exercises in
1.5.2
and 1.6
*/
struct Sales_data {
std::string bookId;
unsigned unitsSold;
double revenue;
};
// reads several transactions and counts how many transactions occur for each ISBN
int main()
{
Sales_data bookIn, currentBook;
int count=0;
std::cin >> currentBook.bookId >> currentBook.unitsSold >> currentBook.revenue;
count++;
while (std::cin >> bookIn.bookId >> bookIn.unitsSold >> bookIn.revenue){
if (bookIn.bookId == currentBook.bookId){
count++;
}
else{
// new book
// print count of last book
std::cout << "ISBN: " << currentBook.bookId << " " << count << " Transactions" << std::endl;
currentBook.bookId = bookIn.bookId;
currentBook.unitsSold = bookIn.unitsSold;
currentBook.revenue = bookIn.revenue;
count=1;
}
}
//print last transaction
std::cout << "ISBN: " << currentBook.bookId << " " << count << " Transactions" << std::endl;
}
|
#define WINVER 0x0502
#define _WIN32_WINNT 0x0502
#define _WIN32_WINDOWS 0x0502
// #define WIN32_LEAN_AND_MEAN
#include <cstdio>
#include <application.hpp>
#include <action.hpp>
#include <component.hpp>
using namespace curses;
class TestTexject:public component {
private:
sp_view create_vew(sp_pen p, rectangle&& r) {
text_color brdclr(BRIGHT_WHITE,NAVY_BLUE);
text_color bodyclr(NAVY_YELLOW,NAVY_BLUE);
sp_border brd(new double_line_titled_border(brdclr,TEXT("Test title")));
return sp_view(new bordered_box_view(p,CURSES_MOVE(rectangle,r), bodyclr, brd) );
}
public:
TestTexject(sp_pen p, const rectangle& rect):
component( create_vew(p, CURSES_MOVE(rectangle,rect) ) )
{
text_color clr( NAVY_YELLOW, p->current_color().background );
p->set_color(clr);
}
void onKeyPressed(const event& ev) {
key_state ks = ev.key;
char_t kcd = ks.key_code;
if( kcd == (wchar_t) 0x3 ) {
std::exit(0);
}
sp_pen p = view()->get_pen();
p->set_cursor(0,0);
p->outch( 0,0, kcd );
p->out_text(2, 0,TEXT("typed") );
}
void onMouse(const event& ev) {
sp_pen p = view()->get_pen();
position pos = p->screen_to_virtual( position(ev.mouse.x, ev.mouse.y) );
wchar_t str[64];
std::swprintf(str, L"mouse x = %i mouse y = %i", pos.x, pos.y);
p->out_text( 0, 1, str);
}
virtual ~TestTexject()
{}
};
CURSES_DECLARE_SPTR(TestTexject);
#ifdef CURSES_NO_EXCEPTIONS
namespace boost {
void throw_exception(std::exception const& exc) {
std::fprintf( stderr, exc.what() );
std::exit(-1);
}
}
#endif // CURSES_NO_EXCEPTIONS
//int main(int argc, const char** argv)
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)
{
sp_terminal trm(new terminal());
#ifdef CURSES_TERMINAL_EMULATOR
trm->set_window_title(L"CPP Curses test application");
#endif
bounds bds = trm->get_bounds();
sp_pen p( new pen( trm.get(), rectangle( 0, 0, bds.width, bds.height) ) );
application app( p );
app.run();
rectangle rect(1, 2, (bds.width-1) / 2, (bds.height-2) / 2 );
sp_TestTexject tj(new TestTexject(p, rect) );
tj->show();
curses::signal ksig( new action( bind_handler(&TestTexject::onKeyPressed, tj) ) );
ksig.connect(event_type::KEY);
curses::signal msig(new action( bind_handler(&TestTexject::onMouse, tj ) ) );
ksig.connect(event_type::MOUSE);
bool active = true;
while(active) {
event ev = trm->wait_for_event();
switch(ev.type) {
case event_type::KEY:
ksig.emit( ev );
break;
case event_type::MOUSE:
msig.emit( ev );
break;
default:
break;
}
}
return 0;
}
|
#include "pch.h"
#include "DirTreeCrawler.h"
#include "InputArgumentsParser.h"
#include "InterruptionWatcher.h"
#include "ParseResultHandler.h"
int wmain(int argc, wchar_t* argv[])
{
InputArgumentParser parser;
if (!parser.parseInputArguments(argc, argv))
{
return 1;
}
auto resultHandler = std::make_shared<ParseResultHandler>(parser.getLog());
DirTreeCrawler presenter(parser.getPathIn(), resultHandler);
presenter.start();
InterruptionWatcher watcher;
while (!presenter.isCompleted())
{
if (watcher.isInterrupted())
{
presenter.stop();
break;
}
}
return 0;
}
|
#pragma once
#ifndef __COMMONHELPER_H_
#define __COMMONHELPER_H_
#include <winsock2.h>
#include <shlwapi.h>
#include <shellapi.h>
#include <tlhelp32.h>
#include <commdlg.h>
#include <io.h>
#include <stdio.h>
#include <fcntl.h>
#include <tchar.h>
#include <sys/stat.h>
#include <map>
#include <regex>
#include <vector>
#include <string>
#include <iconv.h>
#include <shttpd.h>
#include "MACROS.h"
#include "UNDOCAPI.h"
namespace PPSHUAI{
__inline static std::string STRING_FORMAT_A(const CHAR * paFormat, ...)
{
INT nAS = 0;
std::string A = ("");
va_list valist = { 0 };
va_start(valist, paFormat);
nAS = _vscprintf_p(paFormat, valist);
if (nAS > 0)
{
A.resize((nAS + sizeof(CHAR)) * sizeof(CHAR), ('\0'));
_vsnprintf((CHAR *)A.c_str(), nAS * sizeof(CHAR), paFormat, valist);
}
va_end(valist);
return A.c_str();
}
__inline static std::wstring STRING_FORMAT_W(const WCHAR * pwFormat, ...)
{
INT nWS = 0;
std::wstring W = (L"");
va_list valist = { 0 };
va_start(valist, pwFormat);
nWS = _vscwprintf_p(pwFormat, valist);
if (nWS > 0)
{
W.resize((nWS + sizeof(WCHAR)) * sizeof(WCHAR), (L'\0'));
_vsnwprintf((WCHAR *)W.c_str(), nWS * sizeof(WCHAR), pwFormat, valist);
}
va_end(valist);
return W.c_str();
}
typedef enum RANDOMLISTTYPE{
RLTYPE_NULL = 0,//rand
RLTYPE_A__B = 1,//(a,b)
RLTYPE_AA_B = 2,//[a,b)
RLTYPE_A_BB = 3,//(a,b]
RLTYPE_AABB = 4,//[a,b]
}RANDOMLISTTYPE;
template<typename T>
__inline static T GenerateRandom(T min, T max, RANDOMLISTTYPE type = RLTYPE_AABB)
{
T ret = T(0);
srand(time(0));
switch (type)
{
case RLTYPE_A__B: ret = (rand() % (T(max - min))) + (min - 1); break;
case RLTYPE_AA_B: ret = (rand() % (T(max - min))) + (min); break;
case RLTYPE_A_BB: ret = (rand() % (T(max - min))) + (min + 1); break;
case RLTYPE_AABB: ret = (rand() % (T(max - min + 1))) + (min); break;
default:ret = rand() % (T)(RAND_MAX); break;
}
return ret;
}
template<typename T>
__inline static void GenerateRandom(std::vector<T> & vT, int min, int max, RANDOMLISTTYPE type = RLTYPE_AABB)
{
srand(time(0));
for (auto & it : vT)
{
switch (type)
{
case RLTYPE_A__B: it = (rand() % (T(max - min))) + (min - 1); break;
case RLTYPE_AA_B: it = (rand() % (T(max - min))) + (min); break;
case RLTYPE_A_BB: it = (rand() % (T(max - min))) + (min + 1); break;
case RLTYPE_AABB: it = (rand() % (T(max - min + 1))) + (min); break;
default:it = rand() % (T)(RAND_MAX); break;
}
}
}
//获取毫秒时间计数器(返回结果为100纳秒的时间, 1ns=1 000 000ms=1000 000 000s)
#define MILLI_100NANO (ULONGLONG)(1000000ULL / 100ULL)
__inline static std::string GetCurrentSystemTimeA(const CHAR * pFormat = ("%04d-%02d-%02d %02d:%02d:%02d.%03d"))
{
CHAR szTime[MAXCHAR] = { 0 };
SYSTEMTIME st = { 0 };
//FILETIME ft = { 0 };
//::GetSystemTimeAsFileTime(&ft);
::GetLocalTime(&st);
//::GetSystemTime(&st);
//::SystemTimeToFileTime(&st, &ft);
//::SystemTimeToTzSpecificLocalTime(NULL, &st, &st);
wsprintfA(szTime, pFormat, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
return std::string(szTime);
}
__inline static std::wstring GetCurrentSystemTimeW(const WCHAR * pFormat = (L"%04d-%02d-%02d %02d:%02d:%02d.%03d"))
{
WCHAR wzTime[MAXCHAR] = { 0 };
SYSTEMTIME st = { 0 };
//FILETIME ft = { 0 };
//::GetSystemTimeAsFileTime(&ft);
::GetLocalTime(&st);
//::GetSystemTime(&st);
//::SystemTimeToFileTime(&st, &ft);
//::SystemTimeToTzSpecificLocalTime(NULL, &st, &st);
wsprintfW(wzTime, pFormat, st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
return std::wstring(wzTime);
}
#ifndef gettimeofday
__inline static struct timeval* gettimeofday(struct timeval* ptv)
{
typedef union {
FILETIME filetime;
unsigned long long nanotime;
} NANOTIME;
NANOTIME nt = { 0 };
::GetSystemTimeAsFileTime(&nt.filetime);
ptv->tv_usec = (long)((nt.nanotime / 10ULL) % 1000000ULL);
ptv->tv_sec = (long)((nt.nanotime - 116444736000000000ULL) / 10000000ULL);
return ptv;
}
#endif // !gettimeofday
//返回值单位为100ns
__inline static LONGLONG GetCurrentTimerTicks()
{
FILETIME ft = { 0 };
SYSTEMTIME st = { 0 };
ULARGE_INTEGER u = { 0, 0 };
::GetSystemTime(&st);
::SystemTimeToFileTime(&st, &ft);
u.HighPart = ft.dwHighDateTime;
u.LowPart = ft.dwLowDateTime;
return u.QuadPart;
}
//获取运行时间间隔差值(输入参数单位为100纳秒)
__inline static LONGLONG GetIntervalTimerTicks(LONGLONG llTime)
{
return (LONGLONG)((GetCurrentTimerTicks() - llTime) / MILLI_100NANO);
}
//时间间隔差值(输入参数单位为100纳秒)
__inline static LONGLONG SubtractTimerTicks(LONGLONG llTimeA, LONGLONG llTimeB)
{
return (LONGLONG)((llTimeA - llTimeB) / MILLI_100NANO);
}
#if !defined(_DEBUG) && !defined(DEBUG)
#define START_TIMER_TICKS(x)
#define RESET_TIMER_TICKS(x)
#define CLOSE_TIMER_TICKS(x)
#else
#define START_TIMER_TICKS(x) ULONGLONG ull##x = PPSHUAI::GetCurrentTimerTicks();
#define RESET_TIMER_TICKS(x) ull##x = PPSHUAI::GetCurrentTimerTicks();
#define CLOSE_TIMER_TICKS(x) printf(("%s %s: %s() %llu ms\r\n"), PPSHUAI::GetCurrentSystemTimeA().c_str(), #x, __FUNCTION__, (PPSHUAI::GetCurrentTimerTicks() - ull##x) / MILLI_100NANO);
#endif
__inline static int GetFormatParamCountA(const CHAR * p_format)
{
int n_argc = 0;
CHAR * p = (CHAR *)p_format;
while (*p && *(p + 1))
{
if (*p == ('%'))
{
if (*(p + 1) != ('%'))
{
n_argc++;
}
p++;
}
p++;
}
return n_argc;
}
__inline static int GetFormatParamCountW(const WCHAR * p_format)
{
int n_argc = 0;
WCHAR * p = (WCHAR *)p_format;
while (*p && *(p + 1))
{
if (*p == (L'%'))
{
if (*(p + 1) != (L'%'))
{
n_argc++;
}
p++;
}
p++;
}
return n_argc;
}
__inline static bool IsLeapYear(long lYear)
{
return (((lYear % 4 == 0) && (lYear % 100 != 0)) || (lYear % 400 == 0));
}
__inline static bool IsLegalDate(long lYear, long lMonth, long lDay)
{
//大:1 3 5 7 8 10 12
//小:4 6 9 11
//平:2
bool result = false;
if (lYear > 0 && (lMonth > 0 && lMonth < 13) && (lDay > 0 && lDay < 32))
{
if ((2 != lMonth && 4 != lMonth && 6 != lMonth && 9 != lMonth && 11 != lMonth) || (lMonth != 2) || (lDay < 29) || (IsLeapYear(lYear) && lDay < 30))
{
result = true;
}
}
return result;
}
__inline static bool IsLegalDateA(const CHAR * p_date, const CHAR * p_format = ("%04d%02d%02d"))
{
bool result = false;
long lYear = 0;
long lMonth = 0;
long lDay = 0;
int nArgNum = GetFormatParamCountA(p_format);
if (sscanf(p_date, p_format, &lYear, &lMonth, &lDay) == nArgNum)
{
result = IsLegalDate(lYear, lMonth, lDay);
}
return result;
}
__inline static bool IsLegalDateW(const WCHAR * p_date, const WCHAR * p_format = (L"%04d%02d%02d"))
{
bool result = false;
long lYear = 0;
long lMonth = 0;
long lDay = 0;
int nArgNum = GetFormatParamCountW(p_format);
if (swscanf(p_date, p_format, &lYear, &lMonth, &lDay) == nArgNum)
{
result = IsLegalDate(lYear, lMonth, lDay);
}
return result;
}
//输入日期类型格式必须为"20010808"
__inline static int CompareDateTimeA(const CHAR * p_date_l, const CHAR * p_date_r)
{
return (int)(lstrcmpiA(p_date_l, p_date_r));
}
//输入日期类型格式必须为"20010808"
__inline static int CompareDateTimeW(const WCHAR * p_date_l, const WCHAR * p_date_r)
{
return (int)(lstrcmpiW(p_date_l, p_date_r));
}
//输入日期类型格式必须为"20010808"
__inline static bool IsMoreThanNowDateA(const CHAR * p_date, const CHAR * p_date_format = ("%04d%02d%02d"), const CHAR * p_date_format_now = ("%04d-%02d-%02d"), const CHAR * p_datetime_format_now = ("%04d-%02d-%02d %02d:%02d:%02d.%03d"))
{
bool result = false;
long lYear = 0, lMonth = 0, lDay = 0;
int nArgNum = GetFormatParamCountA(p_date_format_now);
if (sscanf(GetCurrentSystemTimeA(p_datetime_format_now).c_str(), p_date_format_now, &lYear, &lMonth, &lDay) == nArgNum)
{
if (CompareDateTimeA(p_date, STRING_FORMAT_A(p_date_format, lYear, lMonth, lDay).c_str()) != 0)
{
result = true;
}
}
return result;
}
//输入日期类型格式必须为"20010808"
__inline static bool IsMoreThanNowDateW(const WCHAR * p_date, const WCHAR * p_date_format = (L"%04d%02d%02d"), const WCHAR * p_date_format_now = (L"%04d-%02d-%02d"), const WCHAR * p_datetime_format_now = (L"%04d-%02d-%02d %02d:%02d:%02d.%03d"))
{
bool result = false;
long lYear = 0, lMonth = 0, lDay = 0;
int nArgNum = GetFormatParamCountW(p_date_format_now);
if (swscanf(GetCurrentSystemTimeW(p_datetime_format_now).c_str(), p_date_format_now, &lYear, &lMonth, &lDay) == nArgNum)
{
if (CompareDateTimeW(p_date, STRING_FORMAT_W(p_date_format, lYear, lMonth, lDay).c_str()) != 0)
{
result = true;
}
}
return result;
}
//根据秒时间获取日期
__inline static std::string STRING_FORMAT_DATE_A(time_t tv_sec, const CHAR * pszFormat = ("%Y%m%d")) { CHAR tzV[_MAX_PATH] = { 0 }; struct tm * tm = localtime(&tv_sec); memset(tzV, 0, sizeof(tzV)); strftime(tzV, sizeof(tzV) / sizeof(CHAR), pszFormat, tm); return (tzV); }
__inline static std::wstring STRING_FORMAT_DATE_W(time_t tv_sec, const WCHAR * pszFormat = (L"%Y%m%d")) { WCHAR tzV[_MAX_PATH] = { 0 }; struct tm * tm = localtime(&tv_sec); memset(tzV, 0, sizeof(tzV)); wcsftime(tzV, sizeof(tzV) / sizeof(WCHAR), pszFormat, tm); return (tzV); }
//根据秒时间获取精确微秒时间
__inline static std::string STRING_FORMAT_DATETIME_A(struct timeval * ptv, const CHAR * pszPrefixFormat = ("%Y-%m-%d %H:%M:%S"), const CHAR * pszSuffixFormat = (".%ld")) { time_t tt = ptv->tv_sec; struct tm * tm = localtime((const time_t *)&tt); CHAR tzV[_MAX_PATH] = { 0 }; memset(tzV, 0, sizeof(tzV)); strftime(tzV, sizeof(tzV) / sizeof(CHAR), pszPrefixFormat, tm); return STRING_FORMAT_A(STRING_FORMAT_A(("%%s%s"), pszSuffixFormat).c_str(), tzV, ptv->tv_usec); }
__inline static std::wstring STRING_FORMAT_DATETIME_W(struct timeval * ptv, const WCHAR * pszPrefixFormat = (L"%Y-%m-%d %H:%M:%S"), const CHAR * pszSuffixFormat = (".%ld")) { time_t tt = ptv->tv_sec; struct tm * tm = localtime((const time_t *)&tt); WCHAR tzV[_MAX_PATH] = { 0 }; memset(tzV, 0, sizeof(tzV)); wcsftime(tzV, sizeof(tzV) / sizeof(WCHAR), pszPrefixFormat, tm); return STRING_FORMAT_W(STRING_FORMAT_W((L"%%s%s"), pszSuffixFormat).c_str(), tzV, ptv->tv_usec); }
//解析错误标识为字符串
__inline static std::string ParseErrorA(DWORD dwErrorCodes, HINSTANCE hInstance = NULL)
{
BOOL bResult = FALSE;
HLOCAL hLocal = NULL;
std::string strErrorText = ("");
bResult = ::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
hInstance,
dwErrorCodes,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
(LPSTR)&hLocal,
0,
NULL);
if (!bResult)
{
if (hInstance)
{
bResult = ::FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_IGNORE_INSERTS,
hInstance,
dwErrorCodes,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
(LPSTR)&hLocal,
0,
NULL);
if (!bResult)
{
// failed
// Unknown error code %08x (%d)
strErrorText = STRING_FORMAT_A(("Unknown error code 0x%08X"), dwErrorCodes);
}
}
}
if (bResult && hLocal)
{
// Success
LPSTR pT = (LPSTR)strchr((LPCSTR)hLocal, ('\r'));
if (pT != NULL)
{
//Lose CRLF
*pT = ('\0');
}
strErrorText = (LPCSTR)hLocal;
}
if (hLocal)
{
::LocalFree(hLocal);
hLocal = NULL;
}
return strErrorText;
}
//解析错误标识为字符串
__inline static std::wstring ParseErrorW(DWORD dwErrorCodes, HINSTANCE hInstance = NULL)
{
BOOL bResult = FALSE;
HLOCAL hLocal = NULL;
std::wstring strErrorText = (L"");
bResult = ::FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
hInstance,
dwErrorCodes,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
(LPWSTR)&hLocal,
0,
NULL);
if (!bResult)
{
if (hInstance)
{
bResult = ::FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_IGNORE_INSERTS,
hInstance,
dwErrorCodes,
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
(LPWSTR)&hLocal,
0,
NULL);
if (!bResult)
{
// failed
// Unknown error code %08x (%d)
strErrorText = STRING_FORMAT_W((L"Unknown error code 0x%08X"), dwErrorCodes);
}
}
}
if (bResult && hLocal)
{
// Success
LPWSTR pT = (LPWSTR)wcschr((LPCWSTR)hLocal, (L'\r'));
if (pT != NULL)
{
//Lose CRLF
*pT = (L'\0');
}
strErrorText = (LPCWSTR)hLocal;
}
if (hLocal)
{
::LocalFree(hLocal);
hLocal = NULL;
}
return strErrorText;
}
__inline static std::string ToUpperCaseA(LPCSTR pA)
{
return strupr((LPSTR)pA);
}
__inline static std::wstring ToUpperCaseW(LPCWSTR pW)
{
return _wcsupr((LPWSTR)pW);
}
__inline static std::string ToLowerCaseA(LPCSTR pA)
{
return strlwr((LPSTR)pA);
}
__inline static std::wstring ToLowerCaseW(LPCWSTR pW)
{
return _wcsupr((LPWSTR)pW);
}
__inline static char s2c(short s)
{
char * a = "\x10\x01\x30\x30\x30\x30\x30\x30\x30\x30\x30\x30___7___\x41\x41\x41\x41\x41\x41____________26____________\x61\x61\x61\x61\x61\x61\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00___7___\x0A\x0A\x0A\x0A\x0A\x0A____________26____________\x0a\x0a\x0a\x0a\x0a\x0a";
char c = 0;
for (int i = 0; i < sizeof(s); i++)
{
c += a[i] * (((char *)&s)[i] - a[((char *)&s)[i] - '0' + sizeof(short)] + a[((char *)&s)[i] - '0' + ('f' - '0') + sizeof(char) + sizeof(short)]);
}
return c;
}
__inline static short c2s(char c)
{
char * a = "\xF0\x0F\x04\x00\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46";
short s = 0;
for (int i = 0; i < sizeof(s); i++)
{
((char*)&s)[i] = a[((unsigned char)(c & a[i]) >> a[i + sizeof(short)]) + sizeof(short) + sizeof(short)];
}
return s;
}
__inline static std::string str2hex(std::string s)
{
std::string h(s.length() * sizeof(short), '\0');
for (int i = 0; i < s.length(); i++)
{
((short*)h.c_str())[i] = c2s(s.at(i));
}
return h;
}
__inline static std::string hex2str(std::string h)
{
std::string s(h.length() / sizeof(short), '\0');
for (int i = 0; i < s.length(); i++)
{
s.at(i) = s2c(((short*)h.c_str())[i]);
}
return s;
}
__inline static std::string str_xor(std::string s)
{
std::string x(s);
for (auto c : x){ c ^= (BYTE)(0xFF); }
return x;
}
__inline static std::string hex_to_str(std::string h)
{
std::string s((""));
for (auto c : h){ s.append(STRING_FORMAT_A(("%02X"), (BYTE)c)); }
return s;
}
__inline static std::string str_to_hex(std::string s)
{
std::string h((""));
size_t i = 0;
size_t l = s.length();
if (!(l % sizeof(WORD)))
{
for (i = 0; i < l; i += sizeof(WORD))
{
h.push_back((BYTE)strtoul(s.substr(i, sizeof(WORD)).c_str(), NULL, 0x10));
}
}
return h;
}
__inline static std::string GetFilePathDriveA(LPCSTR lpFileName)
{
CHAR szDrive[_MAX_DRIVE] = { 0 };
CHAR szDir[_MAX_DIR] = { 0 };
CHAR szFname[_MAX_FNAME] = { 0 };
CHAR szExt[_MAX_EXT] = { 0 };
_splitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szDrive;
}
__inline static std::wstring GetFilePathDriveW(LPCWSTR lpFileName)
{
WCHAR szDrive[_MAX_DRIVE] = { 0 };
WCHAR szDir[_MAX_DIR] = { 0 };
WCHAR szFname[_MAX_FNAME] = { 0 };
WCHAR szExt[_MAX_EXT] = { 0 };
_wsplitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szDrive;
}
__inline static std::string GetFilePathDirA(LPCSTR lpFileName)
{
CHAR szDrive[_MAX_DRIVE] = { 0 };
CHAR szDir[_MAX_DIR] = { 0 };
CHAR szFname[_MAX_FNAME] = { 0 };
CHAR szExt[_MAX_EXT] = { 0 };
_splitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szDir;
}
__inline static std::wstring GetFilePathDirW(LPCWSTR lpFileName)
{
WCHAR szDrive[_MAX_DRIVE] = { 0 };
WCHAR szDir[_MAX_DIR] = { 0 };
WCHAR szFname[_MAX_FNAME] = { 0 };
WCHAR szExt[_MAX_EXT] = { 0 };
_wsplitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szDir;
}
__inline static std::string GetFilePathExtA(LPCSTR lpFileName)
{
CHAR szDrive[_MAX_DRIVE] = { 0 };
CHAR szDir[_MAX_DIR] = { 0 };
CHAR szFname[_MAX_FNAME] = { 0 };
CHAR szExt[_MAX_EXT] = { 0 };
_splitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szExt;
}
__inline static std::wstring GetFilePathExtW(LPCWSTR lpFileName)
{
WCHAR szDrive[_MAX_DRIVE] = { 0 };
WCHAR szDir[_MAX_DIR] = { 0 };
WCHAR szFname[_MAX_FNAME] = { 0 };
WCHAR szExt[_MAX_EXT] = { 0 };
_wsplitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szExt;
}
__inline static std::string GetFilePathFnameA(LPCSTR lpFileName)
{
CHAR szDrive[_MAX_DRIVE] = { 0 };
CHAR szDir[_MAX_DIR] = { 0 };
CHAR szFname[_MAX_FNAME] = { 0 };
CHAR szExt[_MAX_EXT] = { 0 };
_splitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szFname;
}
__inline static std::wstring GetFilePathFnameW(LPCWSTR lpFileName)
{
WCHAR szDrive[_MAX_DRIVE] = { 0 };
WCHAR szDir[_MAX_DIR] = { 0 };
WCHAR szFname[_MAX_FNAME] = { 0 };
WCHAR szExt[_MAX_EXT] = { 0 };
_wsplitpath(lpFileName, szDrive, szDir, szFname, szExt);
return szFname;
}
__inline static void SplitFilePathA(LPCSTR lpFileName, std::string & strDrive,
std::string & strDir, std::string & strFname, std::string & strExt)
{
CHAR szDrive[_MAX_DRIVE] = { 0 };
CHAR szDir[_MAX_DIR] = { 0 };
CHAR szFname[_MAX_FNAME] = { 0 };
CHAR szExt[_MAX_EXT] = { 0 };
_splitpath(lpFileName, szDrive, szDir, szFname, szExt);
strDrive = szDrive;
strDir = szDir;
strFname = szFname;
strExt = szExt;
}
__inline static void SplitFilePathW(LPCWSTR lpFileName, std::wstring & strDrive,
std::wstring & strDir, std::wstring & strFname, std::wstring & strExt)
{
WCHAR szDrive[_MAX_DRIVE] = { 0 };
WCHAR szDir[_MAX_DIR] = { 0 };
WCHAR szFname[_MAX_FNAME] = { 0 };
WCHAR szExt[_MAX_EXT] = { 0 };
_wsplitpath(lpFileName, szDrive, szDir, szFname, szExt);
strDrive = szDrive;
strDir = szDir;
strFname = szFname;
strExt = szExt;
}
#define MEMORY_ALLOCAT malloc
#define MEMORY_REALLOC realloc
#define MEMORY_RELEASE free
__inline static void * MemoryAllocat(void * p, size_t s)
{
return malloc(s);
}
__inline static void * MemoryRealloc(void * p, size_t s)
{
void * v = realloc(p, s);
if (!v)
{
free(p);
}
return v;
}
__inline static void * MemoryRelease(void ** p)
{
free((*p));
return (*p) = 0;
}
class CConfigHelper {
public:
//获取程序文件路径
__inline static tstring GetAppPath()
{
tstring tsFilePath = _T("");
_TCHAR * pFoundPosition = 0;
_TCHAR tFilePath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, tFilePath, MAX_PATH);
if (*tFilePath)
{
pFoundPosition = _tcsrchr(tFilePath, _T('\\'));
if (*(++pFoundPosition))
{
*pFoundPosition = _T('\0');
}
tsFilePath = tFilePath;
}
return tsFilePath;
}
CConfigHelper(LPCTSTR lpPathFileName = _T("config.ini")) {
m_tsPathFileName = CConfigHelper::GetAppPath() + lpPathFileName;
};
virtual ~CConfigHelper() {};
void InitRead(std::map<tstring, std::map<tstring, tstring>> & ttmapmap)
{
LPTSTR lpTSD = NULL;
DWORD dwSectionNames = (0L);
LPTSTR lpSectionNames = (0L);
LPTSTR lpTK = NULL;
DWORD dwKeyNames = (0L);
LPTSTR lpKeyNames = (0L);
LPTSTR lpVL = NULL;
lpTSD = NULL;
dwSectionNames = MAXBYTE;
lpSectionNames = (LPTSTR)malloc(dwSectionNames * sizeof(_TCHAR));
while ((GetPrivateProfileSectionNames(lpSectionNames, dwSectionNames, m_tsPathFileName.c_str())) &&
((GetLastError() == ERROR_MORE_DATA) || (GetLastError() == ERROR_INSUFFICIENT_BUFFER)))
{
lpTSD = (LPTSTR)realloc(lpSectionNames, (dwSectionNames + dwSectionNames) * sizeof(_TCHAR));
if (!lpTSD)
{
if (lpSectionNames)
{
free(lpSectionNames);
lpSectionNames = (0L);
}
}
else
{
lpSectionNames = lpTSD;
dwSectionNames += dwSectionNames;
}
}
lpTSD = lpSectionNames;
while (lpTSD && (*lpTSD))
{
ttmapmap.insert(std::map<tstring, std::map<tstring, tstring>>::value_type(lpTSD, std::map<tstring, tstring>{}));
lpTK = NULL;
dwKeyNames = MAXBYTE;
lpKeyNames = (LPTSTR)malloc(dwKeyNames * sizeof(_TCHAR));
while ((GetPrivateProfileSection(lpTSD, lpKeyNames, dwKeyNames, m_tsPathFileName.c_str())) &&
((GetLastError() == ERROR_MORE_DATA) || (GetLastError() == ERROR_INSUFFICIENT_BUFFER)))
{
lpTK = (LPTSTR)realloc(lpKeyNames, (dwKeyNames + dwKeyNames) * sizeof(_TCHAR));
if (!lpTK)
{
if (lpKeyNames)
{
free(lpKeyNames);
lpKeyNames = (0L);
}
}
else
{
lpKeyNames = lpTK;
dwKeyNames += dwKeyNames;
}
}
lpTK = lpKeyNames;
while (lpTK && (*lpTK))
{
if ((lpVL = _tcschr(lpTK, _T('\x3D'))) && (lpTK != lpVL))
{
*(lpVL) = _T('\x00');//''
ttmapmap.at(lpTSD).insert(std::map<tstring, tstring>::value_type(lpTK, lpVL + 1));
*(lpVL) = _T('\x3D');//'='
}
lpTK += lstrlen(lpTK) + 1;
}
if (lpKeyNames)
{
free(lpKeyNames);
lpKeyNames = (0L);
}
lpTSD += lstrlen(lpTSD) + 1;
}
if (lpSectionNames)
{
free(lpSectionNames);
lpSectionNames = (0L);
}
}
//! ConfigHelper Singleton
static CConfigHelper * getInstance(LPCTSTR lpPathFileName = _T("config.ini")) {
static CConfigHelper instance(lpPathFileName);
return &instance;
}
public:
TSTRING ReadString(LPCTSTR lpSectionName, LPCTSTR lpKeyName, LPCTSTR lpDefaultValue)
{
TSTRING t(USHRT_MAX, _T('\0'));
GetPrivateProfileString(lpSectionName, lpKeyName, lpDefaultValue, (LPTSTR)t.c_str(), t.size(), m_tsPathFileName.c_str());
return t;
}
BOOL WriteString(LPCTSTR lpAppName, LPCTSTR lpKeyName, LPCTSTR lpValue)
{
return WritePrivateProfileString(lpAppName, lpKeyName, lpValue, m_tsPathFileName.c_str());
}
private:
tstring m_tsPathFileName;
std::map<tstring, std::map<tstring, tstring>> m_ttmapmap;//配置信息映射
};
#if !defined(_UNICODE) && !defined(UNICODE)
#define ToUpperCase ToUpperCaseA
#define ToLowerCase ToLowerCaseA
#define STRING_FORMAT STRING_FORMAT_A
#define GetCurrentSystemTime GetCurrentSystemTimeA
#define ParseError ParseErrorA
#define GetFilePathDrive GetFilePathDriveA
#define GetFilePathDir GetFilePathDirA
#define GetFilePathExt GetFilePathExtA
#define GetFilePathFname GetFilePathFnameA
#define SplitFilePath SplitFilePathA
#else
#define ToUpperCase ToUpperCaseW
#define ToLowerCase ToLowerCaseW
#define STRING_FORMAT STRING_FORMAT_W
#define GetCurrentSystemTime GetCurrentSystemTimeW
#define ParseError ParseErrorW
#define GetFilePathDrive GetFilePathDriveW
#define GetFilePathDir GetFilePathDirW
#define GetFilePathExt GetFilePathExtW
#define GetFilePathFname GetFilePathFnameW
#define SplitFilePath SplitFilePathW
#endif // !defined(_UNICODE) && !defined(UNICODE)
//初始化调试窗口显示
__inline static void InitDebugConsole(const _TCHAR * ptszConsoleTitle = _T("TraceDebugWindow"))
{
if (!AllocConsole())
{
MessageBox(NULL, STRING_FORMAT(_T("控制台生成失败! 错误代码:0x%X。"), GetLastError()).c_str(), _T("错误提示"), 0);
}
else
{
SetConsoleTitle(ptszConsoleTitle);
_tfreopen(_T("CONIN$"), _T("rb"), stdin);
_tfreopen(_T("CONOUT$"), _T("wb"), stdout);
_tfreopen(_T("CONOUT$"), _T("wb"), stderr);
//_tfreopen(_T("CONERR$"), _T("wb"), stderr);
_tsetlocale(LC_ALL, _T("chs"));
}
}
//释放掉调试窗口显示
__inline static void ExitDebugConsole()
{
fclose(stderr);
fclose(stdout);
fclose(stdin);
FreeConsole();
}
namespace Convert{
__inline static int codeset_convert(char *from_charset, char *to_charset, const char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
const char **pin = &inbuf;
char **pout = &outbuf;
iconv_t cd = iconv_open(to_charset, from_charset);
if (cd == 0) return -1;
memset(outbuf, 0, outlen);
if (iconv(cd, (char **)pin, &inlen, pout, &outlen) == -1) return -1;
iconv_close(cd);
return 0;
}
/* UTF-8 to GBK */
__inline static int u2g(const char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
return codeset_convert("UTF-8", "GBK", inbuf, inlen, outbuf, outlen);
}
/* GBK to UTF-8 */
__inline static int g2u(const char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
return codeset_convert("GBK", "UTF-8", inbuf, inlen, outbuf, outlen);
}
// ANSI to Unicode
__inline static std::wstring ANSIToUnicode(const std::string str)
{
int len = 0;
len = str.length();
int unicodeLen = ::MultiByteToWideChar(CP_ACP,
0,
str.c_str(),
-1,
NULL,
0);
wchar_t * pUnicode;
pUnicode = new wchar_t[(unicodeLen + 1)];
memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
::MultiByteToWideChar(CP_ACP,
0,
str.c_str(),
-1,
(LPWSTR)pUnicode,
unicodeLen);
std::wstring rt;
rt = (wchar_t*)pUnicode;
delete pUnicode;
return rt;
}
//Unicode to ANSI
__inline static std::string UnicodeToANSI(const std::wstring str)
{
char* pElementText;
int iTextLen;
iTextLen = WideCharToMultiByte(CP_ACP,
0,
str.c_str(),
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_ACP,
0,
str.c_str(),
-1,
pElementText,
iTextLen,
NULL,
NULL);
std::string strText;
strText = pElementText;
delete[] pElementText;
return strText;
}
//UTF - 8 to Unicode
__inline static std::wstring UTF8ToUnicode(const std::string str)
{
int len = 0;
len = str.length();
int unicodeLen = ::MultiByteToWideChar(CP_UTF8,
0,
str.c_str(),
-1,
NULL,
0);
wchar_t * pUnicode;
pUnicode = new wchar_t[unicodeLen + 1];
memset(pUnicode, 0, (unicodeLen + 1) * sizeof(wchar_t));
::MultiByteToWideChar(CP_UTF8,
0,
str.c_str(),
-1,
(LPWSTR)pUnicode,
unicodeLen);
std::wstring rt;
rt = (wchar_t*)pUnicode;
delete pUnicode;
return rt;
}
//Unicode to UTF - 8
__inline static std::string UnicodeToUTF8(const std::wstring str)
{
char* pElementText;
int iTextLen;
iTextLen = WideCharToMultiByte(CP_UTF8,
0,
str.c_str(),
-1,
NULL,
0,
NULL,
NULL);
pElementText = new char[iTextLen + 1];
memset((void*)pElementText, 0, sizeof(char) * (iTextLen + 1));
::WideCharToMultiByte(CP_UTF8,
0,
str.c_str(),
-1,
pElementText,
iTextLen,
NULL,
NULL);
std::string strText;
strText = pElementText;
delete[] pElementText;
return strText;
}
__inline static std::string TToA(tstring tsT)
{
std::string str = "";
#if !defined(UNICODE) && !defined(_UNICODE)
str = tsT;
#else
str = UnicodeToANSI(tsT);
#endif
return str;
}
__inline static std::wstring TToW(tstring tsT)
{
std::wstring wstr = L"";
#if !defined(UNICODE) && !defined(_UNICODE)
wstr = ANSIToUnicode(tsT);
#else
wstr = tsT;
#endif
return wstr;
}
__inline static tstring AToT(std::string str)
{
tstring ts = _T("");
#if !defined(UNICODE) && !defined(_UNICODE)
ts = str;
#else
ts = ANSIToUnicode(str);
#endif
return ts;
}
__inline static tstring WToT(std::wstring wstr)
{
tstring ts = _T("");
#if !defined(UNICODE) && !defined(_UNICODE)
ts = UnicodeToANSI(wstr);
#else
ts = wstr;
#endif
return ts;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:LPWSTR字符串类型转换为LPSTR字符串类型
// 参 数:LPWSTR参数类型
// 返 回 值:返回LPSTR类型数据
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static LPSTR UnicodeToAnsi(LPWSTR lpUnicode)
{
LPSTR pAnsi = NULL;
int nAnsiLength = 0;
if (lpUnicode)
{
nAnsiLength = WideCharToMultiByte(CP_ACP, NULL, lpUnicode, -1, NULL, 0, NULL, NULL);
if (nAnsiLength)
{
pAnsi = (LPSTR)malloc(nAnsiLength * sizeof(CHAR));
if (pAnsi)
{
WideCharToMultiByte(CP_ACP, NULL, lpUnicode, -1, pAnsi, nAnsiLength, NULL, NULL);
}
}
}
return pAnsi;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:LPWSTR字符串类型转换为LPSTR字符串类型
// 参 数:LPWSTR参数类型
// 返 回 值:返回LPSTR类型数据
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static LPWSTR AnsiToUnicode(LPSTR lpAnsi)
{
LPWSTR pUnicode = NULL;
int nUnicodeLength = 0;
if (lpAnsi)
{
nUnicodeLength = MultiByteToWideChar(CP_ACP, NULL, lpAnsi, -1, NULL, 0);
if (nUnicodeLength)
{
pUnicode = (LPWSTR)malloc(nUnicodeLength * sizeof(WCHAR));
if (pUnicode)
{
MultiByteToWideChar(CP_ACP, NULL, lpAnsi, -1, pUnicode, nUnicodeLength);
}
}
}
return pUnicode;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:释放自分配的内存
// 参 数:void *参数类型
// 返 回 值:无返回值
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static void LocalFreeMemory(LPVOID * lpPointer)
{
if (lpPointer && (*lpPointer))
{
free((*lpPointer));
(*lpPointer) = NULL;
}
}
//utf8 转 Unicode
__inline static std::wstring Utf82Unicode(const std::string& utf8string)
{
int widesize = ::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, NULL, 0);
if (widesize == ERROR_NO_UNICODE_TRANSLATION || widesize == 0)
{
return std::wstring(L"");
}
std::vector<wchar_t> resultstring(widesize);
int convresult = ::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, &resultstring[0], widesize);
if (convresult != widesize)
{
return std::wstring(L"");
}
return std::wstring(&resultstring[0]);
}
//unicode 转为 ascii
__inline static std::string WideByte2Acsi(std::wstring& wstrcode)
{
int asciisize = ::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, NULL, 0, NULL, NULL);
if (asciisize == ERROR_NO_UNICODE_TRANSLATION || asciisize == 0)
{
return std::string("");
}
std::vector<char> resultstring(asciisize);
int convresult = ::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, &resultstring[0], asciisize, NULL, NULL);
if (convresult != asciisize)
{
return std::string("");
}
return std::string(&resultstring[0]);
}
//utf-8 转 ascii
__inline static std::string UTF_82ASCII(std::string& strUtf8Code)
{
std::string strRet("");
//先把 utf8 转为 unicode
std::wstring wstr = Utf82Unicode(strUtf8Code);
//最后把 unicode 转为 ascii
strRet = WideByte2Acsi(wstr);
return strRet;
}
///////////////////////////////////////////////////////////////////////
//ascii 转 Unicode
__inline static std::wstring Acsi2WideByte(std::string& strascii)
{
int widesize = MultiByteToWideChar(CP_ACP, 0, (char*)strascii.c_str(), -1, NULL, 0);
if (widesize == ERROR_NO_UNICODE_TRANSLATION || widesize == 0)
{
return std::wstring(L"");
}
std::vector<wchar_t> resultstring(widesize);
int convresult = MultiByteToWideChar(CP_ACP, 0, (char*)strascii.c_str(), -1, &resultstring[0], widesize);
if (convresult != widesize)
{
return std::wstring(L"");
}
return std::wstring(&resultstring[0]);
}
//Unicode 转 Utf8
__inline static std::string Unicode2Utf8(const std::wstring& widestring)
{
int utf8size = ::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, NULL, 0, NULL, NULL);
if (utf8size == 0)
{
return std::string("");
}
std::vector<char> resultstring(utf8size);
int convresult = ::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, &resultstring[0], utf8size, NULL, NULL);
if (convresult != utf8size)
{
return std::string("");
}
return std::string(&resultstring[0]);
}
//ascii 转 Utf8
__inline static std::string ASCII2UTF_8(std::string& strAsciiCode)
{
std::string strRet("");
//先把 ascii 转为 unicode
std::wstring wstr = Acsi2WideByte(strAsciiCode);
//最后把 unicode 转为 utf8
strRet = Unicode2Utf8(wstr);
return strRet;
}
//ANSI转UTF8
__inline static std::string ANSI2UTF8(std::string str)
{
return UnicodeToUTF8(ANSIToUnicode(str));
}
//UTF8转ANSI
__inline static std::string UTF82ANSI(std::string str)
{
return UnicodeToANSI(UTF8ToUnicode(str));
}
//通用版将wstring转化为string
__inline std::string WToA(std::wstring wstr, unsigned codepage = CP_ACP)
{
int nwstrlen = WideCharToMultiByte(codepage, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
if (nwstrlen > 0)
{
std::string str(nwstrlen + 1, '\0');
WideCharToMultiByte(codepage, 0, wstr.c_str(), -1, (LPSTR)str.c_str(), nwstrlen, NULL, NULL);
return str;
}
return ("");
}
//通用版将string转化为wstring
__inline std::wstring AToW(std::string str, unsigned codepage = CP_ACP)
{
int nstrlen = MultiByteToWideChar(codepage, 0, str.c_str(), -1, NULL, 0);
if (nstrlen > 0)
{
std::wstring wstr(nstrlen + 1, '\0');
MultiByteToWideChar(codepage, 0, str.c_str(), -1, (LPWSTR)wstr.c_str(), nstrlen);
return wstr;
}
return (L"");
}
//将X编码转化为Y编码
__inline static std::string CodePage_XToY(std::string str, unsigned src_codepage, unsigned dst_codepage)
{
return WToA(AToW(str, src_codepage), dst_codepage);
}
//将UTF8转化为GB2312
__inline static std::string UTF8ToGB2132(std::string str)
{
return CodePage_XToY(str, CP_UTF8, CP_ACP);
}
//将GB2312转化为UTF8
__inline static std::string GB2132ToUTF8(std::string str)
{
return CodePage_XToY(str, CP_ACP, CP_UTF8);
}
__inline static TSTRING VarChangeToStr(VARIANT var)
{
TSTRING t = _T("");
VARIANT varDest = { 0 };
HRESULT hResult = S_FALSE;
varDest.vt = VT_BSTR;
varDest.bstrVal = BSTR(L"");
hResult = ::VariantChangeType(&varDest, &var, VARIANT_NOUSEROVERRIDE | VARIANT_LOCALBOOL, VT_BSTR);
if (SUCCEEDED(hResult))
{
t = WToT(varDest.bstrVal);
}
return t;
}
__inline static tstring VariantToTstring(VARIANT var)
{
tstring A = _T("");
VARIANT varBSTR = { 0 };
double dDecVal = 0.0f;
SYSTEMTIME st = { 0 };
//CString strFormat(_T(""));
switch (var.vt)
{
case VT_EMPTY: // 0
A = _T("");
break;
case VT_NULL: // 1
A = _T("");
break;
case VT_I2: // 2
A = STRING_FORMAT(_T("%d"), var.iVal);
break;
case VT_I4: // 3
A = STRING_FORMAT(_T("%ld"), var.intVal);
break;
case VT_R4: // 4
A = STRING_FORMAT(_T("%10.6f"), (double)var.fltVal);
break;
case VT_R8: // 5
A = STRING_FORMAT(_T("%10.6f"), var.dblVal);
break;
case VT_CY: // 6
varBSTR.vt = VT_BSTR;
varBSTR.bstrVal = L"";
VariantChangeType(&varBSTR, &var, VARIANT_NOVALUEPROP, varBSTR.vt);
A = STRING_FORMAT(_T("%10.6f"), varBSTR.dblVal);
break;
case VT_DATE: // 7
VariantTimeToSystemTime(var.date, &st);
A = STRING_FORMAT(_T("%04d-%02d-%02d %02d:%02d:%02d.%d"),
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
break;
case VT_BSTR: // 8
A = WToT(var.bstrVal);
break;
case VT_DISPATCH: // 9
A = STRING_FORMAT(_T("0x%lX"), var.pdispVal);
break;
case VT_ERROR: // 10
A = STRING_FORMAT(_T("%ld"), var.scode);
break;
case VT_BOOL: // 11
A = STRING_FORMAT(_T("%d"), varBSTR.boolVal);
break;
case VT_VARIANT: // 12
A = STRING_FORMAT(_T("0x%lX"), var.pvarVal);
break;
case VT_UNKNOWN: // 13
A = STRING_FORMAT(_T("Unknow Ptr:0x%lX"), var.pvarVal);
break;
case VT_DECIMAL: // 14
dDecVal = var.decVal.Lo64;
dDecVal *= (var.decVal.sign == 128) ? -1 : 1;
dDecVal /= pow(10, var.decVal.scale);
A = STRING_FORMAT(tstring(_T("%.") + STRING_FORMAT(_T("%d"), var.decVal.scale) + _T("f")).c_str(), dDecVal);
break;
case VT_I1: // 16
A = STRING_FORMAT(_T("%C(0x%02X)"), var.cVal, var.cVal);
break;
case VT_UI1: // 17
A = STRING_FORMAT(_T("%C(0x%02X)"), var.cVal, var.cVal);
break;
case VT_UI2: // 18
A = STRING_FORMAT(_T("%u"), var.uiVal);
break;
case VT_UI4: // 19
A = STRING_FORMAT(_T("%u"), var.uintVal);
break;
case VT_I8: // 20
A = STRING_FORMAT(_T("%lld"), var.llVal);
break;
case VT_UI8: // 21
A = STRING_FORMAT(_T("%llu"), var.ullVal);
break;
case VT_INT: // 22
A = STRING_FORMAT(_T("%ld"), var.intVal);
break;
case VT_UINT: // 23
A = STRING_FORMAT(_T("%lu"), var.uintVal);
break;
case VT_VOID: // 24
A = _T("");
break;
case VT_HRESULT: // 25
A = _T("");
break;
case VT_PTR: // 26
A = _T("");
break;
case VT_SAFEARRAY: // 27
//A = _T("");
{
HRESULT hResult = S_FALSE;
LONG lIdx = 0;
LONG lLbound = 0;
LONG lUbound = 0;
BSTR bsPropName = NULL;
hResult = SafeArrayGetLBound(var.parray, 1, &lLbound);
hResult = SafeArrayGetUBound(var.parray, 1, &lUbound);
A += _T("[");
for (lIdx = lLbound; lIdx <= lUbound; lIdx++) {
// Get this property name.
hResult = SafeArrayGetElement(var.parray, &lIdx, &bsPropName);
if (lIdx != lLbound)
{
A += _T(",");
}
if (FAILED(hResult))
{
A += _T("");
}
else
{
A += STRING_FORMAT(_T("%s"), WToT(bsPropName));
}
}
A += _T("]");
//hResult = SafeArrayDestroy(var.parray);
//var.parray = NULL;
}
break;
case VT_CARRAY: // 28
A = _T("");
break;
case VT_USERDEFINED: // 29
A = _T("");
break;
case VT_LPSTR: // 30
A = AToT(var.pcVal);
break;
case VT_LPWSTR: // 31
A = WToT(var.bstrVal);
break;
case VT_RECORD: // 36
A = _T("");
break;
case VT_INT_PTR: // 37
A = _T("");
break;
case VT_UINT_PTR: // 38
A = _T("");
break;
case VT_FILETIME: // 64
A = _T("");
break;
case VT_BLOB: // 65
A = _T("");
break;
case VT_STREAM: // 66
A = _T("");
break;
case VT_STORAGE: // 67
A = _T("");
break;
case VT_STREAMED_OBJECT: // 68
A = _T("");
break;
case VT_STORED_OBJECT: // 69
A = _T("");
break;
case VT_BLOB_OBJECT: // 70
A = _T("");
break;
case VT_CF: // 71
A = _T("");
break;
case VT_CLSID: // 72
A = _T("");
break;
case VT_VERSIONED_STREAM: // 73
A = _T("");
break;
case VT_BSTR_BLOB: // 0xfff
A = _T("");
break;
case VT_VECTOR: // 0x1000
A = _T("");
break;
case VT_ARRAY: // 0x2000
A = _T("");
break;
case VT_ARRAY | VT_UI1: // 0x2011
{
HRESULT hResult = S_FALSE;
LONG lIdx = 0;
LONG lLbound = 0;
LONG lUbound = 0;
BYTE bValue = NULL;
hResult = SafeArrayGetLBound(var.parray, 1, &lLbound);
hResult = SafeArrayGetUBound(var.parray, 1, &lUbound);
A += _T("[");
for (lIdx = lLbound; lIdx <= lUbound; lIdx++) {
// Get this property name.
hResult = SafeArrayGetElement(var.parray, &lIdx, &bValue);
if (lIdx != lLbound)
{
A += _T(",");
}
if (FAILED(hResult))
{
A += _T("");
}
else
{
A += STRING_FORMAT(_T("0x%02X"), bValue);
}
}
A += _T("]");
//hResult = SafeArrayDestroy(var.parray);
//var.parray = NULL;
}
break;
case VT_BYREF: // 0x4000
A = _T("");
break;
case VT_RESERVED: // 0x8000
A = _T("");
break;
case VT_ILLEGAL: // 0xffff
A = _T("");
break;
//case VT_ILLEGALMASKED: // 0xfff
// break;
//case VT_TYPEMASK: // 0xfff
// break;
default:
A = _T("");
break;
}
}
__inline static std::string SpeedToShortA(double dSpeed)
{
char cSpeed[MAXBYTE] = { 0 };
const int N_1KB = 1024;
const int N_1MB = N_1KB * N_1KB;
const int N_1GB = N_1MB * N_1KB;
if (dSpeed >= N_1GB)
{
dSpeed /= N_1GB;
sprintf(cSpeed, ("%lf GB/s"), dSpeed);
}
else if (dSpeed >= N_1MB)
{
dSpeed /= N_1MB;
sprintf(cSpeed, ("%lf MB/s"), dSpeed);
}
else if (dSpeed >= N_1KB)
{
dSpeed /= N_1KB;
sprintf(cSpeed, ("%lf KB/s"), dSpeed);
}
else
{
sprintf(cSpeed, ("%lf Bytes/s"), dSpeed);
}
return cSpeed;
}
__inline static std::wstring SpeedToShortW(double dSpeed)
{
wchar_t cSpeed[MAXBYTE] = { 0 };
const int N_1KB = 1024;
const int N_1MB = N_1KB * N_1KB;
const int N_1GB = N_1MB * N_1KB;
if (dSpeed >= N_1GB)
{
dSpeed /= N_1GB;
swprintf(cSpeed, (L"%lf GB/s"), dSpeed);
}
else if (dSpeed >= N_1MB)
{
dSpeed /= N_1MB;
swprintf(cSpeed, (L"%lf MB/s"), dSpeed);
}
else if (dSpeed >= N_1KB)
{
dSpeed /= N_1KB;
swprintf(cSpeed, (L"%lf KB/s"), dSpeed);
}
else
{
swprintf(cSpeed, (L"%lf Bytes/s"), dSpeed);
}
return cSpeed;
}
__inline static std::string TimeToShortA(double dTime)
{
char cTime[MAXBYTE] = { 0 };
const int N_1MIN = 60;
const int N_1HOUR = N_1MIN * N_1MIN;
const int N_1DAY = 24 * N_1HOUR;
double dExternTime = dTime;
int nUnit = 0;
while (dExternTime > 0)
{
if (dExternTime >= N_1DAY)
{
nUnit = dExternTime / N_1DAY;
sprintf(cTime, ("%d天"), nUnit);
dExternTime -= nUnit * N_1DAY;
}
else if (dExternTime > N_1HOUR)
{
nUnit = dExternTime / N_1HOUR;
sprintf(cTime, ("%s%d小时"), cTime, nUnit);
dExternTime -= nUnit * N_1HOUR;
}
else if (dExternTime > N_1MIN)
{
nUnit = dExternTime / N_1MIN;
sprintf(cTime, ("%s%d分钟"), cTime, nUnit);
dExternTime -= nUnit * N_1MIN;
}
else
{
sprintf(cTime, ("%s%lf秒"), cTime, dExternTime);
dExternTime = 0;
}
}
return std::string(cTime);
}
__inline static std::wstring TimeToShortW(double dTime)
{
wchar_t cTime[MAXBYTE] = { 0 };
const int N_1MIN = 60;
const int N_1HOUR = N_1MIN * N_1MIN;
const int N_1DAY = 24 * N_1HOUR;
double dExternTime = dTime;
int nUnit = 0;
while (dExternTime > 0)
{
if (dExternTime >= N_1DAY)
{
nUnit = dExternTime / N_1DAY;
swprintf(cTime, (L"%d天"), nUnit);
dExternTime -= nUnit * N_1DAY;
}
else if (dExternTime > N_1HOUR)
{
nUnit = dExternTime / N_1HOUR;
swprintf(cTime, (L"%s%d小时"), cTime, nUnit);
dExternTime -= nUnit * N_1HOUR;
}
else if (dExternTime > N_1MIN)
{
nUnit = dExternTime / N_1MIN;
swprintf(cTime, (L"%s%d分钟"), cTime, nUnit);
dExternTime -= nUnit * N_1MIN;
}
else
{
swprintf(cTime, (L"%s%lf秒"), cTime, dExternTime);
dExternTime = 0;
}
}
return std::wstring(cTime);
}
#if !defined(UNICODE) && !defined(_UNICODE)
#define SpeedToShort SpeedToShortA
#define TimeToShort TimeToShortA
#else
#define SpeedToShort SpeedToShortW
#define TimeToShort TimeToShortW
#endif
}
namespace FilePath{
__inline static BOOL SelectSaveFile(_TCHAR(&tFileName)[MAX_PATH], const _TCHAR * ptFilter = _T("Execute Files (*.EXE)\0*.EXE\0All Files (*.*)\0*.*\0\0"), HWND hWndOwner = NULL, DWORD dwFlags = OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST, LPOFNHOOKPROC lpofnHookProc = NULL)
{
BOOL bResult = FALSE;
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.lpstrFilter = ptFilter;
ofn.lpstrFile = tFileName;
ofn.hwndOwner = hWndOwner;
ofn.lpfnHook = lpofnHookProc;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = dwFlags;
bResult = GetSaveFileName(&ofn);
if (bResult == FALSE)
{
//dwError = CommDlgExtendedError();
//return bResult;
}
return bResult;
}
__inline static BOOL SelectOpenFile(_TCHAR(&tFileName)[MAX_PATH], const _TCHAR * ptFilter = _T("Execute Files (*.EXE)\0*.EXE\0All Files (*.*)\0*.*\0\0"), HWND hWndOwner = NULL, DWORD dwFlags = OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST, LPOFNHOOKPROC lpofnHookProc = NULL)
{
BOOL bResult = FALSE;
OPENFILENAME ofn = { 0 };
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.lpstrFilter = ptFilter;
ofn.lpstrFile = tFileName;
ofn.hwndOwner = hWndOwner;
ofn.lpfnHook = lpofnHookProc;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = dwFlags;
bResult = GetOpenFileName(&ofn);
if (bResult == FALSE)
{
//dwError = CommDlgExtendedError();
//return bResult;
}
return bResult;
}
//获取程序工作路径
__inline static tstring GetWorkPath()
{
tstring tsWorkPath = _T("");
_TCHAR tWorkPath[MAX_PATH] = { 0 };
GetCurrentDirectory(MAX_PATH, tWorkPath);
if (*tWorkPath)
{
tsWorkPath = tstring(tWorkPath) + _T("\\");
}
return tsWorkPath;
}
//获取系统临时路径
__inline static tstring GetTempPath()
{
_TCHAR tTempPath[MAX_PATH] = { 0 };
::GetTempPath(MAX_PATH, tTempPath);
return tstring(tTempPath);
}
//获取程序文件路径
__inline static tstring GetProgramPath()
{
tstring tsFilePath = _T("");
_TCHAR * pFoundPosition = 0;
_TCHAR tFilePath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, tFilePath, MAX_PATH);
if (*tFilePath)
{
pFoundPosition = _tcsrchr(tFilePath, _T('\\'));
if (*(++pFoundPosition))
{
*pFoundPosition = _T('\0');
}
tsFilePath = tFilePath;
}
return tsFilePath;
}
__inline static //获取系统路径
tstring GetSystemPath()
{
tstring tsSystemPath = _T("");
_TCHAR tSystemPath[MAX_PATH] = { 0 };
GetSystemDirectory(tSystemPath, MAX_PATH);
if (*tSystemPath)
{
tsSystemPath = tstring(tSystemPath) + _T("\\");
}
return tsSystemPath;
}
__inline static //获取系统路径
tstring GetSystemPathX64()
{
tstring tsSystemPath = _T("");
_TCHAR tSystemPath[MAX_PATH] = { 0 };
GetSystemWow64Directory(tSystemPath, MAX_PATH);
if (*tSystemPath)
{
tsSystemPath = tstring(tSystemPath) + _T("\\");
}
return tsSystemPath;
}
__inline static
BOOL FileIsExists(LPCTSTR pFileName)
{
WIN32_FILE_ATTRIBUTE_DATA wfad = { 0 };
return (GetFileAttributesEx(pFileName, GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &wfad)
? ((wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY) : FALSE);
}
__inline static
BOOL PathIsExists(LPCTSTR pFileName)
{
WIN32_FILE_ATTRIBUTE_DATA wfad = { 0 };
return (GetFileAttributesEx(pFileName, GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &wfad)
? !((wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) : FALSE);
}
__inline static
BOOL IsPathExists(LPCTSTR pFileName)
{
WIN32_FILE_ATTRIBUTE_DATA wfad = { 0 };
return (GetFileAttributesEx(pFileName, GET_FILEEX_INFO_LEVELS::GetFileExInfoStandard, &wfad)
? !((wfad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) : FALSE);
}
__inline static
BOOL IsFileExist(LPCTSTR fileName)
{
HANDLE hFindFile = NULL;
WIN32_FIND_DATA findData = { 0 };
hFindFile = FindFirstFile(fileName, &findData);
if (hFindFile != INVALID_HANDLE_VALUE)
{
FindClose(hFindFile);
hFindFile = NULL;
return TRUE;
}
return FALSE;
}
__inline static
BOOL IsFileExistEx(LPCTSTR lpFileName)
{
WIN32_FILE_ATTRIBUTE_DATA wfad = { 0 };
GET_FILEEX_INFO_LEVELS gfil = GetFileExInfoStandard;
if (GetFileAttributes(lpFileName) != INVALID_FILE_ATTRIBUTES)
{
return TRUE;
}
else
{
if (GetFileAttributesEx(lpFileName, gfil, &wfad) &&
wfad.dwFileAttributes != INVALID_FILE_ATTRIBUTES)
{
return TRUE;
}
}
return FALSE;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:遍历目录获取指定文件列表
// 参 数:输出的文件行内容数据、过滤后缀名、过滤的前缀字符
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static BOOL DirectoryTraversal(std::vector<TSTRING> * pTV, LPCTSTR lpRootPath = _T("."), LPCTSTR lpExtension = _T("*.*"))
{
BOOL bResult = FALSE;
HANDLE hFindFile = NULL;
WIN32_FIND_DATA wfd = { 0 };
_TCHAR tFindPath[MAX_PATH + 1] = { 0 };
//构建遍历根目录
wsprintf(tFindPath, TEXT("%s%s"), lpRootPath, lpExtension);
hFindFile = FindFirstFileEx(tFindPath, FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
//hFindFile = FindFirstFile(tRootPath, &wfd);
if (hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
{
pTV->push_back(TSTRING(TSTRING(lpRootPath) + wfd.cFileName));
}
else
{
if (lstrcmp(wfd.cFileName, _T(".")) && lstrcmp(wfd.cFileName, _T("..")))
{
bResult = DirectoryTraversal(pTV, TSTRING(TSTRING(lpRootPath) + wfd.cFileName + _T("\\")).c_str(), lpExtension);
}
}
} while (FindNextFile(hFindFile, &wfd));
FindClose(hFindFile);
hFindFile = NULL;
bResult = TRUE;
}
return bResult;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:遍历目录获取指定文件列表
// 参 数:输出的文件行内容数据、过滤后缀名、过滤的前缀字符
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static BOOL DirectoryTraversal(std::map<SIZE_T, TSTRING> * pSTMAP, LPCTSTR lpRootPath = _T("."), LPCTSTR lpExtension = _T("*.*"))
{
BOOL bResult = FALSE;
HANDLE hFindFile = NULL;
WIN32_FIND_DATA wfd = { 0 };
_TCHAR tFindPath[MAX_PATH + 1] = { 0 };
//构建遍历根目录
wsprintf(tFindPath, TEXT("%s%s"), lpRootPath, lpExtension);
hFindFile = FindFirstFileEx(tFindPath, FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
//hFindFile = FindFirstFile(tRootPath, &wfd);
if (hFindFile != INVALID_HANDLE_VALUE)
{
do
{
pSTMAP->insert(std::map<SIZE_T, TSTRING>::value_type(pSTMAP->size(), TSTRING(TSTRING(lpRootPath) + wfd.cFileName)));
if (((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) && (lstrcmp(wfd.cFileName, _T(".")) && lstrcmp(wfd.cFileName, _T(".."))))
{
bResult = DirectoryTraversal(pSTMAP, TSTRING(TSTRING(lpRootPath) + wfd.cFileName + _T("\\")).c_str(), lpExtension);
}
} while (FindNextFile(hFindFile, &wfd));
FindClose(hFindFile);
hFindFile = NULL;
bResult = TRUE;
}
return bResult;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:遍历目录获取指定文件列表
// 参 数:输出的文件行内容数据、过滤后缀名、过滤的前缀字符
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static BOOL DirectoryTraversal(std::map<TSTRING, TSTRING> * pTTMAP, LPCTSTR lpFindPath = _T(".\\"), LPCTSTR lpRootPath = _T(".\\"), LPCTSTR lpExtension = _T("*.*"))
{
BOOL bResult = FALSE;
HANDLE hFindFile = NULL;
WIN32_FIND_DATA wfd = { 0 };
_TCHAR tChildPath[MAX_PATH + 1] = { 0 };
_TCHAR tFindFileName[MAX_PATH + 1] = { 0 };
if ((lstrlen(lpFindPath) >= lstrlen(lpRootPath)) && StrStrI(lpFindPath, lpRootPath))
{
wsprintf(tChildPath, _T("%s"), lpFindPath + lstrlen(lpRootPath));
}
//构建遍历根目录
wsprintf(tFindFileName, TEXT("%s%s"), lpFindPath, lpExtension);
hFindFile = FindFirstFileEx(tFindFileName, FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0);
//hFindFile = FindFirstFile(tRootPath, &wfd);
if (hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
{
pTTMAP->insert(std::map<TSTRING, TSTRING>::value_type((TSTRING(lpFindPath) + wfd.cFileName), TSTRING(tChildPath) + wfd.cFileName));
}
else
{
if (lstrcmp(wfd.cFileName, _T(".")) && lstrcmp(wfd.cFileName, _T("..")))
{
pTTMAP->insert(std::map<TSTRING, TSTRING>::value_type(TSTRING(lpFindPath) + wfd.cFileName, TSTRING(tChildPath) + wfd.cFileName + _T("\\")));
bResult = DirectoryTraversal(pTTMAP, TSTRING(TSTRING(lpFindPath) + wfd.cFileName + _T("\\")).c_str(), lpRootPath, lpExtension);
}
}
} while (FindNextFile(hFindFile, &wfd));
FindClose(hFindFile);
hFindFile = NULL;
bResult = TRUE;
}
return bResult;
}
//判断目录是否存在,若不存在则创建
__inline static BOOL CreateCascadeDirectory(LPCTSTR lpPathName, //Directory name
LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL // Security attribute
)
{
_TCHAR *pToken = NULL;
_TCHAR tPathTemp[MAX_PATH] = { 0 };
_TCHAR tPathName[MAX_PATH] = { 0 };
_tcscpy(tPathName, lpPathName);
pToken = _tcstok(tPathName, _T("\\"));
while (pToken)
{
_sntprintf(tPathTemp, sizeof(tPathTemp) / sizeof(_TCHAR), _T("%s%s\\"), tPathTemp, pToken);
if (!IsFileExistEx(tPathTemp))
{
//创建失败时还应删除已创建的上层目录,此次略
if (!CreateDirectory(tPathTemp, lpSecurityAttributes))
{
_tprintf(_T("CreateDirectory Failed: %d\n"), GetLastError());
return FALSE;
}
}
pToken = _tcstok(NULL, _T("\\"));
}
return TRUE;
}
__inline static LPVOID MapViewOfFileAgain(HANDLE hFileMapping, LPVOID * lppBaseAddress, ULARGE_INTEGER * pui, SIZE_T stNumberOfBytesToMap = 0, LPVOID lpBaseAddress = 0)
{
if (lppBaseAddress && (*lppBaseAddress))
{
::UnmapViewOfFile((*lppBaseAddress));
(*lppBaseAddress) = NULL;
}
return ((*lppBaseAddress) = ::MapViewOfFileEx(hFileMapping, FILE_MAP_ALL_ACCESS, pui->HighPart, pui->LowPart, stNumberOfBytesToMap, lpBaseAddress));
}
__inline static void MapRelease(HANDLE * phFileMapping, LPVOID * lpBaseAddress)
{
if (lpBaseAddress && (*lpBaseAddress))
{
// 从进程的地址空间撤消文件数据映像
::UnmapViewOfFile((*lpBaseAddress));
(*lpBaseAddress) = NULL;
}
if (phFileMapping && (*phFileMapping))
{
// 关闭文件映射对象
::CloseHandle((*phFileMapping));
(*phFileMapping) = NULL;
}
}
__inline static HANDLE MapFileCreate(LPVOID * lpFileData, LPCTSTR lpFileName)
{
DWORD dwResult = 0;
PBYTE pbFile = NULL;
BOOL bLoopFlag = FALSE;
HANDLE hWaitEvent[] = { 0, 0 };
DWORD dwWaitEventNum = sizeof(hWaitEvent) / sizeof(HANDLE);
SYSTEM_INFO si = { 0 };
HANDLE hFileMapping = NULL;
LPVOID lpBaseAddress = NULL;
ULONGLONG ullFileVolume = 0LL;
SIZE_T stNumberOfBytesToMap = 0;
ULARGE_INTEGER uiFileSize = { 0, 0 };
// 创建文件内核对象,其句柄保存于hFile
HANDLE hFile = ::CreateFile(lpFileName,
GENERIC_WRITE | GENERIC_READ,
FILE_SHARE_READ,
NULL,
CREATE_ALWAYS,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
uiFileSize.LowPart = ::GetFileSize(hFile, &uiFileSize.HighPart);
// 创建文件映射内核对象,句柄保存于hFileMapping
hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE,
uiFileSize.HighPart, uiFileSize.LowPart, NULL);
if (hFile)
{
// 释放文件内核对象
CloseHandle(hFile);
hFile = NULL;
}
if (hFileMapping)
{
// 设定大小、偏移量等参数
//SystemKernel::GetNativeSystemInformation(&si);
//ullFileVolume = si.dwAllocationGranularity;
// 将文件数据映射到进程的地址空间
(*lpFileData) = MapViewOfFileEx(hFileMapping, FILE_MAP_ALL_ACCESS,
uiFileSize.HighPart, uiFileSize.LowPart, stNumberOfBytesToMap, lpBaseAddress);
}
return hFileMapping;
}
__inline static HANDLE MapCreate(LPVOID * lpData, LPCTSTR lpMapName, ULARGE_INTEGER * puiFileSize)
{
SYSTEM_INFO si = { 0 };
HANDLE hFileMapping = NULL;
LPVOID lpBaseAddress = NULL;
ULONGLONG ullFileVolume = 0LL;
SIZE_T stNumberOfBytesToMap = 0;
// 创建文件映射内核对象,句柄保存于hFileMapping
hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
puiFileSize->HighPart, puiFileSize->LowPart, lpMapName);
if (hFileMapping)
{
// 设定大小、偏移量等参数
//PPSHUAI::SystemKernel::GetNativeSystemInformation(&si);
//ullFileVolume = si.dwAllocationGranularity;
// 将文件数据映射到进程的地址空间
(*lpData) = MapViewOfFileEx(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, puiFileSize->QuadPart, lpBaseAddress);
}
return hFileMapping;
}
#define LOGG_FILE_NAME "file.log"
//记录日志接口
__inline static void DebugPrint(int fd, const void * data, unsigned long size)
{
write(fd, data, size);
}
//记录日志接口
__inline static void DebugPrint(int fd, const void * data, unsigned long size, bool bEcho)
{
DebugPrint(fd, data, size);
if (bEcho)
{
DebugPrint(fileno(stdout), data, size);
}
}
//记录日志接口
__inline static void DebugPrint(const void * data, unsigned long size, bool bEcho = false, const _TCHAR * pLogFile = _T(LOGG_FILE_NAME))
{
int fd = 0;
struct _stat64i32 st = { 0 };
_tstat(pLogFile, &st);
if ((st.st_mode & S_IFREG) != S_IFREG)
{
//fd = _topen(logfilename, O_CREAT | O_TRUNC | O_RDWR);
fd = _topen(pLogFile, O_CREAT | O_TRUNC | O_RDWR, 0777);
}
else
{
//fd = _topen(logfilename, O_CREAT | O_APPEND | O_RDWR);
fd = _topen(pLogFile, O_APPEND | O_RDWR, 0777);
////不是今天
//if (DATE_FROM_TIME(st.st_mtime).compare(DATE_FROM_TIME(tv.tv_sec)))
//{
// //fd = _topen(logfilename, O_CREAT | O_TRUNC | O_RDWR);
// fd = _topen(pLogFile, O_CREAT | O_TRUNC | O_RDWR, 0777);
//}
}
if (fd)
{
DebugPrint(fd, data, size, bEcho);
if ((fd != fileno(stdin)) && (fd != fileno(stdout)) && (fd != fileno(stderr)))
{
close(fd);
}
}
}
//记录日志接口
__inline static void DebugPrintC(const _TCHAR * pLogInfo, bool bTime = false, bool bEcho = false, const _TCHAR * pLogFile = _T(LOGG_FILE_NAME))
{
std::string str = ("");
if (bTime)
{
struct timeval tv = { 0 };
gettimeofday(&tv);
str = STRING_FORMAT_A(("[%s] %s"), STRING_FORMAT_DATETIME_A(&tv).c_str(), Convert::TToA(pLogInfo).c_str());
}
else
{
str = Convert::TToA(pLogInfo);
}
DebugPrint(str.c_str(), str.size(), bEcho, pLogFile);
}
//记录日志接口
__inline static void DebugPrintString(tstring tsLogInfo, bool bTime = false, bool bEcho = true, tstring tsLogFile = _T(LOGG_FILE_NAME))
{
DebugPrintC(tsLogInfo.c_str(), bTime, bEcho, tsLogFile.c_str());
}
#define CMD_PATH_NAME "CMD.EXE" //相对路径名称
//获取cmd.exe文件路径
__inline static tstring GetCmdPath()
{
return GetSystemPath() + _T(CMD_PATH_NAME);
}
//设定cmd.exe路径
static const tstring CMD_FULL_PATH_NAME = GetCmdPath();
}
namespace String{
__inline static size_t file_reader(char ** ppdata, size_t &size, std::string filename, std::string mode = "rb")
{
#define DATA_BASE_SIZE 0x10000
FILE * pF = 0;
size_t sizeofread = 0;
char * pdata = 0;
pF = fopen(filename.c_str(), mode.c_str());
if (pF)
{
size = 0;
(*ppdata) = (char *)malloc((size + DATA_BASE_SIZE) * sizeof(char));
while (!feof(pF))
{
sizeofread = fread((void *)((*ppdata) + size), sizeof(char), DATA_BASE_SIZE, pF);
size += sizeofread;
if (sizeofread >= DATA_BASE_SIZE)
{
break;
}
pdata = (*ppdata);
(*ppdata) = (char *)realloc(pdata, (size + DATA_BASE_SIZE) * sizeof(char));
if (!(*ppdata) || GetLastError() != ERROR_SUCCESS)
{
if (pdata)
{
free(pdata);
pdata = 0;
}
break;
}
}
fclose(pF);
pF = 0;
}
return size;
#undef DATA_BASE_SIZE
}
__inline static size_t file_reader(std::string&data, std::string filename, std::string mode = "rb")
{
#define DATA_BASE_SIZE 0x10000
FILE * pF = 0;
size_t size = 0;
pF = fopen(filename.c_str(), mode.c_str());
if (pF)
{
while (!feof(pF))
{
data.resize(data.size() + DATA_BASE_SIZE);
size += fread((void *)(data.c_str() + data.size() - DATA_BASE_SIZE), sizeof(char), DATA_BASE_SIZE, pF);
}
data.resize(size);
fclose(pF);
pF = 0;
}
return size;
#undef DATA_BASE_SIZE
}
__inline static size_t file_writer(std::string data, std::string filename, std::string mode = "wb")
{
FILE * pF = 0;
size_t size = 0;
pF = fopen(filename.c_str(), mode.c_str());
if (pF)
{
size = fwrite((void *)(data.c_str()), sizeof(char), data.size(), pF);
fclose(pF);
pF = 0;
}
return size;
}
__inline static size_t file_writer(char * data, size_t size, std::string filename, std::string mode = "wb")
{
FILE * pF = 0;
size_t ssize = 0;
pF = fopen(filename.c_str(), mode.c_str());
if (pF)
{
ssize = fwrite((void *)(data), sizeof(char), size, pF);
fclose(pF);
pF = 0;
}
return ssize;
}
__inline static bool string_regex_valid(std::string data, std::string pattern)
{
return std::regex_match(data, std::regex(pattern));
}
__inline static int string_regex_replace_all(std::string & result, std::string & data, std::string replace, std::string pattern, std::regex_constants::match_flag_type matchflagtype = std::regex_constants::match_default)
{
int nresult = (-1);
try
{
data = std::regex_replace(data, std::regex(pattern), replace, matchflagtype);
nresult = data.length();
}
catch (const std::exception & e)
{
result = e.what();
}
return nresult;
}
__inline static bool string_regex_find(std::string & result, STRINGVECTORVECTOR & svv, std::string & data, std::string pattern)
{
std::smatch smatch;
bool bresult = false;
result = ("");
try
{
std::string::const_iterator itb = data.begin();
std::string::const_iterator ite = data.end();
while (std::regex_search(itb, ite, smatch, std::regex(pattern)))//如果匹配成功
{
if (smatch.size() > 1)
{
for (size_t stidx = svv.size() + 1; stidx < smatch.size(); stidx++)
{
svv.push_back(STRINGVECTOR());
}
for (size_t stidx = 1; stidx < smatch.size(); stidx++)
{
svv.at(stidx - 1).push_back(std::string(smatch[stidx].first, smatch[stidx].second));
itb = smatch[stidx].second;
}
bresult = true;
}
}
}
catch (const std::exception & e)
{
result = e.what();
}
return bresult;
}
//获取指定两个字符串之间的字符串数据
__inline static std::string string_reader(std::string strData,
std::string strStart, std::string strFinal,
bool bTakeStart = false, bool bTakeFinal = false)
{
std::string strRet = ("");
std::string::size_type stStartPos = std::string::npos;
std::string::size_type stFinalPos = std::string::npos;
stStartPos = strData.find(strStart);
if (stStartPos != std::string::npos)
{
stFinalPos = strData.find(strFinal, stStartPos + strStart.length());
if (stFinalPos != std::string::npos)
{
if (!bTakeStart)
{
stStartPos += strStart.length();
}
if (bTakeFinal)
{
stFinalPos += strFinal.length();
}
strRet = strData.substr(stStartPos, stFinalPos - stStartPos);
}
}
return strRet;
}
//获取指定两个字符串之间的字符串数据
__inline static std::string::size_type string_reader(std::string &strRet, std::string strData,
std::string strStart, std::string strFinal, std::string::size_type stPos = 0,
bool bTakeStart = false, bool bTakeFinal = false)
{
std::string::size_type stRetPos = std::string::npos;
std::string::size_type stStartPos = stPos;
std::string::size_type stFinalPos = std::string::npos;
strRet = ("");
stStartPos = strData.find(strStart, stStartPos);
if (stStartPos != std::string::npos)
{
stRetPos = stFinalPos = strData.find(strFinal, stStartPos + strStart.length());
if (stFinalPos != std::string::npos)
{
if (!bTakeStart)
{
stStartPos += strStart.length();
}
if (bTakeFinal)
{
stFinalPos += strFinal.length();
}
strRet = strData.substr(stStartPos, stFinalPos - stStartPos);
}
}
return stRetPos;
}
__inline static std::string string_replace_all(std::string &strData, std::string strDst, std::string strSrc, std::string::size_type stPos = 0)
{
while ((stPos = strData.find(strSrc, stPos)) != std::string::npos)
{
strData.replace(stPos, strSrc.length(), strDst);
}
return strData;
}
__inline static void string_split_to_vector(STRINGVECTOR & sv, std::string strData, std::string strSplitter, std::string::size_type stPos = 0)
{
std::string strTmp = ("");
std::string::size_type stIdx = 0;
std::string::size_type stSize = strData.length();
while ((stPos = strData.find(strSplitter, stIdx)) != std::string::npos)
{
strTmp = strData.substr(stIdx, stPos - stIdx);
if (!strTmp.length())
{
strTmp = ("");
}
sv.push_back(strTmp);
stIdx = stPos + strSplitter.length();
}
if (stIdx < stSize)
{
strTmp = strData.substr(stIdx, stSize - stIdx);
if (!strTmp.length())
{
strTmp = ("");
}
sv.push_back(strTmp);
}
}
//获取指定两个字符串之间的字符串数据
__inline static std::wstring wstring_reader(std::wstring wstrData,
std::wstring wstrStart, std::wstring wstrFinal,
bool bTakeStart = false, bool bTakeFinal = false)
{
std::wstring wstrRet = (L"");
std::wstring::size_type stStartPos = std::wstring::npos;
std::wstring::size_type stFinalPos = std::wstring::npos;
stStartPos = wstrData.find(wstrStart);
if (stStartPos != std::wstring::npos)
{
stFinalPos = wstrData.find(wstrFinal, stStartPos + wstrStart.length());
if (stFinalPos != std::wstring::npos)
{
if (!bTakeStart)
{
stStartPos += wstrStart.length();
}
if (bTakeFinal)
{
stFinalPos += wstrFinal.length();
}
wstrRet = wstrData.substr(stStartPos, stFinalPos - stStartPos);
}
}
return wstrRet;
}
//获取指定两个字符串之间的字符串数据
__inline static std::wstring::size_type wstring_reader(std::wstring &wstrRet, std::wstring wstrData,
std::wstring wstrStart, std::wstring wstrFinal, std::wstring::size_type stPos = std::wstring::npos,
bool bTakeStart = false, bool bTakeFinal = false)
{
std::wstring::size_type stRetPos = std::wstring::npos;
std::wstring::size_type stStartPos = stPos;
std::wstring::size_type stFinalPos = std::wstring::npos;
wstrRet = (L"");
stStartPos = wstrData.find(wstrStart);
if (stStartPos != std::wstring::npos)
{
stRetPos = stFinalPos = wstrData.find(wstrFinal, stStartPos + wstrStart.length());
if (stFinalPos != std::wstring::npos)
{
if (!bTakeStart)
{
stStartPos += wstrStart.length();
}
if (bTakeFinal)
{
stFinalPos += wstrFinal.length();
}
wstrRet = wstrData.substr(stStartPos, stFinalPos - stStartPos);
}
}
return stRetPos;
}
__inline static std::wstring wstring_replace_all(std::wstring &wstrData, std::wstring wstrDst, std::wstring wstrSrc, std::wstring::size_type stPos = 0)
{
while ((stPos = wstrData.find(wstrSrc, stPos)) != std::wstring::npos)
{
wstrData.replace(stPos, wstrSrc.length(), wstrDst);
}
return wstrData;
}
__inline static void wstring_split_to_vector(WSTRINGVECTOR & wsv, std::wstring wstrData, std::wstring wstrSplitter, std::wstring::size_type stPos = 0)
{
std::wstring wstrTemp = (L"");
std::wstring::size_type stIdx = 0;
std::wstring::size_type stSize = wstrData.length();
while ((stPos = wstrData.find(wstrSplitter, stIdx)) != std::wstring::npos)
{
wstrTemp = wstrData.substr(stIdx, stPos - stIdx);
if (!wstrTemp.length())
{
wstrTemp = (L"");
}
wsv.push_back(wstrTemp);
stIdx = stPos + wstrSplitter.length();
}
if (stIdx < stSize)
{
wstrTemp = wstrData.substr(stIdx, stSize - stIdx);
if (!wstrTemp.length())
{
wstrTemp = (L"");
}
wsv.push_back(wstrTemp);
}
}
#if !defined(UNICODE) && !defined(_UNICODE)
#define TSTRING_SPLIT_TO_VECTOR string_split_to_vector
#else
#define TSTRING_SPLIT_TO_VECTOR wstring_split_to_vector
#endif
//////////////////////////////////////////////////////////////////////////
// 函数说明:选择读取数据行从文件中
// 参 数:输出的文件行内容数据、过滤后缀名、过滤的前缀字符
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline bool ReadLinesFromFile(TSTRINGVECTOR * pStringVector, LPTSTR lpFilter = TEXT(""), TCHAR tNote = TEXT(';'), HWND hWnd = NULL)
{
bool result = false;
FILE * pFile = NULL;
TCHAR tFileName[MAX_PATH + 1] = { 0 };
TCHAR tLineData[MAX_PATH * 4 + 1] = { 0 };
pFile = _tfopen(tFileName, TEXT("rb"));
if (pFile)
{
while (!feof(pFile))
{
_fgetts(tLineData, sizeof(tLineData), pFile);
if (*tLineData != tNote && lstrlen(tLineData))
{
pStringVector->push_back(tLineData);
}
}
fclose(pFile);
pFile = NULL;
result = true;
}
return result;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:执行程序命令并获取执行打印信息
// 参 数:输出的文件行内容数据、要执行的命令
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static bool ExecuteCommand(TSTRINGVECTOR * pStringVector, tstring tCommandLine)
{
bool result = false;
FILE * ppipe = NULL;
tstring tItemText = TEXT("");
_TCHAR tItemChar[2] = { TEXT('\0') };
if (pStringVector)
{
// Open pipe to execute command line
ppipe = _tpopen(tCommandLine.c_str(), TEXT("rb"));
if (ppipe)
{
/* Read pipe until end of file, or an error occurs. */
while (fread(&tItemChar, sizeof(_TCHAR), 1, ppipe))
{
if ((*tItemChar != TEXT('\n'))
&& (*tItemChar != TEXT('\0')))
{
*(tItemChar + 1) = TEXT('\0');
tItemText.append(tItemChar);
}
else
{
pStringVector->push_back(tItemText);
tItemText.empty();
tItemText = TEXT("");
}
}
pStringVector->push_back(tItemText);
/* Close pipe and print return value of pPipe. */
if (feof(ppipe))
{
result = true;
_pclose(ppipe);
ppipe = NULL;
}
}
}
return result;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:执行程序命令并获取执行打印信息
// 参 数:输出的文件行内容数据、要执行的命令
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static bool ExecuteCommandEx(TSTRINGVECTOR * pStdOutputStringVector,
TSTRINGVECTOR * pStdErrorStringVector,
tstring tExecuteFile,
tstring tCommandLine)
{
bool result = false;
STARTUPINFO si = { 0 };
HANDLE hStdErrorRead = NULL;
HANDLE hStdOutputRead = NULL;
HANDLE hStdErrorWrite = NULL;
HANDLE hStdOutputWrite = NULL;
SECURITY_ATTRIBUTES sa = { 0 };
PROCESS_INFORMATION pi = { 0 };
tstring tItemText = TEXT("");
_TCHAR tItemChar[2] = { TEXT('\0') };
unsigned long ulBytesOfRead = 0;
unsigned long ulBytesOfWritten = 0;
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
// Set the bInheritHandle flag so pipe handles are inherited.
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if (CreatePipe(&hStdOutputRead, &hStdOutputWrite, &sa, 0) &&
CreatePipe(&hStdErrorRead, &hStdErrorWrite, &sa, 0))
{
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (SetHandleInformation(hStdOutputRead, HANDLE_FLAG_INHERIT, 0) &&
SetHandleInformation(hStdErrorRead, HANDLE_FLAG_INHERIT, 0))
{
si.hStdOutput = hStdOutputWrite;
si.hStdError = hStdErrorWrite;
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
// Start the child process.
if (CreateProcess(tExecuteFile.size() ? tExecuteFile.c_str() : NULL, // No module name (use command line)
(TCHAR *)tCommandLine.c_str(), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
TRUE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi)) // Pointer to PROCESS_INFORMATION structure
{
// Wait until child process exits.
//WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
if (hStdOutputWrite)
{
CloseHandle(hStdOutputWrite);
hStdOutputWrite = NULL;
}
if (hStdErrorWrite)
{
CloseHandle(hStdErrorWrite);
hStdErrorWrite = NULL;
}
if (pStdOutputStringVector)
{
while (ReadFile(hStdOutputRead, tItemChar, sizeof(_TCHAR),
&ulBytesOfRead, NULL) && ulBytesOfRead)
{
if ((*tItemChar != TEXT('\n')) &&
(*tItemChar != TEXT('\0')))
{
*(tItemChar + 1) = TEXT('\0');
tItemText.append(tItemChar);
}
else
{
pStdOutputStringVector->push_back(tItemText);
tItemText.empty();
tItemText = TEXT("");
}
}
pStdOutputStringVector->push_back(tItemText);
}
if (pStdErrorStringVector)
{
while (ReadFile(hStdErrorRead, tItemChar, sizeof(_TCHAR),
&ulBytesOfRead, NULL) && ulBytesOfRead)
{
if ((*tItemChar != TEXT('\n')) &&
(*tItemChar != TEXT('\0')))
{
*(tItemChar + 1) = TEXT('\0');
tItemText.append(tItemChar);
}
else
{
pStdErrorStringVector->push_back(tItemText);
tItemText.empty();
tItemText = TEXT("");
}
}
pStdErrorStringVector->push_back(tItemText);
}
result = true;
}
}
}
if (hStdErrorWrite)
{
CloseHandle(hStdErrorWrite);
hStdErrorWrite = NULL;
}
if (hStdOutputWrite)
{
CloseHandle(hStdOutputWrite);
hStdOutputWrite = NULL;
}
if (hStdErrorRead)
{
CloseHandle(hStdErrorRead);
hStdErrorRead = NULL;
}
if (hStdOutputRead)
{
CloseHandle(hStdOutputRead);
hStdOutputRead = NULL;
}
return result;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:执行程序命令并获取执行打印信息
// 参 数:输出的文件行内容数据、要执行的命令
// 返 回 值:BOOL返回类型,成功返回TRUE;失败返回FALSE
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static BOOL ExecuteProcess(TCHAR * pProcName, TCHAR * pCmdLine,
BOOL bShowFlag = FALSE, DWORD dwMilliseconds = INFINITE)
{
BOOL bResult = FALSE;
DWORD dwShowFlag = 0;
STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };
DWORD dwCmdLineSizeLength = 0;
TCHAR szCmdLine[MAX_PATH * 4 + 1] = { 0 };
si.cb = sizeof(si);
dwShowFlag = bShowFlag ? NULL : CREATE_NO_WINDOW;
if (pCmdLine != NULL)
{
dwCmdLineSizeLength = (lstrlen(pCmdLine) < sizeof(szCmdLine)) ?
lstrlen(pCmdLine) : sizeof(szCmdLine);
lstrcpyn(szCmdLine, pCmdLine, dwCmdLineSizeLength);
bResult = ::CreateProcess(pProcName, szCmdLine, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS | dwShowFlag, NULL, NULL, &si, &pi);
}
else
{
bResult = ::CreateProcess(pProcName, szCmdLine, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS | dwShowFlag, NULL, NULL, &si, &pi);
}
if (bResult)
{
WaitForSingleObject(pi.hProcess, dwMilliseconds);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
return bResult;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:执行程序命令并获取执行打印信息
// 参 数:要删除的文件名
// 返 回 值:bool返回类型,成功返回true;失败返回false
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static BOOL ForceDeleteFile(TCHAR * pszFileName)
{
BOOL bResult = FALSE;
TCHAR tSystemPath[MAX_PATH + 1] = { 0 };
TCHAR tCmdLine[MAX_PATH * 4 + 1] = { 0 };
if (pszFileName && (*pszFileName))
{
wsprintf(tCmdLine, TEXT("%sCMD.EXE /c DEL /F /S /Q \"%s\""), FilePath::GetSystemPath().c_str(), pszFileName);
bResult = ExecuteProcess(NULL, tCmdLine);
}
return bResult;
}
}
namespace SystemKernel{
__inline static BOOL CreateAdvanceProcess(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
DWORD dwCreateFlags,
LPCTSTR lpCurrentDirectory = NULL,
LPSTARTUPINFO lpStartupInfo = NULL,
LPPROCESS_INFORMATION lpProcessInformation = NULL,
LPVOID lpEnvironment = NULL,
LPSECURITY_ATTRIBUTES lpProcessAttributes = NULL,
LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL,
BOOL bInheritHandles = FALSE)
{
STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };
LPSTARTUPINFO lpsi = &si;
LPPROCESS_INFORMATION lppi = π
if (lpStartupInfo)
{
lpsi = lpStartupInfo;
}
if (lpProcessInformation)
{
lppi = lpProcessInformation;
}
return CreateProcess(
lpApplicationName,
lpCommandLine,
lpProcessAttributes,
lpThreadAttributes,
bInheritHandles,
dwCreateFlags,
lpEnvironment,
lpCurrentDirectory,
lpsi,
lppi
);
}
__inline static BOOL CreateAdvanceProcessAsUser(
LPCTSTR lpApplicationName,
LPTSTR lpCommandLine,
DWORD dwCreateFlags,
LPCTSTR lpCurrentDirectory = NULL,
LPSTARTUPINFO lpStartupInfo = NULL,
LPPROCESS_INFORMATION lpProcessInformation = NULL,
LPVOID lpEnvironment = NULL,
LPSECURITY_ATTRIBUTES lpProcessAttributes = NULL,
LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL,
BOOL bInheritHandles = FALSE,
HANDLE hToken = NULL)
{
STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };
LPSTARTUPINFO lpsi = &si;
LPPROCESS_INFORMATION lppi = π
if (lpStartupInfo)
{
lpsi = lpStartupInfo;
}
if (lpProcessInformation)
{
lppi = lpProcessInformation;
}
return CreateProcessAsUser(
hToken,
lpApplicationName,
lpCommandLine,
lpProcessAttributes,
lpThreadAttributes,
bInheritHandles,
dwCreateFlags,
lpEnvironment,
lpCurrentDirectory,
lpsi,
lppi
);
}
//获取进程用户函数:
__inline static BOOL GetProcessUserName(TSTRING & strUser, DWORD dwID) // 进程ID
{
HANDLE hToken = NULL;
BOOL bResult = FALSE;
DWORD dwSize = 0;
TCHAR szUserName[256] = { 0 };
TCHAR szDomain[256] = { 0 };
DWORD dwDomainSize = 256;
DWORD dwNameSize = 256;
SID_NAME_USE SNU;
PTOKEN_USER pTokenUser = NULL;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwID);
strUser = _T("SYSTEM");
if (hProcess == NULL)
{
switch (GetLastError())
{
case ERROR_ACCESS_DENIED:
strUser = _T("SYSTEM");
break;
default:
strUser = _T("SYSTEM");
break;
}
return bResult;
}
__try
{
if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken))
{
bResult = FALSE;
__leave;
}
if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwSize, &dwSize))
{
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
bResult = FALSE;
__leave;
}
}
pTokenUser = NULL;
pTokenUser = (PTOKEN_USER)malloc(dwSize);
if (pTokenUser == NULL)
{
bResult = FALSE;
__leave;
}
if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwSize, &dwSize))
{
bResult = FALSE;
__leave;
}
if (LookupAccountSid(NULL, pTokenUser->User.Sid, szUserName, &dwNameSize, szDomain, &dwDomainSize, &SNU) != 0)
{
strUser = szUserName;
if (pTokenUser != NULL)
{
free(pTokenUser);
pTokenUser = NULL;
}
return TRUE;
}
}
__finally
{
if (pTokenUser != NULL)
{
free(pTokenUser);
pTokenUser = NULL;
}
}
return FALSE;
}
//获取Windows系统信息
__inline static VOID GetNativeSystemInformation(SYSTEM_INFO * psi)
{
typedef void (WINAPI *LPFN_GetNativeSystemInfo)(LPSYSTEM_INFO);
// Call GetNativeSystemInfo if supported or GetSystemInfo otherwise.
LPFN_GetNativeSystemInfo fnGetNativeSystemInfo = (LPFN_GetNativeSystemInfo)GetProcAddress(GetModuleHandle(_T("KERNEL32.DLL")), "GetNativeSystemInfo");
if (fnGetNativeSystemInfo)
{
fnGetNativeSystemInfo(psi);
}
else
{
GetSystemInfo(psi);
}
}
//获取操作系统版本信息
__inline static void GetWindowsVersion(DWORD * dwMajor, DWORD * dwMinor, DWORD * dwBuildNumber)
{
typedef void (WINAPI * LPFN_RtlGetNtVersionNumbers)(DWORD * dwMajor, DWORD * dwMinor, DWORD * dwBuildNumber);
LPFN_RtlGetNtVersionNumbers pfnRtlGetNtVersionNumbers = NULL;
pfnRtlGetNtVersionNumbers = (LPFN_RtlGetNtVersionNumbers)GetProcAddress(GetModuleHandle(_T("NTDLL.DLL")), "RtlGetNtVersionNumbers");
if (pfnRtlGetNtVersionNumbers)
{
pfnRtlGetNtVersionNumbers(dwMajor, dwMinor, dwBuildNumber);
(*dwBuildNumber) &= 0xFFFF;
}
}
//////////////////////////////////////////////////////////////////////////////
//判断进程是64位还是32位(bIsWow64为TRUE为64位,返回FALSE为32位)
__inline static BOOL IsWow64Process(BOOL & bIsWow64, HANDLE hProcess)
{
typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
BOOL bResult = FALSE;
LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
if (hProcess)
{
fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(_T("KERNEL32.DLL")), "IsWow64Process");
if (fnIsWow64Process)
{
bResult = fnIsWow64Process(hProcess, &bIsWow64);
}
}
return bResult;
}
__inline static BOOL IsWow64Process(BOOL & bIsWow64, DWORD dwProcessId)
{
BOOL bResult = FALSE;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId);
if (hProcess)
{
bResult = IsWow64Process(bIsWow64, hProcess);
CloseHandle(hProcess);
hProcess = NULL;
}
return bResult;
}
__inline static BOOL IsWow64System()
{
typedef VOID(__stdcall*LPFN_GETNATIVESYSTEMINFO)(LPSYSTEM_INFO lpSystemInfo);
BOOL bResult = FALSE;
SYSTEM_INFO si = { 0 };
LPFN_GETNATIVESYSTEMINFO fnGetNativeSystemInfo = NULL;
fnGetNativeSystemInfo = (LPFN_GETNATIVESYSTEMINFO)GetProcAddress(GetModuleHandle(_T("KERNEL32.DLL")), "GetNativeSystemInfo");
if (fnGetNativeSystemInfo)
{
fnGetNativeSystemInfo(&si);
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64 ||
si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
{
bResult = TRUE;
}
}
return bResult;
}
///////////////////////////////////////////////////////////////////////
//获取进程映像名称
//Windows 2000 = GetModuleFileName()
//Windows XP x32 = GetProcessImageFileName()
//Windows XP x64 = GetProcessImageFileName()
//Windows Vista = QueryFullProcessImageName()
//Windows 7 = QueryFullProcessImageName()
//Windows 8 = QueryFullProcessImageName()
//Windows 8.1 = QueryFullProcessImageName()
//Windows 10 = QueryFullProcessImageName()
///////////////////////////////////////////////////////////////////////
__inline static BOOL EnumModules_R3(std::map<DWORD, MODULEENTRY32> * pmemap, DWORD dwPID)
{
BOOL bRet = FALSE;
MODULEENTRY32 me = { 0 };
HANDLE hSnapModule = INVALID_HANDLE_VALUE;
// Take a snapshot of all modules in the specified process.
hSnapModule = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);
if (hSnapModule == INVALID_HANDLE_VALUE)
{
goto __LEAVE_CLEAN__;
}
// Set the size of the structure before using it.
me.dwSize = sizeof(MODULEENTRY32);
// Retrieve information about the first module,
// and exit if unsuccessful
if (!Module32First(hSnapModule, &me))
{
goto __LEAVE_CLEAN__;
}
// Now walk the module list of the process,
// and display information about each module
do
{
pmemap->insert(std::map<DWORD, MODULEENTRY32>::value_type(me.th32ModuleID, me));
} while (Module32Next(hSnapModule, &me));
__LEAVE_CLEAN__:
//关闭句柄
CloseHandle(hSnapModule);
hSnapModule = NULL;
return bRet;
}
__inline static BOOL EnumModules32_R3(std::map<DWORD, MODULEENTRY32> * pmemap, DWORD dwPID)
{
BOOL bRet = FALSE;
MODULEENTRY32 me = { 0 };
HANDLE hSnapModule = INVALID_HANDLE_VALUE;
// Take a snapshot of all modules in the specified process.
hSnapModule = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE32, dwPID);
if (hSnapModule == INVALID_HANDLE_VALUE)
{
goto __LEAVE_CLEAN__;
}
// Set the size of the structure before using it.
me.dwSize = sizeof(MODULEENTRY32);
// Retrieve information about the first module,
// and exit if unsuccessful
if (!Module32First(hSnapModule, &me))
{
goto __LEAVE_CLEAN__;
}
// Now walk the module list of the process,
// and display information about each module
do
{
pmemap->insert(std::map<DWORD, MODULEENTRY32>::value_type(me.th32ModuleID, me));
} while (Module32Next(hSnapModule, &me));
__LEAVE_CLEAN__:
//关闭句柄
CloseHandle(hSnapModule);
hSnapModule = NULL;
return bRet;
}
__inline static BOOL EnumProcess_R3(std::map<DWORD, PROCESSENTRY32> * ppemap)
{
BOOL bRet = FALSE;
PROCESSENTRY32 pe = { 0 };
HANDLE hSnapProcess = INVALID_HANDLE_VALUE;
//创建快照
hSnapProcess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapProcess == INVALID_HANDLE_VALUE)
{
goto __LEAVE_CLEAN__;
}
pe.dwSize = sizeof(PROCESSENTRY32);
//遍历进程
bRet = Process32First(hSnapProcess, &pe);
if (!bRet)
{
goto __LEAVE_CLEAN__;
}
do
{
ppemap->insert(std::map<DWORD, PROCESSENTRY32>::value_type(pe.th32ProcessID, pe));
} while (Process32Next(hSnapProcess, &pe));
__LEAVE_CLEAN__:
//关闭句柄
CloseHandle(hSnapProcess);
hSnapProcess = NULL;
return bRet;
}
__inline static BOOL EnumThread_R3(std::map<DWORD, THREADENTRY32> * ptemap, DWORD dwPID)
{
BOOL bRet = FALSE;
THREADENTRY32 te = { 0 };
HANDLE hSnapThread = INVALID_HANDLE_VALUE;
//创建快照
hSnapThread = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, dwPID);
if (hSnapThread == INVALID_HANDLE_VALUE)
{
goto __LEAVE_CLEAN__;
}
te.dwSize = sizeof(THREADENTRY32);
//遍历进程
bRet = Thread32First(hSnapThread, &te);
if (!bRet)
{
goto __LEAVE_CLEAN__;
}
do
{
ptemap->insert(std::map<DWORD, THREADENTRY32>::value_type(te.th32ThreadID, te));
} while (Thread32Next(hSnapThread, &te));
__LEAVE_CLEAN__:
//关闭句柄
CloseHandle(hSnapThread);
hSnapThread = NULL;
return bRet;
}
__inline static BOOL EnumHeapList_R3(std::map<ULONG_PTR, HEAPLIST32> * phlmap, DWORD dwPID)
{
BOOL bRet = FALSE;
HEAPLIST32 hl = { 0 };
HANDLE hSnapHeapList = INVALID_HANDLE_VALUE;
//创建快照
hSnapHeapList = CreateToolhelp32Snapshot(TH32CS_SNAPHEAPLIST, dwPID);
if (hSnapHeapList == INVALID_HANDLE_VALUE)
{
goto __LEAVE_CLEAN__;
}
hl.dwSize = sizeof(HEAPLIST32);
//遍历进程
bRet = Heap32ListFirst(hSnapHeapList, &hl);
if (!bRet)
{
goto __LEAVE_CLEAN__;
}
do
{
phlmap->insert(std::map<ULONG_PTR, HEAPLIST32>::value_type(hl.th32HeapID, hl));
} while (Heap32ListNext(hSnapHeapList, &hl));
__LEAVE_CLEAN__:
//关闭句柄
CloseHandle(hSnapHeapList);
hSnapHeapList = NULL;
return bRet;
}
__inline static DWORD GetProcessIdByProcessName(const _TCHAR * ptProcessName)
{
DWORD dwPID = 0;
_TCHAR tzProcessName[MAX_PATH] = { 0 };
std::map<DWORD, PROCESSENTRY32> pemap;
std::map<DWORD, PROCESSENTRY32>::iterator itEnd;
std::map<DWORD, PROCESSENTRY32>::iterator itIdx;
lstrcpy(tzProcessName, ptProcessName);
EnumProcess_R3(&pemap);
itEnd = pemap.end();
itIdx = pemap.begin();
for (; itIdx != itEnd; itIdx++)
{
if (!_tcsicmp(itIdx->second.szExeFile, tzProcessName))
{
dwPID = itIdx->second.th32ProcessID;
break;
}
}
return dwPID;
}
__inline static BOOL GetProcessFileNameByProcessId(const DWORD dwProcessId, TSTRING & cstrPath)
{
HANDLE hProcess = NULL;
BOOL bSuccess = FALSE;
// 由于进程权限问题,有些进程是无法被OpenProcess的,如果将调用进程的权限
// 提到“调试”权限,则可能可以打开更多的进程
hProcess = OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, dwProcessId);
if (hProcess)
{
std::map<DWORD, MODULEENTRY32> memap;
EnumModules_R3(&memap, dwProcessId);
}
// 释放句柄
if (NULL != hProcess)
{
CloseHandle(hProcess);
hProcess = NULL;
}
return bSuccess;
}
__inline static HANDLE InitProcessHandle(DWORD dwPID)
{
// Open process
return ::OpenProcess(PROCESS_ALL_ACCESS | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, dwPID);
}
__inline static HANDLE InitProcessHandle(const _TCHAR * ptProcessName)
{
DWORD dwPID = 0;
dwPID = GetProcessIdByProcessName(ptProcessName);
// Open process
return ::OpenProcess(PROCESS_ALL_ACCESS | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, FALSE, dwPID);
}
__inline static void ExitProcessHandle(HANDLE * pHandle)
{
if (pHandle && (*pHandle))
{
CloseHandle((*pHandle));
(*pHandle) = NULL;
}
}
//根据进程ID终止进程
__inline static void TerminateProcessByProcessId(DWORD dwProcessId)
{
DWORD dwExitCode = 0;
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, dwProcessId);
if (hProcess)
{
GetExitCodeProcess(hProcess, &dwExitCode);
TerminateProcess(hProcess, dwExitCode);
CloseHandle(hProcess);
hProcess = 0;
}
}
//传入应用程序文件名称、参数、启动类型及等待时间启动程序
__inline BOOL StartupProgram(tstring tsAppProgName, tstring tsArguments = _T(""), STARTUPINFO * pStartupInfo = NULL, PROCESS_INFORMATION * pProcessInformation = NULL, DWORD dwFlags = CREATE_NEW_CONSOLE, LPVOID lpEnvironment = NULL, LPCTSTR lpCurrentDirectory = NULL, LAUNCHTYPE type = LTYPE_0, DWORD dwWaitTime = WAIT_TIMEOUT)
{
BOOL bRet = FALSE;
STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };
DWORD dwCreateFlags = dwFlags;
LPTSTR lpArguments = NULL;
STARTUPINFO * pSI = &si;
PROCESS_INFORMATION * pPI = π
if (pStartupInfo)
{
pSI = pStartupInfo;
}
if (pProcessInformation)
{
pPI = pProcessInformation;
}
if (tsArguments.length())
{
lpArguments = (LPTSTR)tsArguments.c_str();
}
pSI->cb = sizeof(STARTUPINFO);
// Start the child process.
bRet = CreateProcess(tsAppProgName.c_str(), // No module name (use command line)
lpArguments, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
dwCreateFlags, // No creation flags
lpEnvironment, // Use parent's environment block
lpCurrentDirectory, // Use parent's starting directory
pSI, // Pointer to STARTUPINFO structure
pPI); // Pointer to PROCESS_INFORMATION structure
if (bRet)
{
switch (type)
{
case LTYPE_0:
{
// No wait until child process exits.
}
break;
case LTYPE_1:
{
// Wait until child process exits.
WaitForSingleObject(pPI->hProcess, INFINITE);
}
break;
case LTYPE_2:
{
// Wait until child process exits.
WaitForSingleObject(pPI->hProcess, dwWaitTime);
}
break;
default:
break;
}
// Close process and thread handles.
//CloseHandle(pPI->hProcess);
//CloseHandle(pPI->hThread);
// Exit process.
//TerminateProcessByProcessId(pPI->dwProcessId);
}
else
{
//DEBUG_TRACE(_T("CreateProcess failed (%d).\n"), GetLastError());
}
return bRet;
}
//传入应用程序文件名称、参数、启动类型及等待时间启动程序
__inline static BOOL LaunchAppProg(tstring tsAppProgName, tstring tsArguments = _T(""), LPCTSTR lpWorkPath = NULL, bool bNoUI = true, LAUNCHTYPE type = LTYPE_0, DWORD dwWaitTime = WAIT_TIMEOUT)
{
BOOL bRet = FALSE;
STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };
DWORD dwCreateFlags = CREATE_NO_WINDOW;
LPTSTR lpArguments = NULL;
if (tsArguments.length())
{
lpArguments = (LPTSTR)tsArguments.c_str();
}
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (!bNoUI)
{
dwCreateFlags = 0;
}
// Start the child process.
bRet = CreateProcess(tsAppProgName.c_str(), // No module name (use command line)
lpArguments, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
dwCreateFlags, // No creation flags
NULL, // Use parent's environment block
lpWorkPath, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi); // Pointer to PROCESS_INFORMATION structure
if (bRet)
{
switch (type)
{
case LTYPE_0:
{
// No wait until child process exits.
}
break;
case LTYPE_1:
{
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
}
break;
case LTYPE_2:
{
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, dwWaitTime);
}
break;
default:
break;
}
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
// Exit process.
TerminateProcessByProcessId(pi.dwProcessId);
}
else
{
//DEBUG_TRACE(_T("CreateProcess failed (%d).\n"), GetLastError());
}
return bRet;
}
//传入应用程序文件名称、参数、启动类型及等待时间启动程序
__inline static BOOL StartupProgram(LPCTSTR lpAppProgName = NULL, LPTSTR lpArguments = NULL, STARTUPINFO * pStartupInfo = NULL, PROCESS_INFORMATION * pProcessInformation = NULL, DWORD dwFlags = CREATE_NEW_CONSOLE, LPVOID lpEnvironment = NULL, LPCTSTR lpCurrentDirectory = NULL, LAUNCHTYPE type = LTYPE_0, DWORD dwWaitTime = WAIT_TIMEOUT)
{
BOOL bRet = FALSE;
STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };
DWORD dwCreateFlags = dwFlags;
STARTUPINFO * pSI = &si;
PROCESS_INFORMATION * pPI = π
if (pStartupInfo)
{
pSI = pStartupInfo;
}
if (pProcessInformation)
{
pPI = pProcessInformation;
}
pSI->cb = sizeof(STARTUPINFO);
// Start the child process.
bRet = CreateProcess(lpAppProgName, // No module name (use command line)
lpArguments, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
dwCreateFlags, // No creation flags
lpEnvironment, // Use parent's environment block
lpCurrentDirectory, // Use parent's starting directory
pSI, // Pointer to STARTUPINFO structure
pPI); // Pointer to PROCESS_INFORMATION structure
if (bRet)
{
switch (type)
{
case LTYPE_0:
{
// No wait until child process exits.
}
break;
case LTYPE_1:
{
// Wait until child process exits.
WaitForSingleObject(pPI->hProcess, INFINITE);
}
break;
case LTYPE_2:
{
// Wait until child process exits.
WaitForSingleObject(pPI->hProcess, dwWaitTime);
}
break;
default:
break;
}
// Close process and thread handles.
//CloseHandle(pPI->hProcess);
//CloseHandle(pPI->hThread);
// Exit process.
//TerminateProcessByProcessId(pPI->dwProcessId);
}
else
{
//DEBUG_TRACE(_T("CreateProcess failed (%d).\n"), GetLastError());
}
return bRet;
}
__inline static BOOL StartAppProg(LPCTSTR lpFilename = NULL, LPTSTR lpArgument = NULL, BOOL bSynchronous = TRUE, LPCTSTR lpStartingDirectory = NULL, LPVOID lpEnvironmentBlock = NULL)
{
BOOL bResult = FALSE;
PROCESS_INFORMATION pi = { 0 };
STARTUPINFO si = { 0 };
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
bResult = CreateProcess(lpFilename, // No module name (use command line)
lpArgument, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
CREATE_NO_WINDOW | NORMAL_PRIORITY_CLASS, // No creation flags
lpEnvironmentBlock, // Use parent's environment block
lpStartingDirectory, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi); // Pointer to PROCESS_INFORMATION structure
//异步执行时,执行后不删除分解后的文件;同步执行时,执行后删除分解后的文件
if (bSynchronous) //同步执行
{
WaitForSingleObject(pi.hProcess, INFINITE);
}
//_tunlink(pFilename);
return bResult;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:阻塞式启动程序或脚本
// 参 数:文件名、参数、运行目录
// 返 回 值:成功返回true,否则返回false
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static bool RunAppUnBlock(LPCTSTR lpFileName,
LPCTSTR lpParameters = NULL,
int nShowCmd = SW_HIDE,
LPCTSTR lpDirectory = NULL)
{
bool bResult = false;
SHELLEXECUTEINFO sei = { 0 };
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_ASYNCOK;
sei.hwnd = NULL;
sei.lpVerb = TEXT("OPEN");
sei.lpFile = lpFileName;
sei.lpParameters = lpParameters;
sei.lpDirectory = lpDirectory;
sei.nShow = nShowCmd;
sei.hInstApp = NULL;
if (ShellExecuteEx(&sei))
{
// 等待脚本返回
WaitForSingleObject(sei.hProcess, INFINITE);
bResult = true;
}
return bResult;
}
//系统提权函数
__inline static BOOL ElevatePrivileges(BOOL bEnable = TRUE)
{
BOOL bRet = FALSE;
HANDLE hToken = NULL;
TOKEN_PRIVILEGES tkp = { 0x1, { 0 } };
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid))
{
tkp.Privileges[0].Attributes = (bEnable) ? SE_PRIVILEGE_ENABLED : 0;
if (AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
{
bRet = TRUE;
}
}
}
return bRet;
}
//系统提权函数
__inline static BOOL PromotingPrivilege(LPCTSTR lpszPrivilegeName, BOOL bEnable)
{
BOOL bRet = FALSE;
LUID luid = { 0 };
HANDLE hToken = NULL;
TOKEN_PRIVILEGES tp = { 0x01L, { 0 } };
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_READ, &hToken) &&
LookupPrivilegeValue(NULL, lpszPrivilegeName, &luid))
{
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = (bEnable) ? SE_PRIVILEGE_ENABLED : 0;
bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, NULL, NULL, NULL);
CloseHandle(hToken);
hToken = NULL;
}
return bRet;
}
//检查系统版本是否是Vista或更高的版本
__inline static bool IsOsVersionVistaOrGreater()
{
OSVERSIONINFOEX ovex = { 0 };
_TCHAR tzVersionInfo[MAX_PATH] = { 0 };
//设置参数的大小,调用并判断是否成功
ovex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (!GetVersionEx((OSVERSIONINFO *)(&ovex)))
{
return false;
}
//通过版本号,判断是否是vista及之后版本
if (ovex.dwMajorVersion > 5)
{
return true;
}
else
{
return false;
}
}
//检查并根据系统版本选择打开程序方式
__inline static void ShellExecuteExOpen(tstring tsAppName, tstring tsArguments, tstring tsWorkPath)
{
if (IsOsVersionVistaOrGreater())
{
SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpVerb = _T("runas");
sei.lpFile = tsAppName.c_str();
sei.lpParameters = tsArguments.c_str();
sei.lpDirectory = tsWorkPath.c_str();
sei.nShow = SW_SHOWNORMAL;
if (!ShellExecuteEx(&sei))
{
DWORD dwStatus = GetLastError();
if (dwStatus == ERROR_CANCELLED)
{
//DEBUG_TRACE(_T("提升权限被用户拒绝\n"));
}
else if (dwStatus == ERROR_FILE_NOT_FOUND)
{
//DEBUG_TRACE(_T("所要执行的文件没有找到\n"));
}
else
{
//DEBUG_TRACE(_T("失败原因未找到\n"));
}
}
}
else
{
::ShellExecute(NULL, _T("OPEN"), tsAppName.c_str(), NULL, tsWorkPath.c_str(), SW_SHOWNORMAL);
}
}
__inline static void LaunchAppProgByAdmin(tstring tsAppProgName, tstring tsArguments, bool bNoUI/* = true*/)
{
ShellExecuteExOpen(tsAppProgName, tsArguments, _T(""));
/*const HWND hWnd = 0;
const _TCHAR * pCmd = _T("runas");
const _TCHAR * pWorkPath = _T("");
int nShowType = bNoUI ? SW_HIDE : SW_SHOW;
::ShellExecute(hWnd, pCmd, tsAppProgName.c_str(), tsArguments.c_str(), pWorkPath, nShowType);*/
}
__inline static DWORD LaunchThread(
LPTHREAD_START_ROUTINE lpThreadStartRoutine,
LPVOID lpParameter = NULL, LPHANDLE lppThreadHandle = NULL,
LPDWORD lpThreadId = NULL, DWORD dwCreationFlags = (0L),
SIZE_T dwStackSize = (0L), LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL)
{
DWORD dwThreadId = (0L);
HANDLE hThreadHandle = NULL;
LPDWORD lpThreadID = (lpThreadId ? lpThreadId : &dwThreadId);
LPHANDLE ppTheadHandle = (lppThreadHandle ? lppThreadHandle : &hThreadHandle);
*ppTheadHandle = CreateThread(NULL, NULL, lpThreadStartRoutine, lpParameter, dwCreationFlags, lpThreadID);
return (*lpThreadID);
}
typedef struct tagFileUsedTimeInfoA{
CHAR szFileName[MAX_PATH];//要删除文件名称
time_t tsStartTime;//起始时间(秒数)除去首两位
time_t tuUsedDays;//天数
tagFileUsedTimeInfoA(
LPCSTR _szFileName = (""),
time_t _tsStartTime = (0L),//default now
time_t _tuUsedDays = 86400 * 30)
{
lstrcpyA(this->szFileName, _szFileName);
this->tsStartTime = _tsStartTime;
this->tuUsedDays = _tuUsedDays;
}
tagFileUsedTimeInfoA * ptr()
{
return this;
}
}FileUsedTimeInfoA, *PFileUsedTimeInfoA;
typedef struct tagFileUsedTimeInfoW{
WCHAR szFileName[MAX_PATH];//要删除文件名称
time_t tsStartTime;//起始时间(秒数)除去首两位
time_t tuUsedDays;//天数
tagFileUsedTimeInfoW(
LPCWSTR _szFileName = (L""),
time_t _tsStartTime = 22321946,//default now
time_t _tuUsedDays = 86400 * 30)
{
lstrcpyW(this->szFileName, _szFileName);
this->tsStartTime = _tsStartTime;
this->tuUsedDays = _tuUsedDays;
}
tagFileUsedTimeInfoW * ptr()
{
return this;
}
}FileUsedTimeInfoW, *PFileUsedTimeInfoW;
class CFileUsedTimeInfoA{
public:
CFileUsedTimeInfoA(LPCSTR _szFileName = (""),
time_t _tsStartTime = (0L),//default now
time_t _tuUsedDays = 86400 * 30)
{
lstrcpyA(this->szFileName, _szFileName);
this->tsStartTime = _tsStartTime;
this->tuUsedDays = _tuUsedDays;
}
CFileUsedTimeInfoA * ptr()
{
return this;
}
public:
CHAR szFileName[MAX_PATH];//要删除文件名称
time_t tsStartTime;//default now起始时间(秒数)除去首两位
time_t tuUsedDays;//天数
};
class CFileUsedTimeInfoW{
public:
CFileUsedTimeInfoW(
LPCWSTR _szFileName = (L""),
time_t _tsStartTime = (0L),//default now
time_t _tuUsedDays = 86400 * 30)
{
lstrcpyW(this->szFileName, _szFileName);
this->tsStartTime = _tsStartTime;
this->tuUsedDays = _tuUsedDays;
}
CFileUsedTimeInfoW * ptr()
{
return this;
}
public:
WCHAR szFileName[MAX_PATH];//要删除文件名称
time_t tsStartTime;//起始时间(秒数)除去首两位
time_t tuUsedDays;//天数
};
#if !defined(_UNICODE) && !defined(UNICODE)
#define FileUsedTimeInfo FileUsedTimeInfoA
#define PFileUsedTimeInfo PFileUsedTimeInfoA
#define CFileUsedTimeInfo CFileUsedTimeInfoA
#else
#define FileUsedTimeInfo FileUsedTimeInfoW
#define PFileUsedTimeInfo PFileUsedTimeInfoW
#define CFileUsedTimeInfo CFileUsedTimeInfoW
#endif
__inline static int ClonesMyself(LPCTSTR lpDestFileName = NULL, LPCTSTR lpFileName = _T("TMP.TMP"))
{
_TCHAR tzFileName[MAX_PATH] = { 0 };
_TCHAR tzTempFileName[MAX_PATH] = { 0 };
LPCTSTR lpDestFileNamePtr = tzTempFileName;
::GetModuleFileName(NULL, tzFileName, MAX_PATH);
if (!lpDestFileName)
{
wsprintf(tzTempFileName, _T("%s%s"), PPSHUAI::FilePath::GetTempPath().c_str(), lpFileName);
}
else
{
lpDestFileNamePtr = lpDestFileName;
}
::CopyFile(tzFileName, lpDestFileNamePtr, FALSE);
::CopyFileEx(tzFileName, lpDestFileNamePtr, NULL, NULL, NULL, NULL);
::CopyFile(tzFileName, lpDestFileNamePtr, FALSE);
return (0L);
}
__inline static void MyselfDelete(LPCTSTR lpFileName = NULL, HMODULE hModule = NULL)
{
HANDLE hFile = NULL;
CHAR *ptPointer = NULL;
CHAR szTempFormat[] = \
":REPEAT\r\n" \
"DEL /F /S /Q \"%s\"\r\n" \
"IF EXIST \"%s\" GOTO REPEAT\r\n" \
"RMDIR /Q \"%s\" \r\n" \
"DEL /F /S /Q \"%s\" \r\n";//当前目录下内容全部清除可用:"RMDIR /S /Q \"%s\" \r\n"
DWORD dwNumberOfBytesWritten = 0;
CHAR szCodeData[MAX_PATH * 8] = { 0 };
CHAR szTempFileName[MAX_PATH] = { 0 };
CHAR szDestinationFolder[MAX_PATH] = { 0 };
CHAR szFileName[MAX_PATH] = { 0 };
LPSTR lpFileNamePtr = szFileName;
if (!lpFileName)
{
::GetModuleFileNameA(hModule, szFileName, sizeof(szFileName) / sizeof(*szFileName));
}
else
{
lstrcpyA(szFileName, (LPSTR)PPSHUAI::Convert::TToA(lpFileName).c_str());
}
wsprintfA(szTempFileName, ("%sTMP.BAT"), PPSHUAI::Convert::TToA(PPSHUAI::FilePath::GetTempPath()).c_str());
lstrcpyA(szDestinationFolder, lpFileNamePtr);
ptPointer = strrchr(szDestinationFolder, ('\\'));
if (ptPointer != NULL)
{
*ptPointer = ('\0');
}
wsprintfA(szCodeData, szTempFormat, lpFileNamePtr, lpFileNamePtr, szDestinationFolder, szTempFileName);
hFile = ::CreateFileA(szTempFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
::WriteFile(hFile, szCodeData, lstrlenA(szCodeData), &dwNumberOfBytesWritten, NULL);
::CloseHandle(hFile);
hFile = NULL;
}
::ShellExecuteA(NULL, ("OPEN"), szTempFileName, NULL, NULL, SW_HIDE);
}
__inline static int DeleteMyself(CFileUsedTimeInfo * pFUTI)
{
if (((time(NULL) - (time(NULL) / 100000000) * 100000000) - pFUTI->tsStartTime) > pFUTI->tuUsedDays)
{
MyselfDelete(pFUTI->szFileName);
//::MoveFileEx(pFUTI->szFileName, _T(""), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
//::MoveFileEx(pFUTI->szFileName, _T(""), MOVEFILE_REPLACE_EXISTING | MOVEFILE_DELAY_UNTIL_REBOOT);
::DeleteFile(pFUTI->szFileName);
_tunlink(pFUTI->szFileName);
ExitProcess((0L));
}
return 0;
}
DWORD WINAPI DeleteMyselfThread(LPVOID lpParams)
{
CFileUsedTimeInfo * pFUTI = (CFileUsedTimeInfo *)lpParams;
if (pFUTI)
{
if (((time(NULL) - (time(NULL) / 100000000) * 100000000) - pFUTI->tsStartTime) > pFUTI->tuUsedDays)
{
MyselfDelete(pFUTI->szFileName);
//::MoveFileEx(pFUTI->szFileName, _T(""), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);
//::MoveFileEx(pFUTI->szFileName, _T(""), MOVEFILE_REPLACE_EXISTING | MOVEFILE_DELAY_UNTIL_REBOOT);
::DeleteFile(pFUTI->szFileName);
_tunlink(pFUTI->szFileName);
ExitProcess((0L));
}
}
return (0L);
}
__inline static DWORD StartDeleteMyself(LPVOID lpParam)
{
DWORD dwThreadId = (0L);
HANDLE hThreadHandle = NULL;
dwThreadId = LaunchThread((LPTHREAD_START_ROUTINE)DeleteMyselfThread, lpParam, &hThreadHandle);
if (dwThreadId != (0L))
{
WaitForSingleObject(hThreadHandle, INFINITE);
CloseHandle(hThreadHandle);
hThreadHandle = NULL;
}
return dwThreadId;
}
//检查并根据系统版本选择打开程序方式
__inline static DWORD AdvanceShellExecuteEx(LPCTSTR lpFileName, LPCTSTR lpParameters, LPCTSTR lpDirectory = NULL, ULONG fMask = SEE_MASK_NOCLOSEPROCESS, INT nShowFlag = SW_SHOWNORMAL, LPCTSTR lpVerb = _T("OPEN"), HWND hWnd = NULL)
{
SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
sei.fMask = fMask;
sei.hwnd = hWnd;
sei.lpVerb = lpVerb;//Can be _T("RUNAS")
sei.lpFile = lpFileName;
sei.lpParameters = lpParameters;
sei.lpDirectory = lpDirectory;
sei.nShow = nShowFlag;
::ShellExecuteEx(&sei);
return GetLastError();
}
//检查并根据系统版本选择打开程序方式
__inline static DWORD AdvanceShellExecute(LPCTSTR lpFileName, LPCTSTR lpParameters, LPCTSTR lpDirectory,
INT nShowFlag = SW_SHOWNORMAL, HWND hWnd = NULL, LPCTSTR lpOperation = _T("OPEN"))
{
if (IsOsVersionVistaOrGreater())
{
SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.hwnd = hWnd;
sei.lpVerb = lpOperation;
sei.lpFile = lpFileName;
sei.lpParameters = lpParameters;
sei.lpDirectory = lpDirectory;
sei.nShow = nShowFlag;
::ShellExecuteEx(&sei);
}
else
{
::ShellExecute(hWnd, lpOperation, lpFileName, lpParameters, lpDirectory, nShowFlag);
}
return ::GetLastError();
}
__inline static DWORD LaunchProgram(LPCTSTR lpFileName, LPCTSTR lpParameters, LPCTSTR lpDirectory = NULL)
{
return AdvanceShellExecuteEx(lpFileName, lpParameters, lpDirectory);
}
//程序实例只允许一个
__inline static BOOL RunAppOne(LPCTSTR ptName, BOOL bAutoExit = FALSE)
{
BOOL bResult = FALSE;
HANDLE hMutexInstance = ::CreateMutex(NULL, FALSE, ptName); //创建互斥
if (hMutexInstance)
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
//OutputDebugString(_T("互斥检测返回!"));
if (!bAutoExit)
{
CloseHandle(hMutexInstance);
}
else
{
::ExitProcess((0L));
}
bResult = TRUE;
}
}
return bResult;
}
//枚举并显示窗口
__inline static BOOL EnumShowWindow(LPCTSTR ptPropName, BOOL bAutoExit = FALSE)
{
BOOL bResult = FALSE;
HWND hWndPrevious = ::GetWindow(::GetDesktopWindow(), GW_CHILD);
while (::IsWindow(hWndPrevious))
{
if (::GetProp(hWndPrevious, ptPropName))
{
if (::IsIconic(hWndPrevious))
{
::ShowWindow(hWndPrevious, SW_RESTORE);
::SetForegroundWindow(hWndPrevious);
}
else
{
::SetForegroundWindow(::GetLastActivePopup(hWndPrevious));
}
if (bAutoExit)
{
::ExitProcess(0L);
}
bResult = TRUE;
break;
}
hWndPrevious = ::GetWindow(hWndPrevious, GW_HWNDNEXT);
}
return bResult;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:注册DLL库到Windows系统
// 参 数:新文件名(可选)、资源ID、资源类型
// 返 回 值:成功返回TRUE,否则返回FALSE
// 编 写 者: ppshuai 20141112
//////////////////////////////////////////////////////////////////////////
__inline static void RegisterDynamicLibrary(LPCTSTR lpDllName, BOOL bEnable = FALSE)
{
#define REG_TOOL_NAME TEXT("REGSVR32.EXE")
TCHAR l_tSystemPath[MAX_PATH + 1] = { 0 };//系统路径定义
TCHAR l_tToolCommand[MAX_PATH * 2 + 1] = { 0 };///工具命令路径定义
if (GetSystemDirectory(l_tSystemPath, MAX_PATH) > 0)
{
if (bEnable)
{
wsprintf(l_tToolCommand, TEXT("%s\\%s /s /i \"%s\""),
l_tSystemPath, REG_TOOL_NAME, lpDllName);
}
else
{
wsprintf(l_tToolCommand, TEXT("%s\\%s /s /u \"%s\""),
l_tSystemPath, REG_TOOL_NAME, lpDllName);
}
RunAppUnBlock(l_tToolCommand);
}
}
}
class CUsuallyUtility
{
public:
CUsuallyUtility()
{
}
~CUsuallyUtility()
{
}
public:
// ANSI to WIDE
static LONG AToW(WCHAR ** pW, const CHAR * pA, UINT uCodePage)
{
LONG nWSize = 0;
LONG nASize = lstrlenA(pA);
if (nASize > 0)
{
nWSize = ::MultiByteToWideChar(uCodePage, 0, pA, -1, NULL, 0);
(*pW) = (WCHAR *)malloc((nWSize + 1) * sizeof(WCHAR));
::MultiByteToWideChar(uCodePage, 0, pA, -1, (*pW), nWSize);
}
return nWSize;
}
// WIDE to ANSI
static LONG WToA(CHAR ** pA, const WCHAR * pW, UINT uCodePage)
{
LONG nASize = 0;
LONG nWSize = lstrlenW(pW);
if (nWSize > 0)
{
nASize = ::WideCharToMultiByte(uCodePage, 0, pW, -1, NULL, 0, 0, 0);
(*pA) = (CHAR *)malloc((nASize + 1) * sizeof(CHAR));
::WideCharToMultiByte(uCodePage, 0, pW, -1, (*pA), nASize, 0, 0);
}
return nASize;
}
// ANSI to WIDE
static LONG AToW(WCHAR ** pW, const CHAR * pA)
{
return AToW(pW, pA, CP_ACP);
}
// WIDE to ANSI
static LONG WToA(CHAR ** pA, const WCHAR * pW)
{
return WToA(pA, pW, CP_ACP);
}
// ANSI to TCHAR
static LONG AToT(_TCHAR ** pT, const CHAR * pA)
{
LONG nTSize = 0;
#if !defined(_UNICODE) && !defined(UNICODE)
nTSize = lstrlenA(pA);
(*pT) = (_TCHAR *)malloc((nTSize + 1) * sizeof(_TCHAR));
lstrcpynA((*pT), pA, nTSize);
#else
nTSize = AToW(pT, pA);
#endif
return nTSize;
}
// TCHAR to ANSI
static LONG WToT(_TCHAR ** pT, const WCHAR * pW)
{
LONG nTSize = 0;
#if !defined(_UNICODE) && !defined(UNICODE)
nTSize = WToA(pT, pW);
#else
nTSize = lstrlenW(pW);
(*pT) = (_TCHAR *)malloc((nTSize + 1) * sizeof(_TCHAR));
lstrcpynW((*pT), pW, nTSize);
#endif
return nTSize;
}
// TCHAR to ANSI
static LONG TToA(CHAR ** pA, const _TCHAR * pT)
{
LONG nTSize = 0;
#if !defined(_UNICODE) && !defined(UNICODE)
nTSize = lstrlenA(pT);
(*pA) = (CHAR *)malloc((nTSize + 1) * sizeof(CHAR));
lstrcpynA((*pA), pT, nTSize);
#else
nTSize = WToA(pA, pT);
#endif
return nTSize;
}
// TCHAR to WIDE
static LONG TToW(WCHAR ** pW, const _TCHAR * pT)
{
LONG nTSize = 0;
#if !defined(_UNICODE) && !defined(UNICODE)
nTSize = AToW(pW, pT);
#else
nTSize = lstrlenW(pT);
(*pW) = (WCHAR *)malloc((nTSize + 1) * sizeof(WCHAR));
lstrcpynW((*pW), pT, nTSize);
#endif
return nTSize;
}
static void FreeA(CHAR ** pA)
{
if (pA && (*pA))
{
free((*pA));
(*pA) = 0;
}
}
static void FreeW(WCHAR ** pW)
{
if (pW && (*pW))
{
free((*pW));
(*pW) = 0;
}
}
static void FreeT(_TCHAR ** pT)
{
if (pT && (*pT))
{
free((*pT));
(*pT) = 0;
}
}
};
}
#include "Network.h"
#include "PEFileInfo.h"
#include "ThreadHelper.h"
#include "WindowHeader.h"
#include "MemoryHeader.h"
#include "ListCtrlData.h"
#include "SystemDataInfo.h"
#include "CryptyHeader.h"
#endif //__COMMONHELPER_H_
|
/*
* op_subtract.cpp
*
* Created on: 2 mars 2014
* Author: droper
*/
#include <iostream>
#include "op_subtract.h"
op_subtract::op_subtract() {
}
op_subtract::~op_subtract() {
}
void op_subtract::display(std::ostream &out, int mode) {
if (mode == DISPLAY_F) {
out << getValue();
return;
}
if (child1 != NULL)
child1->display(out, mode);
out << "-";
if (child2 != NULL)
child2->display(out, mode);
}
double op_subtract::getValue() {
if (child1 != NULL && child2 != NULL) {
return child1->getValue() - child2->getValue();
}
return 0;
}
int op_subtract::whoiam() {
return WHOIAM_S;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Spdr3dModel.hpp"
#define SPDRMV_MAX_TAG_NAME 40
#define SPDRMV_MAX_POINT_BUFFER 80
#define SPDRMV_READ_BUFFER 512
static char *readLineFromFile( FILE *fp );
static int parseFile( Spdr3dModel& model, const char *cpFile );
static int parseFileHeader( FILE *fp );
static int parseFileLine( Spdr3dModel& model, FILE *fp, int iOperationPosition );
static int parseOperation( Spdr3dOperation& operation, char *cpText );
static int findTagContent( char *cpText, const char *cpTagName, int iStartAt, int *ipStart, int *ipEnd );
static int findSubstring( char *cpText, const char *cpSubstring, int iStartAt, int *ipStart, int *ipEnd );
static char *readLineFromFile( FILE *fp ) {
int nAllocated, iAllocatedPtr;
char cRead;
char *cpAllocated;
cpAllocated = (char*)malloc( SPDRMV_READ_BUFFER );
if( cpAllocated == NULL ) {
return NULL;
}
nAllocated = SPDRMV_READ_BUFFER;
iAllocatedPtr = 0;
for( ; ; ) {
cRead = fgetc( fp );
if( feof(fp) ) {
break;
}
if( iAllocatedPtr >= nAllocated-1 ) {
if( nAllocated == 0 ) {
cpAllocated = (char*)malloc( SPDRMV_READ_BUFFER );
} else {
cpAllocated = (char*)realloc( cpAllocated, nAllocated + SPDRMV_READ_BUFFER );
}
if( cpAllocated == NULL ) {
return NULL;
}
nAllocated += SPDRMV_READ_BUFFER;
}
cpAllocated[iAllocatedPtr] = cRead;
iAllocatedPtr++;
if( cRead == '\n' ) {
break;
}
}
cpAllocated[iAllocatedPtr] = '\x0';
return cpAllocated;
}
static int findTagContent( char *cpText, const char *cpTagName, int iStartAt, int *ipStart, int *ipEnd ) {
char caOpenTag[SPDRMV_MAX_TAG_NAME+3];
char caCloseTag[SPDRMV_MAX_TAG_NAME+4];
int iFound, iOpenTagStart, iOpenTagEnd, iCloseTagStart, iCloseTagEnd;
if( strlen(cpTagName) > SPDRMV_MAX_TAG_NAME ) {
return 0;
}
sprintf( caOpenTag, "<%s>", cpTagName );
sprintf( caCloseTag, "</%s>", cpTagName );
iFound = findSubstring( cpText, caOpenTag, iStartAt, &iOpenTagStart, &iOpenTagEnd );
if( iFound == 0 ) {
return 0;
}
iFound = findSubstring( cpText, caCloseTag, iOpenTagEnd, &iCloseTagStart, &iCloseTagEnd );
if( iFound == 0 ) {
return 0;
}
if( ipStart != NULL ) {
*ipStart = iOpenTagEnd+1;
}
if( ipEnd != NULL ) {
*ipEnd = iCloseTagStart-1;
}
return 1;
}
static int findSubstring( char *cpText, const char *cpSubstring, int iStartAt, int *ipStart, int *ipEnd ) {
int iFound = 0;
int i, iTextLen, iSubstringLen, iSubstringIndex;
iTextLen = strlen( cpText );
iSubstringLen = strlen( cpSubstring );
iSubstringIndex = 0;
for( i = iStartAt ; i < iTextLen ; i++ ) {
if( tolower(cpSubstring[iSubstringIndex]) == tolower(cpText[i]) ) {
iSubstringIndex++;
if( iSubstringIndex == iSubstringLen ) {
if( ipStart != NULL ) {
*ipStart = i-iSubstringLen+1;
}
if( ipEnd != NULL ) {
*ipEnd = i;
}
iFound = 1;
break;
}
} else {
if( iSubstringIndex > 0 ) {
iSubstringIndex = 0;
}
}
}
return iFound;
}
static int parseFileHeader( FILE *fp ) {
int i, iStatus, iStart, iOperationPosition=-1;
char *cpHeader;
cpHeader = readLineFromFile(fp);
if( cpHeader == NULL ) {
return -1;
}
iStatus = findSubstring( cpHeader, "model", 0, &iStart, NULL );
if( iStatus == 1 ) {
iOperationPosition = 0;
for( i = 0 ; i < iStart ; i++ ) {
if( cpHeader[i] == ';' ) {
iOperationPosition++;
}
}
}
free(cpHeader);
return iOperationPosition;
}
static int parseFileLine( Spdr3dModel& model, FILE *fp, int iOperationModelPosition ) {
int i, iLineLen, iPosition, iOperationModelStart;
char *cpLine;
cpLine = readLineFromFile(fp);
if( cpLine == NULL ) {
return -1;
}
iLineLen = strlen( cpLine );
iPosition = 0;
for( i = 0 ; i < iLineLen ; i++ ) {
if( iPosition == iOperationModelPosition ) {
break;
}
if( cpLine[i] == ';' ) {
iPosition++;
}
}
if( i == iLineLen ) {
return -1;
}
iOperationModelStart = i;
for( ; i < iLineLen ; i++ ) {
if( cpLine[i] == ';' ) {
cpLine[i] = '\x0';
break;
}
}
printf( "Operation model found: %s", &cpLine[iOperationModelStart] );
Spdr3dOperation operation;
parseOperation( operation, &cpLine[iOperationModelStart] );
model.add( operation );
free(cpLine);
return 0;
}
static int parseFile( Spdr3dModel& model, const char *cpFile ) {
//char caText[] = "<object><facet><point> 1, 2, 3</point><point> 4, 5, 6</point><point>7, 8, 9</point><point>10, 11.234234, 12 </point></facet></object>";
FILE *fp;
int iStatus, iOperationModelPosition;
fp = fopen( cpFile, "rb" );
if( fp != NULL ) {
iOperationModelPosition = parseFileHeader( fp );
if( iOperationModelPosition >= 0 ) {
while(1) {
iStatus = parseFileLine( model, fp, iOperationModelPosition );
if( iStatus == -1 ) {
break;
}
}
}
fclose(fp);
}
return 0;
}
static int parseOperation( Spdr3dOperation& operation, char *cpText ) {
int iStatus, iObjectStart, iObjectEnd, iFacetStart, iFacetEnd, iPointStart, iPointEnd;
int iPointIndex, nPointsBuffered;
char caPointBuffer[SPDRMV_MAX_POINT_BUFFER];
float fX, fY, fZ;
iObjectEnd = 0;
while(1) {
iStatus = findTagContent( cpText, "object", iObjectEnd, &iObjectStart, &iObjectEnd );
if( iStatus == 0 ) {
break;
}
puts("OBJECT FOUND!");
Spdr3dObject object;
iFacetEnd = iObjectStart;
while(1) {
iStatus = findTagContent( cpText, "facet", iFacetEnd, &iFacetStart, &iFacetEnd );
if( iStatus == 0 ) {
break;
}
puts("FACET FOUND!");
Spdr3dFacet facet;
iPointEnd = iFacetStart;
while(1) {
iStatus = findTagContent( cpText, "point", iPointEnd, &iPointStart, &iPointEnd );
if( iStatus == 0 ) {
break;
}
for( iPointIndex = iPointStart, nPointsBuffered = 0 ; iPointIndex <= iPointEnd && nPointsBuffered < SPDRMV_MAX_POINT_BUFFER ; ) {
if( cpText[iPointIndex] == ',' ) {
caPointBuffer[ nPointsBuffered ] = ' ';
} else {
caPointBuffer[ nPointsBuffered ] = cpText[iPointIndex];
}
iPointIndex++;
nPointsBuffered++;
}
caPointBuffer[ nPointsBuffered ] = '\x0';
iStatus = sscanf( caPointBuffer, " %f %f %f", &fX, &fY, &fZ );
if( iStatus == 3 ) {
Spdr3dVertex vertex( fX, fY, fZ );
facet.add(vertex);
printf("Added vertex: %f, %f, %f\n", fX, fY, fZ );
}
}
object.add(facet);
}
operation.add(object);
}
return 0;
}
int main( int argc, char* argv[] ) {
if( argc < 2 ) {
printf( "The required argument is missing!\nUse: %s <source.csv>.\nExiting...", argv[0] );
return 0;
}
Spdr3dModel model;
parseFile( model, argv[1] );
Spdr3dModel::display( model, argc, argv );
return 0;
}
|
class LFUCache {
private:
int capacity, size, minFreq;
unordered_map<int, pair<int, int> > keyToPair;
unordered_map<int, list<int> > freqToKeys;
unordered_map<int, list<int>::iterator > keyToIterator;
// remove all data related to given key
void remove(int key){
int freq = keyToPair[key].second;
keyToPair.erase(key);
auto it = keyToIterator[key];
freqToKeys[freq].erase(it);
keyToIterator.erase(key);
}
// put key, val, freq and check if minFreq is increased
void put(int key, int val, int freq){
keyToPair[key] = make_pair(val, freq);
freqToKeys[freq].push_back(key);
keyToIterator[key] = --freqToKeys[freq].end();
if(freqToKeys[minFreq].empty())
minFreq++;
}
public:
LFUCache(int c) {
capacity = c;
size = 0;
minFreq = 1;
}
int get(int key) {
auto pair = keyToPair.find(key);
// if key not exists
if(pair == keyToPair.end())
return -1;
int val = pair -> second . first;
int freq = pair -> second . second;
// increase frequency
remove(key);
put(key, val, freq + 1);
return val;
}
void put(int key, int value) {
int old_val = get(key);
// if key not exists, put
if(old_val == -1){
size++;
put(key, value, 1);
// check if cache reached capacity
if(size > capacity){
// remove the first of minfreq list
int remove_key = freqToKeys[minFreq].front();
remove(remove_key);
}
minFreq = 1;
}
// if key exists, increase frequency.
else{
int freq = keyToPair[key].second;
remove(key);
put(key, value, freq + 1);
}
}
};
|
//---------------------------------------------------------------------------
#pragma hdrstop
#include "FileSearch.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
AllFileSearch::AllFileSearch()
{
m_CurFile = new CFileMappingStream();
m_Result = new TStringList;
m_Process = NULL;
}
AllFileSearch::~AllFileSearch()
{
delete m_CurFile;
delete m_Result;
}
void AllFileSearch::BeginSearch(String path, String fileExt, String data, bool includeSub, TCGauge * process)
{
m_Process = process;
auto_ptr<TStringList> filesList(new TStringList);
GetFileList(path, fileExt, filesList.get(), includeSub);
m_Data = data;
StartSearch(filesList.get());
}
void AllFileSearch::StartSearch(TStringList * searchDir)
{
m_Result->Clear();
m_Process->MaxValue = searchDir->Count;
for(int i=0; i<searchDir->Count; i++)
{
m_Process->Progress = i;
Application->ProcessMessages();
try
{
m_CurFile->Open(searchDir->Strings[i], fmOpenRead);
if(CheckFile())
{
m_Result->Add(searchDir->Strings[i]);
}
m_CurFile->Close();
}
catch(...)
{
continue;
}
}
m_Process->Progress = searchDir->Count;
}
bool AllFileSearch::CheckFile()
{
LPVOID result = m_SearchEngine.NormalSearch(m_CurFile->Memory, m_CurFile->Size, m_Data.c_str());
if(result == NULL)
return false;
return true;
}
void AllFileSearch::ReSearch(String data)
{
if(m_Result->Count == 0)
return;
m_Data = data;
auto_ptr<TStringList> filesList(new TStringList);
filesList->AddStrings(m_Result);
StartSearch(filesList.get());
}
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 10000
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
int N,M;
int table[MAXN+5];
bool isOdd(int k){
return abs(k)&1;
}
bool cmp(int a, int b){
if( a%M != b%M ) return a%M < b%M;
if( isOdd(a) != isOdd(b) ) return isOdd(a) ;
if( isOdd(a) ) return a > b;
return a < b;
}
int main(int argc, char const *argv[])
{
while( ~scanf("%d %d", &N, &M) ){
for(int i = 0 ; i < N ; i++ )
scanf("%d", &table[i]);
sort(table,table+N,cmp);
printf("%d %d\n", N, M);
for(int i = 0 ; i < N ; i++ )
printf("%d\n",table[i]);
}
return 0;
}
|
#include "wave_point.h"
wave_point::wave_point(
std::shared_ptr<shady_engine::texture2D> pTexture,
std::shared_ptr<shady_engine::sprite_renderer> pRenderer,
const glm::vec2& pPosition,
const glm::vec2& pSize)
:
GameEntity(pPosition,pSize),
collider(pPosition,pSize),
mRenderer(pRenderer),
mTexture(pTexture)
{
}
void wave_point::render(const glm::mat4 & pProjection, const glm::mat4 & pView) const
{
static float angle = 0;
angle += 10.0f;
mRenderer->draw_image(pProjection,pView,mTexture,mPosition,mSize,glm::radians(angle));
}
|
#ifndef __FIELD_DATA_H
#define __FIELD_DATA_H
#include "filter_data.h"
namespace wh{
enum class FieldEditor
{
Normal = 0,
Type = 1
};
//-----------------------------------------------------------------------------
class Field
{
public:
class Filter
{
public:
Filter()
:mOp(foEq), mConn(fcAND), mEnable(false)
{}
Filter(const wxString& val, FilterOp fo = foEq
, FilterConn fc = fcAND, bool enable = true)
:mVal(val), mOp(fo), mConn(fc), mEnable(enable)
{}
void Set(const wxString& val, FilterOp fo = foEq
, FilterConn fc = fcAND, bool enable = true)
{
mVal=val;
mOp=fo;
mConn=fc;
mEnable = enable;
}
wxString mVal;
FilterOp mOp;
FilterConn mConn;
bool mEnable;
bool operator==(const Filter& f)const
{
return mVal == f.mVal
&& mOp == f.mOp
&& mEnable == f.mEnable
&& mConn == f.mConn;
}
bool operator!=(const Filter& f)const
{
return !operator==(f);
}
};
wxString mTitle;
wxString mDbTitle;
FieldType mType = ftText;
FieldEditor mEditor = FieldEditor::Normal;
bool mGuiShow = true;
bool mGuiEdit = true;
//bool mSelect = true;
bool mInsert = true;
bool mUpdate = true;
bool mKey = false;
int mSort = 0;
std::vector<Filter> mFilter;
Field(){}
Field(const char* name, FieldType ft, bool show)
:mTitle(name), mType(ft), mGuiShow(show)
{}
Field(const wxString& name, FieldType ft, bool show, const wxString& dbname=wxEmptyString)
:mTitle(name), mType(ft), mGuiShow(show), mDbTitle(dbname)
{}
bool operator==(const Field& fld)const
{
if (mFilter.size() != fld.mFilter.size())
return false;
bool eqFilter = true;
for (size_t i = 0; i < mFilter.size(); ++i)
{
if (mFilter[i] != fld.mFilter[i])
{
eqFilter = false;
break;
}
}
return eqFilter
&& mTitle == fld.mTitle
&& mDbTitle == fld.mDbTitle
&& mType == fld.mType
&& mEditor == fld.mEditor
&& mGuiShow == fld.mGuiShow
&& mGuiEdit == fld.mGuiEdit
&& mInsert == fld.mInsert
&& mUpdate == fld.mUpdate
&& mKey == fld.mKey
&& mSort == fld.mSort;
}
bool operator!=(const Field& fld)const
{
return !operator==(fld);
}
};
//-----------------------------------------------------------------------------
const static std::vector<Field> gEmptyFieldVec;
class FieldsInfo
{
public:
virtual ~FieldsInfo()
{
}
virtual const std::vector<Field>& GetFieldVector()const
{
return gEmptyFieldVec;
}
unsigned int GetFieldQty()const
{
return GetFieldVector().size();
}
const wxString& GetFieldName(unsigned int col)const
{
return GetFieldVector()[col].mTitle;
}
const FieldType& GetFieldType(unsigned int col)const
{
return GetFieldVector()[col].mType;
}
virtual bool GetFieldValue(unsigned int col, wxVariant &variant)
{
return false;
}
};
}//namespace wh{
#endif // __****_H
|
#pragma once
#include"Game.h"
Player* Game::GetPlayer(int n)
{
return players[n];
}
bool Game::SavePlayer(Player* obj)
{
players.push_back(obj);
return 0;
}
|
#ifndef ADAPTER_H
#define ADAPTER_H
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include "search_engine.h"
#include "utils/pstream.h"
class DLRSAdapter : public ProbabilisticSearchEngine {
public:
DLRSAdapter(std::string _name);
//=== Game Control === //
// Notify the search engine that the session starts
void initSession() override;
void finishSession(double totalReward) override;
// Notify the search engine that a new round starts or ends
void initRound() override;
void finishRound(double roundReward) override;
// Notify the search engine that a new step starts or ends
void initStep(State const& current) override;
void finishStep(double reward) override;
void finishStep(std::vector<double> *successor, const double& reward) override;
//=== Search ===//
void estimateBestActions(State const& _rootState, std::vector<int>& bestActions);
// === "Override" methods from superclass that are not needed for this adapter === //
void estimateQValue(State const&, int, double&) override { assert(false); }
void estimateQValues(State const&, std::vector<int> const&, std::vector<double>&) override { assert(false); }
void printRoundStatistics(std::string) const override { assert(false); }
void printStepStatistics(std::string) const override { assert(false); }
private:
std::string in_pipe = "/home/roman/parser/PACTION";
std::string out_pipe = "/home/roman/parser/PSTATE";
void printState(State const& state);
void printState(std::vector<double> *stateVariables);
std::ifstream input;
PStream pstream;
int numberOfStateVariables;
};
#endif
|
#pragma once
#include "../MonsterAction.h"
class Monster;
class Act_Guardian :public MonsterAction
{
public:
Act_Guardian();
bool Action(Monster* me) override;
private:
bool m_first = true;
float m_time = 0;
float m_def = 0;
float m_Exdef = 0;
};
|
/**
* Copyright (c) 2019, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LNAV_HELP_TEXT_HH
#define LNAV_HELP_TEXT_HH
#include <map>
#include <string>
#include <vector>
enum class help_context_t {
HC_NONE,
HC_PARAMETER,
HC_RESULT,
HC_COMMAND,
HC_SQL_COMMAND,
HC_SQL_KEYWORD,
HC_SQL_INFIX,
HC_SQL_FUNCTION,
HC_SQL_TABLE_VALUED_FUNCTION,
};
enum class help_function_type_t {
HFT_REGULAR,
HFT_AGGREGATE,
};
enum class help_nargs_t {
HN_REQUIRED,
HN_OPTIONAL,
HN_ZERO_OR_MORE,
HN_ONE_OR_MORE,
};
enum class help_parameter_format_t {
HPF_STRING,
HPF_REGEX,
HPF_INTEGER,
HPF_NUMBER,
HPF_DATETIME,
HPF_ENUM,
};
struct help_example {
const char* he_description{nullptr};
const char* he_cmd{nullptr};
};
struct help_text {
help_context_t ht_context{help_context_t::HC_NONE};
const char* ht_name{nullptr};
const char* ht_summary{nullptr};
const char* ht_flag_name{nullptr};
const char* ht_group_start{nullptr};
const char* ht_group_end{nullptr};
const char* ht_description{nullptr};
std::vector<struct help_text> ht_parameters;
std::vector<struct help_text> ht_results;
std::vector<struct help_example> ht_example;
help_nargs_t ht_nargs{help_nargs_t::HN_REQUIRED};
help_parameter_format_t ht_format{help_parameter_format_t::HPF_STRING};
std::vector<const char*> ht_enum_values;
std::vector<const char*> ht_tags;
std::vector<const char*> ht_opposites;
help_function_type_t ht_function_type{help_function_type_t::HFT_REGULAR};
void* ht_impl{nullptr};
help_text() = default;
help_text(const char* name, const char* summary = nullptr) noexcept
: ht_name(name), ht_summary(summary)
{
if (name[0] == ':') {
this->ht_context = help_context_t::HC_COMMAND;
this->ht_name = &name[1];
}
}
help_text& command() noexcept
{
this->ht_context = help_context_t::HC_COMMAND;
return *this;
}
help_text& sql_function() noexcept
{
this->ht_context = help_context_t::HC_SQL_FUNCTION;
return *this;
}
help_text& sql_agg_function() noexcept
{
this->ht_context = help_context_t::HC_SQL_FUNCTION;
this->ht_function_type = help_function_type_t::HFT_AGGREGATE;
return *this;
}
help_text& sql_table_valued_function() noexcept
{
this->ht_context = help_context_t::HC_SQL_TABLE_VALUED_FUNCTION;
return *this;
}
help_text& sql_command() noexcept
{
this->ht_context = help_context_t::HC_SQL_COMMAND;
return *this;
}
help_text& sql_keyword() noexcept
{
this->ht_context = help_context_t::HC_SQL_KEYWORD;
return *this;
}
help_text& sql_infix() noexcept
{
this->ht_context = help_context_t::HC_SQL_INFIX;
return *this;
}
help_text& with_summary(const char* summary) noexcept
{
this->ht_summary = summary;
return *this;
}
help_text& with_flag_name(const char* flag) noexcept
{
this->ht_flag_name = flag;
return *this;
}
help_text& with_grouping(const char* group_start,
const char* group_end) noexcept
{
this->ht_group_start = group_start;
this->ht_group_end = group_end;
return *this;
}
help_text& with_parameters(
const std::initializer_list<help_text>& params) noexcept;
help_text& with_parameter(const help_text& ht) noexcept;
help_text& with_result(const help_text& ht) noexcept;
help_text& with_examples(
const std::initializer_list<help_example>& examples) noexcept;
help_text& with_example(const help_example& example) noexcept;
help_text& optional() noexcept
{
this->ht_nargs = help_nargs_t::HN_OPTIONAL;
return *this;
}
help_text& zero_or_more() noexcept
{
this->ht_nargs = help_nargs_t::HN_ZERO_OR_MORE;
return *this;
}
help_text& one_or_more() noexcept
{
this->ht_nargs = help_nargs_t::HN_ONE_OR_MORE;
return *this;
}
help_text& with_format(help_parameter_format_t format) noexcept
{
this->ht_format = format;
return *this;
}
help_text& with_enum_values(
const std::initializer_list<const char*>& enum_values) noexcept;
help_text& with_tags(
const std::initializer_list<const char*>& tags) noexcept;
help_text& with_opposites(
const std::initializer_list<const char*>& opps) noexcept;
template<typename F>
help_text& with_impl(F impl)
{
this->ht_impl = (void*) impl;
return *this;
}
void index_tags();
static std::multimap<std::string, help_text*> TAGGED;
};
#endif
|
#include "stdafx.h"
#include "MultipleResponseQuestionViewController.h"
#include "MultipleResponseQuestionState.h"
#include "MultipleResponseQuestionView.h"
namespace qp
{
CMultipleResponseQuestionViewController::CMultipleResponseQuestionViewController(CMultipleResponseQuestionStatePtr const& questionState, CMultipleResponseQuestionViewPtr const& view)
:CQuestionViewController(questionState, view)
, m_questionState(questionState)
, m_view(view)
, m_choiceSelectedRequestedConnection(view->DoOnChoiceSelected(bind(&CMultipleResponseQuestionViewController::OnChoiceSelectedRequest, this, _1)))
{
}
CMultipleResponseQuestionViewController::~CMultipleResponseQuestionViewController()
{
}
void CMultipleResponseQuestionViewController::OnChoiceSelectedRequest(size_t answerIndex)
{
bool isSelected = m_questionState->ResponseIsSelected(answerIndex);
m_questionState->ChangeResponse(answerIndex, !isSelected);
m_view->Show();
}
}
|
#include<iostream>
using namespace std;
typedef unsigned int ui;
ui n,t,c,*a;
void nhap(){
cin>>n>>t>>c;
a=new ui[n];
for(ui i=0;i<n;i++) cin>>a[i];
}
void xuat(){
ui dem=0,i,k=0;
for(i=0;i<n;i++) if(a[i]<=t) a[i]=1;
else a[i]=0;
for(i=0;i<n;i++)
if(a[i]){
if(i-k+1==c) {
dem++;k++;
}
}
else{
k=i+1;
}
cout<<dem;
}
int main(){
nhap();
xuat();
delete []a;
return 0;
}
|
/*
* Copyright (C) 2007,2008 Alex Shulgin
*
* This file is part of png++ the C++ wrapper for libpng. PNG++ is free
* software; the exact copying conditions are as follows:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PNGPP_GENERATOR_HPP_INCLUDED
#define PNGPP_GENERATOR_HPP_INCLUDED
#pragma once
//#include <cassert>
#include <stdexcept>
#include <iostream>
#include <ostream>
#include "config.hpp"
#include "error.hpp"
#include "streaming_base.hpp"
#include "writer.hpp"
namespace png
{
/**
* \brief Pixel generator class template.
*
* Used as a base class for custom pixel generator classes as well as inside image class implementation to write pixels from the pixel buffer.
*
* A usage example can be found in \c example/pixel_generator.cpp.
*
* Encapsulates PNG %image writing procedure. In order to create a custom pixel %generator use CRTP trick:
*
* \code
* class pixel_generator : public png::generator<pixel, pixel_generator>
* {
* ...
* };
* \endcode
*
* Your pixel %generator class should implement \c get_next_row() method and \c reset() method (optional). Their signatures are as follows:
*
* \code
* png::byte* get_next_row(png::uint_32 pos);
* void reset(size_t pass);
* \endcode
*
* The \c get_next_row() method is called every time a new row of %image data is needed by the writer. The position of the row being written is
* passed as \c pos parameter. The \c pos takes values from \c 0 to \c <image_height>-1 inclusively. The method should return the starting
* address of a row buffer storing an appropriate amount of pixels (i.e. the width of the %image being written). The address should be casted
* to png::byte* pointer type using \c reinterpret_cast<> or a C-style cast.
*
* The optional \c reset() method is called every time the new pass of interlaced %image processing starts. The number of interlace pass is
* avaiable as the only parameter of the method. For non-interlaced images the method is called once prior to any calls to \c get_next_row().
* The value of \c 0 is passed for the \c pass number. You do not have to implement this method unless you are going to support interlaced %image generation.
*
* An optional template parameter \c info_holder encapsulated image_info storage policy.
* Please refer to consumer class documentation for the detailed description of this parameter.
*
* An optional \c bool template parameter \c interlacing_supported specifies whether writing interlacing images is supported by your %generator class.
* It defaults to \c false. An attempt to write an interlaced %image will result in throwing \c std::logic_error.
*
* In order to fully support interlacing specify \c true for \c interlacing_supported parameter and implement \c reset() method.
* You _must_ generate the same pixels for every pass to get the correct PNG %image output.
*
* \see image, consumer
*/
template<typename pixel, typename pixgen, typename info_holder = def_image_info_holder, bool interlacing_supported = false>
class generator : public streaming_base<pixel, info_holder>
{
public:
/**
* \brief Writes an image to the stream.
*
* Essentially, this method constructs a writer object and instructs it to write the image to the stream.
* It handles writing interlaced images as long as your generator class supports this.
*/
template<typename ostream>
inline constexpr void write(ostream& stream)
{
writer<ostream> wr(stream);
wr.set_image_info(this->get_info());
wr.write_info();
if constexpr (__little_endian)
{
if (pixel_traits<pixel>::get_bit_depth() == 16)
{
if constexpr (png_write_swap_supported)
{
wr.set_swap();
}
else
{
throw error("Cannot write 16-bit image: recompile with PNG_WRITE_SWAP_SUPPORTED.");
}
}
}
size_t pass_count;
if (this->get_info().get_interlace_type() != interlace_none)
{
if constexpr (png_write_interlacing_supported)
{
if constexpr (interlacing_supported)
{
pass_count = wr.set_interlace_handling();
}
else
{
throw std::logic_error("Cannot write interlaced image: generator does not support it.");
}
}
else
{
throw error("Cannot write interlaced image: interlace handling disabled.");
}
}
else
{
pass_count = 1;
}
auto pixel_gen{static_cast<pixgen*>(this)};
for (size_t pass{0}; pass < pass_count; ++pass)
{
pixel_gen->reset(pass);
for (size_t pos{0}; pos < this->get_info().get_height(); ++pos)
{
wr.write_row(pixel_gen->get_next_row(pos));
}
}
wr.write_end_info();
}
protected:
using base = streaming_base<pixel, info_holder>;
/**
* \brief Constructs a generator object using passed image_info object to store image information.
*/
explicit inline constexpr generator(image_info& info) noexcept : base(info) {}
/**
* \brief Constructs a generator object prepared to generate an image of specified width and height.
*/
inline constexpr generator(uint64_t width, uint64_t height) noexcept : base(width, height) {}
};
} // namespace png
#endif // PNGPP_GENERATOR_HPP_INCLUDED
|
#pragma once
#ifndef ssqIncH
#define ssqIncH
#define MEMSET_ std::memset
#define MEMCPY_ std::memcpy
#define STRCPY_ std::strcpy
#define Lotter_TM_STR_LEN (20)
struct TParseCmd
{
std::vector<std::string> vS;
TParseCmd() {}
TParseCmd(const std::string& s) { parse(s); }
int size() { return vS.size(); }
static int StrToInt(const std::string& s)
{
if (s.empty())return 0;
if (s.size() < 1) return 0;
int len = s.length();
int i = 0;
int flag = 10;
while (s[i] == ' ')++i;
while (s[i] == '0') { ++i; }
if (s[i] == 'x' || s[i] == 'X')
{
++i;
flag = 16;
}
if (len > i)
{
char *p = NULL;
return std::strtol(&(s[i]), &p, flag);
}
return 0;
}
int parse(const std::string& s)
{
vS.clear();
int len = s.length();
int i = 0;
do
{
while ((s[i] == ' ' || s[i] == '\t') && i < len)++i;
if (i >= len) return 0;
int j = i;
while (j < len && (s[j] != ' ' && s[j] != '\t'))++j;
vS.push_back(s.substr(i, j - i));
i = j;
} while (i < len);
return vS.size();
}
private:
std::string s;
};
struct TLotter3Stru_
{
static int SSQSumAvg;
char tmstr[Lotter_TM_STR_LEN]; ///
unsigned int seqno; ///
int a[10]; ///
int p_[10];
int o1; ///
int e1; ///
char stroe[16]; ///
int iSectiona_[3]; ///
char secranger[16]; ///
int sum1;
char strSum1[16];
int infosame1;
char infoDir1[8];
int the1stOE;
int theLastOe;
///int iLinkCnt;
int iLinkA[3 + 1];
char linkStr[6];
char str1[16];
char infostr1[64];
char str2[16];
char infostr2[64];
int flag_;
int itmp_; ///
std::string c_next_infostr2_;
std::string c_infostr2_;
TLotter3Stru_(int inFlag = 0) ///
{
reset();
}
TLotter3Stru_(TParseCmd& parseCmd)
{
reset();
if (parseCmd.vS.size() > 1) ///loadFromFile
{
std::memcpy(tmstr, parseCmd.vS[1].c_str(), parseCmd.vS[1].size()); ///idtmstr = parseCmd.vS[1];
const char* p = parseCmd.vS[2].c_str();
}
calc_();
}
void calc_()
{
///std::sprintf(idstr, "%02d%02d%02d%02d%02d%02d%02d%02d%02d%02d\0", i1, i2, i3, i4, i5, i6, i7, i8, i9, i10);
}
int chkO_(TLotter3Stru_& rhv, const int inChkNextFlag = 0);
void reset()
{
///i1 = i2 = i3 = i4 = i5 = i6 = j1 = 0;
///e1 = o1 = sum1 = 0;
const int isize1_ = offsetof(TLotter3Stru_, itmp_) - offsetof(TLotter3Stru_, tmstr);
MEMSET_(tmstr, 0, isize1_);
flag_ = 1; ///
c_infostr2_ = "";
}
const char* get_c_infostr2_()
{
return c_infostr2_.c_str();
}
};
#define LS_CHK_SIZE (101)
#define LS_RECCHK_MAX_SIZE (10000)
struct TLsFlagStru_
{
int flaga[10][20];
int flaga2[10][20]; ///
int flagsum2a[10][20]; ///
int flagsum2a2[10][20]; ///
int p_[20];
int sumOEa[3][5][20]; ///
int sumNumA[3][5][20]; ///
};
extern int ParseLotter3Txt(const char s[1024], TLotter3Stru_& inlt);
extern int ParseLotter3XMLRom(const char s[1024], TLotter3Stru_& inlt);
extern int ParseLotter3XMLRom(const std::string& s, TLotter3Stru_& inlt);
extern int ParseLotter3XMLRom2_(const std::string& s, TLotter3Stru_& inlt);
#endif
///std::map<std::string, TLotter3Stru_> mapS2SSQStru;
//unsigned int minLsseqno, maxLsseqno; ///
bool GenDataLsStru(const DWORD inbegin);
bool GetLsDataStruNum(const bool inAddEdtFlag = 0);
bool GetLsDataStruOE(const bool inAddEdtFlag = 0);
bool GetLsDataStruSumNum(const int inflag); ///相邻2个(也可以任意2个)和值的大小和奇偶
bool GetLsDataStruSumOE(const int inflag);
bool GenParseLsData(int x);
//bool bDataRefresh;
//void SaveHisDate();
bool btnLoadDate(const std::string& strHisDataFile);
int get_longest();
void get_need_shoot(int sum);
void text_incersion();
void get_shoot();
int dataProcess(std::string filename, int temp);
|
#include "Light.h"
// public
Light::Light()
{
mBuffer = NULL;
mDirection = D3DXVECTOR3(0.0F, 0.0F, 0.0F);
mPosition = D3DXVECTOR3(0.0F, 0.0F, 0.0F);
mSpeed = 0.0F;
mAngle = 0.0F;
}
Light::~Light()
{
SafeReleaseCom(mBuffer);
}
void Light::Initialize()
{
mDirection = D3DXVECTOR3(0.01F, -1.0F, 0.01F);
mPosition = D3DXVECTOR3(0.0F, 0.0F, 0.0F);
mSpeed = 10.0F;
mAngle = (FLOAT)D3DX_PI / 180.0F * -45.0F;
// 3D 프로젝션 행렬
FLOAT fovy = (FLOAT)D3DX_PI / 2.0F;
FLOAT aspect = 1.0F;
D3DXMatrixPerspectiveFovLH
(
&mProjection,
fovy,
aspect,
gCFEngine.Near,
gCFEngine.Depth
);
CreateBuffer(D3D.GetDevice(), D3D11_BIND_CONSTANT_BUFFER, sizeof(BufferData), D3D11_USAGE_DYNAMIC, NULL, &mBuffer);
}
void Light::Update(FLOAT delta)
{
// 빛의 방향
mAngle -= (FLOAT)D3DX_PI / 180.0F * delta * mSpeed;
mDirection.x = cosf(mAngle);
mDirection.y = sinf(mAngle);
D3DXVec3Normalize(&mDirection, &mDirection);
// View행렬
D3DXVECTOR3 up = D3DXVECTOR3(0.0F, 1.0F, 0.0F);
D3DXVECTOR3 lookat = D3DXVECTOR3(0.0F, 0.0F, 0.0F); // Terrain의 중심좌표.. 보다는 카메라의 위치좌표가 좋지 않을까..?
mPosition = lookat - (mDirection * 300);
D3DXMatrixLookAtLH(&mView, &mPosition, &lookat, &up);
}
void Light::SetBuffer()
{
D3DXMATRIX view = mView;
D3DXMATRIX projection = mProjection;
D3DXMatrixTranspose(&view, &view);
D3DXMatrixTranspose(&projection, &projection);
BufferData data;
data.View = view;
data.Projection = projection;
data.Direction = D3DXVECTOR3(0.01F, -1.0F, 0.01F);
data.Position = mPosition;
data.Pad = D3DXVECTOR2(1.0F, 1.0F);
SetConstantBuffer(D3D.GetContext(), mBuffer, &data, sizeof(BufferData), (UINT)RB_Light);
}
D3DXMATRIX Light::GetView() { return mView; }
D3DXMATRIX Light::GetProjection() { return mProjection; }
D3DXVECTOR3 Light::GetDirection() { return mDirection; }
D3DXVECTOR3 Light::GetPosition() { return mPosition; }
|
//知识点:生成树
/*
题目要求:
点有点权,边有边权
花费点权后,可以让这个点变成 "好的"
求最小花费,
使所有点都与"好的"点直接间接相连.(或者本身为 "好的")
思路:
既有点权,又有边权,
有要求一棵生成树
对原图直接操作不可.
考虑重建图,
将点权转化为边权.
算法实现:
设立一个超级源点,
并将每个点都与超级源点连边
边权值即为每个点的点权值.
然后将超级源点加入图中,
跑最小生成树即可.
*/
#include<cstdio>
#include<algorithm>
#include<ctype.h>
const int MARX = 510;
//=============================================================
struct edge
{
int u,v,w;
}e[MARX*MARX/2];
int n,num,fa[MARX];
bool map[MARX][MARX];
long long ans;
//=============================================================
inline int read()
{
int fl=1,w=0;char ch=getchar();
while(!isdigit(ch) && ch!='-') ch=getchar();
if(ch=='-') fl=-1;
while(isdigit(ch)){w=w*10+ch-'0',ch=getchar();}
return fl*w;
}
inline bool cmp(edge first,edge second){return first.w<second.w;}
inline void add(int u,int v,int w){e[++num].v=v,e[num].u=u,e[num].w=w;}
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}//查集
inline void join(int x,int y)//并集
{
int r1=find(x),r2=find(y);
fa[r1]=r2;
}
void kruscal()//kruscal最小生成树
{
for(int i=1;i<=num;i++)
if(find(e[i].u) != find(e[i].v))
{
join(e[i].u,e[i].v);
ans+=(long long)e[i].w;//答案添加
}
}
void prepare()
{
n=read();
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=n;i++)
{
int w=read();
add(n+1,i,w),add(i,n+1,w);//向超级源点n+1连边
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)//加边
{
int w=read();
if(!map[i][j] && i!=j) add(i,j,w),add(j,i,w);
map[i][j]=map[j][i]=1;
}
std::sort(e+1,e+num+1,cmp);//按照边权升序排序
}
//=============================================================
signed main()
{
prepare();
kruscal();
printf("%lld",ans);
}
|
//
// Created by micky on 15. 5. 22.
//
#ifndef JUDGESERVER_THREAD_H
#define JUDGESERVER_THREAD_H
#include <pthread.h>
#include <signal.h>
#include <string>
#include <exception>
#include <map>
namespace Thread{
void *thread_main(void *args);
class Thread {
private:
static std::map<pthread_t, Thread *> _threads;
pthread_t _id;
bool _running;
public:
Thread();
~Thread() {_threads.erase(_id);}
bool isRunning() const { return _running; }
virtual void run();
void start();
void join(void **ret_data);
void detach();
void stop();
pthread_t getThreadId() const {return _id;}
static Thread *currentThread(){};
friend void *thread_main(void *args);
};
class ThreadException : public std::exception {
private :
std::string _what;
public :
ThreadException(const char *msg) {
_what = msg;
}
virtual const char *what() const throw() {
return _what.c_str();
}
virtual ~ThreadException(){}
};
};
#endif //JUDGESERVER_THREAD_H
|
/************************************************************************/
/*Given an expression string exp, write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[","]” are correct in exp. For example, the program should print true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”*/
/************************************************************************/
#include <stack>
#include <string>
#include <map>
#include <set>
using namespace std;
bool IsBalanced(const string &str){
stack<char> Stack;
set<char> LeftparenthessSet;
set<char> RightparenthessSet;
map<char, char> parenthessMap;
LeftparenthessSet.insert('(');
LeftparenthessSet.insert('{');
LeftparenthessSet.insert('[');
RightparenthessSet.insert(')');
RightparenthessSet.insert(']');
RightparenthessSet.insert('}');
parenthessMap[')'] = '(';
parenthessMap[']'] = '[';
parenthessMap['}'] = '{';
for(int i = 0; i < str.size(); ++i){
//如果是左括号则直接插入
if(LeftparenthessSet.find(str[i]) != LeftparenthessSet.end()){
Stack.push(str[i]);
}
else{
//如果是右括号,则先看栈顶端是否为匹配的左括号,如果是则出栈,否则进栈
if(RightparenthessSet.find(str[i]) != RightparenthessSet.end()){
if(Stack.empty()){
return false;
}
char ch = Stack.top();
if(ch == parenthessMap[str[i]]){
Stack.pop();
}
else{
Stack.push(str[i]);
}
}
}
}
if(Stack.empty()){
return true;
}
return false;
}
//
//int main(){
// string str = "}";
// bool result = IsBalanced(str);
// return true;
//}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.