blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bf13af9b2152c6e129c741a6fed9483e1d3dc4c5 | 9331316cec59492c9ae5a073dda76779cb55f0e3 | /Programacao Orientada Objectos/MMInvaders/Project1WForms/FormJogo.h | 19145bf94c424f82ec1868c381b50e6c49c53afa | [
"MIT"
] | permissive | dicamarques14/ProjectosProgramacao | 818e5ef03acdd8a1f698385f5a70cfbeefca0d90 | fdfa52cc46fc8dcdc65d4cb471ed31546433a6ad | refs/heads/master | 2021-05-23T05:35:01.030007 | 2018-01-20T13:36:43 | 2018-01-20T13:36:43 | 95,093,989 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 44,032 | h | #pragma once
#include <string>
#include <iostream>
using namespace std;
#include "GestaoTudo.h"
#include "FormSelectNivel.h"
#include "Defines.h"
#include "FormLogin.h"
#include "FormTabela.h"
namespace Project1WForms {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Xml;
using namespace System::Collections::Generic; //For Generic List <-- LISTA PB
/// <summary>
/// Summary for FormJogo
/// </summary>
public ref class FormJogo : public System::Windows::Forms::Form
{
int TiroImag; //contador de imagens para os tiros
int EstadoDoJogo; // estado em que se encontra o jogo
int moverJogador; //Se é ou nao para deslocar o jogador e em que direccao
int disparaJogador; //variavel que diz se o espaco esta a ser pressionado ou nao
int ImagemJogador;//qual a imagem que o jogador mostra
int ContarAbreBoca;//decrementa, se for 0 Abre
int ContarFechaBoca;//decrementa, se for 0 Fecha
int ContarMexeInimigo;//decrementa, se 0 desloca os inimigos
int ContarActualizaDados;
int ContarMudaImagemJogador;
int ContarDispararTiroInimigo;
GestaoTudo *GMorg;//ponteiro para o gestor
//Imagens do BOSS
Image ^ImgBossHead;
Image ^ImgBossBoca;
//LISTA DAS IMAGENS
ImageList ^ListaImgTiros;
ImageList ^ListaImgInimigos;
ImageList ^ListaImgJogador;
//Lista das PICTUREBOXES
List<PictureBox^>^ ListPBTiros ;
List<PictureBox^>^ ListPBInimigos ;
private: System::Windows::Forms::PictureBox^ Player_PB;
private: System::Windows::Forms::ListBox^ listBox1;
private: System::Windows::Forms::Label^ Points_LB;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ Lifes_LB;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ Level_LB;
private: System::Windows::Forms::Label^ label4;
private: System::Windows::Forms::Label^ LimitV_LB;
private: System::Windows::Forms::Label^ LimitH_LB;
private: System::Windows::Forms::Label^ username_LB;
private: System::Windows::Forms::Label^ label5;
private: System::Windows::Forms::Label^ hscore_LB;
private: System::Windows::Forms::Label^ label7;
private: System::Windows::Forms::Button^ scrbrd_BTN;
private: System::Windows::Forms::PictureBox^ pictureBox1;
private: System::Windows::Forms::Button^ Fire_BTN;
private: System::Windows::Forms::Button^ Exit_BTN;
private: System::Windows::Forms::Timer^ timer1;
private: System::Windows::Forms::Button^ Start_BTN;
private: System::Windows::Forms::Button^ Stop_BTN;
private: System::ComponentModel::IContainer^ components;
public:
FormJogo(void)
{
InitializeComponent();
GMorg = new GestaoTudo();
GMorg->LeUtilizadoresFicheiro();//carregar os users ja existentes
KeyPreview=true; // para funcionar as teclas
ListaImgTiros = gcnew ImageList();
ListaImgTiros->ColorDepth= ColorDepth::Depth32Bit;
ListaImgTiros->ImageSize = System::Drawing::Size(TiroSize_W, TiroSize_H);
ListaImgInimigos = gcnew ImageList();
ListaImgInimigos->ColorDepth= ColorDepth::Depth32Bit;
ListaImgInimigos->ImageSize = System::Drawing::Size(InimigoSize_W, InimigoSize_H);
ListaImgJogador = gcnew ImageList();
ListaImgJogador->ColorDepth= ColorDepth::Depth32Bit;
ListaImgJogador->ImageSize = System::Drawing::Size(JogadorSize_W, JogadorSize_H);
ImgBossHead = Image::FromFile("..\\Imagens\\Enemy\\boss_head.dg");
ImgBossBoca = Image::FromFile("..\\Imagens\\Enemy\\boss_boca.dg");
ListPBTiros = gcnew(List<PictureBox^>); //http://stackoverflow.com/questions/23519002/visual-c-2012-using-a-stdvector-or-stdlist-in-class
ListPBInimigos = gcnew(List<PictureBox^>);
//CARREGAR AS IMAGENS
addImage(ListaImgTiros,"..\\Imagens\\Bullet\\mm1.png");
addImage(ListaImgTiros,"..\\Imagens\\Bullet\\mm2.png");
addImage(ListaImgTiros,"..\\Imagens\\Bullet\\mm3.png");
addImage(ListaImgTiros,"..\\Imagens\\Bullet\\mm4.png");
addImage(ListaImgTiros,"..\\Imagens\\Bullet\\mm5.png");
addImage(ListaImgTiros,"..\\Imagens\\Bullet\\mm6.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_dead.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_1.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_2.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_3.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_4.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_5.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_6.png");
addImage(ListaImgInimigos,"..\\Imagens\\Enemy\\enemy_7.png");
addImage(ListaImgJogador,"..\\Imagens\\Player\\mariana_dir1.png");
addImage(ListaImgJogador,"..\\Imagens\\Player\\mariana_dir2.png");
addImage(ListaImgJogador,"..\\Imagens\\Player\\mariana_esq1.png");
addImage(ListaImgJogador,"..\\Imagens\\Player\\mariana_esq2.png");
cout << "Imagens Prontas"<<endl;
EstadoDoJogo = Est_Parado;
TiroImag = 0;
moverJogador = 0;
disparaJogador = 0;
ContarAbreBoca=TimerAbreBoca;
ContarFechaBoca=TimerFechaBoca;
ContarMexeInimigo=TimerMexeInimigo;
ContarActualizaDados=TimerActualizaDados;
ContarDispararTiroInimigo = TimerDispararTiroInimigo;
ContarMudaImagemJogador = TimerMudaImagemJogador;
ImagemJogador = 0;
Player_PB->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
Player_PB->BackColor = Drawing::Color::Transparent;//colocar fundo da PB transparente
Player_PB->Image = ListaImgJogador->Images[0];
//colocar limites da area de jogo
LimitV_LB->Location = Drawing::Point(JogoSize_W,0);
LimitV_LB->Size = Drawing::Size(20,JogoSize_H+20);
LimitH_LB->Location = Drawing::Point(0,JogoSize_H);
LimitH_LB->Size = Drawing::Size(JogoSize_W+20,20);
}
protected:
~FormJogo()
{
GMorg->EscreveUtilizadoresFicheiro();
delete GMorg;
if (components)
{
delete components;
}
}
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(FormJogo::typeid));
this->Exit_BTN = (gcnew System::Windows::Forms::Button());
this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));
this->Start_BTN = (gcnew System::Windows::Forms::Button());
this->Stop_BTN = (gcnew System::Windows::Forms::Button());
this->Fire_BTN = (gcnew System::Windows::Forms::Button());
this->Player_PB = (gcnew System::Windows::Forms::PictureBox());
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
this->label1 = (gcnew System::Windows::Forms::Label());
this->Points_LB = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->Lifes_LB = (gcnew System::Windows::Forms::Label());
this->Level_LB = (gcnew System::Windows::Forms::Label());
this->label4 = (gcnew System::Windows::Forms::Label());
this->LimitV_LB = (gcnew System::Windows::Forms::Label());
this->LimitH_LB = (gcnew System::Windows::Forms::Label());
this->username_LB = (gcnew System::Windows::Forms::Label());
this->label5 = (gcnew System::Windows::Forms::Label());
this->hscore_LB = (gcnew System::Windows::Forms::Label());
this->label7 = (gcnew System::Windows::Forms::Label());
this->scrbrd_BTN = (gcnew System::Windows::Forms::Button());
this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->Player_PB))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->BeginInit();
this->SuspendLayout();
//
// Exit_BTN
//
this->Exit_BTN->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->Exit_BTN->FlatAppearance->MouseDownBackColor = System::Drawing::Color::Purple;
this->Exit_BTN->FlatAppearance->MouseOverBackColor = System::Drawing::Color::Navy;
this->Exit_BTN->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->Exit_BTN->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Exit_BTN->Location = System::Drawing::Point(800, 450);
this->Exit_BTN->Name = L"Exit_BTN";
this->Exit_BTN->Size = System::Drawing::Size(131, 35);
this->Exit_BTN->TabIndex = 0;
this->Exit_BTN->TabStop = false;
this->Exit_BTN->Tag = L"15";
this->Exit_BTN->Text = L"EXIT";
this->Exit_BTN->UseVisualStyleBackColor = true;
this->Exit_BTN->Click += gcnew System::EventHandler(this, &FormJogo::Exit_BTN_Click);
//
// timer1
//
this->timer1->Tick += gcnew System::EventHandler(this, &FormJogo::Game_Loop);
//
// Start_BTN
//
this->Start_BTN->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->Start_BTN->BackColor = System::Drawing::Color::Lime;
this->Start_BTN->CausesValidation = false;
this->Start_BTN->FlatAppearance->MouseDownBackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(128)),
static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(128)));
this->Start_BTN->FlatAppearance->MouseOverBackColor = System::Drawing::Color::LimeGreen;
this->Start_BTN->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->Start_BTN->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Start_BTN->Location = System::Drawing::Point(800, 262);
this->Start_BTN->Name = L"Start_BTN";
this->Start_BTN->RightToLeft = System::Windows::Forms::RightToLeft::No;
this->Start_BTN->Size = System::Drawing::Size(131, 35);
this->Start_BTN->TabIndex = 0;
this->Start_BTN->Tag = L"15";
this->Start_BTN->Text = L"Start Game";
this->Start_BTN->UseVisualStyleBackColor = false;
this->Start_BTN->Click += gcnew System::EventHandler(this, &FormJogo::Start_BTN_click);
//
// Stop_BTN
//
this->Stop_BTN->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->Stop_BTN->BackColor = System::Drawing::Color::Red;
this->Stop_BTN->Enabled = false;
this->Stop_BTN->FlatAppearance->MouseDownBackColor = System::Drawing::Color::Salmon;
this->Stop_BTN->FlatAppearance->MouseOverBackColor = System::Drawing::Color::DarkRed;
this->Stop_BTN->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->Stop_BTN->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Stop_BTN->Location = System::Drawing::Point(800, 303);
this->Stop_BTN->Name = L"Stop_BTN";
this->Stop_BTN->Size = System::Drawing::Size(131, 37);
this->Stop_BTN->TabIndex = 0;
this->Stop_BTN->Tag = L"15";
this->Stop_BTN->Text = L"Stop Game";
this->Stop_BTN->UseVisualStyleBackColor = false;
this->Stop_BTN->Click += gcnew System::EventHandler(this, &FormJogo::Stop_BTN_Click);
//
// Fire_BTN
//
this->Fire_BTN->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->Fire_BTN->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)), static_cast<System::Int32>(static_cast<System::Byte>(128)),
static_cast<System::Int32>(static_cast<System::Byte>(0)));
this->Fire_BTN->FlatAppearance->MouseDownBackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(255)),
static_cast<System::Int32>(static_cast<System::Byte>(192)), static_cast<System::Int32>(static_cast<System::Byte>(128)));
this->Fire_BTN->FlatAppearance->MouseOverBackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(192)),
static_cast<System::Int32>(static_cast<System::Byte>(64)), static_cast<System::Int32>(static_cast<System::Byte>(0)));
this->Fire_BTN->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->Fire_BTN->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Fire_BTN->Location = System::Drawing::Point(800, 346);
this->Fire_BTN->Name = L"Fire_BTN";
this->Fire_BTN->Size = System::Drawing::Size(131, 35);
this->Fire_BTN->TabIndex = 0;
this->Fire_BTN->TabStop = false;
this->Fire_BTN->Tag = L"15";
this->Fire_BTN->Text = L"FIRE";
this->Fire_BTN->UseVisualStyleBackColor = false;
this->Fire_BTN->Click += gcnew System::EventHandler(this, &FormJogo::Fire_BTN_Click);
//
// Player_PB
//
this->Player_PB->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
this->Player_PB->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"Player_PB.Image")));
this->Player_PB->Location = System::Drawing::Point(285, 262);
this->Player_PB->Name = L"Player_PB";
this->Player_PB->Size = System::Drawing::Size(55, 75);
this->Player_PB->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->Player_PB->TabIndex = 17;
this->Player_PB->TabStop = false;
//
// listBox1
//
this->listBox1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->listBox1->CausesValidation = false;
this->listBox1->FormattingEnabled = true;
this->listBox1->Location = System::Drawing::Point(737, 468);
this->listBox1->Name = L"listBox1";
this->listBox1->Size = System::Drawing::Size(54, 17);
this->listBox1->TabIndex = 1;
//
// label1
//
this->label1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->label1->AutoSize = true;
this->label1->BackColor = System::Drawing::Color::Transparent;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label1->ForeColor = System::Drawing::Color::Yellow;
this->label1->Location = System::Drawing::Point(685, 93);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(98, 25);
this->label1->TabIndex = 18;
this->label1->Text = L"SCORE:";
//
// Points_LB
//
this->Points_LB->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->Points_LB->BackColor = System::Drawing::Color::Transparent;
this->Points_LB->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Points_LB->ForeColor = System::Drawing::SystemColors::ButtonHighlight;
this->Points_LB->Location = System::Drawing::Point(789, 93);
this->Points_LB->Name = L"Points_LB";
this->Points_LB->Size = System::Drawing::Size(132, 25);
this->Points_LB->TabIndex = 19;
//
// label2
//
this->label2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->label2->AutoSize = true;
this->label2->BackColor = System::Drawing::Color::Transparent;
this->label2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label2->ForeColor = System::Drawing::Color::Yellow;
this->label2->Location = System::Drawing::Point(685, 118);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(82, 25);
this->label2->TabIndex = 20;
this->label2->Text = L"LIFES:";
//
// Lifes_LB
//
this->Lifes_LB->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->Lifes_LB->BackColor = System::Drawing::Color::Transparent;
this->Lifes_LB->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Lifes_LB->ForeColor = System::Drawing::Color::DarkRed;
this->Lifes_LB->Location = System::Drawing::Point(773, 120);
this->Lifes_LB->Name = L"Lifes_LB";
this->Lifes_LB->Size = System::Drawing::Size(148, 23);
this->Lifes_LB->TabIndex = 21;
//
// Level_LB
//
this->Level_LB->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->Level_LB->BackColor = System::Drawing::Color::Transparent;
this->Level_LB->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->Level_LB->ForeColor = System::Drawing::SystemColors::ButtonHighlight;
this->Level_LB->Location = System::Drawing::Point(781, 68);
this->Level_LB->Name = L"Level_LB";
this->Level_LB->Size = System::Drawing::Size(140, 25);
this->Level_LB->TabIndex = 23;
//
// label4
//
this->label4->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->label4->AutoSize = true;
this->label4->BackColor = System::Drawing::Color::Transparent;
this->label4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label4->ForeColor = System::Drawing::Color::Yellow;
this->label4->Location = System::Drawing::Point(685, 68);
this->label4->Name = L"label4";
this->label4->Size = System::Drawing::Size(90, 25);
this->label4->TabIndex = 22;
this->label4->Text = L"LEVEL:";
//
// LimitV_LB
//
this->LimitV_LB->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(167)), static_cast<System::Int32>(static_cast<System::Byte>(167)),
static_cast<System::Int32>(static_cast<System::Byte>(167)));
this->LimitV_LB->Location = System::Drawing::Point(640, 0);
this->LimitV_LB->Name = L"LimitV_LB";
this->LimitV_LB->Size = System::Drawing::Size(20, 109);
this->LimitV_LB->TabIndex = 24;
//
// LimitH_LB
//
this->LimitH_LB->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(167)), static_cast<System::Int32>(static_cast<System::Byte>(167)),
static_cast<System::Int32>(static_cast<System::Byte>(167)));
this->LimitH_LB->Location = System::Drawing::Point(0, 480);
this->LimitH_LB->Name = L"LimitH_LB";
this->LimitH_LB->Size = System::Drawing::Size(260, 20);
this->LimitH_LB->TabIndex = 25;
//
// username_LB
//
this->username_LB->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->username_LB->BackColor = System::Drawing::Color::Transparent;
this->username_LB->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->username_LB->ForeColor = System::Drawing::SystemColors::ButtonHighlight;
this->username_LB->Location = System::Drawing::Point(768, 5);
this->username_LB->Name = L"username_LB";
this->username_LB->Size = System::Drawing::Size(153, 25);
this->username_LB->TabIndex = 27;
//
// label5
//
this->label5->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->label5->AutoSize = true;
this->label5->BackColor = System::Drawing::Color::Transparent;
this->label5->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label5->ForeColor = System::Drawing::Color::Yellow;
this->label5->Location = System::Drawing::Point(686, 5);
this->label5->Name = L"label5";
this->label5->Size = System::Drawing::Size(81, 25);
this->label5->TabIndex = 26;
this->label5->Text = L"USER:";
//
// hscore_LB
//
this->hscore_LB->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->hscore_LB->BackColor = System::Drawing::Color::Transparent;
this->hscore_LB->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->hscore_LB->ForeColor = System::Drawing::SystemColors::ButtonHighlight;
this->hscore_LB->Location = System::Drawing::Point(819, 30);
this->hscore_LB->Name = L"hscore_LB";
this->hscore_LB->Size = System::Drawing::Size(102, 25);
this->hscore_LB->TabIndex = 29;
//
// label7
//
this->label7->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Right));
this->label7->AutoSize = true;
this->label7->BackColor = System::Drawing::Color::Transparent;
this->label7->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->label7->ForeColor = System::Drawing::Color::Yellow;
this->label7->Location = System::Drawing::Point(685, 30);
this->label7->Name = L"label7";
this->label7->Size = System::Drawing::Size(128, 25);
this->label7->TabIndex = 28;
this->label7->Text = L"H. SCORE:";
//
// scrbrd_BTN
//
this->scrbrd_BTN->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right));
this->scrbrd_BTN->BackColor = System::Drawing::Color::Navy;
this->scrbrd_BTN->FlatAppearance->MouseDownBackColor = System::Drawing::Color::DodgerBlue;
this->scrbrd_BTN->FlatAppearance->MouseOverBackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(128)),
static_cast<System::Int32>(static_cast<System::Byte>(128)), static_cast<System::Int32>(static_cast<System::Byte>(255)));
this->scrbrd_BTN->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->scrbrd_BTN->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->scrbrd_BTN->ForeColor = System::Drawing::Color::White;
this->scrbrd_BTN->Location = System::Drawing::Point(800, 409);
this->scrbrd_BTN->Name = L"scrbrd_BTN";
this->scrbrd_BTN->Size = System::Drawing::Size(131, 35);
this->scrbrd_BTN->TabIndex = 30;
this->scrbrd_BTN->TabStop = false;
this->scrbrd_BTN->Tag = L"15";
this->scrbrd_BTN->Text = L"SCORE BOARD";
this->scrbrd_BTN->UseVisualStyleBackColor = false;
this->scrbrd_BTN->Click += gcnew System::EventHandler(this, &FormJogo::scrbrd_BTN_Click);
//
// pictureBox1
//
this->pictureBox1->BackColor = System::Drawing::Color::Transparent;
this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox1.Image")));
this->pictureBox1->Location = System::Drawing::Point(690, 156);
this->pictureBox1->Name = L"pictureBox1";
this->pictureBox1->Size = System::Drawing::Size(230, 100);
this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::AutoSize;
this->pictureBox1->TabIndex = 31;
this->pictureBox1->TabStop = false;
//
// FormJogo
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::AppWorkspace;
this->BackgroundImage = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"$this.BackgroundImage")));
this->ClientSize = System::Drawing::Size(938, 501);
this->Controls->Add(this->pictureBox1);
this->Controls->Add(this->scrbrd_BTN);
this->Controls->Add(this->hscore_LB);
this->Controls->Add(this->label7);
this->Controls->Add(this->username_LB);
this->Controls->Add(this->label5);
this->Controls->Add(this->LimitH_LB);
this->Controls->Add(this->LimitV_LB);
this->Controls->Add(this->Level_LB);
this->Controls->Add(this->label4);
this->Controls->Add(this->Lifes_LB);
this->Controls->Add(this->label2);
this->Controls->Add(this->Points_LB);
this->Controls->Add(this->label1);
this->Controls->Add(this->listBox1);
this->Controls->Add(this->Player_PB);
this->Controls->Add(this->Fire_BTN);
this->Controls->Add(this->Stop_BTN);
this->Controls->Add(this->Start_BTN);
this->Controls->Add(this->Exit_BTN);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon")));
this->KeyPreview = true;
this->MaximizeBox = false;
this->MaximumSize = System::Drawing::Size(1036, 544);
this->Name = L"FormJogo";
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"MMInvaders BetaV1 by: Diogos and Mariana";
this->Load += gcnew System::EventHandler(this, &FormJogo::FormJogo_Load);
this->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &FormJogo::FormJogo_KeyDown);
this->KeyUp += gcnew System::Windows::Forms::KeyEventHandler(this, &FormJogo::FormJogo_KeyUp);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->Player_PB))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void Exit_BTN_Click(System::Object^ sender, System::EventArgs^ e) {
// Ver https://www.youtube.com/watch?v=U14ZpnAmoXg
Close();
}
private: System::Void FormJogo_Load(System::Object^ sender, System::EventArgs^ e)
{
cout << "A Aguardar Login" << endl;
FormLogin ^MarianaEMachado =gcnew FormLogin(GMorg);
MarianaEMachado->ShowDialog();
GMorg->EscreveUtilizadoresFicheiro();//escrever as alteracoes feitas;
cout << "Login Feito" << endl;
}
private: System::Void Start_BTN_click(System::Object^ sender, System::EventArgs^ e)
{
//COMECA O JOGO
cout << "Start Game" << endl;
//troca os botoes activos
Start_BTN->Enabled=false;
Stop_BTN->Enabled=true;
Fire_BTN->Enabled=true;
//Perguntar que nivel deseja carregar
int *nivel = new int;
*nivel = 1;
IntDados ^F = gcnew IntDados(nivel,GMorg->GetTotalNiveis());
if (F->ShowDialog() == Windows::Forms::DialogResult::OK){
PrepararNivel(*nivel);
}
else{
PrepararNivel(NULL);
}
delete nivel;
GMorg->ResetJogador();
listBox1->Select();
EstadoDoJogo = Est_Correr;
timer1->Start();
timer1->Interval = 2;
}
private: System::Void Stop_BTN_Click(System::Object^ sender, System::EventArgs^ e)
{
//Parar o jogo
cout << "Stop Game" << endl;
timer1->Stop();
//troca os botoes activos
Stop_BTN->Enabled=false;
Fire_BTN->Enabled=false;
Start_BTN->Enabled=true;
EstadoDoJogo = Est_Parado;
for (int i = 0; i < ListPBTiros->Count; i++)
Controls->Remove(ListPBTiros[i]);
ListPBTiros->Clear();
for (int i = 0; i < ListPBInimigos->Count; i++)
Controls->Remove(ListPBInimigos[i]);
ListPBInimigos->Clear();
}
private: System::Void Game_Loop(System::Object^ sender, System::EventArgs^ e)
{
if(EstadoDoJogo == Est_Correr){
this->SuspendLayout();//pausa o processamento do layout enquanto preparamos o proximo frame
//Logic---------------------------------------------------------------------
//verifica se ainda existe algum inimigo vivo
if( !VerificarFimNivel(sender, e)){
DeslocaJogador();//desloca o jogador
if (disparaJogador)
{
Fire_BTN_Click(sender,e);
disparaJogador = 0;
}
DeslocaTiros();//desloca os tiros, verifica as colisoes e dispara um tiro dos inimigos se for altura
DeslocaInimigos();//deslocar os inimigos
ControlaBoca();//Caso seja o nivel do boss controla a boca
}
//Rendering---------------------------------------------------------------------
DesenhaJogador();
DesenhaTiros();
DesenhaInimigos();
ActualizarDados(); //actualiza a info nas labels
this->PerformLayout();//mostra o frame novo
}
}
private: System::Void PrepararNivel(int _nivel) {
//manda o gestor preparar o nivel, cria os inimigos na parte grafica
GMorg->PrepararNivel(_nivel);
if(GMorg->GetNivel() != GMorg->GetTotalNiveis()){
for (int i = 0; i < GMorg->GetIDUltInimigo(); i++)
{
CriarInimigo(i+1); //i+1 porque nao comecamos no 0
}
}
else
{
CriarBoss();
}
int x,y;
GMorg->GetPosJogador(x,y);
Player_PB->Location = System::Drawing::Point(x,y);
}
private: System::Void Fire_BTN_Click(System::Object^ sender, System::EventArgs^ e) {
//quando é carregado o botao de disparo
if(EstadoDoJogo == Est_Correr){
CriarTiro(TiroJogador);
}
}
private: System::Void CriarTiro(int _tipo) {
//cada PB tem como nome o id do tiro correspondente
int id = GMorg->CriarTiro(_tipo);
int x=0, y=0;
if(id == -1){ //falhou criar o tiro nogestor, ou atingiu limite
Console::WriteLine("[ERRO]falhou criar tiro, limite atingido?");
return;
}
PictureBox ^PB = gcnew PictureBox();
PB->Image = ListaImgTiros->Images[TiroImag++];
if(TiroImag > 5)//reiniciar o loop de imagens
TiroImag = 0;
GMorg->GetPosTiro(id, x, y);
PB->Location = Drawing::Point(x,y);
PB->Name = id.ToString(); //https://social.msdn.microsoft.com/Forums/vstudio/en-US/d55e67ff-1ae5-44fd-8627-c7373a15d4b3/
PB->Size = System::Drawing::Size(TiroSize_W, TiroSize_H);
PB->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
PB->BackColor = Drawing::Color::Transparent;
PB->TabStop = false;
PB->Visible = true;
//adicionar as PB nas listas
Controls->Add(PB);
ListPBTiros->Add(PB);
//Ficar á frente a imagem
PB->BringToFront();
UpdateZOrder();
}
private: System::Void CriarInimigo(int _id) {
//alocar nova PB, e sincroniza com o inimigo no gestor
PictureBox ^PB = gcnew PictureBox();
PB->Image = ListaImgInimigos->Images[GMorg->GetTipoInimigo(_id)];//ir buscar a imagem correspondente ao tipo
int x=0,y=0;
GMorg->GetPosInimigo(_id,x,y);
PB->Location = Drawing::Point(x,y);
PB->Name = _id.ToString();
PB->Size = System::Drawing::Size(InimigoSize_W, InimigoSize_H);
PB->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
//PB->SizeMode = System::Windows::Forms::PictureBoxSizeMode::AutoSize;
PB->TabStop = false;
PB->Visible = true;
PB->BackColor = Drawing::Color::Transparent;
Controls->Add(PB);
ListPBInimigos->Add(PB);
//Trazer para a frente a Imagem
PB->BringToFront();
UpdateZOrder();
}
private: System::Void CriarBoss() {
//alocar nova PB, e sincroniza com o inimigo no gestor
PictureBox ^PBHead = gcnew PictureBox();
PictureBox ^PBBoca = gcnew PictureBox();
PBHead->Image = ImgBossHead;
PBBoca->Image = ImgBossBoca;
int x=0,y=0;
GMorg->GetPosInimigo(1,x,y);
PBHead->Location = Drawing::Point(x,y);
PBHead->Name = "1";
PBHead->Size = System::Drawing::Size(BossSizeInit_W, BossSizeInit_H);
PBHead->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
PBHead->Visible = true;
PBHead->BackColor = Drawing::Color::Transparent;
float ratioW = (float)BossSizeInit_W/(float)BossSizeFinal_W;
float ratioH = (float)BossSizeInit_H/(float)BossSizeFinal_H;
int bocax = x+ (int)((float)BossBoca_X * ratioW);
int bocay= y+ (int)((float)BossBoca_Y * ratioH);
PBBoca->Location = Drawing::Point(bocax , bocay ); //80 230 no max!
PBBoca->Size = System::Drawing::Size((int)((float)BossBoca_W*(ratioW)), (int)((float)BossBoca_H*(ratioH)));
PBBoca->Name = "0";
//PBBoca->Size = System::Drawing::Size(BossBoca_W, BossBoca_H);
//PBBoca->Location = Drawing::Point( x, y);
PBBoca->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
PBBoca->Visible = true;
//PBBoca->BackColor = Drawing::Color::Transparent;
Controls->Add(PBHead);
ListPBInimigos->Add(PBHead);
Controls->Add(PBBoca);
ListPBInimigos->Add(PBBoca);
//Trazer para a frente a Imagem
PBHead->BringToFront();
UpdateZOrder();
PBBoca->BringToFront();
UpdateZOrder();
}
private: System::Void FormJogo_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
switch (e->KeyCode)
{
case(Keys::A):{//mexe esquerda
if(ImagemJogador<2) //se tiver uma imagem da direcao diferente
ImagemJogador = 2;
if(ContarMudaImagemJogador==0 ){
if(ImagemJogador==2 || ImagemJogador<2)//se tiver na imagem 2
ImagemJogador = 3;
else
ImagemJogador = 2;
ContarMudaImagemJogador=TimerMudaImagemJogador;
}
else
ContarMudaImagemJogador--;
moverJogador = MovEsq;//activa a variavel de direcao com a direccao em que se desloca o jogador
break;}
case(Keys::D):{//mexe direita
if(ImagemJogador>1) //se tiver uma imagem da direcao diferente
ImagemJogador = 1;
if(ContarMudaImagemJogador==0){
if(ImagemJogador==0)//se tiver na imagem 0
ImagemJogador = 1;
else
ImagemJogador = 0;
ContarMudaImagemJogador=TimerMudaImagemJogador;
}
else
ContarMudaImagemJogador--;
moverJogador = MovDir;//activa a variavel de direcao com a direccao em que se desloca o jogador
break;}
case(Keys::Space):{
listBox1->Select();//seleciona a lb para nao activar nenhum botao
disparaJogador = 1;//activa a variavel de disparo
//Fire_BTN_Click(sender,e);
break;}
default:
break;
}
}
private: System::Void FormJogo_KeyUp(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
switch (e->KeyCode)
{
case(Keys::A):{
moverJogador = MovSTOP;//parou de carregar a tecla, coloca a 0
break;}
case(Keys::D):{
moverJogador = MovSTOP;
break;}
case(Keys::Space):{
listBox1->Select();
disparaJogador = 0;
}
default:
break;
}
}
private: String ^ConverterstringToString(string &s){
return gcnew String(s.c_str());
}
private: void addImage(ImageList ^ListaAUsar,String^ imageToLoad)
{
//carregar uma imagem e coloca na lista a usar
if (imageToLoad != "")
ListaAUsar->Images->Add(Image::FromFile(imageToLoad));
}
private: bool VerificarFimNivel(System::Object^ sender, System::EventArgs^ e){//se o nivel tiver terminado retorna true e avanca um nivel
if(GMorg->VerificarFimNivel()){
cout << "Terminou o nivel" << endl;
for (int i = 0; i < ListPBTiros->Count; i++)
Controls->Remove(ListPBTiros[i]);
ListPBTiros->Clear();
for (int i = 0; i < ListPBInimigos->Count; i++)
Controls->Remove(ListPBInimigos[i]);
ListPBInimigos->Clear();
//MessageBox::Show("Uau, nivel completo");
if(GMorg->GetVidas() > 0){
if((GMorg->GetNivel()-1) != GMorg->GetTotalNiveis())//se nao for o ultimo
PrepararNivel(NULL);//avancar de nivel
else
{
Stop_BTN_Click(sender,e);
MessageBox::Show(" CONGRATS\nYOU COMPLETED THE GAME\n SCORE: "+GMorg->GetPoints());
}
}
else
{
Stop_BTN_Click(sender,e);
MessageBox::Show(" GAME OVER\n SCORE: "+GMorg->GetPoints());
}
return true;
}
return false;
}
private: void DeslocaJogador(){
//Verifica se esta a ser pedido para mover o jogador
if(moverJogador != 0){
GMorg->MexerJogador(moverJogador);
}
}
private: void DeslocaTiros(){//desloca os tiros e verifica as colisoes
int yBala = 0;
int xBala = 0;
PictureBox ^PBTemp=nullptr;
int IDBala;
//Verifica se existem balas disparadas
if(ListPBTiros->Count > 0){
for (int i = 0; i < ListPBTiros->Count; i++)
{
PBTemp = ListPBTiros[i];//optimizacao, em vez de ir ao array temos um ponteiro para a picturebox actual
IDBala = int::Parse(PBTemp->Name);
GMorg->GetPosTiro( IDBala , xBala , yBala);
//Verificar se a bala esta fora do ecra OU se colidiu com algum inimigo
if(yBala < 0-TiroSize_H || yBala > JogoSize_H-TiroSize_H || GMorg->VerificarColisoes(IDBala) )
{
//http://stackoverflow.com/questions/21471858/unable-to-dispose-and-remove-controls-from-control-list
ListPBTiros[i]->Visible = false;
Controls->Remove(PBTemp);
ListPBTiros->Remove(PBTemp);
GMorg->RemoverTiro( IDBala );
}
else{
GMorg->DeslocarTiro( IDBala ); //manda deslocar um tiro;
}
}
}
//verifica se é altura para disparar um tiro
if(ContarDispararTiroInimigo == 0){
CriarTiro(TiroInimigo);
ContarDispararTiroInimigo = TimerDispararTiroInimigo - RatioDificuldade*GMorg->GetNivel();//conforme o nivel diminuir o tempo entre disparos
}else
ContarDispararTiroInimigo--;
}
private: void DeslocaInimigos(){
if(ContarMexeInimigo==0){
GMorg->DeslocaInimigos();
ContarMexeInimigo=TimerMexeInimigo - RatioDificuldade*GMorg->GetNivel();//conforme o nivel diminuir o tempo entre disparos
}
else
ContarMexeInimigo--;
}
private: void ControlaBoca(){//Caso seja o nivel do boss controla a boca
if(GMorg->GetNivel()== GMorg->GetTotalNiveis()){
//aberta 1, fechada 0
if(GMorg->getEstadoBoca())
ContarFechaBoca--;
else
ContarAbreBoca--;
if(ContarAbreBoca== 0){
GMorg->controlaBoca(Aberta);
srand(3525656);
ContarAbreBoca=TimerAbreBoca - 10+rand() % 200;//calcula um tempo aleatorio para abrir a boca
cout << "Vai Fechar daqui a " << ContarAbreBoca << endl;
}
if(ContarFechaBoca== 0){
GMorg->controlaBoca(Fechada);
ContarFechaBoca=TimerFechaBoca;
cout << "Vai Abrir daqui a " << ContarFechaBoca << endl;
}
}
}
private: void DesenhaJogador(){//verifica se o jogador foi mexido e actualiza a posicao
int x = 0, y =0;
GMorg->GetPosJogador(x,y);
Player_PB->Location = Drawing::Point(x,y);
Player_PB->Image = ListaImgJogador->Images[ImagemJogador];//actualiza a imagem com a direccao que esta a ir o jogador
}
private: void DesenhaTiros(){
//Deslocar as balas
int yBala = 0;
int xBala = 0;
int IDBala;
PictureBox ^PBTemp=nullptr;
if(ListPBTiros->Count > 0){
for (int i = 0; i < ListPBTiros->Count; i++)
{
PBTemp = ListPBTiros[i];//optimizacao, em vez de ir ao array temos um ponteiro para a picturebox actual
IDBala = int::Parse(PBTemp->Name);
GMorg->GetPosTiro( IDBala , xBala , yBala);
PBTemp->Location = System::Drawing::Point(xBala,yBala); //actualizar a posicao da bala na parte grafica
}
}
}
private: void DesenhaInimigos(){
//Mudar a imagem dos inimigos de acordo com a sua vida
//se tiver morto iniciar a decrementar o decay cada vez que passa por aqui o programa
int IniX,IniY;
if(ListPBInimigos->Count > 0){
if(GMorg->GetNivel() != GMorg->GetTotalNiveis()){//se nao tiver no nivel do boss
PictureBox ^PBTemp2=nullptr;
for (int i = 0; i < ListPBInimigos->Count; i++)
{
PBTemp2 = ListPBInimigos[i];
int IDInimigo = int::Parse(PBTemp2->Name);
int imagem = GMorg->GetVidaInimigo(IDInimigo);
if(imagem > 0){
PBTemp2->Image = ListaImgInimigos->Images[imagem];
GMorg->GetPosInimigo(IDInimigo,IniX,IniY);
PBTemp2->Location = System::Drawing::Point(IniX,IniY);
}
else
{
if(GMorg->getDecayInimigo(IDInimigo) > 0 && PBTemp2->Visible){
PBTemp2->Image = ListaImgInimigos->Images[imagem];
GMorg->ReduzDecayInimigo(IDInimigo);
}
else if(PBTemp2->Visible)
{
PBTemp2->Visible = false;
}
}
}
}
else{//NIVEL BOSS!!!!!!!!!!!!!!!!!!!
int sizeW,sizeH;
int x,y;
GMorg->GetSizeInimigo(sizeW,sizeH);
GMorg->GetPosInimigo(1,x,y);//obter a posicao do inimigo
ListPBInimigos[0]->Location = Drawing::Point(x , y ); //posiciona a cabeca
ListPBInimigos[0]->Size = System::Drawing::Size(sizeW ,sizeH); //coloca o tamanho da cabeca
//calcula o tamanho da boca
float ratioW = (float)sizeW/(float)BossSizeFinal_W;
float ratioH = (float)sizeH/(float)BossSizeFinal_H;
int bocax = x+ (int)((float)BossBoca_X * ratioW);
int bocay= y+ (int)((float)BossBoca_Y * ratioH);
if(GMorg->getEstadoBoca()){//posiciona a boca em estado aberto ou fechado
bocay += (int)((float)BossBoca_H*(ratioH));
}
ListPBInimigos[1]->Location = Drawing::Point(bocax , bocay ); //posiciona a boca
ListPBInimigos[1]->Size = System::Drawing::Size((int)((float)BossBoca_W*(ratioW)), (int)((float)BossBoca_H*(ratioH)));//coloca o tamanho da boca
}
}
}
private: void ActualizarDados(){
if(ContarActualizaDados == 0){
//Escrever nas labels os pontos, vida e nivel actual
String ^points = Convert::ToString(GMorg->GetPoints());
Points_LB->Text = points;
String ^lifes = Convert::ToString(GMorg->GetVidas());
Lifes_LB->Text = lifes;
String ^level = Convert::ToString(GMorg->GetNivel());
Level_LB->Text = level;
String ^username = ConverterstringToString(GMorg->GetUserName());
username_LB->Text = username;
String ^HScore = Convert::ToString(GMorg->GetHScore());
hscore_LB->Text = HScore;
ContarActualizaDados = TimerActualizaDados;
}
else
ContarActualizaDados--;
}
private: System::Void scrbrd_BTN_Click(System::Object^ sender, System::EventArgs^ e) {
FormTabela ^Tabela = gcnew FormTabela(GMorg);
if (Tabela->ShowDialog() == Windows::Forms::DialogResult::OK){
//scrbrd_BTN->DialogResult
}
}
};
}
| [
"[email protected]"
] | |
b70de15e200ceba423618b93c985a5031678bca5 | ec19482fad5f57c63902fea59fa2267ef506bf10 | /NtupleVariables/include/Electron.h | b8dcf322205a0b320eff5dc528dffc096cb41c8c | [] | no_license | vshang/SFrame | 9643a093aa0320fdef69c1d1b31d2d2f396df441 | 72627ed279ffc15a33ef8be0907357e61cbb3475 | refs/heads/master | 2020-07-03T06:00:50.654050 | 2019-09-01T19:23:48 | 2019-09-01T19:23:48 | 200,679,865 | 0 | 0 | null | 2019-08-05T15:15:38 | 2019-08-05T15:15:38 | null | UTF-8 | C++ | false | false | 19,433 | h |
// THIS FILE HAS BEEN GENERATED AUTOMATICALLY. DO NOT EDIT DIRECTLY, CHANGES WILL BE LOST UPON NEXT CODE GENERATION.
// Code produced by Id: CodeIt.py 494 2010-07-30 13:41:32Z svn
#ifndef __UZHTOP_Electron_H__
#define __UZHTOP_Electron_H__
#include <cmath>
#include "Particle.h"
#include <vector>
#include "ElectronNtupleObject.h"
namespace Ntuple {
class ElectronNtupleObject;
}
namespace UZH {
/**
* @short Class that maps ElectronNtupleObjects to Electron Particle class
*
* This class can be used to map the offline Electron information from
* ElectronNtupleObjects to UZH::Electron class. All particles inherit
* from UZH::Particle.
*
* @author Code produced by Id: CodeIt.py 494 2010-07-30 13:41:32Z svn
*
*/
class Electron : public Basic
, public Particle
{
public:
/// default c'tor
Electron();
/// default d'tor
~Electron();
/// c'tor with index
Electron( const Ntuple::ElectronNtupleObject* ana, const Int_t idx );
TLorentzVector* getTLV() const;
TLorentzVector tlv() const;
// variable definitions
int* m_passConversionVeto;
floatingnumber* m_full5x5_sigmaIetaIeta;
floatingnumber* m_full5x5_r9;
floatingnumber* m_dEtaIn;
floatingnumber* m_dPhiIn;
floatingnumber* m_hOverE;
floatingnumber* m_relIsoWithDBeta;
floatingnumber* m_ooEmooP;
int* m_expectedMissingInnerHits;
floatingnumber* m_d0;
floatingnumber* m_dz;
floatingnumber* m_dr03EcalRecHitSumEt;
floatingnumber* m_dr03HcalDepth1TowerSumEt;
floatingnumber* m_rho;
bool m_ecalDriven;
floatingnumber* m_dEtaInSeed;
floatingnumber* m_full5x5_e2x5Max;
floatingnumber* m_full5x5_e5x5;
floatingnumber* m_full5x5_e1x5;
floatingnumber* m_dr03TkSumPt;
floatingnumber* m_hadronicOverEm;
int* m_pdgId;
floatingnumber* m_charge;
floatingnumber* m_et;
int* m_isVetoElectronBoosted;
int* m_isMediumElectronBoosted;
int* m_isTightElectronBoosted;
int* m_isHeepElectronBoosted;
int* m_isLooseElectronBoosted;
floatingnumber* m_pfRhoCorrRelIso03Boost;
floatingnumber* m_pfRhoCorrRelIso04Boost;
floatingnumber* m_pfDeltaCorrRelIsoBoost;
floatingnumber* m_pfRelIsoBoost;
floatingnumber* m_photonIsoBoost;
floatingnumber* m_neutralHadIsoBoost;
floatingnumber* m_chargedHadIsoBoost;
floatingnumber* m_SemileptonicPFIso;
floatingnumber* m_SemileptonicCorrPFIso;
int* m_isVetoElectron;
int* m_isMediumElectron;
int* m_isTightElectron;
int* m_isHeepElectron;
int* m_isLooseElectron;
floatingnumber* m_pfRhoCorrRelIso03;
floatingnumber* m_pfRhoCorrRelIso04;
floatingnumber* m_pfDeltaCorrRelIso;
floatingnumber* m_pfRelIso;
floatingnumber* m_photonIso;
floatingnumber* m_neutralHadIso;
floatingnumber* m_chargedHadIso;
floatingnumber* m_trackIso;
floatingnumber* m_superCluster_eta;
floatingnumber* m_superCluster_e;
/// delta(R) function using the cluster eta/phi position of the electrons
// floatingnumber DeltaRcluster( const Particle* p ) const;
/// delta(R) function using the track eta/phi position of the electrons
// floatingnumber DeltaRtrack( const Particle* p ) const;
// check level given here must be consistent with ...NtupleObject.cxx, otherwise you'll get a segfault
int passConversionVeto() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpassConversionVeto)) std::cout<<"passConversionVeto not connected!"<<std::endl;*/ return *(m_passConversionVeto); }
floatingnumber full5x5_sigmaIetaIeta() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kfull5x5_sigmaIetaIeta)) std::cout<<"full5x5_sigmaIetaIeta not connected!"<<std::endl;*/ return *(m_full5x5_sigmaIetaIeta); }
floatingnumber full5x5_r9() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kfull5x5_r9)) std::cout<<"full5x5_r9 not connected!"<<std::endl;*/ return *(m_full5x5_r9); }
floatingnumber dEtaIn() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdEtaIn)) std::cout<<"dEtaIn not connected!"<<std::endl;*/ return *(m_dEtaIn); }
floatingnumber dPhiIn() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdPhiIn)) std::cout<<"dPhiIn not connected!"<<std::endl;*/ return *(m_dPhiIn); }
floatingnumber hOverE() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::khOverE)) std::cout<<"hOverE not connected!"<<std::endl;*/ return *(m_hOverE); }
floatingnumber relIsoWithDBeta() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::krelIsoWithDBeta)) std::cout<<"relIsoWithDBeta not connected!"<<std::endl;*/ return *(m_relIsoWithDBeta); }
floatingnumber ooEmooP() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kooEmooP)) std::cout<<"ooEmooP not connected!"<<std::endl;*/ return *(m_ooEmooP); }
int expectedMissingInnerHits() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kexpectedMissingInnerHits)) std::cout<<"expectedMissingInnerHits not connected!"<<std::endl;*/ return *(m_expectedMissingInnerHits); }
floatingnumber d0() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kd0)) std::cout<<"d0 not connected!"<<std::endl;*/ return *(m_d0); }
floatingnumber dz() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdz)) std::cout<<"dz not connected!"<<std::endl;*/ return *(m_dz); }
floatingnumber dr03EcalRecHitSumEt() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdr03EcalRecHitSumEt)) std::cout<<"dr03EcalRecHitSumEt not connected!"<<std::endl;*/ return *(m_dr03EcalRecHitSumEt); }
floatingnumber dr03HcalDepth1TowerSumEt() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdr03HcalDepth1TowerSumEt)) std::cout<<"dr03HcalDepth1TowerSumEt not connected!"<<std::endl;*/ return *(m_dr03HcalDepth1TowerSumEt); }
floatingnumber rho() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::krho)) std::cout<<"rho not connected!"<<std::endl;*/ return *(m_rho); }
bool ecalDriven() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kecalDriven)) std::cout<<"ecalDriven not connected!"<<std::endl;*/ return (m_ecalDriven); }
floatingnumber dEtaInSeed() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdEtaInSeed)) std::cout<<"dEtaInSeed not connected!"<<std::endl;*/ return *(m_dEtaInSeed); }
floatingnumber full5x5_e2x5Max() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kfull5x5_e2x5Max)) std::cout<<"full5x5_e2x5Max not connected!"<<std::endl;*/ return *(m_full5x5_e2x5Max); }
floatingnumber full5x5_e5x5() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kfull5x5_e5x5)) std::cout<<"full5x5_e5x5 not connected!"<<std::endl;*/ return *(m_full5x5_e5x5); }
floatingnumber full5x5_e1x5() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kfull5x5_e1x5)) std::cout<<"full5x5_e1x5 not connected!"<<std::endl;*/ return *(m_full5x5_e1x5); }
floatingnumber dr03TkSumPt() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kdr03TkSumPt)) std::cout<<"dr03TkSumPt not connected!"<<std::endl;*/ return *(m_dr03TkSumPt); }
floatingnumber hadronicOverEm() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::khadronicOverEm)) std::cout<<"hadronicOverEm not connected!"<<std::endl;*/ return *(m_hadronicOverEm); }
int pdgId() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpdgId)) std::cout<<"pdgId not connected!"<<std::endl;*/ return *(m_pdgId); }
floatingnumber charge() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kcharge)) std::cout<<"charge not connected!"<<std::endl;*/ return *(m_charge); }
floatingnumber et() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::ket)) std::cout<<"et not connected!"<<std::endl;*/ return *(m_et); }
int isVetoElectronBoosted() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisVetoElectronBoosted)) std::cout<<"isVetoElectronBoosted not connected!"<<std::endl;*/ return *(m_isVetoElectronBoosted); }
int isMediumElectronBoosted() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisMediumElectronBoosted)) std::cout<<"isMediumElectronBoosted not connected!"<<std::endl;*/ return *(m_isMediumElectronBoosted); }
int isTightElectronBoosted() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisTightElectronBoosted)) std::cout<<"isTightElectronBoosted not connected!"<<std::endl;*/ return *(m_isTightElectronBoosted); }
int isHeepElectronBoosted() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisHeepElectronBoosted)) std::cout<<"isHeepElectronBoosted not connected!"<<std::endl;*/ return *(m_isHeepElectronBoosted); }
int isLooseElectronBoosted() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisLooseElectronBoosted)) std::cout<<"isLooseElectronBoosted not connected!"<<std::endl;*/ return *(m_isLooseElectronBoosted); }
floatingnumber pfRhoCorrRelIso03Boost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfRhoCorrRelIso03Boost)) std::cout<<"pfRhoCorrRelIso03Boost not connected!"<<std::endl;*/ return *(m_pfRhoCorrRelIso03Boost); }
floatingnumber pfRhoCorrRelIso04Boost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfRhoCorrRelIso04Boost)) std::cout<<"pfRhoCorrRelIso04Boost not connected!"<<std::endl;*/ return *(m_pfRhoCorrRelIso04Boost); }
floatingnumber pfDeltaCorrRelIsoBoost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfDeltaCorrRelIsoBoost)) std::cout<<"pfDeltaCorrRelIsoBoost not connected!"<<std::endl;*/ return *(m_pfDeltaCorrRelIsoBoost); }
floatingnumber pfRelIsoBoost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfRelIsoBoost)) std::cout<<"pfRelIsoBoost not connected!"<<std::endl;*/ return *(m_pfRelIsoBoost); }
floatingnumber photonIsoBoost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kphotonIsoBoost)) std::cout<<"photonIsoBoost not connected!"<<std::endl;*/ return *(m_photonIsoBoost); }
floatingnumber neutralHadIsoBoost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kneutralHadIsoBoost)) std::cout<<"neutralHadIsoBoost not connected!"<<std::endl;*/ return *(m_neutralHadIsoBoost); }
floatingnumber chargedHadIsoBoost() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kchargedHadIsoBoost)) std::cout<<"chargedHadIsoBoost not connected!"<<std::endl;*/ return *(m_chargedHadIsoBoost); }
floatingnumber SemileptonicPFIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kSemileptonicPFIso)) std::cout<<"SemileptonicPFIso not connected!"<<std::endl;*/ return *(m_SemileptonicPFIso); }
floatingnumber SemileptonicCorrPFIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kSemileptonicCorrPFIso)) std::cout<<"SemileptonicCorrPFIso not connected!"<<std::endl;*/ return *(m_SemileptonicCorrPFIso); }
int isVetoElectron() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisVetoElectron)) std::cout<<"isVetoElectron not connected!"<<std::endl;*/ return *(m_isVetoElectron); }
int isMediumElectron() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisMediumElectron)) std::cout<<"isMediumElectron not connected!"<<std::endl;*/ return *(m_isMediumElectron); }
int isTightElectron() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisTightElectron)) std::cout<<"isTightElectron not connected!"<<std::endl;*/ return *(m_isTightElectron); }
int isHeepElectron() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisHeepElectron)) std::cout<<"isHeepElectron not connected!"<<std::endl;*/ return *(m_isHeepElectron); }
int isLooseElectron() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kisLooseElectron)) std::cout<<"isLooseElectron not connected!"<<std::endl;*/ return *(m_isLooseElectron); }
floatingnumber pfRhoCorrRelIso03() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfRhoCorrRelIso03)) std::cout<<"pfRhoCorrRelIso03 not connected!"<<std::endl;*/ return *(m_pfRhoCorrRelIso03); }
floatingnumber pfRhoCorrRelIso04() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfRhoCorrRelIso04)) std::cout<<"pfRhoCorrRelIso04 not connected!"<<std::endl;*/ return *(m_pfRhoCorrRelIso04); }
floatingnumber pfDeltaCorrRelIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfDeltaCorrRelIso)) std::cout<<"pfDeltaCorrRelIso not connected!"<<std::endl;*/ return *(m_pfDeltaCorrRelIso); }
floatingnumber pfRelIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kpfRelIso)) std::cout<<"pfRelIso not connected!"<<std::endl;*/ return *(m_pfRelIso); }
floatingnumber photonIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kphotonIso)) std::cout<<"photonIso not connected!"<<std::endl;*/ return *(m_photonIso); }
floatingnumber neutralHadIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kneutralHadIso)) std::cout<<"neutralHadIso not connected!"<<std::endl;*/ return *(m_neutralHadIso); }
floatingnumber chargedHadIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::kchargedHadIso)) std::cout<<"chargedHadIso not connected!"<<std::endl;*/ return *(m_chargedHadIso); }
floatingnumber trackIso() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::ktrackIso)) std::cout<<"trackIso not connected!"<<std::endl;*/ return *(m_trackIso); }
floatingnumber superCluster_eta() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::ksuperCluster_eta)) std::cout<<"superCluster_eta not connected!"<<std::endl;*/ return *(m_superCluster_eta); }
floatingnumber superCluster_e() const { /*if(!m_ana->getConnectSucceeded(Ntuple::ElectronNtupleObject::ksuperCluster_e)) std::cout<<"superCluster_e not connected!"<<std::endl;*/ return *(m_superCluster_e); }
void passConversionVeto( const int& val){ *(m_passConversionVeto)=val; }
void full5x5_sigmaIetaIeta( const floatingnumber& val){ *(m_full5x5_sigmaIetaIeta)=val; }
void full5x5_r9( const floatingnumber& val){ *(m_full5x5_r9)=val; }
void dEtaIn( const floatingnumber& val){ *(m_dEtaIn)=val; }
void dPhiIn( const floatingnumber& val){ *(m_dPhiIn)=val; }
void hOverE( const floatingnumber& val){ *(m_hOverE)=val; }
void relIsoWithDBeta( const floatingnumber& val){ *(m_relIsoWithDBeta)=val; }
void ooEmooP( const floatingnumber& val){ *(m_ooEmooP)=val; }
void expectedMissingInnerHits( const int& val){ *(m_expectedMissingInnerHits)=val; }
void d0( const floatingnumber& val){ *(m_d0)=val; }
void dz( const floatingnumber& val){ *(m_dz)=val; }
void dr03EcalRecHitSumEt( const floatingnumber& val){ *(m_dr03EcalRecHitSumEt)=val; }
void dr03HcalDepth1TowerSumEt( const floatingnumber& val){ *(m_dr03HcalDepth1TowerSumEt)=val; }
void rho( const floatingnumber& val){ *(m_rho)=val; }
void ecalDriven( const bool& val){ (m_ecalDriven)=val; }
void dEtaInSeed( const floatingnumber& val){ *(m_dEtaInSeed)=val; }
void full5x5_e2x5Max( const floatingnumber& val){ *(m_full5x5_e2x5Max)=val; }
void full5x5_e5x5( const floatingnumber& val){ *(m_full5x5_e5x5)=val; }
void full5x5_e1x5( const floatingnumber& val){ *(m_full5x5_e1x5)=val; }
void dr03TkSumPt( const floatingnumber& val){ *(m_dr03TkSumPt)=val; }
void hadronicOverEm( const floatingnumber& val){ *(m_hadronicOverEm)=val; }
void pdgId( const int& val){ *(m_pdgId)=val; }
void charge( const floatingnumber& val){ *(m_charge)=val; }
void et( const floatingnumber& val){ *(m_et)=val; }
void isVetoElectronBoosted( const int& val){ *(m_isVetoElectronBoosted)=val; }
void isMediumElectronBoosted( const int& val){ *(m_isMediumElectronBoosted)=val; }
void isTightElectronBoosted( const int& val){ *(m_isTightElectronBoosted)=val; }
void isHeepElectronBoosted( const int& val){ *(m_isHeepElectronBoosted)=val; }
void isLooseElectronBoosted( const int& val){ *(m_isLooseElectronBoosted)=val; }
void pfRhoCorrRelIso03Boost( const floatingnumber& val){ *(m_pfRhoCorrRelIso03Boost)=val; }
void pfRhoCorrRelIso04Boost( const floatingnumber& val){ *(m_pfRhoCorrRelIso04Boost)=val; }
void pfDeltaCorrRelIsoBoost( const floatingnumber& val){ *(m_pfDeltaCorrRelIsoBoost)=val; }
void pfRelIsoBoost( const floatingnumber& val){ *(m_pfRelIsoBoost)=val; }
void photonIsoBoost( const floatingnumber& val){ *(m_photonIsoBoost)=val; }
void neutralHadIsoBoost( const floatingnumber& val){ *(m_neutralHadIsoBoost)=val; }
void chargedHadIsoBoost( const floatingnumber& val){ *(m_chargedHadIsoBoost)=val; }
void SemileptonicPFIso( const floatingnumber& val){ *(m_SemileptonicPFIso)=val; }
void SemileptonicCorrPFIso( const floatingnumber& val){ *(m_SemileptonicCorrPFIso)=val; }
void isVetoElectron( const int& val){ *(m_isVetoElectron)=val; }
void isMediumElectron( const int& val){ *(m_isMediumElectron)=val; }
void isTightElectron( const int& val){ *(m_isTightElectron)=val; }
void isHeepElectron( const int& val){ *(m_isHeepElectron)=val; }
void isLooseElectron( const int& val){ *(m_isLooseElectron)=val; }
void pfRhoCorrRelIso03( const floatingnumber& val){ *(m_pfRhoCorrRelIso03)=val; }
void pfRhoCorrRelIso04( const floatingnumber& val){ *(m_pfRhoCorrRelIso04)=val; }
void pfDeltaCorrRelIso( const floatingnumber& val){ *(m_pfDeltaCorrRelIso)=val; }
void pfRelIso( const floatingnumber& val){ *(m_pfRelIso)=val; }
void photonIso( const floatingnumber& val){ *(m_photonIso)=val; }
void neutralHadIso( const floatingnumber& val){ *(m_neutralHadIso)=val; }
void chargedHadIso( const floatingnumber& val){ *(m_chargedHadIso)=val; }
void trackIso( const floatingnumber& val){ *(m_trackIso)=val; }
void superCluster_eta( const floatingnumber& val){ *(m_superCluster_eta)=val; }
void superCluster_e( const floatingnumber& val){ *(m_superCluster_e)=val; }
private:
const Ntuple::ElectronNtupleObject* m_ana;
}; // class Electron
typedef std::vector< Electron > ElectronVec;
typedef std::vector< Electron >::iterator ElectronVecIt;
typedef std::vector< Electron >::const_iterator ElectronVecConstIt;
/// sort Electrons by pT
bool operator<( const Electron& e1, const Electron& e2 );
/// function class to sort Electron vector contents by pT
class sortElectronPt {
public:
bool operator()( const Electron& e1,
const Electron& e2 );
};
} // end of namespace UZH
/// output stream operator overloaded for Electron objects
std::ostream& operator<<( std::ostream& out,
const UZH::Electron& rhs );
#endif //__UZH_Electron_H__
| [
"[email protected]"
] | |
d3b2514b0f6a94645643a3c70cccccd08d0c372c | 5fe54b2bd86a463c80bbff9177a36ae6b8d3d708 | /test/e2e/test_master/skia/src/core/SkTTopoSort.h | 7003f057aba524636ecd2d212c42c0969d809288 | [
"MIT"
] | permissive | quinzio/cppparser | 1e5d9ea6cd151eaafe4fbe43519ca55bdd2bef66 | 253c4a8d42c8600d0e173834d88cbe42a8347859 | refs/heads/master | 2020-12-20T09:29:38.366763 | 2020-01-14T19:12:27 | 2020-01-14T19:12:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,664 | h | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkTTopoSort_DEFINED
# define SkTTopoSort_DEFINED
# include "include/core/SkRefCnt.h"
# include "include/private/SkTArray.h"
# ifdef SK_DEBUG
template <typename T, typename Traits = T>
void SkTTopoSort_CheckAllUnmarked(const SkTArray<sk_sp<T>>& graph)
{
for (int i = 0; i < graph.count(); ++i)
{
SkASSERT(!Traits::IsTempMarked(graph[i].get()));
SkASSERT(!Traits::WasOutput(graph[i].get()));
}
}
template <typename T, typename Traits = T>
void SkTTopoSort_CleanExit(const SkTArray<sk_sp<T>>& graph)
{
for (int i = 0; i < graph.count(); ++i)
{
SkASSERT(!Traits::IsTempMarked(graph[i].get()));
SkASSERT(Traits::WasOutput(graph[i].get()));
}
}
# endif
// Recursively visit a node and all the other nodes it depends on.
// Return false if there is a loop.
template <typename T, typename Traits = T>
bool SkTTopoSort_Visit(T* node, SkTArray<sk_sp<T>>* result)
{
if (Traits::IsTempMarked(node))
{
// There is a loop.
return false;
}
// If the node under consideration has been already been output it means it
// (and all the nodes it depends on) are already in 'result'.
if (!Traits::WasOutput(node))
{
// This node hasn't been output yet. Recursively assess all the
// nodes it depends on outputing them first.
Traits::SetTempMark(node);
for (int i = 0; i < Traits::NumDependencies(node); ++i)
{
if (!SkTTopoSort_Visit<T, Traits>(Traits::Dependency(node, i), result))
{
return false;
}
}
Traits::Output(node, result->count());
Traits::ResetTempMark(node);
result->push_back(sk_ref_sp(node));
}
return true;
}
// Topologically sort the nodes in 'graph'. For this sort, when node 'i' depends
// on node 'j' it means node 'j' must appear in the result before node 'i'.
// A false return value means there was a loop and the contents of 'graph' will
// be in some arbitrary state.
//
// Traits requires:
// static void Output(T* t, int index) { ... } // 'index' is 't's position in the result
// static bool WasOutput(const T* t) { ... }
//
// static void SetTempMark(T* t) { ... } // transiently used during toposort
// static void ResetTempMark(T* t) { ... }
// static bool IsTempMarked(const T* t) { ... }
//
// static int NumDependencies(const T* t) { ... } // 't' will be output after all the other -
// static T* Dependency(T* t, int index) { ... } // nodes on which it depends
// We'll look on T for these by default, or you can pass a custom Traits type.
//
// TODO: potentially add a version that takes a seed node and just outputs that
// node and all the nodes on which it depends. This could be used to partially
// flush a GrRenderTask DAG.
template <typename T, typename Traits = T>
bool SkTTopoSort(SkTArray<sk_sp<T>>* graph)
{
SkTArray<sk_sp<T>> result;
# ifdef SK_DEBUG
SkTTopoSort_CheckAllUnmarked<T, Traits> (*graph);
# endif
result.reserve(graph->count());
for (int i = 0; i < graph->count(); ++i)
{
if (Traits::WasOutput((*graph)[i].get()))
{
// This node was depended on by some earlier node and has already
// been output
continue;
}
// Output this node after all the nodes it depends on have been output.
if (!SkTTopoSort_Visit<T, Traits>((*graph)[i].get(), &result))
{
return false;
}
}
SkASSERT(graph->count() == result.count());
graph->swap(result);
# ifdef SK_DEBUG
SkTTopoSort_CleanExit<T, Traits> (*graph);
# endif
return true;
}
#endif
| [
"[email protected]"
] | |
edaf34c36029d2cff6b69fef7b0b0bbb412057e1 | 070f1d1b5baba767367c092d02e6fb310b6902f9 | /data/maps/FourIsland_IcefallCave_IcebergChamber/scripts.inc | bbf28c0549406e63fe42d9723caa905430b581c3 | [] | no_license | CharlesAverill/pokefirered | f1450435f6f35d99c79defcca50dfb12ec12af5c | a2c2d216e6fb662b6fa1174f53e0408bc0cecab2 | refs/heads/main | 2023-02-24T15:22:11.467163 | 2021-02-04T02:10:04 | 2021-02-04T02:10:04 | 321,180,253 | 4 | 0 | null | 2021-01-07T01:56:17 | 2020-12-13T23:16:44 | C | UTF-8 | C++ | false | false | 2,752 | inc | FourIsland_IcefallCave_IcebergChamber_MapScripts::
map_script MAP_SCRIPT_ON_RESUME, FourIsland_IcefallCave_IcebergChamber_OnResume
map_script MAP_SCRIPT_ON_TRANSITION, FourIsland_IcefallCave_IcebergChamber_OnTransition
.byte 0
FourIsland_IcefallCave_IcebergChamber_OnResume:
call_if_set FLAG_SYS_SPECIAL_WILD_BATTLE, FourIsland_IcefallCave_IcebergChamber_TryRemoveRegice
end
FourIsland_IcefallCave_IcebergChamber_OnTransition::
call_if_set FLAG_FOUGHT_REGICE, FourIsland_IcefallCave_IcebergChamber_HideRegice
call_if_unset FLAG_FOUGHT_REGICE, FourIsland_IcefallCave_IcebergChamber_TryShowRegice
end
FourIsland_IcefallCave_IcebergChamber_HideRegice::
setvar VAR_TEMP_1, 1
setflag FLAG_HIDE_REGICE
return
FourIsland_IcefallCave_IcebergChamber_TryShowRegice::
setvar VAR_TEMP_1, 1
goto_if_set FLAG_REGICE_DISAPPEARED, EventScript_Return
setvar VAR_TEMP_1, 0
clearflag FLAG_HIDE_REGICE
return
FourIsland_IcefallCave_IcebergChamber_TryRemoveRegice::
specialvar VAR_RESULT, GetBattleOutcome
compare VAR_RESULT, B_OUTCOME_CAUGHT
goto_if_ne EventScript_Return
removeobject 1
return
FourIsland_IcefallCave_IcebergChamber_Initiate_Regice_Battle::
goto_if_questlog EventScript_ReleaseEnd
special QuestLog_CutRecording
lock
faceplayer
waitse
message FourIsland_IcefallCave_IcebergChamber_Statue_Text
waitmessage
delay 20
waitbuttonpress
playmoncry SPECIES_REGICE, 2
message FourIsland_IcefallCave_IcebergChamber_Text_Regice
waitmessage
waitmoncry
delay 20
playbgm MUS_ENCOUNTER_GYM_LEADER, 0
waitbuttonpress
setwildbattle SPECIES_REGICE, 80, ITEM_NONE
setflag FLAG_SYS_SPECIAL_WILD_BATTLE
special StartLegendaryBattle
waitstate
clearflag FLAG_SYS_SPECIAL_WILD_BATTLE
specialvar VAR_RESULT, GetBattleOutcome
compare VAR_RESULT, B_OUTCOME_WON
goto_if_eq FourIsland_IcefallCave_IcebergChamber_DefeatedRegice
compare VAR_RESULT, B_OUTCOME_RAN
goto_if_eq FourIsland_IcefallCave_IcebergChamber_RanFromRegice
compare VAR_RESULT, B_OUTCOME_PLAYER_TELEPORTED
goto_if_eq FourIsland_IcefallCave_IcebergChamber_RanFromRegice
setflag FLAG_FOUGHT_REGICE
release
end
FourIsland_IcefallCave_IcebergChamber_DefeatedRegice::
setflag FLAG_REGICE_DISAPPEARED
setvar VAR_0x8004, SPECIES_REGICE
goto EventScript_MonDisappeared
end
FourIsland_IcefallCave_IcebergChamber_RanFromRegice::
setflag FLAG_REGICE_DISAPPEARED
setvar VAR_0x8004, SPECIES_REGICE
goto EventScript_MonDisappeared
end
FourIsland_IcefallCave_IcebergChamber_Text_Regice:
.string "Jakiih!$"
FourIsland_IcefallCave_IcebergChamber_Statue_Text:
.string "The Pokemon statue that\n"
.string "exudes the power of ice\l"
.string "started moving!$"
| [
"[email protected]"
] | |
26a500fcd9a9a0bbc5aeee37c47a659aa3786c6b | 15a7fd482bdeb804c6247b9baa376a11dc98a823 | /Portable/zoolib/Chan_XX_PipePair.h | 674db3b04cf8f9715b8a6c17113df7211e09fb73 | [
"MIT"
] | permissive | MorningSun-GitBoy/zoolib_cxx | e2da8153005b12b8493ac45fa8f2e5c504619284 | 456a969b88ae26af928eabc892bedaccdded526a | refs/heads/master | 2021-03-25T09:58:09.288346 | 2020-03-10T16:06:28 | 2020-03-10T16:06:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,444 | h | /* -------------------------------------------------------------------------------------------------
Copyright (c) 2018 Andrew Green
http://www.zoolib.org
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------------------------- */
#ifndef __ZooLib_Chan_XX_PipePair_h__
#define __ZooLib_Chan_XX_PipePair_h__ 1
#include "zconfig.h"
#include "zoolib/Chan.h"
#include "zoolib/Counted.h"
#include "zoolib/Time.h"
#include "zoolib/ZThread.h"
namespace ZooLib {
// =================================================================================================
#pragma mark - ImpPipePair
template <class EE>
class ImpPipePair
: public Counted
{
public:
ImpPipePair()
{
fClosed = false;
fSource = nullptr;
fSourceEnd = nullptr;
fDest = nullptr;
fDestCount = 0;
}
~ImpPipePair()
{
ZAcqMtx acq(fMutex);
ZAssert(fSource == nullptr && fDest == nullptr);
}
// For ChanAspect_Abort
void Abort()
{
ZAcqMtx acq(fMutex);
if (not fClosed)
{
fClosed = true;
fCondition_Read.Broadcast();
fCondition_Write.Broadcast();
}
}
// For ChanAspect_DisconnectRead
bool DisconnectRead(double iTimeout)
{
ZAcqMtx acq(fMutex);
if (not fClosed)
{
fSource = fSourceEnd;
fClosed = true;
fCondition_Write.Broadcast();
}
return true;
}
// For ChanAspect_DisconnectWrite
void DisconnectWrite()
{
ZAcqMtx acq(fMutex);
if (not fClosed)
{
fClosed = true;
fCondition_Read.Broadcast();
}
}
// For ChanAspect_Read
size_t Read(EE* oDest, size_t iCount)
{
EE* localDest = static_cast<EE*>(oDest);
EE* localEnd = localDest + iCount;
ZAcqMtx acq(fMutex);
while (localDest < localEnd)
{
if (fSource && fSource < fSourceEnd)
{
// We've got a source waiting to give us data.
size_t countToCopy = std::min(localEnd - localDest, fSourceEnd - fSource);
std::copy(fSource, fSource + countToCopy, localDest);
localDest += countToCopy;
fSource += countToCopy;
fCondition_Write.Broadcast();
break;
}
else if (fDest)
{
// Someone else has registered as wanting data.
fCondition_Read.Wait(fMutex);
}
else
{
// Register ourselves as waiting for data.
if (fClosed)
break;
fDest = localDest;
fDestCount = localEnd - localDest;
fCondition_Write.Broadcast();
fCondition_Read.Wait(fMutex);
fDestCount = 0;
bool readAny = localDest != fDest;
localDest = fDest;
fDest = nullptr;
if (readAny)
break;
}
}
return localDest - static_cast<EE*>(oDest);
}
size_t Readable()
{
ZAcqMtx acq(fMutex);
if (fSource)
return fSourceEnd - fSource;
return 0;
}
// For ChanAspect_WaitReadable
bool WaitReadable(double iTimeout)
{
const double deadline = Time::sSystem() + iTimeout;
ZAcqMtx acq(fMutex);
for (;;)
{
if ((fSource && fSource < fSourceEnd) || fClosed)
return true;
if (not fCondition_Read.WaitUntil(fMutex, deadline))
return false;
}
}
// For ChanAspect_Write
size_t Write(const EE* iSource, size_t iCount)
{
const EE* localSource = static_cast<const EE*>(iSource);
const EE* localEnd = localSource + iCount;
ZAcqMtx acq(fMutex);
while (localSource < localEnd && not fClosed)
{
if (fDestCount)
{
// A reader is waiting for data, so copy straight
// from our source into the reader's dest.
size_t countToCopy = std::min(fDestCount, size_t(localEnd - localSource));
std::copy(localSource, localSource + countToCopy, fDest);
fDest += countToCopy;
localSource += countToCopy;
fDestCount -= countToCopy;
fCondition_Read.Broadcast();
break;
}
else if (fSource)
{
// Someone else has registered as having data to provide.
fCondition_Write.Wait(fMutex);
}
else
{
// Register ourselves as having data to provide.
fSource = localSource;
fSourceEnd = localEnd;
fCondition_Read.Broadcast();
fCondition_Write.Wait(fMutex);
localSource = fSource;
fSource = nullptr;
fSourceEnd = nullptr;
}
}
return localSource - static_cast<const EE*>(iSource);
}
private:
ZMtx fMutex;
ZCnd fCondition_Read;
ZCnd fCondition_Write;
bool fClosed;
const EE* fSource;
const EE* fSourceEnd;
EE* fDest;
size_t fDestCount;
};
// ----------
template <class EE>
class ChanR_PipePair
: public ChanR<EE>
{
public:
ChanR_PipePair(const ZP<ImpPipePair<EE>>& iPipePair)
: fPipePair(iPipePair)
{}
virtual ~ChanR_PipePair()
{
while (not fPipePair->DisconnectRead(1 * Time::kDay))
{}
}
// From ChanAspect_Read
virtual size_t Read(EE* oDest, size_t iCount)
{ return fPipePair->Read(oDest, iCount); }
virtual size_t Readable()
{ return fPipePair->Readable(); }
ZP<ImpPipePair<EE>> fPipePair;
};
// ----------
template <class EE>
class ChanWCon_PipePair
: public ChanWCon<EE>
{
public:
ChanWCon_PipePair(const ZP<ImpPipePair<EE>>& iPipePair)
: fPipePair(iPipePair)
{}
virtual ~ChanWCon_PipePair()
{ fPipePair->Abort(); }
// From ChanAspect_Abort
virtual void Abort()
{ fPipePair->Abort(); }
// From ChanAspect_DisconnectWrite
virtual void DisconnectWrite()
{ return fPipePair->DisconnectWrite(); }
// From ChanAspect_Write
virtual size_t Write(const EE* iSource, size_t iCount)
{ return fPipePair->Write(iSource, iCount); }
ZP<ImpPipePair<EE>> fPipePair;
};
} // namespace ZooLib
#endif // __ZooLib_Chan_XX_PipePair_h__
| [
"[email protected]"
] | |
f5e553e914243d487b6bb9c8691eab9a9e4e066e | 7c0f5268c5b7e8b6ffcf91f8f3129fc5fbba8c2b | /svm.h | f46a61c6c5e240ffdbfdd0fe290629d4cb9ba432 | [] | no_license | zengjichuan/KOIL | b7212f4243319b37ea266b90d05593960b7f38dc | b1b726919570cb5edf5d3624e41dd72ce901987a | refs/heads/master | 2020-12-25T00:05:22.820850 | 2016-04-26T06:26:06 | 2016-04-26T06:26:06 | 57,058,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,337 | h | /**
* @brief Kernelized Online Imbalanced Learning with Fixed Buddget
* Implemented by Junjie Hu
* Contact: [email protected]
*/
#ifndef _SVM_H
#define _SVM_H
#include <string>
#include <vector>
using namespace std;
/**
* @brief SVM node: <index, value> pair for each feature
*
*/
struct svm_node
{
int index;
double value;
};
/**
* @brief libsvm type dataset
*
*/
struct svm_problem {
// data information
unsigned int n; // # instances
unsigned int pos,neg; // # positive,negative instances
unsigned int d; // # features
unsigned int elements; // # all elemnts;
// data value
struct svm_node* x_space;
struct svm_node** x; // x[i]: the i-th sample
double* y; // y[i]: the label of the i-th sample
// cross validation partition
int** idx_cv;
int n_cv;
int d_cv;
int** idx_Asso;
int n_Asso;
int d_Asso;
/**
* @brief load samples x and label y
*
* @param filename file name
*/
void load_problem(string filename);
/**
* @brief load the cross validation information
*
* @param assofile load the associated file
* @param cvfile load the cross validation file
*/
void load_cross_validation(string assofile, string cvfile);
};
enum {LINEAR = 0, RBF = 1, POLY = 2, SIGMOID=3}; // kernel type
/**
* @brief contains all the SVM parameters
*
*/
struct svm_parameter {
svm_parameter():C(1),kernel_type(RBF),degree(2),gamma(1),eta(0.01){}
double C; /* penalty parameter of the objective function*/
int kernel_type; /* kernel type: LINEAR, RBF, POLY */
int degree; /* for poly */
double gamma; /* for poly/rbf/sigmoid */
//double coef0; /* for poly/sigmoid */
double eta; /* learning rate for KOIL*/
};
/**
* @brief SVM decision function
*
*/
struct svm_model
{
svm_model(){
this->initialize(100);
}
struct svm_parameter param; /* parameter */
int l; /* total #SV */
double b; // threshold for the decision
int k_num; // number of k nearest neighbors
int fpidx; // first index in the positive SV list for FIFO++
int fnidx; // first index in the negative SV list for FIFO++
int rsp; // number of scanned positive samples for RS++
int rsn; // number of scanned negative samples for RS++
double project_bound; // project bound for the alpha
// positive SV
struct svm_node ** pos_SV; // pos_SV: pos_SV[i][j]: the j-th feature of the i-th positive SV
double * pos_alpha; // alpha: weight for the positive SV
int pos_n; // current number of positive SV in budget
int max_pos_n; // maximun number of positive SV in budget
//negative SV
struct svm_node ** neg_SV;
double * neg_alpha;
int neg_n;
int max_neg_n;
// member function
void initialize(int budget_size);
void free_model();
int load_model(string model_file_name);
int save_model(string model_file_name);
//double* predict(svm_problem& prob);
double predict(svm_node* xt);
double* predict_list(svm_node** xt, int n);
double kernel_func(svm_node* x1, svm_node* x2);
double f_norm();
};
/**
* @brief SVM with Multiple Kernels decision function
*
*/
struct svm_mkl{
svm_mkl(){}
svm_mkl(int budget_size, double delta, double C, vector<double> glist){
this->initialize(budget_size,delta,C,glist);
}
svm_mkl(int budget_size, double delta, double C, vector<double> glist, vector<int> degreelist){
this->initialize(budget_size,delta,C,glist,degreelist);
}
vector<svm_model> classifiers;
vector<double> weight;
vector<double> p;
double delta; /* smooth term */
double lambda; /* learning rate for each kernel of MKL */
double eta; /* step size for the update of kernel weight */
//member function
void initialize(int budget_size, double delta, double C, vector<double> glist);
void initialize(int budget_size, double delta, double C, vector<double> glist, vector<int> degreelist);
double predict(svm_node* xt);
double* predict_list(svm_node** xt, int n);
void normalize_weight();
void smooth_propbability();
};
double dot(svm_node* a,svm_node*b);
#endif
| [
"[email protected]"
] | |
f376d06460e6aba31bd8388a4dcc9c84b3792eac | 17fe08a8e9fce9d0f71f1b6f28192cb7373ab88c | /zookeeper/server/quorum/QuorumPeer.hh | 0dae6c9059c25d3ae77d61ff29c5838279ccc0f0 | [
"Apache-2.0"
] | permissive | cxxjava/CxxZookeeper | dcf31c6638afc37c1ebe1ba4351b31c10d991364 | 149677c785627aff839b2102ab265c745882fa52 | refs/heads/master | 2021-01-25T13:23:45.102771 | 2018-10-25T17:33:33 | 2018-10-25T17:33:33 | 123,562,911 | 19 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 29,237 | hh | /*
* QuorumPeer.hh
*
* Created on: 2017-11-22
* Author: [email protected]
*/
#ifndef QuorumPeer_HH_
#define QuorumPeer_HH_
#include "Efc.hh"
#include "ELog.hh"
#include "./Follower.hh"
#include "./Leader.hh"
#include "./Observer.hh"
#include "./QuorumMaj.hh"
#include "./Vote.hh"
#include "./Election.hh"
#include "./QuorumCnxManager.hh"
#include "./QuorumAuthServer.hh"
#include "./QuorumServer.hh"
#include "./QuorumStats.hh"
#include "./QuorumAuth.hh"
#include "./NullQuorumAuthServer.hh"
#include "./NullQuorumAuthLearner.hh"
#include "./ReadOnlyZooKeeperServer.hh"
#include "../ServerStats.hh"
#include "../ServerCnxnFactory.hh"
#include "../util/ZxidUtils.hh"
#include "../persistence/FileTxnSnapLog.hh"
#include "../../common/AtomicFileOutputStream.hh"
namespace efc {
namespace ezk {
/**
* This class manages the quorum protocol. There are three states this server
* can be in:
* <ol>
* <li>Leader election - each server will elect a leader (proposing itself as a
* leader initially).</li>
* <li>Follower - the server will synchronize with the leader and replicate any
* transactions.</li>
* <li>Leader - the server will process requests and forward them to followers.
* A majority of followers must log the request before it can be accepted.
* </ol>
*
* This class will setup a datagram socket that will always respond with its
* view of the current leader. The response will take the form of:
*
* <pre>
* int xid;
*
* long myid;
*
* long leader_id;
*
* long leader_zxid;
* </pre>
*
* The request for the current leader will consist solely of an xid: int xid;
*/
class QuorumPeer : public ZooKeeperThread , virtual public QuorumStats::Provider {
private:
static sp<ELogger> LOG;// = LoggerFactory.getLogger(QuorumPeer.class);
public:
/**
* @deprecated As of release 3.4.0, this class has been deprecated, since
* it is used with one of the udp-based versions of leader election, which
* we are also deprecating.
*
* This class simply responds to requests for the current leader of this
* node.
* <p>
* The request contains just an xid generated by the requestor.
* <p>
* The response has the xid, the id of this server, the id of the leader,
* and the zxid of the leader.
*
*
*/
class ResponderThread : public ZooKeeperThread {
private:
QuorumPeer* peer;
public:
volatile boolean running;// = true;
ResponderThread(QuorumPeer* p) : ZooKeeperThread("ResponderThread"), peer(p) {
running = true;
}
virtual void run();
};
/*
* Default value of peer is participant
*/
QuorumServer::LearnerType learnerType;// = LearnerType.PARTICIPANT;
/**
* QuorumVerifier implementation; default (majority).
*/
sp<QuorumVerifier> quorumConfig;
/**
* My id
*/
llong myid;
/**
* This is who I think the leader currently is.
*/
sp<Vote> currentVote;// volatile private Vote currentVote;
/**
* ... and its counterpart for backward compatibility
*/
sp<Vote> bcVote;// volatile private Vote bcVote;
volatile boolean running;// = true;
ServerState state;// = ServerState.LOOKING;
sp<EInetSocketAddress> myQuorumAddr;
int electionType;
sp<FileTxnSnapLog> logFactory;// = null;
sp<QuorumStats> quorumStats_;
sp<EDatagramSocket> udpSocket;
sp<Election> electionAlg;
sp<ServerCnxnFactory> cnxnFactory;
sp<ResponderThread> responder;
llong acceptedEpoch;// = -1;
llong currentEpoch;// = -1;
sp<QuorumCnxManager> qcm;
sp<QuorumAuthServer> authServer;
sp<QuorumAuthLearner> authLearner;
// VisibleForTesting. This flag is used to know whether qLearner's and
// qServer's login context has been initialized as ApacheDS has concurrency
// issues. Refer https://issues.apache.org/jira/browse/ZOOKEEPER-2712
boolean authInitialized;// = false;
/* ZKDatabase is a top level member of quorumpeer
* which will be used in all the zookeeperservers
* instantiated later. Also, it is created once on
* bootup and only thrown away in case of a truncate
* message from the leader
*/
sp<ZKDatabase> zkDb;
llong readLongFromFile(EString name) THROWS(EIOException) {
/* @see:
File file = new File(logFactory.getSnapDir(), name);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
try {
line = br.readLine();
return Long.parseLong(line);
} catch(ENumberFormatException& e) {
throw EIOException("Found " + line + " in " + file);
} finally {
br.close();
}
*/
EFile file(logFactory->getSnapDir(), name.c_str());
ERandomAccessFile raf(&file, "r");
sp<EString> line = raf.readLine();
try {
return ELLong::parseLLong((line != null) ? line->c_str() : "");
} catch(ENumberFormatException& e) {
throw EIOException(__FILE__, __LINE__, ("Found " + line->toString() + " in " + file.toString()).c_str());
}
}
/**
* Write a long value to disk atomically. Either succeeds or an exception
* is thrown.
* @param name file name to write the long to
* @param value the long value to write to the named file
* @throws IOException if the file cannot be written atomically
*/
void writeLongToFile(EString name, llong value) THROWS(EIOException) {
EFile file (logFactory->getSnapDir(), name.c_str());
AtomicFileOutputStream out(&file);
EBufferedOutputStream bos(&out);
boolean aborted = false;
ON_FINALLY_NOTHROW(
if (!aborted) {
// if the close operation (rename) fails we'll get notified.
// worst case the tmp file may still exist
out.close();
}
) {
try {
bos.write(ELLong::toString(value).c_str());
bos.flush();
out.flush();
} catch (EIOException& e) {
LOG->error("Failed to write new file " + file.toString(), e);
// worst case here the tmp file/resources(fd) are not cleaned up
// and the caller will be notified (IOException)
aborted = true;
out.abort();
throw e;
}
}}
}
void loadDataBase() {
EFile updating(logFactory->getSnapDir(), UPDATING_EPOCH_FILENAME);
try {
zkDb->loadDataBase();
// load the epochs
llong lastProcessedZxid = zkDb->getDataTree()->lastProcessedZxid;
llong epochOfZxid = ZxidUtils::getEpochFromZxid(lastProcessedZxid);
try {
currentEpoch = readLongFromFile(CURRENT_EPOCH_FILENAME);
if (epochOfZxid > currentEpoch && updating.exists()) {
LOG->info(
EString(UPDATING_EPOCH_FILENAME)
+ " found. The server was terminated after "
"taking a snapshot but before updating current "
"epoch. Setting current epoch to "
+ epochOfZxid);
setCurrentEpoch(epochOfZxid);
if (!updating.remove()) {
throw EIOException(__FILE__, __LINE__,
("Failed to delete " + updating.toString()).c_str());
}
}
} catch (EFileNotFoundException& e) {
// pick a reasonable epoch number
// this should only happen once when moving to a
// new code version
currentEpoch = epochOfZxid;
LOG->info(
EString(CURRENT_EPOCH_FILENAME)
+ " not found! Creating with a reasonable default of "
+ currentEpoch
+ ". This should only happen when you are upgrading your installation");
writeLongToFile(CURRENT_EPOCH_FILENAME, currentEpoch);
}
if (epochOfZxid > currentEpoch) {
throw EIOException(__FILE__, __LINE__,
("The current epoch, "
+ ZxidUtils::zxidToString(currentEpoch)
+ ", is older than the last zxid, "
+ lastProcessedZxid).c_str());
}
try {
acceptedEpoch = readLongFromFile(ACCEPTED_EPOCH_FILENAME);
} catch (EFileNotFoundException& e) {
// pick a reasonable epoch number
// this should only happen once when moving to a
// new code version
acceptedEpoch = epochOfZxid;
LOG->info(__FILE__, __LINE__,
EString(ACCEPTED_EPOCH_FILENAME)
+ " not found! Creating with a reasonable default of "
+ acceptedEpoch
+ ". This should only happen when you are upgrading your installation");
writeLongToFile(ACCEPTED_EPOCH_FILENAME, acceptedEpoch);
}
if (acceptedEpoch < currentEpoch) {
throw EIOException(__FILE__, __LINE__,
("The accepted epoch, "
+ ZxidUtils::zxidToString(acceptedEpoch)
+ " is less than the current epoch, "
+ ZxidUtils::zxidToString(currentEpoch)).c_str());
}
} catch (EIOException& ie) {
LOG->error("Unable to load database on disk", ie);
throw ERuntimeException(__FILE__, __LINE__, "Unable to run quorum server ", &ie);
}
}
/**
* Count the number of nodes in the map that could be followers.
* @param peers
* @return The number of followers in the map
*/
static int countParticipants(EHashMap<llong, QuorumServer*>* peers) {
int count = 0;
auto iter = peers->values()->iterator();
while (iter->hasNext()) {
QuorumServer* q = iter->next();
if (q->type == QuorumServer::LearnerType::PARTICIPANT) {
count++;
}
}
return count;
}
//protected:
public:
/**
* The number of milliseconds of each tick
*/
int tickTime;
/**
* Minimum number of milliseconds to allow for session timeout.
* A value of -1 indicates unset, use default.
*/
int minSessionTimeout;// = -1;
/**
* Maximum number of milliseconds to allow for session timeout.
* A value of -1 indicates unset, use default.
*/
int maxSessionTimeout;// = -1;
/**
* The number of ticks that the initial synchronization phase can take
*/
int initLimit;
/**
* The number of ticks that can pass between sending a request and getting
* an acknowledgment
*/
int syncLimit;
/**
* Enables/Disables sync request processor. This option is enabled
* by default and is to be used with observers.
*/
boolean syncEnabled;// = true;
/**
* The current tick
*/
EAtomicInteger tick;// = new AtomicInteger();
/**
* Whether or not to listen on all IPs for the two quorum ports
* (broadcast and fast leader election).
*/
boolean quorumListenOnAllIPs;// = false;
/**
* Kerberos quorum service principal. Defaulting to 'zkquorum/localhost'.
*/
EString quorumServicePrincipal;
/**
* Quorum learner login context name in jaas-conf file to read the kerberos
* security details. Defaulting to 'QuorumLearner'.
*/
EString quorumLearnerLoginContext;
/**
* Quorum server login context name in jaas-conf file to read the kerberos
* security details. Defaulting to 'QuorumServer'.
*/
EString quorumServerLoginContext;
// TODO: need to tune the default value of thread size
static const int QUORUM_CNXN_THREADS_SIZE_DEFAULT_VALUE = 20;
/**
* The maximum number of threads to allow in the connectionExecutors thread
* pool which will be used to initiate quorum server connections.
*/
int quorumCnxnThreadsSize = QUORUM_CNXN_THREADS_SIZE_DEFAULT_VALUE;
/**
* Keeps time taken for leader election in milliseconds. Sets the value to
* this variable only after the completion of leader election.
*/
llong electionTimeTaken;// = -1;
public:
sp<Follower> follower;
sp<Leader> leader;
sp<Observer> observer;
/*
* To enable observers to have no identifier, we need a generic identifier
* at least for QuorumCnxManager. We use the following constant to as the
* value of such a generic identifier.
*/
static const llong OBSERVER_ID = ELLong::MAX_VALUE;
/**
* The syncEnabled can also be set via a system property.
*/
constexpr static const char* SYNC_ENABLED = "zookeeper.observer.syncEnabled";
constexpr static const char* CURRENT_EPOCH_FILENAME = "currentEpoch";
constexpr static const char* ACCEPTED_EPOCH_FILENAME = "acceptedEpoch";
constexpr static const char* UPDATING_EPOCH_FILENAME = "updatingEpoch";
/*
* Record leader election time
*/
llong start_fle, end_fle;
EHashMap<llong, QuorumServer*>* quorumPeers;
QuorumServer::LearnerType getLearnerType() {
return learnerType;
}
/**
* Sets the LearnerType both in the QuorumPeer and in the peerMap
*/
void setLearnerType(QuorumServer::LearnerType p) {
learnerType = p;
if (quorumPeers->containsKey(this->myid)) {
this->quorumPeers->get(myid)->type = p;
} else {
LOG->error(EString("Setting LearnerType to ") + p + " but " + myid
+ " not in QuorumPeers. ");
}
}
/**
* The servers that make up the cluster
*/
int getQuorumSize(){
return getVotingView()->size();
}
/**
* get the id of this quorum peer.
*/
llong getId() {
return myid;
}
synchronized
sp<Vote> getCurrentVote(){
SYNCHRONIZED(this) {
return currentVote;
}}
}
synchronized
void setCurrentVote(sp<Vote> v) {
SYNCHRONIZED(this) {
currentVote = v;
}}
}
synchronized
sp<Vote> getBCVote() {
SYNCHRONIZED(this) {
if (bcVote == null) {
return currentVote;
} else {
return bcVote;
}
}}
}
synchronized
void setBCVote(sp<Vote> v) {
SYNCHRONIZED(this) {
bcVote = v;
}}
}
synchronized
void setPeerState(ServerState newState){
SYNCHRONIZED(this) {
state=newState;
}}
}
const char* getPeerStateName() {
return getStateName(getPeerState());
}
synchronized
ServerState getPeerState(){
SYNCHRONIZED(this) {
return state;
}}
}
sp<EInetSocketAddress> getQuorumAddress(){
return myQuorumAddr;
}
public:
QuorumPeer() : ZooKeeperThread("QuorumPeer"),
learnerType(QuorumServer::LearnerType::PARTICIPANT),
running(true),
state(ServerState::LOOKING),
acceptedEpoch(-1),
currentEpoch(-1),
authInitialized(false),
minSessionTimeout(-1),
maxSessionTimeout(-1),
syncEnabled(true),
quorumListenOnAllIPs(false),
electionTimeTaken(-1),
start_fle(0),
end_fle(0)
{
quorumStats_ = new QuorumStats(this);
initialize();
}
/**
* For backward compatibility purposes, we instantiate QuorumMaj by default.
*/
QuorumPeer(EHashMap<llong, QuorumServer*>* quorumPeers, EFile* dataDir,
EFile* dataLogDir, int electionType,
llong myid, int tickTime, int initLimit, int syncLimit,
sp<ServerCnxnFactory> cnxnFactory) THROWS(EIOException) :
ZooKeeperThread("QuorumPeer"),
learnerType(QuorumServer::LearnerType::PARTICIPANT),
running(true),
state(ServerState::LOOKING),
acceptedEpoch(-1),
currentEpoch(-1),
authInitialized(false),
minSessionTimeout(-1),
maxSessionTimeout(-1),
syncEnabled(true),
quorumListenOnAllIPs(false),
electionTimeTaken(-1),
start_fle(0),
end_fle(0) {
this->quorumStats_ = new QuorumStats(this);
initialize();
this->cnxnFactory = cnxnFactory;
this->quorumPeers = quorumPeers;
this->electionType = electionType;
this->myid = myid;
this->tickTime = tickTime;
this->initLimit = initLimit;
this->syncLimit = syncLimit;
this->quorumListenOnAllIPs = false;
this->logFactory = new FileTxnSnapLog(dataLogDir, dataDir);
this->zkDb = new ZKDatabase(this->logFactory);
this->quorumConfig = new QuorumMaj(countParticipants(quorumPeers));
}
QuorumPeer(EHashMap<llong, QuorumServer*>* quorumPeers, EFile* dataDir,
EFile* dataLogDir, int electionType,
llong myid, int tickTime, int initLimit, int syncLimit,
boolean quorumListenOnAllIPs,
sp<ServerCnxnFactory> cnxnFactory,
sp<QuorumVerifier> quorumConfig) THROWS(EIOException) :
ZooKeeperThread("QuorumPeer"),
learnerType(QuorumServer::LearnerType::PARTICIPANT),
running(true),
state(ServerState::LOOKING),
acceptedEpoch(-1),
currentEpoch(-1),
authInitialized(false),
minSessionTimeout(-1),
maxSessionTimeout(-1),
syncEnabled(true),
quorumListenOnAllIPs(false),
electionTimeTaken(-1),
start_fle(0),
end_fle(0) {
this->quorumStats_ = new QuorumStats(this);
initialize();
this->cnxnFactory = cnxnFactory;
this->quorumPeers = quorumPeers;
this->electionType = electionType;
this->myid = myid;
this->tickTime = tickTime;
this->initLimit = initLimit;
this->syncLimit = syncLimit;
this->quorumListenOnAllIPs = quorumListenOnAllIPs;
this->logFactory = new FileTxnSnapLog(dataLogDir, dataDir);
this->zkDb = new ZKDatabase(this->logFactory);
if(quorumConfig == null)
this->quorumConfig = new QuorumMaj(countParticipants(quorumPeers));
else this->quorumConfig = quorumConfig;
}
void initialize() {
// init quorum auth server & learner
authServer = new NullQuorumAuthServer();
authLearner = new NullQuorumAuthLearner();
}
sp<QuorumStats> quorumStats() {
return quorumStats_;
}
synchronized
virtual void start() {
SYNCHRONIZED(this) {
loadDataBase();
cnxnFactory->start();
startLeaderElection();
ZooKeeperThread::start();
}}
}
synchronized
void stopLeaderElection() {
SYNCHRONIZED(this) {
responder->running = false;
responder->interrupt();
}}
}
synchronized
void startLeaderElection() {
SYNCHRONIZED(this) {
try {
currentVote = new Vote(myid, getLastLoggedZxid(), getCurrentEpoch());
} catch(EIOException& e) {
ERuntimeException re(e.getSourceFile(), e.getSourceLine(), e.getMessage());
re.initCause(&e);
throw re;
}
auto iter = getView()->values()->iterator();
while (iter->hasNext()) {
QuorumServer* p = iter->next();
if (p->id == myid) {
myQuorumAddr = p->addr;
break;
}
}
if (myQuorumAddr == null) {
throw ERuntimeException(__FILE__, __LINE__, (EString("My id ") + myid + " not in the peer list").c_str());
}
if (electionType == 0) {
try {
udpSocket = new EDatagramSocket(myQuorumAddr->getPort());
responder = new ResponderThread(this);
EThread::setDaemon(responder, true); //!!!
responder->start();
} catch (ESocketException& e) {
throw ERuntimeException(e.getSourceFile(), e.getSourceLine(), &e);
}
}
this->electionAlg = createElectionAlgorithm(electionType);
}}
}
/**
* returns the highest zxid that this host has seen
*
* @return the highest zxid for this host
*/
llong getLastLoggedZxid() {
if (!zkDb->isInitialized()) {
loadDataBase();
}
return zkDb->getDataTreeLastProcessedZxid();
}
protected:
sp<Follower> makeFollower(sp<FileTxnSnapLog> logFactory) THROWS(EIOException);
sp<Leader> makeLeader(sp<FileTxnSnapLog> logFactory) THROWS(EIOException);
sp<Observer> makeObserver(sp<FileTxnSnapLog> logFactory) THROWS(EIOException);
sp<Election> createElectionAlgorithm(int electionAlgorithm);
sp<Election> makeLEStrategy();
synchronized
void setLeader(sp<Leader> newLeader){
SYNCHRONIZED(this) {
leader=newLeader;
}}
}
synchronized
void setFollower(sp<Follower> newFollower){
SYNCHRONIZED(this) {
follower=newFollower;
}}
}
synchronized
void setObserver(sp<Observer> newObserver){
SYNCHRONIZED(this) {
observer=newObserver;
}}
}
public:
synchronized sp<ZooKeeperServer> getActiveServer();
virtual void run();
virtual void shutdown();
/**
* A 'view' is a node's current opinion of the membership of the entire
* ensemble.
*/
EHashMap<llong, QuorumServer*>* getView() {
//@see: return Collections.unmodifiableMap(this->quorumPeers);
return quorumPeers;
}
/**
* Observers are not contained in this view, only nodes with
* PeerType=PARTICIPANT.
*/
sp<EHashMap<llong,QuorumServer*> > getVotingView();
static sp<EHashMap<llong,QuorumServer*> > viewToVotingView(
EHashMap<llong, QuorumServer*>* view);
/**
* Check if a node is in the current view. With static membership, the
* result of this check will never change; only when dynamic membership
* is introduced will this be more useful.
*/
boolean viewContains(llong sid) {
return quorumPeers->containsKey(sid);
}
/**
* Only used by QuorumStats at the moment
*/
EA<EString*> getQuorumPeers();
EString getServerState() {
switch (getPeerState()) {
case LOOKING:
return LOOKING_STATE;
case LEADING:
return LEADING_STATE;
case FOLLOWING:
return FOLLOWING_STATE;
case OBSERVING:
return OBSERVING_STATE;
}
return UNKNOWN_STATE;
}
/**
* get the id of this quorum peer.
*/
llong getMyid() {
return myid;
}
/**
* set the id of this quorum peer.
*/
void setMyid(long myid) {
this->myid = myid;
}
/**
* Get the number of milliseconds of each tick
*/
int getTickTime() {
return tickTime;
}
/**
* Set the number of milliseconds of each tick
*/
void setTickTime(int tickTime) {
LOG->info(EString("tickTime set to ") + tickTime);
this->tickTime = tickTime;
}
/** Maximum number of connections allowed from particular host (ip) */
int getMaxClientCnxnsPerHost() {
sp<ServerCnxnFactory> fac = getCnxnFactory();
if (fac == null) {
return -1;
}
return fac->getMaxClientCnxnsPerHost();
}
/** minimum session timeout in milliseconds */
int getMinSessionTimeout() {
return minSessionTimeout == -1 ? tickTime * 2 : minSessionTimeout;
}
/** minimum session timeout in milliseconds */
void setMinSessionTimeout(int min) {
LOG->info(EString("minSessionTimeout set to ") + min);
this->minSessionTimeout = min;
}
/** maximum session timeout in milliseconds */
int getMaxSessionTimeout() {
return maxSessionTimeout == -1 ? tickTime * 20 : maxSessionTimeout;
}
/** minimum session timeout in milliseconds */
void setMaxSessionTimeout(int max) {
LOG->info(EString("maxSessionTimeout set to ") + max);
this->maxSessionTimeout = max;
}
/**
* Get the number of ticks that the initial synchronization phase can take
*/
int getInitLimit() {
return initLimit;
}
/**
* Set the number of ticks that the initial synchronization phase can take
*/
void setInitLimit(int initLimit) {
LOG->info(EString("initLimit set to ") + initLimit);
this->initLimit = initLimit;
}
/**
* Get the current tick
*/
int getTick() {
return tick.get();
}
/**
* Return QuorumVerifier object
*/
sp<QuorumVerifier> getQuorumVerifier(){
return quorumConfig;
}
void setQuorumVerifier(sp<QuorumVerifier> quorumConfig){
this->quorumConfig = quorumConfig;
}
/**
* Get an instance of LeaderElection
*/
sp<Election> getElectionAlg(){
return electionAlg;
}
/**
* Get the synclimit
*/
int getSyncLimit() {
return syncLimit;
}
/**
* Set the synclimit
*/
void setSyncLimit(int syncLimit) {
this->syncLimit = syncLimit;
}
/**
* Return syncEnabled.
*
* @return
*/
boolean getSyncEnabled() {
const char* enabled = ESystem::getProperty(SYNC_ENABLED);
if (enabled != null) {
boolean b = EBoolean::parseBoolean(enabled);
LOG->info(SYNC_ENABLED + EString("=") + b);
return b;
} else {
return syncEnabled;
}
}
/**
* Set syncEnabled.
*
* @param syncEnabled
*/
void setSyncEnabled(boolean syncEnabled) {
this->syncEnabled = syncEnabled;
}
/**
* Gets the election type
*/
int getElectionType() {
return electionType;
}
/**
* Sets the election type
*/
void setElectionType(int electionType) {
this->electionType = electionType;
}
boolean getQuorumListenOnAllIPs() {
return quorumListenOnAllIPs;
}
void setQuorumListenOnAllIPs(boolean quorumListenOnAllIPs) {
this->quorumListenOnAllIPs = quorumListenOnAllIPs;
}
sp<ServerCnxnFactory> getCnxnFactory() {
return cnxnFactory;
}
void setCnxnFactory(sp<ServerCnxnFactory> cnxnFactory) {
this->cnxnFactory = cnxnFactory;
}
void setQuorumPeers(EHashMap<llong, QuorumServer*>* quorumPeers) {
this->quorumPeers = quorumPeers;
}
int getClientPort() {
return cnxnFactory->getLocalPort();
}
void setClientPortAddress(sp<EInetSocketAddress> addr) {
}
void setTxnFactory(sp<FileTxnSnapLog> factory) {
this->logFactory = factory;
}
sp<FileTxnSnapLog> getTxnFactory() {
return this->logFactory;
}
/**
* set zk database for this node
* @param database
*/
void setZKDatabase(sp<ZKDatabase> database) {
this->zkDb = database;
}
sp<ZKDatabase> getZkDb() {
return zkDb;
}
void setRunning(boolean running) {
this->running = running;
}
boolean isRunning() {
return running;
}
/**
* get reference to QuorumCnxManager
*/
sp<QuorumCnxManager> getQuorumCnxManager() {
return qcm;
}
llong getCurrentEpoch() THROWS(EIOException) {
if (currentEpoch == -1) {
currentEpoch = readLongFromFile(CURRENT_EPOCH_FILENAME);
}
return currentEpoch;
}
llong getAcceptedEpoch() THROWS(EIOException) {
if (acceptedEpoch == -1) {
acceptedEpoch = readLongFromFile(ACCEPTED_EPOCH_FILENAME);
}
return acceptedEpoch;
}
void setCurrentEpoch(llong e) THROWS(EIOException) {
currentEpoch = e;
writeLongToFile(CURRENT_EPOCH_FILENAME, e);
}
void setAcceptedEpoch(llong e) THROWS(EIOException) {
acceptedEpoch = e;
writeLongToFile(ACCEPTED_EPOCH_FILENAME, e);
}
/**
* Updates leader election info to avoid inconsistencies when
* a new server tries to join the ensemble.
* See ZOOKEEPER-1732 for more info.
*/
void updateElectionVote(llong newEpoch);
void setQuorumServicePrincipal(EString servicePrincipal) {
quorumServicePrincipal = servicePrincipal;
LOG->info(EString::formatOf("%s set to %s",QuorumAuth::QUORUM_KERBEROS_SERVICE_PRINCIPAL,
quorumServicePrincipal.c_str()));
}
void setQuorumLearnerLoginContext(EString learnerContext) {
quorumLearnerLoginContext = learnerContext;
LOG->info(EString::formatOf("%s set to %s", QuorumAuth::QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
quorumLearnerLoginContext.c_str()));
}
void setQuorumServerLoginContext(EString serverContext) {
quorumServerLoginContext = serverContext;
LOG->info(EString::formatOf("%s set to %s", QuorumAuth::QUORUM_SERVER_SASL_LOGIN_CONTEXT,
quorumServerLoginContext.c_str()));
}
void setQuorumCnxnThreadsSize(int qCnxnThreadsSize) {
if (qCnxnThreadsSize > QUORUM_CNXN_THREADS_SIZE_DEFAULT_VALUE) {
quorumCnxnThreadsSize = qCnxnThreadsSize;
}
LOG->info(EString("quorum.cnxn.threads.size set to ") + quorumCnxnThreadsSize);
}
// VisibleForTesting. Returns true if both the quorumlearner and
// quorumserver login has been finished. Otherwse, false.
boolean hasAuthInitialized(){
return authInitialized;
}
sp<QuorumCnxManager> createCnxnManager() {
return new QuorumCnxManager(this->getId(),
this->getView(),
this->authServer,
this->authLearner,
this->tickTime * this->syncLimit,
this->getQuorumListenOnAllIPs(),
this->quorumCnxnThreadsSize);
}
/**
* Sets the time taken for leader election in milliseconds.
*
* @param electionTimeTaken
* time taken for leader election
*/
void setElectionTimeTaken(long electionTimeTaken) {
this->electionTimeTaken = electionTimeTaken;
}
/**
* @return the time taken for leader election in milliseconds.
*/
llong getElectionTimeTaken() {
return electionTimeTaken;
}
};
} /* namespace ezk */
} /* namespace efc */
#endif /* QuorumPeer_HH_ */
| [
"[email protected]"
] | |
a858821dee6d9352ffcbb7867c87aa8cf7c5efb3 | 0d0e78c6262417fb1dff53901c6087b29fe260a0 | /ocr/include/tencentcloud/ocr/v20181119/model/VehicleRegCertOCRRequest.h | 246edba50bd1c874214ef495ae29037884b5dee6 | [
"Apache-2.0"
] | permissive | li5ch/tencentcloud-sdk-cpp | ae35ffb0c36773fd28e1b1a58d11755682ade2ee | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | refs/heads/master | 2022-12-04T15:33:08.729850 | 2020-07-20T00:52:24 | 2020-07-20T00:52:24 | 281,135,686 | 1 | 0 | Apache-2.0 | 2020-07-20T14:14:47 | 2020-07-20T14:14:46 | null | UTF-8 | C++ | false | false | 6,452 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_OCR_V20181119_MODEL_VEHICLEREGCERTOCRREQUEST_H_
#define TENCENTCLOUD_OCR_V20181119_MODEL_VEHICLEREGCERTOCRREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Ocr
{
namespace V20181119
{
namespace Model
{
/**
* VehicleRegCertOCR请求参数结构体
*/
class VehicleRegCertOCRRequest : public AbstractModel
{
public:
VehicleRegCertOCRRequest();
~VehicleRegCertOCRRequest() = default;
std::string ToJsonString() const;
/**
* 获取图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
* @return ImageBase64 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
*/
std::string GetImageBase64() const;
/**
* 设置图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
* @param ImageBase64 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
*/
void SetImageBase64(const std::string& _imageBase64);
/**
* 判断参数 ImageBase64 是否已赋值
* @return ImageBase64 是否已赋值
*/
bool ImageBase64HasBeenSet() const;
/**
* 获取图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
* @return ImageUrl 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
*/
std::string GetImageUrl() const;
/**
* 设置图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
* @param ImageUrl 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
*/
void SetImageUrl(const std::string& _imageUrl);
/**
* 判断参数 ImageUrl 是否已赋值
* @return ImageUrl 是否已赋值
*/
bool ImageUrlHasBeenSet() const;
private:
/**
* 图片的 Base64 值。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经Base64编码后不超过 3M。图片下载时间不超过 3 秒。
图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
*/
std::string m_imageBase64;
bool m_imageBase64HasBeenSet;
/**
* 图片的 Url 地址。
支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
支持的图片大小:所下载图片经 Base64 编码后不超过 3M。图片下载时间不超过 3 秒。
图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
非腾讯云存储的 Url 速度和稳定性可能受一定影响。
*/
std::string m_imageUrl;
bool m_imageUrlHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_OCR_V20181119_MODEL_VEHICLEREGCERTOCRREQUEST_H_
| [
"[email protected]"
] | |
d5c1aba854e4668548431f25525a826e2396fe51 | 2962f164cecb440ecd905ab9f3cc569c03a01ad5 | /RtspPlayer/assemblies/sunell/include/AlarmIOEvent.h | ea059ae40d1194f0f0df14822caa604f3808452a | [] | no_license | paxan222/hello-world | 5ef9bd04a5c4337c1403a04973e2c0c11665bb26 | c55c60e0f72a04e1e2560dc19c2a6bbd7e8b430f | refs/heads/master | 2020-12-11T21:09:30.200433 | 2017-05-04T08:39:53 | 2017-05-04T08:39:53 | 55,044,669 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 10,543 | h | #ifndef _ALARMIOEVENT_H_
#define _ALARMIOEVENT_H_
#include "DomainConst.h"
#include "AlarmOutAction.h"
#include "AlarmRecordAction.h"
#include "AlarmPTZAction.h"
#include "AlarmOverlayAction.h"
#include "ScheduleTimeParam.h"
#include <vector>
#include "SNPlatOS.h"
using namespace std;
/**********************************************************************/
//此处用于控制文件编译字节对齐,拷贝时两行注释间内容需一起拷贝,
//结束处的“#ifdef PRAGMA_PACK”部分也要一起拷贝,否则pragma pack入栈出栈不匹配
#if(PRAGMA_PACK_DEFINE != 10000)
# error Not included "SNPlatOS.h".
#endif
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(push, PRAGMA_PACK_CHAR)
#endif
#ifndef WIN32
#ifndef _PACKED_1_
#define _PACKED_1_ __attribute__((packed, aligned(PRAGMA_PACK_CHAR))) // for gcc
#endif
#else
#ifndef _PACKED_1_
#define _PACKED_1_
#endif
#endif
#else
#ifndef _PACKED_1_
#define _PACKED_1_
#endif
#endif
/**********************************************************************/
class SN_DLL_API AlarmIOEvent
{
public:
AlarmIOEvent();
~AlarmIOEvent();
//拷贝构造函数
AlarmIOEvent(const AlarmIOEvent &p_objAlarmIOEvent);
public:
/**********************************************************************
**概述:
* 设置网络视频设备的设备ID
**输入:
* p_pszDeviceId :字符串,最大长度为CONST_MAXLENGTH_DEVICEID字节,
* 结尾以‘\0’结束。
**输出:
* 无
**返回值:
* true : 成功
* false:失败
**功能:
* 若输入p_pszDeviceId长度<=CONST_MAXLENGTH_DEVICEID,返回true,
* 并保存到m_szDeviceId;
* 若输入p_pszDeviceId为NULL或其长度>CONST_MAXLENGTH_DEVICEID,返回false
************************************************************************/
bool setDeviceId(const char* p_pszDeviceId);
/************************************************************************
**概述:
* 获取网络视频设备的设备ID
**输入:
* 无
**输出:
* 无
**返回值:
* 设备ID
**功能:
*
***************************************************************************/
const char* getDeviceId() const;
/**********************************************************************
**概述:
* 设置报警事件ID
**输入:
* p_nEventId :报警事件ID号
**输出:
* 无
**返回值:
* 无
**功能:
*
************************************************************************/
void setEventId(int p_nEventId);
/************************************************************************
**概述:
* 获取报警事件ID
**输入:
* 无
**输出:
*
**返回值:
* 报警事件ID
**功能:
*
***************************************************************************/
int getEventId() const;
/**********************************************************************
**概述:
* 设置报警策略ID
**输入:
* p_nPolicyId :报警策略ID号
**输出:
* 无
**返回值:
* 无
**功能:
*
************************************************************************/
void setPolicyId(int p_nPolicyId);
/************************************************************************
**概述:
* 获取报警策略ID
**输入:
* 无
**输出:
* 无
**返回值:
* 报警策略ID
**功能:
*
***************************************************************************/
int getPolicyId() const;
/************************************************************************
**概述:
* 设置报警输入ID号
**输入:
* p_nAlarmInId :报警输入ID号
**输出:
* 无
**返回值:
* 无
**功能:
*
**************************************************************************/
void setAlarmInId(int p_nAlarmInId);
/************************************************************************
**概述:
* 获取报警输入ID号
**输入:
* 无
**输出:
* 无
**返回值:
* 报警输入ID号
**功能:
*
**************************************************************************/
int getAlarmInId() const;
/************************************************************************
**概述:
* 设置是否启动IO报警标志
**输入:
* p_bFlag:是否启动IO报警标志
**输出:
* 无
**返回值:
* 无
**功能:
* 设置是否启动IO报警标志
************************************************************************/
void setAlarmIOEnableFlag(const bool p_bFlag);
/************************************************************************
**概述:
* 获取是否启动IO报警标志
**输入:
* 无
**输出:
* 无
**返回值:
* 是否启动IO报警标志
**功能:
* 获取是否启IO报警标志
************************************************************************/
const bool getAlarmIOEnableFlag() const ;
/************************************************************************
**概述:
* 设置报警布防时间
**输入:
* p_objScheduleTimeParam:报警布防时间
**输出:
* 无
**返回值:
* 无
**功能:
* 设置报警布防时间
************************************************************************/
void setScheduleTimeParam(const ScheduleTimeParam &p_objScheduleTimeParam);
/************************************************************************
**概述:
* 获取报警布防时间
**输入:
* 无
**输出:
* 无
**返回值:
* 报警布防时间
**功能:
* 获取报警布防时间
************************************************************************/
const ScheduleTimeParam& getScheduleTimeParam() const;
/************************************************************************
**概述:
* 设置报警输出行为对象列表
**输入:
* p_objAlarmOutActionList:报警输出行为对象列表
**输出:
* 无
**返回值:
*
**功能:
*
**************************************************************************/
void setAlarmOutAction(const vector<AlarmOutAction>& p_objAlarmOutActionList);
/************************************************************************
**概述:
* 获取报警输出行为对象列表
**输入:
* 无
**输出:
* 无
**返回值:
* 报警输出行为对象列表
**功能:
*
**************************************************************************/
vector<AlarmOutAction>* getAlarmOutAction() const;
/************************************************************************
**概述:
* 设置报警录像行为对象列表
**输入:
* p_objAlarmRecordActionList:报警录像行为对象列表
**输出:
* 无
**返回值:
* 无
**功能:
*
**************************************************************************/
void setAlarmRecordAction(const vector<AlarmRecordAction>& p_objAlarmRecordActionList);
/************************************************************************
**概述:
* 获取报警录像行为对象列表
**输入:
* 无
**输出:
* 无
**返回值:
* 报警录像行为对象列表
**功能:
*
**************************************************************************/
vector<AlarmRecordAction>* getAlarmRecordAction() const;
/************************************************************************
**概述:
* 设置报警云台行为对象列表
**输入:
* p_objAlarmPTZActionList:报警云台行为对象列表
**输出:
* 无
**返回值:
*
**功能:
*
**************************************************************************/
void setAlarmPTZAction(const vector<AlarmPTZAction>& p_objAlarmPTZActionList);
/************************************************************************
**概述:
* 获取报警云台行为对象列表
**输入:
* 无
**输出:
* 无
**返回值:
* 报警云台行为对象列表
**功能:
*
**************************************************************************/
vector<AlarmPTZAction>* getAlarmPTZAction() const;
/************************************************************************
**概述:
* 设置报警水印行为对象列表
**输入:
* p_objAlarmOverlayActionList:报警水印行为对象列表
**输出:
* 无
**返回值:
*
**功能:
*
**************************************************************************/
void setAlarmOverlayAction(const vector<AlarmOverlayAction>& p_objAlarmOverlayActionList);
/************************************************************************
**概述:
* 获取报警水印行为对象列表
**输入:
* 无
**输出:
* 无
**返回值:
* 报警水印行为对象列表
**功能:
*
**************************************************************************/
vector<AlarmOverlayAction>* getAlarmOverlayAction() const;
/****************************************************************************
**概述:
* 赋值函数
**输入:
* p_objAlarmIOEvent:IO报警事件对象
**输出:
* 无
**返回值:
* 赋值后的IO报警事件对象
**功能:
*
*****************************************************************************/
AlarmIOEvent& operator = (const AlarmIOEvent &p_objAlarmIOEvent);
bool operator == (const AlarmIOEvent &p_objAlarmIOEvent) const;
bool operator < (const AlarmIOEvent &p_objAlarmIOEvent) const;
private:
int m_nEventId; //报警事件ID
int m_nPolicyId; //报警策略ID
int m_nAlarmInId; //报警输入ID号
bool m_bAlarmIOEnableFlag; //是否启动IO报警(false:不启动, true:启动)
char m_szDeviceId[CONST_MAXLENGTH_DEVICEID + 1]; //设备ID
ScheduleTimeParam m_objScheduleTimeParam; //布防时间参数
vector<AlarmOutAction> m_objAlarmOutActionList; //报警输出行为对象列表
vector<AlarmRecordAction> m_objAlarmRecordActionList; //报警录像行为对象列表
vector<AlarmPTZAction> m_objAlarmPTZActionList; //报警云台行为对象列表
vector<AlarmOverlayAction> m_objAlarmOverlayActionList; //报警水印行为对象列表
}_PACKED_1_;
/**********************************************************************/
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(pop)
#endif
#endif
/**********************************************************************/
#endif //_ALARMINPUTEVENT_H_
| [
"[email protected]"
] | |
d7ae479017517c2eec09e31f42ba9563054764e4 | 2b398d2f6bc8dabc822d6ee698a45b7954a79264 | /AnalgoKu5/Closest Pair of Point.cpp | e1201f31bd41f95e407858505601191c171b258f | [] | no_license | putrinabila/AnalgoKu | d31cb246e97b97d085e13afe968393b995edbbcf | ebe728ec1c10da0a6c6f07af1bf6b65809be61bb | refs/heads/master | 2021-04-18T03:36:35.353273 | 2020-04-13T13:51:20 | 2020-04-13T13:51:20 | 249,501,905 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,811 | cpp | /*
Nama :Putri Nabila
NPM : 140810180007
Kelas : A
Deskripsi : Mencari Pasangan Tititk Terdekat (Closest Pair of Points)
*/
#include <bits/stdc++.h>
using namespace std;
class Point
{
public:
int x, y;
};
int compareX(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->x - p2->x);
}
int compareY(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->y - p2->y);
}
float dist(Point p1, Point p2)
{
return sqrt( (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y)
);
}
float bruteForce(Point P[], int n)
{
float min = FLT_MAX;
for (int i = 0; i < n; ++i)
for (int j = i+1; j < n; ++j)
if (dist(P[i], P[j]) < min)
min = dist(P[i], P[j]);
return min;
}
float min(float x, float y)
{
return (x < y)? x : y;
}
float stripClosest(Point strip[], int size, float d)
{
float min = d;
qsort(strip, size, sizeof(Point), compareY);
for (int i = 0; i < size; ++i)
for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j)
if (dist(strip[i],strip[j]) < min)
min = dist(strip[i], strip[j]);
return min;
}
float closestUtil(Point P[], int n)
{
if (n <= 3)
return bruteForce(P, n);
int mid = n/2;
Point midPoint = P[mid];
float dl = closestUtil(P, mid);
float dr = closestUtil(P + mid, n - mid);
float d = min(dl, dr);
Point strip[n];
int j = 0;
for (int i = 0; i < n; i++)
if (abs(P[i].x - midPoint.x) < d)
strip[j] = P[i], j++;
return min(d, stripClosest(strip, j, d) );
}
float closest(Point P[], int n)
{
qsort(P, n, sizeof(Point), compareX);
return closestUtil(P, n);
}
int main()
{
Point P[] = {{5, 6}, {22, 30}, {45, 55}, {1, 5}, {3, 6}};
int n = sizeof(P) / sizeof(P[0]);
cout << "The smallest distance is " << closest(P, n);
return 0;
}
| [
"[email protected]"
] | |
c6aec03f1ca479d8742408b5779f25aa70a0605d | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir521/dir522/dir572/dir841/dir1543/file1624.cpp | 7ea77b3e29d07e0292fd0a31fddd5d8fc560e9b7 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | #ifndef file1624
#error "macro file1624 must be defined"
#endif
static const char* file1624String = "file1624"; | [
"[email protected]"
] | |
8c3b629975057c0d269a81d00c3d19d30bbbfb66 | 2bdca426e00b7648e1cb76432c7b9548dcfe5095 | /src/dates/yearFractions/ACT365.hpp | 22dca9ba761ee1a557f048c660d37252fa527c37 | [] | no_license | mbrzecki/julian | b6b0c7c5fdc40f2970ae9cbeed1bd12c020dae6f | 04a38f0a26a23ba8f80c879997216c22dbc81ebb | refs/heads/master | 2020-03-28T02:30:08.777303 | 2019-05-28T18:10:30 | 2019-05-28T18:10:30 | 147,575,336 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,075 | hpp | #ifndef JULIAN_ACT365_HPP
#define JULIAN_ACT365_HPP
#include <dates/yearFractions/yearFraction.hpp>
namespace julian {
/**
* @file ACT365.hpp
* @brief File contains definition of ACT365 year fraction.
*/
/** \ingroup yearfraction
* \brief The class encapsulates the ACT365 year fraction convention.
*
* According to ACT365 convention the year fraction is calculated using following formula:
* \f[YearFraction(dates_1,date_2) = \frac{\textrm{Actual number of days between } date_1 \textrm{ and } date_2}{365}\f]
* */
class ACT365: public YearFraction {
public:
ACT365(){};
virtual double operator()(const Date&,const Date&) const;
virtual ACT365* clone() const;
virtual ~ACT365(){};
virtual std::string info() const;
friend class boost::serialization::access;
private:
/** \brief interface used by Boost serialization library
*/
template<class Archive>
void serialize(Archive & , const unsigned int){
boost::serialization::base_object<YearFraction>(*this);
}
};
}
#endif
| [
"[email protected]"
] | |
bccabefb79cd8d1c9da24ff2830172f32a5f4ef3 | 948d53e43956504c0f4b78280d38f94a2cfb7b5a | /src/qt/sendcoinsentry.cpp | 033feb9eed10649f45072f11be311c6d5fe46c02 | [
"MIT"
] | permissive | Amigacoin/Amigacoin | b9bf58eedc59fea29d0d7f8b74f46ef3fdc36468 | e966b4c6981c7e6f7d6fb42dbdccc899ebc41bc6 | refs/heads/master | 2020-04-08T17:52:47.011580 | 2018-11-29T00:49:22 | 2018-11-29T00:49:22 | 159,584,441 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,613 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QFrame(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
ui->payTo->setPlaceholderText(tr("Enter a Amiga address (e.g. Aer4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)"));
#endif
setFocusPolicy(Qt::TabFocus);
setFocusProxy(ui->payTo);
GUIUtil::setupAddressWidget(ui->payTo, this);
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
if(!model)
return;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
ui->addAsLabel->setText(associatedLabel);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
clear();
}
void SendCoinsEntry::setRemoveEnabled(bool enabled)
{
ui->deleteButton->setEnabled(enabled);
}
void SendCoinsEntry::clear()
{
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->payTo->setFocus();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::on_deleteButton_clicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
// Check input validity
bool retval = true;
if(!ui->payAmount->validate())
{
retval = false;
}
else
{
if(ui->payAmount->value() <= 0)
{
// Cannot send 0 coins or less
ui->payAmount->setValid(false);
retval = false;
}
}
if(!ui->payTo->hasAcceptableInput() ||
(model && !model->validateAddress(ui->payTo->text())))
{
ui->payTo->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
SendCoinsRecipient rv;
rv.address = ui->payTo->text();
rv.label = ui->addAsLabel->text();
rv.amount = ui->payAmount->value();
return rv;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);
return ui->payAmount->setupTabChain(ui->addAsLabel);
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
ui->payTo->setText(value.address);
ui->addAsLabel->setText(value.label);
ui->payAmount->setValue(value.amount);
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
| [
"[email protected]"
] | |
dcbd57857afc54cae166abe09c482adfb885e6de | 0ad3309ea19c983090875486ca3e81aa90db06fb | /ratwin/base.h | 3c24e65414f8681dd1a2bf74665c1210da3c55b8 | [] | no_license | jdlugosz/repertoire | 82eac78f6593593da964059bc2dea3913e169472 | 7dd13cf9e7e8d23710681d64f4123067d0101601 | refs/heads/master | 2021-01-24T06:30:09.399288 | 2009-05-03T02:39:31 | 2009-05-03T02:39:31 | 191,081 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,431 | h | // The Repertoire Project copyright 2006 by John M. Dlugosz : see <http://www.dlugosz.com/Repertoire/>
// File: ratwin\base.h
// Revision: public build 9, shipped on 18-Oct-2006
#pragma once
#include "classics\common.h"
#include "classics\2D_point.h"
#include "classics\rect.h"
#if !defined RATWIN_EXPORT
#define RATWIN_EXPORT __declspec(dllimport)
#endif
namespace Dlugosz {
namespace ratwin {
namespace arg {
struct arg32_struct {/*empty*/};
typedef arg32_struct* arg32;
typedef const arg32_struct* carg32;
}
}}
STARTWRAP
namespace ratwin {
using classics::ulong;
using classics::ushort;
using classics::byte;
#if !defined DOUBLE_BAGGED
// using namespace Dlugosz;
namespace arg {
using namespace Dlugosz::ratwin::arg;
}
#endif
namespace types {
namespace internal {
struct HANDLE_struct {/*empty*/};
struct Kernel_HANDLE_struct : public HANDLE_struct {/*empty*/};
// Specializations of HANDLE that are not present in WINDOWS.H
struct Thread_HANDLE_struct : public Kernel_HANDLE_struct {/*empty*/};
struct IO_HANDLE_struct : public Kernel_HANDLE_struct {/*empty*/};
struct Heap_struct : public HANDLE_struct { /*empty*/ };
struct SOCKET_struct : public IO_HANDLE_struct {/*empty*/};
struct HWND_struct : public HANDLE_struct {/*empty*/};
struct HGDIOBJ_struct : public HANDLE_struct {/*empty*/};
struct HBITMAP_struct : public HGDIOBJ_struct {/*empty*/};
struct HBRUSH_struct : public HGDIOBJ_struct {/*empty*/};
struct HPEN_struct : public HGDIOBJ_struct {/*empty*/};
struct HFONT_struct : public HGDIOBJ_struct {/*empty*/};
struct HREGION_struct : public HGDIOBJ_struct {/*empty*/};
struct HKEY_struct : public HANDLE_struct {/*empty*/};
struct HMENU_struct : public HANDLE_struct {/*empty*/};
struct HICON_struct : public HANDLE_struct {/*empty*/};
struct HCURSOR_struct : public HANDLE_struct {/*empty*/};
// don't know what they're related to yet...
struct HINSTANCE_struct : public HANDLE_struct {/*empty*/};
struct HDC_struct : public HANDLE_struct {/*empty*/};
struct HRSRC_struct : public HANDLE_struct {/*empty*/};
// other handle-like things that don't map directly to Windows.H
struct TLS_key_struct : public HANDLE_struct {/*empty*/};
struct PROPSHEETPAGE_struct : public HANDLE_struct {/*empty*/};
} //end of internal
typedef internal::HANDLE_struct* HANDLE;
typedef internal::Kernel_HANDLE_struct* Kernel_HANDLE;
typedef internal::IO_HANDLE_struct* IO_HANDLE; // one that works with ReadFile, WriteFile, etc.
typedef internal::Heap_struct* Heap;
typedef internal::SOCKET_struct* SOCKET;
typedef internal::HWND_struct* HWND;
typedef internal::HINSTANCE_struct* HINSTANCE;
typedef internal::HINSTANCE_struct* HMODULE; //module and instance are same thing
typedef internal::HBITMAP_struct* HBITMAP;
typedef internal::HMENU_struct* HMENU;
typedef internal::HDC_struct* HDC;
typedef internal::HGDIOBJ_struct* HGDIOBJ;
typedef internal::HICON_struct* HICON;
typedef internal::HCURSOR_struct* HCURSOR;
typedef internal::HBRUSH_struct* HBRUSH;
typedef internal::HPEN_struct* HPEN;
typedef internal::HFONT_struct* HFONT;
typedef internal::HREGION_struct* HREGION;
typedef internal::HRSRC_struct* HRSRC;
typedef internal::Thread_HANDLE_struct* Thread_HANDLE;
typedef internal::TLS_key_struct* TLS_key;
typedef internal::HKEY_struct* HKEY;
typedef internal::PROPSHEETPAGE_struct* HPROPSHEETPAGE;
// hsoft<Hwhatever> allows me to define an "in" parameter that accepts
// a strictly-typed Handle subtype, or a plain HANDLE, but not the =wrong=
// strictly-typed Handle.
template <typename T>
struct hsoft {
arg::arg32 value;
hsoft (T param) : value (reinterpret_cast<arg::arg32>(param)) {}
hsoft (HANDLE param) : value (reinterpret_cast<arg::arg32>(param)) {}
};
typedef unsigned short ATOM;
typedef unsigned short LCID;
typedef classics::generic_2D_point<int> POINT;
/*
struct RECT {
long left;
long top;
long right;
long bottom;
};
*/
typedef classics::generic_rect<int> RECT;
struct SECURITY_ATTRIBUTES {
ulong nLength;
void* lpSecurityDescriptor;
bool bInheritHandle;
};
struct security_attributes : public SECURITY_ATTRIBUTES {
security_attributes() { nLength= sizeof(SECURITY_ATTRIBUTES); lpSecurityDescriptor=0; bInheritHandle=false; }
};
// idea: (unsigned wMsg, long lEvent) can also be made strict
} // end of types
} // end of ratwin
ENDWRAP
| [
"[email protected]"
] | |
dbe5dea10c9d3b1fd2c83bd781e1fa66b18934e7 | 6ba282cb7f6dac22858344cec9b5da47d2bfc7fd | /src/common/common.hpp | c8789fcd439bccc0cb2527687c15e7757c340f1e | [] | no_license | vaginessa/ConEmu | 1dd8b6c42428f83a5165e0ea6b4c38c1f9b0d9c5 | 8cfea41511585f88a714b6364d341b61661697d2 | refs/heads/master | 2021-01-14T11:43:51.864153 | 2014-12-16T22:39:00 | 2014-12-16T22:39:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 87,378 | hpp |
/*
Copyright (c) 2009-2014 Maximus5
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors 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 _COMMON_HEADER_HPP_
#define _COMMON_HEADER_HPP_
// Interface version
#define CESERVER_REQ_VER 149
// Max tabs/panes count
#define MAX_CONSOLE_COUNT 30
#include "defines.h"
#include "ConEmuColors.h"
#ifndef _DEBUG
//PRAGMA_ERROR("MIN_CON_WIDTH & MIN_CON_HEIGHT - remake for Far Panels")
#endif
//#define MIN_CON_WIDTH 28
//#define MIN_CON_HEIGHT 7
#define MIN_CON_WIDTH 4
#define MIN_CON_HEIGHT 2
#define DEF_CON_WIDTH RELEASEDEBUGTEST(80,110)
#define DEF_CON_HEIGHT RELEASEDEBUGTEST(25,35)
#define GUI_ATTACH_TIMEOUT 5000
#define CONSOLE_PROCESSES_MAX 20
#ifndef CONSOLE_NO_SELECTION
typedef struct _CONSOLE_SELECTION_INFO
{
DWORD dwFlags;
COORD dwSelectionAnchor;
SMALL_RECT srSelection;
} CONSOLE_SELECTION_INFO, *PCONSOLE_SELECTION_INFO;
#endif
#ifndef _CRT_WIDE
#define __CRT_WIDE(_String) L ## _String
#define _CRT_WIDE(_String) __CRT_WIDE(_String)
#endif
//#define MAXCONMAPCELLS (600*400)
#define CES_NTVDM 0x10
#define CEC_INITTITLE L"ConEmu"
#define VirtualConsoleClass L"VirtualConsoleClass" // окна отрисовки
#define VirtualConsoleClassMain L"VirtualConsoleClass" // главное окно
#define VirtualConsoleClassApp L"VirtualConsoleClassApp" // специальный Popup (не используется)
#define VirtualConsoleClassWork L"VirtualConsoleClassWork" // Holder для всех VCon
#define VirtualConsoleClassBack L"VirtualConsoleClassBack" // Подложка (со скроллерами) для каждого VCon
#define VirtualConsoleClassGhost L"VirtualConsoleClassGhost"
#define ConEmuPanelViewClass L"ConEmuPanelView"
#define RealConsoleClass L"ConsoleWindowClass"
#define WineConsoleClass L"WineConsoleClass"
#define isConsoleClass(sClass) (lstrcmp(sClass, RealConsoleClass)==0 || lstrcmp(sClass, WineConsoleClass)==0)
// Some ANSI & Controls
#define DSC 0x90
#define ESC 0x1B
#define ENQ 0x05
#define BEL 0x07
#define CTRL(x) ((x)&0x1F)
#define CECOPYRIGHTSTRING_A "(c) 2009-2014, [email protected]"
#define CECOPYRIGHTSTRING_W L"© 2009-2014 [email protected]"
#define CEHOMEPAGE_A "http://code.google.com/p/conemu-maximus5"
#define CEHOMEPAGE _CRT_WIDE(CEHOMEPAGE_A)
#define CEDOWNLPAGE L"http://www.fosshub.com/ConEmu.html"
#define CEREPORTBUG L"http://code.google.com/p/conemu-maximus5/wiki/Issues?tm=3"
#define CEREPORTCRASH L"http://code.google.com/p/conemu-maximus5/wiki/Issues?tm=3"
#define CEWHATSNEW L"http://code.google.com/p/conemu-maximus5/wiki/Whats_New"
#define CEMSBUGWIKI L"http://code.google.com/p/conemu-maximus5/wiki/MicrosoftBugs"
#define CEHOOKSWIKI L"http://code.google.com/p/conemu-maximus5/wiki/ConEmuHk"
#define CEDONATEPAGE L"http://conemu.github.io/donate.html"
#define CEFLATTRPAGE L"http://flattr.com/thing/2002773/Maximus5ConEmu-on-GitHub"
// EnvVars
#define ENV_CONEMUDIR_VAR_A "ConEmuDir"
#define ENV_CONEMUDIR_VAR_W _CRT_WIDE(ENV_CONEMUDIR_VAR_A)
#define ENV_CONEMUBASEDIR_VAR_A "ConEmuBaseDir"
#define ENV_CONEMUBASEDIR_VAR_W _CRT_WIDE(ENV_CONEMUBASEDIR_VAR_A)
#define ENV_CONEMUWORKDIR_VAR_A "ConEmuWorkDir"
#define ENV_CONEMUWORKDIR_VAR_W _CRT_WIDE(ENV_CONEMUWORKDIR_VAR_A)
#define ENV_CONEMUDRIVE_VAR_A "ConEmuDrive"
#define ENV_CONEMUDRIVE_VAR_W _CRT_WIDE(ENV_CONEMUDRIVE_VAR_A)
#define ENV_CONEMUWORKDRIVE_VAR_A "ConEmuWorkDrive"
#define ENV_CONEMUWORKDRIVE_VAR_W _CRT_WIDE(ENV_CONEMUWORKDRIVE_VAR_A)
#define ENV_CONEMUHWND_VAR_A "ConEmuHWND"
#define ENV_CONEMUHWND_VAR_W _CRT_WIDE(ENV_CONEMUHWND_VAR_A)
#define ENV_CONEMUPID_VAR_A "ConEmuPID"
#define ENV_CONEMUPID_VAR_W _CRT_WIDE(ENV_CONEMUPID_VAR_A)
#define ENV_CONEMUSERVERPID_VAR_A "ConEmuServerPID"
#define ENV_CONEMUSERVERPID_VAR_W _CRT_WIDE(ENV_CONEMUSERVERPID_VAR_A)
#define ENV_CONEMUDRAW_VAR_A "ConEmuDrawHWND"
#define ENV_CONEMUDRAW_VAR_W _CRT_WIDE(ENV_CONEMUDRAW_VAR_A)
#define ENV_CONEMUBACK_VAR_A "ConEmuBackHWND"
#define ENV_CONEMUBACK_VAR_W _CRT_WIDE(ENV_CONEMUBACK_VAR_A)
#define ENV_CONEMUANSI_VAR_A "ConEmuANSI"
#define ENV_CONEMUANSI_VAR_W _CRT_WIDE(ENV_CONEMUANSI_VAR_A)
#define ENV_CONEMUANSILOG_VAR_A "ConEmuAnsiLog"
#define ENV_CONEMUANSILOG_VAR_W _CRT_WIDE(ENV_CONEMUANSILOG_VAR_A)
#define ENV_CONEMUFAKEDT_VAR_A "ConEmuFakeDT"
#define ENV_CONEMUFAKEDT_VAR_W _CRT_WIDE(ENV_CONEMUFAKEDT_VAR_A)
#define ENV_CONEMU_BUILD_A "ConEmuBuild"
#define ENV_CONEMU_BUILD_W _CRT_WIDE(ENV_CONEMU_BUILD_A)
#define ENV_CONEMU_CONFIG_A "ConEmuConfig"
#define ENV_CONEMU_CONFIG_W _CRT_WIDE(ENV_CONEMU_CONFIG_A)
#define ENV_CONEMU_ISADMIN_A "ConEmuIsAdmin"
#define ENV_CONEMU_ISADMIN_W _CRT_WIDE(ENV_CONEMU_ISADMIN_A)
#define ENV_CONEMU_WAITKEY_A "ConEmuWaitKey"
#define ENV_CONEMU_WAITKEY_W _CRT_WIDE(ENV_CONEMU_WAITKEY_A)
#define ENV_CONEMUREPORTEXE_VAR_A "ConEmuReportExe"
#define ENV_CONEMUREPORTEXE_VAR_W _CRT_WIDE(ENV_CONEMUREPORTEXE_VAR_A)
// Modifies behavior of starting processes inside ConEmu tab
#define ENV_CONEMU_HOOKS_A "ConEmuHooks"
#define ENV_CONEMU_HOOKS_W _CRT_WIDE(ENV_CONEMU_HOOKS_A)
#define ENV_CONEMU_HOOKS_ENABLED L"Enabled" // Informational
#define ENV_CONEMU_HOOKS_DISABLED L"OFF" // don't set hooks from "ConEmuHk.dll"
#define ENV_CONEMU_HOOKS_NOARGS L"NOARG" // don't process -new_console & -cur_console arguments
#define ENV_CONEMU_HOOKS_NOSTART L"NOSTART" // don't use "start xxx.exe" to start new tab
// This is set to "YES" during AutoUpdate script execution
#define ENV_CONEMU_INUPDATE_A "ConEmuInUpdate"
#define ENV_CONEMU_INUPDATE_W _CRT_WIDE(ENV_CONEMU_INUPDATE_A)
#define ENV_CONEMU_INUPDATE_YES L"YES" // This is set to "YES" during AutoUpdate script execution
// When ConEmuC tries to debug process tree - force disable DEBUG_PROCESS/DEBUG_ONLY_THIS_PROCESS flags when creating subchildren
#define ENV_CONEMU_BLOCKCHILDDEBUGGERS_A "ConEmuBlockChildDebuggers"
#define ENV_CONEMU_BLOCKCHILDDEBUGGERS_W _CRT_WIDE(ENV_CONEMU_BLOCKCHILDDEBUGGERS_A)
#define ENV_CONEMU_BLOCKCHILDDEBUGGERS_YES L"YES"
// Used internally
#define ENV_CONEMU_MONITOR_INTERNAL_A "ConEmuMonitorThreadId"
#define ENV_CONEMU_MONITOR_INTERNAL_W _CRT_WIDE(ENV_CONEMU_MONITOR_INTERNAL_A)
// Don't forget add exclusion to IsExportEnvVarAllowed
#define ENV_CONEMU_SLEEP_INDICATE_A "ConEmuSleepIndicator"
#define ENV_CONEMU_SLEEP_INDICATE_W _CRT_WIDE(ENV_CONEMU_SLEEP_INDICATE_A)
#define ENV_CONEMU_SLEEP_INDICATE_NUM L"NUM"
#define ENV_CONEMU_SLEEP_INDICATE_TTL L"TITLE"
#define CONEMU_CONHOST_CREATED_MSG L"ConEmu: ConHost was created PID=" // L"%u\n"
//#define CE_CURSORUPDATE L"ConEmuCursorUpdate%u" // ConEmuC_PID - изменился курсор (размер или выделение). положение курсора отслеживает GUI
// Pipe name formats
#define CESERVERPIPENAME L"\\\\%s\\pipe\\ConEmuSrv%u" // ConEmuC_PID
#define CESERVERINPUTNAME L"\\\\%s\\pipe\\ConEmuSrvInput%u" // ConEmuC_PID
#define CESERVERQUERYNAME L"\\\\%s\\pipe\\ConEmuSrvQuery%u" // ConEmuC_PID
#define CESERVERWRITENAME L"\\\\%s\\pipe\\ConEmuSrvWrite%u" // ConEmuC_PID
#define CESERVERREADNAME L"\\\\%s\\pipe\\ConEmuSrvRead%u" // ConEmuC_PID
#define CEGUIPIPENAME L"\\\\%s\\pipe\\ConEmuGui.%08X" // GetConsoleWindow() // необходимо, чтобы плагин мог общаться с GUI
// ghConEmuWndRoot --> CConEmuMain::GuiServerThreadCommand
#define CEPLUGINPIPENAME L"\\\\%s\\pipe\\ConEmuPlugin%u" // Far_PID
#define CEHOOKSPIPENAME L"\\\\%s\\pipe\\ConEmuHk%u" // PID процесса, в котором крутится Pipe
#define CEINPUTSEMAPHORE L"ConEmuInputSemaphore.%08X" // GetConsoleWindow()
// Mapping name formats
#define CEGUIINFOMAPNAME L"ConEmuGuiInfoMapping.%u" // --> ConEmuGuiMapping ( % == dwGuiProcessId )
#define CECONMAPNAME L"ConEmuFileMapping.%08X" // --> CESERVER_CONSOLE_MAPPING_HDR ( % == (DWORD)ghConWnd )
#define CECONMAPNAME_A "ConEmuFileMapping.%08X" // --> CESERVER_CONSOLE_MAPPING_HDR ( % == (DWORD)ghConWnd ) simplifying ansi
#define CECONAPPMAPNAME L"ConEmuAppMapping.%08X" // --> CESERVER_CONSOLE_APP_MAPPING ( % == (DWORD)ghConWnd )
#define CEFARMAPNAME L"ConEmuFarMapping.%u" // --> CEFAR_INFO_MAPPING ( % == nFarPID )
#define CECONVIEWSETNAME L"ConEmuViewSetMapping.%u" // --> PanelViewSetMapping
//#ifdef _DEBUG
#define CEPANELDLGMAPNAME L"ConEmuPanelViewDlgsMapping.%u" // -> DetectedDialogs ( % == nFarPID )
//#endif
#define CECONOUTPUTNAME L"ConEmuLastOutputMapping.%08X" // --> CESERVER_CONSAVE_MAPHDR ( %X == (DWORD)ghConWnd )
#define CECONOUTPUTITEMNAME L"ConEmuLastOutputMapping.%08X.%u" // --> CESERVER_CONSAVE_MAP ( %X == (DWORD)ghConWnd, %u = CESERVER_CONSAVE_MAPHDR.nCurrentIndex )
// Default terminal hook module name
#define CEDEFTERMDLLFORMAT L"ConEmuHk%s.%02u%02u%02u%s.dll"
#define CEDEFAULTTERMHOOK L"ConEmuDefaultTerm.%u" // Если Event взведен - нужно загрузить хуки в процесс только для перехвата запуска консольных приложений
#define CEDEFAULTTERMHOOKOK L"ConEmuDefaultTermOK.%u" // Взводится в ConEmuHk когда инициализация DefTerm началась (CEDEFAULTTERMHOOK больше не нужен)
#define CEDEFAULTTERMBEGIN L"ConEmuDefTermProc.%u" // Мутекс создается перед началом установки хуков, чтобы не дрались разные процессы-установщики
#define CEDEFAULTTERMHOOKWAIT 0 // Don't need timeout, because we wait for remote thread - WaitForSingleObject(hThread, INFINITE);
//#define CEDEFAULTTERMMUTEX L"IsConEmuDefaultTerm.%u" // Если Mutex есть - значит какая-то версия длл-ки уже была загружена в обрабатываемый процесс
// File name format for AnsiLog
#define CEANSILOGNAMEFMT L"ConEmu-%u-%02u-%02u-p%u.log"
// Events
#define CEDATAREADYEVENT L"ConEmuSrvDataReady.%u"
#define CEFARWRITECMTEVENT L"ConEmuSrvFarWriteCommit.%u"
#define CECURSORCHANGEEVENT L"ConEmuSrvCursorChanged.%u"
#define CEFARALIVEEVENT L"ConEmuFarAliveEvent.%u"
//#define CECONMAPNAMESIZE (sizeof(CESERVER_REQ_CONINFO)+(MAXCONMAPCELLS*sizeof(CHAR_INFO)))
//#define CEGUIATTACHED L"ConEmuGuiAttached.%u"
#define CEGUIRCONSTARTED L"ConEmuGuiRConStarted.%u"
#define CEGUI_ALIVE_EVENT L"ConEmuGuiStarted"
#define CESRVSTARTEDEVENT L"ConEmuSrvStarted.%u" // %u==ServerPID
#define CEKEYEVENT_CTRL L"ConEmuCtrlPressed.%u"
#define CEKEYEVENT_SHIFT L"ConEmuShiftPressed.%u"
#define CEHOOKLOCKMUTEX L"ConEmuHookMutex.%u"
//#define CEHOOKDISABLEEVENT L"ConEmuSkipHooks.%u"
#define CEGHOSTSKIPACTIVATE L"ConEmuGhostActivate.%u"
#define CECONEMUROOTPROCESS L"ConEmuRootProcess.%u" // Если Event взведен - значит это корневой процесс, облегченную версию хуков не использовать!
#define CECONEMUROOTTHREAD L"ConEmuRootThread.%u" // Если Event взведен - ConEmuHk загружен в главной нити, гонять snapshot в GetMainThreadId не требуется
#define CESECURITYNAME "ConEmuLocalData"
//#define CONEMUMSG_ATTACH L"ConEmuMain::Attach" // wParam == hConWnd, lParam == ConEmuC_PID
//WARNING("CONEMUMSG_SRVSTARTED нужно переделать в команду пайпа для GUI");
//#define CONEMUMSG_SRVSTARTED L"ConEmuMain::SrvStarted" // wParam == hConWnd, lParam == ConEmuC_PID
//#define CONEMUMSG_SETFOREGROUND L"ConEmuMain::SetForeground" // wParam == hConWnd, lParam == ConEmuC_PID
#define CONEMUMSG_FLASHWINDOW L"ConEmuMain::FlashWindow"
//#define CONEMUCMDSTARTED L"ConEmuMain::CmdStarted" // wParam == hConWnd, lParam == ConEmuC_PID (as ComSpec)
//#define CONEMUCMDSTOPPED L"ConEmuMain::CmdTerminated" // wParam == hConWnd, lParam == ConEmuC_PID (as ComSpec)
//#define CONEMUMSG_LLKEYHOOK L"ConEmuMain::LLKeyHook" // wParam == hConWnd, lParam == ConEmuC_PID
#define CONEMUMSG_ACTIVATECON L"ConEmuMain::ActivateCon" // wParam == ConNumber (1..12)
#define CONEMUMSG_SWITCHCON L"ConEmuMain::SwitchCon"
#define CONEMUMSG_HOOKEDKEY L"ConEmuMain::HookedKey"
#define CONEMUMSG_CONSOLEHOOKEDKEY L"ConEmuMain::ConsoleHookedKey"
#define CONEMUMSG_PNLVIEWFADE L"ConEmuTh::Fade"
#define CONEMUMSG_PNLVIEWSETTINGS L"ConEmuTh::Settings"
#define PNLVIEWMAPCOORD_TIMEOUT 1000
#define CONEMUMSG_PNLVIEWMAPCOORD L"ConEmuTh::MapCoords"
//#define CONEMUMSG_PNLVIEWLBTNDOWN L"ConEmuTh::LBtnDown"
#define CONEMUMSG_RESTORECHILDFOCUS L"ConEmu::RestoreChildFocus"
// Команды из плагина ConEmu и для GUI Macro
enum ConEmuTabCommand
{
// Эти команды приходят из плагина ConEmu
ctc_ShowHide = 0,
ctc_SwitchCommit = 1,
ctc_SwitchNext = 2,
ctc_SwitchPrev = 3,
// Далее идут параметры только для GUI Macro
ctc_SwitchDirect = 4,
ctc_SwitchRecent = 5,
ctc_SwitchConsoleDirect = 6,
ctc_ActivateConsole = 7,
ctc_ShowTabsList = 8,
ctc_CloseTab = 9,
ctc_SwitchPaneDirect = 10,
};
enum ConEmuStatusCommand
{
csc_ShowHide = 0,
csc_SetStatusText = 1,
};
enum ConEmuWindowCommand
{
cwc_Current = 0,
cwc_Restore = 1, // wmNormal
cwc_Minimize = 2, // SC_MINIMIZE
cwc_MinimizeTSA = 3, // HideWindowToTray
cwc_Maximize = 4, // wmMaximized
cwc_FullScreen = 5, // wmFullScreen
cwc_TileLeft = 6, // Same as Win+Left in Win7
cwc_TileRight = 7, // Same as Win+Right in Win7
cwc_TileHeight = 8, // Same as Win+Shift+Up in Win7
cwc_PrevMonitor = 9, // Same as Win+Shift+Left in Win7
cwc_NextMonitor = 10, // Same as Win+Shift+Right in Win7
cwc_TileWidth = 11, // Maximize width (no analogue yet)
// for comparison
cwc_LastCmd
};
enum CONSOLE_KEY_ID
{
ID_ALTTAB,
ID_ALTESC,
ID_ALTSPACE,
ID_ALTENTER,
ID_ALTPRTSC,
ID_PRTSC,
ID_CTRLESC,
};
#define EvalBufferTurnOnSize(Now) (2*Now+32)
enum RealBufferScroll
{
rbs_None = 0,
rbs_Vert = 1,
rbs_Horz = 2,
rbs_Any = 3,
};
// Generally used for control keys (arrows e.g.) translation
enum TermEmulationType
{
te_win32 = 0,
te_xterm = 1,
};
//#define CONEMUMAPPING L"ConEmuPluginData%u"
//#define CONEMUDRAGFROM L"ConEmuDragFrom%u"
//#define CONEMUDRAGTO L"ConEmuDragTo%u"
//#define CONEMUREQTABS L"ConEmuReqTabs%u"
//#define CONEMUSETWINDOW L"ConEmuSetWindow%u"
//#define CONEMUPOSTMACRO L"ConEmuPostMacro%u"
//#define CONEMUDEFFONT L"ConEmuDefFont%u"
//#define CONEMULANGCHANGE L"ConEmuLangChange%u"
//#define CONEMUEXIT L"ConEmuExit%u"
//#define CONEMUALIVE L"ConEmuAlive%u"
//#define CONEMUREADY L"ConEmuReady%u"
#define CONEMUTABCHANGED L"ConEmuTabsChanged"
#define VIRTUAL_REGISTRY_GUID L"{16B56CA5-F8D2-4EEA-93DC-32403C7355E1}"
#define VIRTUAL_REGISTRY_GUID_A "{16B56CA5-F8D2-4EEA-93DC-32403C7355E1}"
#define VIRTUAL_REGISTRY_ROOT L"Software\\ConEmu Virtual Registry"
//#define CESIGNAL_C L"ConEmuC_C_Signal.%u"
//#define CESIGNAL_BREAK L"ConEmuC_Break_Signal.%u"
typedef DWORD CECMD;
const CECMD
// CECMD_CONSOLEINFO = 1,
CECMD_CONSOLEDATA = 2,
CECMD_CONSOLEFULL = 3,
CECMD_CMDSTARTSTOP = 4, // CESERVER_REQ_STARTSTOP //-V112
// CECMD_GETGUIHWND = 5, // GUI_CMD, In = {}, Out = {dwData[0]==ghWnd, dwData[1]==ConEmuDcWindow
// CECMD_RECREATE = 6,
CECMD_TABSCHANGED = 7,
CECMD_CMDSTARTED = 8, // == CECMD_SETSIZE + восстановить содержимое консоли (запустился comspec)
CECMD_CMDFINISHED = 9, // == CECMD_SETSIZE + сохранить содержимое консоли (завершился comspec)
CECMD_GETOUTPUTFILE = 10, // Записать вывод последней консольной программы во временный файл и вернуть его имя
// CECMD_GETOUTPUT = 11,
CECMD_LANGCHANGE = 12,
CECMD_NEWCMD = 13, // CESERVER_REQ_NEWCMD, Запустить в этом экземпляре новую консоль с переданной командой (используется при SingleInstance и -new_console). Выполняется в GUI!
CECMD_TABSCMD = 14, // enum ConEmuTabCommand: 0: спрятать/показать табы, 1: перейти на следующую, 2: перейти на предыдущую, 3: commit switch
CECMD_RESOURCES = 15, // Посылается плагином при инициализации (установка ресурсов)
// CECMD_GETNEWCONPARM = 16, // Доп.аргументы для создания новой консоли (шрифт, размер,...)
CECMD_SETSIZESYNC = 17, // Синхронно, ждет (но недолго), пока FAR обработает изменение размера (то есть отрисуется)
CECMD_ATTACH2GUI = 18, // (a. GUI|Plugin->SRV) Выполнить подключение видимой (отключенной) консоли к GUI. Без аргументов.
// (b. SRV->GUI) Запрос GUI на вкладку для сервера [IN] CESERVER_REQ_STARTSTOP, [OUT] CESERVER_REQ_STARTSTOPRET.
CECMD_FARLOADED = 19, // Посылается плагином в сервер
// CECMD_SHOWCONSOLE = 20, // В Win7 релизе нельзя скрывать окно консоли, запущенной в режиме администратора -- заменено на CECMD_POSTCONMSG & CECMD_SETWINDOWPOS
CECMD_POSTCONMSG = 21, // В Win7 релизе нельзя посылать сообщения окну консоли, запущенной в режиме администратора
// CECMD_REQUESTCONSOLEINFO = 22, // было CECMD_REQUESTFULLINFO
CECMD_SETFOREGROUND = 23,
CECMD_FLASHWINDOW = 24, // CESERVER_REQ_FLASHWINFO
// CECMD_SETCONSOLECP = 25,
CECMD_SAVEALIASES = 26,
CECMD_GETALIASES = 27,
CECMD_SETSIZENOSYNC = 28, // Почти CECMD_SETSIZE. Вызывается из плагина.
CECMD_FARDETACHED = 29,
CECMD_REGPANELVIEW = 30,
CECMD_ONACTIVATION = 31, // Для установки флажка ConsoleInfo->bConsoleActive
CECMD_SETWINDOWPOS = 32, // CESERVER_REQ_SETWINDOWPOS. //-V112
CECMD_SETWINDOWRGN = 33, // CESERVER_REQ_SETWINDOWRGN.
CECMD_SETBACKGROUND = 34, // CESERVER_REQ_SETBACKGROUND
CECMD_ACTIVATECON = 35, // CESERVER_REQ_ACTIVATECONSOLE
// CECMD_ONSERVERCLOSE = 35, // Посылается из ConEmuC*.exe перед закрытием в режиме сервера
CECMD_DETACHCON = 36,
CECMD_GUIMACRO = 38, // CESERVER_REQ_GUIMACRO. Найти в других консолях редактор/вьювер
CECMD_ONCREATEPROC = 39, // CESERVER_REQ_ONCREATEPROCESS
CECMD_SRVSTARTSTOP = 40, // {DWORD(1/101); DWORD(ghConWnd);}
CECMD_SETFARPID = 41, // Посылается в сервер, чтобы он сменил (CESERVER_CONSOLE_MAPPING_HDR.nFarPID)
CECMD_ASSERT = 42, // Отобразить Assert в ConEmu. In=wchar_t[], Out=DWORD.
CECMD_GUICHANGED = 43, // посылается в сервер, чтобы он обновил у себя ConEmuGuiMapping->CESERVER_CONSOLE_MAPPING_HDR
CECMD_PEEKREADINFO = 44, // CESERVER_REQ_PEEKREADINFO: посылается в GUI на вкладку Debug
CECMD_TERMINATEPID = 45,
CECMD_ATTACHGUIAPP = 46, // CESERVER_REQ_ATTACHGUIAPP
CECMD_KEYSHORTCUTS = 47, // BYTE Data[2]; SetConsoleKeyShortcuts from kernel32.dll
CECMD_SETFOCUS = 48, // CESERVER_REQ_SETFOCUS
CECMD_SETPARENT = 49, // CESERVER_REQ_SETPARENT
CECMD_CTRLBREAK = 50, // GenerateConsoleCtrlEvent(dwData[0], dwData[1])
// CECMD_GETCGUINFO = 51, // ConEmuGuiMapping
CECMD_SETGUIEXTERN = 52, // dwData[0]==TRUE - вынести приложение наружу из вкладки ConEmu, dwData[0]==FALSE - вернуть во вкладку
CECMD_ALIVE = 53, // просто проверка
CECMD_STARTSERVER = 54, // CESERVER_REQ_START. Запустить в консоли ConEmuC.exe в режиме сервера
CECMD_LOCKDC = 55, // CESERVER_REQ_LOCKDC
#ifdef USE_COMMIT_EVENT
CECMD_REGEXTCONSOLE = 56, // CESERVER_REQ_REGEXTCON. Регистрация процесса, использующего ExtendedConsole.dll
#endif
CECMD_GETALLTABS = 57, // CESERVER_REQ_GETALLTABS. Вернуть список всех табов, для показа в Far и использовании в макросах.
CECMD_ACTIVATETAB = 58, // dwData[0]=0-based console, dwData[1]=0-based tab number
CECMD_FREEZEALTSRV = 59, // dwData[0]=1-Freeze, 0-Thaw; dwData[1]=New Alt server PID
CECMD_SETFULLSCREEN = 60, // SetConsoleDisplayMode(CONSOLE_FULLSCREEN_MODE) -> CESERVER_REQ_FULLSCREEN
CECMD_MOUSECLICK = 61, // CESERVER_REQ_PROMPTACTION - обработка клика, если консоль в ReadConsoleW
CECMD_PROMPTCMD = 62, // wData - это LPCWSTR (GUI -> ConEmuHk)
CECMD_SETTABTITLE = 63, // wData - это LPCWSTR, посылается в GUI
CECMD_SETPROGRESS = 64, // wData[0]: 0 - remove, 1 - set, 2 - error. Для "1": wData[1] - 0..100%.
CECMD_SETCONCOLORS = 65, // CESERVER_REQ_SETCONSOLORS
CECMD_SETCONTITLE = 66, // wData - это LPCWSTR, посылается в Server
CECMD_EXPORTVARS = 67, // wData - same as GetEnvironmentStringsW returns, but may be less (selected vars only)
CECMD_EXPORTVARSALL = 68, // same as CECMD_EXPORTVARS, but apply environment to all tabs
CECMD_DUPLICATE = 69, // CESERVER_REQ_DUPLICATE. sent to root console process (cmd, far, powershell), processed with ConEmuHk - Create new tab reproducing current state.
CECMD_BSDELETEWORD = 70, // CESERVER_REQ_PROMPTACTION - default action for Ctrl+BS (prompt) - delete word to the left of the cursor
CECMD_GUICLIENTSHIFT = 71, // GuiStylesAndShifts
CECMD_ALTBUFFER = 72, // CESERVER_REQ_ALTBUFFER: CmdOutputStore/Restore
CECMD_ALTBUFFERSTATE = 73, // Проверить, разрешен ли Alt.Buffer?
CECMD_STARTXTERM = 74, // dwData[0]=bool, start/stop xterm input
//CECMD_DEFTERMSTARTED = 75, // Уведомить GUI, что инициализация хуков для Default Terminal была завершена -- не требуется, ConEmuC ждет успеха
CECMD_UPDCONMAPHDR = 76, // AltServer не может менять CESERVER_CONSOLE_MAPPING_HDR во избежание конфликтов. Это делает только RM_MAINSERVER (req.ConInfo)
CECMD_SETCONSCRBUF = 77, // CESERVER_REQ_SETCONSCRBUF - temporarily block active server reading thread to change console buffer size
CECMD_PORTABLESTART = 78, // CESERVER_REQ_PORTABLESTARTED - used when XxxPortable.exe starts Xxx.exe (paf - kitty, tcc, etc.)
CECMD_STORECURDIR = 79, // CESERVER_REQ_STORECURDIR <== GetCurrentDirectory()
CECMD_GETALLPANELS = 80, // Result ==> CESERVER_REQ_GETALLPANELS
CECMD_SETTOPLEFT = 81, // CESERVER_REQ_CONINFO
CECMD_PROMPTSTARTED = 82, // CESERVER_PROMPTSTARTED (ConEmuHk -> Server)
CECMD_QUERYPALETTE = 83, // CESERVER_PALETTE
/** Команды FAR плагина **/
CMD_FIRST_FAR_CMD = 200,
CMD_DRAGFROM = 200,
CMD_DRAGTO = 201,
CMD_REQTABS = 202,
CMD_SETWINDOW = 203,
CMD_POSTMACRO = 204, // Если первый символ макроса '@' и после него НЕ пробел - макрос выполняется в DisabledOutput
// CMD_DEFFONT = 205,
CMD_LANGCHANGE = 206,
CMD_FARSETCHANGED = 207, // Изменились настройки для фара (isFARuseASCIIsort, isShellNoZoneCheck, ...)
// CMD_SETSIZE = 208,
CMD_EMENU = 209,
CMD_LEFTCLKSYNC = 210,
CMD_REDRAWFAR = 211,
CMD_FARPOST = 212,
CMD_CHKRESOURCES = 213,
// CMD_QUITFAR = 214, // Дернуть завершение консоли (фара?)
CMD_CLOSEQSEARCH = 215,
// CMD_LOG_SHELL = 216,
CMD_SET_CON_FONT = 217, // CESERVER_REQ_SETFONT
CMD_GUICHANGED = 218, // CESERVER_REQ_GUICHANGED. изменились настройки GUI (шрифт), размер окна ConEmu, или еще что-то
CMD_ACTIVEWNDTYPE = 219, // ThreadSafe - получить информацию об активном окне (его типе) в Far
CMD_OPENEDITORLINE = 220, // CESERVER_REQ_FAREDITOR. Открыть в редакторе файл и перейти на строку (обработка ошибок компилятора)
CMD_LAST_FAR_CMD = CMD_OPENEDITORLINE;
#define PIPEBUFSIZE 4096
#define DATAPIPEBUFSIZE 40000
// Console Undocumented
#define MOD_LALT 0x0010
#define MOD_RALT 0x0020
#define MOD_LCONTROL 0x0040
#define MOD_RCONTROL 0x0080
typedef DWORD ConEmuModifiers;
const ConEmuModifiers
// Для удобства, в младшем байте VkMod хранится VK кнопки
cvk_VK_MASK = 0x000000FF,
// Модификаторы, которые юзер просил различать, правый или левый
cvk_LCtrl = 0x00000100,
cvk_RCtrl = 0x00000200,
cvk_LAlt = 0x00000400,
cvk_RAlt = 0x00000800,
cvk_LShift = 0x00001000,
cvk_RShift = 0x00002000,
// Если без разницы, правый или левый
cvk_Ctrl = 0x00010000,
cvk_Alt = 0x00020000,
cvk_Shift = 0x00040000,
cvk_Win = 0x00080000,
cvk_Apps = 0x00100000,
// Без модификатора
cvk_Naked = 0x10000000,
// Спец.модификатор
cvk_NumHost = 0x20000000,
cvk_ArrHost = 0x40000000,
// Маска всех с учетом правый/левый
cvk_CtrlAny = cvk_Ctrl|cvk_LCtrl|cvk_RCtrl,
cvk_AltAny = cvk_Alt|cvk_LAlt|cvk_RAlt,
cvk_ShiftAny = cvk_Shift|cvk_LShift|cvk_RShift,
// Маска вообще всех допустимых кнопок
cvk_ALLMASK = cvk_CtrlAny|cvk_AltAny|cvk_ShiftAny|cvk_Win|cvk_Apps,
// Empty value
cvk_NULL = 0;
// ConEmu internal virtual key codes
#define VK_WHEEL_UP 0xD0
#define VK_WHEEL_DOWN 0xD1
#define VK_WHEEL_LEFT 0xD2
#define VK_WHEEL_RIGHT 0xD3
//
#define VK_WHEEL_FIRST VK_WHEEL_UP
#define VK_WHEEL_LAST VK_WHEEL_RIGHT
//// Команды FAR плагина
//typedef DWORD FARCMD;
//const FARCMD
// CMD_DRAGFROM = 0,
// CMD_DRAGTO = 1,
// CMD_REQTABS = 2,
// CMD_SETWINDOW = 3,
// CMD_POSTMACRO = 4, // Если первый символ макроса '@' и после него НЕ пробел - макрос выполняется в DisabledOutput
//// CMD_DEFFONT = 5,
// CMD_LANGCHANGE = 6,
// CMD_FARSETCHANGED = 7, // Изменились настройки для фара (isFARuseASCIIsort, isShellNoZoneCheck, ...)
//// CMD_SETSIZE = 8,
// CMD_EMENU = 9,
// CMD_LEFTCLKSYNC = 10,
// CMD_REDRAWFAR = 11,
// CMD_FARPOST = 12,
// CMD_CHKRESOURCES = 13,
//// CMD_QUITFAR = 14, // Дернуть завершение консоли (фара?)
// CMD_CLOSEQSEARCH = 15,
//// CMD_LOG_SHELL = 16,
// CMD_SET_CON_FONT = 17, // CESERVER_REQ_SETFONT
// CMD_GUICHANGED = 18, // CESERVER_REQ_GUICHANGED. изменились настройки GUI (шрифт), размер окна ConEmu, или еще что-то
// CMD_ACTIVEWNDTYPE = 19; // ThreadSafe - получить информацию об активном окне (его типе) в Far
//// +2
// //MAXCMDCOUNT = 21;
// //CMD_EXIT = MAXCMDCOUNT-1;
//#pragma pack(push, 1)
#include <pshpack1.h>
typedef unsigned __int64 u64;
struct HWND2
{
DWORD u;
operator HWND() const
{
return (HWND)(DWORD_PTR)u; //-V204
};
operator DWORD() const
{
return (DWORD)u;
};
struct HWND2& operator=(HWND h)
{
u = (DWORD)(DWORD_PTR)h; //-V205
return *this;
};
};
// Для унификации x86/x64. Хранить здесь реальный HKEY нельзя.
// Используется только для "предопределенных" ключей типа HKEY_USERS
struct HKEY2
{
DWORD u;
operator HKEY() const
{
return (HKEY)(DWORD_PTR)(LONG)u;
};
operator DWORD() const
{
return u;
};
struct HKEY2& operator=(HKEY h)
{
//_ASSERTE(((DWORD_PTR)h) < 0x100000000LL);
u = (DWORD)(LONG)(LONG_PTR)h;
return *this;
};
};
struct HANDLE2
{
u64 u;
operator HANDLE() const
{
return (HANDLE)(DWORD_PTR)u;
};
operator DWORD_PTR() const
{
return (DWORD_PTR)u;
};
struct HANDLE2& operator=(HANDLE h)
{
u = (DWORD_PTR)h;
return *this;
};
};
struct MSG64
{
DWORD cbSize;
DWORD nCount;
struct MsgStr {
UINT message;
HWND2 hwnd;
u64 wParam;
u64 lParam;
} msg[1];
};
struct ThumbColor
{
union
{
struct
{
unsigned int ColorRGB : 24;
unsigned int ColorIdx : 5; // 5 bits, to support value '16' - automatic use of panel color
unsigned int UseIndex : 1; // TRUE - Use ColorRef, FALSE - ColorIdx
};
DWORD RawColor;
};
};
struct ThumbSizes
{
// сторона превьюшки или иконки
int nImgSize; // Thumbs: 96, Tiles: 48
// Сдвиг превьюшки/иконки вправо&вниз относительно полного поля файла
int nSpaceX1, nSpaceY1; // Thumbs: 1x1, Tiles: 4x4
// Размер "остатка" вправо&вниз после превьюшки/иконки. Здесь рисуется текст.
int nSpaceX2, nSpaceY2; // Thumbs: 5x25, Tiles: 172x4
// Расстояние между превьюшкой/иконкой и текстом
int nLabelSpacing; // Thumbs: 0, Tiles: 4
// Отступ текста от краев прямоугольника метки
int nLabelPadding; // Thumbs: 0, Tiles: 1
// Шрифт
wchar_t sFontName[36]; // Tahoma
int nFontHeight; // 14
};
enum PanelViewMode
{
pvm_None = 0,
pvm_Thumbnails = 1,
pvm_Tiles = 2,
pvm_Icons = 4,
// следующий режим (если он будет) делать 4! (это bitmask)
pvm_TurnOff = 256,
};
/* Основной шрифт в GUI */
struct ConEmuMainFont
{
wchar_t sFontName[32];
DWORD nFontHeight, nFontWidth, nFontCellWidth;
DWORD nFontQuality, nFontCharSet;
BOOL Bold, Italic;
wchar_t sBorderFontName[32];
DWORD nBorderFontWidth;
};
//DWORD nFarInterfaceSettings;
struct CEFarInterfaceSettings
{
union
{
struct
{
int Reserved1 : 3; // FIS_CLOCKINPANELS и т.п.
int ShowKeyBar : 1; // FIS_SHOWKEYBAR
int AlwaysShowMenuBar : 1; // FIS_ALWAYSSHOWMENUBAR
};
DWORD Raw;
};
};
//DWORD nFarPanelSettings;
struct CEFarPanelSettings
{
union
{
struct
{
int Reserved1 : 5; // FPS_SHOWHIDDENANDSYSTEMFILES и т.п
int ShowColumnTitles : 1; // FPS_SHOWCOLUMNTITLES
int ShowStatusLine : 1; // FPS_SHOWSTATUSLINE
int Reserved2 : 4; // FPS_SHOWFILESTOTALINFORMATION и т.п.
int ShowSortModeLetter : 1; // FPS_SHOWSORTMODELETTER
};
DWORD Raw;
};
};
struct PanelViewSetMapping
{
DWORD cbSize; // Struct size, на всякий случай
/* Цвета и рамки */
ThumbColor crBackground; // Фон превьюшки: RGB или Index
int nPreviewFrame; // 1 (серая рамка вокруг превьюшки
ThumbColor crPreviewFrame; // RGB или Index
int nSelectFrame; // 1 (рамка вокруг текущего элемента)
ThumbColor crSelectFrame; // RGB или Index
/* антиалиасинг */
DWORD nFontQuality;
/* Теперь разнообразные размеры */
ThumbSizes Thumbs;
ThumbSizes Tiles;
/* Основной шрифт в GUI */
struct ConEmuMainFont MainFont;
// Прочие параметры загрузки
BYTE bLoadPreviews; // bitmask of PanelViewMode {1=Thumbs, 2=Tiles}
bool bLoadFolders; // true - load infolder previews (only for Thumbs)
DWORD nLoadTimeout; // 15 sec
DWORD nMaxZoom; // 600%
bool bUsePicView2; // true
bool bRestoreOnStartup;
// AppDistinct палитру нужно получить отдельно
// Здесь хранятся только "общие" цвета
COLORREF crPalette[16], crFadePalette[16];
//// Пока не используется
//DWORD nCacheFolderType; // юзер/программа/temp/и т.п.
//wchar_t sCacheFolder[MAX_PATH];
};
typedef BOOL (WINAPI* PanelViewInputCallback)(HANDLE hInput, PINPUT_RECORD lpBuffer, DWORD nBufSize, LPDWORD lpNumberOfEventsRead, BOOL* pbResult);
typedef union uPanelViewInputCallback
{
u64 Reserved; // необходимо для выравнивания структур при x64 <--> x86
PanelViewInputCallback f; //-V117
} PanelViewInputCallback_t;
typedef BOOL (WINAPI* PanelViewOutputCallback)(HANDLE hOutput,const CHAR_INFO *lpBuffer,COORD dwBufferSize,COORD dwBufferCoord,PSMALL_RECT lpWriteRegion);
typedef union uPanelViewOutputCallback
{
u64 Reserved; // необходимо для выравнивания структур при x64 <--> x86
PanelViewOutputCallback f; //-V117
} PanelViewOutputCallback_t;
struct PanelViewText
{
// Флаг используемости, выравнивание текста, и др.
#define PVI_TEXT_NOTUSED 0
#define PVI_TEXT_LEFT 1
#define PVI_TEXT_CENTER 2
#define PVI_TEXT_RIGHT 4
#define PVI_TEXT_SKIPSORTMODE 0x100 // только для имени колонки (оставить ФАРовскую буковку сортировки с ^)
DWORD nFlags;
// используется только младший байт - индексы консольных цветов
DWORD bConAttr;
// собственно текст
wchar_t sText[128];
};
struct PanelViewInit
{
DWORD cbSize;
BOOL bRegister, bVisible;
HWND2 hWnd;
BOOL bLeftPanel;
// Flags
#define PVI_COVER_NORMAL 0x000 // как обычно, располагаем прямоугольником, в который ФАР выводит файлы
#define PVI_COVER_SCROLL_CLEAR 0x001 // при отрисовке GUI очистит полосу прокрутки (заменит на вертикальную-двойную)
#define PVI_COVER_SCROLL_OVER 0x002 // PVI_COVER_NORMAL + правая рамка (где полоса прокрутки). Плагин должен отрисовать прокрутку сам
#define PVI_COVER_COLTITLE_OVER 0x004 // PVI_COVER_NORMAL + строка с заголовками колонок (если она есть)
#define PVI_COVER_FULL_OVER 0x008 // Вся РАБОЧАЯ область панели (то есть панель - рамка)
#define PVI_COVER_FRAME_OVER 0x010 // Вся область панели (включая рамку)
#define PVI_COVER_2PANEL_OVER 0x020 // Обе панели (полноэкранная)
#define PVI_COVER_CONSOLE_OVER 0x040 // Консоль целиком
DWORD nCoverFlags;
// FAR settings
CEFarInterfaceSettings FarInterfaceSettings;
CEFarPanelSettings FarPanelSettings;
// Координаты всей панели (левой, правой, или fullscreen)
RECT PanelRect;
// Разнообразные текстовые затиралки
PanelViewText tPanelTitle, tColumnTitle, tInfoLine[3];
// Это координаты прямоугольника, в котором реально располагается View
// Координаты определяются в GUI. Единицы - консольные.
RECT WorkRect;
// Callbacks, используются только в плагинах
PanelViewInputCallback_t pfnPeekPreCall, pfnPeekPostCall, pfnReadPreCall, pfnReadPostCall;
PanelViewOutputCallback_t pfnWriteCall;
/* out */
//PanelViewSetMapping ThSet;
BOOL bFadeColors;
};
// События, при которых вызывается функция субплагина для перерисовки фона
enum PaintBackgroundEvents
{
pbe_Common = 0, // при изменении размера окна ConEmu/размера шрифта/палитры ConEmu/...
pbe_PanelDirectory = 1, // при смене папки
//TODO, by request
//bue_LeftDirChanged = 1, // на левой панели изменена текущая папка
//bue_RightDirChanged = 2, // на правой панели изменена текущая папка
//bue_FocusChanged = 4, // фокус переключился между левой/правой панелью
};
enum PaintBackgroundPlaces
{
// Используются при регистрации И отрисовке
pbp_Panels = 1,
pbp_Editor = 2,
pbp_Viewer = 4,
// Используются ТОЛЬКО как [OUT] при отрисовке // Reserved
pbp_UserScreen = 8,
pbp_CommandLine = 16,
pbp_KeyBar = 32,
pbp_MenuBar = 64, // Верхняя строка - падающее меню
pbp_StatusLine = 128, // Статусная строка - редактор/вьювер
// Этот код используется для завершения нити отрисовки
pbp_Finalize = 0x80000000,
};
#define BkPanelInfo_CurDirMax 32768
#define BkPanelInfo_FormatMax MAX_PATH
#define BkPanelInfo_HostFileMax 32768
struct BkPanelInfo
{
BOOL bVisible; // Наличие панели
BOOL bFocused; // В фокусе
BOOL bPlugin; // Плагиновая панель
int nPanelType; // enum PANELINFOTYPE
wchar_t *szCurDir/*[32768]*/; // Текущая папка на панели
wchar_t *szFormat/*[MAX_PATH]*/; // Доступно только в FAR2, в FAR3 это может быть префикс, если "формат" плагином не определен
wchar_t *szHostFile/*[32768]*/; // Доступно только в FAR2
RECT rcPanelRect; // Консольные координаты панели. В FAR 2+ с ключом /w верх может быть != {0,0}
};
struct PaintBackgroundArg
{
DWORD cbSize;
// указан при вызове RegisterBackground(rbc_Register)
LPARAM lParam;
// панели/редактор/вьювер
enum PaintBackgroundPlaces Place;
// Слой, в котором вызван плагин. По сути, это порядковый номер, 0-based
// если (dwLevel > 0) плагин НЕ ДОЛЖЕН затирать фон целиком.
DWORD dwLevel;
// [Reserved] комбинация из enum PaintBackgroundEvents
DWORD dwEventFlags;
// Основной шрифт в ConEmu GUI
struct ConEmuMainFont MainFont;
// Палитра в ConEmu GUI
COLORREF crPalette[16];
// Reserved
DWORD dwReserved[20];
// DC для отрисовки фона. Изначально (для dwLevel==0) DC залит цветом фона crPalette[0]
HDC hdc;
// размер DC в пикселях
int dcSizeX, dcSizeY;
// Координаты панелей в DC (base 0x0)
RECT rcDcLeft, rcDcRight;
// Для облегчения жизни плагинам - текущие параметры FAR
RECT rcConWorkspace; // Координаты рабочей области FAR. В FAR 2 с ключом /w верх может быть != {0,0}
COORD conCursor; // положение курсора, или {-1,-1} если он не видим
CEFarInterfaceSettings FarInterfaceSettings; // ACTL_GETINTERFACESETTINGS
CEFarPanelSettings FarPanelSettings; // ACTL_GETPANELSETTINGS
BYTE nFarColors[col_LastIndex]; // Массив цветов фара
// Информация о панелях
BOOL bPanelsAllowed;
BkPanelInfo LeftPanel;
BkPanelInfo RightPanel;
// [OUT] Плагин должен указать, какие части консоли он "раскрасил" - enum PaintBackgroundPlaces
DWORD dwDrawnPlaces;
};
typedef int (WINAPI* PaintConEmuBackground_t)(struct PaintBackgroundArg* pBk);
// Если функция вернет 0 - обновление фона пока не требуется
typedef int (WINAPI* BackgroundTimerProc_t)(LPARAM lParam);
enum RegisterBackgroundCmd
{
rbc_Register = 1, // Первичная регистрации "фонового" плагина
rbc_Unregister = 2, // Убрать плагин из списка "фоновых"
rbc_Redraw = 3, // Если плагину требуется обновить фон - он зовет эту команду
};
// Аргумент для функции: int WINAPI RegisterBackground(RegisterBackgroundArg *pbk)
struct RegisterBackgroundArg
{ //-V802
DWORD cbSize;
enum RegisterBackgroundCmd Cmd; // DWORD
HMODULE hPlugin; // Instance плагина, содержащего PaintConEmuBackground
// Для дерегистрации всех калбэков достаточно вызвать {sizeof(RegisterBackgroundArg), rbc_Unregister, hPlugin}
// Что вызывать для обновления фона.
// Требуется заполнять только для Cmd==rbc_Register,
// в остальных случаях команды игнорируются
// Плагин может зарегистрировать несколько различных пар {PaintConEmuBackground,lParam}
PaintConEmuBackground_t PaintConEmuBackground; // Собственно калбэк
LPARAM lParam; // lParam будет передан в PaintConEmuBackground
DWORD dwPlaces; // bitmask of PaintBackgroundPlaces
DWORD dwEventFlags; // bitmask of PaintBackgroundEvents
// 0 - плагин предпочитает отрисовывать фон первым. Чем больше nSuggestedLevel
// тем позднее может быть вызван плагин при обновлении фона
DWORD dwSuggestedLevel;
// Необязательный калбэк таймера
BackgroundTimerProc_t BackgroundTimerProc;
// Рекомендованная частота опроса (ms)
DWORD nBackgroundTimerElapse;
};
typedef int (WINAPI* RegisterBackground_t)(RegisterBackgroundArg *pbk);
typedef void (WINAPI* SyncExecuteCallback_t)(LONG_PTR lParam);
struct FarVersion
{
union
{
DWORD dwVer;
struct
{
int Bis : 1;
int dwVerMinor : 15;
int dwVerMajor : 16;
};
};
DWORD dwBuild;
// Macro language changed to Lua
bool IsFarLua() const
{
return ((dwVerMajor > 3) || ((dwVerMajor == 3) && (dwBuild >= 2851)));
};
// Userscreen is now 'Desktop' window with index '0'
bool IsDesktop() const
{
return ((dwVerMajor > 3) || ((dwVerMajor == 3) && (dwBuild >= 4039)));
};
};
// Аргумент для функции OnConEmuLoaded
struct ConEmuLoadedArg
{
DWORD cbSize; // размер структуры в байтах
DWORD nBuildNo; // {Номер сборки ConEmu*10} (i.e. 1012070). Это версия плагина. В принципе, версия GUI может отличаться
// YYMMDDX (YY - две цифры года, MM - месяц, DD - день, X - 0 и выше-номер подсборки)
HMODULE hConEmu; // conemu.dll / conemu.x64.dll
HMODULE hPlugin; // для информации - Instance этого плагина, в котором вызывается OnConEmuLoaded
BOOL bLoaded; // TRUE - при загрузке conemu.dll, FALSE - при выгрузке
BOOL bGuiActive; // TRUE - консоль запущена из-под ConEmu, FALSE - standalone
/* ***************** */
/* Сервисные функции */
/* ***************** */
HWND (WINAPI *GetFarHWND)();
HWND (WINAPI *GetFarHWND2)(BOOL abConEmuOnly);
void (WINAPI *GetFarVersion)(FarVersion* pfv);
BOOL (WINAPI *IsTerminalMode)();
BOOL (WINAPI *IsConsoleActive)();
int (WINAPI *RegisterPanelView)(PanelViewInit *ppvi);
int (WINAPI *RegisterBackground)(RegisterBackgroundArg *pbk);
// Activate console tab in ConEmu
int (WINAPI *ActivateConsole)();
// Synchronous execute CallBack in Far main thread (FAR2 use ACTL_SYNCHRO).
// SyncExecute does not returns, until CallBack finished.
// ahModule must be module handle, which contains CallBack
int (WINAPI *SyncExecute)(HMODULE ahModule, SyncExecuteCallback_t CallBack, LONG_PTR lParam);
};
// другие плагины могут экспортировать функцию "OnConEmuLoaded"
// при активации плагина ConEmu (при запуске фара из-под ConEmu)
// эта функция ("OnConEmuLoaded") будет вызвана, в ней плагин может
// зарегистрировать калбэки для обновления Background-ов
// Внимание!!! Эта же функция вызывается при ВЫГРУЗКЕ conemu.dll,
// при выгрузке hConEmu и все функции == NULL
typedef void (WINAPI* OnConEmuLoaded_t)(struct ConEmuLoadedArg* pConEmuInfo);
enum GuiLoggingType
{
glt_None = 0,
glt_Processes = 1,
glt_Input = 2,
glt_Commands = 3,
glt_Debugger = 4,
glt_Ansi = 5,
// glt_Files, ...
};
enum ComSpecType
{
cst_AutoTccCmd = 0,
cst_EnvVar = 1,
cst_Cmd = 2,
cst_Explicit = 3,
//
cst_Last = cst_Explicit
};
enum ComSpecBits
{
csb_SameOS = 0,
csb_SameApp = 1,
csb_x32 = 2,
csb_x64 = 3, // только для аргументов функций
//
csb_Last = csb_x32,
};
typedef DWORD CEAdd2Path;
const CEAdd2Path
CEAP_AddConEmuBaseDir = 0x00000001,
CEAP_AddConEmuExeDir = 0x00000002,
CEAP_AddAll = CEAP_AddConEmuBaseDir|CEAP_AddConEmuExeDir,
CEAP_None = 0;
struct ConEmuComspec
{
ComSpecType csType;
ComSpecBits csBits;
BOOL isUpdateEnv;
CEAdd2Path AddConEmu2Path;
BOOL isAllowUncPaths;
wchar_t ComspecExplicit[MAX_PATH]; // этот - хранится в настройке
wchar_t Comspec32[MAX_PATH]; // развернутые, готовые к использованию
wchar_t Comspec64[MAX_PATH]; // развернутые, готовые к использованию
wchar_t ConEmuBaseDir[MAX_PATH]; // БЕЗ завершающего слеша. Папка содержит ConEmuC.exe, ConEmuHk.dll, ConEmu.xml
wchar_t ConEmuExeDir[MAX_PATH]; // БЕЗ завершающего слеша. Папка содержит ConEmu.exe, Far.exe (optional)
};
typedef DWORD ConEmuConsoleFlags;
const ConEmuConsoleFlags
CECF_DosBox = 0x00000001, // DosBox установлен, можно пользоваться
CECF_UseTrueColor = 0x00000002, // включен флажок "TrueMod support"
CECF_ProcessAnsi = 0x00000004, // ANSI X3.64 & XTerm-256-colors Support
CECF_UseClink_1 = 0x00000008, // использовать расширение командной строки (ReadConsole). 1 - старая версия (0.1.1)
CECF_UseClink_2 = 0x00000010, // использовать расширение командной строки (ReadConsole) - 2 - новая версия
CECF_UseClink_Any = CECF_UseClink_1|CECF_UseClink_2,
CECF_SleepInBackg = 0x00000020,
CECF_BlockChildDbg = 0x00000040, // When ConEmuC tries to debug process tree - force disable DEBUG_PROCESS/DEBUG_ONLY_THIS_PROCESS flags when creating subchildren
CECF_SuppressBells = 0x00000080, // Suppress output of char(7) to console (which produces annoying bell sound)
CECF_ConExcHandler = 0x00000100, // Set up "SetUnhandledExceptionFilter(CreateDumpOnException)" in alternative servers too
CECF_ProcessNewCon = 0x00000200, // Enable processing of '-new_console' and '-cur_console' switches in your shell prompt, scripts etc. started in ConEmu tabs
CECF_ProcessCmdStart = 0x00000400, // Use "start xxx.exe" to start new tab
CECF_Empty = 0
;
#define SetConEmuFlags(v,m,f) (v) = ((v) & ~(m)) | (f)
struct ConEmuGuiMapping
{
DWORD cbSize;
DWORD nProtocolVersion; // == CESERVER_REQ_VER
DWORD nChangeNum; // incremental change number of structure
HWND2 hGuiWnd; // основное (корневое) окно ConEmu
DWORD nGuiPID; // PID ConEmu.exe
DWORD nLoggingType; // enum GuiLoggingType
wchar_t sConEmuExe[MAX_PATH+1]; // полный путь к ConEmu.exe (GUI)
// --> ComSpec.ConEmuBaseDir: wchar_t sConEmuDir[MAX_PATH+1]; // БЕЗ завершающего слеша. Папка содержит ConEmu.exe
// --> ComSpec.ConEmuBaseDir: wchar_t sConEmuBaseDir[MAX_PATH+1]; // БЕЗ завершающего слеша. Папка содержит ConEmuC.exe, ConEmuHk.dll, ConEmu.xml
wchar_t sConEmuArgs[MAX_PATH*2];
DWORD bUseInjects; // 0-off, 1-on, 3-exe only. Далее могут быть (пока не используется) доп.флаги (битмаск)? chcp, Hook HKCU\FAR[2] & HKLM\FAR and translate them to hive, ...
ConEmuConsoleFlags Flags;
//BOOL bUseTrueColor; // включен флажок "TrueMod support"
//BOOL bProcessAnsi; // ANSI X3.64 & XTerm-256-colors Support
//DWORD bUseClink; // использовать расширение командной строки (ReadConsole). 0 - нет, 1 - старая версия (0.1.1), 2 - новая версия
//BOOL bSleepInBackg; // Sleep in background
BOOL bGuiActive; // Gui is In focus or Not
DWORD dwActiveTick; // Tick, when hActiveCons/bGuiActive was changed
HWND2 hActiveCons[MAX_CONSOLE_COUNT]; // Active or visible Real console HWND
/* Основной шрифт в GUI */
struct ConEmuMainFont MainFont;
// Перехват реестра
DWORD isHookRegistry; // bitmask. 1 - supported, 2 - current
wchar_t sHiveFileName[MAX_PATH];
HKEY2 hMountRoot; // NULL для Vista+, для Win2k&XP здесь хранится корневой ключ (HKEY_USERS), в который загружен hive
wchar_t sMountKey[MAX_PATH]; // Для Win2k&XP здесь хранится имя ключа, в который загружен hive
// DosBox
//BOOL bDosBox; // наличие DosBox
//wchar_t sDosBoxExe[MAX_PATH+1]; // полный путь к DosBox.exe
//wchar_t sDosBoxEnv[8192]; // команды загрузки (mount, и пр.)
ConEmuComspec ComSpec;
};
typedef unsigned int CEFarWindowType;
static const CEFarWindowType
fwt_Any = 0,
fwt_Panels = 1, // _ASSERTE(fwt_Panels == WTYPE_PANELS)
fwt_Viewer = 2, // _ASSERTE(fwt_Viewer == WTYPE_VIEWER)
fwt_Editor = 3, // _ASSERTE(fwt_Viewer == WTYPE_EDITOR)
fwt_TypeMask = 0x00FF,
fwt_Elevated = 0x00100,
fwt_NonElevated = 0x00200, // Аргумент для поиска окна
fwt_ModalFarWnd = 0x00400, // Бывший ConEmuTab.Modal
fwt_NonModal = 0x00800, // Аргумент для поиска окна
fwt_PluginRequired = 0x01000, // Аргумент для поиска окна
fwt_ActivateFound = 0x02000, // Активировать найденный таб. Аргумент для поиска окна
fwt_Disabled = 0x04000, // Таб заблокирован другим модальным табом (или диалогом?)
fwt_Renamed = 0x08000, // Таб был принудительно переименован пользователем (?)
fwt_ActivateOther = 0x10000, // Аргумент для поиска окна. Активировать найденный таб если он НЕ в активной консоли
fwt_CurrentFarWnd = 0x20000, // Бывший ConEmuTab.Current
fwt_ModifiedFarWnd = 0x40000, // Бывший ConEmuTab.Modified
fwt_FarFullPathReq = 0x80000, // Аргумент для поиска окна
fwt_Highlighted = 0x100000, // Подсветить таб
fwt_UpdateFlags = fwt_Elevated|fwt_ModalFarWnd|fwt_Disabled|fwt_CurrentFarWnd|fwt_ModifiedFarWnd|fwt_Highlighted;
;
//TODO("Restrict CONEMUTABMAX to 128 chars. Only filename, and may be ellipsed...");
#define CONEMUTABMAX 0x400
struct ConEmuTab
{
int Pos;
int Current;
CEFarWindowType Type; // (Panels=1, Viewer=2, Editor=3) |(Elevated=0x100) |(NotElevated=0x200) |(Modal=0x400)
int Modified;
int Modal;
int EditViewId;
wchar_t Name[CONEMUTABMAX];
// int Modified;
// int isEditor;
};
struct CESERVER_REQ_CONEMUTAB
{
DWORD nTabCount;
BOOL bMacroActive;
BOOL bMainThread;
int CurrentType; // WTYPE_PANELS / WTYPE_VIEWER / WTYPE_EDITOR
int CurrentIndex; // для удобства, индекс текущего окна в tabs
ConEmuTab tabs[1];
};
struct CESERVER_REQ_CONEMUTAB_RET
{
BOOL bNeedPostTabSend;
BOOL bNeedResize;
COORD crNewSize;
};
struct ForwardedPanelInfo
{
RECT ActiveRect;
RECT PassiveRect;
int ActivePathShift; // сдвиг в этой структуре в байтах
int PassivePathShift; // сдвиг в этой структуре в байтах
BOOL NoFarConsole;
wchar_t szDummy[2];
union //x64 ready
{
WCHAR* pszActivePath/*[MAX_PATH+1]*/; //-V117
u64 Reserved1;
};
union //x64 ready
{
WCHAR* pszPassivePath/*[MAX_PATH+1]*/; //-V117
u64 Reserved2;
};
};
struct ForwardedFileInfo
{
WCHAR Path[MAX_PATH+1];
};
struct CESERVER_REQ_HDR
{
DWORD cbSize; // Не size_t(!), а именно DWORD, т.к. пакетами обмениваются и 32<->64 бит между собой.
DWORD nVersion; // CESERVER_REQ_VER
BOOL bAsync; // не посылать "ответ", сразу закрыть пайп
CECMD nCmd; // DWORD
DWORD nSrcThreadId;
DWORD nSrcPID;
DWORD nCreateTick;
DWORD nBits; // битность вызывающего процесса
DWORD nLastError; // последний GetLastError() при отправке пакета
DWORD IsDebugging;
u64 hModule;
};
#define CHECK_CMD_SIZE(pCmd,data_size) ((pCmd)->hdr.cbSize >= (sizeof(CESERVER_REQ_HDR) + data_size))
struct CESERVER_CHAR_HDR
{
int nSize; // размер структуры динамический. Если 0 - значит прямоугольник is NULL
COORD cr1, cr2; // WARNING: Это АБСОЛЮТНЫЕ координаты (без учета прокрутки), а не экранные.
};
struct CESERVER_CHAR
{
CESERVER_CHAR_HDR hdr; // фиксированная часть
WORD data[2]; // variable(!) length
};
//CECONOUTPUTNAME L"ConEmuLastOutputMapping.%08X" // --> CESERVER_CONSAVE_MAPHDR ( %X == (DWORD)ghConWnd )
struct CESERVER_CONSAVE_MAPHDR
{
CESERVER_REQ_HDR hdr; // Для унификации
CONSOLE_SCREEN_BUFFER_INFO info; // чтобы знать текущий размер текущего буфера
DWORD MaxCellCount;
int CurrentIndex;
wchar_t sCurrentMap[64]; // CECONOUTPUTITEMNAME
};
//CECMD_CONSOLEFULL
//CECONOUTPUTITEMNAME L"ConEmuLastOutputMapping.%08X.%u" // --> CESERVER_CONSAVE_MAP ( %X == (DWORD)ghConWnd, %u = CESERVER_CONSAVE_MAPHDR.nCurrentIndex )
struct CESERVER_CONSAVE_MAP
{
CESERVER_REQ_HDR hdr; // Для унификации
CONSOLE_SCREEN_BUFFER_INFO info;
DWORD MaxCellCount;
int CurrentIndex;
BOOL Succeeded;
TODO("Store TrueColor buffer?");
CHAR_INFO Data[1];
};
struct CESERVER_REQ_RGNINFO
{
DWORD dwRgnInfoSize;
CESERVER_CHAR RgnInfo;
};
struct CESERVER_REQ_FULLCONDATA
{
DWORD dwRgnInfoSize_MustBe0; // must be 0
DWORD dwOneBufferSize; // may be 0
wchar_t Data[300]; // Variable length!!!
};
struct CEFAR_SHORT_PANEL_INFO
{
int PanelType;
int Plugin;
RECT PanelRect;
//int ItemsNumber;
//int SelectedItemsNumber;
//int CurrentItem;
//int TopPanelItem;
int Visible;
int Focus;
//int ViewMode;
//int ShortNames;
//int SortMode;
int ColumnNames;
int StatusLines;
unsigned __int64 Flags;
};
struct CEFAR_PANELTABS
{
int SeparateTabs; // если -1 - то умолчание
int ButtonColor; // если -1 - то умолчание
};
typedef unsigned int CEFAR_MACRO_AREA;
static const CEFAR_MACRO_AREA
fma_Unknown = 0x00000000,
fma_Panels = 0x00000001,
fma_Viewer = 0x00000002,
fma_Editor = 0x00000003,
fma_Dialog = 0x00000004 //-V112
;
WARNING("CEFAR_INFO_MAPPING.nFarColors - subject to change!!!");
struct CEFAR_INFO_MAPPING
{
DWORD cbSize;
DWORD nFarInfoIdx;
FarVersion FarVer;
DWORD nProtocolVersion; // == CESERVER_REQ_VER
DWORD nFarPID, nFarTID;
BYTE nFarColors[col_LastIndex]; // Массив цветов фара
//DWORD nFarInterfaceSettings;
CEFarInterfaceSettings FarInterfaceSettings;
//DWORD nFarPanelSettings;
CEFarPanelSettings FarPanelSettings;
//DWORD nFarConfirmationSettings;
BOOL bFarPanelAllowed; // FCTL_CHECKPANELSEXIST
// Текущая область в фаре
CEFAR_MACRO_AREA nMacroArea;
BOOL bMacroActive;
// Информация собственно о панелях присутствовать не обязана
BOOL bFarPanelInfoFilled;
BOOL bFarLeftPanel, bFarRightPanel;
CEFAR_SHORT_PANEL_INFO FarLeftPanel, FarRightPanel; // FCTL_GETPANELSHORTINFO,...
BOOL bViewerOrEditor; // для облегчения жизни RgnDetect
DWORD nFarConsoleMode;
BOOL bBufferSupport; // FAR2 с ключом /w ?
CEFAR_PANELTABS PanelTabs; // Настройки плагина PanelTabs
// Далее идут строковые ресурсы, на которые в некоторых случаях ориентируется GUI
wchar_t sLngEdit[64]; // "edit"
wchar_t sLngView[64]; // "view"
wchar_t sLngTemp[64]; // "{Temporary panel"
// Far current panel directories
// These MUST be last members!
LONG nPanelDirIdx; // Separately of nFarInfoIdx
wchar_t sActiveDir[0x8000], sPassiveDir[0x8000];
};
// Limited logging of console contents (same output as processed by CECF_ProcessAnsi)
// Initialized during CECMD_SRVSTARTSTOP
struct ConEmuAnsiLog
{
BOOL Enabled;
// Full path with name of log-file
wchar_t Path[MAX_PATH];
};
// CECONMAPNAME
struct CESERVER_CONSOLE_MAPPING_HDR
{
DWORD cbSize;
DWORD nLogLevel;
COORD crMaxConSize;
DWORD bDataReady; // TRUE, после того как сервер успешно запустился и готов отдавать данные
HWND2 hConWnd; // !! положение hConWnd и nGuiPID не менять !!
DWORD nServerPID; //
DWORD nGuiPID; // !! на них ориентируется PicViewWrapper !!
//
DWORD Reserved1; //bConsoleActive;
DWORD nProtocolVersion; // == CESERVER_REQ_VER
DWORD Reserved2; //bThawRefreshThread; // FALSE - увеличивает интервал опроса консоли (GUI теряет фокус)
//
DWORD nActiveFarPID; // PID последнего активного фара
//
DWORD nServerInShutdown; // GetTickCount() начала закрытия сервера
//
wchar_t sConEmuExe[MAX_PATH+1]; // полный путь к ConEmu.exe (GUI)
// --> ComSpec.ConEmuBaseDir: wchar_t sConEmuBaseDir[MAX_PATH+1]; // БЕЗ завершающего слеша. Папка содержит ConEmuC.exe, ConEmuHk.dll, ConEmu.xml
//
DWORD nAltServerPID; //
DWORD ActiveServerPID() const { return nAltServerPID ? nAltServerPID : nServerPID; };
// Root(!) ConEmu window
HWND2 hConEmuRoot;
// DC ConEmu window
HWND2 hConEmuWndDc;
// Back ConEmu window
HWND2 hConEmuWndBack;
DWORD nLoggingType; // enum GuiLoggingType
DWORD bUseInjects; // 0-off, 1-on, 3-exe only. Далее могут быть доп.флаги (битмаск)? chcp, Hook HKCU\FAR[2] & HKLM\FAR and translate them to hive, ...
ConEmuConsoleFlags Flags;
//BOOL bDosBox; // DosBox установлен, можно пользоваться
//BOOL bUseTrueColor; // включен флажок "TrueMod support"
//BOOL bProcessAnsi; // ANSI X3.64 & XTerm-256-colors Support
//DWORD bUseClink; // использовать расширение командной строки (ReadConsole). 0 - нет, 1 - старая версия (0.1.1), 2 - новая версия
// Limited logging of console contents (same output as processed by CECF_ProcessAnsi)
ConEmuAnsiLog AnsiLog;
// Перехват реестра
DWORD isHookRegistry; // bitmask. 1 - supported, 2 - current
wchar_t sHiveFileName[MAX_PATH];
HKEY2 hMountRoot; // NULL для Vista+, для Win2k&XP здесь хранится корневой ключ (HKEY_USERS), в который загружен hive
wchar_t sMountKey[MAX_PATH]; // Для Win2k&XP здесь хранится имя ключа, в который загружен hive
// Разрешенный размер видимой области
BOOL bLockVisibleArea;
COORD crLockedVisible;
// И какая прокрутка допустима
RealBufferScroll rbsAllowed; // пока любая - rbs_Any
ConEmuComspec ComSpec;
};
// CECONAPPMAPNAME
struct CESERVER_CONSOLE_APP_MAPPING
{
DWORD cbSize;
DWORD nProtocolVersion; // == CESERVER_REQ_VER
// Under construction, some fields may be void
// Updated before and after ReadConsoleInput (powershell especially)
DWORD nReadConsoleInputPID;
COORD crReadConsoleInputStart;
// Updated before and after ReadConsole/ReadFile
DWORD nReadConsolePID;
COORD crReadConsoleStart;
};
struct TOPLEFTCOORD
{
int y;
int x;
bool isLocked() const { return (y >= 0 || x >= 0); };
void Reset() { y = x = -1; };
bool Equal(const TOPLEFTCOORD& tl) const { return (tl.x==x && tl.y==y); };
};
struct CESERVER_REQ_CONINFO
{
TOPLEFTCOORD TopLeft;
};
struct CESERVER_REQ_CONINFO_INFO
{
CESERVER_REQ_HDR cmd;
HWND2 hConWnd;
DWORD nPacketId;
DWORD nSrvUpdateTick; // GetTickCount(), когда консоль была считана в последний раз в сервере
DWORD nReserved0; //DWORD nInputTID;
DWORD nProcesses[CONSOLE_PROCESSES_MAX/*20*/];
DWORD dwCiSize;
CONSOLE_CURSOR_INFO ci;
DWORD dwConsoleCP;
DWORD dwConsoleOutputCP;
WORD dwConsoleInMode;
WORD dwConsoleOutMode;
DWORD dwSbiSize;
CONSOLE_SCREEN_BUFFER_INFO sbi; // srWindow - "видимое" в GUI окно
TOPLEFTCOORD TopLeft;
COORD crWindow;
SMALL_RECT srRealWindow; // Те реальные координаты, которые видимы в RealConsole (а не то, что видимо в GUI окне)
COORD crMaxSize; // Максимальный размер консоли в символах (для текущего выбранного шрифта)
DWORD nDataShift; // Для удобства - сдвиг начала данных (data) От начала info
DWORD nDataCount; // Для удобства - количество ячеек (data)
};
//typedef struct tag_CESERVER_REQ_CONINFO_DATA {
// CESERVER_REQ_HDR cmd;
// COORD crMaxSize;
// CHAR_INFO Buf[1];
//} CESERVER_REQ_CONINFO_DATA;
struct CESERVER_REQ_CONINFO_FULL
{
DWORD cbMaxSize; // размер всего буфера CESERVER_REQ_CONINFO_FULL (скорее всего будет меньше реальных данных)
BOOL bDataChanged; // Выставляется в TRUE, при изменениях содержимого консоли (а не только положение курсора...)
CESERVER_CONSOLE_MAPPING_HDR hdr;
CESERVER_REQ_CONINFO_INFO info;
CHAR_INFO data[1];
};
//typedef struct tag_CESERVER_REQ_CONINFO {
// CESERVER_CONSOLE_MAPPING_HDR inf;
// union {
// /* 9*/DWORD dwRgnInfoSize;
// CESERVER_REQ_RGNINFO RgnInfo;
// /*10*/CESERVER_REQ_FULLCONDATA FullData;
// };
//} CESERVER_REQ_CONINFO;
struct CESERVER_REQ_SETSIZE
{
USHORT nBufferHeight; // 0 или высота буфера (режим с прокруткой)
COORD size;
//TOPLEFTCOORD TopLeft;
//SHORT nSendTopLine; // -1 или 0based номер строки зафиксированной в GUI (только для режима с прокруткой)
//SMALL_RECT rcWindow; // координаты видимой области для режима с прокруткой
DWORD dwFarPID; // Если передано - сервер должен сам достучаться до FAR'а и обновить его размер через плагин ПЕРЕД возвратом
};
struct CESERVER_REQ_OUTPUTFILE
{
BOOL bUnicode;
WCHAR szFilePathName[MAX_PATH+1];
};
struct CESERVER_REQ_RETSIZE
{
DWORD nNextPacketId;
COORD crMaxSize; // Current maximum possible size of console window
CONSOLE_SCREEN_BUFFER_INFO SetSizeRet;
};
enum SingleInstanceShowHideType
{
sih_None = 0,
sih_ShowMinimize = 1,
sih_ShowHideTSA = 2,
sih_Show = 3,
sih_SetForeground = 4,
sih_HideTSA = 5,
sih_Minimize = 6,
sih_AutoHide = 7,
sih_QuakeShowHide = 8,
sih_StartDetached = 9,
};
struct CESERVER_REQ_NEWCMD // CECMD_NEWCMD
{
HWND2 hFromConWnd;
HWND2 hFromDcWnd; // ConWnd may differs from parent process, but ENV_CONEMUDRAW_VAR_W would be inherited
SingleInstanceShowHideType ShowHide;
BYTE isAdvLogging;
BYTE Reserved;
wchar_t szConEmu[MAX_PATH]; // Для идентификации, чтобы можно было выполнять команду в instance по тому же пути (путь к папке с ConEmu.exe без слеша)
wchar_t szCurDir[MAX_PATH];
// Внимание! Может содержать параметр -new_console. GUI его должен вырезать перед запуском сервера!
//wchar_t szCommand[1]; // На самом деле - variable_size !!!
DWORD cchCommand;
DWORD cchEnvStrings;
DWORD ptrDataStart;
wchar_t* GetCommand();
wchar_t* GetEnvStrings();
void SetCommand(LPCWSTR asCommand);
void SetEnvStrings(LPCWSTR asStrings, DWORD cchLenZZ);
};
struct CESERVER_REQ_SETFONT
{
DWORD cbSize; // страховка
int inSizeY;
int inSizeX;
wchar_t sFontName[LF_FACESIZE];
};
// изменились настройки GUI (шрифт), размер окна ConEmu, или еще что-то
struct CESERVER_REQ_GUICHANGED
{
DWORD cbSize; // страховка
DWORD nGuiPID;
HWND2 hLeftView, hRightView;
};
// CMD_OPENEDITORLINE. Открыть в редакторе файл и перейти на строку (обработка ошибок компилятора)
struct CESERVER_REQ_FAREDITOR
{
DWORD cbSize; // страховка
int nLine; // 1-based
int nColon; // 1-based
wchar_t szFile[MAX_PATH+1];
};
// CECMD_GETALLTABS. Вернуть список всех открытых табов
struct CESERVER_REQ_GETALLTABS
{
int Count;
struct TabInfo
{
bool ActiveConsole;
bool ActiveTab;
bool Disabled;
int ConsoleIdx; // 0-based
int TabNo; // 0-based
int FarWindow; // 0-based
wchar_t Title[MAX_PATH]; // Если не влезет - то и фиг с ним
} Tabs[1]; // Variable length
};
//CECMD_SETGUIEXTERN
struct CESERVER_REQ_SETGUIEXTERN
{
BOOL bExtern; // TRUE - вынести приложение наружу из вкладки ConEmu, FALSE - вернуть во вкладку
BOOL bDetach; // Отцепиться и забыть про ConEmu
//RECT rcOldPos; // Если bDetach - здесь передается "старое" положение окна
};
enum SrvStartStopType
{
srv_Started = 1,
srv_Stopped = 101,
};
// CECMD_SRVSTARTSTOP
struct CESERVER_REQ_SRVSTARTSTOP
{
SrvStartStopType Started;
HWND2 hConWnd;
DWORD dwKeybLayout;
};
enum StartStopType
{
sst_ServerStart = 0,
sst_AltServerStart = 1,
sst_ServerStop = 2,
sst_AltServerStop = 3,
sst_ComspecStart = 4,
sst_ComspecStop = 5,
sst_AppStart = 6,
sst_AppStop = 7,
sst_App16Start = 8,
sst_App16Stop = 9,
};
struct CESERVER_REQ_STARTSTOP
{
StartStopType nStarted;
HWND2 hWnd; // при передаче В GUI - консоль, при возврате в консоль - GUI
DWORD dwAID; // ConEmu internal ID of started CRealConsole
DWORD dwPID; //, dwInputTID;
DWORD nSubSystem; // 255 для DOS программ, 0x100 - аттач из FAR плагина
DWORD nImageBits; // 16/32/64
BOOL bRootIsCmdExe;
BOOL bUserIsAdmin;
BOOL bMainServerClosing; // if (nStarted == sst_AltServerStop)
DWORD dwKeybLayout; // Только при запуске сервера
// А это приходит из консоли, вдруг консольная программа успела поменять размер буфера
CONSOLE_SCREEN_BUFFER_INFO sbi;
// Максимальный размер консоли на текущем шрифте
COORD crMaxSize;
// Только ComSpec
BOOL bWasBufferHeight;
// "-cur_console:h<N>" для ComSpec
BOOL bForceBufferHeight;
DWORD nForceBufferHeight;
// Только при аттаче. Может быть NULL-ом
u64 hServerProcessHandle;
// При завершении
DWORD nOtherPID; // Для RM_COMSPEC - PID завершенного процесса (при sst_ComspecStop)
// Для информации и удобства (GetModuleFileName(0))
wchar_t sModuleName[MAX_PATH+1];
// Reserved
DWORD nReserved0[17];
// Create background tab, when attaching new console
BOOL bRunInBackgroundTab;
// При запуске в режиме RM_COMSPEC, сохранение "длинного вывода"
DWORD nParentFarPID;
// После детача/аттача мог остаться "альтернативный" сервер
DWORD nAltServerPID;
// Если был успешный вызов функций типа ReadConsole/ReadConsoleInput
BOOL bWasSucceededInRead;
// CmdLine
wchar_t sCmdLine[1]; // variable length
};
// CECMD_ONCREATEPROC
struct CESERVER_REQ_ONCREATEPROCESS
{
//BOOL bUnicode;
int nSourceBits;
wchar_t sFunction[32];
int nImageSubsystem;
int nImageBits;
DWORD nShellFlags; // Флаги ShellExecuteEx
DWORD nCreateFlags, nStartFlags; // Флаги CreateProcess
DWORD nShowCmd;
int nActionLen;
int nFileLen;
int nParamLen;
unsigned __int64 hStdIn, hStdOut, hStdErr;
// Variable length tail
wchar_t wsValue[1];
};
struct CESERVER_REQ_ONCREATEPROCESSRET
{
BOOL bContinue;
//BOOL bUnicode;
BOOL bForceBufferHeight;
BOOL bAllowDosbox;
//int nFileLen;
//int nBaseLen;
//union
//{
// wchar_t wsValue[1];
// char sValue[1];
//};
};
// _ASSERTE(sizeof(CESERVER_REQ_STARTSTOPRET) <= sizeof(CESERVER_REQ_STARTSTOP));
struct CESERVER_REQ_STARTSTOPRET
{
BOOL bWasBufferHeight;
HWND2 hWnd; // при возврате в консоль - GUI (главное окно)
HWND2 hWndDc;
HWND2 hWndBack;
DWORD dwPID; // при возврате в консоль - PID ConEmu.exe
DWORD nBufferHeight, nWidth, nHeight;
DWORD dwMainSrvPID;
DWORD dwAltSrvPID;
DWORD dwPrevAltServerPID;
BOOL bNeedLangChange;
u64 NewConsoleLang;
};
// Result of CESERVER_REQ_SRVSTARTSTOP
struct CESERVER_REQ_SRVSTARTSTOPRET
{
// Main values
CESERVER_REQ_STARTSTOPRET Info;
// Используется при CECMD_ATTACH2GUI
CESERVER_REQ_SETFONT Font;
// Limited logging of console contents (same output as processed by CECF_ProcessAnsi)
ConEmuAnsiLog AnsiLog;
// Avoid spare calls, let do all in one place
ConEmuGuiMapping GuiMapping;
// Environment block (inherited from parent console)
DWORD cchEnvStrings;
union
{
wchar_t szStrings[1]; // Variable length
wchar_t* pszStrings; // Used in GUI Internally
u64 Reserved; // Required for same size in both versions
};
};
struct CESERVER_REQ_POSTMSG
{
BOOL bPost;
HWND2 hWnd;
UINT nMsg;
// Заложимся на унификацию x86 & x64
u64 wParam, lParam;
};
struct CESERVER_REQ_FLASHWINFO
{
BOOL bSimple;
HWND2 hWnd;
BOOL bInvert; // только если bSimple == TRUE
DWORD dwFlags; // а это и далее, если bSimple == FALSE
UINT uCount;
DWORD dwTimeout;
};
// CMD_FARCHANGED - FAR plugin
struct FAR_REQ_FARSETCHANGED
{
BOOL bFARuseASCIIsort;
BOOL bShellNoZoneCheck; // Затычка для SEE_MASK_NOZONECHECKS
BOOL bMonitorConsoleInput; // при (Read/Peek)ConsoleInput(A/W) послать инфу в GUI/Settings/Debug
BOOL bLongConsoleOutput; // при выполнении консольных программ из Far - увеличивать высоту буфера
//wchar_t szEnv[1]; // Variable length: <Name>\0<Value>\0<Name2>\0<Value2>\0\0
ConEmuComspec ComSpec;
};
struct CESERVER_REQ_SETCONCP
{
BOOL bSetOutputCP; // [IN], [Out]=result
DWORD nCP; // [IN], [Out]=LastError
};
// CECMD_SETWINDOWPOS
struct CESERVER_REQ_SETWINDOWPOS
{
HWND2 hWnd;
HWND2 hWndInsertAfter;
int X;
int Y;
int cx;
int cy;
UINT uFlags;
};
// CECMD_SETWINDOWRGN
struct CESERVER_REQ_SETWINDOWRGN
{
HWND2 hWnd;
int nRectCount; // если 0 - сбросить WindowRgn, иначе - обсчитать.
BOOL bRedraw;
RECT rcRects[20]; // [0] - основной окна, [
};
// CECMD_SETBACKGROUND - приходит из плагина "PanelColorer.dll"
// Warning! Structure has variable length. "bmp" field must be followed by bitmap data (same as in *.bmp files)
struct CESERVER_REQ_SETBACKGROUND
{
int nType; // Reserved for future use. Must be 1
BOOL bEnabled; // TRUE - ConEmu use this image, FALSE - ConEmu use self background settings
// какие части консоли раскрашены - enum PaintBackgroundPlaces
DWORD dwDrawnPlaces;
//int nReserved1; // Must by 0. reserved for alpha
//DWORD nReserved2; // Must by 0. reserved for replaced colors
//int nReserved3; // Must by 0. reserved for background op
//DWORD nReserved4; // Must by 0. reserved for flags (BmpIsTransparent, RectangleSpecified)
//DWORD nReserved5; // Must by 0. reserved for level (Some plugins may want to draw small parts over common background)
//RECT rcReserved5; // Must by 0. reserved for filled rect (plugin may cover only one panel, or part of it)
BITMAPFILEHEADER bmp;
BITMAPINFOHEADER bi;
};
// ConEmu respond for CESERVER_REQ_SETBACKGROUND
typedef int SetBackgroundResult;
const SetBackgroundResult
esbr_OK = 0, // All OK
esbr_InvalidArg = 1, // Invalid *RegisterBackgroundArg
esbr_PluginForbidden = 2, // "Allow plugins" unchecked in ConEmu settings ("Main" page)
esbr_ConEmuInShutdown = 3, // Console is closing. This is not an error, just information
esbr_Unexpected = 4, // Unexpected error in ConEmu //-V112
esbr_InvalidArgSize = 5, // Invalid RegisterBackgroundArg.cbSize
esbr_InvalidArgProc = 6, // Invalid RegisterBackgroundArg.PaintConEmuBackground
esbr_LastErrorNo = esbr_InvalidArgProc;
struct CESERVER_REQ_SETBACKGROUNDRET
{
SetBackgroundResult nResult;
};
// CECMD_ACTIVATECON.
struct CESERVER_REQ_ACTIVATECONSOLE
{
HWND2 hConWnd;
};
// CECMD_GUIMACRO
#define CEGUIMACRORETENVVAR L"ConEmuMacroResult"
struct CESERVER_REQ_GUIMACRO
{
DWORD nSucceeded;
DWORD nTabIndex; // Specially selected tab, 1-based
DWORD nSplitIndex; // Specially selected split, 1-based
wchar_t sMacro[1]; // Variable length
};
// CECMD_PEEKREADINFO: посылается в GUI на вкладку Debug
struct CESERVER_REQ_PEEKREADINFO
{
WORD nCount;
BYTE bMainThread;
BYTE bReserved;
wchar_t cPeekRead/*'P'/'R' или 'W' в GUI*/;
wchar_t cUnicode/*'A'/'W'*/;
HANDLE2 h;
DWORD nPID;
DWORD nTID;
INPUT_RECORD Buffer[1];
};
enum ATTACHGUIAPP_FLAGS
{
agaf_Fail = 0,
agaf_Success = 1,
agaf_DotNet = 2,
agaf_NoMenu = 4,
agaf_WS_CHILD = 8,
agaf_Self = 16, // GUI приложение само создало дочернее окно в ConEmu
agaf_Inactive = 32, // GUI приложение создается в НЕ активной вкладке! Фокус нужно вернуть в ConEmu!
agaf_QtWindow = 64, // Qt
};
struct GuiStylesAndShifts
{
DWORD nStyle, nStyleEx;
RECT Shifts;
WCHAR szExeName[MAX_PATH]; // name only, not path
};
// CECMD_ATTACHGUIAPP
struct CESERVER_REQ_ATTACHGUIAPP
{
DWORD nFlags;
DWORD nPID;
DWORD nServerPID;
DWORD hkl;
HWND2 hConEmuWnd; // Root
HWND2 hConEmuDc; // DC Window
HWND2 hConEmuBack; // Back - holder for GUI
HWND2 hAppWindow; // NULL - проверка можно ли, HWND - когда создан
HWND2 hSrvConWnd;
RECT rcWindow; // координаты
DWORD Reserved; // зарезервировано под флаги, вроде "Показывать заголовок"
//DWORD nStyle, nStyleEx;
//BOOL bHideCaption; //
struct GuiStylesAndShifts Styles;
wchar_t sAppFilePathName[MAX_PATH*2];
};
// CECMD_PORTABLESTART
struct CESERVER_REQ_PORTABLESTARTED
{
DWORD nSubsystem;
DWORD nImageBits;
HANDLE2 hProcess;
DWORD nPID;
wchar_t sAppFilePathName[MAX_PATH*2];
};
// CECMD_SETFOCUS
struct CESERVER_REQ_SETFOCUS
{
BOOL bSetForeground;
HWND2 hWindow;
};
// CECMD_SETPARENT
struct CESERVER_REQ_SETPARENT
{
HWND2 hWnd;
HWND2 hParent;
};
struct MyAssertInfo
{
int nBtns;
BOOL bNoPipe;
wchar_t szTitle[255];
wchar_t szDebugInfo[4096];
};
// CECMD_STARTSERVER
struct CESERVER_REQ_START
{
DWORD nGuiPID; // In-ConEmuGuiPID
HWND2 hGuiWnd; // In-ghWnd
HWND2 hAppWnd; // Hooked application window (для GUI режима)
DWORD nValue; // Error codes
};
// CECMD_LOCKDC
struct CESERVER_REQ_LOCKDC
{
HWND2 hDcWnd;
BOOL bLock;
RECT Rect; // Пока просто
};
// CECMD_REGEXTCONSOLE
struct CESERVER_REQ_REGEXTCON
{
HANDLE2 hCommitEvent;
};
struct CESERVER_REQ_FULLSCREEN
{
BOOL bSucceeded;
DWORD nErrCode;
COORD crNewSize;
};
struct CESERVER_REQ_SETCONSOLORS
{
BOOL ChangeTextAttr;
BOOL ChangePopupAttr;
WORD NewTextAttributes;
WORD NewPopupAttributes;
BOOL ReFillConsole;
};
struct CESERVER_REQ_PROMPTACTION
{
BOOL Force;
BOOL BashMargin;
SHORT xPos, yPos; // Only for CECMD_MOUSECLICK
};
struct CESERVER_REQ_DUPLICATE
{
HWND2 hGuiWnd;
DWORD nGuiPID;
DWORD nAID; // внутренний ID в ConEmu
BOOL bRunAs;
DWORD nWidth, nHeight;
DWORD nBufferHeight;
DWORD nColors;
WCHAR sCommand[1]; // variable length, NULL usually
};
enum ALTBUFFER_FLAGS
{
abf_SaveContents = 0x0001,
abf_RestoreContents = 0x0002,
abf_BufferOn = 0x0004,
abf_BufferOff = 0x0008,
};
struct CESERVER_REQ_ALTBUFFER
{
DWORD AbFlags; // ALTBUFFER_FLAGS
USHORT BufferHeight; // In/Out
};
// CECMD_SETCONSCRBUF
struct CESERVER_REQ_SETCONSCRBUF
{
HANDLE2 hRequestor; // HANDLE of requesting thread
HANDLE2 hTemp; // Used internally, set to NULL when bLock and don't change
BOOL bLock; // Lock or release
COORD dwSize; // Informational, new size of the buffer
};
// CECMD_STORECURDIR
struct CESERVER_REQ_STORECURDIR
{
int iActiveCch; // Including terminating zero
int iPassiveCch; // Passive panel, Far only. Including terminating zero
wchar_t szDir[1]; // Variable length;
};
// CECMD_GETALLPANELS
struct CESERVER_REQ_GETALLPANELS
{
int iCount; // Count of 0-term strings
int iCurrent; // Index of the current panel
wchar_t szDirs[1]; // Variable length;
};
struct CESERVER_PROMPTSTARTED
{
// If new fields will be required - add them before szExeName
wchar_t szExeName[1]; // because of variable length
};
struct CESERVER_PALETTE
{
COLORREF crPalette[16];
COLORREF crFadePalette[16];
};
struct CESERVER_REQ
{
CESERVER_REQ_HDR hdr;
union
{
BYTE Data[1]; // variable(!) length
WORD wData[1];
DWORD dwData[1];
u64 qwData[1];
ConEmuGuiMapping GuiInfo;
CESERVER_REQ_CONINFO ReqConInfo;
CESERVER_CONSOLE_MAPPING_HDR ConInfo;
CESERVER_REQ_SETSIZE SetSize;
CESERVER_REQ_RETSIZE SetSizeRet;
CESERVER_REQ_OUTPUTFILE OutputFile;
CESERVER_REQ_NEWCMD NewCmd;
CESERVER_REQ_SRVSTARTSTOP SrvStartStop;
CESERVER_REQ_SRVSTARTSTOPRET SrvStartStopRet;
CESERVER_REQ_STARTSTOP StartStop;
CESERVER_REQ_STARTSTOPRET StartStopRet;
CESERVER_REQ_CONEMUTAB Tabs;
CESERVER_REQ_CONEMUTAB_RET TabsRet;
CESERVER_REQ_POSTMSG Msg;
CESERVER_REQ_FLASHWINFO Flash;
FAR_REQ_FARSETCHANGED FarSetChanged;
CESERVER_REQ_SETCONCP SetConCP;
CESERVER_REQ_SETWINDOWPOS SetWndPos;
CESERVER_REQ_SETWINDOWRGN SetWndRgn;
CESERVER_REQ_SETBACKGROUND Background;
CESERVER_REQ_SETBACKGROUNDRET BackgroundRet;
CESERVER_REQ_ACTIVATECONSOLE ActivateCon;
PanelViewInit PVI;
CESERVER_REQ_SETFONT Font;
CESERVER_REQ_GUIMACRO GuiMacro;
CESERVER_REQ_ONCREATEPROCESS OnCreateProc;
CESERVER_REQ_ONCREATEPROCESSRET OnCreateProcRet;
CESERVER_REQ_PEEKREADINFO PeekReadInfo;
MyAssertInfo AssertInfo;
CESERVER_REQ_ATTACHGUIAPP AttachGuiApp;
CESERVER_REQ_PORTABLESTARTED PortableStarted;
GuiStylesAndShifts GuiAppShifts;
CESERVER_REQ_SETFOCUS setFocus;
CESERVER_REQ_SETPARENT setParent;
CESERVER_REQ_SETGUIEXTERN SetGuiExtern;
CESERVER_REQ_START NewServer;
CESERVER_REQ_LOCKDC LockDc;
CESERVER_REQ_REGEXTCON RegExtCon;
CESERVER_REQ_GETALLTABS GetAllTabs;
CESERVER_REQ_FULLSCREEN FullScreenRet;
CESERVER_REQ_SETCONSOLORS SetConColor;
CESERVER_REQ_PROMPTACTION Prompt;
CESERVER_REQ_DUPLICATE Duplicate;
CESERVER_REQ_ALTBUFFER AltBuf;
CESERVER_REQ_SETCONSCRBUF SetConScrBuf;
CESERVER_REQ_STORECURDIR CurDir;
CESERVER_REQ_GETALLPANELS Panels;
CESERVER_PROMPTSTARTED PromptStarted;
CESERVER_PALETTE Palette;
};
DWORD DataSize() { return (this && (hdr.cbSize >= sizeof(hdr))) ? (hdr.cbSize - sizeof(hdr)) : 0; };
};
//#pragma pack(pop)
#include <poppack.h>
//#define GWL_TABINDEX 0
//#define GWL_LANGCHANGE 4
#ifdef _DEBUG
#define CONEMUALIVETIMEOUT INFINITE
#define CONEMUREADYTIMEOUT INFINITE
#define CONEMUFARTIMEOUT 120000 // Сколько ожидать, пока ФАР среагирует на вызов плагина
#else
#define CONEMUALIVETIMEOUT 1000 // Живость плагина ждем секунду
#define CONEMUREADYTIMEOUT 10000 // А на выполнение команды - 10s max
#define CONEMUFARTIMEOUT 10000 // Сколько ожидать, пока ФАР среагирует на вызов плагина
#endif
#ifndef WM_MOUSEHWHEEL
#define WM_MOUSEHWHEEL 0x020E
#endif
/*enum PipeCmd
{
SetTabs=0,
DragFrom,
DragTo
};*/
// ConEmu.dll экспортирует следующие функции
//HWND WINAPI GetFarHWND();
//void WINAPI _export GetFarVersion ( FarVersion* pfv );
//#if defined(__GNUC__)
////typedef DWORD HWINEVENTHOOK;
//#define WINEVENT_OUTOFCONTEXT 0x0000 // Events are ASYNC
//// User32.dll
//typedef HWINEVENTHOOK (WINAPI* FSetWinEventHook)(DWORD eventMin, DWORD eventMax, HMODULE hmodWinEventProc, WINEVENTPROC pfnWinEventProc, DWORD idProcess, DWORD idThread, DWORD dwFlags);
//typedef BOOL (WINAPI* FUnhookWinEvent)(HWINEVENTHOOK hWinEventHook);
//#endif
#ifdef __cplusplus
#define CERR_CMDLINEEMPTY 200
#define CERR_CMDLINE 201
#define MOUSE_EVENT_MOVE (WM_APP+10)
#define MOUSE_EVENT_CLICK (WM_APP+11)
#define MOUSE_EVENT_DBLCLICK (WM_APP+12)
#define MOUSE_EVENT_WHEELED (WM_APP+13)
#define MOUSE_EVENT_HWHEELED (WM_APP+14)
#define MOUSE_EVENT_FIRST MOUSE_EVENT_MOVE
#define MOUSE_EVENT_LAST MOUSE_EVENT_HWHEELED
//#define INPUT_THREAD_ALIVE_MSG (WM_APP+100)
//#define MAX_INPUT_QUEUE_EMPTY_WAIT 1000
BOOL PackInputRecord(const INPUT_RECORD* piRec, MSG64::MsgStr* pMsg);
BOOL UnpackInputRecord(const MSG64::MsgStr* piMsg, INPUT_RECORD* pRec);
void TranslateKeyPress(WORD vkKey, DWORD dwControlState, wchar_t wch, int ScanCode, INPUT_RECORD* rDown, INPUT_RECORD* rUp);
void CommonShutdown();
typedef void(WINAPI* ShutdownConsole_t)();
extern ShutdownConsole_t OnShutdownConsole;
struct RequestLocalServerParm;
struct AnnotationHeader;
struct AnnotationInfo;
typedef int (WINAPI* RequestLocalServer_t)(/*[IN/OUT]*/RequestLocalServerParm* Parm);
typedef BOOL (WINAPI* ExtendedConsoleWriteText_t)(HANDLE hConsoleOutput, const AnnotationInfo* Attributes, const wchar_t* Buffer, DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten);
typedef void (WINAPI* ExtendedConsoleCommit_t)();
typedef DWORD RequestLocalServerFlags;
const RequestLocalServerFlags
slsf_SetOutHandle = 1,
slsf_RequestTrueColor = 2,
slsf_PrevAltServerPID = 4,
slsf_AltServerStopped = 8,
slsf_GetFarCommitEvent = 16,
slsf_FarCommitForce = 32,
slsf_GetCursorEvent = 64,
slsf_ReinitWindows = 128,
slsf_None = 0;
struct RequestLocalServerParm
{
DWORD StructSize;
RequestLocalServerFlags Flags;
/*[IN]*/ HANDLE* ppConOutBuffer;
/*[OUT]*/ AnnotationHeader* pAnnotation;
/*[OUT]*/ RequestLocalServer_t fRequestLocalServer;
/*[OUT]*/ ExtendedConsoleWriteText_t fExtendedConsoleWriteText;
/*[OUT]*/ ExtendedConsoleCommit_t fExtendedConsoleCommit;
/*[OUT]*/ DWORD_PTR nPrevAltServerPID; // alignment
/*[OUT]*/ HANDLE hFarCommitEvent;
/*[OUT]*/ HANDLE hCursorChangeEvent;
};
#include "MAssert.h"
#include "MSecurity.h"
#endif // __cplusplus
// The size of the PROCESS_ALL_ACCESS flag increased on Windows Server 2008 and Windows Vista.
// If an application compiled for Windows Server 2008 and Windows Vista is run on Windows Server 2003
// or Windows XP/2000, the PROCESS_ALL_ACCESS flag is too large and the function specifying this flag
// fails with ERROR_ACCESS_DENIED. To avoid this problem, specify the minimum set of access rights required
// for the operation. If PROCESS_ALL_ACCESS must be used, set _WIN32_WINNT to the minimum operating system
// targeted by your application (for example, #define _WIN32_WINNT _WIN32_WINNT_WINXP).
#undef PROCESS_ALL_ACCESS
#define PROCESS_ALL_ACCESS "PROCESS_ALL_ACCESS"
#define MY_PROCESS_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF)
// This must be the end line
#endif // _COMMON_HEADER_HPP_
| [
"[email protected]"
] | |
0781881e2040dd4efdc16f09d6ed7e74f9d61f4b | bb41ed511f4b0110094fcb4f3bba7e8153acad0a | /Lab4TrojanBlastPart2/TrojanBlastClient/Src/ShipClient.cpp | e3a0d85c65215a445a165a6501cc41ae713c3323 | [] | no_license | amymelody/ITP-470-Labs | ac885b16fea16df2b91521e170681130f8ea7961 | f09a56f07900b1843c7cf6a7ee2bbb99ec419ba5 | refs/heads/master | 2021-05-27T12:36:16.346512 | 2014-10-20T01:03:20 | 2014-10-20T01:03:20 | 25,649,601 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | #include <TrojanBlastClientPCH.h>
ShipClient::ShipClient()
{
mInactiveTexture = TextureManager::sInstance->GetTexture( "spaceship" );
mThrustingTexture = TextureManager::sInstance->GetTexture( "spaceshipWithThrust" );
mSpriteComponent.reset( new SpriteComponent( this ) );
}
void ShipClient::Update()
{
Ship::Update();
//do we need to replicate this? sure we do!
if( mIsThrusting )
{
mSpriteComponent->SetTexture( mThrustingTexture );
}
else
{
mSpriteComponent->SetTexture( mInactiveTexture );
}
} | [
"[email protected]"
] | |
9713a526ecb212484ecd11010fba6357d8d97529 | e12466a26cfef4f1e79373890286d248caee8b68 | /B. BerSU Ball.cpp | 0dc54e62ac4253cc20f26893e3e2f4af9b0d8135 | [] | no_license | azhanali/Codeforces | 6362fdb031afb1881eaf4dcf44a1ec8444a94bee | 6119512dc55f239c88d72ced37e4dc7f430af105 | refs/heads/master | 2021-09-22T21:30:49.807190 | 2018-09-17T06:41:55 | 2018-09-17T06:41:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 993 | cpp | #include<cstdio>
#include<cmath>
#include<cctype>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<list>
#include<algorithm>
#include<utility>
using namespace std;
int main()
{
int n,m,a[100],b[100],i,j,count,x;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%d",&b[i]);
}
sort(a,a+n);
sort(b,b+m);
count=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
x=fabs(a[i]-b[j]);
if(x>1 && b[j]>a[i])
break;
else if(x<2 && b[j]>0)
{
count++;
b[j]=0;
break;
}
}
}
printf("%d\n",count);
}
return 0;
}
| [
"[email protected]"
] | |
df6e461d586640cdc7d34e0c0c08ff760395680f | b778ee70607a78f10f419af85cd1d092c60e0e3b | /libpkg/http_client_tests/HttpClientTest.cpp | af1a9f71235eecfd2c82167ff220cf7af3fcb9dc | [] | no_license | phaus/pkg6 | ae2ef84cd97aef70284ffaaa337fe7177111fff8 | 668a5e1b3bb876718f601ea95f00ef8f38152513 | refs/heads/master | 2020-03-12T06:34:28.422201 | 2017-06-18T01:07:22 | 2017-06-18T01:07:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | //
// Copyright (c) Till Wegmueller 2016 under CDDL
// for License see LICENSE file in root of repository
//
#include <http_client/HttpClient.h>
#include <gtest/gtest.h>
namespace {
class HTTPTest: public ::testing::Test{
public:
HTTPTest():
client(HttpClient("http", "pkg.openindiana.org", "/hipster", "openindiana.org"))
{}
virtual void SetUp(){
}
HttpClient client;
};
TEST_F(HTTPTest, Versions0){
std::map<std::string,int> ver = client.getVersion();
ASSERT_EQ(1, ver["catalog"]);
ASSERT_EQ(0, ver["p5i"]);
ASSERT_EQ(1, ver["publisher"]);
}
TEST_F(HTTPTest, Manifest0){
std::stringstream ss;
client.getManifest("web/server/[email protected],5.11-2016.0.0.0:20160730T022405Z", ss);
ASSERT_GT(ss.str().size(), 1);
}
TEST_F(HTTPTest, File1){
std::stringstream ss;
client.getFile("e85098cd7a821179b8620b48dc12d04099bff3a3", ss);
ASSERT_GT(ss.str().size(), 1);
}
} | [
"[email protected]"
] | |
e1b44e55709ce0dd443545324761139893e35109 | a63655482df93b9bef2351b5b9eb62ac85ef4257 | /cpp04/ex03/AMateria.hpp | 0c8a728237b865808bcef4580e5384806096d228 | [] | no_license | denisnadey/cpp_modules | a27c345fa1b571bedb5a77fafcbac0aecdaf1e43 | 37dfad413857a557b595c5b80b2f4f54dcc2d0f5 | refs/heads/master | 2023-08-07T05:50:49.898488 | 2021-10-04T11:09:48 | 2021-10-04T11:09:48 | 413,386,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | hpp | //
// Created by Matthos Denys on 6/3/21.
//
#ifndef EX03_AMATERIA_HPP
#define EX03_AMATERIA_HPP
# include "ICharacter.hpp"
# include <string>
# include <limits>
# include "ICharacter.hpp"
class ICharacter;
class AMateria
{
protected:
unsigned int _xp;
std::string _type;
public:
AMateria(const std::string& type);
virtual ~AMateria();
const std::string& getType() const;
unsigned int getXP() const;
virtual AMateria* clone() const = 0;
virtual void use(ICharacter& target);
};
#endif //EX03_AMATERIA_HPP
| [
"[email protected]"
] | |
3854d24b65fda022cb724a2afcef844ca68f6a12 | d77356fb02741d9411d5f46befb8c3cb204a8a6d | /ts/LSocket.h | 630a03bb27eea2f5b6ec3f19a0ae0d57d75bee7c | [] | no_license | cyz1901/winsock-lab | f262418cf042990ce2bf3ac34ae32f1bead97381 | e7d2e11a2a3212293a471908b79f04caac204bc4 | refs/heads/master | 2021-05-20T20:52:39.919715 | 2020-06-04T13:29:11 | 2020-06-04T13:29:11 | 252,411,655 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 683 | h | // LSocket.h: interface for the CLSocket class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_LSOCKET_H__INCLUDED_)
#define AFX_LSOCKET_H__INCLUDED_
class CTsDlg;
//专用于监听客户端连接请求的侦听套接字类定义
class CLSocket : public CSocket
{
DECLARE_DYNAMIC(CLSocket);
//Construction
public:
CLSocket(CTsDlg* pDlg);
virtual ~CLSocket();
// Attributes
public:
CTsDlg* m_pDlg; //成员变量
// Overridable Callbacks
//可重载的回调函数,当套接字收到连接请求时,自动调用此函数
protected:
virtual void OnAccept(int nErrorCode);
};
#endif // !defined(AFX_LSOCKET_H__INCLUDED_)
| [
"[email protected]"
] | |
d5cfb1ccad56a27b2257759184e76c4d8ec71517 | 89b14c44bd593d9b4c0ad5d266bd51569429771f | /Oasis/src/Oasis/Events/Event.h | 6d3461f65d2724bec4e9d5d422d9170bfc5cbd27 | [] | no_license | Niemand-co/Oasis | a1adbab3c8b4a557b2a51e6fe234d3dc1acad152 | 2967ff0057c31416e923157890b3b119f3fa2a03 | refs/heads/main | 2023-06-30T07:43:59.461882 | 2021-08-04T14:05:05 | 2021-08-04T14:05:05 | 384,335,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | h | #pragma once
#include "OApch.h"
#include "Oasis/Core/Core.h"
namespace Oasis {
enum class EventType {
None = 0,
WindowClose, WindowResize, WindowFocus, WIndowLosFocus, WindowMov,
AppTick, AppUpdate, AppRender,
KeyPressed, KeyReleased, KeyTyped,
MouseButtonPressed, MouseButtonReleased, MouseMoved, MouseScrolled
};
enum EventCategory {
None = 0,
EventCategoryApplication = BIT(0),
EventCategoryInput = BIT(1),
EventCategoryKeyboard = BIT(2),
EventCategoryMouse = BIT(3),
EventCategoryMouseButton = BIT(4)
};
#define EVENT_CLASS_TYPE(type) static EventType GetStaticType(){return EventType::##type;}\
virtual EventType GetEventType() const override {return GetStaticType();}\
virtual const char* GetName() const override {return #type;}
#define EVENT_CLASS_CATEGORY(category) virtual int GetCategoryFlags() const override{return category;}
class OASIS_API Event {
friend class EventDispatcher;
public:
virtual EventType GetEventType() const = 0;
virtual const char* GetName() const = 0;
virtual int GetCategoryFlags() const = 0;
virtual std::string ToString() const { return GetName(); }
inline bool isInCategory(EventCategory category) {
return GetCategoryFlags() & category;
}
bool m_Handled = false;
};
class OASIS_API EventDispatcher {
template<typename T>
using EventFunc = std::function<bool(T&)>;
public:
EventDispatcher(Event& event) : m_Event(event) {}
template<typename T>
bool DispatchEvent(EventFunc<T> Func) {
if (m_Event.GetEventType() == T::GetStaticType()) {
m_Event.m_Handled = Func(*(T*)&m_Event);
return true;
}
return false;
}
private:
Event& m_Event;
};
inline std::ostream& operator<<(std::ostream& os, const Event& event){
return os << event.ToString();
}
} | [
"[email protected]"
] | |
fa8be3270a0400e73c24ee07ec803b2bd861775b | 399b5e377fdd741fe6e7b845b70491b9ce2cccfd | /LLVM_src/libcxx/test/std/utilities/utility/pairs/pairs.pair/types.pass.cpp | abda1d8c3b9c277e813a0c26b40c83cc9e5b5d10 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0"
] | permissive | zslwyuan/LLVM-9-for-Light-HLS | 6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab | ec6973122a0e65d963356e0fb2bff7488150087c | refs/heads/master | 2021-06-30T20:12:46.289053 | 2020-12-07T07:52:19 | 2020-12-07T07:52:19 | 203,967,206 | 1 | 3 | null | 2019-10-29T14:45:36 | 2019-08-23T09:25:42 | C++ | UTF-8 | C++ | false | false | 735 | cpp | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <utility>
// template <class T1, class T2>
// struct pair
// {
// typedef T1 first_type;
// typedef T2 second_type;
#include <utility>
#include <type_traits>
int main()
{
typedef std::pair<float, short*> P;
static_assert((std::is_same<P::first_type, float>::value), "");
static_assert((std::is_same<P::second_type, short*>::value), "");
}
| [
"[email protected]"
] | |
372e6774e81bdd525db2a8bcb7c64b3425cd74b6 | 91448636f2526eb9e2c91b744fc7c0828cb23048 | /slist/slist.cpp | 245961e0b0e65db4ebe83dd69ab963826044732e | [] | no_license | hef/strup | 8d6c5fa0db0ab5f1bea51848b78efb97c6ba07ba | f2cd29d87a561821279c62ee244e2692be6824fb | refs/heads/master | 2021-01-20T05:07:41.598132 | 2014-08-07T04:20:07 | 2014-08-07T04:20:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | #include "slist.h"
#include <assert.h>
#include <future>
template <typename T>
struct node
{
T data;
node(T data) : data(data){}
node<T>* slist_next;
};
int main(int, char* [])
{
slist<node<int>> nodes;
nodes.head = nullptr;
node<int>* pNode = nullptr;
pNode = nodes.pop();
assert( nullptr == pNode);
nodes.push(new node<int>(1));
nodes.push(new node<int>(2));
nodes.push(new node<int>(3));
pNode = nodes.pop();
assert( 3 == pNode->data);
delete pNode;
pNode = nodes.pop();
assert( 2 == pNode->data);
delete pNode;
pNode = nodes.pop();
assert( 1 == pNode->data );
delete pNode;
pNode = nodes.pop();
assert(nullptr == pNode );
std::async([&]{
std::chrono::seconds duration(1);
std::this_thread::sleep_for(duration);
nodes.push(new node<int>(8));
});
pNode = nodes.waitPop();
assert( 8 == pNode->data );
return 0;
}
| [
"[email protected]"
] | |
05fb334ba3dd6ed651563c0c6607b1760675bd7c | a16521b981a93d3c59e72e25c034e44f6c04ce12 | /client/chats/CELLMenu.h | 1c26a41c40cb261ecfe9f9a8d8d5ccb953c22bdf | [] | no_license | ch1ch/chat9-- | 504ec097cef7fb8353a3b8602eb148aeecfd597b | 1f68ab6bcbbf3acee1bc84984c17b98698155ef6 | refs/heads/master | 2021-03-19T13:18:15.940072 | 2013-09-10T10:33:05 | 2013-09-10T10:33:05 | 12,726,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | h | //
// CELLMenu.h
// chats
//
// Created by 付剑超 on 13-8-30.
//
//
#ifndef __chats__CELLMenu__
#define __chats__CELLMenu__
#include <iostream>
#include <iostream>
#include "cocos2d.h"
USING_NS_CC;
class CELLMenu : public CCMenu
{
private:
//设置一个点击区域,用于判断点击是否在这个区域内
CCRect _rect;
//是否滑动了MenuItem
bool _isScroll;
public:
//重写registerWithTouchDispatcher函数,设置优先级
virtual void registerWithTouchDispatcher();
//create方法,传进来的是可以响应点击的区域
static CELLMenu* create(CCRect rect);
//重写三个touch函数
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch *touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
};
#endif /* defined(__Test__CELLMenu__) */
| [
"[email protected]"
] | |
1db045c37b0a92f57d38f9925a12914cd5c0a24a | 812f339f6c800c5240f71d23cdc73a61aa82f320 | /graph_2015_1_24_mfcDlg.cpp | e5cc9a04f387c2c9a127c887355ae17aefc7600c | [] | no_license | YuhanSun/Graph | b3fd59169511e0b488bbc6ec336475f167e45070 | 0a175e33830ccaf6a198921f8ad94327d1a90316 | refs/heads/master | 2021-01-17T07:42:37.423410 | 2016-07-11T21:10:36 | 2016-07-11T21:10:36 | 30,267,197 | 0 | 0 | null | 2015-02-13T22:38:06 | 2015-02-03T22:08:08 | C++ | UTF-8 | C++ | false | false | 102,414 | cpp |
// graph_2015_1_24_mfcDlg.cpp : implementation file
//
#include "stdafx.h"
#include "graph_2015_1_24_mfc.h"
#include "graph_2015_1_24_mfcDlg.h"
#include "afxdialogex.h"
#include <string>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define MAX_DATA_SIZE = 10000000000;
//vector<vector<int>> graph = ReadVectorFromDisk("size/graph20.txt");
//vector<vector<int>> graph_v = ReadVectorFromDisk("size/graph19.txt");
vector<vector<int>> m_graph_v;
vector<vector<int>> m_graph_inedge_v;
vector<Entity> m_entity;
int m_range;
int m_node_count;
int m_edge_count;
double m_nonspatial_ratio;
string m_path;
//typedef RTree<int, double, 2, double> MyTree;
//MyTree tree;
vector<int> graph_a[1048576];
int node_count = pow(2,23);
int range = -1;
//ofstream filetime;
bool RBSearch_RTree_TransitiveClosure(int start_id, MyRect rect, vector<vector<int>> &transitive_closure);
bool RBSearch_RTree_TransitiveClosure(int start_id, MyRect rect, vector<vector<int>> &transitive_closure)
{
/*ResetHitID(m_node_count);
Rect search_rect = Rect(rect.left_bottom.x, rect.left_bottom.y, rect.right_top.x, rect.right_top.y);
tree.Search(search_rect.min, search_rect.max, MySearchCallback, NULL);
vector<int> hit_id = GetHitID();
for (int i = 0; i < hit_id.size(); i++)
{
int id = hit_id[i];
for (int j = 0; j < transitive_closure[start_id].size(); j++)
{
if (id == transitive_closure[start_id][j])
return true;
}
}
return false;*/
return false;
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// Cgraph_2015_1_24_mfcDlg dialog
Cgraph_2015_1_24_mfcDlg::Cgraph_2015_1_24_mfcDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(Cgraph_2015_1_24_mfcDlg::IDD, pParent)
, m_starttype(0)
, m_entity_name(_T(""))
, m_step(0)
, m_startspatialrange(0)
, m_endspatialrangeratio(0)
, m_duplicate_times(0)
, m_start_vertex(0)
, m_status_value(0)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
// m_status_value = 0;
}
void Cgraph_2015_1_24_mfcDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, m_starttype);
DDX_CBString(pDX, IDC_COMBO1, m_entity_name);
DDX_Control(pDX, IDC_COMBO1, m_combo);
DDX_Text(pDX, IDC_EDITSpatialRangeRatioStep, m_step);
DDX_Text(pDX, IDC_EDITStartSpatialRangeRatio, m_startspatialrange);
DDX_Text(pDX, IDC_EDITEndSpatialRangeRatio, m_endspatialrangeratio);
DDX_Text(pDX, IDC_EDIT_Duplicate_times, m_duplicate_times);
DDX_Text(pDX, IDC_EDIT_startvertex, m_start_vertex);
}
BEGIN_MESSAGE_MAP(Cgraph_2015_1_24_mfcDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_test, &Cgraph_2015_1_24_mfcDlg::OnBnClickedtest)
ON_BN_CLICKED(IDOK, &Cgraph_2015_1_24_mfcDlg::OnBnClickedOk)
ON_BN_CLICKED(IDC_BUTTON1, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON3, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButton3)
ON_BN_CLICKED(IDC_BUTTON2, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButton2)
ON_BN_CLICKED(IDC_BUTTON4, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButton4)
ON_BN_CLICKED(IDC_HopTest, &Cgraph_2015_1_24_mfcDlg::OnBnClickedHoptest)
ON_BN_CLICKED(IDC_SizeTest, &Cgraph_2015_1_24_mfcDlg::OnBnClickedSizetest)
ON_BN_CLICKED(IDC_BUTTONGenerateGraph, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtongenerategraph)
ON_BN_CLICKED(IDC_BUTTONRatioTest, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonratiotest)
// ON_BN_CLICKED(IDC_BUTTONCOMPARISON, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtoncomparison)
ON_CBN_SELCHANGE(IDC_COMBO1, &Cgraph_2015_1_24_mfcDlg::OnCbnSelchangeCombo1)
ON_EN_CHANGE(IDC_EDIT1, &Cgraph_2015_1_24_mfcDlg::OnEnChangeEdit1)
ON_BN_CLICKED(IDC_BUTTONSpatialFirst, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonspatialfirst)
ON_BN_CLICKED(IDC_BUTTONSpatialFirstTest, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonspatialfirsttest)
ON_BN_CLICKED(IDC_BUTTONSocialFirstTest, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonsocialfirsttest)
ON_EN_CHANGE(IDC_EDITStartSpatialRangeRatio, &Cgraph_2015_1_24_mfcDlg::OnEnChangeEditstartspatialrangeratio)
ON_EN_CHANGE(IDC_EDITSpatialRangeRatioStep, &Cgraph_2015_1_24_mfcDlg::OnEnChangeEditspatialrangeratiostep)
ON_EN_CHANGE(IDC_EDITEndSpatialRangeRatio, &Cgraph_2015_1_24_mfcDlg::OnEnChangeEditendspatialrangeratio)
ON_BN_CLICKED(IDC_BUTTONInitialize, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtoninitialize)
ON_EN_CHANGE(IDC_EDIT_Duplicate_times, &Cgraph_2015_1_24_mfcDlg::OnEnChangeEditDuplicatetimes)
ON_BN_CLICKED(IDC_BUTTONCOMPARISON, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtoncomparison)
ON_BN_CLICKED(IDC_BUTTON_RMBR, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRmbr)
ON_EN_CHANGE(IDC_EDIT_startvertex, &Cgraph_2015_1_24_mfcDlg::OnEnChangeEditstartvertex)
ON_BN_CLICKED(IDC_RMBR_Initizlize, &Cgraph_2015_1_24_mfcDlg::OnBnClickedRmbrInitizlize)
ON_BN_CLICKED(IDC_ReachQuery, &Cgraph_2015_1_24_mfcDlg::OnBnClickedReachquery)
ON_BN_CLICKED(IDC_BUTTON_Generation_Test, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGenerationTest)
ON_BN_CLICKED(IDC_BUTTON_Read, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRead)
ON_BN_CLICKED(IDC_BUTTON_DAG_Generate, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonDagGenerate)
ON_BN_CLICKED(IDC_BUTTON_Entity, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonEntity)
ON_BN_CLICKED(IDC_BUTTON_RandomGraph_Generate, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRandomgraphGenerate)
ON_BN_CLICKED(IDC_BUTTON_RealData_Generate, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRealdataGenerate)
ON_BN_CLICKED(IDC_BUTTON_Gen_Entity, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGenEntity)
ON_BN_CLICKED(IDC_BUTTON_Spatial_Tran, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonSpatialTran)
ON_BN_CLICKED(IDC_BUTTON_Transform, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonTransform)
ON_BN_CLICKED(IDC_BUTTON_Graph_Transform, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGraphTransform)
ON_BN_CLICKED(IDC_BUTTON_Reserse_Transform, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonReserseTransform)
ON_BN_CLICKED(IDC_BUTTONGrid_Generate, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtongridGenerate)
ON_BN_CLICKED(IDC_BUTTON_GEOREACH_GENERATE, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGeoreachGenerate)
ON_BN_CLICKED(IDC_BUTTON_GeoReach_GraphConvert, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGeoreachGraphconvert)
ON_BN_CLICKED(IDC_BUTTON_GeoReach_EntityConvert, &Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGeoreachEntityconvert)
END_MESSAGE_MAP()
// Cgraph_2015_1_24_mfcDlg message handlers
BOOL Cgraph_2015_1_24_mfcDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
m_combo.AddString(_T("entity1"));
m_combo.AddString(_T("entity2"));
m_combo.AddString(_T("entity3"));
m_combo.SetCurSel(2);
// ReadEntityFromDisk(node_count, entity_vector, range,"size/entity23.txt");
// ReadArrayVectorFromDisk(graph_a, "size/graph20.txt");
return TRUE; // return TRUE unless you set the focus to a control
}
void Cgraph_2015_1_24_mfcDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void Cgraph_2015_1_24_mfcDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR Cgraph_2015_1_24_mfcDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void MultilevelTest()
{
/*string path = "D:/test.txt";
char* ch = (char*)path.data();
freopen(ch, "r", stdin);
string line;
getline(cin, line);
vector<string> l = split(line, ",");
vector<vector<bool>> index = vector<vector<bool>>(1);
index[0].resize(21844);
for (int i = 0; i < l.size(); i++)
{
int id = StringtoInt(l[i]);
index[0][id] = true;
}
int offset = 0;
for (int i = 128; i > 2; i /= 2)
{
offset += i*i;
int id = 0;
{
for (int m = 0; m < i; m += 2)
{
for (int n = 0; n < i; n += 2)
{
int grid_id = m*i + n + offset - i*i;
int true_count = 0;
if (index[0][grid_id])
true_count++;
if (index[0][grid_id + 1])
true_count++;
if (index[0][grid_id + i])
true_count++;
if (index[0][grid_id + i + 1])
true_count++;
if (true_count >= 2)
{
int mm = m / 2, nn = n / 2;
int high_level_grid_id = mm*i / 2 + nn;
index[0][high_level_grid_id + offset] = true;
SetFalseRecursive(index, id, grid_id);
SetFalseRecursive(index, id, grid_id + 1);
SetFalseRecursive(index, id, grid_id + i);
SetFalseRecursive(index, id, grid_id + i + 1);
}
}
}
}
}*/
}
void GenerateTopologicalSequence()
{
/*vector<string> filename;
filename.push_back("citeseerx");
filename.push_back("Patents");
filename.push_back("go_uniprot");
filename.push_back("uniprotenc_22m");
filename.push_back("uniprotenc_100m");
filename.push_back("uniprotenc_150m");
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
vector<vector<int>> graph;
ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
queue<int> queue;
TopologicalSort(graph, queue);
stack<int> stack;
while (!queue.empty())
{
int x = queue.front();
queue.pop();
stack.push(x);
}
string path = "data/Real_Data/" + datasource + "/topology_sort.txt";
char* ch = (char*)path.data();
freopen(ch, "w", stdout);
printf("%d\n", stack.size());
int sequence = 0;
while (!stack.empty())
{
int x = stack.top();
stack.pop();
printf("%d\t%d\n", sequence, x);
sequence++;
}
fclose(stdout);
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedtest()
{
GenerateTopologicalSequence();
//MultilevelTest();
//vector<set<int>> index;
////vector<vector<bool>> index;
//vector<int> stored;
//ReadGridPointIndexMultilevelFromDisk(128, index, "Real_Data/citeseerx/GeoReachGrid_128/GeoReachGrid_20_newpartial.txt", stored, m_node_count);
//GridPointIndexToDisk(index, "Real_Data/citeseerx/GeoReachGrid_128/GeoReachGrid_20_newpartial_readtest.txt", stored,m_node_count);
/*vector<Entity> entity1,entity2;
ReadEntityInSCCFromDisk(m_node_count, entity1, m_range, "Real_Data/citeseer/Random_spatial_distributed/20/entity.txt");
ReadEntityInSCCFromDisk(m_node_count, entity2, m_range, "Real_Data/citeseer/Random_spatial_distributed/20/entity.txt");
vector<set<int>> graph;
ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/citeseer/graph.txt");
int start = clock();
GenerateRMBR(entity1, graph);
int time = clock() - start;
start = clock();
GenerateRMBRByQueue(entity2, graph);
time = clock() - start;
EntityInSCC_To_Disk(entity1, m_range, "Real_Data/citeseer/entity1.txt");
EntityInSCC_To_Disk(entity1, m_range, "Real_Data/citeseer/entity2.txt");
for (int i = 0; i < entity1.size(); i++)
{
if (abs(entity1[i].RMBR.left_bottom.x - entity2[i].RMBR.left_bottom.x) > 0.00000001)
{
CString str;
str.Format(TEXT("%d left_bottom.x"), i);
MessageBox(str);
}
if (abs(entity1[i].RMBR.left_bottom.y - entity2[i].RMBR.left_bottom.y) > 0.00000001)
{
CString str;
str.Format(TEXT("%d left_bottom.y"), i);
MessageBox(str);
}
if (abs(entity1[i].RMBR.right_top.x - entity2[i].RMBR.right_top.x) > 0.00000001)
{
CString str;
str.Format(TEXT("%d right_top.x"), i);
MessageBox(str);
}
if (abs(entity1[i].RMBR.right_top.y - entity2[i].RMBR.right_top.y) > 0.00000001)
{
CString str;
str.Format(TEXT("%d right_top.y"), i);
MessageBox(str);
}
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
CDialogEx::OnOK();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButton1()
{
//m_range = 1000;
//vector<set<int>> SCC;
//m_node_count = pow(2, 18);
//m_path = "RMBR/18_16/";
//m_edge_count = 16 * m_node_count;
////GenerateArbitaryGraph(graph_entity, m_node_count, m_edge_count,0.25, 0.25, 0.25);
////ArbitaryGraphToDisk(graph_entity, path + "graph_entity.txt");
////graph_entity.resize(m_node_count);
////ReadGraphFromEdge(graph_entity, path + "edgelist.txt");
////ReadArbitaryGraphFromDisk(graph_entity, m_node_count, m_path + "graph_entity.txt");
//ReadSCC(SCC, m_path + "SCC.txt");
////ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, path + "entity.txt");
//GenerateEntityInSCC(m_node_count, m_entity, m_range, 0.4);
//ConnectSCCEntity(m_entity, SCC);
//GenerateRMBR(m_entity, m_graph_v);
//EntityInSCCSeperate_To_Disk(m_entity, m_range, m_path);
//vector<set<int>> graph_SCC;
//graph_SCC.resize(SCC.size());
//GenerateSCCGraph(m_entity, m_graph_v, graph_SCC);
//ArbitaryGraphToDisk(graph_SCC, m_path + "graph_SCC.txt");
//vector<set<int>> transitive_closure = GetTransitiveClosureDynamic_In_Set(graph_SCC);
//TransitiveClosureDynamic_To_Disk(transitive_closure, 1000, m_path + "transitive_closure.txt");
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButton3()
{
// TODO: Add your control notification handler code here
//graph = ReadVectorFromDisk("size/graph16.txt");
//graph_v = ReadVectorFromDisk("rect_size/graph9.txt");
CString filter;
filter = "文本文档(*.txt)|*.txt|PDF文档(*.pdf)|*.pdf||";
CFileDialog dlg(true);//TRUE, NULL, NULL, OFN_HIDEREADONLY, filter
dlg.DoModal();
//if (dlg.DoModal() == IDOK)
{
CString str;
str = dlg.GetPathName();
MessageBox(str);
}
//CDialogTest dd;
//dd.DoModal();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButton2()
{
// TODO: Add your control notification handler code here
//vector<int> edge_type;
//edge_type.push_back(0);
//edge_type.push_back(2);
//edge_type.push_back(4);
//vector<bool> constraint_step;
//constraint_step.resize(4);
//constraint_step[0] = false;
//constraint_step[1] = false;
//constraint_step[2] = true;
//constraint_step[3] = false;
//vector<MyRect> constraint_rect;
//constraint_rect.resize(3);
//MyRect rect;
//rect.left_bottom.x = 0;
//rect.left_bottom.y = 0;
//rect.right_top.x = 300;
//rect.right_top.y = 300;
//constraint_rect[2] = rect;
//int startnode_id = rnd.GetUniDev()*m_graph_v.size()*0.5;
//vector<int> Paths;
//Paths.reserve(256 * 256 * 256 * 256 * 2 * 7);
//SetStartTime(clock());
////FindQualifiedPaths(Paths, graph_v, startnode_id, 3, edge_type, constraint_step, constraint_rect, entity_vector);
//int returntime = clock() - GetStartTime();
//
//ofstream file("data/size/time.txt", ios::app);
//file << returntime << " " << GetPathsCount() << endl;
//file.close();
//{
// vector<int> tem = Paths;
// Paths.swap(tem);
//}
//filetime << startnode_id << " " << Paths.size() << " " << time << endl;
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButton4()
{
// TODO: Add your control notification handler code here
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButton5()
{
// TODO: Add your control notification handler code here
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedHoptest()
{
// TODO: Add your control notification handler code here
//ofstream filetime, fileaveragetime;
//filetime.open("data/rect_size/time.txt");
//fileaveragetime.open("data/rect_size/average_time.txt");
//vector<int> edge_type;
//edge_type.push_back(0);
//edge_type.push_back(2);
////edge_type.push_back(4);
//vector<bool> constraint_step;
//constraint_step.resize(3);
//constraint_step[0] = false;
//constraint_step[1] = false;
//constraint_step[2] = true;
////constraint_step[3] = false;
//int recsize = 0;
//for (recsize = 50;recsize<=300;recsize+=25)
//{
// filetime << recsize << endl;
// vector<MyRect> constraint_rect;
// constraint_rect.resize(3);
// MyRect rect;
// rect.left_bottom.x = 0;
// rect.left_bottom.y = 0;
// rect.right_top.x = recsize;
// rect.right_top.y = recsize;
// constraint_rect[2] = rect;
// int sum_time = 0,sum_pathscount = 0;
// for (int j = 0; j < 30; j++)
// {
// int startnode_id = rnd.GetUniDev()*m_graph_v.size()*0.5;
// vector<int> Paths;
// int start, time;
// start = clock();
// //FindQualifiedPaths(Paths, graph_v, startnode_id, 3, edge_type, constraint_step, constraint_rect, entity_vector);
// time = clock() - start;
// filetime << startnode_id << " " << GetPathsCount() << " " << time << endl;
// sum_time += time;
// sum_pathscount += GetPathsCount();
// }
// filetime << endl;
// fileaveragetime << recsize << " " << sum_time << " " << sum_pathscount << endl;
//}
//filetime.close();
//fileaveragetime.close();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedSizetest()
{
// TODO: Add your control notification handler code here
//ofstream filetime, fileaveragetime;
//filetime.open("data/rect_size/time.txt");
//fileaveragetime.open("data/rect_size/average_time.txt");
//vector<int> edge_type;
//edge_type.push_back(0);
//edge_type.push_back(2);
//edge_type.push_back(4);
//vector<bool> constraint_step;
//constraint_step.resize(4);
//constraint_step[0] = false;
//constraint_step[1] = false;
//constraint_step[2] = true;
//constraint_step[3] = false;
//int recsize = 0;
//for (recsize = 50; recsize <= 300; recsize += 25)
//{
// filetime << recsize << endl;
// vector<MyRect> constraint_rect;
// constraint_rect.resize(4);
// MyRect rect;
// rect.left_bottom.x = 0;
// rect.left_bottom.y = 0;
// rect.right_top.x = recsize;
// rect.right_top.y = recsize;
// constraint_rect[2] = rect;
// int sum_time = 0, sum_pathscount = 0;
// for (int j = 0; j < 30; j++)
// {
// int startnode_id = rnd.GetUniDev()*m_graph_v.size()*0.5;
// vector<int> Paths;
// int start, time;
// start = clock();
// //FindQualifiedPaths(Paths, graph_v, startnode_id, 3, edge_type, constraint_step, constraint_rect, entity_vector);
// time = clock() - start;
// filetime << startnode_id << " " << GetPathsCount() << " " << time << endl;
// sum_time += time;
// sum_pathscount += GetPathsCount();
// }
// filetime << endl;
// fileaveragetime << recsize << " " << sum_time << " " << sum_pathscount << endl;
//}
//filetime.close();
//fileaveragetime.close();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtongenerategraph()
{
//Generate graphs with different ratio, mutiple by 2 from 32 to 256
/*int node_count = pow(2, 20);
double nonspatial_entity_ratio = 0.5;
double a = 0.25, b = 0.25, c = 0.25;
int start, finish, time;
string filename;
for (int ratio = 16; ratio <= 512; ratio *=2)
{
vector<vector<int>> graph_vector;
graph_vector.resize(node_count);
for (int i = 0; i < node_count; i++)
{
graph_vector[i].reserve(ratio * 2 * 2 * 2);
}
int real_ratio = ratio * 2;
INT64 edge_count = node_count*ratio;
Generate_Vector(graph_vector, node_count, edge_count, a, b, c, 0.5);
stringstream stream;
string str;
stream << real_ratio;
stream >> str;
filename = "ratio/graph" + str + ".txt";
VectorToDisk(graph_vector, filename);
}
*/
//Generate 0.4-0.6 graph and entity
/*
vector<Entity> entity;
GenerateEntity(pow(2, 23), entity, 10000, 0.2);
EntityToDIsk(entity, 10000, "comparison-0.4-0.6/entity.txt");
int node_count = pow(2, 23);
INT64 edge_count = 128 * node_count;
vector<vector<int>> graph;
double a = 0.25, b = 0.25, c = 0.25;
Generate_Vector(graph, node_count, edge_count, a, b, c, 0.4);
VectorToDisk(graph, "comparison-0.4-0.6/graph.txt");
*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonratiotest()
{
//ofstream filetime("data/ratio/time.txt", ios::app);
//ofstream fileaveragetime("data/ratio/average_time.txt", ios::app);
//int node_count = pow(2, 20);
//int range = 500;
//vector<Entity> entity;
//ReadEntityFromDisk(node_count, entity, range, "ratio/entity20.txt");
////ReadEntityFromDisk(node_count, entity, range, "entity.txt");
//vector<int> edge_type;
//edge_type.push_back(0);
//edge_type.push_back(2);
//edge_type.push_back(4);
//vector<bool> spatial_step;
//spatial_step.resize(4);
//spatial_step[0] = false;
//spatial_step[1] = false;
//spatial_step[2] = true;
//spatial_step[3] = false;
//vector<MyRect> constraint_rect;
//constraint_rect.resize(4);
//MyRect rect;
//rect.left_bottom.x = 0;
//rect.left_bottom.y = 0;
//rect.right_top.x = 200;
//rect.right_top.y = 200;
//constraint_rect[2] = rect;
//for (int ratio = 1024; ratio <= 1024; ratio *= 2)
//{
// vector<vector<int>> graph;
// stringstream stream;
// string str;
// stream << ratio;
// stream >> str;
// string filename = "ratio/graph" + str + ".txt";
// graph = ReadVectorFromDisk(filename);
// //graph = ReadVectorFromDisk("graph.txt");
// TRnd rand = time(0);
// filetime << ratio << endl;
// int sum_time = 0, sum_pathscount = 0;
// for (int i = 0; i < 30; i++)
// {
// int startnodeid = rand.GetUniDev()*node_count*0.5;
// vector<int> paths;
// int start = clock();
// FindQualifiedPaths(paths, graph, startnodeid, 3, edge_type, spatial_step, constraint_rect, entity);
// int time = clock() - start;
// filetime << startnodeid << " " << GetPathsCount() << " " << time << endl;
// sum_time += time;
// sum_pathscount += GetPathsCount();
// }
// filetime << endl;
// fileaveragetime << ratio << " " << sum_time / 30 << " " << sum_pathscount / 30 << endl;
//}
//filetime.close();
//fileaveragetime.close();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButton9()
{
// TODO: Add your control notification handler code here
}
void Cgraph_2015_1_24_mfcDlg::OnCbnSelchangeCombo1()
{
// TODO: Add your control notification handler code here
/*
string filename;
int i = m_combo.GetCurSel();
if (i == 0)
filename = "comparison/entity1.txt";
if (i == 1)
filename = "comparison/entity2.txt";
if (i == 2)
filename = "comparison/entity3.txt";
m_entity.clear();
ReadEntityFromDisk(node_count, m_entity, range, filename);
tree.RemoveAll();
for (int i = node_count / 2; i < node_count; i++)
{
Entity c_entity = m_entity[i];
double min[2];
double max[2];
min[0] = c_entity.location.x;
min[1] = c_entity.location.y;
max[0] = c_entity.location.x;
max[1] = c_entity.location.y;
tree.Insert(min, max, i);
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnEnChangeEdit1()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialogEx::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
UpdateData(true);
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonspatialfirst()
{
// TODO: Add your control notification handler code here
/*ofstream filetime("data/comparison-0.4-0.6/time_spatial_first.txt", ios::app);
ofstream fileaveragetime("data/comparison-0.4-0.6/average_time_spatial_first.txt", ios::app);
filetime << "qualified_node_count " << "path_count " << "time_RTree" << "time_graph" << "sumtime" << endl;
fileaveragetime << "spatial_ratio " << "rect_size " << "qualified_node_count " << "path_count " << "average_time_RTree" << "average_time_graph" << "average_time_sum" << endl;
filetime << m_starttype << endl;
fileaveragetime << "type=" << m_starttype << endl;
vector<int> edge_type;
edge_type.push_back(4);
edge_type.push_back(0);
double spatial_ratio = m_startspatialrange;
int size;
int end_type = m_starttype;
vector<int> paths;
for (; fabs(spatial_ratio - m_endspatialrangeratio) > 0.00000001; spatial_ratio += m_step)
{
size = m_range * sqrt(spatial_ratio);
Rect search_rect = Rect(0, 0, size, size);
filetime << spatial_ratio << " " << size << endl;
int sum_time_all = 0, sum_time_RTree = 0, sum_time_graph = 0;
int qualified_node_count;
int pathcount;
for (int i = 0; i < m_duplicate_times; i++)
{
ResetHitID(m_node_count*(1-m_nonspatial_ratio)*spatial_ratio * 2);
pathcount = 0;
int start = clock();
tree.Search(search_rect.min, search_rect.max, MySearchCallback, NULL);
vector<int> hit_id = GetHitID();
int time_RTree = clock() - start;
start = clock();
for (int j = 0; j < hit_id.size(); j++)
{
FindQualifiedPaths(paths, m_graph_v, hit_id[j], end_type, 2, edge_type, m_entity);
pathcount += GetPathsCount();
}
int time_graph = clock() - start;
filetime << hit_id.size() << " " << pathcount << " " << time_RTree << " " << time_graph << " " << time_RTree + time_graph << endl;
sum_time_RTree += time_RTree;
sum_time_graph += time_graph;
sum_time_all = sum_time_all + time_RTree + time_graph;
qualified_node_count = hit_id.size();
}
filetime << endl;
fileaveragetime << spatial_ratio << " " << size << " " << qualified_node_count << " " << pathcount << " " << sum_time_RTree / m_duplicate_times << " " << sum_time_graph / m_duplicate_times << " " << sum_time_all / m_duplicate_times << endl;
}
filetime << endl;
fileaveragetime << endl;
filetime.close();
fileaveragetime.close();*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonspatialfirsttest()
{
// TODO: Add your control notification handler code here
//ofstream filetime("data/comparison-0.2-0.8/time_spatial_first.txt", ios::app);
//ofstream fileaveragetime("data/comparison-0.2-0.8/average_time_spatial_first.txt", ios::app);
//filetime << "qualified_node_count " << "path_count " << "time" << endl;
//fileaveragetime << "spatial_ratio " << "rect_size " << "qualified_node_count " << "path_count " << "average_time" << endl;
//filetime << m_starttype << endl;
//fileaveragetime << m_starttype << endl;
//vector<int> edge_type;
//edge_type.push_back(4);
//edge_type.push_back(0);
//double spatial_ratio = m_startspatialrange;
//int size;
//int end_type = m_starttype;
//vector<int> paths;
//for (; fabs(spatial_ratio - m_endspatialrangeratio) > 0.00000001; spatial_ratio += m_step)
//{
// size = m_range * sqrt(spatial_ratio);
// Rect search_rect = Rect(0, 0, size, size);
// filetime << spatial_ratio << " " << size << endl;
// int sum_time = 0;
// int qualified_node_count;
// int pathcount;
// //for (int i = 0; i < 20; i++)
// {
// ResetHitID(m_node_count*(1 - m_nonspatial_ratio)*spatial_ratio * 2);
// pathcount = 0;
// int start = clock();
// tree.Search(search_rect.min, search_rect.max, MySearchCallback, NULL);
// vector<int> hit_id = GetHitID();
// for (int j = 0; j < hit_id.size(); j++)
// {
// FindQualifiedPaths(paths, m_graph_v, hit_id[j], end_type, 2, edge_type, m_entity);
// pathcount += GetPathsCount();
// }
// int time = clock() - start;
// filetime << hit_id.size() << " " << pathcount << " " << time << endl;
// sum_time += time;
// qualified_node_count = hit_id.size();
// }
// filetime << endl;
// //fileaveragetime << spatial_ratio << " " << size << " " << qualified_node_count << " " << sum_time / 20 << endl;
//}
//filetime << endl;
//fileaveragetime << endl;
//filetime.close();
//fileaveragetime.close();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonsocialfirsttest()
{
// TODO: Add your control notification handler code here
// ofstream filetime("data/comparison-0.2-0.8/time_social_first.txt", ios::app);
// ofstream fileaveragetime("data/comparison-0.2-0.8/average_time_social_first.txt", ios::app);
//
// filetime << "qualified_node_count " << "path_count " << "time" << endl;
// fileaveragetime << "spatial_ratio " << "rect_size " << "qualified_node_count " << "path_count " << "average_time" << endl;
//
// filetime << m_starttype << endl;
// fileaveragetime << m_starttype << endl;
//
// vector<int> edge_type;
// edge_type.push_back(0);
// edge_type.push_back(2);
// //edge_type.push_back(4);
//
// vector<bool> spatial_step;
// spatial_step.resize(4);
// spatial_step[0] = false;
// spatial_step[1] = false;
// spatial_step[2] = true;
// //spatial_step[3] = false;
//
// double spatial_ratio = m_startspatialrange;
// int size;
//
// int start_type = m_starttype;
//
// for (; fabs(spatial_ratio - m_endspatialrangeratio) > 0.00000001; spatial_ratio += m_step)
// {
// size = m_range * sqrt(spatial_ratio);
//
// filetime << spatial_ratio << " " << size << endl;
//
// vector<MyRect> constraint_rect;
// constraint_rect.resize(4);
// MyRect rect;
// rect.left_bottom.x = 0;
// rect.left_bottom.y = 0;
// rect.right_top.x = size;
// rect.right_top.y = size;
// constraint_rect[2] = rect;
//
// int sum_time = 0;
// int qualified_node_count;
// int pathcount;
//// for (int i = 0; i < 20; i++)
// {
// qualified_node_count = 0;
// pathcount = 0;
// int start = clock();
// for (int j = 0; j < node_count; j++)
// {
// if (m_entity[j].type == start_type)
// {
// qualified_node_count++;
// vector<int> paths;
// FindQualifiedPaths(paths, m_graph_v, j, 2, edge_type, spatial_step, constraint_rect, m_entity);
// pathcount += GetPathsCount();
// continue;
// }
// }
// int time = clock() - start;
// filetime << qualified_node_count << " " << pathcount << " " << time << endl;
// sum_time += time;
// }
// filetime << endl;
// //fileaveragetime << spatial_ratio << " " << size << " " << qualified_node_count << " " << pathcount << " " << sum_time / 20 << endl;
// }
// filetime << endl;
// fileaveragetime << endl;
// filetime.close();
// fileaveragetime.close();
}
void Cgraph_2015_1_24_mfcDlg::OnEnChangeEditstartspatialrangeratio()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialogEx::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
UpdateData(true);
}
void Cgraph_2015_1_24_mfcDlg::OnEnChangeEditspatialrangeratiostep()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialogEx::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
UpdateData(true);
}
void Cgraph_2015_1_24_mfcDlg::OnEnChangeEditendspatialrangeratio()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialogEx::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
UpdateData(true);
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtoninitialize()
{
// TODO: Add your control notification handler code here
/*ReadEntityFromDisk(m_node_count, m_entity, m_range, "comparison-0.4-0.6/entity.txt");
for (int i = m_node_count *m_nonspatial_ratio; i < m_node_count; i++)
{
Entity c_entity = m_entity[i];
double min[2];
double max[2];
min[0] = c_entity.location.x;
min[1] = c_entity.location.y;
max[0] = c_entity.location.x;
max[1] = c_entity.location.y;
tree.Insert(min, max, i);
}
m_graph_v = ReadVectorFromDisk("comparison-0.4-0.6/graph.txt");*/
}
void Cgraph_2015_1_24_mfcDlg::OnEnChangeEditDuplicatetimes()
{
// TODO: If this is a RICHEDIT control, the control will not
// send this notification unless you override the CDialogEx::OnInitDialog()
// function and call CRichEditCtrl().SetEventMask()
// with the ENM_CHANGE flag ORed into the mask.
// TODO: Add your control notification handler code here
UpdateData(true);
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtoncomparison()
{
// TODO: Add your control notification handler code here
//ofstream filetime("data/comparison-0.4-0.6/time_social_first.txt", ios::app);
//ofstream fileaveragetime("data/comparison-0.4-0.6/average_time_social_first.txt", ios::app);
//filetime << "qualified_node_count " << "path_count " << "time" << endl;
//fileaveragetime << "spatial_ratio " << "rect_size " << "qualified_node_count " << "path_count " << "average_time" << endl;
//filetime << "type=" << m_starttype << endl;
//fileaveragetime << "type=" << m_starttype << endl;
//vector<int> edge_type;
//edge_type.push_back(0);
//edge_type.push_back(2);
////edge_type.push_back(4);
//vector<bool> spatial_step;
//spatial_step.resize(4);
//spatial_step[0] = false;
//spatial_step[1] = false;
//spatial_step[2] = true;
////spatial_step[3] = false;
//double spatial_ratio = m_startspatialrange;
//int size;
//int start_type = m_starttype;
//for (; fabs(spatial_ratio - m_endspatialrangeratio) > 0.00000001; spatial_ratio += m_step)
//{
// size = m_range * sqrt(spatial_ratio);
// filetime << spatial_ratio << " " << size << endl;
// vector<MyRect> constraint_rect;
// constraint_rect.resize(4);
// MyRect rect;
// rect.left_bottom.x = 0;
// rect.left_bottom.y = 0;
// rect.right_top.x = size;
// rect.right_top.y = size;
// constraint_rect[2] = rect;
// int sum_time = 0;
// int qualified_node_count;
// int pathcount;
// for (int i = 0; i < m_duplicate_times; i++)
// {
// qualified_node_count = 0;
// pathcount = 0;
// int start = clock();
// for (int j = 0; j < node_count; j++)
// {
// if (m_entity[j].type == start_type)
// {
// qualified_node_count++;
// vector<int> paths;
// FindQualifiedPaths(paths, m_graph_v, j, 2, edge_type, spatial_step, constraint_rect, m_entity);
// pathcount += GetPathsCount();
// continue;
// }
// }
// int time = clock() - start;
// filetime << qualified_node_count << " " << pathcount << " " << time << endl;
// sum_time += time;
// }
// filetime << endl;
// fileaveragetime << spatial_ratio << " " << size << " " << qualified_node_count << " " << pathcount << " " << sum_time / m_duplicate_times << endl;
//}
//filetime << endl;
//fileaveragetime << endl;
//filetime.close();
//fileaveragetime.close();
}
void GenerateRMBRSort(string type)
{
/*vector<string> datasets;
datasets.push_back("citeseerx");
datasets.push_back("go_uniprot");
datasets.push_back("Patents");
datasets.push_back("uniprotenc_22m");
datasets.push_back("uniprotenc_100m");
datasets.push_back("uniprotenc_150m");
for (int index = 0; index < datasets.size(); index++)
{
string datasource = datasets[index];
vector<vector<int>> graph;
vector<vector<int>> in_edge_graph;
ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
GenerateInedgeGraph(graph, in_edge_graph);
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/RMBR_initialize_time.csv", ios::app);
ofile << datasource << endl;
ofile << "ratio\tsort_time\ttotal_time" << endl;
ofile.close();
for (int ratio = 20; ratio <= 80; ratio += 20)
{
m_entity.clear();
ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
queue<int> queue;
int start = clock();
TopologicalSort(graph, queue);
int sort_time = clock() - start;
start = clock();
GenerateRMBR(m_entity, in_edge_graph, queue);
int total_time = clock() - start + sort_time;
EntityInSCC_To_Disk(m_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
ofile.open("data/Real_Data/Experiment_result/" + type + "/RMBR_initialize_time.csv", ios::app);
ofile << ratio << "\t" << sort_time << "\t" << total_time << endl;
ofile.close();
}
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRmbr()
{
//GenerateRMBRSort("Clustered_distributed");
GenerateRMBRSort("Zipf_distributed");
//m_range = 1000;
//int node_count = pow(2, 21);
//INT64 edge_count = 1 * node_count;
//string path = "RMBR/2097152_21_1/";
////vector<Entity> entity;
//GenerateEntity(node_count, m_entity, m_range, 0.4);
//EntityToDisk(m_entity, m_range, path + "entity.txt");
//
////vector<vector<int>> graph;
//double a = 0.25, b = 0.25, c = 0.25;
//Generate_Vector_Noback(m_graph_v, node_count, edge_count, a, b, c, 0.4);
//VectorToDisk(m_graph_v, path + "graph.txt");
//
//edge_count = GetEdgeCount();
////ReadEntityFromDisk(m_node_count, m_entity, range, "RMBR/entity.txt");
////graph_v = ReadVectorFromDisk("RMBR/graph.txt");
//GenerateRMBR(m_entity, m_graph_v);
//RMBR_To_Disk(m_entity, m_range, path + "RMBR.txt");
//vector<set<int>> transitive_closure = GetTransitiveClosureDynamic_In_Set(m_graph_v);
//SpatialTransitiveClosureDynamic_To_Disk(transitive_closure, m_range, path + "spatial_transitive_closure.txt", m_entity);
//vector<vector<int>> transitive_closure = GetTransitiveClosure(graph_v, m_entity);
/*
string root = "data/";
root += path + "spatial_transitive_closure.txt";
char *ch = (char *)root.data();
freopen(ch, "w", stdout);
printf("%d %d\n", node_count, m_range);
fclose(stdout);
for (int i = 0; i < node_count; i++)
{
vector<int> transitive_closure_line;
transitive_closure_line = GetTransitiveClosureLine(i, graph_v, m_entity);
SpatialTransitiveClosureLine_To_Disk(transitive_closure_line, i, path + "spatial_transitive_closure.txt", m_entity);
}
*/
//SpatialTransitiveClosure_To_Disk(transitive_closure, m_range, "RMBR/65536_16_1/spatial_transitive_closure.txt", m_entity);
//ReadEntityFromDisk(m_node_count, m_entity, range, "RMBR/entity.txt");
/*tree.RemoveAll();
for (int i = 0; i < m_node_count; i++)
{
double min[2];
double max[2];
min[0] = m_entity[i].location.x;
min[1] = m_entity[i].location.y;
max[0] = m_entity[i].location.x;
max[1] = m_entity[i].location.y;
tree.Insert(min, max, i);
}*/
//ReadRmbr(m_entity, range, "RMBR/RMBR.txt");
//graph_v = ReadVectorFromDisk("RMBR/graph.txt");
//vector<vector<int>> transitive_closure = GetTransitiveClosure(graph_v, m_entity);
//vector<MyRect> RMBR = GetRMBRFromTransitiveClosure(transitive_closure, m_entity);
//TransitiveClosure_To_Disk(transitive_closure, range, "RMBR/transitive_closure.txt");
//TransitiveClosureRMBR_To_Disk(RMBR, range, "RMBR/Transitive_closure_RMBR.txt");
/*
MyRect query_rect;
query_rect.left_bottom.x = 0;
query_rect.left_bottom.y = 0;
query_rect.right_top.x = 50;
query_rect.right_top.y = 50;
for (int start_id = 0; start_id < node_count; start_id++)
{
Initialize_Visited_vertex();
bool result1 = ReachabilityQuery(m_entity, graph_v, start_id, query_rect);
bool result2 = RBSearch_RTree_TransitiveClosure(start_id, query_rect, transitive_closure);
if (result1 == result2)
continue;
MessageBox(_T("false"), _T("Error"), MB_OK);
}
Initialize_Visited_vertex();
bool result1 = ReachabilityQuery(m_entity, graph_v, m_start_vertex, query_rect);
bool result2 = RBSearch_RTree_TransitiveClosure(m_start_vertex, query_rect, transitive_closure);
if (result1 == result2)
MessageBox(_T("true"), _T("Error"), MB_OK);
else
MessageBox(_T("false"), _T("Error"), MB_OK);
*/
/*for (int i = 0; i < m_entity.size(); i++)
{
if ((m_entity[i].RMBR.left_bottom.x - RMBR[i].left_bottom.x)>0.000001 || (m_entity[i].RMBR.left_bottom.y - RMBR[i].left_bottom.y) > 0.000001
|| (m_entity[i].RMBR.right_top.x - RMBR[i].right_top.x) > 0.000001 || (m_entity[i].RMBR.right_top.y - RMBR[i].right_top.y) > 0.000001)
int a = false;
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnEnChangeEditstartvertex()
{
UpdateData(true);
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedRmbrInitizlize()
{
/*m_entity.clear();
m_graph_v.clear();
ReadEntityFromDisk(m_node_count, m_entity, range, "RMBR/entity.txt");
ReadRmbr(m_entity, range, "RMBR/RMBR.txt");
m_graph_v = ReadVectorFromDisk("RMBR/graph.txt");*/
//code for experiment of GenerateRMBR
/*m_entity.clear();
m_graph_v.clear();
ReadGraph(m_graph_v, m_node_count, "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/Patents/graph.txt");
GenerateInedgeGraph(m_graph_v, m_graph_inedge_v);
ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/Patents/Random_spatial_distributed/20/entity.txt");
vector<MyRect> RMBR;
RMBR.resize(m_node_count);
queue<int> q;
TopologicalSort(m_graph_v, q);
GenerateRMBR(m_entity, m_graph_inedge_v, q, RMBR);
RMBR_To_Disk(RMBR, "rmbr.txt");*/
vector<string> datasets;
datasets.push_back("citeseerx");
datasets.push_back("go_uniprot");
datasets.push_back("Patents");
datasets.push_back("uniprotenc_22m");
datasets.push_back("uniprotenc_100m");
datasets.push_back("uniprotenc_150m");
for (int index = 0; index < datasets.size(); index++)
{
string datasource = datasets[index];
vector<vector<int>> graph;
//vector<vector<int>> in_edge_graph;
ReadGraph(graph, m_node_count, "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/" + datasource + "/graph.txt");
//GenerateInedgeGraph(graph, in_edge_graph);
ofstream ofile("RMBR_ini_time.txt", ios::app);
ofile << datasource << endl;
ofile << "ratio\tsort_time\ttotal_time" << endl;
ofile.close();
for (int ratio = 20; ratio <= 80; ratio += 20)
{
m_entity.clear();
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/" + datasource + "/" + "Random_spatial_distributed" + "/" + getstring(ratio) + "/entity.txt");
queue<int> queue;
vector<MyRect> RMBR;
RMBR.resize(m_node_count);
int start = clock();
TopologicalSort(graph, queue);
int sort_time = clock() - start;
start = clock();
//GenerateRMBR(m_entity, graph, queue, RMBR);
int total_time = clock() - start + sort_time;
ofile.open("RMBR_ini_time.txt", ios::app);
ofile << ratio << "\t" << sort_time << "\t" << total_time << endl;
ofile.close();
}
}
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedReachquery()
{
/*MyRect rect;
rect.left_bottom.x = 0;
rect.left_bottom.y = 0;
rect.right_top.x = 70;
rect.right_top.y = 70;
ofstream file_result("data/RMBR/query_result.txt");
for (int i = 0; i < m_node_count; i++)
{
Initialize_Visited_vertex();
bool result = ReachabilityQuery(m_entity, m_graph_v, i, rect);
if (result)
file_result << "true\n";
else
file_result << "false\n";
}
file_result.close();*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGenerationTest()
{
//m_range = 1000;
//m_nonspatial_ratio = 0.4;
//int node_count = pow(2, 15);
//INT64 edge_count = 1 * node_count;
//string path = "RMBR/test/";
//vector<Entity> p_entity;
//GenerateEntity(node_count, p_entity, m_range, m_nonspatial_ratio);
////EntityToDIsk(p_entity, m_range, path + "entity.txt");
//vector<vector<int>> p_graph_v, p_graph_inedge_v;
//double a = 0.25, b = 0.25, c = 0.25;
////graph_v.clear();
////graph_inedge_v.clear();
//Generate_Vector_Noback_In_Edge(p_graph_v, p_graph_inedge_v, node_count, edge_count, a, b, c, m_nonspatial_ratio);
//int count = GetEdgeCount();
////VectorToDisk(p_graph_v, path + "graph.txt");
//int start = clock();
//vector<vector<int>> transitive_closure = GetTransitiveClosure(p_graph_v);
//int time1 = clock() - start;
////TransitiveClosure_To_Disk(transitive_closure, m_range, path + "transitive_closure.txt");
//start = clock();
//vector<set<int>> transitive_closure_dynamic = GetTransitiveClosureDynamic_In_Set(p_graph_v);
//int time2 = clock() - start;
//start = clock();
//vector<hash_set<int>> hs_transitive_closure_dynamic = GetTransitiveClosureDynamic(p_graph_v);
//int time3 = clock() - start;
//TransitiveClosureDynamic_To_Disk(transitive_closure_dynamic, m_range, path + "transitive_closure_dynamic.txt");
/*for (int i = 0; i < transitive_closure.size(); i++)
{
if (transitive_closure[i].size() != transitive_closure_dynamic[i].size())
{
CString str;
str.Format(TEXT("%d"),i);
MessageBox(str);
}
set<int>::iterator end = transitive_closure_dynamic[i].end();
for (int j = 0; j < transitive_closure[i].size(); j++)
{
if (transitive_closure_dynamic[i].find(transitive_closure[i][j]) == end)
{
CString str;
str.Format(TEXT("%d "), TEXT("%d"), i, j);
MessageBox(str);
}
}
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRead()
{
//string path = "RMBR/test/";
//ReadEntityFromDisk(m_node_count, m_entity, m_range, path + "entity.txt");
//m_graph_v = ReadVectorFromDisk(path + "graph.txt");
//vector<hash_set<int>> transitive_closure_dynamic = GetTransitiveClosureDynamic(m_graph_v);
//TransitiveClosureDynamic_To_Disk(transitive_closure_dynamic, m_range, path + "transitive_closure_dynamic.txt");
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonDagGenerate()
{
/*
for (int k = 5; k < 9; k++)
{
m_node_count = pow(2, 18);
int ratio = k;
m_edge_count = ratio * m_node_count;
vector<set<int>> dag;
m_path = "RMBR/DAG/18_"+getstring(ratio)+"/";
GenerateDAG(dag, m_node_count, m_edge_count);
ArbitaryGraphToDisk(dag, m_path + "/dag.txt");
//ReadArbitaryGraphFromDisk(dag, m_node_count, m_path + "dag.txt");
ofstream ofile(m_path + "transitive_closure.txt", ios::out);
ofile.close();
for (int i = 0; i < m_node_count; i++)
{
vector<int> current_tran = GetTransitiveClosureLineArbitary(i, dag);
TransitiveClosureLine_To_Disk(current_tran, i, m_path + "/transitive_closure.txt", m_node_count);
}
GenerateEntityInSCC(m_node_count, m_entity, 1000, 0.4);
GenerateRMBR(m_entity, dag);
EntityInSCCSeperate_To_Disk(m_entity, 1000, m_path);
}
*/
//string m_path = "Real_Data/Patents";
//m_nonspatial_ratio = 0.8;
////hash_map<int, int> id_index;
//vector<vector<int>> real_graph;
//
//
////ReadID(id_index, m_path + "/entity_id.txt");
////ReadArbitaryGraphFromDisk(real_graph, id_index, m_path + "/edgelist.txt", 5);
//ReadGraphFromEdge(real_graph, m_node_count, m_path + "/edgelist.txt", 5);
//
////m_node_count = real_graph.size();
//m_range = 1000;
////ArbitaryGraphEdgeToDisk(real_graph, m_path + "/transform/edgelist.txt");
//GenerateEntityInSCC(m_node_count, m_entity, m_range, m_nonspatial_ratio);
//GenerateRMBR(m_entity, real_graph);
//EntityInSCCSeperate_To_Disk(m_entity, m_range, m_path + "/Random_spatial_distributed/80");
/*for (int i = 0; i < m_node_count; i++)
{
vector<int> trans = GetTransitiveClosureLine(i, real_graph);
TransitiveClosureLine_To_Disk(trans, i, m_path + "/transform/transitive_closure.txt", m_node_count);
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonEntity()
{
// TODO: Add your control notification handler code here
/*m_node_count = pow(2, 18);
int ratio = 1;
m_edge_count = ratio * m_node_count;
m_range = 1000;
m_nonspatial_ratio = 0.4;
vector<set<int>> dag;
m_path = "RMBR/DAG/18_4/";
ReadArbitaryGraphFromDisk(dag, m_node_count, m_path + "dag.txt");
GenerateEntityInSCC(m_node_count, m_entity, m_range, m_nonspatial_ratio);
GenerateRMBR(m_entity, dag);
EntityInSCCSeperate_To_Disk(m_entity, m_range, "RMBR/DAG/18_4");*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRandomgraphGenerate()
{
//vector<set<int>> graph_entity, SCC, graph_SCC;
//for (int k = 6;k<11 ; k++)
//{
// m_range = 1000;
// m_node_count = pow(2, 18);
// int ratio = k;
// m_edge_count = ratio * m_node_count;
//
// m_path = "RMBR/18_" + getstring(ratio);
//
//
// //GenerateArbitaryGraph(graph_entity, m_node_count, m_edge_count);
// //ArbitaryGraphToDisk(graph_entity, m_path + "/graph_entity.txt");
// /*
// for (int i = 0; i < m_node_count; i++)
// {
// graph_entity[i].clear();
// }
// graph_entity.clear();*/
//
// ReadArbitaryGraphFromDisk(graph_entity, m_node_count, m_path + "/graph_entity.txt");
// ReadSCC(SCC, m_path + "/SCC.txt");
// GenerateEntityInSCC(m_node_count, m_entity, m_range, 0.4);
// ConnectSCCEntity(m_entity, SCC);
// GenerateRMBR(m_entity, graph_entity);
// EntityInSCCSeperate_To_Disk(m_entity, m_range, m_path);
// graph_SCC.resize(SCC.size());
// GenerateSCCGraph(m_entity, graph_entity, graph_SCC);
// ArbitaryGraphToDisk(graph_SCC, m_path + "/graph_SCC.txt");
//
//
// //ReadArbitaryGraphFromDisk(graph_SCC, m_node_count, m_path + "/graph_SCC.txt");
// for (int i = 0; i < m_node_count; i++)
// {
// vector<int> transitive_closure = GetTransitiveClosureLineArbitary(i, graph_SCC);
// TransitiveClosureLine_To_Disk(transitive_closure, i, m_path + "/transitive_closure.txt", m_node_count);
// }
// for (int i = 0; i < m_node_count; i++)
// {
// graph_entity[i].clear();
// }
// graph_entity.clear();
// for (int i = 0; i < SCC.size(); i++)
// {
// SCC[i].clear();
// graph_SCC[i].clear();
// }
// SCC.clear();
// graph_SCC.clear();
// m_entity.clear();
//}
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonRealdataGenerate()
{
//string m_path = "Real_Data/WikiTalk";
vector<string> filename;
//filename.push_back("citeseer");
//filename.push_back("citeseerx");
//filename.push_back("go_uniprot");
//filename.push_back("uniprotenc_22m");
//filename.push_back("uniprotenc_100m");
//filename.push_back("uniprotenc_150m");
filename.push_back("Patents");
//TRnd Rnd = time(0);
//int testingcount = 1000;
//for (int i = 0; i < filename.size(); i++)
//{
// string m_path = "Real_Data/" + filename[i];
// vector<vector<int>> real_graph;
// ReadArbitaryGraphFromDisk(real_graph, m_node_count, m_path + "/graph.txt");
// int start = clock();
// double total_count = 0;
// //for (int j = 0; j < testingcount; j++)
// vector<int> trans;
// int id = 225232;
//
// //int id = Rnd.GetUniDev()*m_node_count;
// trans = GetTransitiveClosureLineArbitary(id, real_graph);
// //total_count += trans.size();
// //TransitiveClosureLine_To_Disk(trans, i, m_path + "/transitive_closure.txt", m_node_count);
//
// int time = clock() - start;
// //ofstream file("data/Real_Data/"+filename[i]+"/average_transitive_size.txt", ios::app);
// ofstream file("data/Real_Data/" + filename[i] + "/reachable_vertices.csv");
// //file << " building transitive closure time: " << time;
// //file << testingcount << "\t" << total_count / testingcount;
// file << trans.size() << endl;
// for (int j = 0; j < trans.size(); j++)
// file << trans[j] << "\t";
// file << endl;
//
// file.close();
//}
//ReadArbitaryGraphFromDisk(real_graph, m_node_count, m_path + "/SCC_Graph.txt");
//ReadGraphFromEdge(real_graph, m_node_count, m_path + "/edgelist.txt",5);
/*
//ReadID(id_index, m_path + "/entity_id.txt");
//ReadArbitaryGraphFromDisk(real_graph, id_index, m_path + "/edgelist.txt", 5);
ReadGraphFromEdge(real_graph, m_node_count, m_path + "/WikiTalk.txt", 3);
//ArbitaryGraphToDisk(real_graph, m_path + "/graph_entity.txt");
vector<set<int>> SCC;
ReadSCC(SCC, m_path + "/SCC.txt");
//m_node_count = real_graph.size();
m_range = 1000;
//ArbitaryGraphEdgeToDisk(real_graph, m_path + "/transform/edgelist.txt");
GenerateEntityInSCC(m_node_count, m_entity, m_range, m_nonspatial_ratio);
ConnectSCCEntity(m_entity, SCC);
vector<set<int>> SCC_Graph;
SCC_Graph.resize(SCC.size());
GenerateSCCGraph(m_entity, real_graph, SCC_Graph);
ArbitaryGraphToDisk(SCC_Graph, m_path + "/SCC_Graph.txt");*/
}
void GenerateZipfData(pair<string,int> datasource)
{
/*for (int nonspatial_ratio = 20; nonspatial_ratio <= 80; nonspatial_ratio += 20)
{
vector<Entity> p_entity;
GenerateZipfEntityInSCC(datasource.second, p_entity, 1000, nonspatial_ratio / 100.0);
EntityInSCC_To_Disk(p_entity, 1000, "Real_Data/" + datasource.first + "/Zipf_distributed/" + getstring(nonspatial_ratio) + "/entity.txt");
}*/
}
void GenerateClusteredData(pair<string, int> datasource)
{
//m_range = 1000;
//int center_count = 4;
//TRnd Rnd = time(0);
//vector<Location> centers;
//vector<double> sigmas;
//vector<double> proportions;
//vector<double> v;
//double sum = 0;
//for (int i = 0; i < center_count; i++)
//{
// double x = Rnd.GetUniDev();
// sum += x;
// v.push_back(x);
//}
//for (int i = 0; i < center_count; i++)
//{
// double x = Rnd.GetUniDev()*m_range;
// double y = Rnd.GetUniDev()*m_range;
// Location center(x,y);
// centers.push_back(center);
// sigmas.push_back(Rnd.GetUniDev()*40+30);
// proportions.push_back(v[i]/sum);
//}
//for (int nonspatial_ratio = 20; nonspatial_ratio <= 80; nonspatial_ratio += 20)
//{
// m_entity.clear();
// GenerateClusteredEntityInSCC(datasource.second, m_entity, m_range, nonspatial_ratio / 100.0,centers, sigmas, proportions);
// EntityInSCC_To_Disk(m_entity, m_range, "Real_Data/" + datasource.first + "/Clustered_distributed/" + getstring(nonspatial_ratio) + "/entity.txt");
//}
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGenEntity()
{
vector<pair<string, int>> graphs;
graphs.push_back(make_pair("citeseerx", 6540401));
graphs.push_back(make_pair("go_uniprot", 6967956));
graphs.push_back(make_pair("Patents", 3774768));
graphs.push_back(make_pair("uniprotenc_22m", 1595444));
graphs.push_back(make_pair("uniprotenc_100m", 16087295));
graphs.push_back(make_pair("uniprotenc_150m", 25037600));
m_range = 1000;
for (int i = 0; i < graphs.size(); i++)
GenerateZipfData(graphs[i]);
//GenerateClusteredData(graphs[i]);
//vector<set<int>> graph;
//ofstream ofile("data/Real_Data/RMBR_construct_time_new.txt", ios::app);
////for (int j = 0; j < graphs.size(); j++)
//int j = 3;
//{
// graph.clear();
// m_path = "Real_Data/" + graphs[j].first;
// m_node_count = graphs[j].second;
// ofile << graphs[j].first << endl;
// ofile << "ratio\t" << "RMBR_size\n";
// ReadArbitaryGraphFromDisk(graph, m_node_count, m_path + "/graph.txt");
// for (int times = 0; times < 10; times++)
// {
// for (int i = 20; i < 100; i += 20)
// {
// m_nonspatial_ratio = i / 100.0;
// m_entity.clear();
// //GenerateEntityInSCC(m_node_count, m_entity, m_range, m_nonspatial_ratio);
// //GenerateRMBR(m_entity, graph);
// ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, m_path + "/Random_spatial_distributed/" + getstring(i) + "/entity.txt");
// /*long size = 0;
// for (int k = 0; k < m_entity.size(); k++)
// {
// if (abs(m_entity[k].RMBR.left_bottom.x + 1) < 0.000000001)
// continue;
// double x = m_entity[k].RMBR.left_bottom.x;
// size += sizeof(x) * 4;
// }
// ofile << i << "\t" << size << endl;*/
// long start = clock();
// GenerateRMBR(m_entity, graph);
// long time = clock() - start;
// ofile << i << "\t" << time << endl;
// //EntityInSCC_To_Disk(m_entity, m_range, m_path + "/Random_spatial_distributed/" + getstring(i) + "/entity.txt");
// }
// ofile << endl;
// }
//
//}
//ofile.close();
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonSpatialTran()
{
/*string m_path = "Real_Data/Patents";
m_node_count = 3774768;
vector<vector<int>> tran;
ReadTransitiveClosureFromDisk(tran, m_node_count, m_path + "/transitive_closure.txt");
for (int i = 20; i < 100; i += 20)
{
string entity_path = m_path + "/Random_spatial_distributed/" + getstring(i);
string spatial_tran_path = "data/Real_Data/Patents/Random_spatial_distributed/" + getstring(i) + "/spatial_transitive_closure.txt";
m_entity.clear();
ReadEntityInSCCSeperateFromDisk(m_node_count, m_entity, m_range, entity_path);
char *ch = (char*)spatial_tran_path.data();
freopen(ch, "w", stdout);
for (int j = 0; j < m_node_count; j++)
{
vector<int> line;
line.reserve(tran[j].size());
for (int k = 0; k < tran[j].size(); k++)
{
int end_id = tran[j][k];
if (m_entity[end_id].IsSpatial)
line.push_back(end_id);
}
printf("%d %d ", j, line.size());
for (int k = 0; k < line.size(); k++)
printf("%d ", line[k]);
printf("\n");
}
fclose(stdout);
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonTransform()
{
vector<string> filename;
//filename.push_back("test.txt");
//filename.push_back("citeseer");
//filename.push_back("citeseerx");
//filename.push_back("go_uniprot");
//filename.push_back("uniprotenc_22m");
//filename.push_back("uniprotenc_100m");
//filename.push_back("uniprotenc_150m");
/*string infilepath = "D:/grail-master/grail-master/Downloads";
for (int i = 0; i < filename.size(); i++)
{
string path = infilepath + "/" + filename[i] + ".txt";
char* ch = (char*)path.data();
freopen(ch, "r", stdin);
string line;
SSIZE_T read;
if(!getline(cin, line))
MessageBox(_T("format mismatch"), _T("Error"), MB_OK);
scanf("%d\n", &m_node_count);
vector<set<int>> graph;
graph.resize(m_node_count);
while (getline(cin, line))
{
int index = line.find(':');
string start_str = line.substr(0, index);
int start = atoi((char*)start_str.data());
line = line.substr(index + 2, line.length());
if (line.length() == 1)
continue;
else
{
while (true)
{
index = line.find(' ');
if (index == -1)
break;
else
{
string end_str = line.substr(0, index);
int end = atoi((char*)end_str.data());
graph[start].insert(end);
line = line.substr(index + 1, line.length());
}
}
}
}
fclose(stdin);
string outfilename = "Real_Data/" + filename[i] + "/graph.txt";
ArbitaryGraphToDisk(graph, outfilename);
for (int j = 0; j < m_node_count; j++)
{
graph[j].clear();
}
graph.clear();
}*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGraphTransform()
{
//string path = "Real_Data/Patents";
//
////ArbitaryGraphToDisk(graph, path + "/graph.txt");
//vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, path + "/graph.txt");
///*for (int i = 0; i < graph.size(); i++)
//{
// for (int j = 0; j < graph[i].size(); j++)
// {
// if (i == graph[i][j])
// {
// CString str;
// str.Format(_T("%d"), i);
// MessageBox(str);
// }
// }
//}*/
//int edge_count = 0;
//for (int i = 0; i < graph.size(); i++)
//{
// edge_count += graph[i].size();
//}
//string w_path = "data/" + path + "/graph_PrunedLabel.txt";
//char *ch = (char*)w_path.data();
//freopen(ch, "w", stdout);
//printf("%d %d\n", graph.size(), edge_count);
//for (int i = 0; i < graph.size(); i++)
//{
// if (graph[i].size() != 0)
// {
// printf("%d", graph[i][0] + 1);
// for (int j = 1; j < graph[i].size(); j++)
// {
// printf(" %d", graph[i][j] + 1);
// }
// }
// printf("\n");
//}
//fclose(stdout);
/*for (int i = 0; i < graph.size(); i++)
{
if (graph[i].size() != 0)
{
set<int>::iterator iter = graph[i].begin();
printf("%d", *iter);
set<int>::iterator end = graph[i].end();
iter++;
while (iter != end)
{
printf(" %d", *iter);
iter++;
}
}
printf("\n");
}
fclose(stdout);*/
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonReserseTransform()
{
ifstream infile("D:/PrunedLabeling-master/PrunedLabeling-master/sample.graph");
string line;
int V, E;
stringstream ss;
getline(infile, line);
ss << line;
ss >> V >> E;
vector<vector<int> > G(V);
for (int i = 0; i < V; i++) {
stringstream ss;
int n;
getline(infile, line);
ss << line;
while (ss >> n) {
n--;
G[i].push_back(n);
}
}
infile.close();
/*for (int i = 0; i < G.size(); i++)
{
vector<int> tranline = GetTransitiveClosureLineArbitary(i, G);
TransitiveClosureLine_To_Disk(tranline, i, "Real_Data/Patents/tran_sample.txt", 1000);
}*/
//ArbitaryGraphToDisk(G, "Real_Data/Patents/sample/samplegraph.txt");
}
//void GenerateGridIndex()
//{
// vector<string> filename;
// filename.push_back("Patents");
// //filename.push_back("citeseerx");
// //filename.push_back("go_uniprot");
// //filename.push_back("uniprotenc_22m");
// //filename.push_back("uniprotenc_100m");
// //filename.push_back("uniprotenc_150m");
//
// for (int fileindex = 0; fileindex < filename.size(); fileindex++)
// {
// string datasource = filename[fileindex];
//
// ReadArbitaryGraphFromDisk(m_graph_v, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//
// //get in-edge graph
// vector<vector<int>> in_edge_graph;
// in_edge_graph.resize(m_node_count);
// for (int i = 0; i < m_node_count; i++)
// {
// for (int j = 0; j < m_graph_v[i].size(); j++)
// {
// int neighbor = m_graph_v[i][j];
// in_edge_graph[neighbor].push_back(i);
// }
// }
//
// Location l1;
// l1.x = 0;
// l1.y = 0;
// Location l2;
// l2.x = 1000;
// l2.y = 1000;
// int pieces = 128;
// int grid_count = pieces*pieces;
// //vector<set<int>> index1;
// vector<vector<bool>> index1;
// index1.resize(m_node_count);
// vector<vector<bool>> update;
// //vector<set<int>> update;
// //vector<vector<int>> update;
// update.resize(m_node_count);
// for (int i = 0; i < m_node_count; i++)
// {
// update[i].resize(grid_count);
// index1[i].resize(grid_count);
// }
//
// //for (int ratio = 20; ratio <= 80; ratio += 20)
// int ratio = 80;
// {
// for (int i = 0; i < m_node_count; i++)
// {
// for (int j = 0; j < grid_count; j++)
// {
// index1[i][j] = false;
// update[i][j] = false;
// }
// }
// ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/Random_spatial_distributed/" + getstring(ratio) + "/entity.txt");
// int start = clock();
// GenerateGridPointIndex(l1, l2, pieces, pieces, m_graph_v, in_edge_graph, m_entity, index1, update);
// //GenerateGridPointIndex(l1, l2, pieces, pieces, m_graph_v, m_entity, index1);
// //GenerateGridPointIndexNotInQueue(l1, l2, pieces, pieces, m_graph_v, m_entity, index1);
// int time = clock() - start;
// ofstream ofile("data/Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/construction_time.txt", ios::app);
// //ofile << ratio << "\tWithout Update" << '\t' << time << endl;
// ofile << ratio << "\tWith Update vector bool" << '\t' << time << endl;
// //ofile << ratio << "\tWith Update vector" << '\t' << time << endl;
// ofile.close();
//
// INT64 count = 0;
// //for (int i = 0; i < index1.size(); i++)
// //count += index1[i].size();
// for (int i = 0; i < index1.size(); i++)
// {
// for (int j = 0; j < index1[i].size(); j++)
// {
// if (index1[i][j])
// count += 1;
// }
// }
// for (int i = 0; i < index1.size(); i++)
// {
// //count += index1[i].size();
// }
// ofile.open("data/Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/index_size.txt", ios::app);
// ofile << ratio << "\t" << count * 4 << endl;
// ofile.close();
// //ArbitaryGraphToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_5/GeoReachGrid_" + getstring(ratio) + ".txt");
// GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/GeoReachGrid_" + getstring(ratio) + ".txt");
//
// }
// vector<vector<int>> my_graph;
// m_graph_v.swap(my_graph);
// }
//
//
//
// /*{
// vector<set<int>> index2;
// GenerateGridPointIndexNotInQueue(l1, l2, 5, 5, m_graph_v, m_entity, index2);
// ArbitaryGraphToDisk(index2, "Real_Data/Patents/index_40_noqueue.txt");
//
// }*/
//
// /*for (int i = 0; i < index1.size(); i++)
// {
// if (index1[i].size() != index2[i].size())
// {
// CString str;
// str.Format(TEXT("%d size error"), i);
// MessageBox(str);
// }
// set<int>::iterator end = index2[i].end();
// for (set<int>::iterator iter = index2[i].begin(); iter != end; iter++)
// {
// if (index1[i].find(*iter) == index1[i].end())
// {
// CString str;
// str.Format(TEXT("%d not contain"), i);
// MessageBox(str);
// }
// }
//
// }*/
//}
void SortTest()
{
string datasource = "uniprotenc_22m";
//ReadArbitaryGraphFromDisk(m_graph_v, m_node_count, "Real_Data/" + datasource + "/graph.txt");
/*
vector<vector<int>> graph;
graph.resize(6);
graph[4].push_back(5);
graph[0].push_back(2);
graph[5].push_back(0);
graph[4].push_back(0);
graph[4].push_back(1);
graph[2].push_back(3);
graph[3].push_back(1);
*/
queue<int> queue;
TopologicalSort(m_graph_v, queue);
ofstream ofile("data/Real_Data/uniprotenc_22m/GeoReachGrid_128/log_queue.txt", 'w');
int i = 0;
while (!queue.empty())
{
int id = queue.front();
queue.pop();
i++;
if (id == 1)
ofile << 1 << "\t" << i << endl;
if (id == 318633)
ofile << 318633 << "\t" << i << endl;
if (id == 707601)
ofile << 707601 << "\t" << i << endl;
if (id == 1238884)
ofile << 1238884 << "\t" << i << endl;
}
ofile.close();
}
void GenerateGridSequence(string type)
{
{
vector<string> filename;
//filename.push_back("citeseerx");
filename.push_back("Patents");
//filename.push_back("go_uniprot");
//filename.push_back("uniprotenc_22m");
//filename.push_back("uniprotenc_100m");
//filename.push_back("uniprotenc_150m");
for (int fileindex = 0; fileindex < filename.size(); fileindex++)
{
string datasource = filename[fileindex];
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1;
l1.x = 0;
l1.y = 0;
Location l2;
l2.x = 1000;
l2.y = 1000;
int pieces = 128;
int grid_count = pieces*pieces;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/FullGrid_initialize_time.txt", ios::app);
ofile << datasource << endl;
ofile.close();
for (int ratio = 20; ratio <= 20; ratio += 20)
{
vector<vector<bool>> index1;
index1.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
index1[i].resize(grid_count);
}
queue<int> queue;
vector<Entity> p_entity;
//ReadEntityInSCCFromDisk(m_node_count, p_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
//GenerateGridIndexSequence(l1, l2, pieces, pieces, in_edge_graph, p_entity, index1, queue);
int time = clock() - start;
//ArbitaryGraphToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_5/GeoReachGrid_" + getstring(ratio) + ".txt");
/*if (datasource == "go_uniprot"||datasource == "uniprotenc_22m")
GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_compare.txt");
else
GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + ".txt");*/
/*ofstream ofile("data/Real_Data/Experiment_result/" + type + "/FullGrid_initialize_time.txt", ios::app);
ofile << ratio << '\t' << time << endl;
ofile.close();*/
//INT64 count = 0;
/*for (int i = 0; i < index1.size(); i++)
{
for (int j = 0; j < index1[i].size(); j++)
{
if (index1[i][j])
count += 1;
}
}*/
/*ofile.open("data/Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/"+type+"/index_size.txt", ios::app);
ofile << ratio << "\t" << count * 4 << endl;
ofile.close();*/
}
}
}
{
vector<string> filename;
//filename.push_back("citeseerx");
//filename.push_back("Patents");
filename.push_back("go_uniprot");
filename.push_back("uniprotenc_22m");
filename.push_back("uniprotenc_100m");
filename.push_back("uniprotenc_150m");
for (int fileindex = 0; fileindex < filename.size(); fileindex++)
{
string datasource = filename[fileindex];
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1;
l1.x = 0;
l1.y = 0;
Location l2;
l2.x = 1000;
l2.y = 1000;
int pieces = 128;
int grid_count = pieces*pieces;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/FullGrid_initialize_time.txt", ios::app);
ofile << datasource << endl;
ofile.close();
for (int ratio = 20; ratio <= 80; ratio += 20)
//int ratio = 60;
{
vector<set<int>> index1;
index1.resize(m_node_count);
queue<int> queue;
vector<Entity> p_entity;
//ReadEntityInSCCFromDisk(m_node_count, p_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
//GenerateGridIndexSequence(l1, l2, pieces, pieces, in_edge_graph, p_entity, index1, queue);
int time = clock() - start;
//ArbitaryGraphToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_5/GeoReachGrid_" + getstring(ratio) + ".txt");
//GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + ".txt");
/*ofstream ofile("data/Real_Data/Experiment_result/" + type + "/FullGrid_initialize_time.txt", ios::app);
ofile << ratio << '\t' << time << endl;
ofile.close();*/
//INT64 count = 0;
/*for (int i = 0; i < index1.size(); i++)
count += index1[i].size();*/
/*ofile.open("data/Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/"+type+"/index_size.txt", ios::app);
ofile << ratio << "\t" << count * 4 << endl;
ofile.close();*/
}
}
}
}
boolean compare(vector<vector<bool>> &index1, vector <vector<bool>> &index2)
{
if (index1.size() != index2.size())
return false;
if (index1[0].size() != index2[0].size())
return false;
for (int i = 0; i < index1.size(); i++)
{
for (int j = 0; j < index1[i].size(); j++)
{
if (index1[i][j] != index2[i][j])
{
ofstream ofile("data/Real_Data/uniprotenc_22m/GeoReachGrid_128/log.txt", 'w');
ofile << i << "\n" << j << endl;
return false;
}
}
}
return true;
}
void GeneratePartialGridIndex(string type)
{
vector<string> filename;
/*filename.push_back("citeseerx");
filename.push_back("Patents");*/
filename.push_back("go_uniprot");
//filename.push_back("uniprotenc_22m");
//filename.push_back("uniprotenc_100m");
//filename.push_back("uniprotenc_150m");
int threshold = 200;
for (int file_index = 0; file_index < filename.size(); file_index++)
{
int threshold = 200;
string datasource = filename[file_index];
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/PartialGrid_initialize_time.txt", ios::app);
ofile << datasource << endl;
ofile.close();
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1(0, 0);
Location l2(1000, 1000);
int pieces = 128;
int grid_count = pieces*pieces;
for (int ratio = 20; ratio <= 80; ratio += 20)
//int ratio = 40;
{
vector<vector<bool>> index1 = vector<vector<bool>>(m_node_count);
vector<bool> IsStored = vector<bool>(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
index1[i].resize(grid_count);
}
for (int i = 0; i < m_node_count; i++)
{
IsStored[i] = true;
}
queue<int> queue;
vector<Entity> p_entity;
//ReadEntityInSCCFromDisk(m_node_count, p_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
int sort_time = clock() - start;
//GenerateGridPointIndexPartialSequence(l1, l2, pieces, pieces, in_edge_graph, p_entity, index1, queue, threshold, IsStored);
int total_time = clock() - start;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/PartialGrid_initialize_time.txt", ios::app);
ofile << ratio << "\tWith sort vector" << '\t' << sort_time << "\t" << total_time << endl;
ofile.close();
/*if (datasource == "go_uniprot" || datasource == "uniprotenc_22m")
GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_partial_compare.txt", IsStored);
else
GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type +"/GeoReachGrid_" + getstring(ratio) + "_partial.txt", IsStored);
*/}
}
}
void GeneratePartialGridIndexInSet(string type)
{
vector<string> filename;
//filename.push_back("citeseerx");
//filename.push_back("Patents");
filename.push_back("go_uniprot");
filename.push_back("uniprotenc_22m");
filename.push_back("uniprotenc_100m");
filename.push_back("uniprotenc_150m");
int threshold = 200;
for (int file_index = 0; file_index < filename.size(); file_index++)
{
string datasource = filename[file_index];
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/PartialGrid_initialize_time.txt", ios::app);
ofile << datasource << endl;
ofile.close();
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1(0, 0);
Location l2(1000, 1000);
int pieces = 128;
int grid_count = pieces*pieces;
for (int ratio = 20; ratio <= 80; ratio += 20)
//int ratio = 40;
{
vector<set<int>> index1 = vector<set<int>>(m_node_count);
vector<bool> IsStored = vector<bool>(m_node_count);
queue<int> queue;
for (int i = 0; i < m_node_count; i++)
{
IsStored[i] = true;
}
while (!queue.empty())
queue.pop();
m_entity.clear();
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/" + type +"/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
int sort_time = clock() - start;
//GenerateGridPointIndexPartialSequence(l1, l2, pieces, pieces, in_edge_graph, m_entity, index1, queue, threshold, IsStored);
int total_time = clock() - start;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/PartialGrid_initialize_time.txt", ios::app);
ofile << ratio << "\tWith sort using set" << '\t' << sort_time << "\t" << total_time << endl;
ofile.close();
//GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type +"/GeoReachGrid_" + getstring(ratio) + "_partial.txt", IsStored);
}
}
}
void GenerateMultilevelGrid(string type, string datasource)
{
int threshold = 200;
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1(0, 0);
Location l2(1000, 1000);
int pieces = 128;
int grid_count = 0;
for (int i = pieces; i >= 2; i /= 2)
{
grid_count += i*i;
}
for (int ratio = 20; ratio <= 80; ratio += 20)
{
for (int merge_count = 2; merge_count <= 4; merge_count++)
{
vector<vector<bool>> index1 = vector<vector<bool>>(m_node_count);
vector<bool> IsStored = vector<bool>(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
index1[i].resize(grid_count);
}
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < grid_count; j++)
index1[i][j] = false;
IsStored[i] = true;
}
queue<int> queue;
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
//GenerateMultilevelGridPointIndex(l1, l2, pieces, pieces, in_edge_graph, m_entity, index1, queue, threshold, IsStored, merge_count);
int time = clock() - start;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/multigrid_initialize_time.txt", ios::app);
ofile << datasource << "\t" << ratio << '\t' << merge_count << "\t" << time << endl;
ofile.close();
//GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type +"/GeoReachGrid_" + getstring(ratio) + "_multilevel_" + getstring(merge_count) + "_compare.txt", IsStored);
}
}
}
void GenerateMultilevelGridInSet(string type, string datasource)
{
int threshold = 200;
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1(0, 0);
Location l2(1000, 1000);
int pieces = 128;
int grid_count = 0;
for (int i = pieces; i >= 2; i /= 2)
{
grid_count += i*i;
}
for (int ratio = 20; ratio <= 80; ratio += 20)
{
for (int merge_count = 2; merge_count <= 4; merge_count++)
{
vector<set<int>> index1 = vector<set<int>>(m_node_count);
vector<bool> IsStored = vector<bool>(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
IsStored[i] = true;
}
queue<int> queue;
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
//GenerateMultilevelGridPointIndex(l1, l2, pieces, pieces, in_edge_graph, m_entity, index1, queue, threshold, IsStored, merge_count);
int time = clock() - start;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/multigrid_initialize_inset_time.txt", ios::app);
ofile << datasource << "\t" << ratio << '\t' << merge_count << "\t" << time << endl;
ofile.close();
//GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_multilevel_" + getstring(merge_count) + "_inset.txt", IsStored);
}
}
}
void GenerateMultiFromExist(string type, string datasource)
{
int pieces = 128;
for (int ratio =20; ratio <= 80; ratio += 20)
//int ratio = 40;
{
for (int merge_count = 2; merge_count <= 4; merge_count++)
//int merge_count = 4;
{
vector<int> isstored;
vector<vector<bool>> index;
// ReadGridPointIndexMultilevelFromDisk(pieces, index, "Real_Data/" + datasource + "/GeoReachGrid_128/" + type +"/GeoReachGrid_" + getstring(ratio) + "_newpartial.txt", isstored, m_node_count);
int start = clock();
int offset = 0;
for (int i = pieces; i >= 2; i /= 2)
{
offset += i*i;
for (int j = 0; j < isstored.size(); j++)
{
int id = isstored[j];
/*for (int k = offset-i*i; k < offset; k++)
{
if (index[j][k])
{
int true_count = 0;
int m = (k - offset + i*i) / i;
int n = (k - offset + i*i) - m*i;
int mm = m / 2, nn = n / 2;
int grid_id_base = mm * 2 * i + nn * 2;
if (index[j][grid_id_base])
true_count += 1;
if (index[j][grid_id_base + 1])
true_count++;
if (index[j][grid_id_base + i])
true_count++;
if (index[j][grid_id_base + i + 1])
true_count++;
if (true_count >= merge_count)
{
index[j][grid_id_base] = false;
index[j][grid_id_base + 1] = false;
index[j][grid_id_base + i] = false;
index[j][grid_id_base + i + 1] = false;
index[j][offset + mm*i / 2 + nn] = true;
}
}
}*/
for (int m = 0; m < i; m += 2)
{
for (int n = 0; n < i; n += 2)
{
int grid_id = m*i + n + offset - i*i;
int true_count = 0;
if (index[id][grid_id])
true_count++;
if (index[id][grid_id + 1])
true_count++;
if (index[id][grid_id + i])
true_count++;
if (index[id][grid_id + i + 1])
true_count++;
if (true_count >= merge_count)
{
int mm = m / 2, nn = n / 2;
int high_level_grid_id = mm*i / 2 + nn;
index[id][high_level_grid_id + offset] = true;
index[id][grid_id] = false;
index[id][grid_id + 1] = false;
index[id][grid_id + i] = false;
index[id][grid_id + i + 1] = false;
}
}
}
}
}
int time = clock() - start;
ofstream ofile("data/Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type +"/construction_time_partial.txt", ios::app);
ofile << ratio << "\t" << "multi_exist" << "\t" << merge_count << "\t" << time << endl;
ofile.close();
//GridPointIndexToDisk(index, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type +"/GeoReachGrid_" + getstring(ratio) + "_multilevel_" + getstring(merge_count) + ".txt", isstored, m_node_count);
}
}
}
void GenerateMultilevelGridFull(string type, string datasource)
{
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1(0, 0);
Location l2(1000, 1000);
int pieces = 128;
int grid_count = 0;
for (int i = pieces; i >= 2; i /= 2)
{
grid_count += i*i;
}
for (int ratio = 60; ratio <= 80; ratio += 20)
{
for (int merge_count = 2; merge_count <= 3; merge_count++)
{
vector<vector<bool>> index1 = vector<vector<bool>>(m_node_count);
/*MultiLevelGridIndexVector index1;
{
for (int x = pieces; x >= 2; x /= 2)
{
index1.index[x].resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
index1.index[x][i].resize(x);
for (int j = 0; j < x; j++)
{
index1.index[x][i][j].resize(x);
}
}
}
}*/
for (int i = 0; i < m_node_count; i++)
{
index1[i].resize(grid_count);
}
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < grid_count; j++)
index1[i][j] = false;
}
queue<int> queue;
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
//GenerateMultilevelGridPointIndexFull(l1, l2, pieces, pieces, in_edge_graph, m_entity, index1, queue, merge_count);
//GridPointMultilevelIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_multilevelfull_" + getstring(merge_count) + ".txt", pieces);
int time = clock() - start;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/multigridfull_initialize_time.txt", ios::app);
ofile << datasource << "\t" << ratio << '\t' << merge_count << "\t" << time << endl;
ofile.close();
//GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_multilevelfull_" + getstring(merge_count) + ".txt");
}
}
}
void GenerateMultilevelGridInSetFull(string type, string datasource)
{
vector<vector<int>> graph;
//ReadArbitaryGraphFromDisk(graph, m_node_count, "Real_Data/" + datasource + "/graph.txt");
//get in-edge graph
vector<vector<int>> in_edge_graph;
in_edge_graph.resize(m_node_count);
for (int i = 0; i < m_node_count; i++)
{
for (int j = 0; j < graph[i].size(); j++)
{
int neighbor = graph[i][j];
in_edge_graph[neighbor].push_back(i);
}
}
Location l1(0, 0);
Location l2(1000, 1000);
int pieces = 128;
int grid_count = 0;
for (int i = pieces; i >= 2; i /= 2)
{
grid_count += i*i;
}
for (int ratio = 20; ratio <= 80; ratio += 20)
{
for (int merge_count = 2; merge_count <= 3; merge_count++)
{
vector<set<int>> index1 = vector<set<int>>(m_node_count);
queue<int> queue;
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "Real_Data/" + datasource + "/" + type + "/" + getstring(ratio) + "/entity.txt");
int start = clock();
TopologicalSort(graph, queue);
//GenerateMultilevelGridPointIndexFull(l1, l2, pieces, pieces, in_edge_graph, m_entity, index1, queue, merge_count);
int time = clock() - start;
ofstream ofile("data/Real_Data/Experiment_result/" + type + "/multigridfull_initialize_inset_time.txt", ios::app);
ofile << datasource << "\t" << ratio << '\t' << merge_count << "\t" << time << endl;
ofile.close();
/*if (datasource == "go_uniprot" || datasource == "uniprotenc_22m")
GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_multilevelfull_" + getstring(merge_count) + "_inset.txt");
else
GridPointIndexToDisk(index1, "Real_Data/" + datasource + "/GeoReachGrid_" + getstring(pieces) + "/" + type + "/GeoReachGrid_" + getstring(ratio) + "_multilevelfull_" + getstring(merge_count) + ".txt");
*/}
}
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtongridGenerate()
{
//SortTest();
//GenerateGridSequence("Random_spatial_distributed");
//GenerateGridSequence("Clustered_distributed");
//GenerateGridSequence("Zipf_distributed");
//GeneratePartialGridIndex("Clustered_distributed");
//GeneratePartialGridIndexInSet("Clustered_distributed");
//GeneratePartialGridIndex("Zipf_distributed");
//GeneratePartialGridIndexInSet("Zipf_distributed");
/*vector<vector<bool>> index1, index2;
ReadGridPointIndexFromDisk(128 * 128, index1, "Real_Data/Patents/GeoReachGrid_128/GeoReachGrid_"+getstring(80)+".txt");
ReadGridPointIndexFromDisk(128 * 128, index2, "Real_Data/Patents/GeoReachGrid_128/GeoReachGrid_"+getstring(80)+"_sort.txt");
bool result = compare(index1, index2);
if (result)
{
CString str;
str.Format(TEXT("true"));
MessageBox(str);
}
else
{
CString str;
str.Format(TEXT("false"));
MessageBox(str);
}*/
//GeneratePartialGridIndex("uniprotenc_100m");
//GeneratePartialGridIndexInSet("Random_spatial_distributed");
//GenerateMultilevelGrid("go_uniprot",2, 80);
//GeneratePartialGridIndex("uniprotenc_22m");
//GenerateMultiFromExist("citeseerx");
//GenerateMultiFromExist("go_uniprot");
//GenerateMultiFromExist("Patents");
//GenerateMultiFromExist("uniprotenc_22m");
//GenerateMultiFromExist("uniprotenc_100m");
//GenerateMultiFromExist("uniprotenc_150m");
vector<string> filename;
/*filename.push_back("go_uniprot");
filename.push_back("uniprotenc_22m");
filename.push_back("uniprotenc_100m");
filename.push_back("uniprotenc_150m");
for (int i = 0; i < filename.size(); i++)
{
GenerateMultilevelGridInSetFull("Random_spatial_distributed", filename[i]);
GenerateMultilevelGridInSetFull("Clustered_distributed", filename[i]);
GenerateMultilevelGridInSetFull("Zipf_distributed", filename[i]);
}*/
//filename.clear();
//filename.push_back("citeseerx");
/*filename.push_back("Patents");
filename.push_back("go_uniprot");
filename.push_back("uniprotenc_22m");*/
for (int i = 0; i < filename.size(); i++)
{
//GenerateMultilevelGridFull("Random_spatial_distributed", filename[i]);
//GenerateMultilevelGridFull("Clustered_distributed", filename[i]);
//GenerateMultilevelGridFull("Zipf_distributed", filename[i]);
}
//GenerateMultiFromExistSet("go_uniprot", "Random_spatial_distributed");
string datasource = "citeseerx";
int ratio = 20;
int pieces = 128;
int offset = 0;
for (int i = pieces; i >= 1; i/=2)
offset += i*i;
ReadGraph(m_graph_v, m_node_count, "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/"+datasource+"/graph.txt");
//ReadEntityInSCCFromDisk(m_node_count, m_entity, m_range, "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/" + datasource + "/" + "Random_spatial_distributed" + "/" + getstring(ratio) + "/entity.txt");
queue<int> q;
TopologicalSort(m_graph_v, q);
GenerateInedgeGraph(m_graph_v, m_graph_inedge_v);
vector<vector<bool>> index = vector<vector<bool>>(m_node_count);
for (int i = 0; i < index.size(); i++)
index[i].resize(offset);
//GenerateGridIndexSequence(Location(0, 0), Location(4, 4), 4, 4, m_graph_inedge_v, m_entity, index, q);
//GenerateMultilevelGridPointIndexFull(Location(0, 0), Location(1000, 1000), pieces, pieces, m_graph_inedge_v, m_entity, index, q, 2);
}
void GenerateTest()
{
//code for experiment of Generate GeoReach
/*string dataset = "go_uniprot";
string graph_path = "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/"+dataset+"/newformat_graph.txt";
string entity_path = "D:/Graph_05_13/graph_2015_1_24_mfc/data/Real_Data/"+dataset+"/Random_spatial_distributed/20/newformat_entity.txt";*/
//string GeoReach_path = "GeoReach_"+dataset+".txt";
string graph_path = "graph.txt";
string entity_path = "entity.txt";
string GeoReach_path = "GeoReach.txt";
int MG = 3, MT = 2;
double MR = 0.4;
GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(-2, -2), Location(2, 2), 4, 4);
GenerateGeoReachInSet(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(-2, -2), Location(2, 2), 4, 4);
}
void GenerateExperimentDataMG_Time()
{
vector<string> filename;
filename.push_back("citeseerx");
filename.push_back("go_uniprot");
filename.push_back("Patents");
filename.push_back("uniprotenc_150m");
vector<string> distributions_v;
distributions_v.push_back("Clustered_distributed");
distributions_v.push_back("Zipf_distributed");
int ratio = 20;
string distribution = "Random_spatial_distributed";
int MT = 0;
double MR = 2;
string filepath = "D://ini_time.csv";
ofstream outfile_time;
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
string graph_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/new_graph.txt";
string entity_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/new_entity.txt";
if (datasource == "go_uniprot")
{
outfile_time.open(filepath, ios::app);
outfile_time << datasource << "\t" << endl;
outfile_time.close();
for (int MG = 8; MG <= 64; MG *= 2)
{
outfile_time.open(filepath, ios::app);
outfile_time << MG << "\t";
outfile_time.close();
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/MG/GeoReach_" + getstring(MG) + ".txt";
//GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
int time = GenerateGeoReach_Time(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
outfile_time.open(filepath, ios::app);
outfile_time << time << endl;
outfile_time.close();
}
}
else
{
outfile_time.open(filepath, ios::app);
outfile_time << datasource << "\t" << endl;
outfile_time.close();
for (int MG = 32; MG <= 2048; MG *= 4)
{
outfile_time.open(filepath, ios::app);
outfile_time << MG << "\t";
outfile_time.close();
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/MG/GeoReach_" + getstring(MG) + ".txt";
int time;
if (datasource == "uniprotenc_150m")
time = GenerateGeoReachInSet_Time(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
else
time = GenerateGeoReach_Time(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
//GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
outfile_time.open(filepath, ios::app);
outfile_time << time << endl;
outfile_time.close();
}
}
outfile_time.open(filepath, ios::app);
outfile_time << endl;
outfile_time.close();
}
}
void GenerateExperimentDataMR()
{
vector<string> filename;
filename.push_back("citeseerx");
filename.push_back("go_uniprot");
filename.push_back("Patents");
filename.push_back("uniprotenc_150m");
int ratio = 20;
string distribution = "Random_spatial_distributed";
int MT = 0;
int MG = 0;
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
string graph_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/new_graph.txt";
string entity_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/new_entity.txt";
for (int MR = 0; MR <= 105; MR += 35)
{
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/GeoReach_" + getstring(MR) + ".txt";
if (datasource != "uniprotenc_150m" && datasource != "go_uniprot")
GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR/100.0, MT, Location(0, 0), Location(1000, 1000));
else
GenerateGeoReachInSet(graph_path, entity_path, GeoReach_path, MG, MR/100.0, MT, Location(0, 0), Location(1000, 1000));
}
}
}
void RandomIniTime()
{
vector<string> filename;
//filename.push_back("citeseerx");
filename.push_back("go_uniprot");
//filename.push_back("Patents");
//filename.push_back("uniprotenc_150m");
//int ratio = 20;
string distribution = "Random_spatial_distributed";
int MT = 0;
double MR = 2;
string filepath = "D://ini_time_random.csv";
//ofstream outfile_time;
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
string graph_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/new_graph.txt";
/*outfile_time.open(filepath, ios::app);
outfile_time << datasource << endl;
outfile_time.close();*/
if (datasource == "go_uniprot")
{
//for (int MG = 8; MG <= 64; MG *= 2)
int MG = 8;
{
/*outfile_time.open(filepath, ios::app);
outfile_time << MG << endl;
outfile_time.close();*/
for (int ratio = 20; ratio <= 80; ratio += 20)
{
string entity_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/new_entity.txt";
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/random/GeoReach_" + getstring(ratio) + "_" +getstring(MG) + ".txt";
/*int time = GenerateGeoReachInSet_Time(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));*/
GenerateGeoReachInSet(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
/*outfile_time.open(filepath, ios::app);
outfile_time << ratio << "\t" << time << endl;
outfile_time.close();*/
}
/*outfile_time.open(filepath, ios::app);
outfile_time << endl;
outfile_time.close();*/
}
}
else
{
//for (int MG = 32; MG <= 2048; MG *= 4)
int MG = 32;
{
/*outfile_time.open(filepath, ios::app);
outfile_time << MG << endl;
outfile_time.close();*/
for (int ratio = 20; ratio <= 80; ratio += 20)
{
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/random/GeoReach_" + getstring(ratio) + "_" + getstring(MG) + ".txt";
string entity_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/new_entity.txt";
int time;
if (datasource == "uniprotenc_150m")
GenerateGeoReachInSet(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
//time = GenerateGeoReachInSet_Time(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
else
GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
//time = GenerateGeoReach_Time(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
/*outfile_time.open(filepath, ios::app);
outfile_time << ratio << "\t" << time << endl;
outfile_time.close();*/
}
/*outfile_time.open(filepath, ios::app);
outfile_time << endl;
outfile_time.close();*/
}
}
/*outfile_time.open(filepath, ios::app);
outfile_time << endl;
outfile_time.close();*/
}
}
void GenerateExperimentData()
{
vector<string> filename;
/*filename.push_back("citeseerx");
filename.push_back("go_uniprot");
filename.push_back("Patents");*/
filename.push_back("uniprotenc_150m");
vector<string> distributions_v;
distributions_v.push_back("Clustered_distributed");
//distributions_v.push_back("Zipf_distributed");
int ratio = 20;
//string distribution = "Random_spatial_distributed";
int MT = 0;
double MR = 2;
for (int dis_index = 0; dis_index <= distributions_v.size(); dis_index++)
{
string distribution = distributions_v[dis_index];
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
string graph_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/new_graph.txt";
string entity_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/new_entity.txt";
if (datasource == "go_uniprot")
{
//for (int MG = 8; MG <= 64; MG *= 2)
int MG = 8;
{
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/GeoReach_" + distribution + "_" + getstring(ratio) + "_" + getstring(MG) + ".txt";
GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
}
}
else
{
if (datasource == "Patents")
{
int MG = 32;
//for (int MG = 32; MG <= 2048; MG *= 4)
{
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/GeoReach_" + distribution + "_" + getstring(ratio) + "_" + getstring(MG) + ".txt";
GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
}
}
else
{
int MG = 128;
//for (int MG = 32; MG <= 2048; MG *= 4)
{
string GeoReach_path = "D://Ubuntu_shared/Real_Data/" + datasource + "/GeoReachIndex/GeoReach_" + distribution + "_" + getstring(ratio) + "_" + getstring(MG) + ".txt";
if (datasource == "uniprotenc_150m")
GenerateGeoReachInSet(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
else
GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000));
}
}
}
}
}
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGeoreachGenerate()
{
GenerateExperimentData();
//RandomIniTime();
//GenerateExperimentDataMG();
//GenerateExperimentDataMR();
/*vector<set<int>> index;
set<int> x;
x.insert(0);
x.insert(1);
x.insert(2);
x.insert(3);
x.insert(8);
x.insert(9);
x.insert(10);
x.insert(11);
index.push_back(x);
vector<int> Types;
Types.push_back(0);
Merge(index, Types, 2, 4, 4);*/
//GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000), 128, 128);
//GenerateGeoReach(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000), 128, 128);
//GenerateGeoReachFromInedgeGraph(graph_path, entity_path, GeoReach_path, MG, MR, MT, Location(0, 0), Location(1000, 1000), 128, 128);
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGeoreachGraphconvert()
{
vector<string> filename;
filename.push_back("citeseerx");
filename.push_back("go_uniprot");
filename.push_back("Patents");
filename.push_back("uniprotenc_150m");
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
string original_graphpath = "D://Ubuntu_shared/Real_Data/" + datasource + "/graph.txt";
string new_graphpath = "D://Ubuntu_shared/Real_Data/" + datasource + "/new_graph.txt";
GraphToNewformat(m_graph_v, m_node_count, original_graphpath, new_graphpath);
}
}
void Cgraph_2015_1_24_mfcDlg::OnBnClickedButtonGeoreachEntityconvert()
{
vector<string> filename;
filename.push_back("citeseerx");
filename.push_back("go_uniprot");
filename.push_back("Patents");
filename.push_back("uniprotenc_150m");
int ratio = 20;
//string distribution = "Clustered_distributed";
string distribution = "Zipf_distributed";
//for (int ratio = 20; ratio <= 80; ratio += 20)
{
for (int i = 0; i < filename.size(); i++)
{
string datasource = filename[i];
string original_entitypath = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/entity.txt";
string new_entitypath = "D://Ubuntu_shared/Real_Data/" + datasource + "/" + distribution + "/" + getstring(ratio) + "/new_entity.txt";
EntityInSCCToNewFormat(m_node_count, m_entity, m_range, original_entitypath, new_entitypath);
}
}
}
| [
"[email protected]"
] | |
4c39fa95b7f507806682af886a975997c36a19f4 | 5acf48b516af6ba29cb2208ff47a7491f6fd758e | /src/integrators/mlt.cpp | 8646dd0c702c5e60f6c7987b3740c7b77761b38e | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | mmp/pbrt-v3 | 1342e48431beb32dba2abdee17adfe47c5d3c405 | 13d871faae88233b327d04cda24022b8bb0093ee | refs/heads/master | 2023-09-05T13:56:59.387502 | 2023-09-03T11:37:35 | 2023-09-03T11:37:35 | 37,482,419 | 5,006 | 1,494 | BSD-2-Clause | 2023-05-18T05:23:46 | 2015-06-15T18:13:08 | C++ | UTF-8 | C++ | false | false | 11,359 | cpp |
/*
pbrt source code is Copyright(c) 1998-2016
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// integrators/mlt.cpp*
#include "integrators/mlt.h"
#include "integrators/bdpt.h"
#include "scene.h"
#include "film.h"
#include "sampler.h"
#include "integrator.h"
#include "camera.h"
#include "stats.h"
#include "filters/box.h"
#include "paramset.h"
#include "sampling.h"
#include "progressreporter.h"
namespace pbrt {
STAT_PERCENT("Integrator/Acceptance rate", acceptedMutations, totalMutations);
// MLTSampler Constants
static const int cameraStreamIndex = 0;
static const int lightStreamIndex = 1;
static const int connectionStreamIndex = 2;
static const int nSampleStreams = 3;
// MLTSampler Method Definitions
Float MLTSampler::Get1D() {
ProfilePhase _(Prof::GetSample);
int index = GetNextIndex();
EnsureReady(index);
return X[index].value;
}
Point2f MLTSampler::Get2D() { return {Get1D(), Get1D()}; }
std::unique_ptr<Sampler> MLTSampler::Clone(int seed) {
LOG(FATAL) << "MLTSampler::Clone() is not implemented";
return nullptr;
}
void MLTSampler::StartIteration() {
currentIteration++;
largeStep = rng.UniformFloat() < largeStepProbability;
}
void MLTSampler::Accept() {
if (largeStep) lastLargeStepIteration = currentIteration;
}
void MLTSampler::EnsureReady(int index) {
// Enlarge _MLTSampler::X_ if necessary and get current $\VEC{X}_i$
if (index >= X.size()) X.resize(index + 1);
PrimarySample &Xi = X[index];
// Reset $\VEC{X}_i$ if a large step took place in the meantime
if (Xi.lastModificationIteration < lastLargeStepIteration) {
Xi.value = rng.UniformFloat();
Xi.lastModificationIteration = lastLargeStepIteration;
}
// Apply remaining sequence of mutations to _sample_
Xi.Backup();
if (largeStep) {
Xi.value = rng.UniformFloat();
} else {
int64_t nSmall = currentIteration - Xi.lastModificationIteration;
// Apply _nSmall_ small step mutations
// Sample the standard normal distribution $N(0, 1)$
Float normalSample = Sqrt2 * ErfInv(2 * rng.UniformFloat() - 1);
// Compute the effective standard deviation and apply perturbation to
// $\VEC{X}_i$
Float effSigma = sigma * std::sqrt((Float)nSmall);
Xi.value += normalSample * effSigma;
Xi.value -= std::floor(Xi.value);
}
Xi.lastModificationIteration = currentIteration;
}
void MLTSampler::Reject() {
for (auto &Xi : X)
if (Xi.lastModificationIteration == currentIteration) Xi.Restore();
--currentIteration;
}
void MLTSampler::StartStream(int index) {
CHECK_LT(index, streamCount);
streamIndex = index;
sampleIndex = 0;
}
// MLT Method Definitions
Spectrum MLTIntegrator::L(const Scene &scene, MemoryArena &arena,
const std::unique_ptr<Distribution1D> &lightDistr,
const std::unordered_map<const Light *, size_t> &lightToIndex,
MLTSampler &sampler, int depth, Point2f *pRaster) {
sampler.StartStream(cameraStreamIndex);
// Determine the number of available strategies and pick a specific one
int s, t, nStrategies;
if (depth == 0) {
nStrategies = 1;
s = 0;
t = 2;
} else {
nStrategies = depth + 2;
s = std::min((int)(sampler.Get1D() * nStrategies), nStrategies - 1);
t = nStrategies - s;
}
// Generate a camera subpath with exactly _t_ vertices
Vertex *cameraVertices = arena.Alloc<Vertex>(t);
Bounds2f sampleBounds = (Bounds2f)camera->film->GetSampleBounds();
*pRaster = sampleBounds.Lerp(sampler.Get2D());
if (GenerateCameraSubpath(scene, sampler, arena, t, *camera, *pRaster,
cameraVertices) != t)
return Spectrum(0.f);
// Generate a light subpath with exactly _s_ vertices
sampler.StartStream(lightStreamIndex);
Vertex *lightVertices = arena.Alloc<Vertex>(s);
if (GenerateLightSubpath(scene, sampler, arena, s, cameraVertices[0].time(),
*lightDistr, lightToIndex, lightVertices) != s)
return Spectrum(0.f);
// Execute connection strategy and return the radiance estimate
sampler.StartStream(connectionStreamIndex);
return ConnectBDPT(scene, lightVertices, cameraVertices, s, t, *lightDistr,
lightToIndex, *camera, sampler, pRaster) *
nStrategies;
}
void MLTIntegrator::Render(const Scene &scene) {
std::unique_ptr<Distribution1D> lightDistr =
ComputeLightPowerDistribution(scene);
// Compute a reverse mapping from light pointers to offsets into the
// scene lights vector (and, equivalently, offsets into
// lightDistr). Added after book text was finalized; this is critical
// to reasonable performance with 100s+ of light sources.
std::unordered_map<const Light *, size_t> lightToIndex;
for (size_t i = 0; i < scene.lights.size(); ++i)
lightToIndex[scene.lights[i].get()] = i;
// Generate bootstrap samples and compute normalization constant $b$
int nBootstrapSamples = nBootstrap * (maxDepth + 1);
std::vector<Float> bootstrapWeights(nBootstrapSamples, 0);
if (scene.lights.size() > 0) {
ProgressReporter progress(nBootstrap / 256,
"Generating bootstrap paths");
std::vector<MemoryArena> bootstrapThreadArenas(MaxThreadIndex());
int chunkSize = Clamp(nBootstrap / 128, 1, 8192);
ParallelFor([&](int i) {
// Generate _i_th bootstrap sample
MemoryArena &arena = bootstrapThreadArenas[ThreadIndex];
for (int depth = 0; depth <= maxDepth; ++depth) {
int rngIndex = i * (maxDepth + 1) + depth;
MLTSampler sampler(mutationsPerPixel, rngIndex, sigma,
largeStepProbability, nSampleStreams);
Point2f pRaster;
bootstrapWeights[rngIndex] =
L(scene, arena, lightDistr, lightToIndex, sampler, depth, &pRaster).y();
arena.Reset();
}
if ((i + 1) % 256 == 0) progress.Update();
}, nBootstrap, chunkSize);
progress.Done();
}
Distribution1D bootstrap(&bootstrapWeights[0], nBootstrapSamples);
Float b = bootstrap.funcInt * (maxDepth + 1);
// Run _nChains_ Markov chains in parallel
Film &film = *camera->film;
int64_t nTotalMutations =
(int64_t)mutationsPerPixel * (int64_t)film.GetSampleBounds().Area();
if (scene.lights.size() > 0) {
const int progressFrequency = 32768;
ProgressReporter progress(nTotalMutations / progressFrequency,
"Rendering");
ParallelFor([&](int i) {
int64_t nChainMutations =
std::min((i + 1) * nTotalMutations / nChains, nTotalMutations) -
i * nTotalMutations / nChains;
// Follow {i}th Markov chain for _nChainMutations_
MemoryArena arena;
// Select initial state from the set of bootstrap samples
RNG rng(i);
int bootstrapIndex = bootstrap.SampleDiscrete(rng.UniformFloat());
int depth = bootstrapIndex % (maxDepth + 1);
// Initialize local variables for selected state
MLTSampler sampler(mutationsPerPixel, bootstrapIndex, sigma,
largeStepProbability, nSampleStreams);
Point2f pCurrent;
Spectrum LCurrent =
L(scene, arena, lightDistr, lightToIndex, sampler, depth, &pCurrent);
// Run the Markov chain for _nChainMutations_ steps
for (int64_t j = 0; j < nChainMutations; ++j) {
sampler.StartIteration();
Point2f pProposed;
Spectrum LProposed =
L(scene, arena, lightDistr, lightToIndex, sampler, depth, &pProposed);
// Compute acceptance probability for proposed sample
Float accept = std::min((Float)1, LProposed.y() / LCurrent.y());
// Splat both current and proposed samples to _film_
if (accept > 0)
film.AddSplat(pProposed,
LProposed * accept / LProposed.y());
film.AddSplat(pCurrent, LCurrent * (1 - accept) / LCurrent.y());
// Accept or reject the proposal
if (rng.UniformFloat() < accept) {
pCurrent = pProposed;
LCurrent = LProposed;
sampler.Accept();
++acceptedMutations;
} else
sampler.Reject();
++totalMutations;
if ((i * nTotalMutations / nChains + j) % progressFrequency ==
0)
progress.Update();
arena.Reset();
}
}, nChains);
progress.Done();
}
// Store final image computed with MLT
camera->film->WriteImage(b / mutationsPerPixel);
}
MLTIntegrator *CreateMLTIntegrator(const ParamSet ¶ms,
std::shared_ptr<const Camera> camera) {
int maxDepth = params.FindOneInt("maxdepth", 5);
int nBootstrap = params.FindOneInt("bootstrapsamples", 100000);
int64_t nChains = params.FindOneInt("chains", 1000);
int mutationsPerPixel = params.FindOneInt("mutationsperpixel", 100);
Float largeStepProbability =
params.FindOneFloat("largestepprobability", 0.3f);
Float sigma = params.FindOneFloat("sigma", .01f);
if (PbrtOptions.quickRender) {
mutationsPerPixel = std::max(1, mutationsPerPixel / 16);
nBootstrap = std::max(1, nBootstrap / 16);
}
return new MLTIntegrator(camera, maxDepth, nBootstrap, nChains,
mutationsPerPixel, sigma, largeStepProbability);
}
} // namespace pbrt
| [
"[email protected]"
] | |
0f5a73bc77dabf02ea9d1cd1d49a1729d52eb521 | b5bd546700f49d0f9a27e7b552c33b25d7abbd45 | /800x600/Source/Login-Server/net/Msg.h | 55e622a77893bc76f4d465f87253dbaecdf8f004 | [] | no_license | Nicopla880/Helbreath-Dragon | 10ccadb3dcd47629a16a14360012ee1aa196b1a4 | 7366f7f52ed842b933bf51bdb3ec6e0e714157a3 | refs/heads/master | 2021-01-16T21:27:24.639332 | 2016-06-01T14:27:19 | 2016-06-01T14:27:19 | 64,251,218 | 1 | 0 | null | 2016-07-26T20:12:20 | 2016-07-26T20:12:19 | null | UTF-8 | C++ | false | false | 609 | h | #if !defined(AFX_MSG_H__57BA71C0_B929_11D2_B143_00001C7030A6__INCLUDED_)
#define AFX_MSG_H__57BA71C0_B929_11D2_B143_00001C7030A6__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include <windows.h>
#include "..\defs.hpp"
class CMsg
{
public:
void Get(char * pData, DWORD * pSize, int * pIndex, char * pKey);
BOOL bPut(char * pData, DWORD dwSize, int iIndex, char cKey);
CMsg();
virtual ~CMsg();
char * m_pData;
DWORD m_dwSize;
int m_iIndex;
char m_cKey;
};
#endif // !defined(AFX_MSG_H__57BA71C0_B929_11D2_B143_00001C7030A6__INCLUDED_)
| [
"[email protected]"
] | |
92cbaa4cef5beb45f79cee9e21803dffaecf3ad7 | 12f8b2cb70068ea07702e8fdeda7b42a2b2db135 | /src/masternode-budget.h | 170967ed71b3323026452c82eff94e6fc491c3b0 | [
"MIT"
] | permissive | c2fcoin/c2fcoin | 95d68bf5660f94d80b4d58267776486ac199d652 | 0610cdac4a3d5b959183e7bda8d5a5cf72462f2e | refs/heads/master | 2020-03-29T11:11:22.883908 | 2019-05-20T15:09:30 | 2019-05-20T15:09:30 | 149,840,240 | 1 | 2 | MIT | 2018-12-09T13:06:59 | 2018-09-22T03:00:26 | C++ | UTF-8 | C++ | false | false | 18,131 | h | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODE_BUDGET_H
#define MASTERNODE_BUDGET_H
#include "base58.h"
#include "init.h"
#include "key.h"
#include "main.h"
#include "masternode.h"
#include "net.h"
#include "sync.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
using namespace std;
extern CCriticalSection cs_budget;
class CBudgetManager;
class CFinalizedBudgetBroadcast;
class CFinalizedBudget;
class CBudgetProposal;
class CBudgetProposalBroadcast;
class CTxBudgetPayment;
#define VOTE_ABSTAIN 0
#define VOTE_YES 1
#define VOTE_NO 2
static const CAmount PROPOSAL_FEE_TX = (50 * COIN);
static const CAmount BUDGET_FEE_TX = (50 * COIN);
static const int64_t BUDGET_VOTE_UPDATE_MIN = 60 * 60;
extern std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals;
extern std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets;
extern CBudgetManager budget;
void DumpBudgets();
// Define amount of blocks in budget payment cycle
int GetBudgetPaymentCycleBlocks();
//Check the collateral transaction for the budget proposal/finalized budget
bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf);
//
// CBudgetVote - Allow a masternode node to vote and broadcast throughout the network
//
class CBudgetVote
{
public:
bool fValid; //if the vote is currently valid / counted
bool fSynced; //if we've sent this to our peers
CTxIn vin;
uint256 nProposalHash;
int nVote;
int64_t nTime;
std::vector<unsigned char> vchSig;
CBudgetVote();
CBudgetVote(CTxIn vin, uint256 nProposalHash, int nVoteIn);
bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode);
bool SignatureValid(bool fSignatureCheck);
void Relay();
std::string GetVoteString()
{
std::string ret = "ABSTAIN";
if (nVote == VOTE_YES) ret = "YES";
if (nVote == VOTE_NO) ret = "NO";
return ret;
}
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << nProposalHash;
ss << nVote;
ss << nTime;
return ss.GetHash();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vin);
READWRITE(nProposalHash);
READWRITE(nVote);
READWRITE(nTime);
READWRITE(vchSig);
}
};
//
// CFinalizedBudgetVote - Allow a masternode node to vote and broadcast throughout the network
//
class CFinalizedBudgetVote
{
public:
bool fValid; //if the vote is currently valid / counted
bool fSynced; //if we've sent this to our peers
CTxIn vin;
uint256 nBudgetHash;
int64_t nTime;
std::vector<unsigned char> vchSig;
CFinalizedBudgetVote();
CFinalizedBudgetVote(CTxIn vinIn, uint256 nBudgetHashIn);
bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode);
bool SignatureValid(bool fSignatureCheck);
void Relay();
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << nBudgetHash;
ss << nTime;
return ss.GetHash();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vin);
READWRITE(nBudgetHash);
READWRITE(nTime);
READWRITE(vchSig);
}
};
/** Save Budget Manager (budget.dat)
*/
class CBudgetDB
{
private:
boost::filesystem::path pathDB;
std::string strMagicMessage;
public:
enum ReadResult {
Ok,
FileError,
HashReadError,
IncorrectHash,
IncorrectMagicMessage,
IncorrectMagicNumber,
IncorrectFormat
};
CBudgetDB();
bool Write(const CBudgetManager& objToSave);
ReadResult Read(CBudgetManager& objToLoad, bool fDryRun = false);
};
//
// Budget Manager : Contains all proposals for the budget
//
class CBudgetManager
{
private:
//hold txes until they mature enough to use
// XX42 map<uint256, CTransaction> mapCollateral;
map<uint256, uint256> mapCollateralTxids;
public:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
// keep track of the scanning errors I've seen
map<uint256, CBudgetProposal> mapProposals;
map<uint256, CFinalizedBudget> mapFinalizedBudgets;
std::map<uint256, CBudgetProposalBroadcast> mapSeenMasternodeBudgetProposals;
std::map<uint256, CBudgetVote> mapSeenMasternodeBudgetVotes;
std::map<uint256, CBudgetVote> mapOrphanMasternodeBudgetVotes;
std::map<uint256, CFinalizedBudgetBroadcast> mapSeenFinalizedBudgets;
std::map<uint256, CFinalizedBudgetVote> mapSeenFinalizedBudgetVotes;
std::map<uint256, CFinalizedBudgetVote> mapOrphanFinalizedBudgetVotes;
CBudgetManager()
{
mapProposals.clear();
mapFinalizedBudgets.clear();
}
void ClearSeen()
{
mapSeenMasternodeBudgetProposals.clear();
mapSeenMasternodeBudgetVotes.clear();
mapSeenFinalizedBudgets.clear();
mapSeenFinalizedBudgetVotes.clear();
}
int sizeFinalized() { return (int)mapFinalizedBudgets.size(); }
int sizeProposals() { return (int)mapProposals.size(); }
void ResetSync();
void MarkSynced();
void Sync(CNode* node, uint256 nProp, bool fPartial = false);
void Calculate();
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
void NewBlock();
CBudgetProposal* FindProposal(const std::string& strProposalName);
CBudgetProposal* FindProposal(uint256 nHash);
CFinalizedBudget* FindFinalizedBudget(uint256 nHash);
std::pair<std::string, std::string> GetVotes(std::string strProposalName);
CAmount GetTotalBudget(int nHeight);
std::vector<CBudgetProposal*> GetBudget();
std::vector<CBudgetProposal*> GetAllProposals();
std::vector<CFinalizedBudget*> GetFinalizedBudgets();
bool IsBudgetPaymentBlock(int nBlockHeight);
bool AddProposal(CBudgetProposal& budgetProposal);
bool AddFinalizedBudget(CFinalizedBudget& finalizedBudget);
void SubmitFinalBudget();
bool UpdateProposal(CBudgetVote& vote, CNode* pfrom, std::string& strError);
bool UpdateFinalizedBudget(CFinalizedBudgetVote& vote, CNode* pfrom, std::string& strError);
bool PropExists(uint256 nHash);
bool IsTransactionValid(const CTransaction& txNew, int nBlockHeight);
std::string GetRequiredPaymentsString(int nBlockHeight);
void FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake);
void CheckOrphanVotes();
void Clear()
{
LOCK(cs);
LogPrintf("Budget object cleared\n");
mapProposals.clear();
mapFinalizedBudgets.clear();
mapSeenMasternodeBudgetProposals.clear();
mapSeenMasternodeBudgetVotes.clear();
mapSeenFinalizedBudgets.clear();
mapSeenFinalizedBudgetVotes.clear();
mapOrphanMasternodeBudgetVotes.clear();
mapOrphanFinalizedBudgetVotes.clear();
}
void CheckAndRemove();
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(mapSeenMasternodeBudgetProposals);
READWRITE(mapSeenMasternodeBudgetVotes);
READWRITE(mapSeenFinalizedBudgets);
READWRITE(mapSeenFinalizedBudgetVotes);
READWRITE(mapOrphanMasternodeBudgetVotes);
READWRITE(mapOrphanFinalizedBudgetVotes);
READWRITE(mapProposals);
READWRITE(mapFinalizedBudgets);
}
};
class CTxBudgetPayment
{
public:
uint256 nProposalHash;
CScript payee;
CAmount nAmount;
CTxBudgetPayment()
{
payee = CScript();
nAmount = 0;
nProposalHash = 0;
}
ADD_SERIALIZE_METHODS;
//for saving to the serialized db
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(payee);
READWRITE(nAmount);
READWRITE(nProposalHash);
}
};
//
// Finalized Budget : Contains the suggested proposals to pay on a given block
//
class CFinalizedBudget
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
bool fAutoChecked; //If it matches what we see, we'll auto vote for it (masternode only)
public:
bool fValid;
std::string strBudgetName;
int nBlockStart;
std::vector<CTxBudgetPayment> vecBudgetPayments;
map<uint256, CFinalizedBudgetVote> mapVotes;
uint256 nFeeTXHash;
int64_t nTime;
CFinalizedBudget();
CFinalizedBudget(const CFinalizedBudget& other);
void CleanAndRemove(bool fSignatureCheck);
bool AddOrUpdateVote(CFinalizedBudgetVote& vote, std::string& strError);
double GetScore();
bool HasMinimumRequiredSupport();
bool IsValid(std::string& strError, bool fCheckCollateral = true);
std::string GetName() { return strBudgetName; }
std::string GetProposals();
int GetBlockStart() { return nBlockStart; }
int GetBlockEnd() { return nBlockStart + (int)(vecBudgetPayments.size() - 1); }
int GetVoteCount() { return (int)mapVotes.size(); }
bool IsTransactionValid(const CTransaction& txNew, int nBlockHeight);
bool GetBudgetPaymentByBlock(int64_t nBlockHeight, CTxBudgetPayment& payment)
{
LOCK(cs);
int i = nBlockHeight - GetBlockStart();
if (i < 0) return false;
if (i > (int)vecBudgetPayments.size() - 1) return false;
payment = vecBudgetPayments[i];
return true;
}
bool GetPayeeAndAmount(int64_t nBlockHeight, CScript& payee, CAmount& nAmount)
{
LOCK(cs);
int i = nBlockHeight - GetBlockStart();
if (i < 0) return false;
if (i > (int)vecBudgetPayments.size() - 1) return false;
payee = vecBudgetPayments[i].payee;
nAmount = vecBudgetPayments[i].nAmount;
return true;
}
//check to see if we should vote on this
void AutoCheck();
//total c2fcoin paid out by this budget
CAmount GetTotalPayout();
//vote on this finalized budget as a masternode
void SubmitVote();
//checks the hashes to make sure we know about them
string GetStatus();
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << strBudgetName;
ss << nBlockStart;
ss << vecBudgetPayments;
uint256 h1 = ss.GetHash();
return h1;
}
ADD_SERIALIZE_METHODS;
//for saving to the serialized db
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(LIMITED_STRING(strBudgetName, 20));
READWRITE(nFeeTXHash);
READWRITE(nTime);
READWRITE(nBlockStart);
READWRITE(vecBudgetPayments);
READWRITE(fAutoChecked);
READWRITE(mapVotes);
}
};
// FinalizedBudget are cast then sent to peers with this object, which leaves the votes out
class CFinalizedBudgetBroadcast : public CFinalizedBudget
{
private:
std::vector<unsigned char> vchSig;
public:
CFinalizedBudgetBroadcast();
CFinalizedBudgetBroadcast(const CFinalizedBudget& other);
CFinalizedBudgetBroadcast(std::string strBudgetNameIn, int nBlockStartIn, std::vector<CTxBudgetPayment> vecBudgetPaymentsIn, uint256 nFeeTXHashIn);
void swap(CFinalizedBudgetBroadcast& first, CFinalizedBudgetBroadcast& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.strBudgetName, second.strBudgetName);
swap(first.nBlockStart, second.nBlockStart);
first.mapVotes.swap(second.mapVotes);
first.vecBudgetPayments.swap(second.vecBudgetPayments);
swap(first.nFeeTXHash, second.nFeeTXHash);
swap(first.nTime, second.nTime);
}
CFinalizedBudgetBroadcast& operator=(CFinalizedBudgetBroadcast from)
{
swap(*this, from);
return *this;
}
void Relay();
ADD_SERIALIZE_METHODS;
//for propagating messages
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
//for syncing with other clients
READWRITE(LIMITED_STRING(strBudgetName, 20));
READWRITE(nBlockStart);
READWRITE(vecBudgetPayments);
READWRITE(nFeeTXHash);
}
};
//
// Budget Proposal : Contains the masternode votes for each budget
//
class CBudgetProposal
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
CAmount nAlloted;
public:
bool fValid;
std::string strProposalName;
/*
json object with name, short-description, long-description, pdf-url and any other info
This allows the proposal website to stay 100% decentralized
*/
std::string strURL;
int nBlockStart;
int nBlockEnd;
CAmount nAmount;
CScript address;
int64_t nTime;
uint256 nFeeTXHash;
map<uint256, CBudgetVote> mapVotes;
//cache object
CBudgetProposal();
CBudgetProposal(const CBudgetProposal& other);
CBudgetProposal(std::string strProposalNameIn, std::string strURLIn, int nBlockStartIn, int nBlockEndIn, CScript addressIn, CAmount nAmountIn, uint256 nFeeTXHashIn);
void Calculate();
bool AddOrUpdateVote(CBudgetVote& vote, std::string& strError);
bool HasMinimumRequiredSupport();
std::pair<std::string, std::string> GetVotes();
bool IsValid(std::string& strError, bool fCheckCollateral = true);
bool IsEstablished()
{
// Proposals must be at least a day old to make it into a budget
if (Params().NetworkID() == CBaseChainParams::MAIN) return (nTime < GetTime() - (60 * 60 * 24));
// For testing purposes - 5 minutes
return (nTime < GetTime() - (60 * 5));
}
std::string GetName() { return strProposalName; }
std::string GetURL() { return strURL; }
int GetBlockStart() { return nBlockStart; }
int GetBlockEnd() { return nBlockEnd; }
CScript GetPayee() { return address; }
int GetTotalPaymentCount();
int GetRemainingPaymentCount();
int GetBlockStartCycle();
int GetBlockCurrentCycle();
int GetBlockEndCycle();
double GetRatio();
int GetYeas();
int GetNays();
int GetAbstains();
CAmount GetAmount() { return nAmount; }
void SetAllotted(CAmount nAllotedIn) { nAlloted = nAllotedIn; }
CAmount GetAllotted() { return nAlloted; }
void CleanAndRemove(bool fSignatureCheck);
uint256 GetHash()
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << strProposalName;
ss << strURL;
ss << nBlockStart;
ss << nBlockEnd;
ss << nAmount;
ss << address;
uint256 h1 = ss.GetHash();
return h1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
//for syncing with other clients
READWRITE(LIMITED_STRING(strProposalName, 20));
READWRITE(LIMITED_STRING(strURL, 64));
READWRITE(nTime);
READWRITE(nBlockStart);
READWRITE(nBlockEnd);
READWRITE(nAmount);
READWRITE(address);
READWRITE(nTime);
READWRITE(nFeeTXHash);
//for saving to the serialized db
READWRITE(mapVotes);
}
};
// Proposals are cast then sent to peers with this object, which leaves the votes out
class CBudgetProposalBroadcast : public CBudgetProposal
{
public:
CBudgetProposalBroadcast() : CBudgetProposal() {}
CBudgetProposalBroadcast(const CBudgetProposal& other) : CBudgetProposal(other) {}
CBudgetProposalBroadcast(const CBudgetProposalBroadcast& other) : CBudgetProposal(other) {}
CBudgetProposalBroadcast(std::string strProposalNameIn, std::string strURLIn, int nPaymentCount, CScript addressIn, CAmount nAmountIn, int nBlockStartIn, uint256 nFeeTXHashIn);
void swap(CBudgetProposalBroadcast& first, CBudgetProposalBroadcast& second) // nothrow
{
// enable ADL (not necessary in our case, but good practice)
using std::swap;
// by swapping the members of two classes,
// the two classes are effectively swapped
swap(first.strProposalName, second.strProposalName);
swap(first.nBlockStart, second.nBlockStart);
swap(first.strURL, second.strURL);
swap(first.nBlockEnd, second.nBlockEnd);
swap(first.nAmount, second.nAmount);
swap(first.address, second.address);
swap(first.nTime, second.nTime);
swap(first.nFeeTXHash, second.nFeeTXHash);
first.mapVotes.swap(second.mapVotes);
}
CBudgetProposalBroadcast& operator=(CBudgetProposalBroadcast from)
{
swap(*this, from);
return *this;
}
void Relay();
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
//for syncing with other clients
READWRITE(LIMITED_STRING(strProposalName, 20));
READWRITE(LIMITED_STRING(strURL, 64));
READWRITE(nTime);
READWRITE(nBlockStart);
READWRITE(nBlockEnd);
READWRITE(nAmount);
READWRITE(address);
READWRITE(nFeeTXHash);
}
};
#endif
| [
"[email protected]"
] | |
651e4d47cd31649994b2ffda17f4132a4db044e0 | 683a90831bb591526c6786e5f8c4a2b34852cf99 | /OmegaUp/120_Batalla.cpp | 8850bff34cc8ffd920d0aa5496b9a8e5eed3792d | [] | no_license | dbetm/cp-history | 32a3ee0b19236a759ce0a6b9ba1b72ceb56b194d | 0ceeba631525c4776c21d547e5ab101f10c4fe70 | refs/heads/main | 2023-04-29T19:36:31.180763 | 2023-04-15T18:03:19 | 2023-04-15T18:03:19 | 164,786,056 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | cpp | #include <bits/stdc++.h>
// https://omegaup.com/arena/problem/batalla#problems
using namespace std;
int main() {
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
int n, pointer = 0, suma = 0;
cin >> n;
vector<int> mis(n);
vector<int> Lira(n);
for (int i = 0; i < n; i++) cin >> mis[i];
for (int i = 0; i < n; i++) cin >> Lira[i];
sort(mis.rbegin(), mis.rend());
sort(Lira.rbegin(), Lira.rend());
for (int i = 0; i < n; i++) {
int miSoldado = mis[i];
//cout << miSoldado << endl;
while(pointer < n) {
//cout << "Lira->" << Lira[pointer] << endl;
if(Lira[pointer] < miSoldado) {
suma += miSoldado;
pointer++;
break;
}
pointer++;
}
if(pointer == n) break;
}
cout << suma << endl;
return 0;
}
| [
"[email protected]"
] | |
e0403e7b9f651c8e501ebe56c373685577cdade1 | 2452e0375b99a3226f01814c3138c8edf7b3dbd1 | /阴影/PSSM/Sources/D3D10/ShadowMap_D3D10.h | 7e52acf8b7a409e9390178000f437e4b0f8b2e1a | [] | no_license | hello-choulvlv/hello-world | ac00931ab6b2e7e921e68875b1b8a918476351a7 | 29cdc82c847a4ecf5d6051a6bb084260cded5cc7 | refs/heads/master | 2021-12-29T09:40:58.368942 | 2021-12-15T04:45:47 | 2021-12-15T04:45:47 | 209,924,279 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 701 | h | #pragma once
#include "../Framework/ShadowMap.h"
// This is a simple wrapper class for creating
// and using renderable shadow map textures.
//
class ShadowMap_D3D10 : public ShadowMap
{
public:
ShadowMap_D3D10();
~ShadowMap_D3D10();
bool Create(int iSize);
bool CreateAsTextureArray(int iSize, int iArraySize);
bool CreateAsTextureCube(int iSize);
void Destroy(void);
// start rendering to texture
void EnableRendering(void);
// stop rendering to texture
void DisableRendering(void);
int GetMemoryInMB(void);
public:
int m_iArraySize;
ID3D10Texture2D *m_pTexture;
ID3D10DepthStencilView *m_pDSV;
ID3D10ShaderResourceView *m_pSRV;
}; | [
"[email protected]"
] | |
d995074ede01a7aa31a24fa2a0a96fd513ba6dd5 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/browser/chromeos/file_manager/select_file_dialog_util.cc | 2ec58215c89f989274b6f1386be83db9e3dcf51d | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_manager/select_file_dialog_util.h"
#include "chrome/grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace file_manager {
namespace util {
base::string16 GetSelectFileDialogTitle(
ui::SelectFileDialog::Type dialog_type) {
base::string16 title;
switch (dialog_type) {
case ui::SelectFileDialog::SELECT_NONE:
// Full page file manager doesn't need a title.
break;
case ui::SelectFileDialog::SELECT_FOLDER:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_FOLDER_TITLE);
break;
case ui::SelectFileDialog::SELECT_UPLOAD_FOLDER:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_UPLOAD_FOLDER_TITLE);
break;
case ui::SelectFileDialog::SELECT_SAVEAS_FILE:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_SAVEAS_FILE_TITLE);
break;
case ui::SelectFileDialog::SELECT_OPEN_FILE:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_OPEN_FILE_TITLE);
break;
case ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE:
title = l10n_util::GetStringUTF16(
IDS_FILE_BROWSER_SELECT_OPEN_MULTI_FILE_TITLE);
break;
default:
NOTREACHED();
}
return title;
}
} // namespace util
} // namespace file_manager
| [
"[email protected]"
] | |
9e974d606cbc581ee4dc119aa9527e1fa13b1c3a | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/242/780/CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_10.cpp | 931727c56d2a58a3e8489e521e9ce2e7d8728c56 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,500 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_10.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-10.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: calloc Allocate data using calloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 10 Control flow: if(globalTrue) and if(globalFalse)
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_10
{
#ifndef OMITBAD
void bad()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalTrue)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
}
if(globalTrue)
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second globalTrue to globalFalse */
static void goodB2G1()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalTrue)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
}
if(globalFalse)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Deallocate the memory using free() */
free(data);
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalTrue)
{
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (long *)calloc(100, sizeof(long));
if (data == NULL) {exit(-1);}
}
if(globalTrue)
{
/* FIX: Deallocate the memory using free() */
free(data);
}
}
/* goodG2B1() - use goodsource and badsink by changing the first globalTrue to globalFalse */
static void goodG2B1()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalFalse)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Allocate memory from the heap using new */
data = new long;
}
if(globalTrue)
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
long * data;
/* Initialize data*/
data = NULL;
if(globalTrue)
{
/* FIX: Allocate memory from the heap using new */
data = new long;
}
if(globalTrue)
{
/* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete data;
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_calloc_10; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"[email protected]"
] | |
e52254f6ea39f74db645b41eeefed6bd1baf6755 | be8e1cb8545bbf41f0785b005f4b7711beb9caef | /HW3/HW3/chap7/717.cpp | 8a45b01a1df9d8fb80ff666d2efbccd4770bb127 | [] | no_license | a107590451/OS | 81e2d3d312f66af985abaa92370b8b34f67a7cc3 | 48eee9d725fd90cde9014f5b47fb47e3317ebfc8 | refs/heads/main | 2023-06-24T05:23:53.617763 | 2021-07-21T14:49:11 | 2021-07-21T14:49:11 | 386,230,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,350 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <unistd.h>
sem_t accessible;
// 子執行緒函數
void *northFarmer(void *arg) {//call northFarmer
sem_wait(&accessible);
int walkTime = rand()%3+1;
printf("northFarmer enter walkTime:%ds\n",walkTime);
sleep(walkTime);
sem_post(&accessible);
printf("northFarmer exit\n");
pthread_exit(NULL);
}
void *southFarmer(void *arg) {//call southFarmer
sem_wait(&accessible);
int walkTime = rand()%3+1;
printf("southFarmer enter walkTime:%ds\n",walkTime);
sleep(walkTime);
sem_post(&accessible);
printf("southFarmer exit\n");
pthread_exit(NULL);
}
// 主程式
int main() {
//init
srand(time(NULL));
pthread_t northFarmers[5];
pthread_t southFarmers[5];
sem_init(&accessible, 0, 1);
// 建立子執行緒
for(int i=0;i<5;i++){
pthread_create(&northFarmers[i], NULL, northFarmer, NULL);
pthread_create(&southFarmers[i], NULL, southFarmer, NULL);
}
// 等待子執行緒完畢
for(int i=0;i<5;i++){
pthread_join(southFarmers[i], NULL);
printf("south pthread[%d] end\n",i);
pthread_join(northFarmers[i], NULL);
printf("north pthread[%d] end\n",i);
}
sem_destroy(&accessible);
return 0;
} | [
"[email protected]"
] | |
26b2985ec237d5399a0b9bb7c97c69cbc0e67c07 | 2aeadae5d007421bda27bfcdac0f27b25ad24087 | /User/FML/fml_ano_protocol.cpp | 53c995f47aa9e635dd6afddb63d7b345bac4e112 | [] | no_license | Liu-Ziwen/Alpha-One-Flight-Control-System | 80f8a809492fd76a8130620c98c0985d3e16eb21 | 5988ad416df82b322f2f4e82d704125a45c18807 | refs/heads/master | 2020-05-04T15:24:44.085346 | 2019-04-25T07:41:27 | 2019-04-25T07:41:27 | 179,239,693 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 16,244 | cpp | /**
* @project Alpha One Flight Control System
* @author Dr.Sheng Team
* @version V1.0.0
* @date 22-April-2019
* @file fml_ano_protocol.cpp
*/
#include "main.h"
FML_ANO fml_ano;
/////////////////////////////////////////////////////////////////////////////////////
//exchange函数处理各种数据发送请求,比如想实现每5ms发送一次传感器数据至上位机,即在此函数内实现
//此函数应由用户每1ms调用一次
//在本工程中每400Hz调用一次
void FML_ANO::exchange(void)
{
static uint8_t cnt = 0;
static uint8_t sensor_cnt = 2; //200hz
static uint8_t status_cnt = 4; //100hz
static uint8_t rc_data_cnt = 8; //50hz
static uint8_t motor_pwm_cnt = 20; //20hz
static uint8_t power_cnt = 40; //10hz
if((cnt % sensor_cnt) == (sensor_cnt-1))
flag.send_sensor = 1;
if((cnt % status_cnt) == (status_cnt-1))
flag.send_status = 1;
if((cnt % rc_data_cnt) == (rc_data_cnt-1))
flag.send_rc_data = 1;
if((cnt % motor_pwm_cnt) == (motor_pwm_cnt-1))
flag.send_motor_pwm = 1;
if((cnt % power_cnt) == (power_cnt-1))
flag.send_power = 1;
cnt++;
if(flag.send_version)
{
flag.send_version = 0;
send_version(4,300,100,400,0);
}
else if(flag.send_status)
{
flag.send_status = 0;
send_status(0,0,0,0,0,0);
}
else if(flag.send_sensor)
{
flag.send_sensor = 0;
send_sensor(mpu6k.raw_data.ACC_X, mpu6k.raw_data.ACC_Y, mpu6k.raw_data.ACC_Z,
mpu6k.raw_data.GYR_X, mpu6k.raw_data.GYR_Y, mpu6k.raw_data.GYR_Z,
hmc5883l.raw_data.MAG_X, hmc5883l.raw_data.MAG_Y, hmc5883l.raw_data.MAG_Z,
ms5611.baro_pressure);
}
else if(flag.send_rc_data)
{
flag.send_rc_data = 0;
// send_rc_data(PPM_CAP.Channel[2],
// PPM_CAP.Channel[3],
// PPM_CAP.Channel[1],
// PPM_CAP.Channel[0],
// PPM_CAP.Channel[4],
// PPM_CAP.Channel[5],
// PPM_CAP.Channel[6],
// PPM_CAP.Channel[7],0,0);
}
else if(flag.send_motor_pwm)
{
flag.send_motor_pwm = 0;
send_motor_pwm(0,0,0,0,0,0,0,0);
}
else if(flag.send_power)
{
flag.send_power = 0;
send_power(1200,0);
}
else if(flag.send_pid1)
{
flag.send_pid1 = 0;
send_pid(0,0,0,0,0,0,0,0,0,0);
}
else if(flag.send_pid2)
{
flag.send_pid2 = 0;
}
else if(flag.send_pid3)
{
flag.send_pid3 = 0;
}
}
/////////////////////////////////////////////////////////////////////////////////////
//Data_Receive_Prepare函数是协议预解析,根据协议的格式,将收到的数据进行一次格式性解析,格式正确的话再进行数据解析
//移植时,此函数应由用户根据自身使用的通信方式自行调用,比如串口每收到一字节数据,则调用此函数一次
//此函数解析出符合格式的数据帧后,会自行调用数据解析函数
void FML_ANO::receive_prepare(uint8_t data)
{
static uint8_t _data_len = 0;
static uint8_t _data_cnt = 0;
static uint8_t state = 0;
if(state==0&&data==0xAA)
{
state=1;
com4_rx_buf[0]=data;
}
else if(state==1&&data==0xAF)
{
state=2;
com4_rx_buf[1]=data;
}
else if(state==2&&data<0xF1)
{
state=3;
com4_rx_buf[2]=data;
}
else if(state==3&&data<50)
{
state = 4;
com4_rx_buf[3]=data;
_data_len = data;
_data_cnt = 0;
}
else if(state==4&&_data_len>0)
{
_data_len--;
com4_rx_buf[4+_data_cnt++]=data;
if(_data_len==0)
state = 5;
}
else if(state==5)
{
state = 0;
com4_rx_buf[4+_data_cnt]=data;
data_receive_anl(com4_rx_buf,_data_cnt+5);
}
else
state = 0;
}
/////////////////////////////////////////////////////////////////////////////////////
//Send_Data函数是协议中所有发送数据功能使用到的发送函数
//移植时,用户应根据自身应用的情况,根据使用的通信方式,实现此函数
void FML_ANO::send_data(uint8_t length)
{
hal_dma.transfer(COM4, length);
}
//发送校验数据给上位机
//head:帧头//check_sum:接收到的数据帧计算出的校验和
//如要返回PID1数据帧的校验数据,head = 0x10,见ANO_XIEYI的表格
void FML_ANO::send_check(uint8_t head, uint8_t check_sum)
{
com4_tx_buf[0]=0xAA;
com4_tx_buf[1]=0xAA;
com4_tx_buf[2]=0xEF;
com4_tx_buf[3]=2;
com4_tx_buf[4]=head;
com4_tx_buf[5]=check_sum;
uint8_t sum = 0;
for(uint8_t i=0;i<6;i++)
sum += com4_tx_buf[i];
com4_tx_buf[6]=sum;
send_data(7);
}
//发送版本号
void FML_ANO::send_version(uint8_t hardware_type, uint16_t hardware_ver,uint16_t software_ver,uint16_t protocol_ver,uint16_t bootloader_ver)
{
uint8_t _cnt=0;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x00;
com4_tx_buf[_cnt++]=0;
com4_tx_buf[_cnt++]=hardware_type;
com4_tx_buf[_cnt++]=BYTE1(hardware_ver);
com4_tx_buf[_cnt++]=BYTE0(hardware_ver);
com4_tx_buf[_cnt++]=BYTE1(software_ver);
com4_tx_buf[_cnt++]=BYTE0(software_ver);
com4_tx_buf[_cnt++]=BYTE1(protocol_ver);
com4_tx_buf[_cnt++]=BYTE0(protocol_ver);
com4_tx_buf[_cnt++]=BYTE1(bootloader_ver);
com4_tx_buf[_cnt++]=BYTE0(bootloader_ver);
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++]=sum;
send_data(_cnt);
}
//发送姿态角、高度、飞行模式、加解锁情况
void FML_ANO::send_status(float angle_rol, float angle_pit, float angle_yaw, int32_t alt, uint8_t fly_model, uint8_t armed)
{
uint8_t _cnt=0;
volatile int16_t _temp;
vs32 _temp2 = alt;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x01;
com4_tx_buf[_cnt++]=0;
_temp = (int)(angle_rol*100);
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = (int)(angle_pit*100);
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = (int)(angle_yaw*100);
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
com4_tx_buf[_cnt++]=BYTE3(_temp2);
com4_tx_buf[_cnt++]=BYTE2(_temp2);
com4_tx_buf[_cnt++]=BYTE1(_temp2);
com4_tx_buf[_cnt++]=BYTE0(_temp2);
com4_tx_buf[_cnt++] = fly_model;
com4_tx_buf[_cnt++] = armed;
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++]=sum;
send_data(_cnt);
}
//发送传感器数据,三轴加速度计、三轴陀螺仪、三轴磁力计、气压
void FML_ANO::send_sensor(int16_t a_x,int16_t a_y,int16_t a_z,int16_t g_x,int16_t g_y,int16_t g_z,int16_t m_x,int16_t m_y,int16_t m_z,int32_t bar)
{
uint8_t _cnt=0;
volatile int16_t _temp;
// volatile int32_t _temp2;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x02;
com4_tx_buf[_cnt++]=0;
_temp = a_x;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = a_y;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = a_z;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = g_x;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = g_y;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = g_z;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = m_x;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = m_y;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = m_z;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
// _temp2 = bar;
// com4_tx_buf[_cnt++]=BYTE3(_temp2);
// com4_tx_buf[_cnt++]=BYTE2(_temp2);
// com4_tx_buf[_cnt++]=BYTE1(_temp2);
// com4_tx_buf[_cnt++]=BYTE0(_temp2);
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++] = sum;
send_data(_cnt);
}
//发送遥控器信号值
void FML_ANO::send_rc_data(uint16_t thr,uint16_t yaw,uint16_t rol,uint16_t pit,uint16_t aux1,uint16_t aux2,uint16_t aux3,uint16_t aux4,uint16_t aux5,uint16_t aux6)
{
uint8_t _cnt=0;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x03;
com4_tx_buf[_cnt++]=0;
com4_tx_buf[_cnt++]=BYTE1(thr);
com4_tx_buf[_cnt++]=BYTE0(thr);
com4_tx_buf[_cnt++]=BYTE1(yaw);
com4_tx_buf[_cnt++]=BYTE0(yaw);
com4_tx_buf[_cnt++]=BYTE1(rol);
com4_tx_buf[_cnt++]=BYTE0(rol);
com4_tx_buf[_cnt++]=BYTE1(pit);
com4_tx_buf[_cnt++]=BYTE0(pit);
com4_tx_buf[_cnt++]=BYTE1(aux1);
com4_tx_buf[_cnt++]=BYTE0(aux1);
com4_tx_buf[_cnt++]=BYTE1(aux2);
com4_tx_buf[_cnt++]=BYTE0(aux2);
com4_tx_buf[_cnt++]=BYTE1(aux3);
com4_tx_buf[_cnt++]=BYTE0(aux3);
com4_tx_buf[_cnt++]=BYTE1(aux4);
com4_tx_buf[_cnt++]=BYTE0(aux4);
com4_tx_buf[_cnt++]=BYTE1(aux5);
com4_tx_buf[_cnt++]=BYTE0(aux5);
com4_tx_buf[_cnt++]=BYTE1(aux6);
com4_tx_buf[_cnt++]=BYTE0(aux6);
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++]=sum;
send_data(_cnt);
}
//发送电压和电流值
void FML_ANO::send_power(uint16_t votage, uint16_t current)
{
uint8_t _cnt=0;
uint16_t temp;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x05;
com4_tx_buf[_cnt++]=0;
temp = votage;
com4_tx_buf[_cnt++]=BYTE1(temp);
com4_tx_buf[_cnt++]=BYTE0(temp);
temp = current;
com4_tx_buf[_cnt++]=BYTE1(temp);
com4_tx_buf[_cnt++]=BYTE0(temp);
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++]=sum;
send_data(_cnt);
}
//发送电机PWM值
void FML_ANO::send_motor_pwm(uint16_t m_1,uint16_t m_2,uint16_t m_3,uint16_t m_4,uint16_t m_5,uint16_t m_6,uint16_t m_7,uint16_t m_8)
{
uint8_t _cnt=0;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x06;
com4_tx_buf[_cnt++]=0;
com4_tx_buf[_cnt++]=BYTE1(m_1);
com4_tx_buf[_cnt++]=BYTE0(m_1);
com4_tx_buf[_cnt++]=BYTE1(m_2);
com4_tx_buf[_cnt++]=BYTE0(m_2);
com4_tx_buf[_cnt++]=BYTE1(m_3);
com4_tx_buf[_cnt++]=BYTE0(m_3);
com4_tx_buf[_cnt++]=BYTE1(m_4);
com4_tx_buf[_cnt++]=BYTE0(m_4);
com4_tx_buf[_cnt++]=BYTE1(m_5);
com4_tx_buf[_cnt++]=BYTE0(m_5);
com4_tx_buf[_cnt++]=BYTE1(m_6);
com4_tx_buf[_cnt++]=BYTE0(m_6);
com4_tx_buf[_cnt++]=BYTE1(m_7);
com4_tx_buf[_cnt++]=BYTE0(m_7);
com4_tx_buf[_cnt++]=BYTE1(m_8);
com4_tx_buf[_cnt++]=BYTE0(m_8);
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++]=sum;
send_data(_cnt);
}
//发送PID参数
void FML_ANO::send_pid(uint8_t group,float p1_p,float p1_i,float p1_d,float p2_p,float p2_i,float p2_d,float p3_p,float p3_i,float p3_d)
{
uint8_t _cnt=0;
volatile int16_t _temp;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0xAA;
com4_tx_buf[_cnt++]=0x10+group-1;
com4_tx_buf[_cnt++]=0;
_temp = p1_p * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p1_i * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p1_d * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p2_p * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p2_i * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p2_d * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p3_p * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p3_i * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
_temp = p3_d * 1000;
com4_tx_buf[_cnt++]=BYTE1(_temp);
com4_tx_buf[_cnt++]=BYTE0(_temp);
com4_tx_buf[3] = _cnt-4;
uint8_t sum = 0;
for(uint8_t i=0;i<_cnt;i++)
sum += com4_tx_buf[i];
com4_tx_buf[_cnt++]=sum;
send_data(_cnt);
}
/////////////////////////////////////////////////////////////////////////////////////
//Data_Receive_Anl函数是协议数据解析函数,函数参数是符合协议格式的一个数据帧,该函数会首先对协议数据进行校验
//校验通过后对数据进行解析,实现相应功能
//此函数可以不用用户自行调用,由函数Data_Receive_Prepare自动调用
void FML_ANO::data_receive_anl(uint8_t *data_buf,uint8_t num)
{
uint8_t sum = 0;
for(uint8_t i=0;i<(num-1);i++)
sum += *(data_buf+i);
if(!(sum==*(data_buf+num-1))) return; //判断sum
if(!(*(data_buf)==0xAA && *(data_buf+1)==0xAF)) return; //判断帧头
if(*(data_buf+2)==0x01)
{
if(*(data_buf+4)==0x01)
{
// mpu6050.Acc_CALIBRATE = 1;//校准加速度计
}
if(*(data_buf+4)==0x02)
{
// mpu6050.Gyro_CALIBRATE = 1;//校准陀螺仪
}
if(*(data_buf+4)==0x03)
{
// mpu6050.Acc_CALIBRATE = 1;
// mpu6050.Gyro_CALIBRATE = 1;
}
}
if(*(data_buf+2)==0x02)
{
if(*(data_buf+4)==0x01)
{
flag.send_pid1 = 1;
flag.send_pid2 = 1;
flag.send_pid3 = 1;
flag.send_pid4 = 1;
flag.send_pid5 = 1;
flag.send_pid6 = 1;
}
if(*(data_buf+4)==0x02)
{
}
if(*(data_buf+4)==0xA0) //读取版本信息
{
flag.send_version = 1;
}
if(*(data_buf+4)==0xA1) //恢复默认参数
{
// Para_ResetToFactorySetup();
}
}
if(*(data_buf+2)==0x10) //PID1
{
// ctrl_1.PID[PIDROLL].kp = 0.001*( (volatile int16_t)(*(data_buf+4)<<8)|*(data_buf+5) );
// ctrl_1.PID[PIDROLL].ki = 0.001*( (volatile int16_t)(*(data_buf+6)<<8)|*(data_buf+7) );
// ctrl_1.PID[PIDROLL].kd = 0.001*( (volatile int16_t)(*(data_buf+8)<<8)|*(data_buf+9) );
// ctrl_1.PID[PIDPITCH].kp = 0.001*( (volatile int16_t)(*(data_buf+10)<<8)|*(data_buf+11) );
// ctrl_1.PID[PIDPITCH].ki = 0.001*( (volatile int16_t)(*(data_buf+12)<<8)|*(data_buf+13) );
// ctrl_1.PID[PIDPITCH].kd = 0.001*( (volatile int16_t)(*(data_buf+14)<<8)|*(data_buf+15) );
// ctrl_1.PID[PIDYAW].kp = 0.001*( (volatile int16_t)(*(data_buf+16)<<8)|*(data_buf+17) );
// ctrl_1.PID[PIDYAW].ki = 0.001*( (volatile int16_t)(*(data_buf+18)<<8)|*(data_buf+19) );
// ctrl_1.PID[PIDYAW].kd = 0.001*( (volatile int16_t)(*(data_buf+20)<<8)|*(data_buf+21) );
send_check(*(data_buf+2),sum);
// Param_SavePID();
}
if(*(data_buf+2)==0x11) //PID2
{
// ctrl_1.PID[PID4].kp = 0.001*( (volatile int16_t)(*(data_buf+4)<<8)|*(data_buf+5) );
// ctrl_1.PID[PID4].ki = 0.001*( (volatile int16_t)(*(data_buf+6)<<8)|*(data_buf+7) );
// ctrl_1.PID[PID4].kd = 0.001*( (volatile int16_t)(*(data_buf+8)<<8)|*(data_buf+9) );
// ctrl_1.PID[PID5].kp = 0.001*( (volatile int16_t)(*(data_buf+10)<<8)|*(data_buf+11) );
// ctrl_1.PID[PID5].ki = 0.001*( (volatile int16_t)(*(data_buf+12)<<8)|*(data_buf+13) );
// ctrl_1.PID[PID5].kd = 0.001*( (volatile int16_t)(*(data_buf+14)<<8)|*(data_buf+15) );
// ctrl_1.PID[PID6].kp = 0.001*( (volatile int16_t)(*(data_buf+16)<<8)|*(data_buf+17) );
// ctrl_1.PID[PID6].ki = 0.001*( (volatile int16_t)(*(data_buf+18)<<8)|*(data_buf+19) );
// ctrl_1.PID[PID6].kd = 0.001*( (volatile int16_t)(*(data_buf+20)<<8)|*(data_buf+21) );
send_check(*(data_buf+2),sum);
// Param_SavePID();
}
if(*(data_buf+2)==0x12) //PID3
{
// ctrl_2.PID[PIDROLL].kp = 0.001*( (volatile int16_t)(*(data_buf+4)<<8)|*(data_buf+5) );
// ctrl_2.PID[PIDROLL].ki = 0.001*( (volatile int16_t)(*(data_buf+6)<<8)|*(data_buf+7) );
// ctrl_2.PID[PIDROLL].kd = 0.001*( (volatile int16_t)(*(data_buf+8)<<8)|*(data_buf+9) );
// ctrl_2.PID[PIDPITCH].kp = 0.001*( (volatile int16_t)(*(data_buf+10)<<8)|*(data_buf+11) );
// ctrl_2.PID[PIDPITCH].ki = 0.001*( (volatile int16_t)(*(data_buf+12)<<8)|*(data_buf+13) );
// ctrl_2.PID[PIDPITCH].kd = 0.001*( (volatile int16_t)(*(data_buf+14)<<8)|*(data_buf+15) );
// ctrl_2.PID[PIDYAW].kp = 0.001*( (volatile int16_t)(*(data_buf+16)<<8)|*(data_buf+17) );
// ctrl_2.PID[PIDYAW].ki = 0.001*( (volatile int16_t)(*(data_buf+18)<<8)|*(data_buf+19) );
// ctrl_2.PID[PIDYAW].kd = 0.001*( (volatile int16_t)(*(data_buf+20)<<8)|*(data_buf+21) );
send_check(*(data_buf+2),sum);
// Param_SavePID();
}
if(*(data_buf+2)==0x13) //PID4
{
send_check(*(data_buf+2),sum);
}
if(*(data_buf+2)==0x14) //PID5
{
send_check(*(data_buf+2),sum);
}
if(*(data_buf+2)==0x15) //PID6
{
send_check(*(data_buf+2),sum);
}
}
| [
"[email protected]"
] | |
2c072cd5ea1b204f73d68efde81bb4537168b644 | 166969b35d6885454abdaf8538a2976daf6040ee | /v0.9/deviceManager/serialprotocol2012.cpp | b9933e15f84a882c96d003af24968bb184880519 | [] | no_license | jeffHODev/tcc8900-si4754 | 803f9987e78543909a23df085864065defff09d4 | b8dde12c127e04866891cba2fee9370f30cfd0d2 | refs/heads/master | 2023-04-27T13:36:42.953748 | 2015-09-11T09:05:34 | 2015-09-11T09:05:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,816 | cpp | #include <pthread.h>
#include "Utility.h"
#include "GB19056Proxy.h"
#include "serialprotocol2012.h"
#include "devicemanager.h"
#include "GeneralTimer.h"
#include "mcuprotocol.h"
#include "DeviceManagerDbusMessage.h"
#include "dbusServer.h"
static int sp_fd = -1;
static unsigned char cmd_buf[MAX_LEN];
static int cmd_len = 0;
static int cmd_flag = 0;
static pthread_mutex_t sp_mutex;
int loc1_lock_flag = 0;
int not_process_loc1 = 0;
int mileage_flag = 0;// 1: need to update deploy mileage
extern pthread_mutex_t engine_list_mutex_loc;
extern DBusServerC *dev_DbusServer;
static int in_DB9_check = 0;
GeneralTimerItem *DB9statustimer = NULL;
GeneralTimerItem *DB9mileagetimer = NULL;
extern void data_up_pass_through_info(unsigned char *msgbuf);
int check_sum(unsigned char *buf,int len)
{
int i;
unsigned char temp = 0;
for(i=0; i<len; i++)
{
temp = temp ^ buf[i];
}
return temp;
}
int parse_readbuf(unsigned char *readbuf,int readnum,unsigned char *msgcountbuf)
{
int msgcount = 0;
int i=0,j=0;
unsigned char temp[20];
int datalength;
for(i=0; i<readnum; i++)
{
if(readbuf[i] == 0xAA && readbuf[i+1] == 0x75)
{
temp[j] = i;
j++;
}
}
for(i = 0;i<j;i++)
{
if((readnum -temp[i]) >= 5)
{
datalength = readbuf[temp[i] + 3]<<8 | readbuf[temp[i] + 4];
if((temp[i] + datalength + 7 - 1) <= readnum)
{
msgcountbuf[msgcount] = temp[i];
msgcount++;
}
}
}
return msgcount;
}
//pthread
void* read_serial_data_thread(void *)
{
int read_fd;
int len = 0, rev_len=0;
int data_len=0, i=0,j=0;
unsigned char rev_buf[MAX_LEN];
unsigned char *ptr = NULL;
read_fd = OpenComPort(4, 115200, 8, "1", 'O');
if(read_fd < 0)
{
printf("Can not open the serial port\n");
return 0;
}
memset(rev_buf, 0, sizeof(rev_buf));
while(1)
{
if(rev_len > MAX_LEN/2)
memset(rev_buf, 0, sizeof(rev_buf));
len = ReadComPort(read_fd, rev_buf+rev_len, MAX_LEN);
if(len < 0)
{
printf("ReadComPort failed \n");
break;
}
else
{
rev_len += len;
next:
for(i=0; i<rev_len; i++)
{
if(rev_buf[i] == 0xAA && rev_buf[i+1] == 0x75)
{
if(rev_buf[i+2] == 0xC4)
mileage_flag = 2;
ptr = rev_buf+i;
printf("i=%d, rev_len=%d\n",i,rev_len);
break;
}
}
if((rev_len-i) >= 7)
{
data_len = (ptr[3]<<8) | ptr[4];
if((rev_len-i) >= (7+data_len))
{
pthread_mutex_lock(&sp_mutex);
if(cmd_flag)
{
memcpy(cmd_buf+cmd_len, ptr, 7+data_len);
cmd_len = cmd_len+7+data_len;
}
else
{
memset(cmd_buf, 0, MAX_LEN);
memcpy(cmd_buf, ptr, 7+data_len);
cmd_len = 7+data_len;
}
cmd_flag = 1;
pthread_mutex_unlock(&sp_mutex);
rev_len = rev_len-i-data_len-7;
for(j=0; j<rev_len;j++)
{
rev_buf[j] = rev_buf[i+7+data_len+j];
printf(" 0x%02x ",rev_buf[j]);
}
printf("\n");
if(rev_len >= 7)
goto next;
}
}
}
}
if(read_fd)
CloseComPort(read_fd);
return 0;
}
void process_DB9_check_command(unsigned char *buf, int len)
{
if(buf[len] != check_sum(buf, len))
return ;
DeviceDB9CheckDbusNotifyC notify;
switch(buf[2])
{
case (unsigned char)ENUM_GB19056_CMD_CHECK_IN:
if(!in_DB9_check)
{
in_DB9_check = 1;
StartTimer(DB9statustimer);
notify.flag = 1;
dev_DbusServer->sendNotify(¬ify);
}
else
{
StopTimer(DB9statustimer);
StartTimer(DB9statustimer);
}
break;
case (unsigned char)ENUM_GB19056_CMD_CHECK_MILEAGE:
I2c_write_DB9_7_check_data(DB9_MILEAGE_CHECK);
StartTimer(DB9mileagetimer);
break;
case (unsigned char)ENUM_GB19056_CMD_CHECK_PULSE_FACTOR:
I2c_write_DB9_7_check_data(DB9_PULSE_FACTOR_CHECK);
StopTimer(DB9mileagetimer);
break;
case (unsigned char)ENUM_GB19056_CMD_CHECK_TIME:
I2c_write_DB9_7_check_data(DB9_TIME_CHECK);
StopTimer(DB9mileagetimer);
break;
case (unsigned char)ENUM_GB19056_CMD_CHECK_OUT:
in_DB9_check = 0;
notify.flag = 0;
dev_DbusServer->sendNotify(¬ify);
I2c_write_DB9_7_check_data(DB9_OUT_CHECK);
StopTimer(DB9statustimer);
StopTimer(DB9mileagetimer);
break;
}
}
void* write_serial_data_thread(void *)
{
int i=0,j=0;
unsigned char redbuf[MAX_LEN];
unsigned char msgbuf[MAX_LEN];
unsigned char msgcountbuf[20];
int datalength;
int len=0,flag=0;
vector<unsigned char> input, output;
/* open comport */
sp_fd = OpenComPort(4, 115200, 8, "1", 'O');
if(sp_fd < 0)
{
printf("Can not open the serial port\n");
return 0;
}
while(1)
{
if(cmd_flag)
{
pthread_mutex_lock(&sp_mutex);
memcpy(redbuf, cmd_buf, cmd_len);
len = cmd_len;
cmd_flag = 0;
flag = 1;
pthread_mutex_unlock(&sp_mutex);
}
if(flag)
{
flag = 0;
int msgcount = parse_readbuf(redbuf,len,msgcountbuf);
for(i = 0;i<msgcount;i++)
{
memset(msgbuf,'\0',sizeof(msgbuf));
datalength = redbuf[msgcountbuf[i]+3]<<8 | redbuf[msgcountbuf[i] + 4];
memcpy(msgbuf, redbuf+msgcountbuf[i], datalength + 7);
input.clear();
output.clear();
for(j=0; j<datalength + 7; j++ )
{
input.push_back(msgbuf[j]);
}
if((!in_DB9_check && (msgbuf[2] == ENUM_GB19056_CMD_CHECK_IN)) || in_DB9_check)
{
process_DB9_check_command(msgbuf, datalength+6);
}
if(msgbuf[2]==ENUM_GB19056_CMD_QUERY_MILEAGE || msgbuf[2]==ENUM_GB19056_CMD_CHECK_MILEAGE ||
msgbuf[2]==ENUM_GB19056_CMD_QUERY_SPEED_RECORD || msgbuf[2]==ENUM_GB19056_CMD_QUERY_LOC_RECORD)
{
pthread_mutex_lock (&engine_list_mutex_loc);
loc1_lock_flag = 1;
}
if(msgbuf[2]==ENUM_GB19056_CMD_QUERY_SPEED_RECORD || msgbuf[2]==ENUM_GB19056_CMD_QUERY_LOC_RECORD)
{
not_process_loc1 = 1;
}
#if 0
if(msgbuf[2]==0x1F)
data_up_pass_through_info(msgbuf);
else
#endif
{
GB19056Proxy<2012>::Instance()->ProcessRequest(input, output);
if(loc1_lock_flag)
{
pthread_mutex_unlock (&engine_list_mutex_loc);
loc1_lock_flag = 0;
}
if((output[2] == 0xFA) ||(output[2] == 0xFB))
datalength = 5;
else
datalength = (output[3]<<8|output[4]) + 7;
if(datalength <= 7 || (output[2] != 0x08 && output[2]!=0x09))
{
not_process_loc1 = 0;
}
WriteComPort(sp_fd, &(output[0]), datalength);
switch(output[2])
{
case (unsigned char)ENUM_GB19056_CMD_SET_STATUS_CONFIG_2:
read_deploy_status_config_table();
break;
case (unsigned char)ENUM_GB19056_CMD_SET_PULSE_RATE:
read_deploy_para_table_set_pluse();
break;
case (unsigned char)ENUM_GB19056_CMD_SET_LAP_PULSE_FACTOR:
read_deploy_para_table_set_pluse();
break;
}
}
}
}
else
usleep(500);
}
if(sp_fd!=-1)
CloseComPort(sp_fd);
return 0;
}
void DB9_check_handler(string &name, void *data, void *data2)
{
int value = (int)data;
vector<unsigned char> input, output;
input.clear();
output.clear();
if(value == 1)
{
DeviceDB9CheckDbusNotifyC notify;
notify.flag = 0;
dev_DbusServer->sendNotify(¬ify);
in_DB9_check = 0;
I2c_write_DB9_7_check_data(DB9_OUT_CHECK);
StopTimer(DB9mileagetimer);
input.push_back(0xAA);
input.push_back(0x75);
input.push_back(0xE4);
input.push_back(0x00);
input.push_back(0x00);
input.push_back(0x00);
input.push_back(0x3B);
GB19056Proxy<2012>::Instance()->ProcessRequest(input, output);
}
if(value == 2)
{
int len = 0;
input.push_back(0xAA);
input.push_back(0x75);
input.push_back(0xE1);
input.push_back(0x00);
input.push_back(0x00);
input.push_back(0x00);
input.push_back(0x3E);
pthread_mutex_lock (&engine_list_mutex_loc);
GB19056Proxy<2012>::Instance()->ProcessRequest(input, output);
pthread_mutex_unlock (&engine_list_mutex_loc);
if((output[2] == 0xFA) ||(output[2] == 0xFB))
len = 5;
else
len = (output[3]<<8|output[4]) + 7;
WriteComPort(sp_fd, &(output[0]), len);
}
}
void serial_protocol_init()
{
pthread_t sp_read, sp_write;
DB9statustimer = CreateTimer("DB9status", 6000, (void *)1, DB9_check_handler, false);
DB9mileagetimer = CreateTimer("DB9mileage", 1000, (void *)2, DB9_check_handler, true);
pthread_mutex_init(&sp_mutex, NULL);
pthread_create(&sp_read, NULL,read_serial_data_thread, NULL);
pthread_create(&sp_write, NULL,write_serial_data_thread, NULL);
return;
}
void data_down_pass_through_info(unsigned char *msgbuf,int len)
{
unsigned char buf[1024];
memset(buf, 0, 1024);
#if 0
buf[0] = 0x55;
buf[1] = 0x7A;
buf[2] = 0x1F;
buf[3] = (unsigned char)((len >> 8) & 0xFF);
buf[4] = (unsigned char)(len & 0xFF);
buf[5] = 0x00;
memcpy(buf+6, msgbuf, len);
buf[6+len] = check_sum(buf, 6+len);
#endif
memcpy(buf, msgbuf, len);
for(int j=0; j<len;j++)
{
printf(" 0x%02x ",buf[j]);
}
printf("\n");
WriteComPort(sp_fd, buf,len);
}
| [
"[email protected]"
] | |
c58cdca523943de02ede161d6667794244623f75 | 146d134168c9e348e66e52e34c1296e5023d0df3 | /src/SystemTray.hh | 132069ac9b01e04efedceaae9266d1271e4bd336 | [
"MIT"
] | permissive | ystk/debian-fluxbox | 1e5810e63baf250b1665b6d6736754be4627f8ea | 973f6b0a10e45221ae31e1f6e3a5b0b24b640b5a | refs/heads/master | 2016-09-06T09:00:28.608741 | 2010-07-12T11:23:08 | 2010-07-12T11:23:08 | 35,472,683 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,661 | hh | // SystemTray.hh
// Copyright (c) 2003 - 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef SYSTEMTRAY_HH
#define SYSTEMTRAY_HH
#include "FbTk/FbWindow.hh"
#include "FbTk/EventHandler.hh"
#include "ToolTheme.hh"
#include "ToolbarItem.hh"
#include <list>
#include <memory>
class BScreen;
class ButtonTheme;
class TrayWindow;
class AtomHandler;
namespace FbTk {
template <class T> class ThemeProxy;
class Observer;
}
class SystemTray: public ToolbarItem, public FbTk::EventHandler {
public:
explicit SystemTray(const FbTk::FbWindow &parent,
FbTk::ThemeProxy<ToolTheme> &theme, BScreen& screen);
virtual ~SystemTray();
void move(int x, int y);
void resize(unsigned int width, unsigned int height);
void moveResize(int x, int y,
unsigned int width, unsigned int height);
void show();
void hide();
bool active() { return !m_clients.empty(); }
bool clientMessage(const XClientMessageEvent &event);
void exposeEvent(XExposeEvent &event);
void handleEvent(XEvent &event);
void addClient(Window win, bool using_xembed);
void removeClient(Window win, bool destroyed);
unsigned int width() const;
unsigned int height() const;
unsigned int borderWidth() const;
int numClients() const { return m_clients.size(); }
const FbTk::FbWindow &window() const { return m_window; }
void renderTheme(unsigned char alpha) {
m_window.setBorderWidth(m_theme->border().width());
m_window.setBorderColor(m_theme->border().color());
m_window.setAlpha(alpha);
update();
}
void updateSizing() { m_window.setBorderWidth(m_theme->border().width()); }
void parentMoved() { m_window.parentMoved(); }
static Atom getXEmbedInfoAtom();
private:
void update();
typedef std::list<TrayWindow *> ClientList;
ClientList::iterator findClient(Window win);
void rearrangeClients();
void removeAllClients();
void hideClient(TrayWindow *traywin, bool destroyed = false);
void showClient(TrayWindow *traywin);
FbTk::FbWindow m_window;
FbTk::ThemeProxy<ToolTheme> &m_theme;
BScreen& m_screen;
Pixmap m_pixmap;
std::auto_ptr<AtomHandler> m_handler;
ClientList m_clients;
size_t m_num_visible_clients;
// gaim/pidgin seems to barf if the selection is not an independent window.
// I suspect it's an interacton with parent relationship and gdk window caching.
FbTk::FbWindow m_selection_owner;
std::auto_ptr<FbTk::Observer> m_observer;
};
#endif // SYSTEMTRAY_HH
| [
"[email protected]"
] | |
7d59357333cddf8bc4c68a6d04f1cd73a9d23886 | 17c16fd7343fa00762137c76c520de537433f842 | /booster/booster/smart_ptr/sp_convertible.h | 97048281a30ad4ef6f8d6d742c8d4949192e9e98 | [
"BSL-1.0",
"MIT"
] | permissive | gatehouse/cppcms | 8e0f75eb5835cfa0ba496ebb2eeaba5546746b9c | 7bbfc283b74c64de3fc8bc440c63acdabe5b06c7 | refs/heads/master | 2022-06-14T17:34:15.323609 | 2022-06-03T08:05:40 | 2022-06-03T08:05:40 | 127,905,954 | 0 | 0 | NOASSERTION | 2020-06-23T08:46:49 | 2018-04-03T12:37:47 | C++ | UTF-8 | C++ | false | false | 1,139 | h | #ifndef BOOSTER_SMART_PTR_DETAIL_SP_CONVERTIBLE_HPP_INCLUDED
#define BOOSTER_SMART_PTR_DETAIL_SP_CONVERTIBLE_HPP_INCLUDED
// detail/sp_convertible.hpp
//
// Copyright 2008 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <booster/config.h>
namespace booster
{
namespace detail
{
template< class Y, class T > struct sp_convertible
{
typedef char (&yes) [1];
typedef char (&no) [2];
static yes f( T* );
static no f( ... );
enum _vt { value = sizeof( f( static_cast<Y*>(0) ) ) == sizeof(yes) };
};
struct sp_empty
{
};
template< bool > struct sp_enable_if_convertible_impl;
template<> struct sp_enable_if_convertible_impl<true>
{
typedef sp_empty type;
};
template<> struct sp_enable_if_convertible_impl<false>
{
};
template< class Y, class T > struct sp_enable_if_convertible: public sp_enable_if_convertible_impl< sp_convertible< Y, T >::value >
{
};
} // namespace detail
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_DETAIL_SP_CONVERTIBLE_HPP_INCLUDED
| [
"[email protected]"
] | |
60cd114af69bf5325533090058fef6e687a7f96f | 884cd1c9f75678c1012f27accc51840def7fb704 | /Application/headers/bug.h | 88a2b304c6bcd36743ff92e4497dbf8852e2f386 | [] | no_license | NathanielSmithUOW/BugTracker | 67ed2a14a994aec91488aa999933115607487554 | e9876a0a2baa0578d10c1faa747a9bc67653704a | refs/heads/master | 2020-04-16T02:13:15.777296 | 2016-10-27T22:53:27 | 2016-10-27T22:53:27 | 66,034,607 | 0 | 2 | null | 2016-08-29T04:28:11 | 2016-08-18T22:25:07 | null | UTF-8 | C++ | false | false | 1,335 | h | #ifndef BUG_H
#define BUG_H
#include<QDate>
#include <QList>
class Bug
{
private:
int ID;
QString title;
QString status;
QString application;
double version;
QString description;
QString platform;
QString component;
QString priority;
QString severity;
QString walkthrough;
QString history;
QString assignedTo;
QString identifiedBy;
QDate submitted;
public:
Bug();
Bug(QString, QString, QString, double, QString, QString, QString,QString,QString, QString, QString, QString);
int getID();
QString getTitle();
QString getStatus();
QString getApplication();
double getVersion();
QString getDescription();
QString getPlatform();
QString getComponent();
QString getPriority();
QString getSeverity();
QString getWalkthrough();
QString getHistory();
QString getAssignedTo();
QString getIdentifiedBy();
QDate getSubmitted();
void setStatus(QString);
void setPriority(QString);
void setSeverity(QString);
void setAssignedTo(QString);
void setHistory(QString);
void setID(int);
void setSubmitted(QDate);
};
#endif // BUG_H
| [
"[email protected]"
] | |
26d2418d075ac61f2f149295ab1fb18531feac93 | 69280997e073b25702bacc2116556fca2558afbb | /palindrom_partition.cc | 4ebc330955b6c9c7721435bea19f1f2c096bd57f | [] | no_license | eyanshu1997/competitive | ac869d08f0763a3b3da684a501571326e3330eeb | 47572e96f54662918f6446c8d1f15aad3c0b8543 | refs/heads/master | 2021-04-17T21:49:06.726990 | 2020-05-17T10:23:28 | 2020-05-17T10:23:28 | 249,477,745 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,260 | cc | #include <bits/stdc++.h>
#define pp pair<ll,ll>
#define ll long long int
#define tr(a,x) for(auto a:x)
#define tri(a,x) for(auto a=x.begin();a!=x.end();a++)
#define all(x) x.begin(),x.end()
#define sz(x) (int)(x).size()
#define fo(i,x) for(int i=0;i<x;i++)
#define p_b(x,i) x.push_back(i)
#define printe(i) cout<<i<<" "
#define printed(x,i) cout<< x <<i<<"\n"
#define ip(s) vector <s>vec;for(int i=0;i<n;i++){s tmp;cin>>tmp;vec.push_back(tmp);}
#define op(s) for(auto i:s) cout<<i<<" ";cout<<"\n";
#define vi vector<ll>
#define vpp vector<pair<ll,ll>>
#define newl cout<<"\n"
using namespace std;
void rsolve(string str)
{
int n=sz(str);
vi dp(n,INT_MAX);
vector<vector<bool>> p(n,vector<bool>(n));
fo(i,n)
{
p[i][i]=true;
}
for(int cl=2;cl<=n;cl++)
for(int i=0;i<n-cl+1;i++)
{
int j=i+cl-1;
if(cl==2)
p[i][j]=(str[i] == str[j]);
else
p[i][j]=(str[i] == str[j])&&p[i+1][j-1];
}
fo(i,n)
if(p[0][i]==true)
dp[i]=0;
else
fo(j,i)
if(p[j+1][i]==true &&1+dp[j]<dp[i])
dp[i]=1+dp[j];
cout<<dp[n-1];
}
void solve()
{
string x;
cin>>x;
rsolve(x);
}
int main()
{
ios_base::sync_with_stdio(0);
int num;
cin>>num;
fo(i,num)
{
///cout << "Case #" << i+1<< ": ";
solve();
cout<<"\n";
}
}
| [
"[email protected]"
] | |
3d4b6a91bb5346f06da7ef562c4779f9a844cd58 | daa147315e99014eeb9dfa3dfa1409461b882dcb | /projects/simplepump/src/libs/ESPUpdateServer.h | 3ba1ccaaa39b41be95d4bbb4c7f493d35f16f666 | [] | no_license | mcxiaoke/micro-labs | 2bfcaf544879fad19cbe85de6a76ce947c2fdd16 | af883c294170f57ef2e6b7950b41c6c4fbfbc1f9 | refs/heads/master | 2021-01-01T06:32:13.098237 | 2019-11-04T13:53:41 | 2019-11-04T13:53:41 | 97,451,125 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | h | #ifndef __ESP_HTTP_UPDATE_SERVER_H__
#define __ESP_HTTP_UPDATE_SERVER_H__
#include "compat.h"
#if defined(ESP8266)
#define ESP_SERVER_CLASS ESP8266WebServer
#elif defined(ESP32)
#include <Update.h>
#define ESP_SERVER_CLASS WebServer
#endif
class ESP_SERVER_CLASS;
class ESPUpdateServer
{
public:
ESPUpdateServer(bool serial_debug=false);
void setup(ESP_SERVER_CLASS *server)
{
setup(server, emptyString, emptyString);
}
void setup(ESP_SERVER_CLASS *server, const String& path)
{
setup(server, path, emptyString, emptyString);
}
void setup(ESP_SERVER_CLASS *server, const String& username, const String& password)
{
setup(server, "/update", username, password);
}
void setup(ESP_SERVER_CLASS *server, const String& path, const String& username, const String& password);
void updateCredentials(const String& username, const String& password)
{
_username = username;
_password = password;
}
protected:
void _setUpdaterError();
private:
bool _serial_output;
ESP_SERVER_CLASS *_server;
String _username;
String _password;
bool _authenticated;
String _updaterError;
};
#endif
| [
"[email protected]"
] | |
0bd7f84627b7cfb47a079d9ecc71da7709c437c3 | 8566324b0a42dd56ef204ee1a02b8d701346793a | /src/messagehandler/NewUserNoticeHandler.h | b5736e82d3f49e86236958f19259573a16b61feb | [] | no_license | kppamy/Orca | b81c54c930722f664363c53f36a85e71704af80a | 416226cf9ca6a57c933ef8379bbf0e3ad405dd40 | refs/heads/master | 2021-05-29T04:15:00.438930 | 2015-07-16T04:56:45 | 2015-07-16T04:56:45 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 641 | h | ///////////////////////////////////////////////////////////
// NewUserNoticeHandler.h
// Implementation of the Class NewUserNoticeHandler
// Created on: 13-¾ÅÔÂ-2012 5:16:44
// Original author: kohachiro
///////////////////////////////////////////////////////////
#if !defined(EA_82228BDD_97B1_428c_BE59_08C6B4A3D1D3__INCLUDED_)
#define EA_82228BDD_97B1_428c_BE59_08C6B4A3D1D3__INCLUDED_
class NewUserNoticeHandler
{
public:
NewUserNoticeHandler();
virtual ~NewUserNoticeHandler();
static int invoke(Object data, Object channel) throw Exception;
};
#endif // !defined(EA_82228BDD_97B1_428c_BE59_08C6B4A3D1D3__INCLUDED_)
| [
"[email protected]"
] | |
246b727af7e6eed2b445ae1453a63bea78a820ed | e217eaf05d0dab8dd339032b6c58636841aa8815 | /IfcTunnel/src/OpenInfraPlatform/IfcTunnel/entity/include/IfcElementarySurface.h | 632cdd7ef50b0ba7d923b7e92922325b5646c345 | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | UTF-8 | C++ | false | false | 1,998 | h | /*! \verbatim
* \copyright Copyright (c) 2014 Julian Amann. All rights reserved.
* \date 2014-03-05 19:30
* \author Julian Amann <[email protected]> (https://www.cms.bgu.tum.de/en/team/amann)
* \brief This file is part of the BlueFramework.
* \endverbatim
*/
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "../../model/shared_ptr.h"
#include "../../model/IfcTunnelObject.h"
#include "IfcSurface.h"
namespace OpenInfraPlatform
{
namespace IfcTunnel
{
class IfcAxis2Placement3D;
//ENTITY
class IfcElementarySurface : public IfcSurface
{
public:
IfcElementarySurface();
IfcElementarySurface( int id );
~IfcElementarySurface();
// method setEntity takes over all attributes from another instance of the class
virtual void setEntity( shared_ptr<IfcTunnelEntity> other );
virtual void getStepLine( std::stringstream& stream ) const;
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
virtual void readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcTunnelEntity> >& map );
virtual void setInverseCounterparts( shared_ptr<IfcTunnelEntity> ptr_self );
virtual void unlinkSelf();
virtual const char* classname() const { return "IfcElementarySurface"; }
// IfcRepresentationItem -----------------------------------------------------------
// inverse attributes:
// std::vector<weak_ptr<IfcPresentationLayerAssignment> > m_LayerAssignment_inverse;
// std::vector<weak_ptr<IfcStyledItem> > m_StyledByItem_inverse;
// IfcGeometricRepresentationItem -----------------------------------------------------------
// IfcSurface -----------------------------------------------------------
// IfcElementarySurface -----------------------------------------------------------
// attributes:
shared_ptr<IfcAxis2Placement3D> m_Position;
};
} // end namespace IfcTunnel
} // end namespace OpenInfraPlatform
| [
"[email protected]"
] | |
b322b1e0019b9dfd1556e5c0aa33402477c4a53c | c4a224257c5c055a220949d4a9b880831cca4828 | /ep1/ep1_mac323_11221988/listaOrd.hpp | f8ec1eec649db64c0475d7043de643fb089e5a98 | [] | no_license | davimp/mac323 | 059f76c6f3ea32c09dabe42db6f9d35655c4409a | dedff806b88fa9cac867f00bc7a3f023385ae3a5 | refs/heads/master | 2022-10-01T01:08:41.075166 | 2020-06-08T23:46:07 | 2020-06-08T23:46:07 | 243,635,706 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,261 | hpp | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <time.h>
#ifndef LO_H
#define LO_H
/***************** Lista Ordenada **************************/
struct celulaOrd
{
std::string chave;
int valor;
struct celulaOrd * prox;
};
typedef struct celulaOrd CelulaOrd;
template<class Chave, class Item>
class listaOrd
{
private:
CelulaOrd * ini;
int n;
public:
listaOrd(std::string texto); /* construtor */
~listaOrd();/* destrutor */
void insere(Chave chave, Item valor);
Item devolve(Chave chave);/*devolve o valor*/
void remove(Chave chave);
int rank(Chave chave); /* é o "índice" da chave seguindo a ordenação */
Chave seleciona(int k); /* Para Você selecionar uma chave com rank k */
};
template <class Chave, class Item>
listaOrd<Chave, Item>::listaOrd(std::string texto)
{
std::fstream arquivo;
std::string str;
int aux = 0;
ini = new CelulaOrd;
ini->chave = "";
ini->valor = 0;
ini->prox = nullptr;
arquivo.open(texto);
if (arquivo.fail()) {
std::cout << "ERRO: arquivo" << texto << "nao pode ser aberto.\n";
exit(EXIT_FAILURE);
}
while(arquivo >> str){
aux = devolve(str);
insere(str, aux+1);
}
arquivo.close();
}
template<class Chave, class Item>
listaOrd<Chave, Item>::~listaOrd()
{
CelulaOrd * aux;
aux = ini->prox;
while(ini->prox != nullptr){
aux = ini->prox;
ini->prox = aux->prox;
delete aux;
}
delete ini;
}
template <class Chave, class Item>
void listaOrd<Chave, Item>::insere(Chave chave, Item valor)
{
CelulaOrd *i, * q;
i = ini;
q = ini;
while(i->prox != nullptr && i->prox->chave <= chave){
i = i->prox;
}
if(i->chave == chave){
i->valor = valor;
}
else{
q = new CelulaOrd;
q->chave = chave;
q->valor = valor;
q->prox = i->prox;
i->prox = q;
}
}
template<class Chave, class Item>
Item listaOrd<Chave, Item>::devolve(Chave chave)
{
CelulaOrd * i;
i = ini;
for(i = ini->prox; i != nullptr; i = i->prox)
{
if(i->chave >= chave)
break;
}
if(i == nullptr || i->chave != chave) return 0;
else return i->valor;
}
template<class Chave, class Item>
void listaOrd<Chave, Item>::remove(Chave chave)
{
CelulaOrd *i, *p;
p = ini;
i = ini->prox;
while(i->chave != chave && i->prox != nullptr){
i = i->prox;
p = p->prox;
}
if(i->chave == chave){
p->prox = i->prox;
delete i;
}
}
template<class Chave, class Item>
int listaOrd<Chave, Item>::rank(Chave chave)
{
CelulaOrd *i;
int ans;
ans = 0;
i = ini->prox;
while(i != nullptr){
if(i->chave < chave) ans++;
else break;
i = i->prox;
}
return ans;
}
template<class Chave, class Item>
Chave listaOrd<Chave, Item>::seleciona(int k)
{
CelulaOrd *i;
int r;
r = 0;
i = ini->prox;
while(i != nullptr){
if(r == k) break;
i = i->prox;
r++;
}
if(i != nullptr) return i->chave;
return "";
}
/*************************************************************************/
#endif | [
"[email protected]"
] | |
8cae6413ee1fd5e8aa19c53efb0f8c7834552597 | b074ab21a3e5e33c1f9e146b9befe11373360a10 | /engine/lib/ui/ImageView.cpp | 2f8333cd7431722f417850c9c9551eba938a5664 | [] | no_license | TakayukiHoshi1984/GCube | c731ac33ccd3fdaa5ccb78f68ff5fbeb33820d03 | a36d06b58dac447b70a81adee4e6b35295fe9508 | refs/heads/master | 2021-01-17T22:19:11.725534 | 2013-05-22T08:08:01 | 2013-05-22T08:08:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,629 | cpp | /*
* The MIT License (MIT)
* Copyright (c) 2011 GClue, inc.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* ImageView.cpp
*
* Created on: 2011/07/25
* Author: GClue, Inc.
*/
#include "ImageView.h"
#include "Animation.h"
#include "AnimationSet.h"
#include "Figure.h"
#include "Camera.h"
#include "SimpleShader.h"
#include "Texture.h"
ImageView::ImageView(GCContext *context) : View(context) {
figure = NULL;
clickable = false;
touchListener = NULL;
}
ImageView::~ImageView() {
}
void ImageView::setFigure(Figure *figure) {
this->figure = figure;
if (figure) {
size.x = figure->size.x / 2.0;
size.y = figure->size.y / 2.0;
}
}
void ImageView::draw(double dt, IAnimation *a) {
if (animation && !animation->isStarted()) {
return;
}
if (!figure) {
return;
}
//ブレンドタイプに合わせて合成を変える
//現在はImageViewにしかつけてません
switch(blendType) {
case BLEND_TYPE_ADD:
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
break;
case BLEND_TYPE_MULTIPLE:
glBlendFunc(GL_ZERO, GL_SRC_COLOR);
break;
case BLEND_TYPE_REVERSE:
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
break;
default:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
break;
}
float alpha = 1.0;
float bright = 1.0;
Matrix3D mtx;
testMatrix3D(&mtx, &alpha, &bright);
context->shader->setMVPMatrix(context->camera, &mtx);
context->shader->setAlpha(alpha);
context->shader->setBright(bright);
figure->bind();
figure->draw();
//最後にアルファ合成に戻す
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
| [
"[email protected]"
] | |
51cdad6ffd22c2f9f651d8bb1b8cca0ecf0606e6 | 0006f89c8d952bcf14a6150e9c26c94e47fab040 | /tool/PPMConverter/LinearRemap.h | ad0fd18b5ea81049076236be7f1b3b79d6ab4cff | [
"BSD-3-Clause"
] | permissive | cooperyuan/attila | eceb5d34b8c64c53ffcc52cd96b684d4f88b706f | 29a0ceab793b566c09cf81af26263e4855842c7a | refs/heads/master | 2016-09-05T18:55:56.472248 | 2013-06-29T14:42:02 | 2013-06-29T14:42:02 | 10,222,034 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | #ifndef LINEARREMAP_H
#define LINEARREMAP_H
#include "FragmentMapConverter.h"
class LinearRemap : public FragmentMapConverter
{
private:
// Only friend classes can create LinearRemap objects
LinearRemap();
LinearRemap(const LinearRemap&);
LinearRemap& operator=(const LinearRemap&);
public:
friend class FragmentMapConverterFactory;
PPMFile transform(const PPMFile& fragmentMap);
};
#endif // LINEARREMAP_H
| [
"[email protected]"
] | |
34e5575d16b4d790f05872dd25619e2e2f62cf65 | 5fa5e2ab9b7c7c287bb6e37ccdb296de462ef84c | /class_Spring_2019/hw7/quicksort3.cpp | 8aca69bbb0b61f2223cd4295794d76e692001a44 | [] | no_license | davidseungjin/CPP-DSA | fff67bb3803982ede02e18a0cd82db1c586f9837 | b2c80f5428d1d342fd18b1c9bc00b75dbb86e02d | refs/heads/master | 2021-07-17T15:18:25.897072 | 2020-06-18T05:59:41 | 2020-06-18T05:59:41 | 181,443,948 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,472 | cpp | #include<iostream>
#define MAX_SIZE 9
#define SWAP(x, y, temp)((temp)=(x), (x)=(y), (y)=(temp))
/*
* divide two sublist from pivot
* move everything less than pivot to left, grater than pivot to right
*/
int partition(int list[], int left, int right){
int pivot, temp;
int low, high;
low = left;
high = right + 1;
pivot = list[left]; // this mean pivot is far left index of the list
do{ // repeat until low and high intersect
do{ // if list[low] is less than pivot, increase low
low++; // low starts at left+1
}while(low <= right && list[low] < pivot);
do{ // if list[high] is greater than pivot, decrease high
high--; // high starts at right
}while(high >= left && list[high] > pivot);
if(low < high){ // exchange list[low] and list[high] unless these doesn't intersect
SWAP(list[low], list[high], temp);
}
}while(low< high);
// if low and high intersect, exit the loop above and exchange list[left] and list[high].
SWAP(list[left], list[high], temp);
// return the index of pivot, which is high
return high;
}
void quick_sort(int list[], int left, int right){
if(left<right){
int q = partition(list, left, right);
quick_sort(list, left, q-1);
quick_sort(list, q+1, right);
}
}
void show(int list[], int n){
for(int i=0; i<n; i++){
std::cout << list[i] << std::endl;
}
}
int main(){
int i;
int n = MAX_SIZE;
int list[n]={5,3,8,4,9,1,6,2,7};
quick_sort(list, 0, n-1);
show(list, n);
return 0;
}
| [
"[email protected]"
] | |
569a291cb0b923f63315cba396b7483322b29145 | 083100943aa21e05d2eb0ad745349331dd35239a | /aws-cpp-sdk-lambda/source/model/DeleteEventSourceMappingRequest.cpp | c382daff4c42218ea8a004388b8661df19b349a4 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bmildner/aws-sdk-cpp | d853faf39ab001b2878de57aa7ba132579d1dcd2 | 983be395fdff4ec944b3bcfcd6ead6b4510b2991 | refs/heads/master | 2021-01-15T16:52:31.496867 | 2015-09-10T06:57:18 | 2015-09-10T06:57:18 | 41,954,994 | 1 | 0 | null | 2015-09-05T08:57:22 | 2015-09-05T08:57:22 | null | UTF-8 | C++ | false | false | 995 | cpp | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/lambda/model/DeleteEventSourceMappingRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Lambda::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteEventSourceMappingRequest::DeleteEventSourceMappingRequest() :
m_uUIDHasBeenSet(false)
{
}
Aws::String DeleteEventSourceMappingRequest::SerializePayload() const
{
return "";
}
| [
"[email protected]"
] | |
1f4e3c310361fc3799b83f65a41e0b91b0b9f97e | 024d05e0d5254ac84ef788995fcadd58f795e63a | /stepper_2motions_switch/stepper_2motions_switch.ino | e12de13a5417cad09fa19ad373010c70423d81c2 | [] | no_license | deffer/arduino_stubs | a0f8ccf9a5e31fbdf7887716e0947661767b2551 | dd5bd32ec04102986eee8c9c21b434c44a96b6dd | refs/heads/master | 2020-12-24T06:23:51.576949 | 2016-07-31T04:48:16 | 2016-07-31T04:48:16 | 10,473,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,352 | ino | /**
* 1. Stepper motor bipolar
* 2. motor driver L293D
* 3. switch on-off-on to control the motor
* on (top) - start routine UP (turn clockwise that many times)
* off (middle) - stop any ongoing routine
* on (bottom) - start routine DOWN
* 4. reed switch - to detect the door is at the top (magnet is near the switch)
* LOW - switch is connected - magnet is near the switch - door at the at the top
*
* When switch 3 goes up or down (PIN_TOP or PIN_BOTTOP), a routine is started which will move stepper
* in a direction indicated by switch, which in turn moves the sliding door
* up or down. When door moves UP, additional check is performed
* - if reed switch (4) reads LOW (connected), the door is at the top and we need
* to stop the motor.
*/
#include <Stepper.h>
const int stepsPerRevolution = 200;
const int MAX_STEPS_UP = stepsPerRevolution * 5;
const int MAX_STEPS_DOWN = stepsPerRevolution * 5;
// initialize the stepper library on pins 8 through 11:
// 8 - IN1, 9 - IN2. other side: 10 - IN3, 11 - IN4
// wires of one coil are connected to same side of the driver
Stepper myStepper(stepsPerRevolution, 8,9,10,11);
// pins
int PIN_TOP = 0; // input pullup. LOW - door to go up
int PIN_BOTTOM= 2; // input pullup. LOW - door to go down
int PIN_END_OF_TRACK = 4; // input pullup. LOW - proximity sensor went off
int PIN_ENABLE = 6; // instatly stops or starts the motor
// constants: status of the switch, also routines
int DEF_UP = 1;
int DEF_OFF = 0;
int DEF_DOWN = 2;
// current and previous states
int prevState = DEF_OFF;
int currentRoutine = DEF_OFF; // reusing DEF_ constants for routine names
int routineStep = 0;
void setup() {
// Serial.begin(9600);
myStepper.setSpeed(30); // option 2
pinMode(PIN_TOP, INPUT_PULLUP);
pinMode(PIN_BOTTOM, INPUT_PULLUP);
pinMode(PIN_END_OF_TRACK, INPUT_PULLUP);
pinMode(PIN_ENABLE, OUTPUT);
digitalWrite(PIN_ENABLE, LOW);
}
void loop() {
// read command (from RF receiver or button) and if it has changed:
// compare with current routine:
// if different - do something (stop or start)
// otherwise continue what we were doing (routine) or not doing
int currentState = readSwitchStatus();
// if state changed
if (currentState != prevState){
prevState = currentState;
halt();
if (currentState == DEF_OFF)
return;
else
routine(currentState, true);
}else{
if (currentState != DEF_OFF && currentRoutine != DEF_OFF)
routine(currentRoutine, false);
}
}
void routine(int routineId, bool newCycle){
int maxSteps = routineId == DEF_UP? MAX_STEPS_UP : MAX_STEPS_DOWN;
if (currentRoutine != routineId)
currentRoutine = routineId;
if (routineId == DEF_UP && digitalRead(PIN_END_OF_TRACK)==LOW){
halt();
return;
}
if (newCycle)
digitalWrite(PIN_ENABLE, HIGH);
if (routineId == DEF_UP)
myStepper.step(1);
else
myStepper.step(-1);
routineStep++;
if (routineStep >= maxSteps)
halt();
}
int halt(){
digitalWrite(PIN_ENABLE, LOW);
currentRoutine=DEF_OFF;
routineStep = 0;
}
int readSwitchStatus(){
int val = digitalRead(PIN_TOP);
if (val == LOW){
return DEF_UP;
}
val = digitalRead(PIN_BOTTOM);
if (val == LOW){
return DEF_DOWN;
}
return DEF_OFF;
}
| [
"[email protected]"
] | |
d169960ae1d7c84c045294e34058387e8f699750 | a772c6fcd17f431607a58df7a6cd34873a7e5815 | /inc/halconInc_x64/halconcpp/HCalibData.h | 902d54ab35c2010174b7a5845c0f6241b667cd1a | [] | no_license | wanglvhh/VisionProject | 43624c8728b6ab3812a536d2a3927be5cd62393f | ce9a3d4b5342fa9b578073e69b28881d88a6da2f | refs/heads/master | 2023-07-19T08:09:42.545448 | 2021-09-10T01:30:05 | 2021-09-10T01:30:05 | 404,651,996 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,448 | h | /***********************************************************
* File generated by the HALCON-Compiler hcomp version 17.12
* Usage: Interface to C++
*
* Software by: MVTec Software GmbH, www.mvtec.com
***********************************************************/
#ifndef HCPP_HCALIBDATA
#define HCPP_HCALIBDATA
namespace HalconCpp
{
// Represents an instance of a camera calibration model.
class LIntExport HCalibData : public HToolBase
{
public:
// Create an uninitialized instance
HCalibData():HToolBase() {}
// Copy constructor
HCalibData(const HCalibData& source) : HToolBase(source) {}
// Create HCalibData from handle, taking ownership
explicit HCalibData(Hlong handle);
// Set new handle, taking ownership
void SetHandle(Hlong handle);
// Deep copy of all data represented by this object instance
HCalibData Clone() const;
/*****************************************************************************
* Operator-based class constructors
*****************************************************************************/
// read_calib_data: Restore a calibration data model from a file.
explicit HCalibData(const HString& FileName);
// read_calib_data: Restore a calibration data model from a file.
explicit HCalibData(const char* FileName);
// create_calib_data: Create a HALCON calibration data model.
explicit HCalibData(const HString& CalibSetup, Hlong NumCameras, Hlong NumCalibObjects);
// create_calib_data: Create a HALCON calibration data model.
explicit HCalibData(const char* CalibSetup, Hlong NumCameras, Hlong NumCalibObjects);
/***************************************************************************
* Operators *
***************************************************************************/
// Deserialize a serialized calibration data model.
void DeserializeCalibData(const HSerializedItem& SerializedItemHandle);
// Serialize a calibration data model.
HSerializedItem SerializeCalibData() const;
// Restore a calibration data model from a file.
void ReadCalibData(const HString& FileName);
// Restore a calibration data model from a file.
void ReadCalibData(const char* FileName);
// Store a calibration data model into a file.
void WriteCalibData(const HString& FileName) const;
// Store a calibration data model into a file.
void WriteCalibData(const char* FileName) const;
// Perform a hand-eye calibration.
HTuple CalibrateHandEye() const;
// Determine all camera parameters by a simultaneous minimization process.
double CalibrateCameras() const;
// Remove a data set from a calibration data model.
void RemoveCalibData(const HString& ItemType, const HTuple& ItemIdx) const;
// Remove a data set from a calibration data model.
void RemoveCalibData(const HString& ItemType, Hlong ItemIdx) const;
// Remove a data set from a calibration data model.
void RemoveCalibData(const char* ItemType, Hlong ItemIdx) const;
// Set data in a calibration data model.
void SetCalibData(const HString& ItemType, const HTuple& ItemIdx, const HString& DataName, const HTuple& DataValue) const;
// Set data in a calibration data model.
void SetCalibData(const HString& ItemType, Hlong ItemIdx, const HString& DataName, const HString& DataValue) const;
// Set data in a calibration data model.
void SetCalibData(const char* ItemType, Hlong ItemIdx, const char* DataName, const char* DataValue) const;
// Find the HALCON calibration plate and set the extracted points and contours in a calibration data model.
void FindCalibObject(const HImage& Image, Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx, const HTuple& GenParamName, const HTuple& GenParamValue) const;
// Remove observation data from a calibration data model.
void RemoveCalibDataObserv(Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx) const;
// Get contour-based observation data from a calibration data model.
HXLDCont GetCalibDataObservContours(const HString& ContourName, Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx) const;
// Get contour-based observation data from a calibration data model.
HXLDCont GetCalibDataObservContours(const char* ContourName, Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx) const;
// Get observed calibration object poses from a calibration data model.
HPose GetCalibDataObservPose(Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx) const;
// Set observed calibration object poses in a calibration data model.
void SetCalibDataObservPose(Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx, const HPose& ObjInCameraPose) const;
// Get point-based observation data from a calibration data model.
void GetCalibDataObservPoints(Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx, HTuple* Row, HTuple* Column, HTuple* Index, HTuple* Pose) const;
// Set point-based observation data in a calibration data model.
void SetCalibDataObservPoints(Hlong CameraIdx, Hlong CalibObjIdx, Hlong CalibObjPoseIdx, const HTuple& Row, const HTuple& Column, const HTuple& Index, const HTuple& Pose) const;
// Query information about the relations between cameras, calibration objects, and calibration object poses.
HTuple QueryCalibDataObservIndices(const HString& ItemType, Hlong ItemIdx, HTuple* Index2) const;
// Query information about the relations between cameras, calibration objects, and calibration object poses.
HTuple QueryCalibDataObservIndices(const char* ItemType, Hlong ItemIdx, HTuple* Index2) const;
// Query data stored or computed in a calibration data model.
HTuple GetCalibData(const HString& ItemType, const HTuple& ItemIdx, const HTuple& DataName) const;
// Query data stored or computed in a calibration data model.
HTuple GetCalibData(const HString& ItemType, Hlong ItemIdx, const HString& DataName) const;
// Query data stored or computed in a calibration data model.
HTuple GetCalibData(const char* ItemType, Hlong ItemIdx, const char* DataName) const;
// Define a calibration object in a calibration model.
void SetCalibDataCalibObject(Hlong CalibObjIdx, const HTuple& CalibObjDescr) const;
// Define a calibration object in a calibration model.
void SetCalibDataCalibObject(Hlong CalibObjIdx, double CalibObjDescr) const;
// Set type and initial parameters of a camera in a calibration data model.
void SetCalibDataCamParam(const HTuple& CameraIdx, const HTuple& CameraType, const HCamPar& CameraParam) const;
// Set type and initial parameters of a camera in a calibration data model.
void SetCalibDataCamParam(const HTuple& CameraIdx, const HString& CameraType, const HCamPar& CameraParam) const;
// Set type and initial parameters of a camera in a calibration data model.
void SetCalibDataCamParam(const HTuple& CameraIdx, const char* CameraType, const HCamPar& CameraParam) const;
// Create a HALCON calibration data model.
void CreateCalibData(const HString& CalibSetup, Hlong NumCameras, Hlong NumCalibObjects);
// Create a HALCON calibration data model.
void CreateCalibData(const char* CalibSetup, Hlong NumCameras, Hlong NumCalibObjects);
};
// forward declarations and types for internal array implementation
template<class T> class HSmartPtr;
template<class T> class HToolArrayRef;
typedef HToolArrayRef<HCalibData> HCalibDataArrayRef;
typedef HSmartPtr< HCalibDataArrayRef > HCalibDataArrayPtr;
// Represents multiple tool instances
class LIntExport HCalibDataArray : public HToolArray
{
public:
// Create empty array
HCalibDataArray();
// Create array from native array of tool instances
HCalibDataArray(HCalibData* classes, Hlong length);
// Copy constructor
HCalibDataArray(const HCalibDataArray &tool_array);
// Destructor
virtual ~HCalibDataArray();
// Assignment operator
HCalibDataArray &operator=(const HCalibDataArray &tool_array);
// Clears array and all tool instances
virtual void Clear();
// Get array of native tool instances
const HCalibData* Tools() const;
// Get number of tools
virtual Hlong Length() const;
// Create tool array from tuple of handles
virtual void SetFromTuple(const HTuple& handles);
// Get tuple of handles for tool array
virtual HTuple ConvertToTuple() const;
protected:
// Smart pointer to internal data container
HCalibDataArrayPtr *mArrayPtr;
};
}
#endif
| [
"[email protected]"
] | |
4d392008b6e5b614661420d6031bb25d01a40efd | 790d72eb1be8eb9618b6a4e7d1022a77032d2e6d | /devel/include/ar_track_alvar_msgs/AlvarMarkers.h | b7d7ee01fe36685e6c83baf6d65ab482ac7832a2 | [] | no_license | seroburomalinoviy/ardrone_moving_landing_platform | 3210cc6dfc667e9fec8a9ae1d571f00a1f75b786 | 138ac5730e6e15495669ca3cded2f73b319d22be | refs/heads/master | 2020-05-01T11:56:50.305781 | 2019-03-24T19:51:11 | 2019-03-24T19:51:11 | 177,455,441 | 0 | 0 | null | 2019-03-24T18:50:18 | 2019-03-24T18:50:18 | null | UTF-8 | C++ | false | false | 7,948 | h | // Generated by gencpp from file ar_track_alvar_msgs/AlvarMarkers.msg
// DO NOT EDIT!
#ifndef AR_TRACK_ALVAR_MSGS_MESSAGE_ALVARMARKERS_H
#define AR_TRACK_ALVAR_MSGS_MESSAGE_ALVARMARKERS_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <std_msgs/Header.h>
#include <ar_track_alvar_msgs/AlvarMarker.h>
namespace ar_track_alvar_msgs
{
template <class ContainerAllocator>
struct AlvarMarkers_
{
typedef AlvarMarkers_<ContainerAllocator> Type;
AlvarMarkers_()
: header()
, markers() {
}
AlvarMarkers_(const ContainerAllocator& _alloc)
: header(_alloc)
, markers(_alloc) {
(void)_alloc;
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef std::vector< ::ar_track_alvar_msgs::AlvarMarker_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::ar_track_alvar_msgs::AlvarMarker_<ContainerAllocator> >::other > _markers_type;
_markers_type markers;
typedef boost::shared_ptr< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> const> ConstPtr;
}; // struct AlvarMarkers_
typedef ::ar_track_alvar_msgs::AlvarMarkers_<std::allocator<void> > AlvarMarkers;
typedef boost::shared_ptr< ::ar_track_alvar_msgs::AlvarMarkers > AlvarMarkersPtr;
typedef boost::shared_ptr< ::ar_track_alvar_msgs::AlvarMarkers const> AlvarMarkersConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ar_track_alvar_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'ar_track_alvar_msgs': ['/home/hammerviking/robotic_software/ardrone_moving_landing_platform/src/camera/ar_track_alvar/ar_track_alvar_msgs/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
{
static const char* value()
{
return "943fe17bfb0b4ea7890368d0b25ad0ad";
}
static const char* value(const ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x943fe17bfb0b4ea7ULL;
static const uint64_t static_value2 = 0x890368d0b25ad0adULL;
};
template<class ContainerAllocator>
struct DataType< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
{
static const char* value()
{
return "ar_track_alvar_msgs/AlvarMarkers";
}
static const char* value(const ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
{
static const char* value()
{
return "Header header\n\
AlvarMarker[] markers\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: ar_track_alvar_msgs/AlvarMarker\n\
Header header\n\
uint32 id\n\
uint32 confidence\n\
geometry_msgs/PoseStamped pose\n\
\n\
\n\
================================================================================\n\
MSG: geometry_msgs/PoseStamped\n\
# A Pose with reference coordinate frame and timestamp\n\
Header header\n\
Pose pose\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Pose\n\
# A representation of pose in free space, composed of position and orientation. \n\
Point position\n\
Quaternion orientation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Point\n\
# This contains the position of a point in free space\n\
float64 x\n\
float64 y\n\
float64 z\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Quaternion\n\
# This represents an orientation in free space in quaternion form.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
float64 w\n\
";
}
static const char* value(const ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.markers);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct AlvarMarkers_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ar_track_alvar_msgs::AlvarMarkers_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "markers[]" << std::endl;
for (size_t i = 0; i < v.markers.size(); ++i)
{
s << indent << " markers[" << i << "]: ";
s << std::endl;
s << indent;
Printer< ::ar_track_alvar_msgs::AlvarMarker_<ContainerAllocator> >::stream(s, indent + " ", v.markers[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // AR_TRACK_ALVAR_MSGS_MESSAGE_ALVARMARKERS_H
| [
"[email protected]"
] | |
15c455fcc8e26ad82947826b28dd4a2fe650e106 | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-backup/source/model/CopyJobState.cpp | 41ac44904195ae604b11c952950be09b170a5e39 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 2,452 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/backup/model/CopyJobState.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace Backup
{
namespace Model
{
namespace CopyJobStateMapper
{
static const int CREATED_HASH = HashingUtils::HashString("CREATED");
static const int RUNNING_HASH = HashingUtils::HashString("RUNNING");
static const int COMPLETED_HASH = HashingUtils::HashString("COMPLETED");
static const int FAILED_HASH = HashingUtils::HashString("FAILED");
CopyJobState GetCopyJobStateForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == CREATED_HASH)
{
return CopyJobState::CREATED;
}
else if (hashCode == RUNNING_HASH)
{
return CopyJobState::RUNNING;
}
else if (hashCode == COMPLETED_HASH)
{
return CopyJobState::COMPLETED;
}
else if (hashCode == FAILED_HASH)
{
return CopyJobState::FAILED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<CopyJobState>(hashCode);
}
return CopyJobState::NOT_SET;
}
Aws::String GetNameForCopyJobState(CopyJobState enumValue)
{
switch(enumValue)
{
case CopyJobState::CREATED:
return "CREATED";
case CopyJobState::RUNNING:
return "RUNNING";
case CopyJobState::COMPLETED:
return "COMPLETED";
case CopyJobState::FAILED:
return "FAILED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace CopyJobStateMapper
} // namespace Model
} // namespace Backup
} // namespace Aws
| [
"[email protected]"
] | |
d8a0de17ee4fb865e5db95e74fee6522b28ced5b | 2defaf5d67e113c94f0a975d9dcbdd2ebcab5c30 | /libs/leetcode/LeetCode101/leetcode_101/chapter_11/48 旋转图像.cpp | 3217b7c0ad4935e73444d620c9b4bee706a7d398 | [
"Apache-2.0"
] | permissive | duanshuai123/MyApp_Framework | 58bfc824c759551b8f900a772b5370d02e64a507 | 048e78044e630d380e39ecab66ecdb02c7e8488b | refs/heads/master | 2022-11-23T21:07:18.695044 | 2022-11-21T00:33:15 | 2022-11-21T00:33:15 | 200,981,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 979 | cpp |
// 48. Rotate Image
class Solution {
public:
void rotateEdge(vector<vector<int> >& matrix, int k, int len) {
// assert(k < matrix.size() / 2);
// assert(len == matrix.size() - k * 2);
for (int l = 0; l < len - 1; l++) {
int tmp = matrix[k][k + l];
matrix[k][k + l] = matrix[k + len - 1 - l][k];
matrix[k + len - 1 - l][k] = matrix[k + len - 1][k + len - 1 - l];
matrix[k + len - 1][k + len - 1 - l] = matrix[k + l][k + len - 1];
matrix[k + l][k + len - 1] = tmp;
}
return;
}
void rotate(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) {
return;
}
int n = matrix.size();
// assert(matrix[0].size() == n);
for (int k = 0; k < (n / 2); k++) {
int len = n - k * 2;
rotateEdge(matrix, k, len);
}
return;
}
};
| [
"[email protected]"
] | |
827d868c1f131365c3b2741f1a3c6da5e7fbe1c2 | 0e1bbc7e3479cc3b2eb9ca97e27b381d85e55a78 | /homebrain/src/utils/Message/src/MessageHandler.h | 170da5e5f44810cfdc489caa7e00589dbf6909e3 | [] | no_license | qrsforever/homebrain | ad174657451b713a4492c7f91f19ad7455630eb3 | 506958353c0d5fba59d23ae656446d6b636c042b | refs/heads/master | 2020-04-25T08:42:33.001693 | 2019-10-09T05:32:01 | 2019-10-09T05:32:01 | 172,655,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,524 | h | /***************************************************************************
* MessageHandler.h - Message Handler Handler
*
* Created: 2018-06-01 10:12:50
*
* Copyright QRS
****************************************************************************/
#ifndef __MessageHandler_H__
#define __MessageHandler_H__
#include <stdint.h>
#include "Message.h"
#include "MessageQueue.h"
#include "MessageLooper.h"
/* Log Message Type */
#define MT_LOG 0
#define LOG_EVENT_FILE_CREATE 1
#define LOG_EVENT_FILE_READY 2
#define LOG_EVENT_FILE_UPLOAD 3
#ifdef USE_SHARED_PTR
#include <memory>
#endif
#ifdef __cplusplus
namespace UTILS {
class MessageHandler {
protected:
virtual void handleMessage(Message *msg) = 0;
public:
class Callback {
public: virtual ~Callback() {}
public: virtual bool handleMessage(Message *msg) = 0;
}; /* calss Callback */
virtual void dispatchMessage(Message *msg);
MessageHandler();
MessageHandler(MessageQueue *queue);
virtual ~MessageHandler();
Message *obtainMessage();
Message *obtainMessage(int what);
Message *obtainMessage(int what, int arg1, int arg2);
bool sendMessage(Message *msg);
bool sendEmptyMessage(int what);
bool sendEmptyMessageDelayed(int what, uint32_t delayMillis);
bool sendEmptyMessageAtTime(int what, uint32_t uptimeMillis);
bool sendMessageDelayed(Message *msg, uint32_t delayMillis);
bool sendMessageAtTime(Message *msg, uint32_t uptimeMillis);
bool sendMessageAtFrontOfQueue(Message *msg);
void removeMessages(int what);
void removeMessages(int what, int arg1, int arg2);
bool hasMessages(int what);
bool hasMessages(int what, int arg1, int arg2);
#ifdef USE_SHARED_PTR
Message *obtainMessage(int what, std::shared_ptr<Object> obj);
Message *obtainMessage(int what, int arg1, int arg2, std::shared_ptr<Object> obj);
void removeMessages(int what, std::shared_ptr<Object> obj);
void removeAllMessages(std::shared_ptr<Object> token);
bool hasMessages(int what, std::shared_ptr<Object> obj);
#else
Message *obtainMessage(int what, Object *obj);
Message *obtainMessage(int what, int arg1, int arg2, Object *obj);
void removeMessages(int what, Object *object);
void removeAllMessages(Object *token);
bool hasMessages(int what, Object *object);
#endif
MessageQueue *mQueue;
Callback *mCallback;
}; /* class MessageHandler */
} /* namespace UTILS */
#endif /* __cplusplus */
#endif /* _MessageHandler_H_ */
| [
"[email protected]"
] | |
518ba965ee84b0df4d661ea6d5ab384b3c53e4bb | d324d147e8c414de852b94119bdb130df64096b8 | /sb_jaus/JAUS++/src/cxutils/math/PIDController.cpp | 1b2c437492925173800e57e78a9ca56b3521d413 | [] | no_license | UBC-Snowbots/IGVC2015 | af6ca169e2e4e11b07fa8982d3e6e9ce41a49040 | 18d5274f9b65079ec176e951fdbc6292e1b535f8 | refs/heads/master | 2020-05-15T15:15:24.135949 | 2016-01-09T19:53:43 | 2016-01-09T19:53:43 | 24,005,303 | 1 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 9,874 | cpp | ////////////////////////////////////////////////////////////////////////////////////
///
/// \file PIDController.cpp
/// \brief Proportional, Integral, and Differential Controller class used to
/// create closed loop operations.
///
/// <br>Author(s): Daniel Barber
/// <br>Created: 9 May 2007
/// <br>Copyright (c) 2009
/// <br>Applied Cognition and Training in Immersive Virtual Environments
/// <br>(ACTIVE) Laboratory
/// <br>Institute for Simulation and Training (IST)
/// <br>University of Central Florida (UCF)
/// <br>All rights reserved.
/// <br>Email: [email protected]
/// <br>Web: http://active.ist.ucf.edu
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
/// * Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright
/// notice, this list of conditions and the following disclaimer in the
/// documentation and/or other materials provided with the distribution.
/// * Neither the name of the ACTIVE LAB, IST, UCF, 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 ACTIVE LAB''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 UCF 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 <limits.h>
#include "cxutils/Timer.h"
#include "cxutils/math/PIDController.h"
using namespace CxUtils;
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Constructor.
///
////////////////////////////////////////////////////////////////////////////////////
PIDController::PIDController()
{
Reset();
//Default DT if not set elsewhere
mDT = 1.0;
mTolerance = 0.0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Destructor.
///
////////////////////////////////////////////////////////////////////////////////////
PIDController::~PIDController()
{
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Set the update interval for PID constants
///
/// \param[in] dt Delta Time variable for PID calculations, default is 1.
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::SetRate(const double dt)
{
mDT = dt;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Uses error feedback to provide new input to the system.
///
/// This function performs the calculations of the PID controller. It checks
/// to make sure the returned value is within the bounds of the maximum and
/// minimum values your system can take. The upper and lower bounds can be
/// set using the setBounds function.
///
/// The error provided should be the error of your system between desired
/// and actual. This controller does not calculate error so that it can
/// be kept generic. The results of this function are only as good as
/// the PID gain values that model your system.
///
/// \param error The feedback error of the system.
///
/// \return The output to provide your system from the PID controller.
///
////////////////////////////////////////////////////////////////////////////////////
double PIDController::UpdatePID(const double error)
{
double solution;
double filteredError = error;
if(fabs(error) <= fabs(mTolerance))
{
filteredError = 0.0;
}
// Prevent over winding the sum of error. This basically
// means, if you are already giving the system 100%, you can't
// give it higher than that, so don't keep increasing
// the error
if(mPreviousSolution > mLowerBound && mPreviousSolution < mUpperBound)
{
this->mSumOfError += filteredError;
}
solution = mP*filteredError +
mI*mSumOfError*mDT +
mD*(filteredError - mPreviousError)/mDT;
mPreviousError = filteredError;
// Add any offset for the system
solution += this->mOffset;
// Check upper and lower bounds of solution for
// the system being used
if(solution <= mLowerBound)
solution = mLowerBound;
if(solution >= mUpperBound)
solution = mUpperBound;
this->mPreviousSolution = solution;
return solution;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets any desired offset for calculating solution from the PID.
///
/// For example, if the inputs you want to provide your system are between
/// [-100,100], then your offset would be 0, and you would have upper and
/// lower bounds of [-100,100]. If your system was [50, 150], you would have
/// an offset of 50, with upper and lower bounds of [50,150].
///
/// \param offset The offset to add to the PID solutions.
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::SetOffset(const double offset)
{
this->mOffset = offset;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets boundaries for the solutions the PID can calculate.
///
/// For example, if the inputs you want to provide your system are between
/// [-100,100], then your offset would be 0, and you would have upper and
/// lower bounds of [-100,100]. If your system was [50, 150], you would have
/// an offset of 50, with upper and lower bounds of [50,150].
///
/// \param min The lower bound of your system inputs
/// \param max The upper bound of your system inputs
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::SetBounds(const double min, const double max)
{
if(max > min)
{
this->mLowerBound = min;
this->mUpperBound = max;
}
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets the tolerance value for your error.
///
/// \param allowedError The allowed error for control.
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::SetTolerance(const double allowedError)
{
mTolerance = allowedError;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets the PID gain values of your controller.
///
/// By adjusting these values you can increase or decrease the performance
/// of the PID controller. You should have a limited understanding of
/// how to adjust these values before doing so.
///
/// \param p The proportional gain
/// \param i The integral gain
/// \param d The derivative gain
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::SetGains(const double p, const double i, const double d)
{
mP = p;
mI = i;
mD = d;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Clears out any summed error.
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::ClearError()
{
mSumOfError = 0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Sets all values back to defaults.
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::Reset()
{
mLowerBound = -LONG_MAX;
mUpperBound = LONG_MAX;
mP = 0;
mI = 0;
mD = 0;
mSumOfError = 0;
mPreviousSolution = 0;
mPreviousError = 0;
mOffset = 0;
}
////////////////////////////////////////////////////////////////////////////////////
///
/// \brief Resets the sum of errors, and configures the controller based on
/// the inputs.
///
/// \param lower Lower bound of system inputs
/// \param upper Upper bound of system inputs
/// \param offset Offset to add to system input solutions
/// \param p The proportional gain
/// \param i The integral gain
/// \param d The derivative gain
///
////////////////////////////////////////////////////////////////////////////////////
void PIDController::Reset(const double lower,
const double upper,
const double offset,
const double p,
const double i,
const double d)
{
SetBounds(lower, upper);
SetGains(p, i, d);
SetOffset(offset);
mSumOfError = 0;
mPreviousSolution = mOffset;
mPreviousError = 0;
}
/* End of File */
| [
"[email protected]"
] | |
6d920da97d9ae06b085eb94fca74a9e33166724b | 2bec5a52ce1fb3266e72f8fbeb5226b025584a16 | /fixest/inst/testfiles/cpp_tapply_vsum/cpp_tapply_vsum_DeepState_TestHarness.cpp | 927db8f8b453c3d3fa127c698b2723130fcd5c1c | [] | no_license | akhikolla/InformationHouse | 4e45b11df18dee47519e917fcf0a869a77661fce | c0daab1e3f2827fd08aa5c31127fadae3f001948 | refs/heads/master | 2023-02-12T19:00:20.752555 | 2020-12-31T20:59:23 | 2020-12-31T20:59:23 | 325,589,503 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,423 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// cpp_tapply_vsum_DeepState_TestHarness_generation.cpp and cpp_tapply_vsum_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
NumericVector cpp_tapply_vsum(int Q, NumericVector x, IntegerVector dum);
TEST(fixest_deepstate_test,cpp_tapply_vsum_test){
RInside R;
std::cout << "input starts" << std::endl;
IntegerVector Q(1);
Q[0] = RcppDeepState_int();
qs::c_qsave(Q,"/home/akhila/fuzzer_packages/fuzzedpackages/fixest/inst/testfiles/cpp_tapply_vsum/inputs/Q.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "Q values: "<< Q << std::endl;
NumericVector x = RcppDeepState_NumericVector();
qs::c_qsave(x,"/home/akhila/fuzzer_packages/fuzzedpackages/fixest/inst/testfiles/cpp_tapply_vsum/inputs/x.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "x values: "<< x << std::endl;
IntegerVector dum = RcppDeepState_IntegerVector();
qs::c_qsave(dum,"/home/akhila/fuzzer_packages/fuzzedpackages/fixest/inst/testfiles/cpp_tapply_vsum/inputs/dum.qs",
"high", "zstd", 1, 15, true, 1);
std::cout << "dum values: "<< dum << std::endl;
std::cout << "input ends" << std::endl;
try{
cpp_tapply_vsum(Q[0],x,dum);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"[email protected]"
] | |
157b1794cf0089a395be5b70f5b7f8ed5a5da242 | e8282e3ae8aafa07b7f7261c639f206c4e97e0fc | /02 - SMA/Latihan_OSN_2016/SPOJ/gshop.cpp | 759fc9fab6375fc72079584d2ae7dcc713dbfb77 | [] | no_license | irfansofyana/cp-codes | 7cad844da49b901ccf678b75c31ed41e2fa9d645 | 9fa723129088f0e4832ecb7e012fe586b6d59e41 | refs/heads/master | 2023-04-04T00:48:36.334817 | 2021-04-12T03:07:06 | 2021-04-12T03:07:06 | 218,084,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,119 | cpp | #include <bits/stdc++.h>
using namespace std;
int t,n,k;
vector<int> arr;
int i,j,x;
bool ganti;
vector<int> semua;
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> t;
while (t--) {
cin >> n >> k;
int ans = 0;
semua.clear();
for (i = 0 ; i < n ; i++) {
cin >> x;
semua.push_back(x);
if (x > 0) {
ans += x;
}
else arr.push_back(x);
}
int awal = k;
if (arr.size()!=0){
for (i = 0 ; i < arr.size() && k > 0; i++) {
arr[i] *= -1;
k--;
}
if (k == 0) {
for (i = 0 ; i < arr.size(); i++){
ans += arr[i];
}
}
else {
ans = 0;
for (i = 0 ; i < semua.size(); i++){
if (semua[i] <= 0) semua[i] *= -1;
ans += semua[i];
}
sort(semua.begin(),semua.end());
if (k%2 == 1) {
ans -= 2*semua[0];
}
}
}
else {
ans = 0;
sort(semua.begin(),semua.end());
for (i = 0 ; i < semua.size(); i++){
ans += semua[i];
}
if (awal % 2 == 1) {
ans -= 2*semua[0];
}
}
cout << ans << '\n';
arr.clear();
}
return 0;
} | [
"[email protected]"
] | |
b48abd90e4dcb5b67a9376e5f89a9a31325bdb24 | e3e3bf2a8cb16c8e87139237a7f03aa6807f7f2c | /io/src/writer/AbstractDataWriter.hpp | 6487c873b1b0970889bfffd72dea3e1cf6fb6913 | [
"BSD-3-Clause"
] | permissive | uofs-simlab/ChasteOS | f67b67f246befbc38edc3dc93b5e55a7bbf1fcfc | 04d98998e2ebad3f29086b8eaa1d89c08c6fccf6 | refs/heads/master | 2021-05-07T04:10:38.591384 | 2017-11-20T15:48:06 | 2017-11-20T15:48:06 | 111,127,403 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,547 | hpp | /*
Copyright (c) 2005-2016, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ABSTRACTDATAWRITER_HPP
#define ABSTRACTDATAWRITER_HPP
#include <string>
/**
* An abstract base class for data output.
* Loosely based on NetCDF api.
*/
class AbstractDataWriter
{
public:
/**
* Define the fixed dimension.
* This method must be overridden in concrete classes.
*
* @param rDimensionName The name of the dimension
* @param rDimensionUnits The physical units of the dimension
* @param dimensionSize The size of the dimension
*
* @return The identifier of the variable
*/
virtual int DefineFixedDimension(const std::string& rDimensionName,
const std::string& rDimensionUnits,
long dimensionSize)=0;
/**
* Define the unlimited dimension, i.e. the dimension that increases as the simulation progresses.
* This method must be overridden in concrete classes.
*
* @param rDimensionName The name of the unlimited dimension
* @param rDimensionUnits The physical units of the unlimited dimension
*
* @return The identifier of the variable
*/
virtual int DefineUnlimitedDimension(const std::string& rDimensionName,
const std::string& rDimensionUnits)=0;
/**
* Define a variable.
* This method must be overridden in concrete classes.
*
* @param rVariableName The name of the dimension
* @param rVariableUnits The physical units of the dimension
*
* @return The identifier of the variable
*/
virtual int DefineVariable(const std::string& rVariableName,
const std::string& rVariableUnits)=0;
/**
* End the define mode of the DataWriter.
* This method must be overridden in concrete classes.
*/
virtual void EndDefineMode()=0;
/**
* Dummy function for DoAdvanceAlongUnlimitedDimension.
* This method must be overridden in concrete classes.
*/
virtual void AdvanceAlongUnlimitedDimension()=0;
/**
* Input the variable value to the output file or ancillary file
* This method must be overridden in concrete classes.
*
* @param variableID
* @param variableValue
* @param dimensionPosition The position in column (defaults to -1). This is required if
* there is a fixed dimension, and will be the position along that dimension
*/
virtual void PutVariable(int variableID, double variableValue, long dimensionPosition=-1)=0;
/**
* Close any open files.
* This method must be overridden in concrete classes.
*/
virtual void Close()=0;
/**
* Base class with virtual methods needs a virtual destructor.
*/
virtual ~AbstractDataWriter()
{}
};
#endif //ABSTRACTDATAWRITER_HPP
| [
"[email protected]"
] | |
0d55acd98524b83f19a4ed4572e2276dd7abc986 | 6d254fef0e57cb82eb5a566cb9e81d749c2923bf | /src/SelectorWindow.cpp | b7771f0cf1cda957221e5661f59ee31b373336fa | [] | no_license | WalonLi/PictureDisplayer | 42eeee6ca267135e5cbc0812a48b6741ec7bbd39 | 585d6dc1d29eb0537445b0b45b15b557d304d371 | refs/heads/master | 2021-01-23T19:45:47.367447 | 2015-02-01T07:21:22 | 2015-02-01T07:21:22 | 28,432,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | /**
Provide by Walon Li, YJ Fang
File SelectorWindow.cpp
**/
#include <QDebug>
#include "include/SelectorWindow.h"
SelectorWindow::SelectorWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Selector)
{
this->setFixedSize(300, 100);
ui->setupUi(this);
}
SelectorWindow::~SelectorWindow()
{
delete ui;
}
void SelectorWindow::on_select_btn_clicked()
{
QString file_name ;
file_name = QFileDialog::getOpenFileName(this, "Choose your script file.") ;
qDebug() << file_name ;
}
void SelectorWindow::on_load_btn_clicked()
{
this->close() ;
}
| [
"[email protected]"
] | |
ef1cab9c6dac5cf0729085b3834d95d8fea496ea | f4395475af5bbc6ed17210008b9dcc46c6d6b10d | /src/wasm/wasm-objects.h | 169e752fa4bfd496161f49125e12f9a2fc083a2b | [
"BSD-3-Clause",
"bzip2-1.0.6",
"SunPro"
] | permissive | AlainRFP/v8 | aff652a851d58cd22b920d1549a61085df72607c | 134c67ef8abb2374488c71240347de58dadfe9e0 | refs/heads/master | 2020-04-10T05:58:47.671587 | 2018-12-07T13:33:57 | 2018-12-07T14:52:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,848 | h | // Copyright 2016 the V8 project authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_WASM_WASM_OBJECTS_H_
#define V8_WASM_WASM_OBJECTS_H_
#include "src/base/bits.h"
#include "src/debug/debug.h"
#include "src/debug/interface-types.h"
#include "src/heap/heap.h"
#include "src/objects.h"
#include "src/objects/script.h"
#include "src/signature.h"
#include "src/wasm/value-type.h"
// Has to be the last include (doesn't have include guards)
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
namespace wasm {
struct CompilationEnv;
class InterpretedFrame;
struct InterpretedFrameDeleter;
class NativeModule;
class SignatureMap;
class WasmCode;
struct WasmFeatures;
class WasmInterpreter;
struct WasmModule;
class WireBytesRef;
} // namespace wasm
class BreakPoint;
class JSArrayBuffer;
class SeqOneByteString;
class WasmDebugInfo;
class WasmInstanceObject;
class WasmModuleObject;
template <class CppType>
class Managed;
#define DECL_OPTIONAL_ACCESSORS(name, type) \
V8_INLINE bool has_##name(); \
DECL_ACCESSORS(name, type)
// TODO(3770): Replacement for the above, temporarily separate.
#define DECL_OPTIONAL_ACCESSORS2(name, type) \
V8_INLINE bool has_##name(); \
DECL_ACCESSORS2(name, type)
// A helper for an entry in an indirect function table (IFT).
// The underlying storage in the instance is used by generated code to
// call functions indirectly at runtime.
// Each entry has the following fields:
// - object = target instance, if a WASM function, tuple if imported
// - sig_id = signature id of function
// - target = entrypoint to WASM code or import wrapper code
class IndirectFunctionTableEntry {
public:
inline IndirectFunctionTableEntry(Handle<WasmInstanceObject>, int index);
void clear();
void Set(int sig_id, Handle<WasmInstanceObject> target_instance,
int target_func_index);
Object* object_ref();
int sig_id();
Address target();
private:
Handle<WasmInstanceObject> const instance_;
int const index_;
};
// A helper for an entry for an imported function, indexed statically.
// The underlying storage in the instance is used by generated code to
// call imported functions at runtime.
// Each entry is either:
// - WASM to JS, which has fields
// - object = a Tuple2 of the importing instance and the callable
// - target = entrypoint to import wrapper code
// - WASM to WASM, which has fields
// - object = target instance
// - target = entrypoint for the function
class ImportedFunctionEntry {
public:
inline ImportedFunctionEntry(Handle<WasmInstanceObject>, int index);
// Initialize this entry as a WASM to JS call. This accepts the isolate as a
// parameter, since it must allocate a tuple.
void SetWasmToJs(Isolate*, Handle<JSReceiver> callable,
const wasm::WasmCode* wasm_to_js_wrapper);
// Initialize this entry as a WASM to WASM call.
void SetWasmToWasm(WasmInstanceObject* target_instance, Address call_target);
WasmInstanceObject* instance();
JSReceiver* callable();
Object* object_ref();
Address target();
private:
Handle<WasmInstanceObject> const instance_;
int const index_;
};
// Representation of a WebAssembly.Module JavaScript-level object.
class WasmModuleObject : public JSObject {
public:
DECL_CAST(WasmModuleObject)
DECL_ACCESSORS(managed_native_module, Managed<wasm::NativeModule>)
DECL_ACCESSORS2(export_wrappers, FixedArray)
DECL_ACCESSORS(script, Script)
DECL_ACCESSORS2(weak_instance_list, WeakArrayList)
DECL_OPTIONAL_ACCESSORS2(asm_js_offset_table, ByteArray)
DECL_OPTIONAL_ACCESSORS2(breakpoint_infos, FixedArray)
inline wasm::NativeModule* native_module() const;
inline const wasm::WasmModule* module() const;
inline void reset_breakpoint_infos();
// Dispatched behavior.
DECL_PRINTER(WasmModuleObject)
DECL_VERIFIER(WasmModuleObject)
// Layout description.
#define WASM_MODULE_OBJECT_FIELDS(V) \
V(kNativeModuleOffset, kPointerSize) \
V(kExportWrappersOffset, kPointerSize) \
V(kScriptOffset, kPointerSize) \
V(kWeakInstanceListOffset, kPointerSize) \
V(kAsmJsOffsetTableOffset, kPointerSize) \
V(kBreakPointInfosOffset, kPointerSize) \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize,
WASM_MODULE_OBJECT_FIELDS)
#undef WASM_MODULE_OBJECT_FIELDS
// Creates a new {WasmModuleObject} with a new {NativeModule} underneath.
static Handle<WasmModuleObject> New(
Isolate* isolate, const wasm::WasmFeatures& enabled,
std::shared_ptr<const wasm::WasmModule> module,
OwnedVector<const uint8_t> wire_bytes, Handle<Script> script,
Handle<ByteArray> asm_js_offset_table);
// Creates a new {WasmModuleObject} for an existing {NativeModule} that is
// reference counted and might be shared between multiple Isolates.
static Handle<WasmModuleObject> New(
Isolate* isolate, std::shared_ptr<wasm::NativeModule> native_module,
Handle<Script> script, size_t code_size_estimate);
static Handle<WasmModuleObject> New(
Isolate* isolate, std::shared_ptr<wasm::NativeModule> native_module,
Handle<Script> script, Handle<FixedArray> export_wrappers,
size_t code_size_estimate);
// Set a breakpoint on the given byte position inside the given module.
// This will affect all live and future instances of the module.
// The passed position might be modified to point to the next breakable
// location inside the same function.
// If it points outside a function, or behind the last breakable location,
// this function returns false and does not set any breakpoint.
static bool SetBreakPoint(Handle<WasmModuleObject>, int* position,
Handle<BreakPoint> break_point);
// Check whether this module was generated from asm.js source.
inline bool is_asm_js();
static void AddBreakpoint(Handle<WasmModuleObject>, int position,
Handle<BreakPoint> break_point);
static void SetBreakpointsOnNewInstance(Handle<WasmModuleObject>,
Handle<WasmInstanceObject>);
// Get the module name, if set. Returns an empty handle otherwise.
static MaybeHandle<String> GetModuleNameOrNull(Isolate*,
Handle<WasmModuleObject>);
// Get the function name of the function identified by the given index.
// Returns a null handle if the function is unnamed or the name is not a valid
// UTF-8 string.
static MaybeHandle<String> GetFunctionNameOrNull(Isolate*,
Handle<WasmModuleObject>,
uint32_t func_index);
// Get the function name of the function identified by the given index.
// Returns "wasm-function[func_index]" if the function is unnamed or the
// name is not a valid UTF-8 string.
static Handle<String> GetFunctionName(Isolate*, Handle<WasmModuleObject>,
uint32_t func_index);
// Get the raw bytes of the function name of the function identified by the
// given index.
// Meant to be used for debugging or frame printing.
// Does not allocate, hence gc-safe.
Vector<const uint8_t> GetRawFunctionName(uint32_t func_index);
// Return the byte offset of the function identified by the given index.
// The offset will be relative to the start of the module bytes.
// Returns -1 if the function index is invalid.
int GetFunctionOffset(uint32_t func_index);
// Returns the function containing the given byte offset.
// Returns -1 if the byte offset is not contained in any function of this
// module.
int GetContainingFunction(uint32_t byte_offset);
// Translate from byte offset in the module to function number and byte offset
// within that function, encoded as line and column in the position info.
// Returns true if the position is valid inside this module, false otherwise.
bool GetPositionInfo(uint32_t position, Script::PositionInfo* info);
// Get the source position from a given function index and byte offset,
// for either asm.js or pure WASM modules.
static int GetSourcePosition(Handle<WasmModuleObject>, uint32_t func_index,
uint32_t byte_offset,
bool is_at_number_conversion);
// Compute the disassembly of a wasm function.
// Returns the disassembly string and a list of <byte_offset, line, column>
// entries, mapping wasm byte offsets to line and column in the disassembly.
// The list is guaranteed to be ordered by the byte_offset.
// Returns an empty string and empty vector if the function index is invalid.
debug::WasmDisassembly DisassembleFunction(int func_index);
// Extract a portion of the wire bytes as UTF-8 string.
// Returns a null handle if the respective bytes do not form a valid UTF-8
// string.
static MaybeHandle<String> ExtractUtf8StringFromModuleBytes(
Isolate* isolate, Handle<WasmModuleObject>, wasm::WireBytesRef ref);
static MaybeHandle<String> ExtractUtf8StringFromModuleBytes(
Isolate* isolate, Vector<const uint8_t> wire_byte,
wasm::WireBytesRef ref);
// Get a list of all possible breakpoints within a given range of this module.
bool GetPossibleBreakpoints(const debug::Location& start,
const debug::Location& end,
std::vector<debug::BreakLocation>* locations);
// Return an empty handle if no breakpoint is hit at that location, or a
// FixedArray with all hit breakpoint objects.
static MaybeHandle<FixedArray> CheckBreakPoints(Isolate*,
Handle<WasmModuleObject>,
int position);
};
// Representation of a WebAssembly.Table JavaScript-level object.
class WasmTableObject : public JSObject {
public:
DECL_CAST(WasmTableObject)
DECL_ACCESSORS2(functions, FixedArray)
// TODO(titzer): introduce DECL_I64_ACCESSORS macro
DECL_ACCESSORS(maximum_length, Object)
DECL_ACCESSORS2(dispatch_tables, FixedArray)
// Layout description.
#define WASM_TABLE_OBJECT_FIELDS(V) \
V(kFunctionsOffset, kPointerSize) \
V(kMaximumLengthOffset, kPointerSize) \
V(kDispatchTablesOffset, kPointerSize) \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize, WASM_TABLE_OBJECT_FIELDS)
#undef WASM_TABLE_OBJECT_FIELDS
inline uint32_t current_length();
void Grow(Isolate* isolate, uint32_t count);
static Handle<WasmTableObject> New(Isolate* isolate, uint32_t initial,
int64_t maximum,
Handle<FixedArray>* js_functions);
static void AddDispatchTable(Isolate* isolate, Handle<WasmTableObject> table,
Handle<WasmInstanceObject> instance,
int table_index);
static void Set(Isolate* isolate, Handle<WasmTableObject> table,
int32_t index, Handle<JSFunction> function);
static void UpdateDispatchTables(Isolate* isolate,
Handle<WasmTableObject> table,
int table_index, wasm::FunctionSig* sig,
Handle<WasmInstanceObject> target_instance,
int target_func_index);
static void ClearDispatchTables(Isolate* isolate,
Handle<WasmTableObject> table, int index);
};
// Representation of a WebAssembly.Memory JavaScript-level object.
class WasmMemoryObject : public JSObject {
public:
DECL_CAST(WasmMemoryObject)
DECL_ACCESSORS(array_buffer, JSArrayBuffer)
DECL_INT_ACCESSORS(maximum_pages)
DECL_OPTIONAL_ACCESSORS2(instances, WeakArrayList)
// Layout description.
#define WASM_MEMORY_OBJECT_FIELDS(V) \
V(kArrayBufferOffset, kPointerSize) \
V(kMaximumPagesOffset, kPointerSize) \
V(kInstancesOffset, kPointerSize) \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize,
WASM_MEMORY_OBJECT_FIELDS)
#undef WASM_MEMORY_OBJECT_FIELDS
// Add an instance to the internal (weak) list.
static void AddInstance(Isolate* isolate, Handle<WasmMemoryObject> memory,
Handle<WasmInstanceObject> object);
inline bool has_maximum_pages();
// Return whether the underlying backing store has guard regions large enough
// to be used with trap handlers.
bool has_full_guard_region(Isolate* isolate);
V8_EXPORT_PRIVATE static Handle<WasmMemoryObject> New(
Isolate* isolate, MaybeHandle<JSArrayBuffer> buffer, int32_t maximum);
static int32_t Grow(Isolate*, Handle<WasmMemoryObject>, uint32_t pages);
};
// Representation of a WebAssembly.Global JavaScript-level object.
class WasmGlobalObject : public JSObject {
public:
DECL_CAST(WasmGlobalObject)
DECL_ACCESSORS(array_buffer, JSArrayBuffer)
DECL_INT32_ACCESSORS(offset)
DECL_INT_ACCESSORS(flags)
DECL_PRIMITIVE_ACCESSORS(type, wasm::ValueType)
DECL_BOOLEAN_ACCESSORS(is_mutable)
#define WASM_GLOBAL_OBJECT_FLAGS_BIT_FIELDS(V, _) \
V(TypeBits, wasm::ValueType, 8, _) \
V(IsMutableBit, bool, 1, _)
DEFINE_BIT_FIELDS(WASM_GLOBAL_OBJECT_FLAGS_BIT_FIELDS)
#undef WASM_GLOBAL_OBJECT_FLAGS_BIT_FIELDS
// Layout description.
#define WASM_GLOBAL_OBJECT_FIELDS(V) \
V(kArrayBufferOffset, kPointerSize) \
V(kOffsetOffset, kPointerSize) \
V(kFlagsOffset, kPointerSize) \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize,
WASM_GLOBAL_OBJECT_FIELDS)
#undef WASM_GLOBAL_OBJECT_FIELDS
V8_EXPORT_PRIVATE static MaybeHandle<WasmGlobalObject> New(
Isolate* isolate, MaybeHandle<JSArrayBuffer> buffer, wasm::ValueType type,
int32_t offset, bool is_mutable);
inline int type_size() const;
inline int32_t GetI32();
inline int64_t GetI64();
inline float GetF32();
inline double GetF64();
inline void SetI32(int32_t value);
inline void SetI64(int64_t value);
inline void SetF32(float value);
inline void SetF64(double value);
private:
// This function returns the address of the global's data in the
// JSArrayBuffer. This buffer may be allocated on-heap, in which case it may
// not have a fixed address.
inline Address address() const;
};
// Representation of a WebAssembly.Instance JavaScript-level object.
class WasmInstanceObject : public JSObject {
public:
DECL_CAST(WasmInstanceObject)
DECL_ACCESSORS(module_object, WasmModuleObject)
DECL_ACCESSORS(exports_object, JSObject)
DECL_ACCESSORS2(native_context, Context)
DECL_OPTIONAL_ACCESSORS(memory_object, WasmMemoryObject)
DECL_OPTIONAL_ACCESSORS(globals_buffer, JSArrayBuffer)
DECL_OPTIONAL_ACCESSORS2(imported_mutable_globals_buffers, FixedArray)
DECL_OPTIONAL_ACCESSORS(debug_info, WasmDebugInfo)
DECL_OPTIONAL_ACCESSORS(table_object, WasmTableObject)
DECL_ACCESSORS2(imported_function_refs, FixedArray)
DECL_OPTIONAL_ACCESSORS2(indirect_function_table_refs, FixedArray)
DECL_OPTIONAL_ACCESSORS(managed_native_allocations, Foreign)
DECL_OPTIONAL_ACCESSORS2(exceptions_table, FixedArray)
DECL_ACCESSORS(undefined_value, Oddball)
DECL_ACCESSORS(null_value, Oddball)
DECL_ACCESSORS2(centry_stub, Code)
DECL_PRIMITIVE_ACCESSORS(memory_start, byte*)
DECL_PRIMITIVE_ACCESSORS(memory_size, size_t)
DECL_PRIMITIVE_ACCESSORS(memory_mask, size_t)
DECL_PRIMITIVE_ACCESSORS(isolate_root, Address)
DECL_PRIMITIVE_ACCESSORS(stack_limit_address, Address)
DECL_PRIMITIVE_ACCESSORS(real_stack_limit_address, Address)
DECL_PRIMITIVE_ACCESSORS(imported_function_targets, Address*)
DECL_PRIMITIVE_ACCESSORS(globals_start, byte*)
DECL_PRIMITIVE_ACCESSORS(imported_mutable_globals, Address*)
DECL_PRIMITIVE_ACCESSORS(indirect_function_table_size, uint32_t)
DECL_PRIMITIVE_ACCESSORS(indirect_function_table_sig_ids, uint32_t*)
DECL_PRIMITIVE_ACCESSORS(indirect_function_table_targets, Address*)
DECL_PRIMITIVE_ACCESSORS(jump_table_start, Address)
// Dispatched behavior.
DECL_PRINTER(WasmInstanceObject)
DECL_VERIFIER(WasmInstanceObject)
// Layout description.
#define WASM_INSTANCE_OBJECT_FIELDS(V) \
V(kModuleObjectOffset, kPointerSize) \
V(kExportsObjectOffset, kPointerSize) \
V(kNativeContextOffset, kPointerSize) \
V(kMemoryObjectOffset, kPointerSize) \
V(kGlobalsBufferOffset, kPointerSize) \
V(kImportedMutableGlobalsBuffersOffset, kPointerSize) \
V(kDebugInfoOffset, kPointerSize) \
V(kTableObjectOffset, kPointerSize) \
V(kImportedFunctionRefsOffset, kPointerSize) \
V(kIndirectFunctionTableRefsOffset, kPointerSize) \
V(kManagedNativeAllocationsOffset, kPointerSize) \
V(kExceptionsTableOffset, kPointerSize) \
V(kUndefinedValueOffset, kPointerSize) \
V(kNullValueOffset, kPointerSize) \
V(kCEntryStubOffset, kPointerSize) \
V(kFirstUntaggedOffset, 0) /* marker */ \
V(kMemoryStartOffset, kPointerSize) /* untagged */ \
V(kMemorySizeOffset, kSizetSize) /* untagged */ \
V(kMemoryMaskOffset, kSizetSize) /* untagged */ \
V(kIsolateRootOffset, kPointerSize) /* untagged */ \
V(kStackLimitAddressOffset, kPointerSize) /* untagged */ \
V(kRealStackLimitAddressOffset, kPointerSize) /* untagged */ \
V(kImportedFunctionTargetsOffset, kPointerSize) /* untagged */ \
V(kGlobalsStartOffset, kPointerSize) /* untagged */ \
V(kImportedMutableGlobalsOffset, kPointerSize) /* untagged */ \
V(kIndirectFunctionTableSigIdsOffset, kPointerSize) /* untagged */ \
V(kIndirectFunctionTableTargetsOffset, kPointerSize) /* untagged */ \
V(kJumpTableStartOffset, kPointerSize) /* untagged */ \
V(kIndirectFunctionTableSizeOffset, kUInt32Size) /* untagged */ \
V(k64BitArchPaddingOffset, kPointerSize - kUInt32Size) /* padding */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize,
WASM_INSTANCE_OBJECT_FIELDS)
#undef WASM_INSTANCE_OBJECT_FIELDS
V8_EXPORT_PRIVATE const wasm::WasmModule* module();
static bool EnsureIndirectFunctionTableWithMinimumSize(
Handle<WasmInstanceObject> instance, uint32_t minimum_size);
bool has_indirect_function_table();
void SetRawMemory(byte* mem_start, size_t mem_size);
// Get the debug info associated with the given wasm object.
// If no debug info exists yet, it is created automatically.
static Handle<WasmDebugInfo> GetOrCreateDebugInfo(Handle<WasmInstanceObject>);
static Handle<WasmInstanceObject> New(Isolate*, Handle<WasmModuleObject>);
Address GetCallTarget(uint32_t func_index);
// Iterates all fields in the object except the untagged fields.
class BodyDescriptor;
};
// Representation of WebAssembly.Exception JavaScript-level object.
class WasmExceptionObject : public JSObject {
public:
DECL_CAST(WasmExceptionObject)
DECL_ACCESSORS2(serialized_signature, PodArray<wasm::ValueType>)
DECL_ACCESSORS(exception_tag, HeapObject)
// Layout description.
#define WASM_EXCEPTION_OBJECT_FIELDS(V) \
V(kSerializedSignatureOffset, kPointerSize) \
V(kExceptionTagOffset, kPointerSize) \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize,
WASM_EXCEPTION_OBJECT_FIELDS)
#undef WASM_EXCEPTION_OBJECT_FIELDS
// Checks whether the given {sig} has the same parameter types as the
// serialized signature stored within this exception object.
bool IsSignatureEqual(const wasm::FunctionSig* sig);
static Handle<WasmExceptionObject> New(Isolate* isolate,
const wasm::FunctionSig* sig,
Handle<HeapObject> exception_tag);
};
// A WASM function that is wrapped and exported to JavaScript.
class WasmExportedFunction : public JSFunction {
public:
WasmInstanceObject* instance();
V8_EXPORT_PRIVATE int function_index();
V8_EXPORT_PRIVATE static WasmExportedFunction* cast(Object* object);
static bool IsWasmExportedFunction(Object* object);
static Handle<WasmExportedFunction> New(Isolate* isolate,
Handle<WasmInstanceObject> instance,
MaybeHandle<String> maybe_name,
int func_index, int arity,
Handle<Code> export_wrapper);
Address GetWasmCallTarget();
wasm::FunctionSig* sig();
};
// Information for a WasmExportedFunction which is referenced as the function
// data of the SharedFunctionInfo underlying the function. For details please
// see the {SharedFunctionInfo::HasWasmExportedFunctionData} predicate.
class WasmExportedFunctionData : public Struct {
public:
DECL_ACCESSORS2(wrapper_code, Code);
DECL_ACCESSORS(instance, WasmInstanceObject)
DECL_INT_ACCESSORS(jump_table_offset);
DECL_INT_ACCESSORS(function_index);
DECL_CAST(WasmExportedFunctionData)
// Dispatched behavior.
DECL_PRINTER(WasmExportedFunctionData)
DECL_VERIFIER(WasmExportedFunctionData)
// Layout description.
#define WASM_EXPORTED_FUNCTION_DATA_FIELDS(V) \
V(kWrapperCodeOffset, kPointerSize) \
V(kInstanceOffset, kPointerSize) \
V(kJumpTableOffsetOffset, kPointerSize) /* Smi */ \
V(kFunctionIndexOffset, kPointerSize) /* Smi */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(HeapObject::kHeaderSize,
WASM_EXPORTED_FUNCTION_DATA_FIELDS)
#undef WASM_EXPORTED_FUNCTION_DATA_FIELDS
};
class WasmDebugInfo : public Struct, public NeverReadOnlySpaceObject {
public:
DECL_ACCESSORS(wasm_instance, WasmInstanceObject)
DECL_ACCESSORS(interpreter_handle, Object); // Foreign or undefined
DECL_ACCESSORS2(interpreted_functions, FixedArray);
DECL_OPTIONAL_ACCESSORS2(locals_names, FixedArray)
DECL_OPTIONAL_ACCESSORS2(c_wasm_entries, FixedArray)
DECL_OPTIONAL_ACCESSORS(c_wasm_entry_map, Managed<wasm::SignatureMap>)
DECL_CAST(WasmDebugInfo)
// Dispatched behavior.
DECL_PRINTER(WasmDebugInfo)
DECL_VERIFIER(WasmDebugInfo)
// Layout description.
#define WASM_DEBUG_INFO_FIELDS(V) \
V(kInstanceOffset, kPointerSize) \
V(kInterpreterHandleOffset, kPointerSize) \
V(kInterpretedFunctionsOffset, kPointerSize) \
V(kLocalsNamesOffset, kPointerSize) \
V(kCWasmEntriesOffset, kPointerSize) \
V(kCWasmEntryMapOffset, kPointerSize) \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(HeapObject::kHeaderSize, WASM_DEBUG_INFO_FIELDS)
#undef WASM_DEBUG_INFO_FIELDS
static Handle<WasmDebugInfo> New(Handle<WasmInstanceObject>);
// Setup a WasmDebugInfo with an existing WasmInstance struct.
// Returns a pointer to the interpreter instantiated inside this
// WasmDebugInfo.
// Use for testing only.
V8_EXPORT_PRIVATE static wasm::WasmInterpreter* SetupForTesting(
Handle<WasmInstanceObject>);
// Set a breakpoint in the given function at the given byte offset within that
// function. This will redirect all future calls to this function to the
// interpreter and will always pause at the given offset.
static void SetBreakpoint(Handle<WasmDebugInfo>, int func_index, int offset);
// Make a set of functions always execute in the interpreter without setting
// breakpoints.
static void RedirectToInterpreter(Handle<WasmDebugInfo>,
Vector<int> func_indexes);
void PrepareStep(StepAction);
// Execute the specified function in the interpreter. Read arguments from
// arg_buffer.
// The frame_pointer will be used to identify the new activation of the
// interpreter for unwinding and frame inspection.
// Returns true if exited regularly, false if a trap occurred. In the latter
// case, a pending exception will have been set on the isolate.
static bool RunInterpreter(Isolate* isolate, Handle<WasmDebugInfo>,
Address frame_pointer, int func_index,
Address arg_buffer);
// Get the stack of the wasm interpreter as pairs of <function index, byte
// offset>. The list is ordered bottom-to-top, i.e. caller before callee.
std::vector<std::pair<uint32_t, int>> GetInterpretedStack(
Address frame_pointer);
std::unique_ptr<wasm::InterpretedFrame, wasm::InterpretedFrameDeleter>
GetInterpretedFrame(Address frame_pointer, int frame_index);
// Unwind the interpreted stack belonging to the passed interpreter entry
// frame.
void Unwind(Address frame_pointer);
// Returns the number of calls / function frames executed in the interpreter.
uint64_t NumInterpretedCalls();
// Get scope details for a specific interpreted frame.
// This returns a JSArray of length two: One entry for the global scope, one
// for the local scope. Both elements are JSArrays of size
// ScopeIterator::kScopeDetailsSize and layout as described in debug-scopes.h.
// The global scope contains information about globals and the memory.
// The local scope contains information about parameters, locals, and stack
// values.
static Handle<JSObject> GetScopeDetails(Handle<WasmDebugInfo>,
Address frame_pointer,
int frame_index);
static Handle<JSObject> GetGlobalScopeObject(Handle<WasmDebugInfo>,
Address frame_pointer,
int frame_index);
static Handle<JSObject> GetLocalScopeObject(Handle<WasmDebugInfo>,
Address frame_pointer,
int frame_index);
static Handle<JSFunction> GetCWasmEntry(Handle<WasmDebugInfo>,
wasm::FunctionSig*);
};
// Tags provide an object identity for each exception defined in a wasm module
// header. They are referenced by the following fields:
// - {WasmExceptionObject::exception_tag} : The tag of the exception object.
// - {WasmInstanceObject::exceptions_table}: List of tags used by an instance.
class WasmExceptionTag : public Struct {
public:
static Handle<WasmExceptionTag> New(Isolate* isolate, int index);
// Note that this index is only useful for debugging purposes and it is not
// unique across modules. The GC however does not allow objects without at
// least one field, hence this also serves as a padding field for now.
DECL_INT_ACCESSORS(index);
DECL_CAST(WasmExceptionTag)
DECL_PRINTER(WasmExceptionTag)
DECL_VERIFIER(WasmExceptionTag)
// Layout description.
#define WASM_EXCEPTION_TAG_FIELDS(V) \
V(kIndexOffset, kPointerSize) \
/* Total size. */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(Struct::kHeaderSize, WASM_EXCEPTION_TAG_FIELDS)
#undef WASM_EXCEPTION_TAG_FIELDS
};
class AsmWasmData : public Struct {
public:
static Handle<AsmWasmData> New(
Isolate* isolate, std::shared_ptr<wasm::NativeModule> native_module,
Handle<FixedArray> export_wrappers, Handle<ByteArray> asm_js_offset_table,
Handle<HeapNumber> uses_bitset);
DECL_ACCESSORS(managed_native_module, Managed<wasm::NativeModule>)
DECL_ACCESSORS2(export_wrappers, FixedArray)
DECL_ACCESSORS2(asm_js_offset_table, ByteArray)
DECL_ACCESSORS(uses_bitset, HeapNumber)
DECL_CAST(AsmWasmData)
DECL_PRINTER(AsmWasmData)
DECL_VERIFIER(AsmWasmData)
// Layout description.
#define ASM_WASM_DATA_FIELDS(V) \
V(kManagedNativeModuleOffset, kPointerSize) \
V(kExportWrappersOffset, kPointerSize) \
V(kAsmJsOffsetTableOffset, kPointerSize) \
V(kUsesBitsetOffset, kPointerSize) \
/* Total size. */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(Struct::kHeaderSize, ASM_WASM_DATA_FIELDS)
#undef ASM_WASM_DATA_FIELDS
};
#undef DECL_OPTIONAL_ACCESSORS
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_WASM_WASM_OBJECTS_H_
| [
"[email protected]"
] | |
e5c328eacf04f02ad6b80cf8a3cfeadea0ce9a81 | a2973e7238e0dc8c7b70da7d92e3c5712af0f4ae | /connect4/MacGraphicsStarter/Circle.cpp | 04fc7e2f1a284d0b33f2300b5632f4bbb2a26f09 | [] | no_license | codybrowncit/C-plus-plus | 581487db5e3b35ee9388f1a110a40d27c38cf343 | 2cea4d315b96f0537a598e16fcbcb430e1bd47a4 | refs/heads/master | 2020-12-25T19:04:11.471095 | 2015-05-14T23:16:57 | 2015-05-14T23:16:57 | 31,285,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | //
// Circle.cpp
// MacGraphicsStarter
//
// Created by Cody Brown on 11/2/14.
//
//
#include "Circle.h"
#include <cmath>
Circle::Circle(double x1, double y1, double x2, double y2, double red, double green, double blue )
:Shape(red, green, blue)
{
points.push_back(x1);
points.push_back(y1);
points.push_back(x2);
points.push_back(y2);
Mid=1;
}
void Circle::draw()
{
double x1, x2, y1, y2, radius;
x1 = points[0];
y1 = points[1];
x2 = points[2];
y2 = points[3];
radius = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
glColor3d(Mred, Mgreen, Mblue);
glBegin(GL_POLYGON);
for(int i=0; i<32; i++)
{
double theta = (double)i/32.0 * 2.0 * 3.1415926;
double x = x1 + radius * cos(theta);
double y = y1 + radius * sin(theta);
glVertex2d(x, y);
}
glEnd();
}
| [
"[email protected]"
] | |
f124e64a6fc8cf8b8af14ff652214e1f4891ab65 | 6a1436c6c937348d1389877d37204f2cd14336ab | /c++/types/characters/special_characters_notations.cpp | f4b2ea8f06b2a2cf18b31fc8fc597c898242a0c4 | [] | no_license | katheroine/languagium | 45bdc9888ca20121b16c3d19f5e60d7524b11726 | d5ebfb4d8050e2a24bc4ca98be0edf7167e4bfee | refs/heads/main | 2023-09-01T21:21:44.848400 | 2023-08-23T12:09:18 | 2023-08-23T12:09:18 | 231,378,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | cpp | #include <iostream>
int main()
{
std::cout << "backspace \\b: " << '\b' << std::endl;
std::cout << "carriage return \\r: " << '\r' << std::endl;
std::cout << "new page \\f: " << '\f' << std::endl;
std::cout << "new line \\n: " << '\n' << std::endl;
std::cout << "horizontal tabulation \\t: " << '\t' << std::endl;
std::cout << "vertical tabulation \\v: " << '\v' << std::endl;
std::cout << "sound signal \\a: " << '\a' << std::endl;
}
| [
"[email protected]"
] | |
ea0d78a28a9cee3838f75c4e0f8dbd332452fdd0 | 8a7960fc8fd499ae29b6d8e2d65174ce8213d492 | /digital/libraries/MPU9250/MPU9250/QuaternionFilter.h | 87c7142c9b86cb943052206431788cd288585646 | [
"MIT"
] | permissive | lionzan/sextants | 7be58db53274565985c2b7dd9114a6a1414f0a66 | 1e30a1432815828c744be49fb05df01453d8a735 | refs/heads/master | 2020-04-21T04:04:22.586100 | 2019-10-29T19:50:07 | 2019-10-29T19:50:07 | 169,302,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,621 | h | #pragma once
#ifndef QUATERNIONFILTER_H
#define QUATERNIONFILTER_H
class QuaternionFilter
{
float GyroMeasError = PI * (40.0f / 180.0f); // gyroscope measurement error in rads/s (start at 40 deg/s)
float GyroMeasDrift = PI * (0.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
float beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta
float zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value
const float Kp = 2.0f * 5.0f; // these are the free parameters in the Mahony filter and fusion scheme, Kp for proportional feedback, Ki for integral
const float Ki = 0.0f;
float deltat = 0.0f, sum = 0.0f; // integration interval for both filter schemes
uint32_t lastUpdate = 0, firstUpdate = 0; // used to calculate integration interval
uint32_t Now = 0; // used to calculate integration interval
// for mahony only
float eInt[3] = {0.0f, 0.0f, 0.0f}; // vector to hold integral error for Mahony method
public:
void bind() {}
// MadgwickQuaternionUpdate
void update(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz, float* q)
{
// updateParams()
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, _2bx, _2bz;
float s1, s2, s3, s4;
float qDot1, qDot2, qDot3, qDot4;
// Auxiliary variables to avoid repeated arithmetic
float _2q1mx;
float _2q1my;
float _2q1mz;
float _2q2mx;
float _4bx;
float _4bz;
float _2q1 = 2.0f * q1;
float _2q2 = 2.0f * q2;
float _2q3 = 2.0f * q3;
float _2q4 = 2.0f * q4;
float _2q1q3 = 2.0f * q1 * q3;
float _2q3q4 = 2.0f * q3 * q4;
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
gx *= PI / 180.f;
gy *= PI / 180.f;
gz *= PI / 180.f;
// updateTime()
Now = micros();
deltat = ((Now - lastUpdate) / 1000000.0f); // set integration time by time elapsed since last filter update
lastUpdate = Now;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
_2q1mx = 2.0f * q1 * mx;
_2q1my = 2.0f * q1 * my;
_2q1mz = 2.0f * q1 * mz;
_2q2mx = 2.0f * q2 * mx;
hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;
hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;
_2bx = sqrtf(hx * hx + hy * hy);
_2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;
_4bx = 2.0f * _2bx;
_4bz = 2.0f * _2bz;
// Gradient decent algorithm corrective step
s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
norm = sqrtf(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step magnitude
norm = 1.0f/norm;
s1 *= norm;
s2 *= norm;
s3 *= norm;
s4 *= norm;
// Compute rate of change of quaternion
qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;
qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;
qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;
qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;
// Integrate to yield quaternion
q1 += qDot1 * deltat;
q2 += qDot2 * deltat;
q3 += qDot3 * deltat;
q4 += qDot4 * deltat;
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion
norm = 1.0f/norm;
q[0] = q1 * norm;
q[1] = q2 * norm;
q[2] = q3 * norm;
q[3] = q4 * norm;
}
// Similar to Madgwick scheme but uses proportional and integral filtering on the error between estimated reference vectors and
// measured ones.
// MahonyQuaternionUpdate
void MahonyQuaternionUpdate(float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz, float* q)
{
float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
float norm;
float hx, hy, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
float pa, pb, pc;
// Auxiliary variables to avoid repeated arithmetic
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
bx = sqrtf((hx * hx) + (hy * hy));
bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);
// Estimated direction of gravity and magnetic field
vx = 2.0f * (q2q4 - q1q3);
vy = 2.0f * (q1q2 + q3q4);
vz = q1q1 - q2q2 - q3q3 + q4q4;
wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);
// Error is cross product between estimated direction and measured direction of gravity
ex = (ay * vz - az * vy) + (my * wz - mz * wy);
ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
if (Ki > 0.0f)
{
eInt[0] += ex; // accumulate integral error
eInt[1] += ey;
eInt[2] += ez;
}
else
{
eInt[0] = 0.0f; // prevent integral wind up
eInt[1] = 0.0f;
eInt[2] = 0.0f;
}
// Apply feedback terms
gx = gx + Kp * ex + Ki * eInt[0];
gy = gy + Kp * ey + Ki * eInt[1];
gz = gz + Kp * ez + Ki * eInt[2];
// Integrate rate of change of quaternion
pa = q2;
pb = q3;
pc = q4;
q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * deltat);
q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * deltat);
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * deltat);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * deltat);
// Normalise quaternion
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
norm = 1.0f / norm;
q[0] = q1 * norm;
q[1] = q2 * norm;
q[2] = q3 * norm;
q[3] = q4 * norm;
}
};
#endif // QUATERNIONFILTER_H
| [
"[email protected]"
] | |
c242e12f1e1ad1284c10e2a2c9e18beaea0161c4 | 0bb4e59d0663af8fe26d4d56824182ec2fbbf005 | /include/bullet/parser/ast/type_expr.hpp | 151af4ed2f44c3009d50fa88e857fe49b1db4d06 | [] | no_license | seertaak/bt | fa75d1bc3f4c30f230de33396e5a6fb883542d00 | f2764132c19f24c1c7b979954ca08ea38ce028ef | refs/heads/master | 2020-04-04T17:30:41.529115 | 2020-03-19T07:35:51 | 2020-03-19T07:35:51 | 156,123,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | hpp | #pragma once
#include <iostream>
#include <boost/hana/all.hpp>
#include <bullet/parser/ast/data.hpp>
#include <bullet/parser/ast_fwd.hpp>
namespace bt { namespace parser { namespace syntax {
template <typename Attr>
struct type_expr_t {
BOOST_HANA_DEFINE_STRUCT(type_expr_t, (attr_node_t<Attr>, type));
auto operator<=>(const type_expr_t&) const = default;
};
template <typename Attr>
auto operator<<(std::ostream& os, const type_expr_t<Attr>& e) -> std::ostream& {
if (e.type.get())
os << e.type.get();
else
os << "IMPLDEF";
return os;
}
}}} // namespace bt::parser::syntax
| [
"[email protected]"
] | |
47b3229ef94938c3394afd50752d2adcfbfa1b47 | a7cd298752be739395738df24975d481d276a5b4 | /include/channel.h | 0eeca6c8d244acf92027f28611da7e757429f08f | [] | no_license | xanpeng/libgochannel | c45ca0dec8579876f238b556398508cccb3462aa | 6582ade8083e5f33525d0a70fa7e1f61fcead667 | refs/heads/master | 2020-05-02T10:08:05.597306 | 2014-08-05T14:07:24 | 2014-08-05T14:07:24 | 22,494,013 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 23,438 | h | // Copyright 2014, Alex Horn. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef CPP_CHANNEL_H
#define CPP_CHANNEL_H
#include <mutex>
#include <deque>
#include <vector>
#include <limits>
#include <random>
#include <memory>
#include <thread>
#include <cstddef>
#include <cassert>
#include <functional>
#include <type_traits>
#include <condition_variable>
namespace utils { namespace internal {
template<class T, class ...Args>
std::unique_ptr<T> make_unique(Args&& ...args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template<class T>
struct _is_exception_safe :
std::integral_constant<bool,
std::is_nothrow_copy_constructible<T>::value or
std::is_nothrow_move_constructible<T>::value>
{};
// Note that currently handshakes between send/receives inside selects
// have higher priority compared to sends/receives outside selects.
// TODO: investigate and ideally also discuss other scheduling algorithms
template<class T, std::size_t N>
class _channel {
static_assert(N < std::numeric_limits<std::size_t>::max(),
"N must be strictly less than the largest possible size_t value");
private:
std::mutex m_mutex;
std::condition_variable m_send_begin_cv;
std::condition_variable m_send_end_cv;
std::condition_variable m_recv_cv;
std::deque<std::pair<std::thread::id, T>> m_queue; // id: sender; FIFO order
bool m_is_send_done;
bool m_is_try_send_done;
bool m_is_recv_ready;
bool m_is_try_send_ready;
bool m_is_try_recv_ready;
bool is_full() const {
return m_queue.size() > N;
}
// Is nonblocking receive and nonblocking send ready for handshake?
bool is_try_ready() const {
return m_is_try_recv_ready && m_is_try_send_ready;
}
// Block calling thread until queue becomes nonempty. While waiting
// (i.e. queue is empty), give try_send() a chance to succeed.
//
// \pre: calling thread owns lock
// \post: queue is nonempty and calling thread still owns lock
void _pre_blocking_recv(std::unique_lock<std::mutex>& lock) {
m_is_recv_ready = true;
m_recv_cv.wait(lock, [this]{ return !m_queue.empty(); });
// TODO: support the case where both ends of a channel are inside a select
assert(!is_try_ready());
}
// Pop front of queue and unblock one _send() (if any)
//
// \pre: calling thread must own lock and queue is nonempty
// \post: calling thread doesn't own lock anymore, and protocol with
// try_send() and try_recv() is fulfilled
void _post_blocking_recv(std::unique_lock<std::mutex>& lock) {
// If queue is full, then there exists either a _send() waiting
// for m_send_end_cv, or try_send() has just enqueued an element.
//
// In general, the converse is false: if there exists a blocking send,
// then a nonblocking receive might have just dequeued an element,
// i.e. queue is not full.
assert(!is_full() || !m_is_send_done || !m_is_try_send_done);
// blocking and nonblocking send can never occur simultaneously
assert(m_is_try_send_done || m_is_send_done);
m_queue.pop_front();
// protocol with nonblocking calls
m_is_try_send_done = true;
m_is_recv_ready = false;
m_is_try_recv_ready = false;
m_is_try_send_ready = false;
// Consider two concurrent _send() calls denoted by s and s'.
//
// Suppose s is waiting to enqueue an element (i.e. m_send_begin_cv),
// whereas s' is waiting for an acknowledgment (i.e. m_send_end_cv)
// that its previously enqueued element has been dequeued. Since s'
// is waiting and the flag m_is_send_done is only modified by _send(),
// m_is_send_done is false. Hence, we notify m_send_end_cv. This
// causes s' to notify s, thereby allowing s to proceed if possible.
//
// Now suppose there is no such s' (say, due to the fact that the
// queue never became full). Then, m_is_send_done == true. Thus,
// m_send_begin_cv is notified and s proceeds if possible. Note
// that if we hadn't notified s this way, then it could deadlock
// in case that it waited on m_is_try_send_done to become true.
if (m_is_send_done) {
lock.unlock();
// nonblocking, see also note below about notifications
m_send_begin_cv.notify_one();
}
else
{
// unlock before notifying threads; otherwise, the
// notified thread would unnecessarily block again
lock.unlock();
// we rely on the following semantics of notify_one():
//
// if a notification n is issued to s (i.e. s is chosen from among
// a set of threads waiting on a condition variable associated with
// mutex m) but another thread t locks m before s wakes up (i.e. s
// has not owned yet m after n had been issued), then n is retried
// as soon as t unlocks m. The retries repeat until n arrives at s
// meaning that s actually owns m and checks its wait guard.
m_send_end_cv.notify_one();
}
}
template<class U>
void _send(U&&);
public:
// \pre: calling thread must own mutex()
// \post: calling thread doesn't own mutex() anymore
template<class U>
bool try_send(std::unique_lock<std::mutex>&, U&&);
// \pre: calling thread must own mutex()
// \post: calling thread doesn't own mutex() anymore
std::pair<bool, std::unique_ptr<T>> try_recv_ptr(std::unique_lock<std::mutex>&);
_channel(const _channel&) = delete;
// Propagates exceptions thrown by std::condition_variable constructor
_channel()
: m_mutex(),
m_send_begin_cv(),
m_send_end_cv(),
m_recv_cv(),
m_queue(),
m_is_send_done(true),
m_is_try_send_done(true),
m_is_recv_ready(false),
m_is_try_send_ready(false),
m_is_try_recv_ready(false) {}
// channel lock
std::mutex& mutex() {
return m_mutex;
}
// Propagates exceptions thrown by std::condition_variable::wait()
void send(const T& t) {
_send(t);
}
// Propagates exceptions thrown by std::condition_variable::wait()
void send(T&& t) {
_send(std::move(t));
}
// Propagates exceptions thrown by std::condition_variable::wait()
T recv();
// Propagates exceptions thrown by std::condition_variable::wait()
void recv(T&);
// Propagates exceptions thrown by std::condition_variable::wait()
std::unique_ptr<T> recv_ptr();
}; // class _channel
} // namespace internal
template<class T, std::size_t N> class ichannel;
template<class T, std::size_t N> class ochannel;
/// Go-style concurrency
/// Thread synchronization mechanism as in the Go language.
/// As in Go, cpp::channel<T, N> are first-class values.
///
/// Unlike Go, however, cpp::channels<T, N> cannot be nil
/// not closed. This simplifies the usage of the library.
///
/// The template arguments are as follows:
///
/// * T -- type of data to be communicated over channel
/// * N is zero -- synchronous channel
/// * N is positive -- asynchronous channel with queue size N
///
/// Note that cpp::channel<T, N>::recv() is only supported if T is
/// exception safe. This is automatically checked at compile time.
/// If T is not exception safe, use any of the other receive member
/// functions.
///
/// \see http://golang.org/ref/spec#Channel_types
/// \see http://golang.org/ref/spec#Send_statements
/// \see http://golang.org/ref/spec#Receive_operator
/// \see http://golang.org/doc/effective_go.html#chan_of_chan
template<class T, std::size_t N = 0>
class channel {
static_assert(N < std::numeric_limits<std::size_t>::max(),
"N must be strictly less than the largest possible size_t value");
private:
friend class ichannel<T, N>;
friend class ochannel<T, N>;
std::shared_ptr<internal::_channel<T, N>> m_channel_ptr;
public:
channel(const channel& other) noexcept
: m_channel_ptr(other.m_channel_ptr) {}
// Propagates exceptions thrown by std::condition_variable constructor
channel()
: m_channel_ptr(std::make_shared<internal::_channel<T, N>>()) {}
channel& operator=(const channel& other) noexcept {
m_channel_ptr = other.m_channel_ptr;
return *this;
}
bool operator==(const channel& other) const noexcept {
return m_channel_ptr == other.m_channel_ptr;
}
bool operator!=(const channel& other) const noexcept {
return m_channel_ptr != other.m_channel_ptr;
}
bool operator==(const ichannel<T, N>&) const noexcept;
bool operator!=(const ichannel<T, N>&) const noexcept;
bool operator==(const ochannel<T, N>&) const noexcept;
bool operator!=(const ochannel<T, N>&) const noexcept;
// Propagates exceptions thrown by std::condition_variable::wait()
void send(const T& t) {
m_channel_ptr->send(t);
}
// Propagates exceptions thrown by std::condition_variable::wait()
void send(T&& t) {
m_channel_ptr->send(std::move(t));
}
// Propagates exceptions thrown by std::condition_variable::wait()
T recv() {
static_assert(internal::_is_exception_safe<T>::value,
"Cannot guarantee exception safety, use another recv operator");
return m_channel_ptr->recv();
}
// Propagates exceptions thrown by std::condition_variable::wait()
std::unique_ptr<T> recv_ptr() {
return m_channel_ptr->recv_ptr();
}
// Propagates exceptions thrown by std::condition_variable::wait()
void recv(T& t) {
m_channel_ptr->recv(t);
}
}; // class channel
class select;
/// Can only be used to receive elements of type T
template<class T, std::size_t N = 0>
class ichannel {
private:
friend class select;
friend class channel<T, N>;
std::shared_ptr<internal::_channel<T, N>> m_channel_ptr;
public:
ichannel(const channel<T, N>& other) noexcept
: m_channel_ptr(other.m_channel_ptr) {}
ichannel(const ichannel& other) noexcept
: m_channel_ptr(other.m_channel_ptr) {}
ichannel(ichannel&& other) noexcept
: m_channel_ptr(std::move(other.m_channel_ptr)) {}
ichannel& operator=(const ichannel& other) noexcept {
m_channel_ptr = other.m_channel_ptr;
return *this;
}
bool operator==(const ichannel& other) const noexcept {
return m_channel_ptr == other.m_channel_ptr;
}
bool operator!=(const ichannel& other) const noexcept {
return m_channel_ptr != other.m_channel_ptr;
}
// Propagates exceptions thrown by std::condition_variable::wait()
T recv() {
static_assert(internal::_is_exception_safe<T>::value,
"Cannot guarantee exception safety, use another recv operator");
return m_channel_ptr->recv();
}
// Propagates exceptions thrown by std::condition_variable::wait()
void recv(T& t) {
m_channel_ptr->recv(t);
}
// Propagates exceptions thrown by std::condition_variable::wait()
std::unique_ptr<T> recv_ptr() {
return m_channel_ptr->recv_ptr();
}
}; // class ichannel
/// Can only be used to send elements of type T
template<class T, std::size_t N = 0>
class ochannel {
private:
friend class select;
friend class channel<T, N>;
std::shared_ptr<internal::_channel<T, N>> m_channel_ptr;
public:
ochannel(const channel<T, N>& other) noexcept
: m_channel_ptr(other.m_channel_ptr) {}
ochannel(const ochannel& other) noexcept
: m_channel_ptr(other.m_channel_ptr) {}
ochannel(ochannel&& other) noexcept
: m_channel_ptr(std::move(other.m_channel_ptr)) {}
ochannel& operator=(const ochannel& other) noexcept {
m_channel_ptr = other.m_channel_ptr;
return *this;
}
bool operator==(const ochannel& other) const noexcept {
return m_channel_ptr == other.m_channel_ptr;
}
bool operator!=(const ochannel& other) const noexcept {
return m_channel_ptr != other.m_channel_ptr;
}
// Propagates exceptions thrown by std::condition_variable::wait()
void send(const T& t) {
m_channel_ptr->send(t);
}
// Propagates exceptions thrown by std::condition_variable::wait()
void send(T&& t) {
m_channel_ptr->send(std::move(t));
}
}; // class ochannel
/// Go's select statement
/// \see http://golang.org/ref/spec#Select_statements
///
/// \warning select objects must not be shared between threads
///
// TODO: investigate and ideally discuss pseudo-random distribution
class select {
private:
template<class T, std::size_t N, class NullaryFunction>
class try_send_nullary {
private:
template<class U, class V = typename std::remove_reference<U>::type>
static bool _run(ochannel<V, N>& c, U&& u, NullaryFunction f) {
internal::_channel<V, N>& _c = *c.m_channel_ptr;
std::unique_lock<std::mutex> lock(_c.mutex(), std::defer_lock);
if (lock.try_lock() && _c.try_send(lock, std::forward<U>(u))) {
assert(!lock.owns_lock());
f();
return true;
}
return false;
}
public:
bool operator()(ochannel<T, N>& c, const T& t, NullaryFunction f) {
return _run(c, t, f);
}
bool operator()(ochannel<T, N>& c, T&& t, NullaryFunction f) {
return _run(c, std::move(t), f);
}
};
template<class T, std::size_t N, class NullaryFunction>
struct try_recv_nullary {
bool operator()(ichannel<T, N>& c, T& t, NullaryFunction f) {
internal::_channel<T, N>& _c = *c.m_channel_ptr;
std::unique_lock<std::mutex> lock(_c.mutex(), std::defer_lock);
if (lock.try_lock()) {
std::pair<bool, std::unique_ptr<T>> pair = _c.try_recv_ptr(lock);
if (pair.first) {
assert(!lock.owns_lock());
t = *pair.second;
f();
return true;
}
}
return false;
}
};
template<class T, std::size_t N, class UnaryFunction>
struct try_recv_unary {
bool operator()(ichannel<T, N>& c, UnaryFunction f) {
internal::_channel<T, N>& _c = *c.m_channel_ptr;
std::unique_lock<std::mutex> lock(_c.mutex(), std::defer_lock);
if (lock.try_lock()) {
std::pair<bool, std::unique_ptr<T>> pair = _c.try_recv_ptr(lock);
if (pair.first) {
assert(!lock.owns_lock());
f(std::move(*pair.second));
return true;
}
}
return false;
}
};
typedef std::function<bool()> try_function;
typedef std::vector<try_function> try_functions;
try_functions m_try_functions;
std::random_device random_device;
std::mt19937 random_gen;
public:
select()
: m_try_functions(),
random_device(),
random_gen(random_device()) {}
/* send cases */
template<class T, std::size_t N, class U = typename std::remove_reference<T>::type>
select& send_only(channel<U, N> c, T&& t) {
return send_only(ochannel<U, N>(c), std::forward<T>(t));
}
template<class T, std::size_t N, class U = typename std::remove_reference<T>::type>
select& send_only(ochannel<U, N> c, T&& t) {
return send(c, std::forward<T>(t), [](){ /* skip */ });
}
template<class T, std::size_t N, class NullaryFunction, class U = typename std::remove_reference<T>::type>
select& send(channel<U, N> c, T&& t, NullaryFunction f) {
return send(ochannel<U, N>(c), std::forward<T>(t), f);
}
template<class T, std::size_t N, class NullaryFunction, class U = typename std::remove_reference<T>::type>
select& send(ochannel<U, N> c, T&& t, NullaryFunction f) {
m_try_functions.push_back(std::bind(try_send_nullary<U, N, NullaryFunction>(), c, std::forward<T>(t), f));
return *this;
}
/* receive cases */
template<class T, std::size_t N>
select& recv_only(channel<T, N> c, T& t) {
return recv_only(ichannel<T, N>(c), t);
}
template<class T, std::size_t N>
select& recv_only(ichannel<T, N> c, T& t) {
return recv(c, t, [](){ /* skip */ });
}
template<class T, std::size_t N, class NullaryFunction>
select& recv(channel<T, N> c, T& t, NullaryFunction f) {
return recv(ichannel<T, N>(c), t, f);
}
template<class T, std::size_t N, class NullaryFunction>
select& recv(ichannel<T, N> c, T& t, NullaryFunction f) {
m_try_functions.push_back(std::bind(try_recv_nullary<T, N, NullaryFunction>(), c, std::ref(t), f));
return *this;
}
template<class T, std::size_t N, class UnaryFunction>
select& recv(channel<T, N> c, UnaryFunction f) {
return recv(ichannel<T, N>(c), f);
}
template<class T, std::size_t N, class UnaryFunction>
select& recv(ichannel<T, N> c, UnaryFunction f) {
m_try_functions.push_back(std::bind(try_recv_unary<T, N, UnaryFunction>(), c, f));
return *this;
}
/// Nonblocking like Go's select statement with default case
/// Returns true if and only if exactly one case succeeded
bool try_once() {
const try_functions::size_type n = m_try_functions.size(), i = random_gen();
for(try_functions::size_type j = 0; j < n; j++) {
if (m_try_functions.at((i + j) % n)())
return true;
}
return false;
}
void wait() {
const try_functions::size_type n = m_try_functions.size();
try_functions::size_type i = random_gen();
for(;;)
{
i = (i + 1) % n;
if (m_try_functions.at(i)())
break;
}
}
};
template<class T, std::size_t N>
bool channel<T, N>::operator==(const ichannel<T, N>& other) const noexcept {
return m_channel_ptr == other.m_channel_ptr;
}
template<class T, std::size_t N>
bool channel<T, N>::operator!=(const ichannel<T, N>& other) const noexcept {
return m_channel_ptr != other.m_channel_ptr;
}
template<class T, std::size_t N>
bool channel<T, N>::operator==(const ochannel<T, N>& other) const noexcept {
return m_channel_ptr == other.m_channel_ptr;
}
template<class T, std::size_t N>
bool channel<T, N>::operator!=(const ochannel<T, N>& other) const noexcept {
return m_channel_ptr != other.m_channel_ptr;
}
template<class T, std::size_t N>
template<class U>
bool internal::_channel<T, N>::try_send(std::unique_lock<std::mutex>& lock, U&& u) {
m_is_try_send_ready = true;
// TODO: support the case where both ends of a channel are inside a select
assert(!is_try_ready());
if ((!m_is_send_done || !m_is_try_send_done || is_full() || (0 == N - m_queue.size() && !m_is_recv_ready))) {
// TODO: investigate potential LLVM libc++ RAII unlocking issue
lock.unlock();
return false;
}
// if enqueue should block, there must be a receiver waiting
m_is_try_send_done = 0 < N - m_queue.size();
assert(m_is_try_send_done || m_is_recv_ready);
m_queue.emplace_back(std::this_thread::get_id(), std::forward<U>(u));
// Let v be the value enqueued by try_send(). If m_is_try_send_done
// is false, no other sender (whether blocking or not) can enqueue a
// value until a receiver has dequeued v, thereby ensuring the channel
// FIFO order when the queue is filled up by try_send(). Moreover, in
// that case, since m_is_try_send_done implies m_is_recv_ready, such a
// receiver is guaranteed to exist, and it will reset m_is_try_send_done
// to true so that other senders can make progress after v has been
// dequeued. And by notifying m_recv_cv, other receivers waiting for
// the queue to become nonempty can make progress as well.
lock.unlock();
m_recv_cv.notify_one();
return true;
}
template<class T, std::size_t N>
std::pair<bool, std::unique_ptr<T>> internal::_channel<T, N>::try_recv_ptr(std::unique_lock<std::mutex>& lock) {
m_is_try_recv_ready = true;
if (m_queue.empty())
return std::make_pair(false, std::unique_ptr<T>(nullptr));
// If queue is full, then there exists either a _send() waiting
// for m_send_end_cv, or try_send() has just enqueued an element.
//
// In general, the converse is false: if there exists a blocking send,
// then a nonblocking receive might have just dequeued an element,
// i.e. queue is not full.
assert(!is_full() || !m_is_send_done || !m_is_try_send_done);
// blocking and nonblocking send can never occur simultaneously
assert(m_is_try_send_done || m_is_send_done);
std::pair<std::thread::id, T> pair(std::move(m_queue.front()));
assert(!is_full() || std::this_thread::get_id() != pair.first);
// move/copy before pop_front() to ensure strong exception safety
std::unique_ptr<T> t_ptr(make_unique<T>(std::move(pair.second)));
m_queue.pop_front();
// protocol with nonblocking calls
m_is_try_send_done = true;
m_is_try_recv_ready = false;
m_is_try_send_ready = false;
// see also explanation in _channel::_post_blocking_recv()
if (m_is_send_done) {
lock.unlock();
m_send_begin_cv.notify_one();
}
else {
lock.unlock();
m_send_end_cv.notify_one();
}
return std::make_pair(true, std::move(t_ptr));
}
template<class T, std::size_t N>
template<class U>
void internal::_channel<T, N>::_send(U&& u) {
// unlock before notifying threads; otherwise, the notified thread would unnecessarily block again
{
// wait (if necessary) until queue is no longer full and any previous _send() has successfully enqueued element
std::unique_lock<std::mutex> lock(m_mutex);
m_send_begin_cv.wait(lock, [this]{ return m_is_send_done && m_is_try_send_done && !is_full(); });
// TODO: support the case where both ends of a channel are inside a select
assert(!is_try_ready());
m_queue.emplace_back(std::this_thread::get_id(), std::forward<U>(u));
m_is_send_done = false;
}
// nonblocking
m_recv_cv.notify_one();
// wait (if necessary) until u has been received by another thread
{
std::unique_lock<std::mutex> lock(m_mutex);
// It is enough to check !is_full() because m_is_send_done == false.
// Therefore, no other thread could have caused the queue to fill up
// during the brief time we didn't own the lock.
//
// Performance note: unblocks after at least N successful recv calls
m_send_end_cv.wait(lock, [this]{ return !is_full(); });
m_is_send_done = true;
}
// see also explanation in _channel<T, N>::recv()
m_send_begin_cv.notify_one();
}
template<class T, std::size_t N>
T internal::_channel<T, N>::recv() {
static_assert(internal::_is_exception_safe<T>::value,
"Cannot guarantee exception safety, use another recv operator");
std::unique_lock<std::mutex> lock(m_mutex);
_pre_blocking_recv(lock);
std::pair<std::thread::id, T> pair(std::move(m_queue.front()));
assert(!is_full() || std::this_thread::get_id() != pair.first);
_post_blocking_recv(lock);
return std::move(pair.second);
}
template<class T, std::size_t N>
void internal::_channel<T, N>::recv(T& t) {
std::unique_lock<std::mutex> lock(m_mutex);
_pre_blocking_recv(lock);
std::pair<std::thread::id, T> pair(std::move(m_queue.front()));
assert(!is_full() || std::this_thread::get_id() != pair.first);
// assignment before pop_front() to ensure strong exception safety
t = std::move(pair.second);
_post_blocking_recv(lock);
}
template<class T, std::size_t N>
std::unique_ptr<T> internal::_channel<T, N>::recv_ptr() {
std::unique_lock<std::mutex> lock(m_mutex);
_pre_blocking_recv(lock);
std::pair<std::thread::id, T> pair(std::move(m_queue.front()));
assert(!is_full() || std::this_thread::get_id() != pair.first);
// move/copy before pop_front() to ensure strong exception safety
std::unique_ptr<T> t_ptr(make_unique<T>(std::move(pair.second)));
_post_blocking_recv(lock);
return t_ptr;
}
class thread_guard {
private:
std::thread& thread_;
public:
explicit thread_guard(std::thread& thread)
: thread_(thread) {}
thread_guard(const thread_guard&) = delete;
thread_guard& operator=(const thread_guard&) = delete;
~thread_guard() {
if (thread_.joinable()) thread_.join();
}
};
} // namespace utils
#endif
| [
"[email protected]"
] | |
a9d45482581c85f10d11022b54a24a9a246e9e42 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/net/rras/cps/pbserver/pbserver.cpp | dfbd5aef330f14b397000622b894d903f35328e4 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 59,034 | cpp | /*----------------------------------------------------------------------------
pbserver.cpp
CPhoneBkServer class implementation
Copyright (c) 1997-1998 Microsoft Corporation
All rights reserved.
Authors:
byao Baogang Yao
History:
1/23/97 byao -- Created
5/29/97 t-geetat -- Modified -- added performance counters,
shared memory
5/02/00 sumitc -- removed db dependency
--------------------------------------------------------------------------*/
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <tchar.h>
#include <aclapi.h>
#include "common.h"
#include "pbserver.h"
#include "ntevents.h"
#include "cpsmon.h"
#include "shlobj.h"
#include "shfolder.h"
//
// Phone book "database" implementation
//
char g_szPBDataDir[2 * MAX_PATH] = "";
HRESULT GetPhoneBook(char * pszPBName,
int dLCID,
int dOSType,
int dOSArch,
int dPBVerCurrent,
char * pszDownloadPath);
extern "C"
{
#include "util.h"
}
const DWORD MAX_BUFFER_SIZE = 1024; // maximum size of input buffer
const DWORD SEND_BUFFER_SIZE = 4096; // block size when sending CAB file
const char achDefService[] = "Default"; //default service name
const int dDefPBVer = 0; // default phone book version number, this should be 0,
// however, since David's test data used 0, we used 0 too.
// SUBJECT TO CHANGE
#define MAX_PATH_LEN 256
// missing value -- if parameter-pair is empty, it is set to this value
const int MISSING_VALUE = -1;
// make this public so the thread can access it
unsigned char g_achDBDirectory[MAX_PATH_LEN+1]; // full path for all phone book files
// constant strings
unsigned char c_szChangeFileName[] = "newpb.txt"; // newpb.txt
unsigned char c_szDBName[] = "pbserver"; // "pbserver" -- data source name
// the following error status code/string is copied from ISAPI.CPP
// which is part of the MFC library source code
typedef struct _httpstatinfo {
DWORD dwCode;
LPCTSTR pstrString;
} HTTPStatusInfo;
//
// The following two structures are used in the SystemTimeToGMT function
//
static TCHAR * s_rgchDays[] =
{
TEXT("Sun"),
TEXT("Mon"),
TEXT("Tue"),
TEXT("Wed"),
TEXT("Thu"),
TEXT("Fri"),
TEXT("Sat")
};
static TCHAR * s_rgchMonths[] =
{
TEXT("Jan"),
TEXT("Feb"),
TEXT("Mar"),
TEXT("Apr"),
TEXT("May"),
TEXT("Jun"),
TEXT("Jul"),
TEXT("Aug"),
TEXT("Sep"),
TEXT("Oct"),
TEXT("Nov"),
TEXT("Dec")
};
static HTTPStatusInfo statusStrings[] =
{
{ HTTP_STATUS_OK, "OK" },
{ HTTP_STATUS_CREATED, "Created" },
{ HTTP_STATUS_ACCEPTED, "Accepted" },
{ HTTP_STATUS_NO_CONTENT, "No download Necessary" },
{ HTTP_STATUS_TEMP_REDIRECT, "Moved Temporarily" },
{ HTTP_STATUS_REDIRECT, "Moved Permanently" },
{ HTTP_STATUS_NOT_MODIFIED, "Not Modified" },
{ HTTP_STATUS_BAD_REQUEST, "Bad Request" },
{ HTTP_STATUS_AUTH_REQUIRED, "Unauthorized" },
{ HTTP_STATUS_FORBIDDEN, "Forbidden" },
{ HTTP_STATUS_NOT_FOUND, "Not Found" },
{ HTTP_STATUS_SERVER_ERROR, "Server error, type unknown" },
{ HTTP_STATUS_NOT_IMPLEMENTED, "Not Implemented" },
{ HTTP_STATUS_BAD_GATEWAY, "Bad Gateway" },
{ HTTP_STATUS_SERVICE_NA, "Cannot find service on server, bad request" },
{ 0, NULL }
};
// Server asynchronized I/O context
typedef struct _SERVER_CONTEXT
{
EXTENSION_CONTROL_BLOCK * pEcb;
HSE_TF_INFO hseTF;
TCHAR szBuffer[SEND_BUFFER_SIZE];
}
SERVERCONTEXT, *LPSERVERCONTEXT;
DWORD WINAPI MonitorDBFileChangeThread(LPVOID lpParam);
BOOL InitPBFilesPath();
//
// definition of global data
// All the following variable(object) can only have one instance
//
CPhoneBkServer * g_pPBServer; // Phone Book Server object
CNTEvent * g_pEventLog; // event log
CRITICAL_SECTION g_CriticalSection; // critical section
HANDLE g_hMonitorThread; // the monitor thread that checks the new file notification
HANDLE g_hProcessHeap; // handle of the global heap for the extension process;
BOOL g_fNewPhoneBook = FALSE; // whether there's a new phone book
BOOL g_fBeingShutDown = FALSE; // whether the system is being shut down
//
// Variables used in memory mapping
//
CCpsCounter *g_pCpsCounter = NULL; // Pointer to memory mapped object
HANDLE g_hSharedFileMapping = NULL; // Handle to the shared file mapping
HANDLE g_hSemaphore = NULL; // Handle to the semaphore for shared-file
////////////////////////////////////////////////////////////////////////
//
// Name: GetExtensionVersion
//
// Class: CPhoneBkServer
//
// Synopsis: implement the first DLL entry point function
//
//
// Return: TRUE succeed
// FALSE
//
// Parameters:
// pszVer[out] version information that needs to be filled out
//
BOOL CPhoneBkServer::GetExtensionVersion(LPHSE_VERSION_INFO pVer)
{
// Set version number
pVer -> dwExtensionVersion = MAKELONG(HSE_VERSION_MINOR,
HSE_VERSION_MAJOR);
// Load description string
lstrcpyn(pVer->lpszExtensionDesc,
"Connection Point Server Application",
HSE_MAX_EXT_DLL_NAME_LEN);
OutputDebugString("CPhoneBkServer.GetExtensionVersion() : succeeded \n");
return TRUE;
}
//////////////////////////////////////////////////////////////////////////////
//
// Name: GetParameterPairs
//
// Class: CPhoneBkServer
//
// Synopsis: Get the parameter-value pairs from an input string(from URL)
//
// Return: number of parameter pairs actually read
// a value of -1 stands for error --> INVALID_QUERY_STRING
//
// Parameter:
// pszInputString[in] Input string (null terminated)
// lpPairs[out] Pointer to the parameter/value pairs
// int dMaxPairs Maximum number of parameter pairs allowed
//
int CPhoneBkServer:: GetParameterPairs(char *pszInputString,
LPPARAMETER_PAIR lpPairs,
int dMaxPairs)
{
int i = 0;
if (NULL == pszInputString)
{
return INVALID_QUERY_STRING;
}
for(i = 0; pszInputString[0] != '\0' && i < dMaxPairs; i++)
{
// m_achVal == 'p=what%3F';
GetWord(lpPairs[i].m_achVal, pszInputString, '&', NAME_VALUE_LEN - 1);
// m_achVal == 'p=what?'
UnEscapeURL(lpPairs[i].m_achVal);
GetWord(lpPairs[i].m_achName,lpPairs[i].m_achVal,'=', NAME_VALUE_LEN - 1);
// m_achVal = what?
// m_achName = p
}
#ifdef _LOG_DEBUG_MESSAGE
char achMsg[64];
wsprintf(achMsg, "inside GetParameterPairs: dNumPairs : %d", i);
LogDebugMessage(achMsg);
if (pszInputString[0] != '\0')
LogDebugMessage("there are more parameters\n");
#endif
if (pszInputString[0] != '\0')
{
// more parameters available
return INVALID_QUERY_STRING;
}
else
{
//succeed
return i;
}
}
////////////////////////////////////////////////////////////////////////
//
// Name: GetQueryParameter
//
// Class: CPhoneBkServer
//
// Synopsis: scan through the query string, and get the value for all
// query parameters
//
// Return: TRUE all query parameters are correct
// FALSE invalid parameter existed
//
// Parameters:
// pszQuery[in] Query string from the client(URL encripted)
// pQueryParameter[out] pointer to the query parameters structure
//
//
BOOL CPhoneBkServer:: GetQueryParameter(char *pszQuery, LPQUERY_PARAMETER lpQueryParameter)
{
const int MAX_PARAMETER_NUM = 10;
PARAMETER_PAIR Pairs[MAX_PARAMETER_NUM]; // maximum 10 pairs -- just to be safe.
int dNumPairs, i;
#ifdef _LOG_DEBUG_MESSAGE
char achMsg[MAX_BUFFER_SIZE + 50];
if (0 < _snprintf(achMsg, MAX_BUFFER_SIZE + 50, "pszquery=%s", pszQuery))
{
LogDebugMessage(achMsg);
}
#endif
dNumPairs = GetParameterPairs(pszQuery, Pairs, MAX_PARAMETER_NUM);
#ifdef _LOG_DEBUG_MESSAGE
wsprintf(achMsg, "number of pairs : %d", dNumPairs);
LogDebugMessage(achMsg);
#endif
// initialize the parameter values
// check the validity of the parameter
m_QueryParameter.m_achPB[0]='\0'; // empty service name
m_QueryParameter.m_dPBVer = MISSING_VALUE; // empty pbversion
m_QueryParameter.m_dOSArch = MISSING_VALUE;
m_QueryParameter.m_dOSType = MISSING_VALUE;
m_QueryParameter.m_dLCID = MISSING_VALUE;
m_QueryParameter.m_achCMVer[0] = '\0';
m_QueryParameter.m_achOSVer[0] = '\0';
if (INVALID_QUERY_STRING == dNumPairs) // invalid number of parameters in query string
{
return FALSE;
}
for (i = 0; i < dNumPairs; i++)
{
_strlwr(Pairs[i].m_achName);
if (lstrcmpi(Pairs[i].m_achName, "osarch") == 0)
{
if (lstrlen(Pairs[i].m_achVal) == 0)
lpQueryParameter->m_dOSArch = MISSING_VALUE;
else
lpQueryParameter->m_dOSArch = atoi(Pairs[i].m_achVal);
}
else if (lstrcmpi(Pairs[i].m_achName, "ostype") == 0)
{
if (lstrlen(Pairs[i].m_achVal) == 0)
lpQueryParameter->m_dOSType = MISSING_VALUE;
else
lpQueryParameter->m_dOSType = atoi(Pairs[i].m_achVal);
}
else if (lstrcmpi(Pairs[i].m_achName,"lcid") == 0)
{
if (lstrlen(Pairs[i].m_achVal) == 0)
lpQueryParameter->m_dLCID = MISSING_VALUE;
else
lpQueryParameter->m_dLCID = atoi(Pairs[i].m_achVal);
}
else if (lstrcmpi(Pairs[i].m_achName,"osver") == 0)
{
lstrcpy(lpQueryParameter->m_achOSVer,Pairs[i].m_achVal);
}
else if (lstrcmpi(Pairs[i].m_achName,"cmver") == 0)
{
lstrcpy(lpQueryParameter->m_achCMVer, Pairs[i].m_achVal);
}
else if (lstrcmpi(Pairs[i].m_achName,"pb") == 0)
{
lstrcpy(lpQueryParameter->m_achPB,Pairs[i].m_achVal);
}
else if (lstrcmpi(Pairs[i].m_achName,"pbver") == 0)
{
if (lstrlen(Pairs[i].m_achVal) == 0)
lpQueryParameter->m_dPBVer = MISSING_VALUE;
else
lpQueryParameter->m_dPBVer = atoi(Pairs[i].m_achVal);
}
}
// LogDebug message:
#ifdef _LOG_DEBUG_MESSAGE
sprintf(achMsg, "osarch:%d", m_QueryParameter.m_dOSArch);
LogDebugMessage(achMsg);
sprintf(achMsg, "ostype:%d", m_QueryParameter.m_dOSType);
LogDebugMessage(achMsg);
sprintf(achMsg, "lcid:%d", m_QueryParameter.m_dLCID);
LogDebugMessage(achMsg);
sprintf(achMsg, "osver:%s ", m_QueryParameter.m_achOSVer);
LogDebugMessage(achMsg);
sprintf(achMsg, "cmver:%s", m_QueryParameter.m_achCMVer);
LogDebugMessage(achMsg);
sprintf(achMsg, "PB :%s ", m_QueryParameter.m_achPB);
LogDebugMessage(achMsg);
sprintf(achMsg, "PBVer:%d ", m_QueryParameter.m_dPBVer);
LogDebugMessage(achMsg);
#endif
return TRUE;
}
#if 0
/*
////////////////////////////////////////////////////////////////////////
//
// Name: FormSQLQuery
//
// Class: CPhoneBkServer
//
// Synopsis: Form a SQL query statement for ODBC database server
//
//
void CPhoneBkServer:: FormSQLQuery(char *pszQuery, char *pszService, int dLCID, int dOSType, int dOSArch)
{
char achTempStr[128];
lstrcpy(pszQuery,"Select Phonebooks.ISPid, Phonebooks.Version, Phonebooks.LCID");
lstrcat(pszQuery,", Phonebooks.OS, Phonebooks.Arch, Phonebooks.VirtualPath");
lstrcat(pszQuery," FROM ISPs, Phonebooks");
sprintf(achTempStr," WHERE (ISPs.Description Like '%s'", pszService);
lstrcat(pszQuery,achTempStr);
lstrcat(pszQuery," AND ISPs.ISPid = Phonebooks.ISPid)");
sprintf(achTempStr, " AND (Phonebooks.OS = %d)", dOSType);
lstrcat(pszQuery,achTempStr);
lstrcat(pszQuery," ORDER BY Phonebooks.Version DESC");
}
//----------------------------------------------------------------------------
//
// Function: Virtual2Physical()
//
// Class: CPhoneBkServer
//
// Synopsis: Convert a virtual path to a physical path
//
// Arguments: pEcb - ISAPI extension control block
// *pszFileName - the virtual path]
//
// Returns: TRUE: succeed; otherwise FALSE
//
// History: 05/30/96 VetriV Created
// 1/25/97 byao Modified to be used in the phone book
// server ISAPI
//----------------------------------------------------------------------------
BOOL CPhoneBkServer::Virtual2Physical(EXTENSION_CONTROL_BLOCK * pEcb,
char * pszVirtualPath,
char * pszPhysicalPath)
{
DWORD dw = MAX_PATH;
LPSTR lpsz;
char szLocalFile[MAX_PATH];
BOOL fRet;
// Is this a relative virtual path?
//
if (pszVirtualPath[0] != L'/' && pszVirtualPath[1] != L':')
{
// Base this path off of the path of our current script
fRet = pEcb->GetServerVariable(pEcb->ConnID, "PATH_INFO", szLocalFile, &dw);
if (FALSE == fRet)
{
return FALSE;
}
lpsz = _tcsrchr(szLocalFile, '/');
assert(lpsz != NULL);
if (!lpsz)
{
return FALSE;
}
*(++lpsz) = NULL;
dw = sizeof(szLocalFile) - PtrToLong((const void *)(lpsz - szLocalFile));
}
else
{
lstrcpy(szLocalFile, pszVirtualPath);
}
LogDebugMessage("within Virtual2Physical:");
LogDebugMessage(szLocalFile);
// Map this to a physical file name
dw = sizeof(szLocalFile);
fRet = (*pEcb->ServerSupportFunction)(pEcb->ConnID, HSE_REQ_MAP_URL_TO_PATH, szLocalFile, &dw, NULL);
if (FALSE == fRet)
{
return FALSE;
}
lstrcpy(pszPhysicalPath, szLocalFile);
return TRUE;
}
*/
#endif
//----------------------------------------------------------------------------
//
// Function: GetFileLength()
//
// Class: CPhoneBkServer
//
// Synopsis: Reads the pszFileName file and sends back the file size
//
// Arguments: lpszFileName - Contains the file name (with full path)]
//
// Returns: TRUE if succeed, otherwise FALSE;
//
// History: 03/07/97 byao Created
//
//----------------------------------------------------------------------------
DWORD CPhoneBkServer::GetFileLength(LPSTR lpszFileName)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
DWORD dwFileSize;
//
// Open file
//
hFile = CreateFile(lpszFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
return 0L;
//
// Get File Size
//
dwFileSize = GetFileSize(hFile, NULL);
CloseHandle(hFile);
if (-1 == dwFileSize)
{
dwFileSize = 0;
}
return dwFileSize;
}
//----------------------------------------------------------------------------
//
// Function: SystemTimeToGMT
//
// Synopsis: Converts the given system time to string representation
// containing GMT Formatted String
//
// Arguments: [st System time that needs to be converted *Reference*]
// [pstr pointer to string which will contain the GMT time
// on successful return]
// [cbBuff size of pszBuff in bytes]
//
// Returns: TRUE on success. FALSE on failure.
//
// History: 04/12/97 VetriV Created (from IIS source)
//
//----------------------------------------------------------------------------
BOOL SystemTimeToGMT(const SYSTEMTIME & st, LPSTR pszBuff, DWORD cbBuff)
{
if (!pszBuff || cbBuff < 40 )
{
return FALSE;
}
//
// Formats a string like: "Thu, 14 Jul 1994 15:26:05 GMT"
//
sprintf(pszBuff, "%s, %02d %s %d %02d:%02d:%0d GMT",
s_rgchDays[st.wDayOfWeek],
st.wDay,
s_rgchMonths[st.wMonth - 1],
st.wYear,
st.wHour,
st.wMinute,
st.wSecond);
return TRUE;
}
//----------------------------------------------------------------------------
//
// Function: FormHttpHeader
//
// Synopsis: Form's the IIS 3.0 HTTP Header
//
// Arguments: pszBuffer Buffer that will contain both the header and the
// status text
// pszResponse status text
// pszExtraHeader extra header information
//
// Returns: ERROR_SUCCESS on success. Error code on failure.
//
// History: 04/12/97 VetriV Created
// 05/22/97 byao Modified, to make it work with CPS server
//----------------------------------------------------------------------------
DWORD FormHttpHeader(LPSTR pszBuffer, LPSTR pszResponse, LPSTR pszExtraHeader)
{
// start with stand IIS header
wsprintf(pszBuffer,
"HTTP/1.0 %s\r\nServer: Microsoft-IIS/3.0\r\nDate: ",
pszResponse);
//
// Append the time
//
SYSTEMTIME SysTime;
TCHAR szTime[128];
GetSystemTime(&SysTime);
if (FALSE == SystemTimeToGMT(SysTime, szTime, 128))
{
//
// TODO: Error Handling
//
}
lstrcat(pszBuffer, szTime);
lstrcat(pszBuffer, "\r\n");
// Append extra header string
lstrcat(pszBuffer, pszExtraHeader);
return ERROR_SUCCESS;
}
//----------------------------------------------------------------------------
//
// Function: HseIoCompletion
//
// Synopsis: Callback routine that handles asynchronous WriteClient
// completion callback
//
// Arguments: [pECB - Extension Control Block]
// [pContext - Pointer to the AsyncWrite structure]
// [cbIO - Number of bytes written]
// [dwError - Error code if there was an error while writing]
//
// Returns: None
//
// History: 04/10/97 VetriV Created
// 05/22/97 byao Modified to make it work for CPS server
//
//----------------------------------------------------------------------------
VOID HseIoCompletion(EXTENSION_CONTROL_BLOCK * pEcb,
PVOID pContext,
DWORD cbIO,
DWORD dwError)
{
LPSERVERCONTEXT lpServerContext = (LPSERVERCONTEXT) pContext;
if (!lpServerContext)
{
return;
}
lpServerContext->pEcb->ServerSupportFunction(
lpServerContext->pEcb->ConnID,
HSE_REQ_DONE_WITH_SESSION,
NULL,
NULL,
NULL);
if (lpServerContext->hseTF.hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(lpServerContext->hseTF.hFile);
}
HeapFree(g_hProcessHeap, 0, lpServerContext);
SetLastError(dwError);
return;
}
////////////////////////////////////////////////////////////////////////
//
// Name: HttpExtensionProc
//
// Class: CPhoneBkServer
//
// Synopsis: implement the second DLL entry point function
//
// Return: HTTP status code
//
// Parameters:
// pEcb[in/out] - extension control block
//
// History: Modified byao 5/22/97
// new implementation: using asynchronized I/O
// Modified t-geetat : Added PerfMon counters
//
/////////////////////////////////////////////////////////////////////////
DWORD CPhoneBkServer:: HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK pEcb)
{
DWORD dwBufferLen = MAX_BUFFER_SIZE;
char achQuery[MAX_BUFFER_SIZE], achMsg[128];
char achPhysicalPath[MAX_PATH_LEN];
int dVersionDiff; // version difference between client & server's phone books
BOOL fRet;
DWORD dwStatusCode = NOERROR;
int dwRet;
DWORD dwCabFileSize;
BOOL fHasContent = FALSE;
CHAR szResponse[64];
char achExtraHeader[128];
char achHttpHeader[1024];
char achBuffer[SEND_BUFFER_SIZE];
DWORD dwResponseSize;
LPSERVERCONTEXT lpServerContext;
HSE_TF_INFO hseTF;
QUERY_PARAMETER QueryParameter;
g_pCpsCounter->AddHit(TOTAL);
// get the query string
fRet = (*pEcb->GetServerVariable)(pEcb->ConnID,
"QUERY_STRING",
achQuery,
&dwBufferLen);
//
// If there is an error, log an NT event and leave.
//
if (!fRet)
{
dwStatusCode = GetLastError();
#ifdef _LOG_DEBUG_MESSAGE
switch (dwStatusCode)
{
case ERROR_INVALID_PARAMETER:
lstrcpy(achMsg,"error: invalid parameter");
break;
case ERROR_INVALID_INDEX:
lstrcpy(achMsg,"error: invalid index");
break;
case ERROR_INSUFFICIENT_BUFFER:
lstrcpy(achMsg,"error: insufficient buffer");
break;
case ERROR_MORE_DATA:
lstrcpy(achMsg,"error: more data coming");
break;
case ERROR_NO_DATA:
lstrcpy(achMsg,"error: no data available");
break;
}
LogDebugMessage(achMsg);
#endif
wsprintf(achMsg, "%ld", dwStatusCode);
g_pEventLog -> FLogError(PBSERVER_CANT_GET_PARAMETER, achMsg);
goto CleanUp;
}
LogDebugMessage("prepare to get query parameters");
// parse the query string, get the value of each parameter
GetQueryParameter(achQuery, &QueryParameter);
// check the validity of the parameter
if (MISSING_VALUE == QueryParameter.m_dOSArch ||
MISSING_VALUE == QueryParameter.m_dOSType ||
MISSING_VALUE == QueryParameter.m_dLCID ||
0 == lstrlen(QueryParameter.m_achCMVer) ||
0 == lstrlen(QueryParameter.m_achOSVer))
{
// invalid data
dwStatusCode = HTTP_STATUS_BAD_REQUEST;
goto CleanUp;
}
//
// Use defaults for some missing values
//
if (0 == lstrlen(QueryParameter.m_achPB))
{
lstrcpy(QueryParameter.m_achPB, achDefService);
}
if (MISSING_VALUE == QueryParameter.m_dPBVer)
{
QueryParameter.m_dPBVer = dDefPBVer;
}
// DebugBreak();
#ifdef _LOG_DEBUG_MESSAGE
sprintf(achMsg, "in main thread, g_fNewPhoneBook = %s;",
g_fNewPhoneBook ? "TRUE" : "FALSE");
LogDebugMessage(achMsg);
#endif
HRESULT hr;
hr = GetPhoneBook(QueryParameter.m_achPB,
QueryParameter.m_dLCID,
QueryParameter.m_dOSType,
QueryParameter.m_dOSArch,
QueryParameter.m_dPBVer,
achPhysicalPath);
fHasContent = FALSE;
if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
{
// we couldn't find the required file (phonebook name is probably bad)
dwStatusCode = HTTP_STATUS_SERVICE_NA;
}
else if (FAILED(hr))
{
// some other error
dwStatusCode = HTTP_STATUS_SERVER_ERROR;
}
else if (S_FALSE == hr)
{
// you don't need a phone book
dwStatusCode = HTTP_STATUS_NO_CONTENT;
}
else
{
// we have a phone book for you...
fHasContent = TRUE;
dwStatusCode = HTTP_STATUS_OK;
}
CleanUp:
if (HTTP_STATUS_OK != dwStatusCode && HTTP_STATUS_NO_CONTENT != dwStatusCode)
{
g_pCpsCounter->AddHit(ERRORS);
}
// DebugBreak();
LogDebugMessage("download file:");
LogDebugMessage(achPhysicalPath);
// convert virtual path to physical path
if (fHasContent)
{
// get cab file size
dwCabFileSize = GetFileLength(achPhysicalPath);
}
BuildStatusCode(szResponse, dwStatusCode);
dwResponseSize = lstrlen(szResponse);
dwRet = HSE_STATUS_SUCCESS;
// prepare for the header
if (HTTP_STATUS_OK == dwStatusCode && dwCabFileSize)
{
// not a NULL cab file
wsprintf(achExtraHeader,
"Content-Type: application/octet-stream\r\nContent-Length: %ld\r\n\r\n",
dwCabFileSize);
}
else
{
lstrcpy(achExtraHeader, "\r\n"); // just send back an empty line
}
// set up asynchronized I/O context
lpServerContext = NULL;
lpServerContext = (LPSERVERCONTEXT) HeapAlloc(g_hProcessHeap,
HEAP_ZERO_MEMORY,
sizeof(SERVERCONTEXT));
if (!lpServerContext)
{
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_INTERNAL, achMsg);
return HSE_STATUS_ERROR;
}
lpServerContext->pEcb = pEcb;
lpServerContext->hseTF.hFile = INVALID_HANDLE_VALUE;
if (!pEcb->ServerSupportFunction(pEcb->ConnID,
HSE_REQ_IO_COMPLETION,
HseIoCompletion,
0,
(LPDWORD) lpServerContext))
{
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_INTERNAL, achMsg);
HeapFree(g_hProcessHeap, 0, lpServerContext);
return HSE_STATUS_ERROR;
}
// if there's no content, send header and status code back using WriteClient();
// otherwise, use TransmitFile to send the file content back
FormHttpHeader(achHttpHeader, szResponse, achExtraHeader);
lstrcpy(lpServerContext->szBuffer, achHttpHeader);
//
// send status code or the file back
//
dwRet = HSE_STATUS_PENDING;
if (!fHasContent)
{
// Append status text as the content
lstrcat(lpServerContext->szBuffer, szResponse);
dwResponseSize = lstrlen(lpServerContext->szBuffer);
if (pEcb->WriteClient(pEcb->ConnID,
lpServerContext->szBuffer,
&dwResponseSize,
HSE_IO_ASYNC) == FALSE)
{
pEcb->dwHttpStatusCode = HTTP_STATUS_SERVER_ERROR;
dwRet = HSE_STATUS_ERROR;
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_CANT_SEND_HEADER,achMsg);
HeapFree(g_hProcessHeap, 0, lpServerContext);
return dwRet;
}
}
else
{
// send file back using TransmitFile
HANDLE hFile = INVALID_HANDLE_VALUE;
hFile = CreateFile(achPhysicalPath,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
wsprintf(achMsg, "%s (%u)", achPhysicalPath, GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_CANT_OPEN_FILE, achMsg);
HeapFree(g_hProcessHeap, 0, lpServerContext);
return HSE_STATUS_ERROR;
}
lpServerContext->hseTF.hFile = hFile;
lpServerContext->hseTF.pfnHseIO = NULL;
lpServerContext->hseTF.pContext = lpServerContext;
lpServerContext->hseTF.BytesToWrite = 0; // entire file
lpServerContext->hseTF.Offset = 0; // from beginning
lpServerContext->hseTF.pHead = lpServerContext->szBuffer;
lpServerContext->hseTF.HeadLength = lstrlen(lpServerContext->szBuffer);
lpServerContext->hseTF.pTail = NULL;
lpServerContext->hseTF.TailLength = 0;
lpServerContext->hseTF.dwFlags = HSE_IO_ASYNC | HSE_IO_DISCONNECT_AFTER_SEND;
if (!pEcb->ServerSupportFunction(pEcb->ConnID,
HSE_REQ_TRANSMIT_FILE,
&(lpServerContext->hseTF),
0,
NULL))
{
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_CANT_SEND_CONTENT,achMsg);
dwRet = HSE_STATUS_ERROR;
CloseHandle(lpServerContext->hseTF.hFile);
HeapFree(g_hProcessHeap, 0, lpServerContext);
return dwRet;
}
}
return HSE_STATUS_PENDING;
}
//
// build status string from code
//
void CPhoneBkServer::BuildStatusCode(LPTSTR pszResponse, DWORD dwCode)
{
assert(pszResponse);
HTTPStatusInfo * pInfo = statusStrings;
while (pInfo->pstrString)
{
if (dwCode == pInfo->dwCode)
{
break;
}
pInfo++;
}
if (pInfo->pstrString)
{
wsprintf(pszResponse, "%d %s", dwCode, pInfo->pstrString);
}
else
{
assert(dwCode != HTTP_STATUS_OK);
// ISAPITRACE1("Warning: Nonstandard status code %d\n", dwCode);
BuildStatusCode(pszResponse, HTTP_STATUS_OK);
}
}
//
// DLL initialization function
//
BOOL WINAPI DllMain(HINSTANCE hInst, ULONG ulReason,
LPVOID lpReserved)
{
switch (ulReason)
{
case DLL_PROCESS_ATTACH:
//DebugBreak();
OutputDebugString("DllMain: process attach\n");
return InitProcess();
break;
case DLL_PROCESS_DETACH:
LogDebugMessage("process detach");
break;
}
return TRUE;
}
//
// global initialization procedure.
//
BOOL InitProcess()
{
//TODO: in order to avoid any future problems, any significant initialization
// should be done in GetExtensionVersion()
DWORD dwID;
DWORD dwServiceNameLen;
SECURITY_ATTRIBUTES sa;
PACL pAcl = NULL;
g_fBeingShutDown = FALSE;
//
// May throw STATUS_NO_MEMORY if memory is low. We want to make sure this
// doesn't bring down the process (the admin may have configured pbserver
// to run in-process)
//
__try
{
OutputDebugString("InitProcess: to InitializeCriticalSection ... \n");
// initialize CriticalSection
InitializeCriticalSection(&g_CriticalSection);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
#if DBG
char achMsg[256];
DWORD dwErr = GetExceptionCode();
wsprintf(achMsg,"InitProcess: InitializeCriticalSection failed, thread=%ld ExceptionCode=%08lx", GetCurrentThreadId(), dwErr);
OutputDebugString(achMsg);
#endif
return FALSE;
}
OutputDebugString("InitProcess: to GetProcessHeap() ... \n");
g_hProcessHeap = GetProcessHeap();
if (NULL == g_hProcessHeap)
{
goto failure;
}
OutputDebugString("InitProcess: to new CNTEvent... \n");
g_pEventLog = new CNTEvent("Phone Book Service");
if (NULL == g_pEventLog)
goto failure;
/*
// check for validity of timebomb
dwServiceNameLen = lstrlen(SERVICE_NAME);
if (!IsTimeBombValid(SERVICE_NAME, dwServiceNameLen)) {
g_pEventLog -> FLogError(PBSERVER_ERROR_SERVICE_EXPIRED);
goto failure;
}
*/
// Begin Geeta
//
// Create a semaphore for the shared memory
//
// Initialize a default Security attributes, giving world permissions,
// this is basically prevent Semaphores and other named objects from
// being created because of default acls given by winlogon when perfmon
// is being used remotely.
sa.bInheritHandle = FALSE;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = malloc(sizeof(SECURITY_DESCRIPTOR));
if ( !sa.lpSecurityDescriptor )
{
goto failure;
}
if ( !InitializeSecurityDescriptor(sa.lpSecurityDescriptor,SECURITY_DESCRIPTOR_REVISION) )
{
goto failure;
}
// bug 30991: Security issue, don't use NULL DACLs.
//
if (FALSE == SetAclPerms(&pAcl))
{
goto failure;
}
if (FALSE == SetSecurityDescriptorDacl(sa.lpSecurityDescriptor, TRUE, pAcl, FALSE))
{
goto failure;
}
OutputDebugString("InitProcess: To create semaphone...\n");
g_hSemaphore = CreateSemaphore( &sa, // Security attributes
1, // Initial Count
1, // Max count
SEMAPHORE_OBJECT ); // Semaphore name -- in "cpsmon.h"
if (ERROR_ALREADY_EXISTS == GetLastError())
{
//
// We're not expecting anyone to have this semaphore already created.
// In the interests of security (a pre-existing semaphore could have been
// created by anyone, and we don't want anyone other than ourselves owning
// the pbsmon semaphore), we exit.
//
OutputDebugString("InitProcess: semaphore already exists - exiting.\n");
assert(0);
goto failure;
// ISSUE-2000/10/30-SumitC Note that if pbserver is taken down without the
// chance to delete the semaphore, we can't restart
// until the machine is rebooted.
}
if ( NULL == g_hSemaphore )
{
goto failure;
}
OutputDebugString("InitProcess: To initialize shared memory ...\n");
//
// initialize Shared memory
//
if (!InitializeSharedMem(sa))
{
goto failure;
}
// free the memory
free ((void *) sa.lpSecurityDescriptor);
OutputDebugString("InitProcess: To grant permissions SHARED_OBJECT...\n");
//
// initialize Counters
//
OutputDebugString("InitProcess: To initialize perfmon counters\n");
g_pCpsCounter->InitializeCounters();
// End Geeta
//
// Initialize the global variables. Note: must do this before Creating the
// monitor thread (because of g_szPBDataDir, g_achDBFileName etc)
//
if (!InitPBFilesPath())
{
goto failure;
}
char achTempName[MAX_PATH_LEN+1];
char szDBFileName[MAX_PATH_LEN+1];
DWORD dwBufferSize;
char *pszFoundPosition;
// get the full path name for the data base
wsprintf(achTempName, "SOFTWARE\\ODBC\\ODBC.INI\\%s", c_szDBName);
OutputDebugString(achTempName);
dwBufferSize = sizeof(szDBFileName);
if (!GetRegEntry(HKEY_LOCAL_MACHINE,
achTempName,
"DBQ",
REG_SZ,
NULL,
0,
(unsigned char *)&szDBFileName,
&dwBufferSize))
{
/*
wsprintf(achMsg,"HKLM\\%s\\DBQ : Error code %ld", achTempName, GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_ODBC_CANT_READ_REGISTRY, achMsg);
*/
goto failure;
}
// initialize the NewDBFilename --> actually newpb.mdb
// & the ChangeFileName --> actually newpb.txt
//
lstrcpy(achTempName, szDBFileName);
pszFoundPosition = _tcsrchr(achTempName, '\\'); // found the last '\' --> path info
if( pszFoundPosition != NULL)
{
*(pszFoundPosition+1) = '\0';
}
// store the directory name for the phone book files
lstrcpy((char *)g_achDBDirectory, achTempName);
//
// initialize PhoneBookServer object
// PhoneBookServer object should be the last to initialize because
// it requires some other objects to be initialized first, such as
// eventlog, critical section, odbc interface, etc.
OutputDebugString("InitProcess: To new a phone book server\n");
g_pPBServer = new CPhoneBkServer;
if (NULL == g_pPBServer)
{
return FALSE;
}
OutputDebugString("InitProcess: To create a thread for DB file change monitoring\n");
// create the thread to monitor file change
g_hMonitorThread = CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)MonitorDBFileChangeThread,
NULL,
0,
&dwID
);
if (INVALID_HANDLE_VALUE == g_hMonitorThread)
{
g_pEventLog->FLogError(PBSERVER_ERROR_INTERNAL);
goto failure;
}
SetThreadPriority(g_hMonitorThread, THREAD_PRIORITY_ABOVE_NORMAL);
return TRUE;
failure: // clean up everything in case of failure
OutputDebugString("InitProcess: failed\n");
DeleteCriticalSection(&g_CriticalSection);
// free the memory
if (sa.lpSecurityDescriptor)
{
free ((void *) sa.lpSecurityDescriptor);
}
if (g_pEventLog)
{
delete g_pEventLog;
g_pEventLog = NULL;
}
if (g_pPBServer)
{
delete g_pPBServer;
g_pPBServer = NULL;
}
if (pAcl)
{
LocalFree(pAcl);
}
// Begin geeta
if (g_hSemaphore)
{
CloseHandle(g_hSemaphore);
g_hSemaphore = NULL;
}
// end geeta
return FALSE;
}
// global cleanup process
BOOL CleanUpProcess()
{
HANDLE hFile; // handle for the temporary file
DWORD dwResult;
char achDumbFile[2 * MAX_PATH + 4];
char achMsg[64];
// kill the change monitor thread
if (g_hMonitorThread != INVALID_HANDLE_VALUE)
{
// now try to synchronize between the main thread and the child thread
// step1: create a new file in g_szPBDataDir, therefore unblock the child thread
// which is waiting for such a change in file directory
g_fBeingShutDown = TRUE;
lstrcpy(achDumbFile, (char *)g_szPBDataDir);
lstrcat(achDumbFile,"temp");
// create a temp file, then delete it!
// This is to create a change in the directory so the child thread can exit itself
FILE * fpTemp = fopen(achDumbFile, "w");
if (fpTemp)
{
fclose(fpTemp);
DeleteFile(achDumbFile);
}
// step2: wait for the child thread to terminate
dwResult = WaitForSingleObject(g_hMonitorThread, 2000L); // wait for one second
if (WAIT_FAILED == dwResult)
{
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog -> FLogError(PBSERVER_ERROR_WAIT_FOR_THREAD, achMsg);
}
if (g_hMonitorThread != INVALID_HANDLE_VALUE)
{
CloseHandle(g_hMonitorThread);
}
}
// disconnect from ODBC
if (g_pPBServer)
{
delete g_pPBServer;
g_pPBServer = NULL;
}
// clean up all allocated resources
if (g_pEventLog)
{
delete g_pEventLog;
g_pEventLog = NULL;
}
// Begin Geeta
//
// Close the semaphore
//
if ( NULL != g_hSemaphore )
{
CloseHandle(g_hSemaphore);
g_hSemaphore = NULL;
OutputDebugString("CLEANUPPROCESS: Semaphore deleted\n");
}
//
// Close the shared memory object
//
CleanUpSharedMem();
// End Geeta
DeleteCriticalSection(&g_CriticalSection);
return TRUE;
}
// Entry Points of this ISAPI Extension DLL
// ISA entry point function. Intialize the server object g_pPBServer
BOOL WINAPI GetExtensionVersion(LPHSE_VERSION_INFO pVer)
{
return g_pPBServer ? g_pPBServer->GetExtensionVersion(pVer) : FALSE;
}
// ISA entry point function. Implemented through object g_pPBServer
DWORD WINAPI HttpExtensionProc(LPEXTENSION_CONTROL_BLOCK pEcb)
{
DWORD dwRetCode;
if (NULL == g_pPBServer)
{
return HSE_STATUS_ERROR;
}
dwRetCode = g_pPBServer->HttpExtensionProc(pEcb);
return dwRetCode;
}
//
// The standard entry point called by IIS as the last function.
//
BOOL WINAPI TerminateExtension(DWORD dwFlags)
{
return CleanUpProcess();
}
//
// StrEqual(achStr, pszStr)
//
// Test whether achStr is equal to pszStr.
// Please note: the point here is: achStr is not zero-ended
BOOL StrEqual(char achStr[], char *pszStr)
{
int i;
for (i = 0; i < lstrlen(pszStr); i++)
{
if (achStr[i] != pszStr[i])
{
return FALSE;
}
}
return TRUE;
}
//+---------------------------------------------------------------------------
//
// Function: MonitorDBFileChangeThread
//
// Synopsis: Call the MonitorDBFileChange method to monitor any write to
// the database file
//
// Arguments: [lpParam] -- additional thread parameter
//
// History: 01/28/97 byao Created
//
//----------------------------------------------------------------------------
DWORD WINAPI MonitorDBFileChangeThread(LPVOID lpParam)
{
HANDLE hDir = NULL;
char achMsg[256];
DWORD dwRet = 0;
DWORD dwNextEntry, dwAction, dwFileNameLength, dwOffSet;
char achFileName[MAX_PATH_LEN+1];
char achLastFileName[MAX_PATH_LEN+1];
//
// open a handle to the PBS dir, which we're going to monitor
//
hDir = CreateFile (
(char *)g_achDBDirectory, // pointer to the directory name
FILE_LIST_DIRECTORY, // access (read-write) mode
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, // share mode
NULL, // security descriptor
OPEN_EXISTING, // how to create
FILE_FLAG_BACKUP_SEMANTICS, // file attributes
NULL // file with attributes to copy
);
if (INVALID_HANDLE_VALUE == hDir)
{
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_CANT_CREATE_FILE, (char *)g_szPBDataDir, achMsg);
dwRet = 1L;
goto Cleanup;
}
while (1)
{
const DWORD c_dwMaxChanges = 1024;
BYTE arrChanges[c_dwMaxChanges];
DWORD dwNumChanges;
//
// This is a synchronous call - we sit here waiting for something to
// change in this directory. If something does, we check to see if it
// is something for which we should log an event.
//
if (!ReadDirectoryChangesW(hDir,
arrChanges,
c_dwMaxChanges,
FALSE,
FILE_NOTIFY_CHANGE_LAST_WRITE,
&dwNumChanges,
NULL,
NULL))
{
//
// if this fails, log the failure and leave
//
wsprintf(achMsg, "%ld", GetLastError());
g_pEventLog->FLogError(PBSERVER_ERROR_CANT_DETERMINE_CHANGE, achMsg);
OutputDebugString(achMsg);
dwRet = 1L;
goto Cleanup;
}
OutputDebugString("detected a file system change\n");
achLastFileName[0] = TEXT('\0');
dwNextEntry = 0;
do
{
DWORD dwBytes;
FILE_NOTIFY_INFORMATION * pFNI = (FILE_NOTIFY_INFORMATION*) &arrChanges[dwNextEntry];
// check only the first change
dwOffSet = pFNI->NextEntryOffset;
dwNextEntry += dwOffSet;
dwAction = pFNI->Action;
dwFileNameLength = pFNI->FileNameLength;
OutputDebugString("prepare to convert the changed filename\n");
//TODO: check whether we can use UNICODE for all filenames
dwBytes = WideCharToMultiByte(CP_ACP,
0,
pFNI->FileName,
dwFileNameLength,
achFileName,
MAX_PATH_LEN,
NULL,
NULL);
if (0 == dwBytes)
{
// failed to convert filename
g_pEventLog->FLogError(PBSERVER_ERROR_CANT_CONVERT_FILENAME, achFileName);
OutputDebugString("Can't convert filename\n");
continue;
}
//
// Conversion succeeded. Null-terminate the filename.
//
achFileName[dwBytes/sizeof(WCHAR)] = '\0';
if (0 == _tcsicmp(achLastFileName, achFileName))
{
// the same file changed
OutputDebugString("the same file changed again\n");
continue;
}
// keep the last filename
_tcscpy(achLastFileName, achFileName);
if (g_fBeingShutDown)
{
//
// Time to go ...
//
dwRet = 1L;
goto Cleanup;
}
//
// now a file has changed. Test whether it's monitored file 'newpb.txt'
//
LogDebugMessage(achLastFileName);
LogDebugMessage((char *)c_szChangeFileName);
if ((0 == _tcsicmp(achLastFileName, (char *)c_szChangeFileName)) &&
(FILE_ACTION_ADDED == dwAction || FILE_ACTION_MODIFIED == dwAction))
{
EnterCriticalSection(&g_CriticalSection);
LogDebugMessage("entered critical section!");
g_fNewPhoneBook = TRUE;
LogDebugMessage("leaving critical section!");
LeaveCriticalSection(&g_CriticalSection);
g_pEventLog->FLogInfo(PBSERVER_INFO_NEW_PHONEBOOK);
}
#ifdef _LOG_DEBUG_MESSAGE
sprintf(achMsg, "in child thread, g_fNewPhoneBook = %s;",
g_fNewPhoneBook ? "TRUE" : "FALSE");
LogDebugMessage(achMsg);
#endif
}
while (dwOffSet);
}
Cleanup:
if (hDir)
{
CloseHandle(hDir);
}
return dwRet;
}
// Begin Geeta
//----------------------------------------------------------------------------
//
// Function: GetSemaphore
//
// Synopsis: This function gets hold of the semaphore for accessing shared file.
//
// Arguments: None.
//
// Returns: TRUE if succeeds, FALSE if fails.
//
// History: 06/02/97 t-geetat Created
//
//----------------------------------------------------------------------------
BOOL GetSemaphore()
{
DWORD WaitRetValue = WaitForSingleObject( g_hSemaphore, INFINITE );
switch (WaitRetValue)
{
case WAIT_OBJECT_0:
return TRUE ;
case WAIT_ABANDONED:
return TRUE;
default:
return FALSE;
}
return FALSE;
}
//----------------------------------------------------------------------------
//
// Function: InitializeSharedMem
//
// Synopsis: Sets up the memory mapped file
//
// Arguments: SECURITY_ATTRIBUTES sa: security descriptor for this object
//
// Returns: TRUE if successful, FALSE otherwise
//
// History: 05/29/97 Created by Geeta Tarachandani
//
//----------------------------------------------------------------------------
BOOL InitializeSharedMem(SECURITY_ATTRIBUTES sa)
{
//
// Create a memory mapped object
//
OutputDebugString("InitializeSharedMem: to create file mapping\n");
g_hSharedFileMapping = CreateFileMapping(
INVALID_HANDLE_VALUE, // Shared object is in memory
&sa, // security descriptor
PAGE_READWRITE| SEC_COMMIT, // Desire R/W access
0, // |_
sizeof(CCpsCounter), // | Size of mapped object
SHARED_OBJECT ); // Shared Object
if (NULL == g_hSharedFileMapping)
{
goto CleanUp;
}
OutputDebugString("InitializeSharedMem: MapViewofFileEx\n");
g_pCpsCounter = (CCpsCounter *) MapViewOfFileEx(
g_hSharedFileMapping, // Handle to shared file
FILE_MAP_WRITE, // Write access desired
0, // Mapping offset
0, // Mapping offset
sizeof(CCpsCounter), // Mapping object size
NULL ); // Any base address
if (NULL == g_pCpsCounter)
{
goto CleanUp;
}
return TRUE;
CleanUp:
CleanUpSharedMem();
return FALSE;
}
//----------------------------------------------------------------------------
//
// Function: InitializeCounters()
//
// Class: CCpsCounter
//
// Synopsis: Initializes all the Performance Monitoring Counters to 0
//
// Arguments: None
//
// Returns: void
//
// History: 05/29/97 Created by Geeta Tarachandani
//
//----------------------------------------------------------------------------
void CCpsCounter::InitializeCounters( void )
{
m_dwTotalHits =0;
m_dwNoUpgradeHits =0;
m_dwDeltaUpgradeHits=0;
m_dwFullUpgradeHits =0;
m_dwErrors =0;
}
inline void CCpsCounter::AddHit(enum CPS_COUNTERS eCounter)
{
if (GetSemaphore())
{
switch (eCounter)
{
case TOTAL:
g_pCpsCounter->m_dwTotalHits ++;
break;
case NO_UPGRADE:
g_pCpsCounter->m_dwNoUpgradeHits ++;
break;
case DELTA_UPGRADE:
g_pCpsCounter->m_dwDeltaUpgradeHits ++;
break;
case FULL_UPGRADE:
g_pCpsCounter->m_dwFullUpgradeHits ++;
break;
case ERRORS:
g_pCpsCounter->m_dwErrors ++;
break;
default:
OutputDebugString("Unknown counter type");
break;
}
}
ReleaseSemaphore(g_hSemaphore, 1, NULL);
}
//----------------------------------------------------------------------------
//
// Function: CleanUpSharedMem()
//
// Synopsis: Unmaps the shared file & closes all file handles
//
// Arguments: None
//
// Returns: Void
//
// History: 06/01/97 Created by Geeta Tarachandani
//
//----------------------------------------------------------------------------
void CleanUpSharedMem()
{
//
// Unmap the shared file
//
if (g_pCpsCounter)
{
UnmapViewOfFile( g_pCpsCounter );
g_pCpsCounter = NULL;
}
CloseHandle(g_hSharedFileMapping);
g_hSharedFileMapping = NULL;
}
// End Geeta
BOOL InitPBFilesPath()
{
if (lstrlen(g_szPBDataDir))
{
return TRUE;
}
else
{
//
// Get location of PB files on this machine (\program files\phone book service\data)
//
if (S_OK == SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, g_szPBDataDir))
{
lstrcat(g_szPBDataDir, "\\phone book service\\Data\\");
return TRUE;
}
else
{
return FALSE;
}
}
}
HRESULT GetCurrentPBVer(char * pszPBName, int * pnCurrentPBVer)
{
HRESULT hr = S_OK;
char szTmp[2 * MAX_PATH];
int nNewestPB = 0;
assert(pszPBName);
assert(pnCurrentPBVer);
if (!pszPBName || !pnCurrentPBVer)
{
hr = E_INVALIDARG;
goto Cleanup;
}
if (!InitPBFilesPath())
{
hr = E_FAIL;
goto Cleanup;
}
//
// go to subdir named 'pszPBName', and find all FULL cabs.
//
wsprintf(szTmp, "%s%s\\*full.cab", g_szPBDataDir, pszPBName);
HANDLE hFind;
WIN32_FIND_DATA finddata;
hFind = FindFirstFile(szTmp, &finddata);
if (INVALID_HANDLE_VALUE == hFind)
{
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
goto Cleanup;
}
//
// Find the highest-numbered full cab we have, and cache that number
//
do
{
int nVer;
int nRet = sscanf(finddata.cFileName, "%dfull.cab", &nVer);
if (1 == nRet)
{
if (nVer > nNewestPB)
{
nNewestPB = nVer;
}
}
}
while (FindNextFile(hFind, &finddata));
FindClose(hFind);
*pnCurrentPBVer = nNewestPB;
#if DBG
//
// re-iterate, looking for deltas.
//
wsprintf(szTmp, "%s%s\\*delta*.cab", g_szPBDataDir, pszPBName);
hFind = FindFirstFile(szTmp, &finddata);
if (INVALID_HANDLE_VALUE == hFind)
{
OutputDebugString("found Nfull, but no deltas (this is ok if this is the first phonebook)");
goto Cleanup;
}
do
{
int nVerTo, nVerFrom;
int nRet = sscanf(finddata.cFileName, "%ddelta%d.cab", &nVerTo, &nVerFrom);
if (2 == nRet)
{
if (nVerTo > nNewestPB)
{
assert(0 && "largest DELTA cab has corresponding FULL cab missing");
break;
}
}
}
while (FindNextFile(hFind, &finddata));
FindClose(hFind);
#endif
Cleanup:
return hr;
}
BOOL
CheckIfFileExists(const char * psz)
{
HANDLE hFile = CreateFile(psz,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
return FALSE;
}
else
{
CloseHandle(hFile);
return TRUE;
}
}
HRESULT
GetPhoneBook(IN char * pszPBName,
IN int dLCID,
IN int dOSType,
IN int dOSArch,
IN int dPBVerCaller,
OUT char * pszDownloadPath)
{
HRESULT hr = S_OK;
int dVersionDiff;
int nCurrentPBVer;
#if DBG
char achMsg[256];
#endif
assert(pszPBName);
assert(pszDownloadPath);
if (!pszPBName || !pszDownloadPath)
{
hr = E_INVALIDARG;
goto Cleanup;
}
hr = GetCurrentPBVer(pszPBName, &nCurrentPBVer);
if (S_OK != hr)
{
goto Cleanup;
}
dVersionDiff = nCurrentPBVer - dPBVerCaller;
if (dVersionDiff <= 0)
{
//
// no download
//
hr = S_FALSE;
g_pCpsCounter->AddHit(NO_UPGRADE);
}
else
{
if (dVersionDiff < 5 && 0 != dPBVerCaller)
{
//
// incremental update => try to find the delta cab
//
wsprintf(pszDownloadPath, "%s%s\\%dDELTA%d.cab",
g_szPBDataDir, pszPBName, nCurrentPBVer, dPBVerCaller);
// x:\program files\phone book service\ phone_book_name \ nDELTAm.cab
if (!CheckIfFileExists(pszDownloadPath))
{
hr = S_FALSE;
}
else
{
g_pCpsCounter->AddHit(DELTA_UPGRADE);
}
}
//
// note that if we tried to find a delta above and failed, hr is set to
// S_FALSE, so we fall through to the full download below.
//
if (dVersionDiff >= 5 || 0 == dPBVerCaller || S_FALSE == hr)
{
//
// bigger than 5, or no pb at all => full download
//
wsprintf(pszDownloadPath, "%s%s\\%dFULL.cab",
g_szPBDataDir, pszPBName, nCurrentPBVer);
// x:\program files\phone book service\ phone_book_name \ nFULL.cab
if (!CheckIfFileExists(pszDownloadPath))
{
hr = S_OK;
// return "success", the failure to open the file will be trapped
// by caller.
}
else
{
if (S_FALSE == hr)
{
hr = S_OK;
}
g_pCpsCounter->AddHit(FULL_UPGRADE);
}
}
}
Cleanup:
return hr;
}
| [
"[email protected]"
] | |
f105877d913981999f435180bbf49a0484af64c9 | def39f068050b234df9f6909d4277f96b740f11c | /E-olimp/4419. Dense forest .cpp | 43ca6dcdef241cf9b42c3bfeca949b316b810e9a | [] | no_license | azecoder/Problem-Solving | 41a9a4302c48c8de59412ab9175b253df99f1f28 | a920b7bac59830c7b798127f6eed0e2ab31a5fa2 | refs/heads/master | 2023-02-10T09:47:48.322849 | 2021-01-05T14:14:09 | 2021-01-05T14:14:09 | 157,236,604 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | #include <iostream>
#include <stdio.h>
#include <math.h>
#define exp 1e-8
using namespace std;
double Vp , Vf , Oy;
double dis(double x , double y) {
return sqrt(x*x + y*y);
}
double f(double d) {
double t1 = dis(1.0 - Oy , d) / Vp;
double t2 = dis(1.0 - d , Oy) / Vf;
return t1 + t2;
}
int main()
{
double l = 0.0 , r = 1.0;
cin >> Vp >> Vf >> Oy;
while (r - l >= exp) {
double k = l + (r - l) / 3;
double p = r - (r - l) / 3;
if (f(k) < f(p)) r = p;
else l = k;
}
printf("%.8lf\n",l);
return 0;
} | [
"[email protected]"
] | |
b8479386c42d14f9cd16a0c89f33d77b910ac376 | 9e6a8adb8ee148433937b08fac64095611168504 | /libs/sweet_parser/sweet/lua/lua_test/TestLuaValue.cpp | f9932dc87570ab8291cea36689791f50f57f6a47 | [] | no_license | yglukhov/le | 844df1e89ad54adc5e6d3ad1cc500baeb778b78d | 220ea0f3ddc08799995477daf567f77bd5bb1f5e | refs/heads/master | 2016-09-06T12:44:44.028536 | 2014-07-25T17:31:54 | 2014-07-25T17:31:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,601 | cpp | //
// TestLuaValue.cpp
// Copyright (c) 2011 Charles Baker. All rights reserved.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
#include <sweet/unit/UnitTest.h>
#include <sweet/lua/Lua.hpp>
#include <sweet/lua/LuaValue.hpp>
using namespace sweet::lua;
SUITE( LuaValue )
{
TEST( LuaValueLeavesValueOnStack )
{
Lua lua;
lua_State* lua_state = lua.get_lua_state();
lua_newtable( lua_state );
LuaValue value( lua, -1 );
CHECK( lua_istable(lua_state, -1) );
}
TEST( LuaValueReferencesString )
{
const char* STRING_VALUE = "string";
Lua lua;
lua_State* lua_state = lua.get_lua_state();
lua_pushstring( lua_state, STRING_VALUE );
LuaValue value( lua, -1 );
lua_pop( lua_state, 1 );
lua_gc( lua_state, LUA_GCCOLLECT, 0 );
lua_push( lua_state, value );
CHECK( lua_isstring(lua_state, -1) );
CHECK_EQUAL( lua_tostring(lua_state, -1), STRING_VALUE );
}
TEST( LuaValueReferencesTable )
{
Lua lua;
lua_State* lua_state = lua.get_lua_state();
lua_newtable( lua_state );
LuaValue value( lua, -1 );
lua_pop( lua_state, 1 );
lua_gc( lua_state, LUA_GCCOLLECT, 0 );
lua_push( lua_state, value );
CHECK( lua_istable(lua_state, -1) );
}
TEST( LuaValueCanBeCopied )
{
const char* STRING_VALUE = "string";
Lua lua;
lua_State* lua_state = lua.get_lua_state();
lua_pushstring( lua_state, STRING_VALUE );
LuaValue value( lua, -1 );
lua_pop( lua_state, 1 );
LuaValue other_value( value );
lua_push( lua_state, value );
lua_push( lua_state, other_value );
CHECK( lua_equal(lua_state, -1, -2) );
}
TEST( DefaultConstructedLuaValueCanBeAssignedTo )
{
const char* STRING_VALUE = "string";
Lua lua;
lua_State* lua_state = lua.get_lua_state();
lua_pushstring( lua_state, STRING_VALUE );
LuaValue value( lua, -1 );
lua_pop( lua_state, 1 );
LuaValue other_value;
other_value = value;
lua_push( lua_state, value );
lua_push( lua_state, other_value );
CHECK( lua_equal(lua_state, -1, -2) );
}
TEST( LuaValueCanBeAssignedTo )
{
const char* STRING_VALUE = "string";
Lua lua;
lua_State* lua_state = lua.get_lua_state();
lua_pushstring( lua_state, STRING_VALUE );
LuaValue value( lua, -1 );
lua_pop( lua_state, 1 );
LuaValue other_value( value );
other_value = value;
lua_push( lua_state, value );
lua_push( lua_state, other_value );
CHECK( lua_equal(lua_state, -1, -2) );
}
}
| [
"[email protected]"
] | |
496b4c218c6c0980c6d182f0f9d7994623a4382b | ad6e1f2e9bbefca3b94a609bb0faefeebd7bf12c | /me/debug/IErrorHandler.h | 11ceb5836d5d6356f79e8e428b5a2cf60cdb3f67 | [] | no_license | kit10us/MercuryEngine | c9842201b19abdc0bb093681834742925cf0d493 | e1951f223dc8908a4cf7884a8cdf73442b6bd760 | refs/heads/master | 2023-06-22T09:44:19.756924 | 2021-07-21T13:45:24 | 2021-07-21T13:45:24 | 206,671,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | h | // Copyright (c) 2003 - 2011, Kit10 Studios LLC
// All Rights Reserved
#pragma once
#include <me/debug/ErrorLevel.h>
#include <unify/Exception.h>
#include <memory>
#include <string>
namespace me::debug
{
/// <summary>
/// Conveys the result of how an error was handled.
/// </summary>
enum class ReportErrorResult
{
Continue,
Retry,
Abort
};
/// <summary>
/// Handlers errors, allowing custom functionality.
/// </summary>
class IErrorHandler
{
public:
typedef std::shared_ptr< IErrorHandler > ptr;
~IErrorHandler() {}
/// <summary>
/// Report an error to the error handler.
/// </summary>
virtual ReportErrorResult ReportError( ErrorLevel level, std::string error, bool canContinue = false, bool canRetry = false ) = 0;
};
} | [
"[email protected]"
] | |
9c752410d92a51e40791c32f90451f7989ba5ac9 | 0924811574db23b20df99efa3e8e2b4e314c92c1 | /src/njoy21/input/THERMR/Card2/Icoh/test/Icoh.test.cpp | 53fcf1c41c2d28c2cb96d3afe302ef30047676a0 | [
"BSD-2-Clause"
] | permissive | McStasMcXtrace/NJOY21 | 32b0eb8c442f8a2f244be620a1d389ea6f8f0961 | c4c2657c8dcc3629bcdc35ba6b3707c91ae030e9 | refs/heads/master | 2021-01-09T05:23:27.780319 | 2018-06-14T12:11:43 | 2018-06-14T12:11:43 | 80,757,654 | 1 | 0 | null | 2018-06-14T12:11:44 | 2017-02-02T18:53:52 | C++ | UTF-8 | C++ | false | false | 965 | cpp | #define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "njoy21.hpp"
using namespace njoy::njoy21::input;
SCENARIO( "THERMR icoh values",
"[THERMR],[Card2], [Icoh]"){
GIVEN( "valid icoh values" ){
std::vector<int> validValues{0, 1, 2, 3, 11, 12, 13};
THEN( "the returned class has the correct value" ){
for( int icoh : validValues ){
iRecordStream<char> iss(
std::istringstream( std::to_string( icoh ) ) );
REQUIRE( icoh == argument::extract<
THERMR::Card2::Icoh >( iss ).value );
}
} // THEN
} // GIVEN
GIVEN( "invalid icoh values" ){
std::vector<int> invalidValues{-1, 4, 10, 14};
THEN( "an exception is thrown" ){
for( int icoh : invalidValues ){
iRecordStream<char> iss(
std::istringstream( std::to_string( icoh ) ) );
REQUIRE_THROWS( argument::extract<
THERMR::Card2::Icoh >( iss ) );
}
} // THEN
} // GIVEN
} // SCENARIO
| [
"[email protected]"
] | |
dee241ee45baddec40df20ba7284a50235fc38be | 572580660d475027fa349e47a078479222066726 | /Server/kennel/monitor/monitor/monitor/AimParser/aimparser.cpp | 9e0b4924695f11b36ac409ec8b48752ea58f4ac2 | [] | no_license | SiteView/ecc82Server | 30bae118932435e226ade01bfbb05b662742e6dd | 084b06af3a7ca6c5abf5064e0d1f3f8069856d25 | refs/heads/master | 2021-01-10T21:11:37.487455 | 2013-01-16T09:22:02 | 2013-01-16T09:22:02 | 7,639,874 | 6 | 3 | null | null | null | null | GB18030 | C++ | false | false | 239,200 | cpp | // AimParser.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include "AimParser.h"
//#include "../Global/global.h"
#include "iostream"
using namespace std;
#include "base/funcgeneral.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//在卓望版本打开,标准6.2关闭
//#define ZHUOWANG
//
// Note!
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//
/////////////////////////////////////////////////////////////////////////////
// CAimParserApp
BEGIN_MESSAGE_MAP(CAimParserApp, CWinApp)
//{{AFX_MSG_MAP(CAimParserApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAimParserApp construction
CAimParserApp::CAimParserApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CAimParserApp object
CAimParserApp theApp;
//#define KEY_PATH "SOFTWARE\\Aim"
//#define KEY_NAME "RootPath"
//char IniFileName[1024];
enum {
char_space = 32, //0x20
char_return = 13, //0x0D
char_newline = 10 //0x0A
};
void AddToLogFile(const int nMonitorType, const char*szMsg);
void GetColumnFromLine(CString& strIn, int nColumn, CString& strOut, int nMonitorType = -1);
void GetLineString(const CStringList& lstStr, const int nReverse, int nStart, CString& strOut);
BOOL GetIniFileName(const char *FileName, char *IniFileName);
BOOL GetColumnIndex(CStringList& lstStr, int& nColumn,char*IniFileName);
BOOL GetColumnIndex( CString strIn, int& nColumn, char* pszMatch );
BOOL FormatSource(const char * szSource, const int nMonitorType, CStringList& lstStr,char*IniFileName);
BOOL GetBufferByNewMatchLine(const char * szSource, const int nMonitorType,char*IniFileName,char**buffer);
extern "C" __declspec(dllexport)
BOOL GetMatchColumn(const int nMatchColumnLine,const char * matchcolumnName,const CStringList* pList,int &matchcolumn);
BOOL _GetMatchColumn(const char *szSrc,const char *szName, int &nMatchColumn);
char *FindMonth(char *original);
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fstream>
using namespace std;
#include <atltime.h>
#include <atlstr.h>
CTime strToTime(CString strTime)
{
int iMonth = atoi(strTime.Left(2));
int iDay = atoi(strTime.Mid(2,2));
int iHour = atoi(strTime.Mid(4,2));
int iMinute = atoi(strTime.Mid(6,2));
int iYear = atoi(strTime.Right(2));
CTime tt(iYear+2000,iMonth,iDay,iHour,iMinute,0);
return tt;
}
void WriteLog( const char* str )
{
return;
char timebuf[128],datebuf[128];
_tzset();
_strtime( timebuf );
_strdate( datebuf );
char szLogFile[] = "aimParser.log";
// 判断文件大小:在不打开文件的情况下实现
struct _stat buf;
if( _stat( szLogFile, &buf ) == 0 )
{
if( buf.st_size > 100*1024 )
{
FILE *log = fopen( szLogFile, "w" );
if( log != NULL )
fclose( log );
}
}
FILE *log = fopen( szLogFile,"a+");
if( log != NULL )
{
fprintf( log, "%s %s \t%s\n", datebuf, timebuf, str );
fclose( log );
}
}
bool WriteLog(CString strFileName,const CString strLog)
{
return false;
char szDataBuf[128] = _T("");
char szTimeBuf[128] = _T("");
char szTempBuf[1024*10] = _T("");
_strdate(szDataBuf);
_strtime(szTimeBuf);
sprintf(szTempBuf,"%s-%s",szDataBuf,szTimeBuf);
CString szFileName="";
char szFileDirectory[MAX_PATH]={};
GetCurrentDirectory(MAX_PATH, szFileDirectory);
szFileName.Format("%s\\UnixPaser",szFileDirectory);
CreateDirectory(szFileName,NULL);
szFileName.Format("%s\\%s.log",szFileName,strFileName);
//szFileName.Format("%s.log",strFileName);
ofstream stFileStream;
stFileStream.open(szFileName, ios::app);
stFileStream<<szTempBuf<<"\t"<<strLog<<endl;
stFileStream.close();
return true;
}
void ConvertUtf8ToGBK(CString &strUtf8)
{
int len= MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, NULL,0);
unsigned short * wszGBK = new unsigned short[len+1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)strUtf8, -1, (LPWSTR)wszGBK, len);
len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK=new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, (LPWSTR)wszGBK, -1, szGBK, len, NULL,NULL);
strUtf8 = szGBK;
delete[] szGBK;
delete[] wszGBK;
}
void ConvertGBKToUtf8(CString& strGBK)
{
int len=MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL,0);
unsigned short * wszUtf8 = new unsigned short[len+1];
memset(wszUtf8, 0, len * 2 + 2);
MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, (LPWSTR)wszUtf8, len);
len = WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)wszUtf8, -1, NULL, 0, NULL, NULL);
char *szUtf8=new char[len + 1];
memset(szUtf8, 0, len + 1);
WideCharToMultiByte (CP_UTF8, 0, (LPWSTR)wszUtf8, -1, szUtf8, len, NULL,NULL);
strGBK = szUtf8;
delete[] szUtf8;
delete[] wszUtf8;
}
char *FindMonth(char *original, int &mlen)
{
char *s_tmp = NULL;
if(s_tmp = strstr(original, "Jan"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_01"))) // <%IDS_AimParser_01%>"1月"
else if(s_tmp = strstr(original,"1月"))
mlen = 3;
else if(s_tmp = strstr(original, "Feb"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_02"))) // <%IDS_AimParser_02%>"2月"
else if(s_tmp = strstr(original,"2月"))
mlen = 3;
else if(s_tmp = strstr(original, "Mar"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_03"))) // <%IDS_AimParser_03%>"3月"
else if(s_tmp = strstr(original,"3月"))
mlen = 3;
else if(s_tmp = strstr(original, "Apr"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_04"))) // <%IDS_AimParser_04%>"4月"
else if(s_tmp = strstr(original,"4月"))
mlen = 3;
else if(s_tmp = strstr(original, "May"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_05"))) // <%IDS_AimParser_05%>"5月"
else if(s_tmp = strstr(original,"5月"))
mlen = 3;
else if(s_tmp = strstr(original, "Jun"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_06"))) // <%IDS_AimParser_06%>"6月"
else if(s_tmp = strstr(original,"6月"))
mlen = 3;
else if(s_tmp = strstr(original, "Jul"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_07"))) // <%IDS_AimParser_07%>"7月"
else if(s_tmp = strstr(original,"7月"))
mlen = 3;
else if(s_tmp = strstr(original, "Aug"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_08"))) // <%IDS_AimParser_08%>"8月"
else if(s_tmp = strstr(original,"8月"))
mlen = 3;
else if(s_tmp = strstr(original, "Sep"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_09"))) // <%IDS_AimParser_09%>"9月"
else if(s_tmp = strstr(original,"9月"))
mlen = 3;
else if(s_tmp = strstr(original, "Oct"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_10"))) // <%IDS_AimParser_10%>"10月"
else if(s_tmp = strstr(original,"10月"))
mlen = 4;
else if(s_tmp = strstr(original, "Nov"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_11"))) // <%IDS_AimParser_11%>"11月"
else if(s_tmp = strstr(original,"11月"))
mlen = 4;
else if(s_tmp = strstr(original, "Dec"))
mlen = 3;
//else if(s_tmp = strstr(original, FuncGetStringFromIDS("SV_MONTH", "MONTH_12"))) // <%IDS_AimParser_12%>"12月"
else if(s_tmp = strstr(original,"12月"))
mlen = 4;
else
mlen = 0;
return s_tmp;
}
extern "C" __declspec(dllexport) BOOL CpuParserTest(const char * szSource, const int nTelInfo, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
if(nTelInfo & 0x02)
{
int count = 1;
POSITION pos = lstString.FindIndex(0);
while(pos)
printf("Line %2.2d: %s<br>\r\n", count++, lstString.GetNext(pos));
printf("\r\n<br>");
fflush(stdout);
}
int nOsType = DFNParser_GetPrivateProfileInt("cpu", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"idle\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_13%>"), nIdle); // <%IDS_AimParser_13%>CPU 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_14%>"), nStart); // <%IDS_AimParser_14%>CPU 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_15%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_15%>CPU 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("%s(%%): %d",
FuncGetStringFromIDS("SV_CPU", "CPU_USED"), nValue);
// <%IDS_AimParser_16%>CPU使用率
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nWait = DFNParser_GetPrivateProfileInt("cpu", "wait", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"idle\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_17%>"), nIdle); // <%IDS_AimParser_17%>CPU 命令设置
printf("%s \"wait\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_18%>"), nWait); // <%IDS_AimParser_18%>CPU 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_19%>"), nStart); // <%IDS_AimParser_19%>CPU 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_20%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_20%>CPU 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nIdle, strOut1);
GetColumnFromLine(strTarget, nWait, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut1) - atoi((LPCTSTR)strOut2);
if(nValue < 0) nValue = 0;
strMsg.Format("%s(%%): %d",
FuncGetStringFromIDS("SV_CPU", "CPU_USED"),nValue);
// <%IDS_AimParser_21%>CPU使用率
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"idle\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_22%>"),nIdle); // <%IDS_AimParser_22%>CPU 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_23%>"),nStart); // <%IDS_AimParser_23%>CPU 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_24%>"),nReverse ? "true" : "false"); // <%IDS_AimParser_24%>CPU 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("%s(%%): %d",
FuncGetStringFromIDS("SV_CPU", "CPU_USED"),nValue);
// <%IDS_AimParser_25%>CPU使用率
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if (nOsType == 4) { // HPUX
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"idle\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_13%>"), nIdle); // <%IDS_AimParser_13%>CPU 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_14%>"), nStart); // <%IDS_AimParser_14%>CPU 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_15%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_15%>CPU 命令设置
fflush(stdout);
}
int nCount = 0;
int index = nStart;
while(1)
{
GetLineString(lstString, nReverse, index, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
break;
else {
char buff[256] = {0};
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg += FuncGetStringFromIDS("SV_CPU", "CPU_USED");
strMsg += "_";
strMsg += _itoa(nCount, buff, 10);
strMsg += ": ";
strMsg += _itoa(nValue, buff, 10);
strMsg += ", ";
//strMsg.Format("%s(%%): %d", FuncGetStringFromIDS("<%IDS_AimParser_16%>"), nValue); // <%IDS_AimParser_16%>CPU使用率
nCount ++;
}
index ++;
}
if(!strMsg.IsEmpty())
{
strMsg.Delete(strMsg.GetLength() - 2, 2);
char buff[256] = {0};
sprintf(buff, "%s_%d",
FuncGetStringFromIDS("SV_CPU", "CPU_USED"), nCount - 1);
if(nCount == 1)
{
strMsg.Replace(buff, FuncGetStringFromIDS("SV_CPU", "CPU_USED"));
}
else
{
char buff2[256] = {0};
sprintf(buff2, "%s_%s",
FuncGetStringFromIDS("SV_CPU", "CPU_USED"), "Average");
strMsg.Replace(buff, buff2);
}
strcpy(szOut, (LPCTSTR)strMsg);
}
else
{
bRet = FALSE;
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport) BOOL HP_CpuParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
int nOsType = DFNParser_GetPrivateProfileInt("cpu", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nWait = DFNParser_GetPrivateProfileInt("cpu", "wait", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nIdle, strOut1);
GetColumnFromLine(strTarget, nWait, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut1) - atoi((LPCTSTR)strOut2);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if (nOsType == 4) { // HPUX
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nWIO = DFNParser_GetPrivateProfileInt("cpu", "wio", 0, IniFileName);
int nUsr = DFNParser_GetPrivateProfileInt("cpu", "usr", 0, IniFileName);
int nSys = DFNParser_GetPrivateProfileInt("cpu", "sys", 0, IniFileName);
int nCount = 0;
int index = nStart;
int nUsedValue = 0;
CString strIdle = _T("");
CString strWIO = _T("");
CString strUsr = _T("");
CString strSys = _T("");
puts("hp");
while(1)
{
GetLineString(lstString, nReverse, index, strTarget);
GetColumnFromLine(strTarget, nIdle, strIdle);
GetColumnFromLine(strTarget, nWIO, strWIO);
GetColumnFromLine(strTarget, nUsr, strUsr);
GetColumnFromLine(strTarget, nSys, strSys);
if (strIdle.IsEmpty() || strWIO.IsEmpty() || strUsr.IsEmpty() || strSys.IsEmpty())
{
break;
}
else {
nUsedValue = 100 - atoi((LPCTSTR)strIdle) - atoi((LPCTSTR)strWIO);
if(nUsedValue < 0) nUsedValue = 0;
strMsg.Format("utilization=%d$sysper=%d$usrper=%d$wio=%d$idle=%d$",
nUsedValue, atoi((LPCTSTR)strSys), atoi((LPCTSTR)strUsr),
atoi((LPCTSTR)strWIO), atoi((LPCTSTR)strIdle));
strcpy(szOut, (LPCTSTR)strMsg);
// char buff[256] = {0};
// nValue = 100 - atoi((LPCTSTR)strOut);
// if(nValue < 0) nValue = 0;
// strMsg += "utilization";
// strMsg += _itoa(nCount, buff, 10);
// strMsg += "=";
// strMsg += _itoa(nValue, buff, 10);
// strMsg += "$";
// nCount ++;
}
index ++;
}
// if(!strMsg.IsEmpty())
// {
// char buff[256] = {0};
// sprintf(buff, "%s%d", "utilization", nCount - 1);
// strMsg.Replace(buff, "utilization");
//
// strcpy(szOut, (LPCTSTR)strMsg);
// }
// else
// {
// bRet = FALSE;
// }
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
#ifdef ZHUOWANG
//卓望使用的监测器,hp cpu特殊处理
extern "C" __declspec(dllexport)
BOOL CpuParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
//cout << "----------------------- CpuParser Start -----------------------" <<endl;
CString strFile = _T("CpuParser");
CString strLog = _T("");
//WriteLog(strFile,"----------------------- CpuParser Start -----------------------");
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("cpu", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
strLog.Format("nReverse=%d; nStart=%d; nIdle=%d",nReverse,nStart,nIdle);
WriteLog(strFile,strLog);
GetLineString(lstString, nReverse, nStart, strTarget);
cout << "strTarget:"<<strTarget<<endl;
strLog.Format("strTarget:%s",strTarget);
WriteLog(strFile,strTarget);
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"nIdle:"<< nIdle<<endl;
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else
{
cout << "strOut:" << strOut << endl;
strLog.Format("strOut:%s",strOut);
WriteLog(strFile, strLog);
nValue = 100 - atoi((LPCTSTR)strOut);
cout << "nValue:" << nValue << endl;
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nWait = DFNParser_GetPrivateProfileInt("cpu", "wait", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nIdle, strOut1);
GetColumnFromLine(strTarget, nWait, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut1) - atoi((LPCTSTR)strOut2);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if (nOsType == 4) { // HPUX
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nWIO = DFNParser_GetPrivateProfileInt("cpu", "wio", 0, IniFileName);
int nUsr = DFNParser_GetPrivateProfileInt("cpu", "usr", 0, IniFileName);
int nSys = DFNParser_GetPrivateProfileInt("cpu", "sys", 0, IniFileName);
int nCount = 0;
int index = nStart;
int nUsedValue = 0;
CString strIdle = _T("");
CString strWIO = _T("");
CString strUsr = _T("");
CString strSys = _T("");
puts("hp");
while(1)
{
GetLineString(lstString, nReverse, index, strTarget);
GetColumnFromLine(strTarget, nIdle, strIdle);
GetColumnFromLine(strTarget, nWIO, strWIO);
GetColumnFromLine(strTarget, nUsr, strUsr);
GetColumnFromLine(strTarget, nSys, strSys);
if (strIdle.IsEmpty() || strWIO.IsEmpty() || strUsr.IsEmpty() || strSys.IsEmpty())
{
break;
}
else {
nUsedValue = 100 - atoi((LPCTSTR)strIdle) - atoi((LPCTSTR)strWIO);
if(nUsedValue < 0) nUsedValue = 0;
strMsg.Format("utilization=%d$sysper=%d$usrper=%d$wio=%d$idle=%d$",
nUsedValue, atoi((LPCTSTR)strSys), atoi((LPCTSTR)strUsr),
atoi((LPCTSTR)strWIO), atoi((LPCTSTR)strIdle));
strcpy(szOut, (LPCTSTR)strMsg);
// char buff[256] = {0};
// nValue = 100 - atoi((LPCTSTR)strOut);
// if(nValue < 0) nValue = 0;
// strMsg += "utilization";
// strMsg += _itoa(nCount, buff, 10);
// strMsg += "=";
// strMsg += _itoa(nValue, buff, 10);
// strMsg += "$";
// nCount ++;
}
index ++;
}
// if(!strMsg.IsEmpty())
// {
// char buff[256] = {0};
// sprintf(buff, "%s%d", "utilization", nCount - 1);
// strMsg.Replace(buff, "utilization");
//
// strcpy(szOut, (LPCTSTR)strMsg);
// }
// else
// {
// bRet = FALSE;
// }
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
#else
//区分hp cpu和普通cpu
extern "C" __declspec(dllexport)
BOOL CpuParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
cout << "----------------------- CpuParser Start -----------------------" <<endl;
puts(szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "strTemp = " << strTemp << endl;
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("cpu", "ostype", 0, IniFileName);
if (nOsType == 1)
{ // Linux
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
//printf("%d -%d-%d\n",nReverse,nStart,nIdle);
//cout << "strTarget:"<<strTarget<<endl;
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"nIdle="<<nIdle<<endl;
/*start ***add by mtx************************************************************************************************/
//得到匹配列
int nMatchColumnLine = DFNParser_GetPrivateProfileInt("cpu", "matchColumnLine", 0, IniFileName);
char matchcolumnName[16] = {0};
DFNParser_GetPrivateProfileString("cpu", "matchcolumn", "", matchcolumnName, sizeof(matchcolumnName), IniFileName);
cout << "matchcolumnName:"<<matchcolumnName<<endl;
cout << "nMatchColumnLine:"<<nMatchColumnLine<<endl;
//判断是否有匹配列
if((matchcolumnName[0]>0) && (nMatchColumnLine>0))
{
int matchcolumn = 0;
//得到新的 dy:lstString 这里是只读。
if(GetMatchColumn(nMatchColumnLine,matchcolumnName,&lstString,matchcolumn))
{
nIdle = matchcolumn;
cout << "nIdle =" << nIdle <<endl;
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "新的strTemp = " << strTemp << endl;
}
}
}
/*end ***add by mtx************************************************************************************************/
GetLineString(lstString, nReverse, nStart, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
cout <<"strOut:" <<strOut <<endl;
if (strOut.IsEmpty())
bRet = FALSE;
else
{
nValue =100 - atoi((LPCTSTR)strOut);
//nValue = atoi((LPCTSTR)strOut); //直接只要use 的
cout <<"nValue:" <<strOut <<endl;
if(nValue < 0) nValue = 0;
//nValue = 100;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nWait = DFNParser_GetPrivateProfileInt("cpu", "wait", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nIdle, strOut1);
GetColumnFromLine(strTarget, nWait, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut1) - atoi((LPCTSTR)strOut2);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else {
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if (nOsType == 4)
{ // HPUX
int nReverse = DFNParser_GetPrivateProfileInt("cpu", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("cpu", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("cpu", "idle", 0, IniFileName);
int nCount = 0;
int index = nStart;
while(1)
{
GetLineString(lstString, nReverse, index, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
break;
else {
char buff[256] = {0};
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg += "utilization";
strMsg += _itoa(nCount, buff, 10);
strMsg += "=";
strMsg += _itoa(nValue, buff, 10);
strMsg += "$";
nCount ++;
}
index ++;
}
if(!strMsg.IsEmpty())
{
char buff[256] = {0};
sprintf(buff, "%s%d", "utilization", nCount - 1);
strMsg.Replace(buff, "utilization");
strcpy(szOut, (LPCTSTR)strMsg);
}
else
{
bRet = FALSE;
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
#endif
extern "C" __declspec(dllexport)
BOOL GetMatchColumn(const int nMatchColumnLine,const char * matchcolumnName,const CStringList* pList,int &matchcolumn)
{
if(!pList)
return FALSE;
POSITION pos = pList->GetHeadPosition();
int i = 0;
while (pos)
{
i++;
CString sTemp = pList->GetNext(pos);
if(i == nMatchColumnLine)
{
char szSrc[1024]={0};
strcpy(szSrc, (LPCTSTR)sTemp);
cout << "szSrc =" << szSrc << endl;
if(_GetMatchColumn(szSrc,matchcolumnName,matchcolumn))
return TRUE;
break;
}
}
return FALSE;
}
BOOL _GetMatchColumn(const char *szSrc,const char *szName, int &nMatchColumn)
{
char *t_szSrc = strdup(szSrc);
char *t_szName = strdup(szName);
char *s_tmp = t_szSrc;
char *s_tmp1 = NULL;
//去掉空格
while(*s_tmp == 32)
{
s_tmp++;
}
int nPos = 0;
while(1){
if(s_tmp1 = strstr(s_tmp, " "))
{
nPos++;
//去掉空格
int nSpace = 0;
while(*s_tmp1 == 32)
{
nSpace++;
s_tmp1++;
}
//得到每一列的名称长度
int nLen = s_tmp1 - s_tmp - nSpace;
//得到列名
char cTemp[16]={0};
strncpy(cTemp, s_tmp, nLen);
//比较
if(!strcmp(cTemp,szName))
{
//判断列名后的空格
if (*(s_tmp+nLen) == 32)
{
nMatchColumn = nPos;
free(t_szSrc);
free(t_szName);
return TRUE;
}
}
s_tmp = s_tmp1;
}
else
{
//当为最后一列时
if(!strcmp(s_tmp,szName))
{
nPos++;
nMatchColumn = nPos;
free(t_szSrc);
free(t_szName);
return TRUE;
}
break;
}
}
free(t_szSrc);
free(t_szName);
return TRUE;
}
extern "C" __declspec(dllexport)
BOOL FileParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
int nOsType = DFNParser_GetPrivateProfileInt("file", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nStart = DFNParser_GetPrivateProfileInt("file", "startline", 0, IniFileName);
int nMode = DFNParser_GetPrivateProfileInt("file", "mode", 0, IniFileName);
int nName = DFNParser_GetPrivateProfileInt("file", "name", 0, IniFileName);
int nReverse = DFNParser_GetPrivateProfileInt("file", "reverselines", 0, IniFileName);
int i = nStart;
while(1)
{
GetLineString(lstString, nReverse, i++, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nMode, strOut1);
GetColumnFromLine(strTarget, nName, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
break;
else
{
if(strOut1.GetAt(0) == 'd')
continue;
sprintf(szOut, "%s%s$$$", szOut, strOut2);
}
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
BOOL GetBufferByNewMatchLine(const char * szSource, const int nMonitorType,char*IniFileName,char**buffer)
{
char *Source = NULL;
char matchLine[16] = {0};
Source = strdup(szSource);
if (Source)
{
if (nMonitorType == CPU_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("cpu", "matchLine1", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == DISK_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("disk", "matchLine1", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == MEMORY_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("memory", "matchLine1", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == SERVICE_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("service", "matchLine1", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == DISKS_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("disks", "matchLine1", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == FILE_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("file", "matchLine1", "", matchLine, sizeof(matchLine), IniFileName);
}
else
{
}
//////////////////////////////////////////////////////////////////////////
//lish
//CString strFileName = "GetBufferByNewMatchLine";
//CString strLog ="";
//WriteLog(strFileName,"============== GetBufferByNewMatchLine Start ==============");
//strLog.Format("matchLine=%s",matchLine);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
//Linux5
//if ( (nMonitorType == DISK_TYPE_MONITOR) && (strcmp(IniFileName,"Linux")== 0))
//{
// CString strNewMatch = matchLine;
// ConvertGBKToUtf8(strNewMatch);
// *buffer = strstr(Source, strNewMatch);
// //////////////////////////////////////////////////////////////////////////
// //lish
// //strLog.Format("buffer=%s",*buffer);
// //WriteLog(strFileName, strLog);
// //////////////////////////////////////////////////////////////////////////
// if(!*buffer)
// return FALSE;
// else
// return TRUE;
//}
*buffer = strstr(Source, matchLine);
if(!*buffer)
return FALSE;
else
return TRUE;
}
else
return FALSE;
return TRUE;
}
BOOL FormatSource(const char * szSource, const int nMonitorType, CStringList& lstStr,char*IniFileName)
{
WriteLog("============== FormatSource ==============");
//////////////////////////////////////////////////////////////////////////
//lish
CString strFileName = "FormatSource";
CString strLog ="";
//WriteLog(strFileName,"============== FormatSource Start ==============");
//////////////////////////////////////////////////////////////////////////
BOOL bRet = FALSE;
char *Source = NULL;
char *buffer = NULL;
char matchLine[16] = {0};
Source = strdup(szSource);
if (Source)
{
if (nMonitorType == CPU_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("cpu", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == DISK_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("disk", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == MEMORY_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("memory", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == SERVICE_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("service", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == USER_CPU_MONITOR)
{
DFNParser_GetPrivateProfileString("usercpu", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == DISKS_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("disks", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == FILE_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("file", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if(nMonitorType == FREE_PMEMORY)
{
DFNParser_GetPrivateProfileString("totalPhysicalMemory", "matchline","",matchLine,sizeof(matchLine), IniFileName);
}
else if(nMonitorType == MULCPU_TYPE_MONITOR)//获取多核利用率 dy 2010.5.24
{
DFNParser_GetPrivateProfileString("mulcpus","matchline","",matchLine,sizeof(matchLine), IniFileName);
}
else if(nMonitorType == MULCPUS_TYPE_MONITOR)//获取多核CPU序列
{
DFNParser_GetPrivateProfileString("mulcpus","matchline","",matchLine,sizeof(matchLine), IniFileName);
}
else if (nMonitorType == DISKSIO_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("diskio","matchline","",matchLine,sizeof(matchLine), IniFileName);
}
else if (nMonitorType == SWAP_TYPE_MONITOR)
{
DFNParser_GetPrivateProfileString("swap", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == ARCSDE_STATUS_MONITOR)
{
DFNParser_GetPrivateProfileString("arcsdeStatus", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == ARCSDE_USER_MONITOR)
{
DFNParser_GetPrivateProfileString("arcsdeUser", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == AIX_ERRPT_LIST_MONITOR)
{
DFNParser_GetPrivateProfileString("errpt", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == AIX_ERRPT_DETAIL_MONITOR)
{
DFNParser_GetPrivateProfileString("errptDetail", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else if (nMonitorType == AIX_ERRPT_LIST_MONITOR)
{
DFNParser_GetPrivateProfileString("errpt", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
}
else
{
}
buffer = strstr(Source, matchLine);
printf("matchline matchLine = %s\n",matchLine);
//printf("matchline Source = %s\n",Source);
printf("matchline buffer = %s\n",buffer);
//////////////////////////////////////////////////////////////////////////
//lish
//strLog.Format("第一次取值:matchLine=%s,buffer=%s",matchLine,buffer);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
if (nMonitorType == FREE_PMEMORY)
{
CString strFile = _T("FREE_PMEMORY");
WriteLog(strFile,"--------------- FormatSource --------------- ");
strLog.Format("\nmatchLine=%s\nbuffer=%s",matchLine,buffer);
WriteLog(strFileName,strLog);
}
/*start ***add by mtx************************************************************************************************/
if(!buffer)
{
char* bufferTemp;
GetBufferByNewMatchLine(szSource,nMonitorType,IniFileName,&buffer);
//Linux5 获取磁盘 显示中文 lish
if (nMonitorType == DISK_TYPE_MONITOR && (strcmp(IniFileName,"Linux") == 0) )
{
CString strGBK = Source;
CString matchLineNew = "文件系统";
buffer = strstr(strGBK, matchLineNew);
if (!buffer)
{
ConvertGBKToUtf8(matchLineNew);
buffer = strstr(strGBK, matchLineNew);
}
//////////////////////////////////////////////////////////////////////////
//lish
//strLog.Format("第二次取值:matchLine=%s,buffer=%s,strGBK=%s",matchLineNew,buffer,strGBK);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
}
}
if(!buffer)
return FALSE;
/*end ***add by mtx************************************************************************************************/
if(buffer)
{
char *s_original = buffer;
char *s_derive = NULL;
char *s_derive2 = NULL;
//while ((s_derive = strchr(s_original,char_return))) { // for telnet
//while ((s_derive = strchr(s_original,char_newline))) { // just for debug from file and SSH
while (1)
{
s_derive = strchr(s_original, char_return);
s_derive2 = strchr(s_original, char_newline);
//puts(s_derive);
//puts(s_derive2);
//WriteLog("s_derive:");
//WriteLog(s_derive);
//WriteLog("s_derive2:");
//WriteLog(s_derive2);
if(s_derive && s_derive2)
{
if(s_derive2 < s_derive)
s_derive = s_derive2;
}
else if(s_derive2 && !s_derive)
{
s_derive = s_derive2;
}
else if(!s_derive2 && s_derive)
{
}
else
{
break;
}
// if (!(s_derive = strchr(s_original,char_return))) // for telnet
// if (!(s_derive = strchr(s_original,char_newline))) // just for debug from file or SSH
// break;
/*if (!(s_derive = strstr(s_original,"\r\n"))) // just for debug
break;*/
s_original[s_derive-s_original] = 0;
if(nMonitorType == SERVICE_TYPE_MONITOR)
{
int mlen = 0;
char *s_tmp = FindMonth(s_original, mlen);
while(s_tmp && *(s_tmp + mlen) == ' ')
{
*(s_tmp + mlen) = '+';
mlen ++;
}
}
if (nMonitorType == PROCESS_TYPE_MONITOR)
{
int mlen = 0;
char *s_tmp = FindMonth(s_original, mlen);
while(s_tmp && *(s_tmp + mlen) == ' ')
{
*(s_tmp + mlen) = '+';
mlen ++;
}
}
if(nMonitorType == MEMORY_TYPE_MONITOR )
{
{
char *s_tmp = NULL;
while(s_tmp = strstr(s_original, ","))
{
*(s_tmp) = ' ';
*(s_tmp + 1) = ' ';
}
}
}
WriteLog( "\nline:\n" );
WriteLog( s_original );
lstStr.AddTail(s_original);
s_derive += 1;
while (1)
{
if (s_derive[0] == char_newline || s_derive[0] == char_return)
s_derive += 1;
else
break;
}
s_original = s_derive;
}
lstStr.AddTail(s_original);
bRet = TRUE;
}
free(Source);
}
return bRet;
}
void GetLastLineString(const CStringList& lstStr,CString& strOut)
{
int nCount = lstStr.GetCount();
POSITION pos = NULL;
pos = lstStr.GetHeadPosition();
while(pos)
{
strOut = lstStr.GetNext(pos);
//WriteLog("GetLastLineString",strOut);
nCount --;
if (nCount ==1)
{
//WriteLog("GetLastLineString",strOut);
break;
}
}
}
void GetLineString(const CStringList& lstStr, const int nReverse, int nStart, CString& strOut)
{
POSITION pos = NULL;
if (nReverse)
{
pos = lstStr.GetTailPosition();
while (pos)
{
strOut = lstStr.GetPrev(pos);
nStart--;
if (nStart == 0)
break;
}
}
else
{
pos = lstStr.GetHeadPosition();
while (pos)
{
strOut = lstStr.GetNext(pos);
nStart--;
if (nStart == 0)
break;
}
}
return;
}
void GetColumnFromLine(CString& strIn, int nColumn, CString& strOut, int nMonitorType)
{
strOut = _T("");
int nLen = strIn.GetLength();
TCHAR ch;
CString str = _T("");
if(nColumn == 999)
{
int index = strIn.ReverseFind(' ');
if(index >= 0)
strOut = strIn.Right(strIn.GetLength() - index - 1);
}
else
{
for (int i = 0; i < nLen; i++)
{
ch = strIn.GetAt(i);
if (ch == char_space)
continue;
nColumn--;
str = strIn.Right(nLen - i);
str = str.SpanExcluding(" ");
/*if (nColumn == 4) {
int nFound = str.Find(":", 0);
if (nFound >=0)
nColumn --;
}*/
if (nColumn == 0)
{
if (nMonitorType == SERVICE_TYPE_MONITOR || nMonitorType == PROCESS_TYPE_MONITOR || nMonitorType == AIX_ERRPT_LIST_MONITOR)
{
char *p = strIn.GetBuffer(strIn.GetLength());
strOut = p+i;
strIn.ReleaseBuffer();
}
else
{
strOut = str;
}
break;
}
i += str.GetLength();
}
}
return;
}
extern "C" __declspec(dllexport) BOOL MemoryParserTest(const char * szSource, const int nTelInfo, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strTarget2 = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
if(nTelInfo & 0x02)
{
int count = 1;
POSITION pos = lstString.FindIndex(0);
while(pos)
printf("%s %2.2d: %s<br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_26%>"),count++, lstString.GetNext(pos)); // <%IDS_AimParser_26%>行
printf("<br>\r\n");
fflush(stdout);
}
int nOsType = DFNParser_GetPrivateProfileInt("memory", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"used\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_27%>"), nUsed); // <%IDS_AimParser_27%>内存 命令设置
printf("%s \"total\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_28%>"), nTotal); // <%IDS_AimParser_28%>内存 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_29%>"), nStart); // <%IDS_AimParser_29%>内存 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_30%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_30%>内存 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%dk", &nUsed);
sscanf((LPCTSTR)strOut2, "%dk", &nTotal);
float fRate = (float)(100.0 * nUsed / (1.0 * nTotal));
float fMbFree = (float)((nTotal - nUsed) / (1.0 * 1024 * 1024));
strMsg.Format("%s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_USED"), fRate,
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_FREED"), fMbFree);
// <%IDS_AimParser_31%>Memory使用率,<%IDS_AimParser_32%>Memory剩余
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
int nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"used\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_33%>"), nUsed); // <%IDS_AimParser_33%>内存 命令设置
printf("%s \"free\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_34%>"), nFree); // <%IDS_AimParser_34%>内存 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_35%>"), nStart); // <%IDS_AimParser_35%>内存 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_36%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_36%>内存 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%dk", &nUsed);
sscanf((LPCTSTR)strOut2, "%dk", &nFree);
float fRate = (float)(100.0 * nUsed / (1.0 * (nUsed + nFree)));
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_USED"), fRate,
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_FREED"), fMbFree);
// <%IDS_AimParser_37%>Memory使用率,<%IDS_AimParser_38%>Memory剩余
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"total\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_39%>"), nTotal); // <%IDS_AimParser_39%>内存 命令设置
printf("%s \"free\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_40%>"), nFree); // <%IDS_AimParser_40%>内存 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_41%>"), nStart); // <%IDS_AimParser_41%>内存 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_42%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_42%>内存 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
float fRate = (float)(100.0 * (nTotal - nFree) / (1.0 * nTotal));
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s(%%): %.2f %s: %.2f", FuncGetStringFromIDS("SV_MEMORY",
"MEMORY_USED"), fRate,
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_FREED"), fMbFree);
// <%IDS_AimParser_43%>Memory使用率,<%IDS_AimParser_44%>Memory剩余
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 4) { // compatible with digital os
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nFreeLine = DFNParser_GetPrivateProfileInt("memory", "freeLine", 0, IniFileName);
long nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
int nTotalLine = DFNParser_GetPrivateProfileInt("memory", "totalLine", 0, IniFileName);
long nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
long nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"totalline\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_45%>"), nTotalLine); // <%IDS_AimParser_45%>内存 命令设置
printf("%s \"total\": %ld <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_46%>"), nTotal); // <%IDS_AimParser_46%>内存 命令设置
printf("%s \"freeline\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_47%>"), nFreeLine); // <%IDS_AimParser_47%>内存 命令设置
printf("%s \"free\": %ld <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_48%>"), nFree); // <%IDS_AimParser_48%>内存 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_49%>"), nStart); // <%IDS_AimParser_49%>内存 命令设置
printf("%s \"swapunit\": %ld <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_50%>"), nSwapUnit); // <%IDS_AimParser_50%>内存 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_51%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_51%>内存 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nFreeLine, strTarget);
GetLineString(lstString, nReverse, nTotalLine, strTarget2);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget2, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%ld", &nFree);
sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
float fRate = (float)(100.0 * (nTotal - nFree) / (1.0 * nTotal));
float fMbFree = (float)(nFree * nSwapUnit / (1.0 * 1024 * 1024));
strMsg.Format("%s(%%): %.2f %s: %.2f", FuncGetStringFromIDS("SV_MEMORY",
"MEMORY_USED"), fRate,
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_FREED"), fMbFree);
// <%IDS_AimParser_52%>Memory使用率,<%IDS_AimParser_53%>Memory剩余
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 5)
{
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
long nUsePercent = DFNParser_GetPrivateProfileInt("memory", "usePercent", 0, IniFileName);
long nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"use percent\": %ld <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_54%>"), nUsePercent); // <%IDS_AimParser_54%>内存 命令设置
printf("%s \"total\": %ld <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_55%>"), nTotal); // <%IDS_AimParser_55%>内存 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_56%>"), nStart); // <%IDS_AimParser_56%>内存 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_57%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_57%>内存 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsePercent, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%ld", &nUsePercent);
sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
float fRate = (float)(1.0 * nUsePercent);
float fMbFree = (float)(nTotal * (100 - fRate) / 100.0);
strMsg.Format("%s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_USED"), fRate,
FuncGetStringFromIDS("SV_MEMORY", "MEMORY_FREED"), fMbFree);
// <%IDS_AimParser_58%>Memory使用率,<%IDS_AimParser_59%>Memory剩余
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL MemoryParser(const char * szSource, const int nMonitorType, char *szOut,
const char *FileName)
{
cout << "---------------- Call MemoryParser --------------" << endl;
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strTarget2 = _T("");
CString strMsg = _T("");
int nValue = 0;
double dwUsed=0 , dwTotal=0 ,dwFree = 0 , dwUsePercent=0;
// szSource = "总数: 分配了 1000000K + 保留 5000K = 使用 1005000K, 5000000K 可使用";
bRet = FormatSource(szSource, nMonitorType, lstString, IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("memory", "ostype", 0, IniFileName);
if (nOsType == 1)
{ // Linux
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else
{
//float
dwUsed = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
if(nTotal == 0)
{
bRet = FALSE;
}
else
{
float fRate = (float)(100 * dwUsed / (1.0 * dwTotal));
float fMbFree = (float)((dwTotal - dwUsed) / (1.0 * 1024 * 1024));
float fMbTotal = (float)(dwTotal/(1.0* 1024 * 1024));
//float fMbTotal = (float)(nTotal/(1.0 * 1024 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$TotalMemory=%.2f$pagesPerSec=0.0$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
cout << "nUsed:" << nUsed <<endl;
cout << "nFree:" << nFree <<endl;
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
cout << "strOut1:" << strOut1 << endl;
cout << "strOut2:" << strOut2 << endl;
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else
{
dwUsed = atof(strOut1);///1024;
dwFree = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
//sscanf((LPCTSTR)strOut1, "%dk", &nUsed);
//sscanf((LPCTSTR)strOut2, "%dk", &nFree);
float fRate = (float)(100.0 * dwUsed / (1.0 * (dwUsed + dwFree)));
float fMbFree = (float)(dwFree / (1.0 * 1024));
//float fMbTotal = (float)(nUsed+nFree)/(1.0* 1000 * 1024);
float fMbTotal = (float)((dwUsed+dwFree)/(1.0 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%d", &nFree);
//sscanf((LPCTSTR)strOut2, "%d", &nTotal);
dwFree = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(100.0 * (dwTotal - dwFree) / (1.0 * dwTotal));
float fMbFree = (float)(dwFree / (1.0 * 1024));
//float fMbTotal = (float)nTotal/(1.0* 1000 * 1024);
float fMbTotal = (float)(dwTotal/(1.0 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 4) { // compatible with digital os
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nFreeLine = DFNParser_GetPrivateProfileInt("memory", "freeLine", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
int nTotalLine = DFNParser_GetPrivateProfileInt("memory", "totalLine", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
cout << "szSource:\n" << szSource << endl;
GetLineString(lstString, nReverse, nFreeLine, strTarget);
GetLineString(lstString, nReverse, nTotalLine, strTarget2);
CString strTemp = _T("");
strTemp.Format("nReverse=%d; nStart=%d; nFreeLine=%d; nFree=%d; nTotalLine=%d; nTotal=%d; nSwapUnit=%d",
nReverse,nStart,nFreeLine,nFree,nTotalLine,nTotal,nSwapUnit);
cout << strTemp << endl;
cout << "strTarget:" << strTarget << endl;
cout << "strTarget2:" << strTarget2 << endl;
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget2, nTotal, strOut2);
cout << "strOut1:" << strOut1 << endl;
cout << "strOut2:" << strOut2 << endl;
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%ld", &nFree);
//sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
dwFree = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(100.0 * (dwTotal - dwFree) / (1.0 * dwTotal));
float fMbFree = (float)(dwFree * nSwapUnit / (1.0 * 1024 * 1024));
float fMbTotal = (float)(dwTotal* nSwapUnit /(1.0* 1024 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 5)
{ //aix
printf("MemoryParser aix\n");
int nTotalSize = DFNParser_GetPrivateProfileInt("memory", "size", 0, IniFileName);
int nInuse = DFNParser_GetPrivateProfileInt("memory", "inuse", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nPin = DFNParser_GetPrivateProfileInt("memory", "pin", 0, IniFileName);
UINT nVirtual = DFNParser_GetPrivateProfileInt("memory", "virtual", 0, IniFileName);
UINT nInuse_work = DFNParser_GetPrivateProfileInt("memory", "inuse_work", 0, IniFileName);
UINT nInuse_clnt = DFNParser_GetPrivateProfileInt("memory", "inuse_clnt", 0, IniFileName);
printf("nTotalSize = %d, %d, %d, %d, %d,%d,%d\n",nTotalSize,nInuse,
nFree,nPin,nVirtual,nInuse_work,nInuse_clnt);
GetLineString(lstString, 0, 1, strTarget);
printf("strTarget = %s\n",strTarget.GetBuffer(0));
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
CString strOut4 = _T("");
CString strOut5 = _T("");
CString strOut6 = _T("");
CString strOut7 = _T("");
GetColumnFromLine(strTarget, nTotalSize, strOut1);
GetColumnFromLine(strTarget, nInuse, strOut2);
GetColumnFromLine(strTarget, nFree, strOut3);
GetColumnFromLine(strTarget, nPin, strOut4);
GetColumnFromLine(strTarget, nVirtual, strOut5);
printf("strOut1 = %s\n",strOut1.GetBuffer(0));
printf("strOut2 = %s\n",strOut2.GetBuffer(0));
printf("strOut3 = %s\n",strOut3.GetBuffer(0));
printf("strOut4 = %s\n",strOut4.GetBuffer(0));
printf("strOut5 = %s\n",strOut5.GetBuffer(0));
GetLineString(lstString, 0, 5, strTarget);
printf("two strTarget = %s\n",strTarget.GetBuffer(0));
GetColumnFromLine(strTarget, nInuse_work, strOut6);
GetColumnFromLine(strTarget, nInuse_clnt, strOut7);
printf("strOut6 = %s\n",strOut6.GetBuffer(0));
printf("strOut7 = %s\n",strOut7.GetBuffer(0));
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else
{
dwUsePercent=0;
dwTotal = atof(strOut1)*4/1024;
dwUsed = atof(strOut2)*4/1024;
dwFree = atof(strOut3)*4/1024;
dwUsePercent = dwUsed / dwTotal;
float dwPin = atof(strOut4)*4/1024;
float dwVirtual = atof(strOut5)*4/1024;
float dwWorkInUseMemory = atof(strOut6)*4/1024;
float dwClntMemory = atof(strOut7)*4/1024;
if (dwUsePercent<0 || dwTotal==0 || dwUsed==0)
{
bRet = FALSE;
}
else
{
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$TotalMemory=%.2f$useMemory=%.2f$pinMemory=%.2f$virtualMemory=%.2f$workInUseMemory=%.2f$clntMemory=%.2f$",
dwUsePercent*100, dwFree, dwTotal,dwUsed,dwPin,dwVirtual,dwWorkInUseMemory,dwClntMemory);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 6) { // UNIX WARE 内存解析
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
dwUsed = atof(strOut1);///1024;
dwFree = atof(strOut2);///1024;
float fRate = (float)(100.0 * dwUsed / (1.0 * (dwUsed + dwFree)));
float fMbFree = (float)(dwFree / (1.0 * 1024));
fMbFree = fMbFree/2;
float fMbTotal = (float)((dwUsed+dwFree)/(1.0 * 1024));
fMbTotal = fMbTotal/2;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
//swap分区2010-09-28dy
extern "C" __declspec(dllexport)
BOOL SwapParser(const char * szSource, const int nMonitorType, char *szOut,
const char *FileName)
{
cout << "---------------- Call SwapParser --------------" << endl;
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strTarget2 = _T("");
CString strMsg = _T("");
int nValue = 0;
double dwUsed=0 , dwTotal=0 ,dwFree = 0 , dwUsePercent=0;
// szSource = "总数: 分配了 1000000K + 保留 5000K = 使用 1005000K, 5000000K 可使用";
bRet = FormatSource(szSource, nMonitorType, lstString, IniFileName);
if (bRet) {
int nOsType = DFNParser_GetPrivateProfileInt("swap", "ostype", 0, IniFileName);
if (nOsType == 1)
{ // Linux
int nReverse = DFNParser_GetPrivateProfileInt("swap", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("swap", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("swap", "used", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("swap", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
printf("strOut1 = %s", strOut1.GetBuffer(strOut1.GetLength()));
printf("strOut2 = %s", strOut2.GetBuffer(strOut2.GetLength()));
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else
{
//float
dwUsed = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
if(nTotal == 0)
{
bRet = FALSE;
}
else
{
float fRate = (float)(100 * dwUsed / (1.0 * dwTotal));
float fMbFree = (float)((dwTotal - dwUsed) / (1.0 * 1024 * 1024));
float fMbTotal = (float)(dwTotal/(1.0* 1024 * 1024));
//float fMbTotal = (float)(nTotal/(1.0 * 1024 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$TotalMemory=%.2f$pagesPerSec=0.0$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("swap", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("swap", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("swap", "used", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("swap", "free", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("swap", "swapunit", 0, IniFileName);
cout << "nUsed:" << nUsed <<endl;
cout << "nFree:" << nFree <<endl;
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
cout << "strOut1:" << strOut1 << endl;
cout << "strOut2:" << strOut2 << endl;
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else
{
dwUsed = atof(strOut1);///1024;
dwFree = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
//sscanf((LPCTSTR)strOut1, "%dk", &nUsed);
//sscanf((LPCTSTR)strOut2, "%dk", &nFree);
float fRate = (float)(100.0 * dwUsed / (1.0 * (dwUsed + dwFree)));
float fMbFree = (float)(dwFree / (1.0 * 1024));
//float fMbTotal = (float)(nUsed+nFree)/(1.0* 1000 * 1024);
float fMbTotal = (float)((dwUsed+dwFree)/(1.0 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("swap", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("swap", "startline", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("swap", "free", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("swap", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%d", &nFree);
//sscanf((LPCTSTR)strOut2, "%d", &nTotal);
dwFree = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(100.0 * (dwTotal - dwFree) / (1.0 * dwTotal));
float fMbFree = (float)(dwFree / (1.0 * 1024));
//float fMbTotal = (float)nTotal/(1.0* 1000 * 1024);
float fMbTotal = (float)(dwTotal/(1.0 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 4) { // compatible with digital os
int nReverse = DFNParser_GetPrivateProfileInt("swap", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("swap", "startline", 0, IniFileName);
int nFreeLine = DFNParser_GetPrivateProfileInt("swap", "freeLine", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("swap", "free", 0, IniFileName);
int nTotalLine = DFNParser_GetPrivateProfileInt("swap", "totalLine", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("swap", "total", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("swap", "swapunit", 0, IniFileName);
cout << "szSource:\n" << szSource << endl;
GetLineString(lstString, nReverse, nFreeLine, strTarget);
GetLineString(lstString, nReverse, nTotalLine, strTarget2);
CString strTemp = _T("");
strTemp.Format("nReverse=%d; nStart=%d; nFreeLine=%d; nFree=%d; nTotalLine=%d; nTotal=%d; nSwapUnit=%d",
nReverse,nStart,nFreeLine,nFree,nTotalLine,nTotal,nSwapUnit);
cout << strTemp << endl;
cout << "strTarget:" << strTarget << endl;
cout << "strTarget2:" << strTarget2 << endl;
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget2, nTotal, strOut2);
cout << "strOut1:" << strOut1 << endl;
cout << "strOut2:" << strOut2 << endl;
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%ld", &nFree);
//sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
dwFree = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(100.0 * (dwTotal - dwFree) / (1.0 * dwTotal));
float fMbFree = (float)(dwFree * nSwapUnit / (1.0 * 1024 * 1024));
float fMbTotal = (float)(dwTotal* nSwapUnit /(1.0* 1024 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 5)
{
int nReverse = DFNParser_GetPrivateProfileInt("swap", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("swap", "startline", 0, IniFileName);
UINT nUsePercent = DFNParser_GetPrivateProfileInt("swap", "usePercent", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("swap", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsePercent, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%ld", &nUsePercent);
//sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
dwUsePercent = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(1.0 * dwUsePercent);
float fMbFree = (float)(dwTotal * (100 - fRate) / 100.0);
//float fMbTotal = (float)nTotal/(1.0* 1000 * 1024);
//float fMbTotal = (float)nTotal/(1.0 * 1024);
float fMbTotal = (float)dwTotal;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 6) { // UNIX WARE 内存解析
int nReverse = DFNParser_GetPrivateProfileInt("swap", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("swap", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("swap", "used", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("swap", "free", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("swap", "swapunit", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
dwUsed = atof(strOut1);///1024;
dwFree = atof(strOut2);///1024;
float fRate = (float)(100.0 * dwUsed / (1.0 * (dwUsed + dwFree)));
float fMbFree = (float)(dwFree / (1.0 * 1024));
fMbFree = fMbFree/2;
float fMbTotal = (float)((dwUsed+dwFree)/(1.0 * 1024));
fMbTotal = fMbTotal/2;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL PMemoryParser(const char * szSource, const int nMonitorType, char *szOut,
const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
//mtx???
//strcpy(IniFileName,"C:\\SITEVIEW6\\SiteView.DataCollection.WebService\\MonitorManager\\templates.os\\Linux.cmd");
CStringList lstString;
CString strTarget = _T("");
CString strTarget2 = _T("");
CString strMsg = _T("");
int nValue = 0;
double dwUsed=0 , dwTotal=0 ,dwFree = 0 , dwUsePercent=0;
double dwCached = 0;
double dwBuffers = 0;
// szSource = "总数: 分配了 1000000K + 保留 5000K = 使用 1005000K, 5000000K 可使用";
bRet = FormatSource(szSource, nMonitorType, lstString, IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("memory", "ostype", 0, IniFileName);
//单独使用PhysicalMemory的ostype,而不是用memory,不改动以前的 yi.duan 2012-02-15
int nPhysicalMemoryOsType = DFNParser_GetPrivateProfileInt("PhysicalMemory", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("physicalmemory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("physicalmemory", "startline", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("physicalmemory", "total", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("physicalmemory", "free", 0, IniFileName);
UINT nCached = DFNParser_GetPrivateProfileInt("physicalmemory", "cached", 0, IniFileName);
UINT nBuffers = DFNParser_GetPrivateProfileInt("physicalmemory", "buffers", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
CString strOut4 = _T("");
GetColumnFromLine(strTarget, nTotal, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
GetColumnFromLine(strTarget, nCached, strOut3);
GetColumnFromLine(strTarget, nBuffers, strOut4);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else
{
//float
dwTotal = atof(strOut1);///1024;
dwFree = atof(strOut2);
dwCached = atof(strOut3);
dwBuffers = atof(strOut4);
dwFree += dwCached;
dwFree += dwBuffers;
dwUsed = dwTotal - dwFree;
if(nTotal == 0)
{
bRet = FALSE;
}
else
{
float fRate = (float)(dwUsed / (1.0 * dwTotal));
fRate = fRate*100;
float fMbFree = (float)(dwFree / (1.0 * 1024));
fMbFree = fMbFree/1024;
float fMbTotal = (float)(dwTotal/(1.0* 1024));
fMbTotal = fMbTotal/1024;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 2)
{ // Solaris
//-----------------------------------------------------------------------------------------------------------
// 更改内容:针对solaris的物理内存信息采取两步获取(prtconf:总物理内存,vmstat:剩余物理内存)
// 更改人:邹晓
// 更改时间:2009.02.25
//-----------------------------------------------------------------------------------------------------------
if( nMonitorType == TOTAL_PMEMORY )
{
int nReverse = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "reverselines", 0, IniFileName );
int nStart = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "startline", 0, IniFileName );
UINT nTotal = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "value", 0, IniFileName );
UINT nUnit = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "unit", 0, IniFileName );
GetLineString( lstString, nReverse, nStart, strTarget );
CString strOut = _T( "" );
GetColumnFromLine( strTarget, nTotal, strOut );
if( strOut.IsEmpty() )
bRet = FALSE;
else
{
float fTotalMemory = atof( strOut );
fTotalMemory = fTotalMemory * (float)nUnit;
strMsg.Format("totalMemory=%.2f$", fTotalMemory );
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if( nMonitorType == FREE_PMEMORY )
{
int nReverse = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "reverselines", 0, IniFileName );
int nStart = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "startline", 0, IniFileName );
UINT nFree = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "value", 0, IniFileName );
UINT nUnit = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "unit", 0, IniFileName );
GetLineString( lstString, nReverse, nStart, strTarget );
CString strOut = _T( "" );
GetColumnFromLine( strTarget, nFree, strOut );
if( strOut.IsEmpty() )
bRet = FALSE;
else
{
float fFreeMemory = atof( strOut );
fFreeMemory = fFreeMemory * (float)nUnit;
strMsg.Format("freeMemory=%.2f$", fFreeMemory );
strcpy(szOut, (LPCTSTR)strMsg);
}
}// 结束更改
else
{
int nReverse = DFNParser_GetPrivateProfileInt("physicalmemory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("physicalmemory", "startline", 0, IniFileName);
UINT nReal = DFNParser_GetPrivateProfileInt("physicalmemory", "real", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("physicalmemory", "free", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("physicalmemory", "memunit", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nReal, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
dwFree = atof(strOut2);
float fMbFree = (float)(dwFree / (1.0 * 1024));
float fMbTotal = atof(strOut1);
float fRate = (fMbTotal- fMbFree)/ fMbTotal;
fRate = fRate*100;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 3)
{ // FreeBSD and hp
if(nPhysicalMemoryOsType == 6)//hp yi.duan 2012-02-15
{
cout << "===========================" << endl;
if( nMonitorType == TOTAL_PMEMORY )
{
int nStart = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "startline", 0, IniFileName );
int nReverse = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "reverselines", 0, IniFileName );
UINT nUnit = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "unit", 0, IniFileName );
UINT nTotal = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "value", 0, IniFileName );
GetLineString( lstString, nReverse, nStart, strTarget );
CString strOut = _T( "" );
GetColumnFromLine( strTarget, nTotal, strOut );
if( strOut.IsEmpty() )
bRet = FALSE;
else
{
float fTotalMemory = atof( strOut );
fTotalMemory = fTotalMemory * (float)nUnit;
cout << "total fTotalMemory = " << fTotalMemory << endl;
strMsg.Format("totalMemory=%.2f$", fTotalMemory );
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if( nMonitorType == FREE_PMEMORY )
{//vmstat Free 内存值*4/1024 兆
int nReverse = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "reverselines", 0, IniFileName );
int nStart = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "startline", 0, IniFileName );
UINT nFree = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "value", 0, IniFileName );
UINT nUnit = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "unit", 0, IniFileName );
GetLineString( lstString, nReverse, nStart, strTarget );
CString strOut = _T( "" );
GetColumnFromLine( strTarget, nFree, strOut );
cout << "free strOut = " << strOut << endl;
if( strOut.IsEmpty() )
bRet = FALSE;
else
{
float fFreeMemory = atof( strOut );
fFreeMemory = fFreeMemory *4 * (float)nUnit;
cout << "free fFreeMemory = " << fFreeMemory << endl;
strMsg.Format("freeMemory=%.2f$", fFreeMemory );
strcpy(szOut, (LPCTSTR)strMsg);
}
}
cout << "===========================" << endl;
}
else
{
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%d", &nFree);
//sscanf((LPCTSTR)strOut2, "%d", &nTotal);
dwFree = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(100.0 * (dwTotal - dwFree) / (1.0 * dwTotal));
float fMbFree = (float)(dwFree / (1.0 * 1024));
//float fMbTotal = (float)nTotal/(1.0* 1000 * 1024);
float fMbTotal = (float)(dwTotal/(1.0 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 4) { // compatible with digital os
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nFreeLine = DFNParser_GetPrivateProfileInt("memory", "freeLine", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
int nTotalLine = DFNParser_GetPrivateProfileInt("memory", "totalLine", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
GetLineString(lstString, nReverse, nFreeLine, strTarget);
GetLineString(lstString, nReverse, nTotalLine, strTarget2);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget2, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%ld", &nFree);
//sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
dwFree = atof(strOut1);///1024;
dwTotal = atof(strOut2);///1024;
//sscanf((LPCTSTR)strOut1, "%f", &dwUsed);
//sscanf((LPCTSTR)strOut2, "%f", &dwTotal);
float fRate = (float)(100.0 * (dwTotal - dwFree) / (1.0 * dwTotal));
float fMbFree = (float)(dwFree * nSwapUnit / (1.0 * 1024 * 1024));
float fMbTotal = (float)(dwTotal/(1.0* 1024 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 5)//AIX
{
//-----------------------------------------------------------------------------------------------------------
// 更改内容:针对aix的物理内存信息采取两步获取(prtconf:总物理内存,vmstat:剩余物理内存)
// 更改人:邹晓
// 更改时间:2009.02.25
//-----------------------------------------------------------------------------------------------------------
if( nMonitorType == TOTAL_PMEMORY )
{
int nReverse = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "reverselines", 0, IniFileName );
int nStart = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "startline", 0, IniFileName );
UINT nTotal = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "value", 0, IniFileName );
UINT nUnit = DFNParser_GetPrivateProfileInt( "totalPhysicalMemory", "unit", 0, IniFileName );
GetLineString( lstString, nReverse, nStart, strTarget );
CString strOut = _T( "" );
GetColumnFromLine( strTarget, nTotal, strOut );
if( strOut.IsEmpty() )
bRet = FALSE;
else
{
float fTotalMemory = atof( strOut );
fTotalMemory = fTotalMemory * (float)nUnit;
strMsg.Format("totalMemory=%.2f$", fTotalMemory );
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if( nMonitorType == FREE_PMEMORY )
{
int nReverse = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "reverselines", 0, IniFileName );
int nStart = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "startline", 0, IniFileName );
UINT nFree = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "value", 0, IniFileName );
UINT nUnit = DFNParser_GetPrivateProfileInt( "freePhysicalMemory", "unit", 0, IniFileName );
GetLineString( lstString, nReverse, nStart, strTarget );
//////////////////////////////////////////////////////////////////////////
// lish
CString strFile = _T("FREE_PMEMORY");
CString strLog = _T("");
//strFile.Format("FREE_PMEMORY");
WriteLog(strFile,"=================== FREE_PMEMORY Start =========================");
strLog.Format("szSource:\n%s",szSource);
cout << "szSource = " << szSource << endl;
WriteLog(strFile,szSource);
strLog.Format("strTarget:\n%s",strTarget);
cout << "strTarget = " << strTarget << endl;
WriteLog(strFile,strLog);
strLog.Format("\nnReverse = %d\nnStart=%d\nnFree=%d\nnUnit=%d",nReverse,nStart,nFree,nUnit);
WriteLog(strFile,strLog);
//////////////////////////////////////////////////////////////////////////
CString strOut = _T( "" );
GetColumnFromLine( strTarget, nFree, strOut );
strLog.Format("strOut=%s",strOut);
WriteLog(strFile,strLog);
cout << "strOut = " << strOut << endl;
if( strOut.IsEmpty() )
bRet = FALSE;
else
{
float fFreeMemory = atof( strOut );
fFreeMemory = fFreeMemory * (float)nUnit;
strMsg.Format("freeMemory=%.2f$", fFreeMemory );
strcpy(szOut, (LPCTSTR)strMsg);
}
WriteLog(strFile,strMsg);
WriteLog(strFile,"================= FREE_PMEMORY End ======================");
}// 结束更改
else
{
int nReverse = DFNParser_GetPrivateProfileInt("physicalmemory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("physicalmemory", "startline", 0, IniFileName);
UINT nSize = DFNParser_GetPrivateProfileInt("physicalmemory", "size", 0, IniFileName);
UINT nInuse = DFNParser_GetPrivateProfileInt("physicalmemory", "inuse", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("physicalmemory", "free", 0, IniFileName);
CString str;
str.Format("nReverse=%d, nStart=%d, nSize=%d, nInuse=%d, nFree=%d", nReverse, nStart, nSize, nInuse, nFree);
OutputDebugString((LPCSTR)str); //zjw
GetLineString(lstString, nReverse, nStart, strTarget);
OutputDebugString((LPCSTR)strTarget); //zjw
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nSize, strOut1);
GetColumnFromLine(strTarget, nInuse, strOut2);
GetColumnFromLine(strTarget, nFree, strOut3);
str.Format("%s, %s, %s", strOut1, strOut2, strOut3);
OutputDebugString((LPCSTR)str); //zjw
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
dwUsePercent = atof(strOut2)/atof(strOut1);///1024;
dwTotal = atof(strOut1)*4/1024;///1024;
float fRate = (float)(1.0 * dwUsePercent);
float fMbFree = atof(strOut3)*4/1024;
float fMbTotal = (float)dwTotal;
fRate = fRate*100;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL MemoryParser_zw(const char * szSource, const int nMonitorType, char *szOut,
const char *FileName, const char* szTotalMem)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
// printf("get it\n");
CStringList lstString;
CString strTarget = _T("");
CString strTarget2 = _T("");
CString strMsg = _T("");
double dwUsed = 0.0;
double dwFree = 0.0;
int nValue = 0;
long lTotalMem = 0;
lTotalMem = atol(szTotalMem);
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
int nOsType = DFNParser_GetPrivateProfileInt("memory", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
// printf("lnux\n");
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
//sscanf((LPCTSTR)strOut1, "%dk", &nUsed);
dwUsed = atof(strOut1);
//sscanf((LPCTSTR)strOut2, "%dk", &nTotal);
if(nTotal == 0)
{
bRet = FALSE;
}
else
{
float fRate = (float)(100.0 * dwUsed / (1.0 * lTotalMem*1024*1024));
float fMbFree = (float)(lTotalMem - dwUsed / (1.0 * 1024 * 1024));
//float fMbTotal = (float)(lTotalMem/(1.0* 1024 * 1024));
float fMbTotal = (float)(lTotalMem);
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nUsed = DFNParser_GetPrivateProfileInt("memory", "used", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsed, strOut1);
GetColumnFromLine(strTarget, nFree, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%dk", &nUsed);
sscanf((LPCTSTR)strOut2, "%dk", &nFree);
float fRate = (float)(100.0 * nUsed / (1.0 * (nUsed + nFree)));
float fMbFree = (float)(nFree / (1.0 * 1024));
float fMbTotal = (float)((nUsed+nFree)/(1.0 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
// GetColumnFromLine(strTarget, nTotal, strOut2);
//if (strOut1.IsEmpty() || strOut2.IsEmpty())
if (strOut1.IsEmpty())
bRet = FALSE;
else {
// sscanf((LPCTSTR)strOut1, "%d", &dwUsed);
// sscanf((LPCTSTR)strOut2, "%d", &nTotal);
dwFree = atof(strOut1);
float fRate = (float)(100.0 * (lTotalMem*1024 - dwFree) / (1.0 * lTotalMem*1024));
float fMbFree = (float)(dwFree / (1.0 * 1024));
float fMbTotal = (float)lTotalMem;
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 4) { // compatible with digital os
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
int nFreeLine = DFNParser_GetPrivateProfileInt("memory", "freeLine", 0, IniFileName);
UINT nFree = DFNParser_GetPrivateProfileInt("memory", "free", 0, IniFileName);
int nTotalLine = DFNParser_GetPrivateProfileInt("memory", "totalLine", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
UINT nSwapUnit = DFNParser_GetPrivateProfileInt("memory", "swapunit", 0, IniFileName);
GetLineString(lstString, nReverse, nFreeLine, strTarget);
GetLineString(lstString, nReverse, nTotalLine, strTarget2);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget2, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%ld", &nFree);
sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
float fRate = (float)(100.0 * (nTotal - nFree) / (1.0 * nTotal));
float fMbFree = (float)(nFree * nSwapUnit / (1.0 * 1024 * 1024));
float fMbTotal = (float)(nTotal/(1.0* 1000 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 5)
{
int nReverse = DFNParser_GetPrivateProfileInt("memory", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memory", "startline", 0, IniFileName);
UINT nUsePercent = DFNParser_GetPrivateProfileInt("memory", "usePercent", 0, IniFileName);
UINT nTotal = DFNParser_GetPrivateProfileInt("memory", "total", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
GetColumnFromLine(strTarget, nUsePercent, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
if (strOut1.IsEmpty() || strOut2.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%ld", &nUsePercent);
sscanf((LPCTSTR)strOut2, "%ld", &nTotal);
float fRate = (float)(1.0 * nUsePercent);
float fMbFree = (float)(nTotal * (100 - fRate) / 100.0);
float fMbTotal = (float)(nTotal/(1.0* 1000 * 1024));
strMsg.Format("percentUsed=%.2f$Mbfree=%.2f$pagesPerSec=0.0$TotalMemory=%.2f$", fRate, fMbFree, fMbTotal);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport) BOOL DiskParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
//////////////////////////////////////////////////////////////////////////
//lish
CString strFileName = "DiskParser";
CString strLog ="";
//strLog.Format("szScource=%s",szSource);
//WriteLog(strFileName,"================== DiskParser Start ==================");
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
bRet = FormatSource(szSource, nMonitorType, lstString, IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("disk", "ostype", 0, IniFileName);
if (nOsType == 1)
{ // Linux
int nReverse = DFNParser_GetPrivateProfileInt("disk", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("disk", "startline", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("disk", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("disk", "total", 0, IniFileName);
int nPercentUsed = DFNParser_GetPrivateProfileInt("disk", "percentused", 0, IniFileName);
__int64 nFree_8 = 0;
__int64 nTotal_8 =0;
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
GetColumnFromLine(strTarget, nPercentUsed, strOut3);
//////////////////////////////////////////////////////////////////////////
//lish
//int nCount = lstString.GetCount();
//strLog.Format("strOut1=%s, strOut2=%s, strOut3=%s, nCount=%d, strTarget=%s",strOut1,strOut2,strOut3,nCount,strTarget);
//strLog.Format(" nFree=%d, nTotal=%d, nPercentUsed=%d, nReverse=%d",nFree,nTotal,nPercentUsed,nReverse);
//strLog.Format("strTemp=%s",strTemp);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
{
GetLineString(lstString, nReverse, nStart+1, strTarget);
GetColumnFromLine(strTarget, nFree - 1, strOut1);
GetColumnFromLine(strTarget, nTotal - 1, strOut2);
GetColumnFromLine(strTarget, nPercentUsed - 1, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
bRet = FALSE;
else
{
sscanf((LPCTSTR)strOut2, "%I64d", &nTotal_8);
sscanf((LPCTSTR)strOut1, "%I64d", &nFree_8);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
double fPercentFull = (double)(1.0 * nPercentUsed);
double fMbFree = (double)(nFree_8 / (1.0 * 1024));
double fper=(double)((100.00-fPercentFull)/100.00);
//Edit By Kevin.Yang
double fTotalSize= (double)(nTotal_8 / (1.0 * 1024)); //(fper<=0)?0:fMbFree/fper;
//////////////////////////////////////////////////////////////////////////
//lish
//ntemp2 = _atoi64(strOut2);
//int nCount = lstString.GetCount();
//strLog.Format("strOut1=%s, strOut2=%s, strOut3=%s, nCount=%d, strTarget=%s",strOut1,strOut2,strOut3,nCount,strTarget);
//strLog.Format("%s, nFree=%d, nTotal=%d, nPercentUsed=%d, nReverse=%d",strLog,nFree,nTotal,nPercentUsed,nReverse);
//strLog.Format("nTemp1=%d, ntemp2=%d, strOut1=%s, strOut2=%s",nTemp1,ntemp2,strOut1,strOut2);
//WriteLog(strFileName,strLog);
strLog.Format("nFree_8=%I64d, nTotal_8=%I64d",nFree_8,nTotal_8);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
//wangpeng
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
//strMsg.Format("percentFull=%.2f$Mbfree=%.2f$TotalSize=%.2f$", fPercentFull, fMbFree,fTotalSize);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if ((strOut1=="-") || (strOut2=="-") || (strOut3=="-"))
{
//dy:AIX 的/prco 是"-"的 。/proc 是一个目录,其中包含了反映内核和进程树的各种文件。
//这些文件和目录并不存在于磁盘中,因此当您对这些文件进行读取和写入时,
//实际上是在从操作系统本身获取相关信息。
//df -k /proc
//Filesystem 1K-blocks Used Available Use% Mounted on
//- - - - - /proc
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", 0, 0);
strcpy(szOut, (LPCTSTR)strMsg);
}
else
{
sscanf((LPCTSTR)strOut1, "%I64d", &nFree_8);
sscanf((LPCTSTR)strOut2, "%I64d", &nTotal_8);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
double fPercentFull = (double)(1.0 * nPercentUsed);
double fMbFree = (double)(nFree_8 / (1.0 * 1024));
double fper=(double)((100.00-fPercentFull)/100.00);
double fTotalSize= (double)(nTotal_8 / (1.0 * 1024)); //(fper<=0)?0:fMbFree/fper;
//////////////////////////////////////////////////////////////////////////
//lish
//int nCount = lstString.GetCount();
//strLog.Format("strOut1=%s, strOut2=%s, strOut3=%s, nCount=%d, strTarget=%s",strOut1,strOut2,strOut3,nCount,strTarget);
//strLog.Format("%s, nFree=%d, nTotal=%d, nPercentUsed=%d, nReverse=%d",strLog,nFree,nTotal,nPercentUsed,nReverse);
//strLog.Format("strTemp=%s",strTemp);
//WriteLog(strFileName,strLog);
strLog.Format("nFree_8=%I64d, nTotal_8=%I64d",nFree_8,nTotal_8);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
//wangpeng
//strMsg.Format("percentFull=%.2f$Mbfree=%.2f$TotalSize=%.2f$", fPercentFull, fMbFree,fTotalSize);
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2)
{ // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("disk", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("disk", "startline", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("disk", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("disk", "total", 0, IniFileName);
int nPercentUsed = DFNParser_GetPrivateProfileInt("disk", "percentused", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
GetColumnFromLine(strTarget, nPercentUsed, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
{
GetLineString(lstString, nReverse, nStart + 1, strTarget);
GetColumnFromLine(strTarget, nFree - 1, strOut1);
GetColumnFromLine(strTarget, nTotal - 1, strOut2);
GetColumnFromLine(strTarget, nPercentUsed - 1, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
{
printf("parser disk error\n");
bRet = FALSE;
}
else
{
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
float fper=(float)((100.00-fPercentFull)/100.00);
float fTotalSize= (float)(nTotal / (1.0 * 1024)); //(fper<=0)?0:fMbFree/fper;
//wangpeng
//strMsg.Format("percentFull=%.2f$Mbfree=%.2f$TotalSize=%.2f$", fPercentFull, fMbFree,fTotalSize);
if (fPercentFull>100)
{
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", 1.0, 8000.0);
}
else
{
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
}
strcpy(szOut, (LPCTSTR)strMsg);
if (fMbFree==0)
{
printf("parser disk error 2 \n");
bRet= FALSE;
}
}
}
else
{
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
float fper=(float)((100.00-fPercentFull)/100.00);
float fTotalSize= (float)(nTotal / (1.0 * 1024)); //(fper<=0)?0:fMbFree/fper;
// strMsg.Format("percentFull=%.2f$Mbfree=%.2f$TotalSize=%.2f$", fPercentFull, fMbFree,fTotalSize);
//wangpeng
if (fMbFree<1.00)
{
printf("parser disk error 2 \n");
bRet= FALSE;
}
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3)
{ // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("disk", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("disk", "startline", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("disk", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("disk", "total", 0, IniFileName);
int nPercentUsed = DFNParser_GetPrivateProfileInt("disk", "percentused", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
GetColumnFromLine(strTarget, nPercentUsed, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty()) {
GetLineString(lstString, nReverse, nStart + 1, strTarget);
GetColumnFromLine(strTarget, nFree - 1, strOut1);
GetColumnFromLine(strTarget, nTotal - 1, strOut2);
GetColumnFromLine(strTarget, nPercentUsed - 1, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
float fper=(float)((100.00-fPercentFull)/100.00);
float fTotalSize= (float)(nTotal / (1.0 * 1024)); //(fper<=0)?0:fMbFree/fper;
//wangpeng
//strMsg.Format("percentFull=%.2f$Mbfree=%.2f$TotalSize=%.2f$", fPercentFull, fMbFree,fTotalSize);
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else
{
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
float fper=(float)((100.00-fPercentFull)/100.00);
float fTotalSize= (float)(nTotal / (1.0 * 1024)); //(fper<=0)?0:fMbFree/fper;
// strMsg.Format("percentFull=%.2f$Mbfree=%.2f$TotalSize=%.2f$", fPercentFull, fMbFree,fTotalSize);
strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else
{
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport) BOOL DiskParserTest(const char * szSource, const int nTelInfo, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
if(nTelInfo & 0x02)
{
int count = 1;
POSITION pos = lstString.FindIndex(0);
while(pos)
printf("Line %2.2d: %s<br>\r\n", count++, lstString.GetNext(pos));
printf("<br>\r\n");
fflush(stdout);
}
int nOsType = DFNParser_GetPrivateProfileInt("disk", "ostype", 0, IniFileName);
if (nOsType == 1) { // Linux
int nReverse = DFNParser_GetPrivateProfileInt("disk", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("disk", "startline", 0, IniFileName);
int nName = DFNParser_GetPrivateProfileInt("disks", "name", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("disk", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("disk", "total", 0, IniFileName);
int nPercentUsed = DFNParser_GetPrivateProfileInt("disk", "percentused", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"name\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_60%>"), nName); // <%IDS_AimParser_60%>磁盘空间 命令设置
printf("%s \"use percent\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_61%>"), nPercentUsed); // <%IDS_AimParser_61%>磁盘空间 命令设置
printf("%s \"free\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_62%>"), nFree); // <%IDS_AimParser_62%>磁盘空间 命令设置
printf("%s \"total\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_63%>"), nTotal); // <%IDS_AimParser_63%>磁盘空间 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_64%>"), nStart); // <%IDS_AimParser_64%>磁盘空间 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_65%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_65%>磁盘空间 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut0 = _T("");
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nName, strOut0);
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
GetColumnFromLine(strTarget, nPercentUsed, strOut3);
if (strOut0.IsEmpty() || strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty()) {
GetLineString(lstString, nReverse, nStart+1, strTarget);
GetColumnFromLine(strTarget, nFree - 1, strOut1);
GetColumnFromLine(strTarget, nTotal - 1, strOut2);
GetColumnFromLine(strTarget, nPercentUsed - 1, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format(" %s[%s] %s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_DISK","DISK_DESC"), strOut0,
FuncGetStringFromIDS("SV_DISK","DISK_USED"), fPercentFull,
FuncGetStringFromIDS("SV_DISK","DISK_FREED"), fMbFree);
// <%IDS_AimParser_66%>磁盘,<%IDS_AimParser_67%>使用率,<%IDS_AimParser_68%>剩余空间
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s [%s] %s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_DISK","DISK_DESC"), strOut0,
FuncGetStringFromIDS("SV_DISK","DISK_USED"), fPercentFull,
FuncGetStringFromIDS("SV_DISK","DISK_FREED"), fMbFree);
// <%IDS_AimParser_69%>,<%IDS_AimParser_70%>,<%IDS_AimParser_71%>
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("disk", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("disk", "startline", 0, IniFileName);
int nName = DFNParser_GetPrivateProfileInt("disks", "name", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("disk", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("disk", "total", 0, IniFileName);
int nPercentUsed = DFNParser_GetPrivateProfileInt("disk", "percentused", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"name\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_72%>"), nName); // <%IDS_AimParser_72%>磁盘空间 命令设置
printf("%s \"use percent\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_73%>"), nPercentUsed); // <%IDS_AimParser_73%>磁盘空间 命令设置
printf("%s \"free\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_74%>"), nFree); // <%IDS_AimParser_74%>磁盘空间 命令设置
printf("%s \"total\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_75%>"), nTotal); // <%IDS_AimParser_75%>磁盘空间 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_76%>"), nStart); // <%IDS_AimParser_76%>磁盘空间 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_77%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_77%>磁盘空间 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut0 = _T("");
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nName, strOut0);
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
GetColumnFromLine(strTarget, nPercentUsed, strOut3);
if (strOut0.IsEmpty() || strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty()) {
GetLineString(lstString, nReverse, nStart + 1, strTarget);
GetColumnFromLine(strTarget, nFree - 1, strOut1);
GetColumnFromLine(strTarget, nTotal - 1, strOut2);
GetColumnFromLine(strTarget, nPercentUsed - 1, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s [%s] %s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_DISK","DISK_DESC"), strOut0,
FuncGetStringFromIDS("SV_DISK","DISK_USED"), fPercentFull,
FuncGetStringFromIDS("SV_DISK","DISK_FREED"), fMbFree);
// <%IDS_AimParser_78%>,<%IDS_AimParser_79%>,<%IDS_AimParser_80%>
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s [%s] %s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_DISK","DISK_DESC"), strOut0,
FuncGetStringFromIDS("SV_DISK","DISK_USED"), fPercentFull,
FuncGetStringFromIDS("SV_DISK","DISK_FREED"), fMbFree);
// <%IDS_AimParser_81%>,<%IDS_AimParser_82%>,<%IDS_AimParser_83%>
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("disk", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("disk", "startline", 0, IniFileName);
int nName = DFNParser_GetPrivateProfileInt("disks", "name", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("disk", "free", 0, IniFileName);
int nTotal = DFNParser_GetPrivateProfileInt("disk", "total", 0, IniFileName);
int nPercentUsed = DFNParser_GetPrivateProfileInt("disk", "percentused", 0, IniFileName);
if(nTelInfo & 0x02)
{
printf("%s \"name\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_84%>"), nName); // <%IDS_AimParser_84%>磁盘空间 命令设置
printf("%s \"use percent\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_85%>"), nPercentUsed); // <%IDS_AimParser_85%>磁盘空间 命令设置
printf("%s \"free\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_86%>"), nFree); // <%IDS_AimParser_86%>磁盘空间 命令设置
printf("%s \"total\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_87%>"), nTotal); // <%IDS_AimParser_87%>磁盘空间 命令设置
printf("%s \"startLine\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_88%>"), nStart); // <%IDS_AimParser_88%>磁盘空间 命令设置
printf("%s \"reverseLines\": %s <br><br>\r\n\r\n", FuncGetStringFromIDS("<%IDS_AimParser_89%>"), nReverse ? "true" : "false"); // <%IDS_AimParser_89%>磁盘空间 命令设置
fflush(stdout);
}
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut0 = _T("");
CString strOut1 = _T("");
CString strOut2 = _T("");
CString strOut3 = _T("");
GetColumnFromLine(strTarget, nName, strOut0);
GetColumnFromLine(strTarget, nFree, strOut1);
GetColumnFromLine(strTarget, nTotal, strOut2);
GetColumnFromLine(strTarget, nPercentUsed, strOut3);
if (strOut0.IsEmpty() || strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty()) {
GetLineString(lstString, nReverse, nStart + 1, strTarget);
GetColumnFromLine(strTarget, nFree - 1, strOut1);
GetColumnFromLine(strTarget, nTotal - 1, strOut2);
GetColumnFromLine(strTarget, nPercentUsed - 1, strOut3);
if (strOut1.IsEmpty() || strOut2.IsEmpty() || strOut3.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s [%s] %s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_DISK","DISK_DESC"), strOut0,
FuncGetStringFromIDS("SV_DISK","DISK_USED"), fPercentFull,
FuncGetStringFromIDS("SV_DISK","DISK_FREED"), fMbFree);
// <%IDS_AimParser_90%>,<%IDS_AimParser_91%>,<%IDS_AimParser_92%>
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
sscanf((LPCTSTR)strOut1, "%d", &nFree);
sscanf((LPCTSTR)strOut2, "%d", &nTotal);
sscanf((LPCTSTR)strOut3, "%d%%", &nPercentUsed);
float fPercentFull = (float)(1.0 * nPercentUsed);
float fMbFree = (float)(nFree / (1.0 * 1024));
strMsg.Format("%s [%s] %s(%%): %.2f %s: %.2f",
FuncGetStringFromIDS("SV_DISK","DISK_DESC"), strOut0,
FuncGetStringFromIDS("SV_DISK","DISK_USED"), fPercentFull,
FuncGetStringFromIDS("SV_DISK","DISK_FREED"), fMbFree); // <%IDS_AimParser_93%>,<%IDS_AimParser_94%>,<%IDS_AimParser_95%>
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport) BOOL UserCPUParser(const char * szSource, const int nMonitorType, char *szOut, const char* szUserName, const char *FileName)
{
char szTemp[1024] = {0};
WriteLog("============== UserCPUParser ==============");
WriteLog( szSource );
WriteLog( szUserName );
WriteLog( FileName );
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
return bRet;
}
CStringList lstString;
CStringList lstProcs;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
int nUserColumn = 0;
int nCPUColumn = 0;
int nPIDColumn = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("usercpu", "ostype", 0, IniFileName);
int j = 0;
if ( 1 )// aix
{
CString strIn = lstString.GetHead();
char buffer[32] = {0};
WriteLog( "fileName:" );
WriteLog( IniFileName );
// 从配置文件中获取userColumn
DFNParser_GetPrivateProfileString( "usercpu", "userColumnName", "", buffer, sizeof(buffer), IniFileName );
bRet = GetColumnIndex( strIn, nUserColumn, buffer );
sprintf( szTemp, "userColumn=%d", nUserColumn );
WriteLog( szTemp );
if (bRet)
{
int nTempColumn = DFNParser_GetPrivateProfileInt( "usercpu", "userColumnIndex", 0, IniFileName );
if( nTempColumn )
{
if( nTempColumn != nUserColumn )
{
nUserColumn = nTempColumn;
}
}
}
// 从配置文件中获取cpuColumn
DFNParser_GetPrivateProfileString( "usercpu", "CPUColumnName", "", buffer, sizeof(buffer), IniFileName );
bRet = GetColumnIndex( strIn, nCPUColumn, buffer );
sprintf( szTemp, "cpuColumn=%d", nCPUColumn );
WriteLog( szTemp );
if (bRet)
{
int nTempColumn = DFNParser_GetPrivateProfileInt( "usercpu", "CPUColumnIndex", 0, IniFileName );
if( nTempColumn )
{
if( nTempColumn != nCPUColumn )
{
nCPUColumn = nTempColumn;
}
}
}
// 从配置文件中获取PIDColumn
DFNParser_GetPrivateProfileString( "usercpu", "PIDColumnName", "", buffer, sizeof(buffer), IniFileName );
bRet = GetColumnIndex( strIn, nPIDColumn, buffer );
sprintf( szTemp, "PIDColumn=%d", nPIDColumn );
WriteLog( szTemp );
WriteLog("============== 循环匹配: ==============");
CString strUserName = _T("");
CString strPID = _T("");
std::list<string> listPID;
std::list<string>::iterator it;
bool bWhile(true);
float fCPU(0.0);
POSITION pos = lstString.GetHeadPosition();
strTarget = lstString.GetNext(pos);
while( pos )
{
strTarget = lstString.GetNext(pos);
sprintf( szTemp, "string=%s", strTarget.GetBuffer(strTarget.GetLength()) );
WriteLog( szTemp );
/*
GetColumnFromLine( strTarget, nPIDColumn, strPID, nMonitorType );
strUserName.TrimRight(" ");
sprintf( szTemp, "PID=%s", strPID.GetBuffer(strPID.GetLength()) );
WriteLog( szTemp );
for( it=listPID.begin(); it!=listPID.end(); it++ )
{
if( it->compare(strPID.GetBuffer(strPID.GetLength())) == 0 )
{
bWhile = false;
break;
}
}
if( !bWhile )
{
break;
}
else
{
listPID.push_back( strPID.GetBuffer(strPID.GetLength()) );
}
*/
GetColumnFromLine( strTarget, nUserColumn, strUserName, nMonitorType );
strPID.TrimRight(" ");
sprintf( szTemp, "userName=%s", strUserName.GetBuffer(strUserName.GetLength()) );
WriteLog( szTemp );
if ( !stricmp((LPCTSTR)strUserName, szUserName) )
{
CString strCPU = _T("");
GetColumnFromLine( strTarget, nCPUColumn, strCPU, nMonitorType );
strCPU.TrimRight(" ");
sprintf( szTemp, "cpu=%s", strCPU.GetBuffer(strCPU.GetLength()) );
WriteLog( szTemp );
fCPU += atof( strCPU.GetBuffer(strCPU.GetLength()) );
}
}
sprintf( szOut, "user=%s$cpu=%.1f", szUserName, fCPU );
WriteLog( szOut );
}
}
return TRUE;
}
extern "C" __declspec(dllexport)
BOOL ServiceParser(const char * szSource, const int nMonitorType, char *szOut, const char* szProcName, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CStringList lstProcs;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
int nColumn = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("service", "ostype", 0, IniFileName);
int j = 0;
if (nOsType == 1)
{ // Linux
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
//puts(strOut);
cout << "strOut:" << strOut <<endl;
j++;
if (szProcName == NULL)
{
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1)
{
BOOL bFound = FALSE;
while (pos1)
{
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut))
{
bFound = TRUE;
break;
}
}
if (!bFound)
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
if (strOut.GetLength()>100) //2010-09-27太大了的字符strOut舍弃了,szProcName是全称,故有问题
{
char strOutBuf[102] = {0};
char szProcNameBuf[102] = {0};
strncpy(strOutBuf, strOut.GetBuffer(strOut.GetLength()), 100);
strncpy(szProcNameBuf, szProcName, 100);
if (!strcmp(strOutBuf, szProcNameBuf))
{
//if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
else
{
if (!stricmp((LPCTSTR)strOut, szProcName))
{
//if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$", nProcesses);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 2)
{ // Solaris
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet) {
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn) {
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos) {
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
cout << "strOut:" << strOut <<endl;
j++;
if ((szProcName == NULL)) {
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1) {
BOOL bFound = FALSE;
while (pos1) {
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut)) {
bFound = TRUE;
break;
}
}
if (!bFound) {
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else {
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else {
if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$", nProcesses);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else if(nOsType == 3) { // FreeBSD
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet) {
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn) {
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos) {
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
j++;
if (szProcName == NULL) {
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1) {
BOOL bFound = FALSE;
while (pos1) {
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut)) {
bFound = TRUE;
break;
}
}
if (!bFound) {
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else {
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else {
if (!stricmp((LPCTSTR)strOut, szProcName)) {
//if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$", nProcesses);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
printf("=====================\n");
printf("szOut = %s\n",szOut);
printf("=====================\n");
}
return bRet;
}
extern "C" __declspec(dllexport) BOOL ServiceParserTest(const char * szSource, const int nTelInfo, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char szProcName[1024] = {0};
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CStringList lstProcs;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
int nColumn = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
if(nTelInfo & 0x02)
{
int count = 1;
POSITION pos = lstString.FindIndex(0);
while(pos)
printf("Line %2.2d: %s<br>\r\n", count++, lstString.GetNext(pos));
printf("<br>\r\n");
fflush(stdout);
}
int nOsType = DFNParser_GetPrivateProfileInt("service", "ostype", 0, IniFileName);
int j = 0;
if (nOsType == 1) { // Linux
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet) {
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn) {
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
if(nTelInfo & 0x02)
{
printf("%s \"namecolumnindex\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_96%>"), nColumn); // <%IDS_AimParser_96%>SERVICE 命令设置
fflush(stdout);
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos) {
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
j++;
if(j <= 1)
continue;
else if(j == 2)
strcpy(szProcName ,strOut.GetBuffer(strOut.GetLength()));
if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
strMsg.Format("Service [%s] %s %d", szProcName,
FuncGetStringFromIDS("SV_SERVICE","SERVICE_DESC"), nProcesses); // <%IDS_AimParser_97%>运行实例:
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 2) { // Solaris
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet) {
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn) {
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
if(nTelInfo & 0x02)
{
printf("%s \"namecolumnindex\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_98%>"), nColumn); // <%IDS_AimParser_98%>SERVICE 命令设置
fflush(stdout);
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos) {
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
j++;
if(j <= 1)
continue;
else if(j == 2)
strcpy(szProcName ,strOut.GetBuffer(strOut.GetLength()));
if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
strMsg.Format("Service [%s] %s %d", szProcName,
FuncGetStringFromIDS("SV_SERVICE","SERVICE_DESC"), nProcesses);
// <%IDS_AimParser_99%>运行实例:
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if(nOsType == 3) { // FreeBSD
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet) {
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn) {
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
if(nTelInfo & 0x02)
{
printf("%s \"namecolumnindex\": %d <br>\r\n", FuncGetStringFromIDS("<%IDS_AimParser_100%>"), nColumn); // <%IDS_AimParser_100%>SERVICE 命令设置
fflush(stdout);
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos) {
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
j++;
if(j <= 1)
continue;
else if(j == 2)
strcpy(szProcName ,strOut.GetBuffer(strOut.GetLength()));
if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
strMsg.Format("Service [%s] %s %d", szProcName,
FuncGetStringFromIDS("SV_SERVICE","SERVICE_DESC"), nProcesses);
// <%IDS_AimParser_101%>运行实例:
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
BOOL GetColumnIndex(CStringList& lstStr, int& nColumn,char*IniFileName)
{
BOOL bRet = FALSE;
char buffer[32] = {0};
DFNParser_GetPrivateProfileString("service", "namecolumnname", "", buffer, sizeof(buffer), IniFileName);
//cout <<"buffer:"<<buffer <<endl;
CString strIn = lstStr.GetHead();
int nLen = strIn.GetLength();
//cout << "nLen:"<<nLen <<endl;
TCHAR ch;
CString str = _T("");
int j = 0;
for (int i = 0; i < nLen; i++)
{
ch = strIn.GetAt(i);
if (ch == char_space)
continue;
j++;
str = strIn.Right(nLen - i);
str = str.SpanExcluding(" ");
cout << "str:" <<str <<endl;
if (!str.Compare(buffer))
{
nColumn = j;
bRet = TRUE;
break;
}
i += str.GetLength();
}
return bRet;
}
BOOL GetColumnIndexAix(CStringList& lstStr, int& nColumn,char*IniFileName)
{
BOOL bRet = FALSE;
char buffer[32] = {0};
DFNParser_GetPrivateProfileString("errpt", "namecolumnname", "", buffer, sizeof(buffer), IniFileName);
//cout <<"buffer:"<<buffer <<endl;
CString strIn = lstStr.GetHead();
int nLen = strIn.GetLength();
//cout << "nLen:"<<nLen <<endl;
TCHAR ch;
CString str = _T("");
int j = 0;
for (int i = 0; i < nLen; i++)
{
ch = strIn.GetAt(i);
if (ch == char_space)
continue;
j++;
str = strIn.Right(nLen - i);
str = str.SpanExcluding(" ");
cout << "str:" <<str <<endl;
if (!str.Compare(buffer))
{
nColumn = j;
bRet = TRUE;
break;
}
i += str.GetLength();
}
return bRet;
}
BOOL GetColumnIndex( CString strIn, int& nColumn, char* pszMatch )
{
WriteLog( "============= GetColumnIndex ==============" );
WriteLog(strIn.GetBuffer(strIn.GetLength()));
WriteLog(pszMatch);
BOOL bRet = FALSE;
int nLen = strIn.GetLength();
TCHAR ch;
CString str = _T("");
int j = 0;
for (int i = 0; i < nLen; i++) {
ch = strIn.GetAt(i);
if (ch == char_space)
continue;
j++;
str = strIn.Right(nLen - i);
str = str.SpanExcluding(" ");
if (!str.Compare(pszMatch)) {
nColumn = j;
bRet = TRUE;
break;
}
i += str.GetLength();
}
return bRet;
}
BOOL GetIniFileName(const char *FileName,char *IniFileName)
{
strcpy(IniFileName,FileName);
return TRUE;
/*
HKEY hKey = NULL;
LONG lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,KEY_PATH,0,KEY_READ,&hKey);
if(lRet != ERROR_SUCCESS)
return FALSE;
LPTSTR lpName = NULL, lpValue = NULL;
CString strSubKey = _T(""), strValKey = _T("");
DWORD dwIndex = 0, dwS1 = 255, dwS2 = 255, dwType = REG_SZ;
BOOL bFindFlag = FALSE;
while(lRet == ERROR_SUCCESS)
{
lpName = strSubKey.GetBuffer(dwS1);
lpValue = strValKey.GetBuffer(dwS2);
lRet = RegEnumValue(hKey, dwIndex++, lpName , &dwS1,NULL, &dwType ,(LPBYTE)lpValue, &dwS2);
dwS1 = 255;
dwS2 = 255;
strSubKey.ReleaseBuffer();
strValKey.ReleaseBuffer();
if(lRet == ERROR_NO_MORE_ITEMS)
break;
if(strSubKey.CompareNoCase(KEY_NAME) == 0)
{
bFindFlag = TRUE;
strValKey.Replace("/", "\\");
#if _DEBUG
strValKey += "\\templates.os\\";
#else
strValKey += "\\MonitorManager\\templates.os\\";
#endif
CString strFileName = _T("");
strFileName.Format("%s%s", (LPCTSTR)strValKey, FileName);
strcpy(IniFileName, (LPCTSTR)strFileName);
break;
}
}
RegCloseKey(hKey);
return bFindFlag;
*/
}
void AddToLogFile(const int nMonitorType, const char*szMsg)
{
HKEY hKey = NULL;
LONG lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,KEY_PATH,0,KEY_READ,&hKey);
if(lRet != ERROR_SUCCESS)
return;
CString strFileName = _T("");
LPTSTR lpName = NULL, lpValue = NULL;
CString strSubKey = _T(""), strValKey = _T("");
DWORD dwIndex = 0, dwS1 = 255, dwS2 = 255, dwType = REG_SZ;
BOOL bFindFlag = FALSE;
while(lRet == ERROR_SUCCESS)
{
lpName = strSubKey.GetBuffer(dwS1);
lpValue = strValKey.GetBuffer(dwS2);
lRet = RegEnumValue(hKey, dwIndex++, lpName , &dwS1,NULL, &dwType ,(LPBYTE)lpValue, &dwS2);
dwS1 = 255;
dwS2 = 255;
strSubKey.ReleaseBuffer();
strValKey.ReleaseBuffer();
if(lRet == ERROR_NO_MORE_ITEMS)
break;
if(strSubKey.CompareNoCase(KEY_NAME) == 0)
{
bFindFlag = TRUE;
strValKey.Replace("/", "\\");
strValKey += "\\doc\\dragondoc\\";
strFileName.Format("%stemp.dat", (LPCTSTR)strValKey);
break;
}
}
RegCloseKey(hKey);
if (bFindFlag && (nMonitorType == 11)) {
FILE *logfile=fopen((LPCTSTR)strFileName,"a+");
if (logfile) {
CTime curtime = CTime::GetCurrentTime();
CString strtime = curtime.Format("%Y-%m-%d %H:%M:%S");
fprintf(logfile,"Time: %s\r\n", (LPCTSTR)strtime);
switch (nMonitorType) {
case 7: // CPU
fprintf(logfile,"MonitorType: CPU\r\n");
break;
case 8: // Disk
fprintf(logfile,"MonitorType: Disk\r\n");
break;
case 9: // Memory
fprintf(logfile,"MonitorType: Memory\r\n");
break;
case 11: // Service
fprintf(logfile,"MonitorType: Service\r\n");
break;
case 21: // File
fprintf(logfile, "MonitorType: File\r\n");
break;
}
fprintf(logfile,"%s\r\n",szMsg);
fclose(logfile);
}
}
}
extern "C" __declspec(dllexport)
BOOL DisksParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
//////////////////////////////////////////////////////////////////////////
//lish
CString strFileName;
strFileName = "DisksParser";
CString strLog = "";
WriteLog(strFileName,"--------------- DisksParser Start --------------");
// WriteLog(strFileName,szSource);
strLog.Format("IniFileName=%s,nMonitorType=%d",FileName,nMonitorType);
WriteLog(strFileName,strLog);
// WriteLog(strFileName,"--------------- DisksParser End --------------");
//////////////////////////////////////////////////////////////////////////
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
char matchLine[64] = {0};
char matchLineNew[64]={0};
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("disks", "ostype", 0, IniFileName);
if (nOsType == 1)
{ // Linux
int nName = DFNParser_GetPrivateProfileInt("disks", "name", 0, IniFileName);
int nMount = DFNParser_GetPrivateProfileInt("disks", "mount", 0, IniFileName);
DFNParser_GetPrivateProfileString("disks", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
//memset(matchLineNew,0,64);
//sprintf(matchLineNew,"文件系统");
//////////////////////////////////////////////////////////////////////////
//lish
//strLog.Format("matchLine=%s",matchLine);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
/*CString strTemp="";
CString strVal="strTemp:";
POSITION temp = lstString.GetHeadPosition();
while(temp)
{
strTemp = lstString.GetNext(temp);
WriteLog(strFileName,strTemp);
}*/
POSITION pos = lstString.GetHeadPosition();
//舍弃第一行 lish 2009-8-13
strTarget = lstString.GetNext(pos);
//strLog.Format("strTarget=%s, nName=%d, nMount=%d",strTarget,nName,nMount);
//WriteLog(strFileName,strLog);
while (pos)
{
CString strOut1 = _T("");
CString strOut2 = _T("");
strTarget = lstString.GetNext(pos);
strLog.Format("strTarget=%s",strTarget);
WriteLog(strFileName,strLog);
GetColumnFromLine(strTarget, nName, strOut1, nMonitorType);
GetColumnFromLine(strTarget, nMount, strOut2, nMonitorType);
strOut1.TrimRight(" ");
strOut2.TrimRight(" ");
//////////////////////////////////////////////////////////////////////////
//lish
//strLog.Format("strOut1=%s,strOut2=%s",strOut1,strOut2);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
if ( (!(!strOut1.Compare((LPCTSTR)matchLine)))&&(!strOut2.IsEmpty()))
{
sprintf(szOut, "%s%s###%s$$$", szOut, (LPCTSTR)strOut1, (LPCTSTR)strOut2);
}
else if ((!(!strOut1.Compare((LPCTSTR)matchLine)))&&(strOut2.IsEmpty()))
{
if (pos)
{
sprintf(szOut, "%s%s###", szOut, (LPCTSTR)strOut1);
strTarget = lstString.GetNext(pos);
strLog.Format("strTarget=%s",strTarget);
WriteLog(strFileName,strLog);
GetColumnFromLine(strTarget, nMount - 1, strOut2, nMonitorType);
strOut2.TrimRight(" ");
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut2);
}
}
else
{
}
}
}
else if(nOsType == 2)
{ // Solaris
int nName = DFNParser_GetPrivateProfileInt("disks", "name", 0, IniFileName);
int nMount = DFNParser_GetPrivateProfileInt("disks", "mount", 0, IniFileName);
DFNParser_GetPrivateProfileString("disks", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
POSITION pos = lstString.GetHeadPosition();
while (pos)
{
CString strOut1 = _T("");
CString strOut2 = _T("");
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nName, strOut1, nMonitorType);
GetColumnFromLine(strTarget, nMount, strOut2, nMonitorType);
strOut1.TrimRight(" ");
strOut2.TrimRight(" ");
if ((!(!strOut1.Compare((LPCTSTR)matchLine)))&&(!strOut2.IsEmpty()))
{
sprintf(szOut, "%s%s###%s$$$", szOut, (LPCTSTR)strOut1, (LPCTSTR)strOut2);
}
else if ((!(!strOut1.Compare((LPCTSTR)matchLine)))&&(strOut2.IsEmpty()))
{
if (pos)
{
sprintf(szOut, "%s%s###", szOut, (LPCTSTR)strOut1);
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nMount - 1, strOut2, nMonitorType);
strOut2.TrimRight(" ");
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut2);
}
}
else
{
}
}
}
else if(nOsType == 3)
{ // FreeBSD
int nName = DFNParser_GetPrivateProfileInt("disks", "name", 0, IniFileName);
int nMount = DFNParser_GetPrivateProfileInt("disks", "mount", 0, IniFileName);
DFNParser_GetPrivateProfileString("disks", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
POSITION pos = lstString.GetHeadPosition();
while (pos)
{
CString strOut1 = _T("");
CString strOut2 = _T("");
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nName, strOut1, nMonitorType);
GetColumnFromLine(strTarget, nMount, strOut2, nMonitorType);
strOut1.TrimRight(" ");
strOut2.TrimRight(" ");
if ((!(!strOut1.Compare((LPCTSTR)matchLine)))&&(!strOut2.IsEmpty())) {
sprintf(szOut, "%s%s###%s$$$", szOut, (LPCTSTR)strOut1, (LPCTSTR)strOut2);
}
else if ((!(!strOut1.Compare((LPCTSTR)matchLine)))&&(strOut2.IsEmpty())) {
if (pos) {
sprintf(szOut, "%s%s###", szOut, (LPCTSTR)strOut1);
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nMount - 1, strOut2, nMonitorType);
strOut2.TrimRight(" ");
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut2);
}
}
else
{
}
}
}
else
{
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport) BOOL DiskActParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet) {
int nOsType = DFNParser_GetPrivateProfileInt("DiskAct", "ostype", 0, IniFileName);
if(nOsType == 5) { // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("DiskAct", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("DiskAct", "startline", 0, IniFileName);
int nDiskAct = DFNParser_GetPrivateProfileInt("DiskAct", "diskact", 0, IniFileName);
float fDiskAct = 0.0;
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut1 = _T("");
GetColumnFromLine(strTarget, nDiskAct, strOut1);
if (strOut1.IsEmpty()) {
GetLineString(lstString, nReverse, nStart + 1, strTarget);
GetColumnFromLine(strTarget, nDiskAct - 1, strOut1);
if (strOut1.IsEmpty())
bRet = FALSE;
else {
sscanf((LPCTSTR)strOut1, "%f", &fDiskAct);
strMsg.Format("DiskAct=%.2f$", fDiskAct);
// strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
sscanf((LPCTSTR)strOut1, "%f", &fDiskAct);
strMsg.Format("DiskAct=%.2f$", fDiskAct);
// strMsg.Format("percentFull=%.2f$Mbfree=%.2f$", fPercentFull, fMbFree);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else {
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
//获取cpu序列
extern "C" __declspec(dllexport)
BOOL MulCPUSParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
BOOL bRet = FALSE;
//////////////////////////////////////////////////////////////////////////
//lish
CString strFileName;
strFileName = "MulCPUSParser";
CString strLog = "";
WriteLog(strFileName,"--------------- MulCPUSParser Start --------------");
// WriteLog(strFileName,szSource);
strLog.Format("IniFileName=%s,nMonitorType=%d\nszSource=%s",FileName,nMonitorType,szSource);
WriteLog(strFileName,strLog);
// WriteLog(strFileName,"--------------- DisksParser End --------------");
//////////////////////////////////////////////////////////////////////////
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
WriteLog(strFileName,"GetIniFileName is failed!");
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
//char matchLine[64] = {0};
//char matchLineNew[64]={0};
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
WriteLog(strFileName,"FormatSource is success!");
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("mulcpus", "ostype", 0, IniFileName);
if (nOsType == 1)
{
char matchLine[64]={0};
DFNParser_GetPrivateProfileString("mulcpus", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
char matchEnd[64]={0};
DFNParser_GetPrivateProfileString("mulcpus", "end", "", matchEnd, sizeof(matchEnd), IniFileName);
int nName = DFNParser_GetPrivateProfileInt("mulcpus", "name", 0, IniFileName);
strLog.Format("nName=%d\nnOsType=%d\nmatchEnd=%s",nName,nOsType,matchEnd);
WriteLog(strFileName,strLog);
POSITION pos = lstString.GetHeadPosition();
while(pos)
{
strTarget = lstString.GetNext(pos);
strLog.Format("strTarget=%s",strTarget);
WriteLog(strFileName,strLog);
CString strOut = _T("");
GetColumnFromLine(strTarget, nName, strOut, nMonitorType);
strLog.Format("strOut=%s",strOut);
WriteLog(strFileName,strLog);
if ((! strOut.Compare(matchEnd)) || (strOut.IsEmpty()))
{
break;
}
if(! strOut.Compare(matchLine))
{
continue;
}
sprintf(szOut,"%s%s$$$",szOut,strOut);
}
}
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL MulCPUParser(const char * szSource, const int nMonitorType, char *szOut, const char* szCpuName, const char *FileName)
{
BOOL bRet = FALSE;
//////////////////////////////////////////////////////////////////////////
//lish
CString strFileName;
strFileName = "MulCPUParser";
CString strLog = "";
WriteLog(strFileName,"--------------- MulCPUParser Start --------------");
// WriteLog(strFileName,szSource);
strLog.Format("IniFileName=%s,nMonitorType=%d\nszSource=%s",FileName,nMonitorType,szSource);
WriteLog(strFileName,strLog);
// WriteLog(strFileName,"--------------- DisksParser End --------------");
//////////////////////////////////////////////////////////////////////////
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
WriteLog(strFileName,"GetIniFileName is failed!");
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
//char matchLine[64] = {0};
//char matchLineNew[64]={0};
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "strTemp = " << strTemp << endl;
}
if (bRet)
{
WriteLog(strFileName,"FormatSource is success!");
int nOsType = DFNParser_GetPrivateProfileInt("mulcpus", "ostype", 0, IniFileName);
if (nOsType == 1) //Linux
{
//char matchLine[64]={0};
//DFNParser_GetPrivateProfileString("mulcpus", "matchline", "", matchLine, sizeof(matchLine), IniFileName);
char matchEnd[64]={0};
DFNParser_GetPrivateProfileString("mulcpus", "end", "", matchEnd, sizeof(matchEnd), IniFileName);
int nName = DFNParser_GetPrivateProfileInt("mulcpus", "name", 0, IniFileName);
int nUser = DFNParser_GetPrivateProfileInt("mulcpus", "user", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
int nSystem = DFNParser_GetPrivateProfileInt("mulcpus", "system", 0, IniFileName);
CString strUser = _T("");
CString strIdle = _T("");
CString strSystem = _T("");
strLog.Format("\nnName=%d\nnOsType=%d\nmatchEnd=%s",nName,nOsType,matchEnd);
WriteLog(strFileName,strLog);
strLog.Format("\nnUser=%d\nnIdle=%d\nnSystem=%d",nUser,nIdle,nSystem);
WriteLog(strFileName,strLog);
POSITION pos = lstString.GetHeadPosition();
while(pos)
{
strTarget = lstString.GetNext(pos);
strLog.Format("strTarget=%s",strTarget);
WriteLog(strFileName,strLog);
CString strName = _T("");
GetColumnFromLine(strTarget, nName, strName, nMonitorType);
strLog.Format("strOut=%s",strName);
WriteLog(strFileName,strLog);
if ( ( !strName.Compare(matchEnd) ) || (strName.IsEmpty()) )
{
bRet = FALSE;
break;
}
if ( !strName.Compare((LPCTSTR)szCpuName) )//找到指定cpu
{
GetColumnFromLine(strTarget, nUser, strUser, nMonitorType);
GetColumnFromLine(strTarget, nIdle, strIdle, nMonitorType);
GetColumnFromLine(strTarget, nSystem, strSystem, nMonitorType);
sprintf(szOut,"user=%s$system=%s$idle=%s$",strUser,strSystem,strIdle);
WriteLog(strFileName, szOut);
bRet = TRUE;
break;
}
//sprintf(szOut,"%s%s$$$",szOut,strName);
}
}
lstString.RemoveAll();
}
return bRet;
// return TRUE;
}
//////////////////////////////////////////////////////////////////////////
//yi.duan: 多cpu 2010.5.24
//////////////////////////////////////////////////////////////////////////
extern "C" __declspec(dllexport)
BOOL CPUsParser(const char * szSource, const int nMonitorType, char *szOut, const char* szCpuName, const char *FileName)
{
BOOL bRet = FALSE;
int nValue = 0;
int nMatchCount = 0;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
CString strFileName;
WriteLog(strFileName,"GetIniFileName is failed!");
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
//char matchLine[64] = {0};
//char matchLineNew[64]={0};
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName); // matchline 去掉不要的
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "strTemp = " << strTemp << endl;
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("mulcpus", "ostype", 0, IniFileName);
if (nOsType == 1) // Linux CentOS
{
/*安装了sysstat工具,有mpstat命令
int nReverse = DFNParser_GetPrivateProfileInt("mulcpus", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("mulcpus", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
//printf("%d -%d-%d\n",nReverse,nStart,nIdle);
//cout << "strTarget:"<<strTarget<<endl;
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"nIdle="<<nIdle<<endl;
//start add by mtx------------------------------------------------------------
//得到匹配列
int nMatchColumnLine = DFNParser_GetPrivateProfileInt("mulcpus", "matchColumnLine", 0, IniFileName);
char matchcolumnName[16] = {0};
DFNParser_GetPrivateProfileString("mulcpus", "matchcolumn", "", matchcolumnName, sizeof(matchcolumnName), IniFileName);
cout << "matchcolumnName:"<<matchcolumnName<<endl;
cout << "nMatchColumnLine:"<<nMatchColumnLine<<endl;
//判断是否有匹配列
if((matchcolumnName[0]>0) && (nMatchColumnLine>0))
{
int matchcolumn = 0;
//得到新的 dy:lstString 这里是只读。
if(GetMatchColumn(nMatchColumnLine,matchcolumnName,&lstString,matchcolumn))
{
nIdle = matchcolumn;
cout << "nIdle =" << nIdle <<endl;
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "新的strTemp = " << strTemp << endl;
}
nMatchCount = lstString.GetCount();
cout << " lstString.GetCount() = " << nMatchCount << endl;
}
}
//end add by mtx------------------------------------------------------------
CString strTemp = "";
CString strFinally= "";
int TotalRate = 0;
int i = 0;
while((nMatchCount-2)>i) // 第一行为字段,最好一行为空数据,去掉这2条
{
GetLineString(lstString, nReverse, nStart+i, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
cout <<"strOut:" <<strOut <<endl;
if (strOut.IsEmpty())
{
bRet = FALSE;
break;
}
else
{
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) //dy: 小于0,应该是数据读错了吧?2010.05.24
{
nValue = 0;
}
if(i==0) //dy 第一次得到是总的cpu使用率 2010.05.24
{
TotalRate = nValue;
}
else //每一个cpu的使用率
{
strTemp.Format("CPU%d:%d,",i-1, nValue); //cpu是从0开始计数
strFinally += strTemp;
}
i++;
}
}
strMsg.Format("utilization=%d$detailutilization=%s", TotalRate, strFinally);
strcpy(szOut, (LPCTSTR)strMsg); */
//-----------------------------------------------------------------------
// 没安装sysstat 解析cat /proc/stat
int nReverse = DFNParser_GetPrivateProfileInt("mulcpus", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("mulcpus", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
char matchEnd[64]={0};
DFNParser_GetPrivateProfileString("mulcpus", "end", "", matchEnd, sizeof(matchEnd), IniFileName);
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"matchEnd:"<< matchEnd <<endl;
CString strTemp = "";
CString strFinally= "";
CString strOut = _T("");
float idleValve = 0;
float CPUValve = 0;
int CPUNumber = 0; //cpu是从0开始计数
int TotalRate = 0;
POSITION pos = lstString.GetHeadPosition();
strTarget = lstString.GetNext(pos); //从第二条开始
while(pos)
{
strTarget = lstString.GetNext(pos);
cout <<"strTarget:"<< strTarget<<endl;
GetColumnFromLine(strTarget, 1, strOut); //看第一列是否为结束符
cout <<"while strOut:"<< strOut <<endl;
if ((!strOut.Compare(matchEnd)) || (strOut.IsEmpty()))
{
break; //第一列为结束符
}
for (int i=0; i<8; i++) //cpu有8列数值
{
float temp = 0;
GetColumnFromLine(strTarget, nIdle+i, strOut);
cout <<"for strOut:"<< strOut <<endl;
temp = atof((LPCTSTR)strOut);
if(temp < 0) //dy: 小于0,应该是数据读错了吧?2010.05.24
{
CPUValve = 0;
}
else //每一个cpu的使用率
{
if (i==4) //第四列为空闲
{
idleValve = temp;
}
CPUValve += temp;
}
}
TotalRate += 100 - (int)(100*(1-idleValve/CPUValve));
strTemp.Format("CPU%d:%d,",CPUNumber, 100 - (int)(100*(1-idleValve/CPUValve)));
strFinally += strTemp;
CPUNumber++;
}
strMsg.Format("utilization=%d$detailutilization=%s", TotalRate/CPUNumber, strFinally);
strMsg.TrimRight(',');
strcpy(szOut, (LPCTSTR)strMsg);
}
else if(nOsType == 2)
{ // Solaris
int nReverse = DFNParser_GetPrivateProfileInt("mulcpus", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("mulcpus", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"nIdle="<<nIdle<<endl;
int nMatchColumnLine = DFNParser_GetPrivateProfileInt("mulcpus", "matchColumnLine", 0, IniFileName);
char matchcolumnName[16] = {0};
DFNParser_GetPrivateProfileString("mulcpus", "matchcolumn", "", matchcolumnName, sizeof(matchcolumnName), IniFileName);
cout << "matchcolumnName:"<<matchcolumnName<<endl;
cout << "nMatchColumnLine:"<<nMatchColumnLine<<endl;
//判断是否有匹配列
if((matchcolumnName[0]>0) && (nMatchColumnLine>0))
{
int matchcolumn = 0;
//得到新的 dy:lstString 这里是只读。
if(GetMatchColumn(nMatchColumnLine,matchcolumnName,&lstString,matchcolumn))
{
nIdle = matchcolumn;
cout << "nIdle =" << nIdle <<endl;
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "新的strTemp = " << strTemp << endl;
}
nMatchCount = lstString.GetCount();
cout << " lstString.GetCount() = " << nMatchCount << endl;
}
}
CString strTemp = "";
CString strFinally= "";
int TotalRate = 0;
int i = 0;
while((nMatchCount-2)>i) // 第一行为字段,最好一行为空数据,去掉这2条 求出有几个cpu
{
GetLineString(lstString, nReverse, nStart+i, strTarget);
// cout <<"strTarget:\n"<<strTarget<<endl;
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
// cout <<"strOut:" <<strOut <<endl;
if (strOut.IsEmpty())
{
bRet = FALSE;
break;
}
else
{
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) //dy: 小于0,应该是数据读错了吧?2010.05.24
{
nValue = 0;
}
strTemp.Format("CPU%d:%d,",i, nValue); //cpu是从0开始计数
strFinally += strTemp;
TotalRate += nValue;
i++;
}
}
TotalRate = TotalRate/(nMatchCount-2); //Solaris 没有总cpu利用率
if (strFinally.GetLength()>1024)//yi.duan 2011-10-19 字符组过长导致monitorSchudle解析不了
{
strFinally = strFinally.Left(512);
}
strMsg.Format("utilization=%d$detailutilization=%s", TotalRate, strFinally);
strMsg.TrimRight(',');
strcpy(szOut, (LPCTSTR)strMsg);
}
else if(nOsType == 3)
{ // FreeBSD
int nReverse = DFNParser_GetPrivateProfileInt("mulcpus", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("mulcpus", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
GetLineString(lstString, nReverse, nStart, strTarget);
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
if (strOut.IsEmpty())
bRet = FALSE;
else
{
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) nValue = 0;
strMsg.Format("utilization=%d$", nValue);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
else if (nOsType == 4)
{ // HPUX
int nReverse = DFNParser_GetPrivateProfileInt("mulcpus", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("mulcpus", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"nIdle="<<nIdle<<endl;
int nMatchColumnLine = DFNParser_GetPrivateProfileInt("mulcpus", "matchColumnLine", 0, IniFileName);
char matchcolumnName[16] = {0};
DFNParser_GetPrivateProfileString("mulcpus", "matchcolumn", "", matchcolumnName, sizeof(matchcolumnName), IniFileName);
cout << "matchcolumnName:"<<matchcolumnName<<endl;
cout << "nMatchColumnLine:"<<nMatchColumnLine<<endl;
nMatchCount = lstString.GetCount();
cout << " lstString.GetCount() = " << nMatchCount << endl;
CString strTemp = "";
CString strFinally= "";
int TotalRate = 0;
int i = 0;
while((nMatchCount-2)>i)
{
GetLineString(lstString, nReverse, nStart+i, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strOut = _T("");
GetColumnFromLine(strTarget, nIdle, strOut);
cout <<"strOut:" <<strOut <<endl;
if (strOut.IsEmpty())
{
break;
}
else
{
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) //dy: 小于0,应该是数据读错了吧?2010.05.24
{
nValue = 0;
}
strTemp.Format("CPU%d:%d,",i, nValue); //cpu是从0开始计数
strFinally += strTemp;
TotalRate += nValue;
i++;
cout <<"strTemp:" <<strTemp <<endl;
}
}
TotalRate = TotalRate/(nMatchCount-2); //HP
strMsg.Format("utilization=%d$detailutilization=%s", TotalRate, strFinally);
strMsg.TrimRight(',');
strcpy(szOut, (LPCTSTR)strMsg);
}
else if (nOsType == 5)
{ // AIX
int nReverse = DFNParser_GetPrivateProfileInt("mulcpus", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("mulcpus", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("mulcpus", "idle", 0, IniFileName);
cout <<"nReverse:"<< nReverse<<endl;
cout <<"nStart:"<<nStart <<endl;
cout <<"nIdle="<<nIdle<<endl;
int nMatchColumnLine = DFNParser_GetPrivateProfileInt("mulcpus", "matchColumnLine", 0, IniFileName);
char matchcolumnName[16] = {0};
DFNParser_GetPrivateProfileString("mulcpus", "matchcolumn", "", matchcolumnName, sizeof(matchcolumnName), IniFileName);
cout << "matchcolumnName:"<<matchcolumnName<<endl;
cout << "nMatchColumnLine:"<<nMatchColumnLine<<endl;
nMatchCount = lstString.GetCount();
cout << " lstString.GetCount() = " << nMatchCount << endl;
CString strTemp = "";
CString strFinally= "";
int TotalRate = 0;
int i = 0;
while((nMatchCount-2)>i)
{
GetLineString(lstString, nReverse, nStart+i, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strOut = _T("");
if (i==0) //如果是第一行 值在第六列
{
GetColumnFromLine(strTarget, nIdle+1, strOut);
}
else
{
GetColumnFromLine(strTarget, nIdle, strOut);
}
cout <<"strOut:" <<strOut <<endl;
if (strOut.IsEmpty())
{
break;
}
else
{
nValue = 100 - atoi((LPCTSTR)strOut);
if(nValue < 0) //dy: 小于0,应该是数据读错了吧?2010.05.24
{
nValue = 0;
}
strTemp.Format("CPU%d:%d,",i, nValue); //cpu是从0开始计数
strFinally += strTemp;
TotalRate += nValue;
i++;
cout <<"strTemp:" <<strTemp <<endl;
}
}
TotalRate = TotalRate/(nMatchCount-2); //HP
strMsg.Format("utilization=%d$detailutilization=%s", TotalRate, strFinally);
strMsg.TrimRight(',');
strcpy(szOut, (LPCTSTR)strMsg);
}
else
{
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL MemoryIOParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
//////////////////////////////////////////////////////////////////////////
//lish
CString strFileName;
strFileName = "MemoryIOParser";
CString strLog = "";
//WriteLog(strFileName,"--------------- MemoryIOParser Start --------------");
// WriteLog(strFileName,szSource);
cout << "--------------- MemoryIOParser Start --------------" << endl;
strLog.Format("IniFileName=%s,nMonitorType=%d\nszSource=%s",FileName,nMonitorType,szSource);
//WriteLog(strFileName,strLog);
//////////////////////////////////////////////////////////////////////////
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
WriteLog(strFileName,"GetIniFileName is failed!");
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
//char matchLine[64] = {0};
//char matchLineNew[64]={0};
float fSiVal=0, fSoVal=0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (!bRet)
{
WriteLog(strFileName,"FormatSource is failed!");
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("memoryio", "ostype", 0, IniFileName);
if (1== nOsType) //Linux CentOS
{
int nReverse = DFNParser_GetPrivateProfileInt("memoryio", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memoryio", "startline", 0, IniFileName);
int nSi = DFNParser_GetPrivateProfileInt("memoryio", "si", 0, IniFileName);
int nSo = DFNParser_GetPrivateProfileInt("memoryio", "so", 0, IniFileName);
cout << "nReverse:" << nReverse <<endl;
cout << "nStart:" << nStart<<endl;
cout << "nSi:" << nSi <<endl;
cout << "nSo:" << nSo <<endl;
GetLineString(lstString, nReverse, nStart, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strSi = _T("");
CString strSo = _T("");
GetColumnFromLine(strTarget, nSi, strSi);
GetColumnFromLine(strTarget, nSo, strSo);
cout << "strSi:" <<strSi <<endl;
cout << "strSo:" << strSo <<endl;
if (strSi.IsEmpty() || strSo.IsEmpty())
{
bRet = FALSE;
}
else
{
fSiVal = atof((LPCTSTR)strSi);
fSoVal = atof((LPCTSTR)strSo);
strMsg.Format("PagesInPerSec=%.2f$PagesOutPerSec=%.2f$PagesPerSec=%.2f$",fSiVal,fSoVal,fSiVal+fSoVal);
strcpy(szOut, (LPCTSTR)strMsg);
cout <<"szOut:" << szOut <<endl;
}
}
else if (2 == nOsType) //Solaris && AIX
{
//cout << "IniFileName:" << IniFileName << endl;
int nReverse = DFNParser_GetPrivateProfileInt("memoryio", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memoryio", "startline", 0, IniFileName);
int nSi = DFNParser_GetPrivateProfileInt("memoryio", "pi", 0, IniFileName);
int nSo = DFNParser_GetPrivateProfileInt("memoryio", "po", 0, IniFileName);
int nFree = DFNParser_GetPrivateProfileInt("memoryio", "free", 0, IniFileName);
int nUnit = DFNParser_GetPrivateProfileInt( "memoryio", "unit", 0, IniFileName );
cout << "nReverse:" << nReverse << endl;
cout << "nStart:" << nStart<< endl;
cout << "nFree:" << nFree << endl;
cout << "nUnit:" << nUnit << endl;
cout << "nSi:" << nSi << endl;
cout << "nSo:" << nSo << endl;
GetLineString(lstString, nReverse, nStart, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strSi = _T("");
CString strSo = _T("");
CString strFree = _T("");
GetColumnFromLine(strTarget, nSi, strSi);
GetColumnFromLine(strTarget, nSo, strSo);
GetColumnFromLine(strTarget, nFree, strFree);
cout << "strSi:" <<strSi << endl;
cout << "strSo:" << strSo << endl;
cout << "strFree:" << strFree << endl;
if (strSi.IsEmpty() || strSo.IsEmpty() || strFree.IsEmpty())
{
bRet = FALSE;
}
else
{
fSiVal = atof((LPCTSTR)strSi);
fSoVal = atof((LPCTSTR)strSo);
float fFree = atof((LPCTSTR) strFree);
fFree *= nUnit ;
strMsg.Format("PagesInPerSec=%.2f$PagesOutPerSec=%.2f$PagesPerSec=%.2f$Mbfree=%.2f$"
,fSiVal,fSoVal,fSiVal+fSoVal,fFree);
strcpy(szOut, (LPCTSTR)strMsg);
cout <<"szOut:" << szOut <<endl;
}
//return FALSE;
}
else if (nOsType ==3)//hp
{
int nReverse = DFNParser_GetPrivateProfileInt("memoryio", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("memoryio", "startline", 0, IniFileName);
int nSi = DFNParser_GetPrivateProfileInt("memoryio", "si", 0, IniFileName);
int nSo = DFNParser_GetPrivateProfileInt("memoryio", "so", 0, IniFileName);
cout << "nReverse:" << nReverse <<endl;
cout << "nStart:" << nStart<<endl;
cout << "nSi:" << nSi <<endl;
cout << "nSo:" << nSo <<endl;
GetLineString(lstString, nReverse, nStart, strTarget);
cout <<"strTarget:\n"<<strTarget<<endl;
CString strSi = _T("");
CString strSo = _T("");
CString strFree = _T("");
GetColumnFromLine(strTarget, nSi, strSi);
GetColumnFromLine(strTarget, nSo, strSo);
cout << "strSi:" <<strSi << endl;
cout << "strSo:" << strSo << endl;
if (strSi.IsEmpty() || strSo.IsEmpty())
{
bRet = FALSE;
}
/*POSITION pos = lstString.GetHeadPosition();
CString strVal = _T("");
while(pos)
{
strVal = lstString.GetNext(pos);
cout << "strVal:" << strVal << endl;
}*/
fSiVal = atof((LPCTSTR)strSi);
fSoVal = atof((LPCTSTR)strSo);
strMsg.Format("PagesInPerSec=%.2f$PagesOutPerSec=%.2f$PagesPerSec=%.2f$"
,fSiVal,fSoVal,fSiVal+fSoVal);
strcpy(szOut, (LPCTSTR)strMsg);
cout <<"szOut:" << szOut <<endl;
//return FALSE;
}
else
{
return FALSE;
}
}
return bRet;
}
BOOL FormatStr(CStringList& pList, CString strIn)
{
if (strIn.IsEmpty())
{
return FALSE;
}
int nLen = strIn.GetLength();
CString str = _T("");
TCHAR ch;
for (int i = 0; i < nLen; i++)
{
ch = strIn.GetAt(i);
if (ch == ' ')
continue;
str = strIn.Right(nLen - i);
str = str.SpanExcluding(" ");
pList.AddTail(str);
i += str.GetLength();
}
return TRUE;
}
int ReturnSecond(CString str)
{
int nSecond = 0;
int nDay = 0;
int nHour = 0;
int nMin = 0;
CString strTemp = str;
CString strPre = _T("");
CString strTime = _T("");
bool bTime = false;
CStringList pList;
FormatStr(pList, str);
POSITION pos = pList.GetHeadPosition();
while(pos)
{
strPre = strTemp;
strTemp = pList.GetNext(pos);
if(strstr(strTemp, "up"))
{
bTime = true;
}
else if (strstr(strTemp, "day" ))
{
nDay = atoi((LPCTSTR)strPre);
}
else if (strstr(strTemp, "min"))
{
nMin = atoi((LPCTSTR)strPre);
break;
}
else if (strstr(strTemp,":"))
{
if (bTime)
{
strTime = strTemp;
break;
}
}
}
if ( !strTime.IsEmpty())
{
int nPos = strTime.Find(":",0);
nHour = atoi(strTime.Left(nPos));
nMin = atoi(strTime.Right(strTime.GetLength() - nPos -1));
}
nSecond = nDay*24*60*60;
nSecond += nHour*60*60;
nSecond += nMin*60;
return nSecond;
}
float ReturnAverageLoad(CString str)
{
float fAvgLoad = 0.00;
CStringList pList;
CString strLoad = _T("");
FormatStr(pList, str);
POSITION pos = pList.GetTailPosition();
strLoad = pList.GetPrev(pos);
fAvgLoad = atof(strLoad);
return fAvgLoad;
}
extern "C" __declspec(dllexport)
BOOL SystemTimeParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
CString strFile = "SystemTimeParser";
cout << "-------------- SystemTimeParser start ---------------" <<endl;
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
//WriteLog(strFileName,"GetIniFileName is failed!");
cout << "----------- GetIniFileName failed -----------------" <<endl;
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
//char matchLine[64] = {0};
//char matchLineNew[64]={0};
float fRunVal=0.00, fIdleVal=0.00, fRunPercent=0.00;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
cout << "------------ GetIniFileName is success -----------------"<<endl;
cout << "szSource:" <<szSource <<endl;
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("systime", "ostype", 0, IniFileName);
if (1 == nOsType) //Linux
{
strTarget = szSource;
int nReverse = DFNParser_GetPrivateProfileInt("systime", "reverselines", 0, IniFileName);
int nStart = DFNParser_GetPrivateProfileInt("systime", "startline", 0, IniFileName);
int nIdle = DFNParser_GetPrivateProfileInt("systime", "idle", 0, IniFileName);
int nRun = DFNParser_GetPrivateProfileInt("systime", "run", 0, IniFileName);
cout << "nReverse: " << nReverse<< endl;
cout << "nStart:" << nStart<< endl;
cout << "nIdle:" <<nIdle << endl;
cout << "nRun:" << nRun<< endl;
CString strRun = _T("");
CString strIdle = _T("");
GetColumnFromLine( strTarget, nRun, strRun );
GetColumnFromLine( strTarget, nIdle, strIdle);
cout << "strRun:" << strRun << endl;
cout << "strIdle:" << strIdle <<endl;
if (strRun.IsEmpty() || strIdle.IsEmpty())
{
bRet = FALSE;
}
else
{
fRunVal = atof((LPCTSTR)strRun);
fIdleVal = atof((LPCTSTR) strIdle);
fRunPercent = (fRunVal - fIdleVal)/fRunVal;
if (fRunPercent < 0 )
{
fRunPercent = 0.00;
}
if (fRunPercent > 100)
{
fRunPercent = 100.00;
}
strMsg.Format("systemRunTime=%.2f$systemIdleTime=%.2f$systemRunLoad=%.2f$$",fRunVal, fIdleVal, fRunPercent );
//cout << "strMsg:" << strMsg <<endl;
strcpy(szOut, (LPCTSTR)strMsg);
cout <<"szOut:" << szOut <<endl;
}
}
else if(2 == nOsType)
{
strTarget = szSource;
fRunVal = (float)ReturnSecond(strTarget);
fRunPercent = ReturnAverageLoad(strTarget);
fIdleVal = fRunVal*(1-fRunPercent);
strMsg.Format("systemRunTime=%.2f$systemIdleTime=%.2f$systemRunLoad=%.2f$$",fRunVal, fIdleVal, fRunPercent);
strcpy(szOut, (LPCTSTR)strMsg);
cout <<"szOut:" << szOut <<endl;
//return FALSE;
}
else
{
return FALSE;
}
}
return TRUE;
}
BOOL GetProColumnIndex(CStringList& lstStr, int& nColumn,char*IniFileName)
{
BOOL bRet = FALSE;
char buffer[32] = {0};
DFNParser_GetPrivateProfileString("process", "namecolumnname", "", buffer, sizeof(buffer), IniFileName);
//cout <<"buffer:"<<buffer <<endl;
CString strIn = lstStr.GetHead();
int nLen = strIn.GetLength();
//cout << "nLen:"<<nLen <<endl;
TCHAR ch;
CString str = _T("");
int j = 0;
for (int i = 0; i < nLen; i++)
{
ch = strIn.GetAt(i);
if (ch == char_space)
continue;
j++;
str = strIn.Right(nLen - i);
str = str.SpanExcluding(" ");
//cout << "str:" <<str <<endl;
if (!str.Compare(buffer))
{
nColumn = j;
bRet = TRUE;
break;
}
i += str.GetLength();
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL ProcessParser(const char * szSource, const int nMonitorType, char *szOut, const char* szProcName, const char *FileName)
{
BOOL bRet = FALSE;
cout << "-------------- ProcessParser Start! -------------------"<<endl;
CString strFile = _T("ProcessParser");
CString strLog = _T("");
WriteLog(strFile, "-------------- ProcessParser Start! -------------------");
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
cout << "-------------- GetIniFileName failed! ---------------"<<endl;
WriteLog(strFile,"-------------- GetIniFileName failed! ---------------");
return bRet;
}
cout << "----------------- GetIniFileName is success ---------------"<<endl;
WriteLog(strFile,"----------------- GetIniFileName is success ---------------");
CStringList lstString;
CStringList lstProcs;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
int nColumn = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (!bRet)
{
cout << "--------------- FormatSource is failed ----------------"<<endl;
WriteLog(strFile, "--------------- FormatSource is failed ----------------");
}
//WriteLog(strFile,"---------------------- FormatSource is success ------------");
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("process", "ostype", 0, IniFileName);
strLog.Format("nOsType=%d",nOsType);
WriteLog(strFile,strLog);
int j = 0;
if (nOsType == 1)
{ // Linux
//strLog.Format("nOsType:1");
//WriteLog(strFile, strLog);
bRet = GetProColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
//WriteLog("--------------- GetColumnIndex Success ----------------");
int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
CString strCPU = _T("");
CString strMem = _T("");
CString strStat= _T("");
CString strTime= _T("");
float fMemSize = 0.00, fCpuPercent=0.00;
int nCpuColumn = DFNParser_GetPrivateProfileInt("process", "cpupercent", 0, IniFileName);
int nMemColumn = DFNParser_GetPrivateProfileInt("process", "phymemsize", 0, IniFileName);
int nTimeColumn = DFNParser_GetPrivateProfileInt("process", "starttime", 0, IniFileName);
int nStatColumn = DFNParser_GetPrivateProfileInt("process", "stat", 0, IniFileName);
/*strLog.Format("nCpuColumn=%d; nMemColumn=%d; nTimeColumn=%d; nStatColumn=%d",nCpuColumn,nMemColumn,nTimeColumn,nStatColumn);
WriteLog(strFile, strLog);
strLog.Format("szProcName:%s",szProcName);
WriteLog(strFile,strLog);*/
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
//puts(strOut);
//cout << "strOut:" << strOut <<endl;
j++;
if (szProcName == NULL)
{
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1)
{
BOOL bFound = FALSE;
while (pos1)
{
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut))
{
bFound = TRUE;
break;
}
}
if (!bFound)
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
//cout << "--------------- szProcName == NULL -------------" <<endl;
if (!stricmp((LPCTSTR)strOut, szProcName))
{
GetColumnFromLine(strTarget, nCpuColumn, strCPU);
GetColumnFromLine(strTarget, nMemColumn, strMem);
GetColumnFromLine(strTarget, nStatColumn, strStat);
GetColumnFromLine(strTarget, nTimeColumn, strTime);
cout << "----------------- Find Process success ------------"<<endl;
cout << "strCpu:"<<strCPU <<endl;
cout << "strMem:"<<strMem <<endl;
cout << "strStat:"<<strStat <<endl;
cout << "strTime:"<<strTime <<endl;
fMemSize = atof((LPCTSTR)strMem);
fCpuPercent = atof((LPCTSTR)strCPU);
cout << "fMemSize:" << fMemSize<<endl;
cout << "fCpuPercent:"<<fCpuPercent<<endl;
nProcesses++;
break;
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$ProcessOccupyCPUTime=%.2f$PhysicalMemory=%.2f$ProcessStatus=%s$ProcessStartTime=%s$$",
nProcesses,fCpuPercent,fMemSize,strStat,strTime);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
}
}
}
else if (nOsType == 2)
{
bRet = GetProColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
//WriteLog("--------------- GetColumnIndex Success ----------------");
int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
CString strCPU = _T("");
CString strMem = _T("");
CString strStat= _T("");
CString strTime= _T("");
float fMemSize = 0.00, fCpuPercent=0.00;
int nCpuColumn = DFNParser_GetPrivateProfileInt("process", "cpupercent", 0, IniFileName);
int nMemColumn = DFNParser_GetPrivateProfileInt("process", "phymemsize", 0, IniFileName);
int nTimeColumn = DFNParser_GetPrivateProfileInt("process", "starttime", 0, IniFileName);
int nStatColumn = DFNParser_GetPrivateProfileInt("process", "stat", 0, IniFileName);
/*strLog.Format("nCpuColumn=%d; nMemColumn=%d; nTimeColumn=%d; nStatColumn=%d",nCpuColumn,nMemColumn,nTimeColumn,nStatColumn);
WriteLog(strFile, strLog);
strLog.Format("szProcName:%s",szProcName);
WriteLog(strFile,strLog);*/
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
//puts(strOut);
//cout << "strOut:" << strOut <<endl;
j++;
if (szProcName == NULL)
{
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1)
{
BOOL bFound = FALSE;
while (pos1)
{
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut))
{
bFound = TRUE;
break;
}
}
if (!bFound)
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
//cout << "--------------- szProcName == NULL -------------" <<endl;
if (!stricmp((LPCTSTR)strOut, szProcName))
{
GetColumnFromLine(strTarget, nCpuColumn, strCPU);
GetColumnFromLine(strTarget, nMemColumn, strMem);
GetColumnFromLine(strTarget, nStatColumn, strStat);
GetColumnFromLine(strTarget, nTimeColumn, strTime);
cout << "----------------- Find Process success ------------"<<endl;
cout << "strCpu:"<<strCPU <<endl;
cout << "strMem:"<<strMem <<endl;
cout << "strStat:"<<strStat <<endl;
cout << "strTime:"<<strTime <<endl;
fMemSize = atof((LPCTSTR)strMem);
fCpuPercent = atof((LPCTSTR)strCPU);
cout << "fMemSize:" << fMemSize<<endl;
cout << "fCpuPercent:"<<fCpuPercent<<endl;
nProcesses++;
break;
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$ProcessOccupyCPUTime=%.2f$PhysicalMemory=%.2f$ProcessStatus=%s$ProcessStartTime=%s$$",
nProcesses,fCpuPercent,fMemSize,strStat,strTime);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
}
}
}
else if (3 == nOsType)
{
CString str = _T("aix");
CString strT = _T("");
WriteLog(str ,"---------------- aix call ------------");
WriteLog(str, szSource);
bRet = GetProColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
WriteLog(str,"----------- bRet:True -------------");
int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
strT.Format("nColumn:%d",nColumn);
WriteLog(str, strT);
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
CString strCPU = _T("");
CString strMem = _T("");
CString strStat= _T("");
CString strTime= _T("");
float fMemSize = 0.00, fCpuPercent=0.00;
int nCpuColumn = DFNParser_GetPrivateProfileInt("process", "cpupercent", 0, IniFileName);
int nMemColumn = DFNParser_GetPrivateProfileInt("process", "phymemsize", 0, IniFileName);
int nTimeColumn = DFNParser_GetPrivateProfileInt("process", "starttime", 0, IniFileName);
int nStatColumn = DFNParser_GetPrivateProfileInt("process", "stat", 0, IniFileName);
strT.Format("nCpuColumn:%d; nMemColumn:%d; nTimeColumn=%d; nStatColumn=%d",nCpuColumn,nMemColumn,nTimeColumn,nStatColumn);
WriteLog(str, strT);
int i =0;
while(pos)
{
i ++;
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
strOut.TrimLeft(" ");
strT.Format("i=%d strOut:%s",i,strOut);
WriteLog(str, strT);
j++;
if (szProcName == NULL)
{
if (j <= 1)
continue;
//if (!strOut.IsEmpty())
//{
//lstProcs.AddTail(strOut);
//sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
//WriteLog(str, szOut);
//}
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1)
{
BOOL bFound = FALSE;
while (pos1)
{
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut))
{
bFound = TRUE;
break;
}
}
if (!bFound)
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
//WriteLog(str, strOut);
}
}
else
{
//cout << "--------------- szProcName == NULL -------------" <<endl;
if (!stricmp((LPCTSTR)strOut, szProcName))
{
GetColumnFromLine(strTarget, nCpuColumn, strCPU);
GetColumnFromLine(strTarget, nMemColumn, strMem);
GetColumnFromLine(strTarget, nStatColumn, strStat);
GetColumnFromLine(strTarget, nTimeColumn, strTime);
cout << "----------------- Find Process success ------------"<<endl;
cout << "strCpu:"<<strCPU <<endl;
cout << "strMem:"<<strMem <<endl;
cout << "strStat:"<<strStat <<endl;
cout << "strTime:"<<strTime <<endl;
fMemSize = atof((LPCTSTR)strMem);
fCpuPercent = atof((LPCTSTR)strCPU);
cout << "fMemSize:" << fMemSize<<endl;
cout << "fCpuPercent:"<<fCpuPercent<<endl;
nProcesses++;
break;
}
}
}
WriteLog(str, szOut);
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$ProcessOccupyCPUTime=%.2f$PhysicalMemory=%.2f$ProcessStatus=%s$ProcessStartTime=%s$$",
nProcesses,fCpuPercent,fMemSize,strStat,strTime);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
}
}
bRet = FALSE;
}
else if (4 == nOsType)
{
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
//puts(strOut);
cout << "strOut:" << strOut <<endl;
j++;
if (szProcName == NULL)
{
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1)
{
BOOL bFound = FALSE;
while (pos1)
{
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut))
{
bFound = TRUE;
break;
}
}
if (!bFound)
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
if (!stricmp((LPCTSTR)strOut, szProcName))
{
//if (!strOut.Compare(szProcName)) {
nProcesses++;
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Processes=%d$", nProcesses);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
else
{
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
//extern "C" __declspec(dllexport)
//BOOL ProcessParser(const char * szSource, const int nMonitorType, char *szOut, const char* szProcName, const char *FileName)
//{
// //AddToLogFile(nMonitorType, szSource);
//
// BOOL bRet = FALSE;
//
// cout << "-------------- ProcessParser Start! -------------------"<<endl;
//
// char IniFileName[1024]={0};
// bRet = GetIniFileName(FileName,IniFileName);
// if (!bRet)
// {
// cout << "-------------- GetIniFileName failed! ---------------"<<endl;
// return bRet;
// }
// cout << "----------------- GetIniFileName is success ---------------"<<endl;
//
// CStringList lstString;
// CStringList lstProcs;
//
// CString strTarget = _T("");
// CString strMsg = _T("");
//
// int nValue = 0;
// int nColumn = 0;
//
// bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
// if (!bRet)
// {
// cout << "--------------- FormatSource is failed ----------------"<<endl;
// }
//
// if (bRet)
// {
// int nOsType = DFNParser_GetPrivateProfileInt("process", "ostype", 0, IniFileName);
//
// int j = 0;
// if (nOsType == 1)
// { // Linux
// cout << "---------- Linux System ------------- " <<endl;
// bRet = GetProColumnIndex(lstString, nColumn,IniFileName);
// cout << "nColumn:" << nColumn <<endl;
//
// if (bRet)
// {
// cout << "-------------- GetColumnIndex Success ---------------------" <<endl;
//
// int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
// cout << "nTempColumn:" << nTempColumn <<endl;
// cout << "szProcName:"<<szProcName <<endl;
// if (nTempColumn)
// {
// if (nTempColumn != nColumn)
// nColumn = nTempColumn;
// }
//
// POSITION pos = lstString.GetHeadPosition();
// CString strOut = _T("");
// int nProcesses = 0;
// CString strCPU = _T("");
// CString strMem = _T("");
// CString strStat= _T("");
// CString strTime= _T("");
// int nCpuColumn = DFNParser_GetPrivateProfileInt("process", "cpupercent", 0, IniFileName);
// int nMemColumn = DFNParser_GetPrivateProfileInt("process", "phymemsize", 0, IniFileName);
// int nTimeColumn = DFNParser_GetPrivateProfileInt("process", "starttime", 0, IniFileName);
// int nStatColumn = DFNParser_GetPrivateProfileInt("process", "stat", 0, IniFileName);
// cout << "nCpuColumn:" << nCpuColumn <<endl;
// cout << "nMemColumn:" << nMemColumn <<endl;
// cout << "nTimeColumn:" << nTimeColumn <<endl;
// cout << "nStatColumn:" << nStatColumn <<endl;
//
// while (pos)
// {
// strTarget = lstString.GetNext(pos);
// GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
// strOut.TrimRight(" ");
// //cout << "strTarget:"<<strTarget<<endl;
// cout << "strOut:"<<strOut <<endl;
// //puts(strOut);
// if (!stricmp((LPCTSTR)strOut, szProcName))
// {
// GetColumnFromLine(strTarget, nCpuColumn, strCPU, nMonitorType);
// GetColumnFromLine(strTarget, nMemColumn, strMem, nMonitorType);
// GetColumnFromLine(strTarget, nStatColumn, strStat, nMonitorType);
// GetColumnFromLine(strTarget, nTimeColumn, strTime, nMonitorType);
//
// cout << "strCpu:"<<strCPU <<endl;
// cout << "strMem:"<<strMem <<endl;
// cout << "strStat:"<<strStat <<endl;
// cout << "strTime:"<<strTime <<endl;
// }
// }
//
// if(szProcName != NULL)
// {
// strMsg.Format("Processes=%d$", nProcesses);
// strcpy(szOut, (LPCTSTR)strMsg);
// }
// }
// }
//
// else
// {
// bRet = FALSE;
// }
//
// lstString.RemoveAll();
// }
// return bRet;
//}
//
//
//
extern "C" __declspec(dllexport)
BOOL DISKIOParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
cout << "-------------- DISKIOParser start ---------------" <<endl;
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
//WriteLog(strFileName,"GetIniFileName is failed!");
cout << "----------- GetIniFileName failed -----------------" <<endl;
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
float fReadVal=0, fWriteVal=0, fTransVal=0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (!bRet)
{
cout << "--------------- FormatSource is failed! --------------"<<endl;
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("diskio", "ostype", 0, IniFileName);
if (1 == nOsType) //Linux
{
cout << "------------ Linux System --------------"<<endl;
POSITION pos = lstString.GetHeadPosition();
//int nLen = lstString.GetSize();
//cout << "nLen:" <<nLen <<endl;
CString strDevice = _T("");
CString strRead = _T("");
CString strWrite = _T("");
int nDeviceColumn = DFNParser_GetPrivateProfileInt("diskio", "device", 0, IniFileName);
int nWriteColumn = DFNParser_GetPrivateProfileInt("diskio", "write", 0, IniFileName);
int nReadColumn = DFNParser_GetPrivateProfileInt("diskio", "read", 0, IniFileName);
cout << "nDeviceColumn:" << nDeviceColumn << endl;
cout << "nWriteColumn:" << nWriteColumn << endl;
cout << "nReadColumn:" << nReadColumn << endl;
while(pos)
{
strTarget = lstString.GetNext(pos);
//cout << strTarget << endl;
GetColumnFromLine(strTarget, nDeviceColumn, strDevice);
//IDE硬盘和SCSI硬盘
if ( !stricmp((LPCTSTR)strDevice, "hda") || !stricmp((LPCTSTR)strDevice, "sda") )
{
cout << "strDevice:" << strDevice <<endl;
GetColumnFromLine(strTarget, nReadColumn, strRead);
GetColumnFromLine(strTarget, nWriteColumn, strWrite);
cout << "strWrite:" << strWrite << endl;
cout << "strRead:" << strRead <<endl;
fReadVal = atof((LPCTSTR) strRead);
fWriteVal = atof( (LPCTSTR) strWrite);
fTransVal = fReadVal + fWriteVal ;
break;
}
}
strMsg.Format("ReadPerSec=%.2f$WritePerSec=%.2f$TransfersPerSec=%.2f$$",fReadVal, fWriteVal ,fTransVal);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
}
else if (2 == nOsType)
{
cout << "------------ Solaris System --------------"<<endl;
POSITION pos = lstString.GetHeadPosition();
int nStart = DFNParser_GetPrivateProfileInt("diskio", "startline", 0, IniFileName);
CString strDevice = _T("");
CString strRead = _T("");
CString strWrite = _T("");
int nDeviceColumn = DFNParser_GetPrivateProfileInt("diskio", "device", 0, IniFileName);
int nWriteColumn = DFNParser_GetPrivateProfileInt("diskio", "write", 0, IniFileName);
int nReadColumn = DFNParser_GetPrivateProfileInt("diskio", "read", 0, IniFileName);
cout << "nDeviceColumn:" << nDeviceColumn << endl;
cout << "nWriteColumn:" << nWriteColumn << endl;
cout << "nReadColumn:" << nReadColumn << endl;
cout << "nStart" <<nStart << endl;
while(pos)
{
nStart --;
strTarget = lstString.GetNext(pos);
cout <<"strTarget:" << strTarget << endl;
if (nStart<=0)
{
GetColumnFromLine(strTarget, nReadColumn, strRead);
GetColumnFromLine(strTarget, nWriteColumn, strWrite);
//cout << "strWrite:" << strWrite << endl;
//cout << "strRead:" << strRead <<endl;
fReadVal += atof((LPCTSTR) strRead);
fWriteVal += atof( (LPCTSTR) strWrite);
}
}
fTransVal = (fReadVal + fWriteVal) ;
cout << fReadVal << endl;
cout << fWriteVal << endl;
cout << fTransVal << endl;
strMsg.Format("ReadPerSec=%.2f$WritePerSec=%.2f$TransfersPerSec=%.2f$$",fReadVal, fWriteVal ,fTransVal);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
//bRet = FALSE;
}
else if (3 == nOsType)
{
POSITION pos = lstString.GetHeadPosition();
int nStart = DFNParser_GetPrivateProfileInt("diskio", "startline", 0, IniFileName);
int nReadColumn = DFNParser_GetPrivateProfileInt("diskio", "read", 0, IniFileName);
int nWriteColumn = DFNParser_GetPrivateProfileInt("diskio", "write", 0, IniFileName);
cout << "nStart:" << nStart <<endl;
cout << "nReadColumn:" << nReadColumn <<endl;
cout << "nWriteColumn:" << nWriteColumn <<endl;
CString strRead = _T("");
CString strWrite = _T("");
while(pos)
{
nStart --;
strTarget = lstString.GetNext(pos);
cout <<"strTarget:" << strTarget << endl;
if (nStart == 0)
{
cout << nStart <<":"<<"strTarget:" << strTarget << endl;
GetColumnFromLine(strTarget, nReadColumn, strRead);
GetColumnFromLine(strTarget, nWriteColumn, strWrite);
cout << "strWrite:" << strWrite << endl;
cout << "strRead:" << strRead <<endl;
fReadVal = atof((LPCTSTR) strRead);
fWriteVal = atof( (LPCTSTR) strWrite);
fTransVal = fReadVal + fWriteVal ;
break;
}
}
strMsg.Format("ReadPerSec=%.2f$WritePerSec=%.2f$TransfersPerSec=%.2f$$",fReadVal, fWriteVal ,fTransVal);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
bRet = TRUE;
}
else if (4 == nOsType)
{
POSITION pos = lstString.GetHeadPosition();
int nStart = DFNParser_GetPrivateProfileInt("diskio", "startline", 0, IniFileName);
int nTransColumn = DFNParser_GetPrivateProfileInt("diskio", "trans", 0, IniFileName);
cout << "nStart:" << nStart <<endl;
cout << "nTransColumn:" << nTransColumn <<endl;
CString strTrans = _T("");
while (pos)
{
nStart --;
strTarget = lstString.GetNext(pos);
//cout <<"strTarget:" << strTarget << endl;
if (nStart <= 0)
{
GetColumnFromLine(strTarget, nTransColumn, strTrans);
//cout << "strTrans:" << strTrans << endl;
fTransVal += atof((LPCTSTR) strTrans);
}
}
cout << "fTransVal:" << fTransVal << endl;
strMsg.Format("ReadPerSec=%.2f$WritePerSec=%.2f$TransfersPerSec=%.2f$$",fReadVal, fWriteVal ,fTransVal);
strcpy(szOut, (LPCTSTR)strMsg);
cout << "szOut:" <<szOut <<endl;
bRet = FALSE;
}
else
{
bRet = FALSE;
}
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL ProcNumParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
BOOL bRet = FALSE;
cout << "-------------- ProcNumParser Start! -------------------"<<endl;
CString strFile = _T("ProcessParser");
CString strLog = _T("");
//WriteLog(strFile, "-------------- ProcessParser Start! -------------------");
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
cout << "-------------- GetIniFileName failed! ---------------"<<endl;
//WriteLog(strFile,"-------------- GetIniFileName failed! ---------------");
return bRet;
}
//cout << "----------------- GetIniFileName is success ---------------"<<endl;
//WriteLog(strFile,"----------------- GetIniFileName is success ---------------");
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
int nProcNum = 0;
int nValue = 0;
int nColumn = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (!bRet)
{
cout << "--------------- FormatSource is failed ----------------"<<endl;
WriteLog(strFile, "--------------- FormatSource is failed ----------------");
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("process", "ostype", 0, IniFileName);
strLog.Format("nOsType=%d",nOsType);
WriteLog(strFile,strLog);
int j = 0;
if (nOsType == 1)
{ // Linux
//strLog.Format("nOsType:1");
//WriteLog(strFile, strLog);
bRet = GetProColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
//WriteLog("--------------- GetColumnIndex Success ----------------");
int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
//puts(strOut);
//cout << "strOut:" << strOut <<endl;
j++;
if (j <= 1)
continue;
else
{
if( !strOut.IsEmpty())
{
nProcNum ++ ;
strLog.Format("i=%d strOut=%s",nProcNum, strOut);
WriteLog("ProcNum", strLog);
}
}
}
//cout <<"nProcNum:" << nProcNum <<endl;
sprintf(szOut,"ProcessNumber=%d$$",nProcNum);
cout << "szOut:" << szOut << endl;
}
}
else if (nOsType == 2)
{
bRet = GetProColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
//WriteLog("--------------- GetColumnIndex Success ----------------");
int nTempColumn = DFNParser_GetPrivateProfileInt("process", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
//puts(strOut);
//cout << "strOut:" << strOut <<endl;
j++;
if (j <= 1)
continue;
else
{
if( !strOut.IsEmpty())
{
nProcNum ++ ;
}
}
}
//cout <<"nProcNum:" << nProcNum <<endl;
sprintf(szOut,"ProcessNumber=%d$$",nProcNum);
cout << "szOut:" << szOut << endl;
}
}
else
{
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet ;
}
//////////////////////////////////////////////////////////////////////////
//yi.duan: 国家绘测局arcsde 用户 2010.12-08
//////////////////////////////////////////////////////////////////////////
extern "C" __declspec(dllexport)
BOOL arcsdeUserParser(const char * szSource, const int nMonitorType, char *szOut, const char *FileName)
{
BOOL bRet = FALSE;
int nValue = 0;
int nMatchCount = 0;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
{
CString strFileName;
WriteLog(strFileName,"GetIniFileName is failed!");
return bRet;
}
CStringList lstString;
CString strTarget = _T("");
CString strMsg = _T("");
//char matchLine[64] = {0};
//char matchLineNew[64]={0};
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName); // matchline 去掉不要的
POSITION pos = lstString.FindIndex(0);
while(pos)
{
CString strTemp = lstString.GetNext(pos);
cout << "strTemp = " << strTemp << endl;
}
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("arcsdeUser", "ostype", 0, IniFileName);
if (nOsType == 5) // Linux CentOS
{
int nStart = DFNParser_GetPrivateProfileInt("arcsdeUser", "startline", 0, IniFileName);
int nUserName = DFNParser_GetPrivateProfileInt("arcsdeUser", "userName", 0, IniFileName);
int nHost = DFNParser_GetPrivateProfileInt("arcsdeUser", "host", 0, IniFileName);
int nTime = DFNParser_GetPrivateProfileInt("arcsdeUser", "time", 0, IniFileName);
cout <<"nStart:"<<nStart <<endl;
cout <<"nUserName:"<< nUserName <<endl;
cout <<"nHost:"<< nHost <<endl;
cout <<"nTime:"<< nTime <<endl;
CString strOut = _T("");
CString strReturn = _T("");
CString strTemp = _T("");
POSITION pos = lstString.GetHeadPosition();
strTarget = lstString.GetNext(pos); //从第二条开始
int i = 0;
while(pos)
{
i++;
if (i<3)
{
strTarget = lstString.GetNext(pos);
continue;
}
strTarget = lstString.GetNext(pos);
cout <<"strTarget:"<< strTarget<<endl;
GetColumnFromLine(strTarget, nUserName, strOut);
cout <<"nUserName strOut = "<< strOut<<endl;
if (strOut=="")
{
i--;
//strReturn = strReturn.Left(strReturn.GetLength()-strOut1.GetLength());
break;
}
strTemp = "UserName=";
strTemp += strOut;
strTemp += ",";
strReturn += strTemp;
GetColumnFromLine(strTarget, nHost, strOut);
cout <<"host strOut = "<< strOut<<endl;
if (strOut=="")
{
i--;
//strReturn = strReturn.Left(strReturn.GetLength()-strOut2.GetLength());
break;
}
strTemp = "HostName=";
strTemp += strOut;
strTemp += ",";
strReturn += strTemp;
GetColumnFromLine(strTarget, nTime, strOut);
cout <<"time strOut = "<< strOut<<endl;
if (strOut=="")
{
i--;
//strReturn = strReturn.Left(strReturn.GetLength()-strOut3.GetLength());
break;
}
strTemp = "Time=";
strTemp += strOut;
strTemp += "-";
strReturn += strTemp;
GetColumnFromLine(strTarget, nTime+1, strOut);
cout <<"time strOut = "<< strOut<<endl;
if (strOut=="")
{
i--;
//strReturn = strReturn.Left(strReturn.GetLength()-strOut4.GetLength());
break;
}
strTemp = strOut;
strReturn += strTemp;
strReturn += ";";
}
sprintf(szOut,"ConnectionsNumber=%d$Result=%s$", (i-2),strReturn.GetBuffer(strReturn.GetLength()));
cout <<"szOut:"<< szOut <<endl;
}
else
{
bRet = FALSE;
}
lstString.RemoveAll();
}
return bRet;
}
extern "C" __declspec(dllexport)
BOOL AixErrptListParser(const char * szSource, const int nMonitorType, char *szOut, const char* szProcName, const char *FileName)
{
//AddToLogFile(nMonitorType, szSource);
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CStringList lstProcs;
CString strTarget = _T("");
CString strMsg = _T("");
int nValue = 0;
int nColumn = 0;
int j = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
{ // Aix
bRet = GetColumnIndexAix(lstString, nColumn,IniFileName);
if (bRet)
{
int nTempColumn = DFNParser_GetPrivateProfileInt("errpt", "namecolumnindex", 0, IniFileName);
if (nTempColumn) {
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, nMonitorType);
strOut.TrimRight(" ");
cout << "strOut:" << strOut <<endl;
j++;
if ((szProcName == NULL))
{
if (j <= 1)
continue;
POSITION pos1= lstProcs.GetHeadPosition();
if (pos1)
{
/* BOOL bFound = FALSE;
while (pos1)
{
CString strProc = lstProcs.GetNext(pos1);
if (!strProc.Compare((LPCTSTR)strOut)) {
bFound = TRUE;
break;
}
}
if (!bFound)*/
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
lstProcs.AddTail(strOut);
sprintf(szOut, "%s%s$$$", szOut, (LPCTSTR)strOut);
}
}
else
{
if (!strOut.Compare(szProcName))
{
nProcesses++;
}
}
}
if(szProcName != NULL)
{
strMsg.Format("Detail=%s$", szProcName);
strcpy(szOut, (LPCTSTR)strMsg);
}
}
}
lstString.RemoveAll();
printf("=====================\n");
printf("szOut = %s\n",szOut);
printf("=====================\n");
return bRet;
}
extern "C" __declspec(dllexport)
BOOL AixErrptDetailParser(const char * szSource, const int nMonitorType, char *szOut, const char* szProcName, const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CString strMsg = _T("");
CString strReturn = _T("");
int j = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
if (bRet)
{
char matchLine[16] = {0};
//DFNParser_GetPrivateProfileString("errptDetail", "end", "",
// matchLine, sizeof(matchLine), IniFileName);
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
while (pos)
{
strOut = lstString.GetNext(pos);
cout << "strOut:" << strOut <<endl;
if(strOut.Find("----------")>=0) // if(strOut.Find(matchLine)>=0)
{
j++;
cout << "Find:" << strOut <<endl;
if (j==2)
{
break;
}
}
else if (strOut=="DF")
{
cout << "Find DF:" << strOut <<endl;
continue;
}
else
{
strMsg += strOut;
strMsg += "\n";
}
}
}
if (strMsg.GetLength()>1024)//yi.duan 2011-10-19 字符组过长导致monitorSchudle解析不了
{
printf("data too long\n");
strMsg = strMsg.Left(512);
}
strReturn.Format("Detail=%s$", strMsg);
strcpy(szOut, (LPCTSTR)strReturn);
lstString.RemoveAll();
return bRet;
}
extern "C" __declspec(dllexport)
BOOL AixErrptFilterParser(const char * szSource, const int nMonitorType, char *szOut, const char* szProcName, const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CStringList lstExtraparam;
CString strMsg = _T("");
CString strReturn = _T("");
CString strMatchCondition = _T(""),
strMatchT = _T(""),
strMatchC = _T("");
int j = 0;
bRet = FormatSource(szSource, nMonitorType, lstString,IniFileName);
printf("szSource = %s\n",szSource);
if (strstr(szSource,"EccFree") || strstr(szSource,"errpt"))
{
printf("aimparser EccFree error\n");
return FALSE;
}
MakeStringListByChar(lstExtraparam,szProcName);
POSITION pos = lstExtraparam.FindIndex(0);
while(pos)
{
CString strTemp = lstExtraparam.GetNext(pos);
if(strTemp.Find("_MatchT=", 0) == 0)
{
strMatchT = strTemp.Right(strTemp.GetLength() - strlen("_MatchT="));
}
else if(strTemp.Find("_MatchC=", 0) == 0)
{
strMatchC = strTemp.Right(strTemp.GetLength() - strlen("_MatchC="));
}
else if(strTemp.Find("_MatchCondition=", 0) == 0)
{
strMatchCondition = strTemp.Right(strTemp.GetLength() - strlen("_MatchCondition="));
}
}
printf("strMatchT = %s\n", strMatchT.GetBuffer(strMatchT.GetLength()));
printf("strMatchC = %s\n", strMatchC.GetBuffer(strMatchC.GetLength()));
printf("strMatchCondition = %s\n", strMatchCondition.GetBuffer(strMatchCondition.GetLength()));
CString strColT = _T("");
CString strColC = _T("");
CString strColCond = _T("");
CString strTime = _T("");
UINT errptDetail_T = DFNParser_GetPrivateProfileInt("errptDetail", "T", 0, IniFileName);
UINT errptDetail_C = DFNParser_GetPrivateProfileInt("errptDetail", "C", 0, IniFileName);
UINT errptDetail_Condition = DFNParser_GetPrivateProfileInt("errptDetail", "ID", 0, IniFileName);
UINT errptDetail_filterTime = DFNParser_GetPrivateProfileInt("errptDetail", "filterTimeMinute", 10, IniFileName);
CTime logTime;
CTime currentTime = CTime::GetCurrentTime();
CTimeSpan grepTime;
int countLog = 0;
if (bRet)
{
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
while (pos)
{
strOut = lstString.GetNext(pos);
cout << endl << "strOut:" << strOut << endl;
if(strOut.Find("----------") >=0)
{
cout << "head or end:" << strOut <<endl;
continue;
}
else if (strOut=="DF")
{
cout << "Find DF:" << strOut <<endl;
continue;
}
else
{
GetColumnFromLine(strOut, errptDetail_T, strColT);
GetColumnFromLine(strOut, errptDetail_C, strColC);
GetColumnFromLine(strOut, errptDetail_Condition, strColCond);
GetColumnFromLine(strOut, 2, strTime);
logTime = strToTime(strTime);
grepTime = currentTime - logTime;
printf("grepTime Seconds = %d",grepTime.GetTotalSeconds());
printf("strTime = %d-%d-%d,%d:%d:%d\n",logTime.GetYear(),logTime.GetMonth(),
logTime.GetDay(),logTime.GetHour(),logTime.GetMinute(),logTime.GetSecond());
if (grepTime.GetTotalSeconds() <= errptDetail_filterTime * 60 ) //刷新时间
{
cout << "strColT :" << strColT <<endl;
cout << "strColC :" << strColC <<endl;
cout << "strColCond :" << strColCond <<endl;
if ( (strMatchT.IsEmpty() || strColT.Find(strMatchT)>=0) &&
(strMatchC.IsEmpty() || strColC.Find(strMatchC)>=0) &&
(strMatchCondition.IsEmpty() || strColCond.Find(strMatchCondition)>=0) )
{
cout << " Find :" << strOut <<endl;
strMsg += strOut;
strMsg += "\n";
countLog++;
}
else
{
cout << "not Find :" << strOut <<endl;
}
}
}
}//end while
}//end if
if (countLog==0)
{
strReturn.Format("countLog=0$Detail=none$");
}
else
{
if (strMsg.GetLength()>1024)//yi.duan 2011-10-19 字符组过长导致monitorSchudle解析不了
{
printf("data too long\n");
strMsg = strMsg.Left(512);
}
strReturn.Format("countLog=%d$Detail=%s$", countLog, strMsg);
}
strcpy(szOut, (LPCTSTR)strReturn);
lstString.RemoveAll();
return bRet;
}
extern "C" __declspec(dllexport)
BOOL ServiceParserFilter(const char *matchStr, const char * szSource, char *szOut, const char* szProcName, const char *FileName)
{
BOOL bRet = FALSE;
char IniFileName[1024]={0};
bRet = GetIniFileName(FileName,IniFileName);
if (!bRet)
return bRet;
CStringList lstString;
CStringList lstProcs;
CString strTarget = _T("");
CString strMsg = _T("");
cout << "matchStr:" << matchStr <<endl;
int nValue = 0;
int nColumn = 0;
bRet = FormatSource(szSource, SERVICE_TYPE_MONITOR, lstString,IniFileName);
if (bRet)
{
int nOsType = DFNParser_GetPrivateProfileInt("service", "ostype", 0, IniFileName);
int j = 0;
/*if (nOsType == 1)
{*/ // Linux
printf("===========================\n");
printf("matchStr = %s\n",matchStr);
printf("===========================\n");
bRet = GetColumnIndex(lstString, nColumn,IniFileName);
if (bRet)
{
int nTempColumn = DFNParser_GetPrivateProfileInt("service", "namecolumnindex", 0, IniFileName);
if (nTempColumn)
{
if (nTempColumn != nColumn)
nColumn = nTempColumn;
}
POSITION pos = lstString.GetHeadPosition();
CString strOut = _T("");
int nProcesses = 0;
if(0 == strcmp(szProcName,""))
{
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, SERVICE_TYPE_MONITOR);
strOut.TrimRight(" ");
j++;
/*if (!stricmp((LPCTSTR)strOut, szProcName))
{*/
if (strstr(strOut,matchStr))
{
cout << "strOut:" << strOut <<endl;
nProcesses++;
}
//}
}
}else
{
while (pos)
{
strTarget = lstString.GetNext(pos);
GetColumnFromLine(strTarget, nColumn, strOut, SERVICE_TYPE_MONITOR);
strOut.TrimRight(" ");
j++;
if (stricmp((LPCTSTR)strOut, szProcName)==0)
{
cout << "allstrOut:" << strOut <<endl;
/*if (strstr(szProcName,matchStr))
{*/
nProcesses++;
//}
}
}
}
//if(szProcName != NULL)
//{
strMsg.Format("Processes=%d$", nProcesses);
strcpy(szOut, (LPCTSTR)strMsg);
//}
}
/*}
else
{
bRet = FALSE;
}*/
lstString.RemoveAll();
printf("=====================\n");
printf("szOut = %s\n",szOut);
printf("=====================\n");
}
return bRet;
}
| [
"[email protected]"
] | |
0057c33de105fd389dd48f124ffc2a3b07c3dd7c | f746b56ae58841d4a1952a0fb0af687562212d1a | /UVA/UVA_10058.cpp | aaed09c5bc0cf1f3e1c036881724642b2ee7858f | [] | no_license | root-life28/problem_solving | f763c87ae93ca33e864caf9cd71e581906b8e80e | 7db64f4640791dd07139565b8b5e32ab8ae9a3a8 | refs/heads/master | 2021-10-27T15:19:54.783640 | 2019-04-17T21:53:09 | 2019-04-17T21:53:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,104 | cpp | /*
UVA 10058
Author: Youssef ElGhareeb
Idea: Parse the input string and transform it to a vector string
Then process it from left to right using a state machine according to the rules
*/
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <cstring>
using namespace std;
#define loop(i,n) for(int i=0; i<n; i++)
#define ll long long
#define pii pair<int, int>
#define pb push_back
string s;
vector<string> words;
const string verbs[] = {"hate", "love", "know", "like", "hates", "loves", "knows", "likes"};
const string nouns[] = {"tom", "jerry", "goofy", "mickey", "jimmy", "dog", "cat", "mouse"};
void parse() {
words.clear();
string cur;
for(int i=0; i<s.length(); i++) {
if (s[i] == ' ') {
if (cur != "") {
words.push_back(cur);
cur = "";
}
}
else {
cur += s[i];
}
}
if (cur != "") words.push_back(cur);
}
bool is_article(int ind) {
return words[ind] == "a" || words[ind] == "the";
}
bool is_noun(int& ind) {
loop(j, sizeof(nouns) / sizeof(nouns[0])) {
if (words[ind] == nouns[j]) {
++ind;
return true;
}
}
return false;
}
bool get_verb(int& ind) {
if (ind >= words.size()) return false;
loop(j, sizeof(verbs) / sizeof(verbs[0])) {
if (verbs[j] == words[ind]) {
++ind;
return true;
}
}
return false;
}
bool get_active_list(int& ind) {
while (true) {
if (ind >= words.size()) return false;
if (is_article(ind)) ++ind;
if (ind >= words.size()) return false;
if (!is_noun(ind)) return false;
if (ind < words.size() && words[ind] == "and") {
++ind;
}
else break;
}
return true;
}
bool check() {
int ind = 0;
while (true) {
if(!get_active_list(ind)) return false;
if(!get_verb(ind)) return false;
if(!get_active_list(ind)) return false;
if (ind == words.size()) break;
if (words[ind] == ",") {
++ind;
}
else return false;
}
return true;
}
int main() {
ios_base::sync_with_stdio(false);
while (getline(cin, s)) {
parse();
if (check()) cout<<"YES I WILL\n";
else cout<<"NO I WON'T\n";
}
return 0;
} | [
"[email protected]"
] | |
12a57c636cf150963c9e39068c0af6026214683b | 3ffddf73d11b580873f58c5d9f51681f7a411e95 | /LegendDataEditor/LegendDataEditor/STL/txVector.h | 1ff31b202cc19ab7e065e284074e65cfde1d1aa7 | [] | no_license | jinwenhua/GameEditor | 5b63a0cab930da81bc0711c9949aee212e90c99c | 6847fcebd5005bfe44df3d0d1a660c2a80e4c1e0 | refs/heads/master | 2022-10-11T04:46:53.499957 | 2020-06-04T14:44:07 | 2020-06-04T14:44:07 | 270,599,534 | 1 | 0 | null | 2020-06-08T09:00:41 | 2020-06-08T09:00:41 | null | UTF-8 | C++ | false | false | 1,755 | h | #ifndef _TX_VECTOR_H_
#define _TX_VECTOR_H_
#include "txSTLBase.h"
template<typename T>
class txVector : public txSTLBase
{
public:
typedef typename std::vector<T>::iterator iterator;
public:
txVector()
{}
virtual ~txVector(){ clear(); }
void push_back(const T& elem)
{
checkLock();
mVector.push_back(elem);
}
iterator erase(const iterator& iter, bool check = true)
{
if (check)
{
checkLock();
}
return mVector.erase(iter);
}
iterator erase(int index, bool check = true)
{
if (index < 0 || index >= size())
{
return end();
}
return erase(begin() + index);
}
int find(const T& value)
{
int count = (int)mVector.size();
for(int i = 0; i < count; ++i)
{
if (mVector[i] == value)
{
return i;
}
}
return -1;
}
void clear()
{
checkLock();
mVector.clear();
}
void insert(const iterator& iter, const T& elem, bool check = true)
{
if (check)
{
checkLock();
}
mVector.insert(iter, elem);
}
int size() const
{
return mVector.size();
}
iterator begin()
{
return mVector.begin();
}
iterator end()
{
return mVector.end();
}
const T& operator[](int i) const
{
if (i < 0 || i >= size())
{
//LOG_ERROR("%s", "vector index out of range!");
}
return mVector[i];
}
T& operator[](int i)
{
if (i < 0 || i >= size())
{
//LOG_ERROR("%s", "vector index out of range!");
}
return mVector[i];
}
void resize(int s)
{
checkLock();
mVector.resize(s);
}
bool contains(const T& value)
{
return std::find(begin(), end(), value) != end();
}
void merge(const txVector<T>& other)
{
int count = other.mVector.size();
for(int i = 0; i < count; ++i)
{
push_back(other[i]);
}
}
protected:
protected:
std::vector<T> mVector;
};
#endif | [
"[email protected]"
] | |
68be324d06eb74201a45379bdc61743736ce185e | 674bcb4bf88b5359ea9710c864481af61f5867d3 | /src/external/bgfx/3rdparty/spirv-tools/source/opt/value_number_table.cpp | 82549a6dc9e7832594dce63c764ca20dc6ced90e | [
"BSD-2-Clause",
"MIT",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | HippoPlayer/HippoPlayer | a1da46743507c866c5e614f36122348794229b05 | a3145f9797a5ef7dd1b79ee8ccd3476c8c5310a6 | refs/heads/master | 2023-04-19T13:05:36.210552 | 2021-05-08T06:48:18 | 2021-05-08T06:48:18 | 2,195,999 | 44 | 5 | Apache-2.0 | 2022-10-19T15:45:21 | 2011-08-12T08:12:25 | C | UTF-8 | C++ | false | false | 7,444 | cpp | // Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "source/opt/value_number_table.h"
#include <algorithm>
#include "source/opt/cfg.h"
#include "source/opt/ir_context.h"
namespace spvtools {
namespace opt {
uint32_t ValueNumberTable::GetValueNumber(Instruction* inst) const {
assert(inst->result_id() != 0 &&
"inst must have a result id to get a value number.");
// Check if this instruction already has a value.
auto result_id_to_val = id_to_value_.find(inst->result_id());
if (result_id_to_val != id_to_value_.end()) {
return result_id_to_val->second;
}
return 0;
}
uint32_t ValueNumberTable::GetValueNumber(uint32_t id) const {
return GetValueNumber(context()->get_def_use_mgr()->GetDef(id));
}
uint32_t ValueNumberTable::AssignValueNumber(Instruction* inst) {
// If it already has a value return that.
uint32_t value = GetValueNumber(inst);
if (value != 0) {
return value;
}
// If the instruction has other side effects, then it must
// have its own value number.
// OpSampledImage and OpImage must remain in the same basic block in which
// they are used, because of this we will assign each one it own value number.
if (!context()->IsCombinatorInstruction(inst)) {
value = TakeNextValueNumber();
id_to_value_[inst->result_id()] = value;
return value;
}
switch (inst->opcode()) {
case SpvOpSampledImage:
case SpvOpImage:
case SpvOpVariable:
value = TakeNextValueNumber();
id_to_value_[inst->result_id()] = value;
return value;
default:
break;
}
// If it is a load from memory that can be modified, we have to assume the
// memory has been modified, so we give it a new value number.
//
// Note that this test will also handle volatile loads because they are not
// read only. However, if this is ever relaxed because we analyze stores, we
// will have to add a new case for volatile loads.
if (inst->IsLoad() && !inst->IsReadOnlyLoad()) {
value = TakeNextValueNumber();
id_to_value_[inst->result_id()] = value;
return value;
}
analysis::DecorationManager* dec_mgr = context()->get_decoration_mgr();
// When we copy an object, the value numbers should be the same.
if (inst->opcode() == SpvOpCopyObject &&
dec_mgr->HaveTheSameDecorations(inst->result_id(),
inst->GetSingleWordInOperand(0))) {
value = GetValueNumber(inst->GetSingleWordInOperand(0));
if (value != 0) {
id_to_value_[inst->result_id()] = value;
return value;
}
}
// Phi nodes are a type of copy. If all of the inputs have the same value
// number, then we can assign the result of the phi the same value number.
if (inst->opcode() == SpvOpPhi && inst->NumInOperands() > 0 &&
dec_mgr->HaveTheSameDecorations(inst->result_id(),
inst->GetSingleWordInOperand(0))) {
value = GetValueNumber(inst->GetSingleWordInOperand(0));
if (value != 0) {
for (uint32_t op = 2; op < inst->NumInOperands(); op += 2) {
if (value != GetValueNumber(inst->GetSingleWordInOperand(op))) {
value = 0;
break;
}
}
if (value != 0) {
id_to_value_[inst->result_id()] = value;
return value;
}
}
}
// Replace all of the operands by their value number. The sign bit will be
// set to distinguish between an id and a value number.
Instruction value_ins(context(), inst->opcode(), inst->type_id(),
inst->result_id(), {});
for (uint32_t o = 0; o < inst->NumInOperands(); ++o) {
const Operand& op = inst->GetInOperand(o);
if (spvIsIdType(op.type)) {
uint32_t id_value = op.words[0];
auto use_id_to_val = id_to_value_.find(id_value);
if (use_id_to_val != id_to_value_.end()) {
id_value = (1 << 31) | use_id_to_val->second;
}
value_ins.AddOperand(Operand(op.type, {id_value}));
} else {
value_ins.AddOperand(Operand(op.type, op.words));
}
}
// TODO: Implement a normal form for opcodes that commute like integer
// addition. This will let us know that a+b is the same value as b+a.
// Otherwise, we check if this value has been computed before.
auto value_iterator = instruction_to_value_.find(value_ins);
if (value_iterator != instruction_to_value_.end()) {
value = id_to_value_[value_iterator->first.result_id()];
id_to_value_[inst->result_id()] = value;
return value;
}
// If not, assign it a new value number.
value = TakeNextValueNumber();
id_to_value_[inst->result_id()] = value;
instruction_to_value_[value_ins] = value;
return value;
}
void ValueNumberTable::BuildDominatorTreeValueNumberTable() {
// First value number the headers.
for (auto& inst : context()->annotations()) {
if (inst.result_id() != 0) {
AssignValueNumber(&inst);
}
}
for (auto& inst : context()->capabilities()) {
if (inst.result_id() != 0) {
AssignValueNumber(&inst);
}
}
for (auto& inst : context()->types_values()) {
if (inst.result_id() != 0) {
AssignValueNumber(&inst);
}
}
for (auto& inst : context()->module()->ext_inst_imports()) {
if (inst.result_id() != 0) {
AssignValueNumber(&inst);
}
}
for (Function& func : *context()->module()) {
// For best results we want to traverse the code in reverse post order.
// This happens naturally because of the forward referencing rules.
for (BasicBlock& block : func) {
for (Instruction& inst : block) {
if (inst.result_id() != 0) {
AssignValueNumber(&inst);
}
}
}
}
}
bool ComputeSameValue::operator()(const Instruction& lhs,
const Instruction& rhs) const {
if (lhs.result_id() == 0 || rhs.result_id() == 0) {
return false;
}
if (lhs.opcode() != rhs.opcode()) {
return false;
}
if (lhs.type_id() != rhs.type_id()) {
return false;
}
if (lhs.NumInOperands() != rhs.NumInOperands()) {
return false;
}
for (uint32_t i = 0; i < lhs.NumInOperands(); ++i) {
if (lhs.GetInOperand(i) != rhs.GetInOperand(i)) {
return false;
}
}
return lhs.context()->get_decoration_mgr()->HaveTheSameDecorations(
lhs.result_id(), rhs.result_id());
}
std::size_t ValueTableHash::operator()(const Instruction& inst) const {
// We hash the opcode and in-operands, not the result, because we want
// instructions that are the same except for the result to hash to the
// same value.
std::u32string h;
h.push_back(inst.opcode());
h.push_back(inst.type_id());
for (uint32_t i = 0; i < inst.NumInOperands(); ++i) {
const auto& opnd = inst.GetInOperand(i);
for (uint32_t word : opnd.words) {
h.push_back(word);
}
}
return std::hash<std::u32string>()(h);
}
} // namespace opt
} // namespace spvtools
| [
"Collin"
] | Collin |
2859167d3b5973f5cf6d4d71f3b78ec281cd40b0 | a6562c37cbf85f66f448ea05c81d984440e3025a | /Penguin Glide/PenguinGlide/Source/PenguinGlide/Interactable.h | 96c997faf6004e2a58012b69ca041dfe27eeda92 | [] | no_license | Energyslam/PenguinGlideUnreal | 5120805d2bc65dd2c80ffa9b06f6157f2d3d03e8 | 6fa141f3b3ce60963c475d12beb81f8e33cd55af | refs/heads/master | 2021-07-04T22:12:51.238836 | 2021-02-16T18:38:17 | 2021-02-16T18:38:17 | 218,162,565 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 1,855 | h | #pragma once
#include "CoreMinimal.h"
#include <string>
#include "Particles/ParticleSystem.h"
#include "Particles/ParticleSystemComponent.h"
#include "ParticleDefinitions.h"
#include "ConstructorHelpers.h"
#include "GameFramework/Actor.h"
#include "Interactable.generated.h"
using namespace std;
UCLASS()
/*!
* \brief This class is used for the interactables in the game, namely the power-ups.
* \details The interactables in the game right now is the power-up. The power-up has two seperate particle system, one to indicate
* to the player that there is something special about it, and one that plays once the player has picked it up to
* give some juice to the game. This makes it feel more impactful than simply picking it up. This class is derived from
* a blueprint. This blueprint holds the static mesh that the interactable has, which is a standard sphere with a material.
* It creates and attaches the particle system during runtime.
*
* \author Max Groen
* \version 1
* \date 15/05/2019
* \copyright Energyslam™
*/
class PENGUINGLIDE_API AInteractable : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AInteractable();
class UParticleSystemComponent* MyParticleSystem; //!< This particle system is always playing until it is picked up
class UParticleSystemComponent* MyConstantParticleSystem; //!< this particle system will only play once it has been picked up
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components")
UStaticMeshComponent* StaticMesh;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Components")
UParticleSystem* particles;
FString warning;
FColor warningColor;
virtual void ResolveCollision();
}; | [
"max.groen4"
] | max.groen4 |
4c90f5b4a5d76130237372ca46991ec0ed3c5be6 | f0749232d54f17e3c321b0b90daaeb23b9faec82 | /Online Judge Code/[Other] Online-Judge-Solutions-master_from github/SPOJ/Classical/63 - Square Brackets.cpp | 872b7e647d10ac011cb4bf744dfaa727be66444d | [] | no_license | tmuttaqueen/MyCodes | c9024a5b901e68e7c7466885eddbfcd31a5c9780 | 80ec40b26649029ad546ce8ce5bfec0b314b1f61 | refs/heads/master | 2020-04-18T22:20:51.845309 | 2019-05-16T18:11:02 | 2019-05-16T18:11:02 | 167,791,029 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | cpp | #include <cstdio>
#include <cstring>
using namespace std;
int memo[38][38];
bool open[38];
int solve(int s, int e){
if(s > e) return 1;
if(open[e]) return 0;
if(e == s+1) return 1;
int &ret = memo[s][e];
if(ret == -1){
ret = 0;
for(int i = s+1;i <= e;i += 2)
if(!open[i]) ret += solve(s+1,i-1) * solve(i+1,e);
}
return ret;
}
int main(){
int T,N,K;
scanf("%d",&T);
while(T--){
scanf("%d %d",&N,&K);
memset(open,false,sizeof(open));
for(int i = 0,x;i < K;++i){
scanf("%d",&x);
open[--x] = true;
}
memset(memo,-1,sizeof(memo));
printf("%d\n",solve(0,2*N-1));
}
return 0;
}
| [
"[email protected]"
] | |
ab56a5de7d372d666d7e18c2dc0230c96f9386d9 | 25fd4ead4f0631481489660b621d3b3f125b43d0 | /Lisp interpreter/lispp/symbol_object.cpp | 3a0ebc86b54e7f9812bf6d69a84d673d9f1189ea | [] | no_license | Sul123/Demo | c8728b2928c805be863d20c4e4ae9cf2a680a25f | 206e16bd8e55e085aedeb322633c053ab56d86d9 | refs/heads/master | 2020-03-19T05:26:18.846722 | 2018-07-29T21:14:43 | 2018-07-29T21:14:43 | 135,930,710 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | cpp | #include "symbol_object.h"
#include "scope.h"
#include "errors.h"
#include <string>
SymbolObject::SymbolObject(const SymbolObject& other) : symbol_(other.symbol_) {}
SymbolObject::SymbolObject(const std::string& symbol) : symbol_(symbol) {}
ObjectPtr SymbolObject::Duplicate() const {
return std::make_shared<SymbolObject>(*this);
}
ObjectPtr SymbolObject::Evaluate(ScopePtr scope) {
ObjectPtr object = scope->Get(symbol_);
if (!object) {
throw NameError("Name error, " + symbol_ + " not defined");
}
return object;
}
std::string SymbolObject::Print() const {
return symbol_;
}
bool SymbolObject::IsSymbol() const {
return true;
}
const std::string& SymbolObject::GetSymbol() const {
return symbol_;
}
| [
"[email protected]"
] | |
31b0a3983f84564bb18f5831b027482db7186e8b | 845abf347fa5f5715dd3379237e42e88fbca34a9 | /hackerrank/problems/queen_attack_2.cpp | 0f76b8415f01c89c1deee4ca6ecb5ecb897c8a87 | [] | no_license | tariqul87/coding-practice | cf03375a08e8d78d8464960ccb26ee5937a12782 | 209814f8ddef2e9c202b7750f09e964b3fe8d117 | refs/heads/master | 2021-06-22T04:04:45.269606 | 2020-12-16T13:15:32 | 2020-12-16T13:15:32 | 158,011,562 | 0 | 0 | null | 2020-12-16T13:15:33 | 2018-11-17T18:11:38 | C++ | UTF-8 | C++ | false | false | 3,248 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the queensAttack function below.
int queensAttack(int n, int k, int r_q, int c_q, vector<vector<int>> obstacles)
{
int up = n - r_q;
int down = r_q - 1;
int left = c_q - 1;
int right = n - c_q;
int lud = min(left, up);
int rud = min(right, up);
int ldd = min(left, down);
int rdd = min(right, down);
for (int i = 0; i < obstacles.size(); i++)
{
int r = obstacles[i][0], c = obstacles[i][1];
int r_d = r - r_q;
if (r_d > 0)
{
if (c_q - c == abs(r_d)) // lud
{
lud = min(lud, c_q - c - 1);
}
else if (c_q == c)
{ // up
up = min(up, r - r_q - 1);
}
else if (c - c_q == abs(r_d))
{ //rud
rud = min(c - c_q - 1, rud);
}
}
else if (r_d == 0)
{
if (c_q > c)
{
left = min(left, c_q - c - 1);
}
else if (c > c_q)
{
right = min(right, c - c_q - 1);
}
}
else if (r_d < 0)
{
if (c_q - c == abs(r_d)) // ldd
{
ldd = min(ldd, c_q - c - 1);
}
else if (c_q == c) // down
{
down = min(down, r_q - r - 1);
}
else if (c - c_q == abs(r_d)) // rdd
{
rdd = min(c - c_q - 1, rdd);
}
}
}
int result = lud + up + rud + left + right + ldd + down + rdd;
return result;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string nk_temp;
getline(cin, nk_temp);
vector<string> nk = split_string(nk_temp);
int n = stoi(nk[0]);
int k = stoi(nk[1]);
string r_qC_q_temp;
getline(cin, r_qC_q_temp);
vector<string> r_qC_q = split_string(r_qC_q_temp);
int r_q = stoi(r_qC_q[0]);
int c_q = stoi(r_qC_q[1]);
vector<vector<int>> obstacles(k);
for (int i = 0; i < k; i++)
{
obstacles[i].resize(2);
for (int j = 0; j < 2; j++)
{
cin >> obstacles[i][j];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int result = queensAttack(n, k, r_q, c_q, obstacles);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string)
{
string::iterator new_end = unique(input_string.begin(), input_string.end(), [](const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ')
{
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos)
{
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
| [
"[email protected]"
] | |
163d1f5f6d99bc6b90945b85dc6351aa5e21508b | ecf0bc675b4225da23f1ea36c0eda737912ef8a9 | /Reco_Csrc/Engine/GameState.cpp | fe8780b8e85f1ed04ecfadcaf2ded7066ae9c077 | [] | no_license | Artarex/MysteryV2 | 6015af1b501ce5b970fdc9f5b28c80a065fbcfed | 2fa5608a4e48be36f56339db685ae5530107a520 | refs/heads/master | 2022-01-04T17:00:05.899039 | 2019-03-11T19:41:19 | 2019-03-11T19:41:19 | 175,065,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | version https://git-lfs.github.com/spec/v1
oid sha256:28b5213cdbda737acc6507b14c04be2e38c80e19a667989c21003f9c06d2b521
size 39008
| [
"[email protected]"
] | |
2771328e3ee730ea53d83bb344f6419f238e1f8b | fe75ab418adfd723f48b8eafc80515c9fd913395 | /LeetCode/!0022. Generate Parentheses.cpp | c2a7ab467154e445658292baa552da8f58632ad8 | [] | no_license | AshkenSC/Programming-Practice | d029e9d901f51ef750ed4089f10c1f16783d2695 | 98e20c63ce1590deda6761ff2f9c8c37f3fb3c4a | refs/heads/master | 2021-07-20T06:41:12.673248 | 2021-06-25T15:44:06 | 2021-06-25T15:44:06 | 127,313,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp | /*
0022. Generate Parentheses
给定n对括号,写一个函数生成所有有效的括号组合。例如,给定n=3,解集为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路:回溯法(深度优先遍历结果树进行枚举 + 按题目要求剪枝)
满足条件:左右括号数量相等,都为n。当左括号小于右括号数量,或者左/右括号数量大于n,则停止深度探索,return
*/
class Solution {
public:
void dfs(vector<string>& result, string current, int n, int left_bracket, int right_bracket) {
// 如果是这几种情况,则不再向下深度遍历
if (left_bracket < right_bracket || left_bracket > n || right_bracket > n)
return;
// 满足条件,加入解集
if (left_bracket == right_bracket && left_bracket == n) {
result.push_back(current);
return;
}
// dfs遍历
dfs(result, current + '(', n, left_bracket + 1, right_bracket);
dfs(result, current + ')', n, left_bracket, right_bracket + 1);
}
vector<string> generateParenthesis(int n) {
vector<string> result;
dfs(result, "", n, 0, 0);
return result;
}
}; | [
"[email protected]"
] | |
3aed0d3e74d95ff3639e899b6557be8697eed380 | b20dc5ba0c11a315d35385d042306e48cf4dbc62 | /CS 216 Intro to Software Engineering/practicum/week8/debugging/rectangle.h | 43431d2f6b4c1b23e00644d0f387850f8f4287ee | [] | no_license | shliu/UKY | f7704965d15653d89caa371b22f3f5beefa284c4 | 0d8c9e84fedd9e61cac243e56009b465c25a2ea5 | refs/heads/master | 2021-01-25T12:14:35.000873 | 2014-09-26T04:41:35 | 2014-09-26T04:41:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | h | #ifndef RECTANGLE_H
#define RECTANGLE_H
#include "polygon.h"
#include "point.h"
class Rectangle : public Polygon {
public:
Rectangle(const Point& p0, const Point& p1);
virtual int numberOfPoints() const { return 4; }
virtual Point point(const int& index) const;
virtual double circumference() const;
private:
// lower left corner point
Point m_p0;
// upper right corner point
Point m_p1;
}; // class Rectangle
#endif | [
"[email protected]"
] | |
4669867c015c584f480e9f726469d802b8d652a8 | 934a1bb50d9480a8f78c2b567ac229637fb36105 | /src/engine/BehaviourList.cpp | 1c901c3f641e34911922486f52b24206a0f90807 | [
"MIT"
] | permissive | alextrevisan/3dfx-glide-game-engine | a73d1150174dedb94af0036f7c0197aa9a6cfdcc | 9a47c65d3705fb7b43e59cf90432b053f467e844 | refs/heads/master | 2022-12-04T06:08:06.153509 | 2020-08-28T23:17:32 | 2020-08-28T23:17:32 | 268,642,355 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | cpp | #include "BehaviourList.h"
BehaviourList& BehaviourList::GetInstance()
{
if(!Instance)
Instance = new BehaviourList();
return *Instance;
}
const std::vector<MonoBehaviour*>& BehaviourList::Items()
{
return MonoBehaviourList;
}
void BehaviourList::Add(MonoBehaviour* item)
{
MonoBehaviourList.push_back(item);
}
void BehaviourList::Erase(MonoBehaviour* item)
{
const auto it = std::find(MonoBehaviourList.begin(), MonoBehaviourList.end(),item);
MonoBehaviourListToRemove.push_back(it);
}
void BehaviourList::Apply()
{
for(auto it: MonoBehaviourListToRemove)
{
MonoBehaviourList.erase(it);
}
MonoBehaviourListToRemove.clear();
}
BehaviourList::BehaviourList()
{
}
BehaviourList::~BehaviourList()
{
for(auto it: MonoBehaviourList)
{
delete it;
}
MonoBehaviourList.clear();
}
BehaviourList* BehaviourList::Instance = nullptr;
| [
"[email protected]"
] | |
caa99c60c673ffc26e985c9b96defcbaf48b38fb | c5eaeff3e501e069aafae1c6b3a8e16785f3eeb1 | /ZTI.CPP | 2260c5315b895d1ebf4bb5062fd5b01d33448488 | [
"MIT"
] | permissive | SammyB428/NMEA0183 | 1c25ebbab2d078543c0f1aeeb7809800c742d190 | 8bf11491443762c9696d2eb3da1fa1b755db2f04 | refs/heads/master | 2023-03-17T18:51:08.346579 | 2023-03-03T10:43:45 | 2023-03-03T10:43:45 | 46,305,122 | 37 | 21 | MIT | 2022-02-03T14:25:43 | 2015-11-16T21:50:29 | C++ | UTF-8 | C++ | false | false | 3,740 | cpp | /*
Author: Samuel R. Blackburn
Internet: [email protected]
"You can get credit for something or get it done, but not both."
Dr. Richard Garwin
The MIT License (MIT)
Copyright (c) 1996-2019 Sam Blackburn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// SPDX-License-Identifier: MIT
/*
** This Sentence Not Recommended For New Designs
** ZTG is recommended.
*/
#include "nmea0183.h"
#pragma hdrstop
void ZTI::Empty( void ) noexcept
{
UTCTimeString.clear();
UTCTime = 0;
TimeToGoString.clear();
TimeToGo = 0;
To.clear();
}
bool ZTI::Parse( SENTENCE const& sentence ) noexcept
{
/*
** ZTI - Estimated time to point of interest
**
** 1 2 3 4
** | | | |
** $--ZTI,hhmmss.ss,hhmmss.ss,c--c*hh<CR><LF>
**
** 1) Universal Time Coordinated (UTC)
** 2) Arrival Time
** 3) Waypoint ID (To)
** 4) Checksum
*/
/*
** First we check the checksum...
*/
if ( sentence.IsChecksumBad( 4 ) == NMEA0183_BOOLEAN::True )
{
SetErrorMessage(STRING_VIEW("Invalid Checksum"));
return( false );
}
auto temp_time{ time(nullptr) };
auto tm_p{ gmtime(&temp_time) };
auto const year{ tm_p->tm_year + 1900 };
auto const month{ tm_p->tm_mon };
auto const day{ tm_p->tm_mday };
UTCTimeString = sentence.Field( 1 );
int hours{ 0 };
std::ignore = std::from_chars(UTCTimeString.data(), UTCTimeString.data() + 2, hours, 10);
int minutes{ 0 };
std::ignore = std::from_chars(UTCTimeString.data() + 2, UTCTimeString.data() + 4, minutes, 10);
int seconds{ 0 };
std::ignore = std::from_chars(UTCTimeString.data() + 4, UTCTimeString.data() + 6, seconds, 10);
UTCTime = ctime( year, month, day, hours, minutes, seconds );
TimeToGoString = sentence.Field( 2 );
std::ignore = std::from_chars(TimeToGoString.data(), TimeToGoString.data() + 2, hours, 10);
std::ignore = std::from_chars(TimeToGoString.data() + 2, TimeToGoString.data() + 4, minutes, 10);
std::ignore = std::from_chars(TimeToGoString.data() + 4, TimeToGoString.data() + 6, seconds, 10);
TimeToGo = ctime( year, month, day, hours, minutes, seconds );
To = sentence.Field( 3 );
return( true );
}
bool ZTI::Write( SENTENCE& sentence ) const noexcept
{
/*
** Let the parent do its thing
*/
RESPONSE::Write( sentence );
sentence += UTCTimeString;
sentence += TimeToGoString;
sentence += To;
sentence.Finish();
return( true );
}
ZTI const& ZTI::operator = ( ZTI const& source ) noexcept
{
UTCTimeString = source.UTCTimeString;
UTCTime = source.UTCTime;
TimeToGoString = source.TimeToGoString;
TimeToGo = source.TimeToGo;
To = source.To;
return( *this );
}
| [
"[email protected]"
] | |
ff1ea0eed3024e98c9e6315ae857af0b639f9105 | a7b4e22a6cdb67f08758099c0a881a7288f63ff4 | /Framework/Source/FrameworkPCH.h | eb21c0ea26808938004fa20cd637bc8d397a6bbe | [] | no_license | makh0024/20F_GAM1571 | 9f7679a1b3009f5d2eeea3832bd47a5b9e5d7c2b | c50ba8c80ca0c0fbb936b59f2f48311675d7afdb | refs/heads/master | 2023-02-01T05:22:39.867457 | 2020-12-15T19:37:45 | 2020-12-15T19:37:45 | 294,181,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | h | #ifndef __FrameworkPCH_H__
#define __FrameworkPCH_H__
// This file includes many static headers and must be included by all files
// inside this Framework project.
// Any changes to any of these headers will cause a full rebuild of the
// Framework project, which isn't desirable.
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <windowsx.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <math.h>
#include <map>
#include <vector>
#include <queue>
#include <string>
#include <GL/GL.h>
#include "GL/glext.h"
#include "GL/wglext.h"
#include "GL/GLExtensions.h"
#include "GL/WGLExtensions.h"
#include "../Libraries/imgui/imgui.h"
#include "../Libraries/rapidjson/document.h"
#include "Memory/MyMemory.h"
#endif //__FrameworkPCH_H__
| [
"[email protected]"
] | |
a84520309a89f116b2db5241b14325ee08e87727 | a2d23bffdcbe195b9faba90e0bfea7f2d383116f | /정수삼각형.cpp | fea4dd4cfc6c98fb60edc59ae9f2c3528f7010f8 | [] | no_license | epiglottiss/algorithm | 6b11503465f4e60a946602c3fab89714752d9631 | 1de627a3844afc437090ff0d0a5c3b0518818d63 | refs/heads/master | 2023-02-03T12:49:11.185769 | 2020-12-20T13:33:01 | 2020-12-20T13:33:01 | 264,973,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
int n;
scanf_s("%d", &n);
vector<int> inputs;
vector<int> memo(n,0);
for (size_t i = 0; i < n; i++)
{
//vector<int> *inputs = new vector<int>();
for (size_t j = 0; j < i+1; j++)
{
int node;
scanf_s("%d", &node);
inputs.push_back(node);
}
for (size_t k = 0; k < i+1; k++)
{
try
{
if (k == 0) { throw k; }
if (k == i) { throw k; }
inputs[k] += (max(memo[k - 1], memo[k]));
}
catch (size_t k)
{
inputs[k] += (k == 0 ? memo[k] : memo[k - 1]);
}
}
copy(inputs.begin(), inputs.end(), memo.begin());
//memo.assign(inputs.begin(),inputs.end());
inputs.clear();
//for (size_t i = 0; i < memo.size(); i++)
//{
// cout << memo[i] << ' ';
//
//}
}
printf("%d", *max_element(memo.begin(), memo.end()));
return 0;
}
| [
"[email protected]"
] | |
387a57180e15f049b4e2e83afa0c09ce9b366ae5 | df4ba2859cdff274deb3e54eda7cbcf798657517 | /SourceALE/SelfAddrDlg.h | 7e1324199737c1c54304c6cad921b42ee0b331a6 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | DigitalHERMES/ALELite | 478b029b898c5144d3fef1767a294ff72cb29fa4 | 43b6e2cdcfd8bc5aa983dc4817c4e3e90e02be1a | refs/heads/master | 2022-11-06T15:43:29.458137 | 2020-06-20T21:28:45 | 2020-06-20T21:28:45 | 270,898,251 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,622 | h | // SelfAddrDlg.h : header file
// 11 Dec 1998
#if !defined(AFX_SELFADDRDLG_H__E7D694C1_807E_11D2_8F3A_0060089F9D1C__INCLUDED_)
#define AFX_SELFADDRDLG_H__E7D694C1_807E_11D2_8F3A_0060089F9D1C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CSelfAddrDlg dialog
class CSelfAddrDlg : public CDialog
{
private:
CEdit& ctlSelfAddr() {return *(CEdit *) GetDlgItem(IDC_EDIT1); }
CEdit& ctlNetAddr() {return *(CEdit *) GetDlgItem(IDC_EDIT2); }
CEdit& ctlSlotWait() {return *(CEdit *) GetDlgItem(IDC_EDIT3); }
CListBox& ctlChannelList() {return *(CListBox *) GetDlgItem(IDC_LIST1); }
// Construction
public:
CSelfAddrDlg(CWnd* pParent = NULL); // standard constructor
struct CALEDoc::DATA *pData;
BOOL bNew; // TRUE if this is a new record, FALSE to edit existing record
int pos; // The position of the record to edit or where to add a new record
// Dialog Data
//{{AFX_DATA(CSelfAddrDlg)
enum { IDD = IDD_SELFADDR };
// NOTE: the ClassWizard will add data members here
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSelfAddrDlg)
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CSelfAddrDlg)
virtual BOOL OnInitDialog();
virtual void OnOK();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SELFADDRDLG_H__E7D694C1_807E_11D2_8F3A_0060089F9D1C__INCLUDED_)
| [
"[email protected]"
] | |
95c230af51f0d466a4c9d2e21b93654e8b5311f1 | 295eb752d0ea8d6f9c3f0646f9d6b07a707da700 | /ROS/catkin_ws/src/ralfmain_slam/ert_main.cpp | 200e8b5e9391bed9e6fa4cd2ef08b66af1dbf759 | [] | no_license | GiulliMo/Master_Soft | f4f836c0f2a9e105d809e68f9064546ab08fbc0a | ae168a90bab75acb4753c87b9d24af3e0752d189 | refs/heads/master | 2022-07-27T11:03:00.356237 | 2020-10-20T14:39:12 | 2020-10-20T14:39:12 | 241,363,290 | 0 | 0 | null | 2022-07-06T20:53:41 | 2020-02-18T13:07:44 | HTML | UTF-8 | C++ | false | false | 2,718 | cpp | //
// Academic License - for use in teaching, academic research, and meeting
// course requirements at degree granting institutions only. Not for
// government, commercial, or other organizational use.
//
// File: ert_main.cpp
//
// Code generated for Simulink model 'RALFMain_SLAM'.
//
// Model version : 1.191
// Simulink Coder version : 9.3 (R2020a) 18-Nov-2019
// C/C++ source code generated on : Thu Jul 16 13:44:06 2020
//
// Target selection: ert.tlc
// Embedded hardware selection: Intel->x86-64 (Linux 64)
// Code generation objectives: Unspecified
// Validation result: Not run
//
#include <stdio.h>
#include <stdlib.h>
#include "RALFMain_SLAM.h"
#include "RALFMain_SLAM_private.h"
#include "rtwtypes.h"
#include "limits.h"
#include "rt_nonfinite.h"
#include "linuxinitialize.h"
#define UNUSED(x) x = x
#define NAMELEN 16
// Function prototype declaration
void exitFcn(int sig);
void *terminateTask(void *arg);
void *baseRateTask(void *arg);
void *subrateTask(void *arg);
volatile boolean_T stopRequested = false;
volatile boolean_T runModel = true;
sem_t stopSem;
sem_t baserateTaskSem;
pthread_t schedulerThread;
pthread_t baseRateThread;
void *threadJoinStatus;
int terminatingmodel = 0;
void *baseRateTask(void *arg)
{
runModel = (rtmGetErrorStatus(RALFMain_SLAM_M) == (NULL)) &&
!rtmGetStopRequested(RALFMain_SLAM_M);
while (runModel) {
sem_wait(&baserateTaskSem);
RALFMain_SLAM_step();
// Get model outputs here
stopRequested = !((rtmGetErrorStatus(RALFMain_SLAM_M) == (NULL)) &&
!rtmGetStopRequested(RALFMain_SLAM_M));
runModel = !stopRequested;
}
runModel = 0;
terminateTask(arg);
pthread_exit((void *)0);
return NULL;
}
void exitFcn(int sig)
{
UNUSED(sig);
rtmSetErrorStatus(RALFMain_SLAM_M, "stopping the model");
}
void *terminateTask(void *arg)
{
UNUSED(arg);
terminatingmodel = 1;
{
runModel = 0;
}
// Disable rt_OneStep() here
// Terminate model
RALFMain_SLAM_terminate();
sem_post(&stopSem);
return NULL;
}
int main(int argc, char **argv)
{
UNUSED(argc);
UNUSED(argv);
void slros_node_init(int argc, char** argv);
slros_node_init(argc, argv);
rtmSetErrorStatus(RALFMain_SLAM_M, 0);
// Initialize model
RALFMain_SLAM_initialize();
// Call RTOS Initialization function
myRTOSInit(0.01, 0);
// Wait for stop semaphore
sem_wait(&stopSem);
#if (MW_NUMBER_TIMER_DRIVEN_TASKS > 0)
{
int i;
for (i=0; i < MW_NUMBER_TIMER_DRIVEN_TASKS; i++) {
CHECK_STATUS(sem_destroy(&timerTaskSem[i]), 0, "sem_destroy");
}
}
#endif
return 0;
}
//
// File trailer for generated code.
//
// [EOF]
//
| [
"[email protected]"
] | |
e8d1ea17a27705c99ace0dcb76421cb2cb828c4d | 65f9576021285bc1f9e52cc21e2d49547ba77376 | /LINUX/android/vendor/qcom/proprietary/sensors-see/sensors-hal/framework/ssc_sensor.cpp | e870fd6ddcf01e530d7ef820d46a6dc0b87910de | [] | no_license | AVCHD/qcs605_root_qcom | 183d7a16e2f9fddc9df94df9532cbce661fbf6eb | 44af08aa9a60c6ca724c8d7abf04af54d4136ccb | refs/heads/main | 2023-03-18T21:54:11.234776 | 2021-02-26T11:03:59 | 2021-02-26T11:03:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,003 | cpp | /*
* Copyright (c) 2017-2018 Qualcomm Technologies, Inc.
* All Rights Reserved.
* Confidential and Proprietary - Qualcomm Technologies, Inc.
*/
#include <thread>
#include <chrono>
#include "ssc_utils.h"
#include "ssc_sensor.h"
#include "sensors_log.h"
#include "sensors_timeutil.h"
#include "sns_resampler.pb.h"
#include <mutex>
using namespace std;
static const auto MSEC_PER_SEC = 1000;
static const auto WAIT_TIME_MS = 250;
static const char *SSC_DATATYPE_RESAMPLER = "resampler";
static char DIAG_LOG_MODULE_NAME[] = "sensors-hal";
ssc_sensor::ssc_sensor(sensor_uid suid, sensor_wakeup_type wakeup):
sensor(wakeup),
_suid(suid),
_attributes(lookup_attributes()),
_resampler_suid(get_resampler_suid()),
_pending_flush_requests(0),
_diag(uint64_t(this))
{
if (wakeup == SENSOR_WAKEUP) {
set_wakeup_flag(true);
_wakeup_type = wakeup;
}
set_sensor_info();
}
void ssc_sensor::set_sensor_typename(const string& type_name)
{
string name_attr = attributes().get_string(SNS_STD_SENSOR_ATTRID_NAME);
name_attr.pop_back(); /* remove NUL terminator */
_sensor_name = name_attr + " " + type_name +
((_wakeup_type == SENSOR_WAKEUP) ? " Wakeup" : " Non-wakeup");
set_name(_sensor_name.c_str());
}
void ssc_sensor::set_nowk_msgid(const int msg_id)
{
_nowk_msg_id_list.push_back(msg_id);
}
void ssc_sensor::set_sensor_info()
{
const sensor_attributes& attr = attributes();
set_vendor(attr.get_string(SNS_STD_SENSOR_ATTRID_VENDOR).c_str());
_datatype = attr.get_string(SNS_STD_SENSOR_ATTRID_TYPE);
set_sensor_typename();
auto version = attr.get_ints(SNS_STD_SENSOR_ATTRID_VERSION);
if (version.size() > 0 && version[0] > 0) {
set_version(version[0]);
} else {
set_version(1);
}
auto stream_type = attr.get_stream_type();
switch (stream_type) {
case SNS_STD_SENSOR_STREAM_TYPE_STREAMING: {
set_reporting_mode(SENSOR_FLAG_CONTINUOUS_MODE);
vector<float> rates = attr.get_floats(SNS_STD_SENSOR_ATTRID_RATES);
/* streaming sensors must have rates attribute */
if (rates.size() == 0) {
throw runtime_error(
"rates attribute unavailable for a streaming sensor");
}
/* ceil() is used to make sure that delay (period) is not
truncated, as it will cause the calculated rates to be
more than what is supported by the sensor */
_sensor_max_delay = int32_t(ceil(USEC_PER_SEC / rates[0]));
set_max_delay(_sensor_max_delay);
int32_t min_delay = int32_t(ceil(USEC_PER_SEC / rates[rates.size()-1]));
set_min_delay(min_delay);
vector<float> low_lat_rates = attr.get_floats(SNS_STD_SENSOR_ATTRID_ADDITIONAL_LOW_LATENCY_RATES);
if (low_lat_rates.size() != 0) {
min_delay = int32_t(ceil(USEC_PER_SEC / low_lat_rates[low_lat_rates.size()-1]));
}
set_min_low_lat_delay(min_delay);
/* if streaming sensor is physical, use resampler */
auto phys_sensor_attr = attr.get_bools(
SNS_STD_SENSOR_ATTRID_PHYSICAL_SENSOR);
if (phys_sensor_attr.size() > 0 && phys_sensor_attr[0] == true) {
set_resampling(true);
}
break;
}
case SNS_STD_SENSOR_STREAM_TYPE_ON_CHANGE:
case SNS_STD_SENSOR_STREAM_TYPE_SINGLE_OUTPUT:
set_reporting_mode(SENSOR_FLAG_ON_CHANGE_MODE);
break;
default:
throw runtime_error("invalid stream_type " + to_string(stream_type));
}
auto resolution = attr.get_floats(SNS_STD_SENSOR_ATTRID_SELECTED_RESOLUTION);
if (resolution.size() > 0) {
set_resolution(resolution[0]);
} else {
/* set default value 0.1 */
set_resolution(0.1);
sns_logd("dt=%s, SNS_STD_SENSOR_ATTRID_SELECTED_RESOLUTION not set",
_datatype.c_str());
}
auto ranges = attr.get_ranges(SNS_STD_SENSOR_ATTRID_SELECTED_RANGE);
if (ranges.size() > 0) {
set_max_range(ranges[0].second);
} else {
/* set default value 1.0 */
set_max_range(1.0f);
sns_logd("dt=%s, SNS_STD_SENSOR_ATTRID_SELECTED_RANGE not set",
_datatype.c_str());
}
auto currents = attr.get_ints(SNS_STD_SENSOR_ATTRID_ACTIVE_CURRENT);
if (currents.size() > 0) {
/* use max current and convert from uA to mA */
auto max_iter = std::max_element(currents.begin(), currents.end());
set_power(float(*max_iter) / 1000.0);
}
// TODO: calculate following based on system capacity
set_fifo_max_count(10000);
}
void ssc_sensor::activate()
{
std::lock_guard<mutex> lk(_mutex);
if (!is_active()) {
/* establish a new connection to ssc */
_ssc_conn = make_unique<ssc_connection>(
[this](const uint8_t *data, size_t size)
{
ssc_conn_event_cb(data, size);
});
if ( _wakeup_type == SENSOR_WAKEUP)
_ssc_conn->set_unsuspendable_channel();
_ssc_conn->use_report_indication();
_ssc_conn->register_error_cb([this](auto e){ ssc_conn_error_cb(e); });
_ssc_conn->register_resp_cb([this](uint32_t resp_value){ ssc_conn_resp_cb(resp_value); });
send_sensor_config_request();
}
}
void ssc_sensor::deactivate()
{
std::lock_guard<mutex> lk(_mutex);
if (is_active()) {
_ssc_conn.reset();
}
}
void ssc_sensor::add_nowk_msgid_list(sns_client_request_msg &req_msg)
{
std::vector<int>::iterator it = _nowk_msg_id_list.begin();
while(it != _nowk_msg_id_list.end())
{
req_msg.mutable_susp_config()->add_nowakeup_msg_ids(*it);
it++;
}
}
sns_client_request_msg ssc_sensor::create_resampler_config_request()
{
sns_client_request_msg pb_req_msg;
sns_resampler_config pb_resampler_config;
string pb_resampler_config_encoded;
float sample_rate = float(NSEC_PER_SEC) / get_params().sample_period_ns;
sns_logd("sr=%f", sample_rate);
pb_resampler_config.mutable_sensor_uid()->set_suid_high(_suid.high);
pb_resampler_config.mutable_sensor_uid()->set_suid_low(_suid.low);
pb_resampler_config.set_resampled_rate(sample_rate);
pb_resampler_config.set_rate_type(SNS_RESAMPLER_RATE_FIXED);
pb_resampler_config.set_filter(true); // TODO: check if this is correct
pb_resampler_config.SerializeToString(&pb_resampler_config_encoded);
sns_logd("SNS_RESAMPLER_MSGID_SNS_RESAMPLER_CONFIG");
add_nowk_msgid_list(pb_req_msg);
pb_req_msg.set_msg_id(SNS_RESAMPLER_MSGID_SNS_RESAMPLER_CONFIG);
pb_req_msg.mutable_request()->set_payload(pb_resampler_config_encoded);
return pb_req_msg;
}
void ssc_sensor::send_sensor_config_request()
{
string pb_req_msg_encoded;
sns_client_request_msg pb_req_msg;
if (_resampling == true) {
pb_req_msg = create_resampler_config_request();
pb_req_msg.mutable_suid()->set_suid_high(_resampler_suid.high);
pb_req_msg.mutable_suid()->set_suid_low(_resampler_suid.low);
} else {
pb_req_msg = create_sensor_config_request();
pb_req_msg.mutable_suid()->set_suid_high(_suid.high);
pb_req_msg.mutable_suid()->set_suid_low(_suid.low);
}
uint32_t batch_period_us = get_params().max_latency_ns / NSEC_PER_USEC;
uint32_t flush_period_us = 0;
/* To support Android Hi-Fi requirements for non-wakeup sensors, if
batch period is less than the time required to buffer
fifoReservedEventCount number of events, we need to set flush period
according to the fifoReservedEventCount. For streaming sensors,
this will be derived from the sample_period and for non-streaming
sensors, flush period will be set to a max value */
if (_wakeup_type == SENSOR_NO_WAKEUP) {
if (get_reporting_mode() == SENSOR_FLAG_CONTINUOUS_MODE)
{
flush_period_us = (get_params().sample_period_ns / NSEC_PER_USEC) *
get_sensor_info().fifoReservedEventCount;
} else {
if (get_sensor_info().fifoReservedEventCount > 0) {
flush_period_us = UINT32_MAX;
}
}
if (flush_period_us > batch_period_us) {
pb_req_msg.mutable_request()->mutable_batching()->
set_flush_period(flush_period_us);
} else {
flush_period_us = 0;
}
} else {
/*after fifoMaxEventCount need to wake up Apps and send the samples
set batch period corresponding to that as you need to wakeup the App*/
if (get_reporting_mode() == SENSOR_FLAG_CONTINUOUS_MODE) {
uint32_t batch_period_max_us =
(get_params().sample_period_ns / NSEC_PER_USEC) *
get_sensor_info().fifoMaxEventCount;
if(batch_period_us > batch_period_max_us) {
sns_logi("dt=%s, asked batch_period_us : %u adjusted_us : %u",
_datatype.c_str(),
(unsigned int)batch_period_us,
(unsigned int)batch_period_max_us);
batch_period_us = batch_period_max_us;
}
}
}
pb_req_msg.mutable_request()->mutable_batching()->
set_batch_period(batch_period_us);
pb_req_msg.mutable_susp_config()->set_delivery_type(get_delivery_type());
pb_req_msg.mutable_susp_config()->
set_client_proc_type(SNS_STD_CLIENT_PROCESSOR_APSS);
pb_req_msg.SerializeToString(&pb_req_msg_encoded);
sns_logd("dt=%s, bp=%u, fp=%u, resampling=%d", _datatype.c_str(),
(unsigned int) batch_period_us,
(unsigned int) flush_period_us,
_resampling);
_diag.log_request_msg(pb_req_msg_encoded, _datatype, DIAG_LOG_MODULE_NAME);
_ssc_conn->send_request(pb_req_msg_encoded);
}
void ssc_sensor::update_config()
{
lock_guard<mutex> lk(_mutex);
send_sensor_config_request();
}
void ssc_sensor::flush()
{
std::lock_guard<mutex> lk(_mutex);
if (!is_active()) {
return;
}
sns_client_request_msg pb_req_msg;
string pb_req_msg_encoded;
pb_req_msg.set_msg_id(SNS_STD_MSGID_SNS_STD_FLUSH_REQ);
pb_req_msg.mutable_request()->clear_payload();
if (_resampling == true) {
pb_req_msg.mutable_suid()->set_suid_high(_resampler_suid.high);
pb_req_msg.mutable_suid()->set_suid_low(_resampler_suid.low);
} else {
pb_req_msg.mutable_suid()->set_suid_high(_suid.high);
pb_req_msg.mutable_suid()->set_suid_low(_suid.low);
}
pb_req_msg.mutable_susp_config()->set_delivery_type(get_delivery_type());
pb_req_msg.mutable_susp_config()->set_client_proc_type(SNS_STD_CLIENT_PROCESSOR_APSS);
pb_req_msg.SerializeToString(&pb_req_msg_encoded);
_pending_flush_requests++;
uint32_t pending = _pending_flush_requests;
sns_logd("sending SNS_STD_MSGID_SNS_STD_FLUSH_REQ, pending=%u",
(unsigned int) pending);
_diag.log_request_msg(pb_req_msg_encoded, _datatype, DIAG_LOG_MODULE_NAME);
_ssc_conn->send_request(pb_req_msg_encoded);
}
void ssc_sensor::handle_sns_std_flush_event(
const sns_client_event_msg_sns_client_event& pb_event)
{
uint32_t pending = _pending_flush_requests;
if (pending > 0) {
sensors_event_t hal_event;
memset(&hal_event, 0x00, sizeof(sensors_event_t));
hal_event.version = META_DATA_VERSION;
hal_event.meta_data.what = META_DATA_FLUSH_COMPLETE;
hal_event.meta_data.sensor = get_sensor_info().handle;
sns_logd("dt=%s, META_DATA_FLUSH_COMPLETE, pending=%u",
_datatype.c_str(), (unsigned int) pending);
submit_sensors_hal_event(hal_event);
_pending_flush_requests--;
on_flush_complete();
}
}
void ssc_sensor::ssc_conn_event_cb(const uint8_t *data, size_t size)
{
string pb_event_msg_encoded((char *)data, size);
_diag.log_event_msg(pb_event_msg_encoded, _datatype, DIAG_LOG_MODULE_NAME);
sns_client_event_msg pb_event_msg;
pb_event_msg.ParseFromArray(data, size);
for (int i=0; i < pb_event_msg.events_size(); i++) {
auto&& pb_event = pb_event_msg.events(i);
sns_logv("event[%d] msg_id=%d, ts=%llu", i, pb_event.msg_id(),
(unsigned long long) pb_event.timestamp());
if (pb_event.msg_id() == SNS_STD_MSGID_SNS_STD_FLUSH_EVENT) {
handle_sns_std_flush_event(pb_event);
} else {
handle_sns_client_event(pb_event);
}
}
}
void ssc_sensor::ssc_conn_resp_cb(uint32_t resp_value)
{
_diag.log_response_msg(resp_value,_datatype, DIAG_LOG_MODULE_NAME);
}
void ssc_sensor::ssc_conn_error_cb(ssc_error_type e)
{
sns_loge("error = %d", e);
/* re-send config request when connection resets */
if (e == SSC_CONNECTION_RESET) {
bool got_sensorback = false;
uint8_t retry_cnt = RETRY_CNT;
sns_loge("connection reset, resend config request");
//check for suid and then send config request
while (retry_cnt && is_active()) {
using namespace std::chrono;
suid_lookup lookup(
[this, &got_sensorback](const string& datatype, const auto& suids)
{
sns_logd("got the suid call back");
int i;
for (i = 0; i < (int)suids.size(); i++) {
if ((suids[i].high == _suid.high) &&
(suids[i].low == _suid.low))
got_sensorback = true;
}
});
if (got_sensorback == true) {
sns_logi("after ssr, discovery of %s took %f sec",
_datatype.c_str(),
(float)((RETRY_CNT-retry_cnt)*((float)WAIT_TIME_MS/MSEC_PER_SEC)));
break;
}
lookup.request_suid(_datatype);
retry_cnt--;
sns_logd("requesting suid (cnt) %d", retry_cnt);
this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME_MS));
}
if (is_active()) {
if (got_sensorback)
send_sensor_config_request();
else
sns_loge("could not restart %s after ssr", _datatype.c_str());
} else {
sns_logi("%s deactivated during ssr", _datatype.c_str());
}
}
}
void ssc_sensor::handle_sns_client_event(
const sns_client_event_msg_sns_client_event& pb_event)
{
switch(pb_event.msg_id()) {
case SNS_STD_SENSOR_MSGID_SNS_STD_SENSOR_EVENT:
handle_sns_std_sensor_event(pb_event);
break;
default:
break;
}
}
sns_client_request_msg ssc_sensor::create_sensor_config_request()
{
sns_client_request_msg pb_req_msg;
auto stream_type = attributes().get_stream_type();
add_nowk_msgid_list(pb_req_msg);
/* populate request message based on stream type */
if (stream_type == SNS_STD_SENSOR_STREAM_TYPE_STREAMING) {
float sample_rate = float(NSEC_PER_SEC) / get_params().sample_period_ns;
sns_logd("sr=%f", sample_rate);
sns_std_sensor_config pb_stream_cfg;
string pb_stream_cfg_encoded;
sns_logd("sending SNS_STD_SENSOR_MSGID_SNS_STD_SENSOR_CONFIG");
pb_stream_cfg.set_sample_rate(sample_rate);
pb_stream_cfg.SerializeToString(&pb_stream_cfg_encoded);
pb_req_msg.set_msg_id(SNS_STD_SENSOR_MSGID_SNS_STD_SENSOR_CONFIG);
pb_req_msg.mutable_request()->set_payload(pb_stream_cfg_encoded);
} else {
sns_logd("sending SNS_STD_SENSOR_MSGID_SNS_STD_ON_CHANGE_CONFIG");
pb_req_msg.set_msg_id(SNS_STD_SENSOR_MSGID_SNS_STD_ON_CHANGE_CONFIG);
pb_req_msg.mutable_request()->clear_payload();
}
return pb_req_msg;
}
void ssc_sensor::handle_sns_std_sensor_event(
const sns_client_event_msg_sns_client_event& pb_event)
{
sns_std_sensor_event pb_stream_event;
pb_stream_event.ParseFromString(pb_event.payload());
sensors_event_t hal_event = create_sensor_hal_event(pb_event.timestamp());
int num_items = pb_stream_event.data_size();
if (num_items > SENSORS_HAL_MAX_DATA_LEN) {
sns_loge("num_items=%d exceeds SENSORS_HAL_MAX_DATA_LEN=%d",
num_items, SENSORS_HAL_MAX_DATA_LEN);
num_items = SENSORS_HAL_MAX_DATA_LEN;
}
for (int i = 0; i < num_items; i++) {
hal_event.data[i] = pb_stream_event.data(i);
}
if (sensors_log::get_level() >= sensors_log::DEBUG) {
/* debug: print the event data */
string s = "[";
for (int i = 0; i < pb_stream_event.data_size(); i++) {
s += to_string(pb_stream_event.data(i));
if (i < pb_stream_event.data_size() - 1) {
s += ", ";
} else {
s += "]";
}
}
sns_logd("%s_sample: ts = %llu ns; value = %s", _datatype.c_str(),
(unsigned long long) hal_event.timestamp, s.c_str());
}
submit_sensors_hal_event(hal_event);
}
sensors_event_t ssc_sensor::create_sensor_hal_event(uint64_t ssc_timestamp)
{
sensors_event_t hal_event;
//Fix for static analysis error - uninitialized variable
memset(&hal_event, 0x00, sizeof(sensors_event_t));
hal_event.version = sizeof(sensors_event_t);
hal_event.sensor = get_sensor_info().handle;
hal_event.type = get_sensor_info().type;
hal_event.timestamp = sensors_timeutil::get_instance().
qtimer_ticks_to_elapsedRealtimeNano(ssc_timestamp);
sns_logv("ssc_ts = %llu tk, hal_ts = %lld ns, %lf",
(unsigned long long)ssc_timestamp,
(long long)hal_event.timestamp, hal_event.timestamp / 1000000000.0 );
return hal_event;
}
sensor_uid ssc_sensor::get_resampler_suid()
{
const auto& suids =
sensor_factory::instance().get_suids(SSC_DATATYPE_RESAMPLER);
if (suids.size() == 0) {
throw runtime_error("resampler suid not found");
}
return suids[0];
}
void ssc_sensor::set_resampling(bool val)
{
_resampling = val;
/* change max delay (min rate) based on resampler usage */
set_max_delay(val ? RESAMPLER_MAX_DELAY : _sensor_max_delay);
}
int8_t ssc_sensor::sensors_hal_sample_status(
sns_std_sensor_sample_status std_status)
{
switch (std_status) {
case SNS_STD_SENSOR_SAMPLE_STATUS_UNRELIABLE:
return SENSOR_STATUS_UNRELIABLE;
case SNS_STD_SENSOR_SAMPLE_STATUS_ACCURACY_LOW:
return SENSOR_STATUS_ACCURACY_LOW;
case SNS_STD_SENSOR_SAMPLE_STATUS_ACCURACY_MEDIUM:
return SENSOR_STATUS_ACCURACY_MEDIUM;
case SNS_STD_SENSOR_SAMPLE_STATUS_ACCURACY_HIGH:
return SENSOR_STATUS_ACCURACY_HIGH;
default:
sns_loge("invalid std_status = %d", std_status);
}
return SENSOR_STATUS_UNRELIABLE;
}
static bool ssc_sensor_module_init()
{
sensor_factory::request_datatype(SSC_DATATYPE_RESAMPLER);
return true;
}
SENSOR_MODULE_INIT(ssc_sensor_module_init);
| [
"[email protected]"
] | |
11d97796ecfd20cdd4ac0d1337198b254f33d80f | 8504192cad2b9c755eda53d911a33b3ef49400bd | /mlpack-1.0.12/include/mlpack/methods/logistic_regression/logistic_regression.hpp | f5ae6a5ec8c87ea998b741d075c038c3ecc991d2 | [
"BSD-3-Clause"
] | permissive | brycepg/machine_learning_group2 | 47fa9279a9fb1a3d54803372c649c2c3984910aa | 6461da5398e13880c4d222c049ff909991abc6a5 | refs/heads/master | 2021-01-23T15:50:59.981613 | 2015-04-02T01:43:15 | 2015-04-02T01:43:15 | 31,920,073 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,250 | hpp | /**
* @file logistic_regression.hpp
* @author Sumedh Ghaisas
*
* The LogisticRegression class, which implements logistic regression. This
* implements supports L2-regularization.
*
* This file is part of mlpack 1.0.12.
*
* mlpack is free software; you may redstribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_HPP
#define __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_HPP
#include <mlpack/core.hpp>
#include <mlpack/core/optimizers/lbfgs/lbfgs.hpp>
#include "logistic_regression_function.hpp"
namespace mlpack {
namespace regression {
template<
template<typename> class OptimizerType = mlpack::optimization::L_BFGS
>
class LogisticRegression
{
public:
/**
* Construct the LogisticRegression class with the given labeled training
* data. This will train the model. Optionally, specify lambda, which is the
* penalty parameter for L2-regularization. If not specified, it is set to 0,
* which results in standard (unregularized) logistic regression.
*
* @param predictors Input training variables.
* @param responses Outputs resulting from input training variables.
* @param lambda L2-regularization parameter.
*/
LogisticRegression(const arma::mat& predictors,
const arma::vec& responses,
const double lambda = 0);
/**
* Construct the LogisticRegression class with the given labeled training
* data. This will train the model. Optionally, specify lambda, which is the
* penalty parameter for L2-regularization. If not specified, it is set to 0,
* which results in standard (unregularized) logistic regression.
*
* @param predictors Input training variables.
* @param responses Outputs results from input training variables.
* @param initialPoint Initial model to train with.
* @param lambda L2-regularization parameter.
*/
LogisticRegression(const arma::mat& predictors,
const arma::vec& responses,
const arma::mat& initialPoint,
const double lambda = 0);
/**
* Construct the LogisticRegression class with the given labeled training
* data. This will train the model. This overload takes an already
* instantiated optimizer (which holds the LogisticRegressionFunction error
* function, which must also be instantiated), so that the optimizer can be
* configured before the training is run by this constructor. The predictors
* and responses and initial point are all taken from the error function
* contained in the optimizer.
*
* @param optimizer Instantiated optimizer with instantiated error function.
*/
LogisticRegression(OptimizerType<LogisticRegressionFunction>& optimizer);
/**
* Construct a logistic regression model from the given parameters, without
* performing any training. The lambda parameter is used for the
* ComputeAccuracy() and ComputeError() functions; this constructor does not
* train the model itself.
*
* @param parameters Parameters making up the model.
* @param lambda L2-regularization penalty parameter.
*/
LogisticRegression(const arma::vec& parameters, const double lambda = 0);
//! Return the parameters (the b vector).
const arma::vec& Parameters() const { return parameters; }
//! Modify the parameters (the b vector).
arma::vec& Parameters() { return parameters; }
//! Return the lambda value for L2-regularization.
const double& Lambda() const { return lambda; }
//! Modify the lambda value for L2-regularization.
double& Lambda() { return lambda; }
/**
* Predict the responses to a given set of predictors. The responses will be
* either 0 or 1. Optionally, specify the decision boundary; logistic
* regression returns a value between 0 and 1. If the value is greater than
* the decision boundary, the response is taken to be 1; otherwise, it is 0.
* By default the decision boundary is 0.5.
*
* @param predictors Input predictors.
* @param responses Vector to put output predictions of responses into.
* @param decisionBoundary Decision boundary (default 0.5).
*/
void Predict(const arma::mat& predictors,
arma::vec& responses,
const double decisionBoundary = 0.5) const;
/**
* Compute the accuracy of the model on the given predictors and responses,
* optionally using the given decision boundary. The responses should be
* either 0 or 1. Logistic regression returns a value between 0 and 1. If
* the value is greater than the decision boundary, the response is taken to
* be 1; otherwise, it is 0. By default, the decision boundary is 0.5.
*
* The accuracy is returned as a percentage, between 0 and 100.
*
* @param predictors Input predictors.
* @param responses Vector of responses.
* @param decisionBoundary Decision boundary (default 0.5).
* @return Percentage of responses that are predicted correctly.
*/
double ComputeAccuracy(const arma::mat& predictors,
const arma::vec& responses,
const double decisionBoundary = 0.5) const;
/**
* Compute the error of the model. This returns the negative objective
* function of the logistic regression log-likelihood function. For the model
* to be optimal, the negative log-likelihood function should be minimized.
*
* @param predictors Input predictors.
* @param responses Vector of responses.
*/
double ComputeError(const arma::mat& predictors,
const arma::vec& responses) const;
// Returns a string representation of this object.
std::string ToString() const;
private:
//! Vector of trained parameters.
arma::vec parameters;
//! L2-regularization penalty parameter.
double lambda;
};
}; // namespace regression
}; // namespace mlpack
// Include implementation.
#include "logistic_regression_impl.hpp"
#endif // __MLPACK_METHODS_LOGISTIC_REGRESSION_LOGISTIC_REGRESSION_HPP
| [
"[email protected]"
] | |
6b01513bfdf4a50c302f535580504c519e870a0c | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/115/970/CWE762_Mismatched_Memory_Management_Routines__new_delete_array_int_64a.cpp | 0db2a5692bc5cac0a6ae58c4ee1d1f97a1c0472f | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,579 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__new_delete_array_int_64a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_delete_array.label.xml
Template File: sources-sinks-64a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: Allocate data using new
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using delete
* BadSink : Deallocate data using delete []
* Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__new_delete_array_int_64
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(void * dataVoidPtr);
void bad()
{
int * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */
data = new int;
badSink(&data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(void * dataVoidPtr);
static void goodG2B()
{
int * data;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new [] */
data = new int[100];
goodG2BSink(&data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(void * dataVoidPtr);
static void goodB2G()
{
int * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */
data = new int;
goodB2GSink(&data);
}
void good()
{
goodG2B();
goodB2G();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__new_delete_array_int_64; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"[email protected]"
] | |
46cbe0d6498b4c6cd23d9daddc26a2689aaef7c6 | f881f64589cbe575bdacbf5b06873fddc5a1a818 | /UVA Codes/Volume 115/11565 - Simple Equations/11565 - Simple Equations.cpp | b7515056066497f217180bff4751c09a4379c2bb | [] | no_license | dipu-bd/OJ-Codes | ae1c9c71ab75b11a8b4f7c86c4ab826729f7ba30 | 9afd2a590e9936bf4d74b0ea3f88ebf437f9584b | refs/heads/master | 2021-01-18T23:01:04.067008 | 2016-03-31T13:09:57 | 2016-03-31T13:09:57 | 30,977,239 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,129 | cpp | /*==================================
Author : Sudipto Chandra (Dipu)
Email : [email protected]
University : SUST
===================================*/
//#include <bits/stdc++.h>
//C headers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <ctype.h>
#include <assert.h>
//cpp headers
#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <deque>
#include <list>
using namespace std;
//typedefs
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vii;
typedef vector<pii> vpii;
//always useful
#define unsigned un
#define gcd(a,b) __gcd(a,b)
#define clr(a) memset(a, 0, sizeof(a))
#define mem(a,b) memset(a, b, sizeof(a))
#define memsz(a,b,n) memset(a, b, n * sizeof(*a))
#define REP(i, a, n) for(int i = a; i < n; ++i)
#define REPE(i, a, n) for(int i = a; i <= n; ++i)
#define REPNE(i, a, n) for(int i = a; i >= n; --i)
//input-output
#define sf scanf
#define pf printf
#define sf1(a) scanf("%d", &a)
#define sf2(a, b) scanf("%d %d", &a, &b)
#define sf3(a, b, c) scanf("%d %d %d", &a, &b, &c)
#define sf4(a, b, c, d) scanf("%d %d %d %d", &a, &b, &c, &d)
#define deb1(a) cout << a << "\n"
#define deb2(a,b) cout << a << " " << b << "\n"
#define deb3(a,b,c) cout << a << " " << b << " " << c << "\n"
#define deb4(a,b,c,d) cout << a << " " << b << " " << c << " " << d << "\n"
//useful with graphs
#define fr first
#define sc second
#define pb push_back
#define pp pop_back
#define mp make_pair
#define ins insert
#define IT iterator
#define all(v) v.begin(), v.end()
#define ssort(v) stable_sort(v.begin(), v.end())
#define LB lower_bound
#define UB upper_bound
#define POPC __builtin_popcount
#define loop(i, x) for(__typeof((x).begin()) i=(x).begin(); i!=(x).end(); ++i)
#define rloop(i, x) for(__typeof((x).rbegin()) i=(x).rbegin(); i!=(x).rend(); ++i)
#define TEMPLATE template<typename T>
//variables and functions
TEMPLATE inline T sqr(T n) { return n * n; }
TEMPLATE inline T pmod(T n, T m) { return ((n % m) + m) % m; }
TEMPLATE inline T lcm(T a, T b) { return a * (b / gcd(a, b)); }
TEMPLATE T power(T n, ll p) { if(!p) return 1; else { T res = sqr(power(n, p >> 1)); if(p & 1) res *= n; return res; } }
TEMPLATE T bigmod(T n, ll p, T m) { if(!p) return 1; else { T r = sqr(bigmod(n, p >> 1, m)) % m; if(p & 1) r = (r * n) % m; return r; } }
TEMPLATE T exgcd(T a, T b, T& x, T& y) { if(!b) { x = 1; y = 0; return a; } else { T g = exgcd(b, a % b, y, x); y -= (a / b) * x; return g; } }
TEMPLATE T modinv(T a, T m) { T x, y; exgcd(a, m, x, y); return pmod(x, m); }
TEMPLATE inline T extract(const string& s, T ret) { stringstream ss(s); ss >> ret; return ret; }
TEMPLATE inline string tostring(T n) { stringstream ss; ss << n; return ss.str(); }
inline double hypot(double x, double y) { return sqrt(sqr(x) + sqr(y)); }
/*------------------------------------------------------------------------------------*/
//const int oo = 1 << 30;
//const int mod = 1000000007;
int test, cas = 1;
int main()
{
sf1(test);
while(test--)
{
int A, B, C;
sf3(A, B, C);
bool solved = 0;
for(int x = 1; x * x < C; x++)
{
if(B % x != 0) continue;
int d = C - x * x - 2 * B / x;
if(d < 0) continue;
int y = ((int)(A - x + sqrt(d))) / 2;
int z = ((int)(A - x - sqrt(d))) / 2;
if(x + y + z != A) continue;
if(x * y * z != B) continue;
if(x * x + y * y + z * z != C) continue;
set<int> arr;
arr.insert(x);
arr.insert(y);
arr.insert(z);
if(arr.size() != 3) continue;
loop(it, arr)
{
if(it != arr.begin())
putchar(' ');
printf("%d", *it);
}
putchar('\n');
solved = 1;
break;
}
if(!solved)
{
puts("No solution.");
}
}
return 0;
}
| [
"[email protected]"
] | |
96eb8a1ed0c1e19903731541128d47e5fc74cb8c | 36f70f3ce323f2b910a9428a6c78d84fca9608a6 | /glim/include/glim/paint/gl/VertexArray.h | af1f3e8962e18ec424ea1ce85e56b5c26f9fce00 | [] | no_license | lykhonis/glim | 14570b8432b43c5020a8af348dec6f45c9c7965c | 263f317b88f8789da985ad02420ccb3ba3383a82 | refs/heads/master | 2022-12-23T01:20:52.616907 | 2020-09-24T19:19:52 | 2020-09-24T19:19:52 | 293,303,768 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | h | #pragma once
#include <vector>
#include <glim/paint/gl/Buffer.h>
namespace glim::paint::gl {
class VertexArray final {
public:
VertexArray() noexcept;
VertexArray(const VertexArray &) = delete;
VertexArray(VertexArray &&other) noexcept
: index_(other.index_), array_(other.array_), buffers_(std::move(other.buffers_)) {
other.array_ = std::nullopt;
}
VertexArray &operator=(const VertexArray &) = delete;
VertexArray &operator=(VertexArray &&other) noexcept {
if (this != &other) {
index_ = other.index_;
array_ = other.array_;
buffers_ = std::move(other.buffers_);
other.array_ = std::nullopt;
}
return *this;
}
~VertexArray();
void bind();
void unbind();
void addBuffer(Buffer);
private:
int index_ = 0;
std::optional<GLuint> array_;
std::vector<Buffer> buffers_;
};
}
| [
"[email protected]"
] | |
2477a2f156dee4af7afbbc46a3c45292313eaf6e | 4bea57e631734f8cb1c230f521fd523a63c1ff23 | /projects/openfoam/rarefied-flows/impingment/sims/test/nozzle1/8.36/grad(rho) | c5e496d062ca376e839208d6a433acd11cacddb5 | [] | no_license | andytorrestb/cfal | 76217f77dd43474f6b0a7eb430887e8775b78d7f | 730fb66a3070ccb3e0c52c03417e3b09140f3605 | refs/heads/master | 2023-07-04T01:22:01.990628 | 2021-08-01T15:36:17 | 2021-08-01T15:36:17 | 294,183,829 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,265 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "8.36";
object grad(rho);
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -4 0 0 0 0 0];
internalField nonuniform List<vector>
1900
(
(-5132.42 -0.236933 0)
(-14552.2 0.101612 0)
(4278.34 0.00293167 0)
(1987.53 0.854568 0)
(-24.0296 0.744211 0)
(-656.771 -0.496406 0)
(-928.573 -2.32934 0)
(-815.735 2.7448 0)
(-392.181 6.73004 0)
(826.821 -41.1333 0)
(-5132.56 -0.450877 0)
(-14552 0.201234 0)
(4279.1 0.138298 0)
(1988.27 1.57772 0)
(-25.3806 1.24184 0)
(-659.844 -0.893239 0)
(-925.332 -4.89495 0)
(-806.676 -6.06621 0)
(-436.059 -50.0037 0)
(-155.528 -113.914 0)
(-5132.67 4.44089e-09 0)
(-14551.6 6.96332e-09 0)
(4279.72 7.33635e-09 0)
(1988.63 6.25278e-09 0)
(-26.5006 6.43041e-09 0)
(-662.908 3.76588e-09 0)
(-933.746 -2.41585e-09 0)
(-860.844 -5.15143e-10 0)
(-500.029 3.73035e-10 0)
(-267.262 5.50671e-10 0)
(-5132.56 0.450877 0)
(-14552 -0.201234 0)
(4279.1 -0.138298 0)
(1988.27 -1.57772 0)
(-25.3806 -1.24184 0)
(-659.844 0.893239 0)
(-925.332 4.89495 0)
(-806.676 6.06621 0)
(-436.059 50.0037 0)
(-155.528 113.914 0)
(-5132.42 0.236933 0)
(-14552.2 -0.101612 0)
(4278.34 -0.00293166 0)
(1987.53 -0.854568 0)
(-24.0296 -0.744211 0)
(-656.771 0.496406 0)
(-928.573 2.32934 0)
(-815.735 -2.7448 0)
(-392.181 -6.73004 0)
(826.821 41.1333 0)
(40.4716 -848.474 1.23646e-11)
(-2098.06 -647.173 -1.46253e-11)
(-3412.1 -659.183 -1.83604e-11)
(-3797.97 -785.852 0)
(-25806.8 -7324.09 -7.5925e-11)
(-470.797 -1009.88 1.22112e-11)
(-1416.93 -774.06 1.46253e-11)
(-3161.94 -657.769 1.83604e-11)
(-6278.77 -303.998 0)
(-24105.5 -6098.29 0)
(-807.884 -3.21804e-11 0)
(-1415.19 1.38291e-09 0)
(-2928.21 7.40149e-11 0)
(-6070.33 1.07658e-09 0)
(-26323 -2.22045e-09 0)
(-470.797 1009.88 1.22112e-11)
(-1416.93 774.06 1.46253e-11)
(-3161.94 657.769 1.83604e-11)
(-6278.77 303.998 0)
(-24105.5 6098.29 0)
(40.4716 848.474 -3.6787e-11)
(-2098.06 647.173 -1.46253e-11)
(-3412.1 659.183 -1.83604e-11)
(-3797.97 785.852 -4.8835e-11)
(-25806.8 7324.09 7.5925e-11)
(-43681.5 14744.8 1.74117e-11)
(-15683.2 6351.06 -9.92664e-12)
(-7887.19 3094.06 0)
(-5783.84 2128.83 4.89361e-12)
(-1621.75 1333.8 -1.7275e-12)
(-39200.1 19143.9 -8.92788e-12)
(-18224.7 5548.27 5.05895e-12)
(-8919.11 1882.75 0)
(-6271.84 1262.63 -3.10808e-12)
(-3390 328.051 4.44387e-13)
(-40733 -1.34572e-09 0)
(-20087.1 -7.21171e-10 0)
(-9236.61 1.05266e-09 0)
(-6460.7 -2.46716e-10 1.25844e-12)
(-3466.53 9.7388e-10 -8.88774e-13)
(-39200.1 -19143.9 -8.92788e-12)
(-18224.7 -5548.27 5.05895e-12)
(-8919.11 -1882.75 0)
(-6271.84 -1262.63 -3.10808e-12)
(-3390 -328.051 4.44387e-13)
(-43681.5 -14744.8 8.92788e-12)
(-15683.2 -6351.06 -1.91273e-13)
(-7887.19 -3094.06 0)
(-5783.84 -2128.83 6.41134e-14)
(-1621.75 -1333.8 1.7275e-12)
(1887.1 -8334.23 0)
(735.779 -6664.79 0)
(-106.613 -4350.42 0)
(-361.164 -3712.61 0)
(-596.68 -3509.93 0)
(-819.379 -3452.16 0)
(-910.166 -3394.12 0)
(-1154.35 -3156.71 0)
(-1294.84 -2893.44 0)
(-540.347 -2226.79 0)
(1180.63 -2123.67 0)
(4044.83 -2153.26 0)
(3613.23 -2264.3 0)
(542.164 -1773.18 0)
(-575.787 -1422.16 0)
(-802.877 -1063.76 0)
(-571.81 -941.171 0)
(-287.485 -984.855 0)
(-84.7074 -857.824 0)
(-173.623 -480.879 0)
(-756.175 -116.106 0)
(-1549.22 133.16 0)
(-2396.16 195.348 0)
(-3310.55 185.859 0)
(-3275.67 134.543 0)
(-1753.04 41.3871 0)
(-426.071 1.39475 0)
(-57.3076 -1.33801 0)
(572.175 -0.836895 0)
(2035.46 0.830965 0)
(2455.9 -0.744885 0)
(1505.9 -6.49272 0)
(926.233 -7.68013 0)
(770.046 -6.00307 0)
(674.372 -2.45249 0)
(635.701 3.47694 0)
(750.579 8.25668 0)
(931.541 11.6497 0)
(982.438 18.2348 0)
(1053.61 18.4566 0)
(270.54 -3469.13 0)
(952.57 -4896.63 0)
(315.392 -3316 0)
(-315.359 -2720.82 0)
(-626.464 -2404.66 0)
(-804.158 -2265.28 0)
(-794.806 -2177.85 0)
(-1004.49 -1890.88 0)
(-1098.65 -1664.03 0)
(-418.183 -1144.59 0)
(1202.98 -1123.25 0)
(4005.86 -1117.36 0)
(3610.85 -1444.17 0)
(656.587 -1093.24 0)
(-458.663 -910.226 0)
(-690.743 -665.562 0)
(-501.013 -421.848 0)
(-246.996 -277.467 0)
(-42.1984 -207.972 0)
(-127.601 -113.977 0)
(-712.392 348.916 0)
(-1520.93 499.719 0)
(-2379.27 264.558 0)
(-3309.13 132.762 0)
(-3299.14 58.2122 0)
(-1773.05 11.363 0)
(-430.763 0.206745 0)
(-57.5069 -0.563189 0)
(572.3 -0.300303 0)
(2035.42 0.313667 0)
(2455.19 -0.303156 0)
(1505.19 -3.50971 0)
(926.178 -4.27965 0)
(770.478 -3.80457 0)
(675.584 -1.90763 0)
(637.059 2.34644 0)
(751.716 4.30704 0)
(933.276 5.28579 0)
(983.968 7.73128 0)
(1049.98 8.39396 0)
(133.028 -3.39123e-10 0)
(780.324 4.44089e-10 0)
(526.352 1.12233e-09 0)
(-96.0445 1.30804e-09 0)
(-464.16 3.95643e-10 0)
(-753.399 -3.39123e-10 0)
(-801.251 8.23584e-10 0)
(-1004.88 2.09933e-09 0)
(-1077.74 1.17885e-09 0)
(-383.029 -5.32907e-10 0)
(1188.55 -3.63346e-10 0)
(3951.47 -4.03717e-11 0)
(3620.25 5.07069e-09 0)
(697.493 -1.09811e-09 0)
(-451.371 2.97136e-09 0)
(-660.803 3.56886e-09 0)
(-458.91 6.96009e-09 0)
(-225.267 1.7045e-08 0)
(-37.1468 1.16271e-08 0)
(-11.6194 1.00526e-08 0)
(-577.646 6.04769e-09 0)
(-1573.76 -5.65204e-11 0)
(-2502.91 -5.5713e-09 0)
(-3370.57 -1.06824e-08 0)
(-3310.98 -4.52164e-09 0)
(-1769.91 -5.65204e-10 0)
(-429.54 4.3763e-09 0)
(-57.4551 -5.24833e-11 0)
(572.43 2.04281e-09 0)
(2035.46 1.23215e-08 0)
(2454.79 -5.83775e-09 0)
(1504.75 -1.37345e-08 0)
(926.147 -6.02346e-09 0)
(770.736 -1.64717e-09 0)
(676.162 -2.03474e-09 0)
(637.509 -3.79494e-09 0)
(751.434 -3.01173e-09 0)
(932.537 -3.59309e-09 0)
(983.342 -1.5745e-09 0)
(1053.25 1.59065e-09 0)
(270.54 3469.13 0)
(952.57 4896.63 0)
(315.392 3316 0)
(-315.359 2720.82 0)
(-626.464 2404.66 0)
(-804.158 2265.28 0)
(-794.806 2177.85 0)
(-1004.49 1890.88 0)
(-1098.65 1664.03 0)
(-418.183 1144.59 0)
(1202.98 1123.25 0)
(4005.86 1117.36 0)
(3610.85 1444.17 0)
(656.587 1093.24 0)
(-458.663 910.226 0)
(-690.743 665.562 0)
(-501.013 421.848 0)
(-246.996 277.467 0)
(-42.1984 207.972 0)
(-127.601 113.977 0)
(-712.392 -348.916 0)
(-1520.93 -499.719 0)
(-2379.27 -264.558 0)
(-3309.13 -132.762 0)
(-3299.14 -58.2122 0)
(-1773.05 -11.363 0)
(-430.763 -0.206745 0)
(-57.5069 0.563189 0)
(572.3 0.300303 0)
(2035.42 -0.313667 0)
(2455.19 0.303156 0)
(1505.19 3.50971 0)
(926.178 4.27965 0)
(770.478 3.80457 0)
(675.584 1.90763 0)
(637.059 -2.34644 0)
(751.716 -4.30704 0)
(933.276 -5.28579 0)
(983.968 -7.73128 0)
(1049.98 -8.39396 0)
(1887.1 8334.23 0)
(735.779 6664.79 0)
(-106.613 4350.42 0)
(-361.164 3712.61 0)
(-596.68 3509.93 0)
(-819.379 3452.16 0)
(-910.166 3394.12 0)
(-1154.35 3156.71 0)
(-1294.84 2893.44 0)
(-540.347 2226.79 0)
(1180.63 2123.67 0)
(4044.83 2153.26 0)
(3613.23 2264.3 0)
(542.164 1773.18 0)
(-575.787 1422.16 0)
(-802.877 1063.76 0)
(-571.81 941.171 0)
(-287.485 984.855 0)
(-84.7074 857.824 0)
(-173.623 480.879 0)
(-756.175 116.106 0)
(-1549.22 -133.16 0)
(-2396.16 -195.348 0)
(-3310.55 -185.859 0)
(-3275.67 -134.543 0)
(-1753.04 -41.3871 0)
(-426.071 -1.39475 0)
(-57.3076 1.33801 0)
(572.175 0.836895 0)
(2035.46 -0.830965 0)
(2455.9 0.744885 0)
(1505.9 6.49272 0)
(926.233 7.68013 0)
(770.046 6.00307 0)
(674.372 2.45249 0)
(635.701 -3.47694 0)
(750.579 -8.25668 0)
(931.541 -11.6497 0)
(982.438 -18.2348 0)
(1053.61 -18.4566 0)
(-1229.7 7846.69 0)
(-1295.71 5177.24 0)
(-1048.49 3607 0)
(-789.615 2711.56 0)
(-824.271 2204.29 0)
(-859.202 1975.23 0)
(-846.753 2074.61 0)
(-1145.26 2104.74 0)
(-1455.11 2198.6 0)
(-759.789 2128.39 0)
(1182.71 2077.84 0)
(4049.02 2491.76 0)
(3369.67 1924.02 0)
(260.639 1406.96 0)
(-768.241 1054.59 0)
(-862.802 457.615 0)
(-468.648 244.004 0)
(-252.463 240.718 0)
(-309.178 192.469 0)
(-539.647 25.0366 0)
(-1046.94 -162.102 0)
(-1683.58 -304.159 0)
(-2392.8 -329.423 0)
(-3269.35 -289.782 0)
(-3235.67 -225.308 0)
(-1712.67 -72.1726 0)
(-409.388 -2.15001 0)
(-56.3376 2.53965 0)
(571.085 1.64805 0)
(2035.31 -2.10134 0)
(2458.97 1.22261 0)
(1508.71 11.1388 0)
(925.809 13.602 0)
(767.697 10.9428 0)
(671.038 5.7686 0)
(631.91 -1.47622 0)
(747.904 -9.63392 0)
(929.024 -14.9802 0)
(981.467 -20.8147 0)
(1056.9 -17.67 0)
(-2059.22 2704.97 0)
(-2260.39 2782.55 0)
(-1977.57 2728.32 0)
(-1483.12 2360.81 0)
(-1184.19 1935.55 0)
(-922.985 1670.53 0)
(-819.368 1401.42 0)
(-1039.75 1183.04 0)
(-1186.12 1292.89 0)
(-539.045 1490.24 0)
(1529.66 1638.6 0)
(3894.36 2357.33 0)
(2698.49 1301.31 0)
(-144.689 910.993 0)
(-1387.41 432.263 0)
(-1551.85 -184.566 0)
(-836.14 -407.539 0)
(-355.926 -535.143 0)
(-172.177 -556.734 0)
(-319.027 -489.724 0)
(-917.485 -470.594 0)
(-1638.41 -459.059 0)
(-2384.1 -450.223 0)
(-3232.31 -475.225 0)
(-3087.42 -380.143 0)
(-1559.64 -104.695 0)
(-363.021 -1.31244 0)
(-54.1679 4.93089 0)
(568.287 3.67429 0)
(2035.14 -2.49347 0)
(2467.02 1.40309 0)
(1516.33 16.3974 0)
(926.271 21.4712 0)
(763.757 19.3564 0)
(664.193 13.4853 0)
(622.892 4.65093 0)
(739.001 -5.85688 0)
(922.116 -16.1912 0)
(980.367 -21.6851 0)
(1073.64 -16.1255 0)
(-1427.44 320.856 0)
(-1273.21 575.604 0)
(-1454.89 996.734 0)
(-1553.55 1128.29 0)
(-1489.45 1034.78 0)
(-1373.91 898.203 0)
(-1316.51 500.006 0)
(-1249.85 111.237 0)
(-1159.09 550.943 0)
(-426.653 1065.86 0)
(2018.27 1384.62 0)
(3723.99 1546.52 0)
(1975.93 201.296 0)
(-576.803 -120.013 0)
(-1823.96 -463.33 0)
(-1672.07 -429.303 0)
(-806.477 -173.666 0)
(-396.233 -176.672 0)
(-265.411 -230.321 0)
(-456.639 -355.46 0)
(-1017.39 -515.769 0)
(-1663.95 -576.32 0)
(-2408.38 -594.041 0)
(-3201.82 -635.9 0)
(-2878.61 -476.516 0)
(-1347.62 -113.905 0)
(-303.749 2.4004 0)
(-51.5322 9.08416 0)
(563.93 7.61972 0)
(2033.12 0.401133 0)
(2477.17 4.54314 0)
(1528.05 23.4787 0)
(928.66 30.3991 0)
(760.002 28.3607 0)
(656.867 22.077 0)
(613.272 13.1422 0)
(727.82 2.12026 0)
(913.772 -11.7769 0)
(981.531 -17.119 0)
(1081.94 -10.311 0)
(-1827.18 -66.4109 0)
(-1609.09 -232.392 0)
(-1444.98 -269.187 0)
(-1446.46 -219.593 0)
(-1405.91 -149.452 0)
(-1438.31 -73.2788 0)
(-1577.72 -270.109 0)
(-990.663 -308.588 0)
(-266.21 221.706 0)
(264.316 1008.12 0)
(1992.85 1727.85 0)
(2754.06 955.018 0)
(1092.56 -482.723 0)
(-785.146 -856.333 0)
(-1685.46 -1146.64 0)
(-1272.72 -653.172 0)
(-592.695 -349.984 0)
(-410.521 -340.697 0)
(-344.464 -336.721 0)
(-594.095 -473.295 0)
(-1130.31 -648.562 0)
(-1713.83 -724.154 0)
(-2441.51 -759.857 0)
(-3119.05 -788.662 0)
(-2584.41 -521.014 0)
(-1098.13 -101.635 0)
(-244.504 7.03236 0)
(-49.1383 12.5658 0)
(559.919 10.7163 0)
(2032.17 1.33144 0)
(2489.25 1.58757 0)
(1541.24 20.4746 0)
(930.975 27.3594 0)
(755.737 25.1781 0)
(649.528 20.3651 0)
(603.661 13.8682 0)
(714.988 4.30123 0)
(903.576 -10.973 0)
(981.779 -15.7766 0)
(1081.71 -9.42854 0)
(-1490.69 -237.945 0)
(-1468.61 -17.6713 0)
(-1442.55 50.8619 0)
(-1438.17 82.2879 0)
(-1348.46 158.341 0)
(-1490.18 146.2 0)
(-1543.26 124.752 0)
(-775.916 639.211 0)
(109.736 752.191 0)
(1024.73 962.016 0)
(1967.1 1130.52 0)
(1593.8 250.686 0)
(230.449 -757.614 0)
(-1216.58 -1350.7 0)
(-1628.19 -1358.93 0)
(-904.375 -606.56 0)
(-505.365 -487.998 0)
(-383.453 -427.276 0)
(-393.187 -430.682 0)
(-757.141 -616.626 0)
(-1259.12 -790.466 0)
(-1771.2 -852.802 0)
(-2470.54 -897.501 0)
(-2971.66 -900.097 0)
(-2216.57 -510.198 0)
(-838.774 -80.8679 0)
(-193.701 6.83557 0)
(-47.9822 10.0723 0)
(553.104 8.22455 0)
(2024.32 -0.937565 0)
(2495.62 -5.30076 0)
(1552.88 8.98407 0)
(933.193 13.5578 0)
(753.262 10.3995 0)
(645.969 7.71798 0)
(597.792 5.16873 0)
(703.882 0.586959 0)
(894.424 -12.4734 0)
(983.019 -15.8362 0)
(1082.64 -9.56956 0)
(-1331.13 -451.719 0)
(-1330.79 -326.295 0)
(-1348.66 -238.458 0)
(-1342.89 -173.541 0)
(-1344.32 -97.6387 0)
(-1470.68 -65.6508 0)
(-1102.63 244.07 0)
(-386.04 675.681 0)
(44.8567 819.223 0)
(628.884 682.523 0)
(1307.39 71.6079 0)
(934.591 -879.159 0)
(-450.599 -1701.8 0)
(-1364.6 -2150.55 0)
(-968.371 -1224.56 0)
(-433.46 -705.055 0)
(-419.931 -620.157 0)
(-355.289 -484.333 0)
(-526.929 -586.876 0)
(-940.796 -801.29 0)
(-1357.9 -925.889 0)
(-1816.98 -961.084 0)
(-2487.09 -1020.6 0)
(-2745.84 -956.495 0)
(-1794.97 -447.596 0)
(-599.902 -63.1793 0)
(-156.871 -3.27168 0)
(-47.7999 -2.09973 0)
(549.31 -4.23022 0)
(2019.14 -17.138 0)
(2498.81 -23.7948 0)
(1559.42 -2.3019 0)
(932.339 7.70149 0)
(750.11 3.0732 0)
(644.487 -4.08187 0)
(596.789 -7.2787 0)
(697.988 -7.56285 0)
(887.75 -14.405 0)
(984.578 -15.4706 0)
(1082.82 -9.51882 0)
(-1265.85 -745.295 0)
(-1263.11 -685.355 0)
(-1295.35 -620.102 0)
(-1302.47 -530.043 0)
(-1244.49 -403.583 0)
(-1160.89 -219.923 0)
(-828.889 127.222 0)
(-221.677 180.348 0)
(116.329 112.579 0)
(304.298 -62.7958 0)
(462.209 -540.607 0)
(-115.126 -1583.8 0)
(-994.71 -2301.19 0)
(-756.694 -1770.02 0)
(-235.256 -988.338 0)
(-321.949 -870.013 0)
(-292.67 -655.588 0)
(-351.382 -619.886 0)
(-698.618 -807.946 0)
(-1083.83 -981.32 0)
(-1413.11 -1034.85 0)
(-1862.47 -1042.67 0)
(-2466.12 -1091.7 0)
(-2419.49 -907.336 0)
(-1355.73 -315.751 0)
(-410.607 -15.0026 0)
(-134.843 21.068 0)
(-48.9059 23.4821 0)
(538.613 24.0069 0)
(2005.47 18.0625 0)
(2509.92 38.745 0)
(1583.24 92.3943 0)
(938.372 120.754 0)
(741.907 116.338 0)
(635.993 95.1035 0)
(594.438 52.7407 0)
(697.015 11.3934 0)
(886.804 -11.2926 0)
(987.727 -12.9829 0)
(1085.16 -9.16718 0)
(-1235.16 -1213.45 0)
(-1210.15 -1125.16 0)
(-1198.99 -1052.15 0)
(-1134.25 -962.252 0)
(-1045.48 -864.577 0)
(-959.174 -725.241 0)
(-716.919 -513.976 0)
(-400.15 -480.654 0)
(-189.446 -741.126 0)
(-0.550205 -919.054 0)
(-158.309 -1375.29 0)
(-761.974 -2111.82 0)
(-630.043 -1978.98 0)
(-99.4831 -1159.13 0)
(-101.097 -949.716 0)
(-112.809 -776.626 0)
(-178.899 -659.726 0)
(-502.108 -799.265 0)
(-875.22 -957.911 0)
(-1159.45 -980.883 0)
(-1417.02 -922.087 0)
(-1871.76 -920.182 0)
(-2356.67 -934.101 0)
(-1998.1 -638.487 0)
(-935.081 -64.4775 0)
(-275.331 146.436 0)
(-119.785 170.017 0)
(-44.9678 178.401 0)
(544.087 190.775 0)
(2033.34 254.381 0)
(2570.44 442.588 0)
(1638.44 589.583 0)
(955.412 607.266 0)
(725.392 517.543 0)
(583.203 395.264 0)
(516.123 275.176 0)
(636.283 165.899 0)
(864.26 56.6844 0)
(986.626 2.90165 0)
(1080.36 -10.5374 0)
(-1119.06 -1721.72 0)
(-1107.67 -1623.06 0)
(-1138.37 -1604.29 0)
(-1121.72 -1567.93 0)
(-1016.1 -1462.28 0)
(-823.041 -1252.56 0)
(-593.196 -1033.21 0)
(-440.568 -1032.42 0)
(-306.129 -1202.57 0)
(-306.802 -1458.71 0)
(-687.182 -1927.36 0)
(-696.869 -1907.68 0)
(-76.6672 -1052.08 0)
(235.144 -756.293 0)
(133.341 -731.64 0)
(-42.5043 -646.932 0)
(-314.485 -707.297 0)
(-638.723 -745.461 0)
(-873.631 -668.133 0)
(-1049.3 -482.926 0)
(-1354.61 -268.464 0)
(-1874.05 -246.479 0)
(-2194.67 -253.788 0)
(-1581.49 320.469 0)
(-599.354 864.811 0)
(-184.64 1015.98 0)
(-104.041 1048.57 0)
(-28.9028 1076.18 0)
(611.831 1138.34 0)
(2248.13 1509.82 0)
(2832.93 1987.67 0)
(1741.93 2074.8 0)
(868.952 1945.12 0)
(537.614 1626.29 0)
(402.439 1271.78 0)
(373.413 900.952 0)
(486.469 548.618 0)
(729.734 286.205 0)
(922.95 94.4907 0)
(1060.91 -8.88386 0)
(-1045.19 -1999.55 0)
(-1096.99 -1985.94 0)
(-1145.87 -1946.33 0)
(-997.399 -1795.44 0)
(-741.567 -1580.35 0)
(-545.707 -1392.81 0)
(-504.789 -1385.17 0)
(-563.357 -1529.52 0)
(-600.229 -1589.68 0)
(-698.98 -1648.74 0)
(-590.961 -1589.35 0)
(81.4802 -934.636 0)
(479.479 -547.314 0)
(209.299 -526.817 0)
(4.28795 -411.749 0)
(-89.3509 -245.935 0)
(-273.845 -53.3521 0)
(-464.368 251.398 0)
(-622.232 691.641 0)
(-774.31 1069.32 0)
(-1189.18 1158.32 0)
(-1857.62 1032.94 0)
(-1810.34 1182.92 0)
(-920.182 1876.38 0)
(-264.862 2256.69 0)
(-98.2496 2328.11 0)
(-61.7749 2334.91 0)
(41.5324 2352.87 0)
(961.956 2469.33 0)
(2851.79 3020.91 0)
(3114.89 3211.28 0)
(1597.44 2961.93 0)
(523.21 2752.99 0)
(76.5327 2447.17 0)
(-115.761 2165.57 0)
(-180.738 1781.91 0)
(43.8895 1256.85 0)
(426.647 749.382 0)
(702.268 328.69 0)
(934.982 -6.86922 0)
(-973.319 -1899.37 0)
(-1056.39 -2011.37 0)
(-954.791 -1949.37 0)
(-769.041 -1810 0)
(-628.113 -1799.95 0)
(-634.965 -1906.1 0)
(-724.934 -1918.92 0)
(-637.637 -1654.56 0)
(-421.018 -1315.73 0)
(-306.485 -966.238 0)
(0.958253 -442.07 0)
(307.275 -12.9451 0)
(316.322 60.1474 0)
(365.779 411.468 0)
(404.009 1041.36 0)
(302.86 1586.35 0)
(164.763 1997.83 0)
(79.1792 2249.72 0)
(-85.4477 2341.2 0)
(-599.595 2169.25 0)
(-1389.68 1645.73 0)
(-1850.34 1270.67 0)
(-1381.89 1683.46 0)
(-546.763 2200.72 0)
(-164.051 2326.22 0)
(-109.263 2314.57 0)
(-80.1854 2280.81 0)
(100.622 2275.17 0)
(1255.58 2374.94 0)
(2963.1 2613.01 0)
(2776.09 2296.6 0)
(1300.3 1939.13 0)
(372.917 1845.82 0)
(-28.4517 1774.49 0)
(-238.629 1811.28 0)
(-502.255 1828.71 0)
(-508.517 1641.18 0)
(-164.679 1214.53 0)
(194.199 674.91 0)
(604.712 18.0582 0)
(-971.551 -1612.05 0)
(-1145.16 -1578.6 0)
(-951.827 -1437.86 0)
(-853.418 -1177.35 0)
(-834.17 -924.493 0)
(-660.343 -604.511 0)
(-262.393 -276.882 0)
(17.8959 -6.48226 0)
(63.058 270.145 0)
(142.911 703.672 0)
(327.668 1407.9 0)
(565.435 2054.9 0)
(888.459 2705.13 0)
(1154.84 3153.4 0)
(1136.44 3266.7 0)
(832.333 3135.82 0)
(365.406 2837.13 0)
(-133.479 2374.61 0)
(-699.778 1676.98 0)
(-1444.49 857.99 0)
(-2055.07 226.013 0)
(-1821.26 319.81 0)
(-914.111 997.985 0)
(-300.792 1341.65 0)
(-155.154 1375.7 0)
(-142.011 1358.03 0)
(-99.7448 1337.95 0)
(132.241 1345.31 0)
(1287.51 1386.04 0)
(2776.29 1258.6 0)
(2465.51 926.934 0)
(1163.06 787.421 0)
(364.552 825.007 0)
(43.2499 868.123 0)
(-63.5117 969.796 0)
(-344.656 1122.94 0)
(-547.96 1205.48 0)
(-504.482 1097.67 0)
(-450.692 739.944 0)
(-68.4133 46.9511 0)
(-999.531 -790.931 0)
(-888.532 -164.757 0)
(-568.137 480.839 0)
(-274.343 1202.81 0)
(-76.1006 2007.9 0)
(-10.9032 2861.74 0)
(-148.652 3561.33 0)
(-110.502 4001.81 0)
(263.312 4293.23 0)
(789.9 4412.95 0)
(1303.05 4419.52 0)
(1557.33 4366.54 0)
(1374.87 4142.29 0)
(906.928 3571.71 0)
(387.064 2729.53 0)
(-111.082 1773.16 0)
(-568.759 962.096 0)
(-1038.78 337.048 0)
(-1546.92 -309.629 0)
(-1997.8 -848.505 0)
(-1908.29 -715.072 0)
(-1106.44 99.7819 0)
(-397.212 714.013 0)
(-182.781 862.257 0)
(-148.265 875.032 0)
(-145.645 874.885 0)
(-92.4431 875.877 0)
(146.966 887.62 0)
(1172.02 874.409 0)
(2520.69 533.521 0)
(2322.05 225.495 0)
(1202.09 236.84 0)
(450.684 335.89 0)
(111.072 402.168 0)
(6.91954 434.966 0)
(-275.145 500.948 0)
(-532.861 561.753 0)
(-613.284 510.898 0)
(-818.316 355.706 0)
(-744.946 -40.6636 0)
(309.543 212.403 0)
(80.3617 1191.01 0)
(366.015 2178.75 0)
(618.113 2928.65 0)
(764.431 3579.75 0)
(836.599 4112.68 0)
(836.219 4702.41 0)
(723.181 5393.64 0)
(459.247 5634.18 0)
(264.61 5270.5 0)
(282.943 4368.93 0)
(298.289 3170.8 0)
(122.537 2012.45 0)
(-206.558 1047.11 0)
(-596.71 302.442 0)
(-870.829 -237.485 0)
(-1018.48 -668.283 0)
(-1358.96 -1040.18 0)
(-1842.22 -1286.2 0)
(-1835.19 -1092.62 0)
(-1141.27 -310.952 0)
(-444.144 416.404 0)
(-179.363 656.171 0)
(-145.628 696.913 0)
(-142.985 701.299 0)
(-141.197 706.323 0)
(-87.4725 715.179 0)
(130.827 709.997 0)
(946.292 677.132 0)
(2150.98 229.155 0)
(2179.62 -98.2271 0)
(1269.44 -24.3546 0)
(523.869 77.7018 0)
(138.723 120.011 0)
(31.6759 129.034 0)
(-222.48 155.744 0)
(-538.372 190.099 0)
(-703.037 106.064 0)
(-982.196 -43.3585 0)
(-1046.55 -183.064 0)
(1743.18 551.869 0)
(1006.31 1105.42 0)
(1106.32 1705.71 0)
(1075.71 1979.01 0)
(1064.87 2142.78 0)
(1070.93 2202.53 0)
(1085.73 2302.58 0)
(787.39 2437.9 0)
(144.652 2380.16 0)
(-429.344 2125.23 0)
(-720.302 1590.75 0)
(-713.466 759.947 0)
(-671.584 -22.4646 0)
(-740.895 -579.402 0)
(-850.822 -893.108 0)
(-1046.51 -1030.44 0)
(-1342.27 -1240.4 0)
(-1634.23 -1488.13 0)
(-1597.45 -1285.74 0)
(-1058.02 -531.183 0)
(-454.136 190.104 0)
(-174.487 492.178 0)
(-126.905 550.348 0)
(-139.293 558.471 0)
(-139.197 565.034 0)
(-132.27 577.939 0)
(-88.9023 595.031 0)
(110.303 582.116 0)
(708.661 540.821 0)
(1773.52 91.0777 0)
(2077.76 -308.542 0)
(1371.62 -202.714 0)
(589.8 -91.5154 0)
(160.538 -33.1395 0)
(41.353 -26.3835 0)
(-216.301 17.3065 0)
(-580.735 61.4131 0)
(-838.252 19.0083 0)
(-1096.93 -136.382 0)
(-968.074 -155.14 0)
(2378.76 85.3747 0)
(1192.24 131.48 0)
(1207.84 211.914 0)
(1039.29 189.857 0)
(979.82 188.516 0)
(990.586 181.926 0)
(1063.03 239.059 0)
(797.942 282.645 0)
(157.95 333.334 0)
(-496.088 284.516 0)
(-1032.7 7.99415 0)
(-1256.27 -464.768 0)
(-1168.11 -902.015 0)
(-1045.54 -1153.17 0)
(-1031.34 -1327.29 0)
(-1205.5 -1497.04 0)
(-1459.53 -1561.78 0)
(-1402.65 -1289.26 0)
(-920.073 -631.88 0)
(-413.012 17.5916 0)
(-155.123 356.143 0)
(-96.9997 448.163 0)
(-115.48 466.558 0)
(-131.477 479.201 0)
(-124.225 499.218 0)
(-112.29 524.287 0)
(-83.4473 551.556 0)
(78.5884 546.575 0)
(473.11 472.958 0)
(1332.5 105.758 0)
(1896.51 -443.808 0)
(1478.57 -465.438 0)
(687.277 -370.809 0)
(201.487 -275.228 0)
(80.2875 -286.575 0)
(-137.876 -224.003 0)
(-536.733 -128.875 0)
(-893.639 -81.1918 0)
(-1150.01 -174.168 0)
(-944.435 -107.587 0)
(1813.52 -452.638 0)
(1128.25 -697.521 0)
(1162.58 -779.762 0)
(1053.17 -835.427 0)
(1057.23 -796.426 0)
(1119.63 -742.993 0)
(1182.79 -653.942 0)
(878.237 -701.735 0)
(146.455 -746.37 0)
(-742.853 -899.472 0)
(-1442.34 -1255.47 0)
(-1590.38 -1495.75 0)
(-1334.96 -1518.03 0)
(-1150.71 -1479.59 0)
(-1182.18 -1507.53 0)
(-1272.47 -1490.64 0)
(-1142.05 -1180.78 0)
(-738.139 -554.516 0)
(-338.119 29.0438 0)
(-105.926 358.345 0)
(-39.2223 485.92 0)
(-68.0872 521.593 0)
(-96.9946 543.874 0)
(-107.821 569.054 0)
(-95.7505 598.102 0)
(-81.8352 626.747 0)
(-67.4249 656.711 0)
(34.5626 666.061 0)
(283.873 567.059 0)
(890.094 342.996 0)
(1527.34 -292.555 0)
(1441.96 -566.708 0)
(773.093 -563.339 0)
(241.709 -520.002 0)
(90.7154 -582.934 0)
(-64.3351 -582.377 0)
(-443.117 -501.017 0)
(-881.899 -336.03 0)
(-1122.37 -252.189 0)
(-666.507 -212.959 0)
(908.53 243.28 0)
(877.012 -1018.5 0)
(1074.95 -1060.23 0)
(1023.23 -1235.62 0)
(1068.89 -1319.87 0)
(1127.89 -1385.38 0)
(1102.79 -1445.8 0)
(708.875 -1679.67 0)
(-32.5972 -1912.43 0)
(-986.678 -2134.36 0)
(-1607.29 -2252.94 0)
(-1509.28 -2013 0)
(-1152.54 -1663.29 0)
(-1035.42 -1396.42 0)
(-1041.99 -1149.79 0)
(-890.628 -779.811 0)
(-557.444 -259.233 0)
(-236.823 213.494 0)
(-40.4076 500.372 0)
(27.2504 635.057 0)
(2.18924 672.617 0)
(-41.1535 699.259 0)
(-69.7455 732.018 0)
(-79.2205 768.019 0)
(-68.6298 804.402 0)
(-55.8122 832.849 0)
(-45.5626 861.445 0)
(-7.80404 879.652 0)
(161.793 813.957 0)
(504.143 635.978 0)
(1019.89 102.734 0)
(1217.63 -397.526 0)
(732.285 -609.898 0)
(182.604 -665.664 0)
(20.1807 -804.256 0)
(-58.9374 -891.06 0)
(-299.344 -907.499 0)
(-653.859 -677.489 0)
(-1031.42 -248.388 0)
(-170.904 -409.264 0)
(-875.793 16424.7 0)
(-127.862 -134.371 0)
(953.358 -903.401 0)
(802.972 -1331.15 0)
(912.905 -1533.82 0)
(998.276 -1810.32 0)
(899.206 -2272.49 0)
(428.577 -2821.43 0)
(-291.702 -3269.13 0)
(-1070.98 -3370.79 0)
(-1325.39 -2872.89 0)
(-1022.18 -2111.71 0)
(-740.801 -1514.71 0)
(-655.881 -1052.41 0)
(-587.995 -541.374 0)
(-414.299 0.490702 0)
(-184.865 414.838 0)
(-6.15556 633.056 0)
(68.1151 718.61 0)
(60.0553 729.958 0)
(22.6452 742.487 0)
(-10.8461 774.517 0)
(-30.7353 822.092 0)
(-38.0691 874.067 0)
(-33.278 923.267 0)
(-26.8665 959.886 0)
(-22.3241 991.392 0)
(-11.1984 1013.16 0)
(49.0606 1003.42 0)
(204.733 849.547 0)
(531.415 483.449 0)
(755.243 -199.925 0)
(514.705 -735.037 0)
(54.4189 -953.234 0)
(-126.484 -1076.14 0)
(-163.824 -1145.93 0)
(-237.312 -1134.62 0)
(-246.756 -1037.82 0)
(-863.895 -843.766 0)
(1377.96 943.398 0)
(8174.98 -8829.14 0)
(-15821 3004.76 0)
(-78.3102 -391.061 0)
(415.74 -1094.58 0)
(607.143 -2199.02 0)
(416.083 -3269.62 0)
(128.45 -4364.23 0)
(-251.527 -4944.49 0)
(-561.983 -4846.56 0)
(-604.851 -3891.68 0)
(-393.993 -2520.51 0)
(-200.479 -1462.4 0)
(-131.754 -748.809 0)
(-97.4824 -152.335 0)
(-27.379 371.554 0)
(30.8122 741.009 0)
(52.1187 930.128 0)
(55.9028 968.098 0)
(52.9714 936.382 0)
(50.2583 902.416 0)
(45.1274 897.701 0)
(35.5568 926.142 0)
(26.1844 974.828 0)
(18.2755 1023.16 0)
(14.0684 1064.58 0)
(9.83551 1088.69 0)
(5.77162 1110.91 0)
(3.78218 1121.4 0)
(4.13185 1121.57 0)
(3.08489 1045.36 0)
(8.57665 823.408 0)
(43.4567 238.371 0)
(6.36911 -506.874 0)
(-146.096 -1001.43 0)
(-165.509 -976.025 0)
(-115.289 -972.65 0)
(-195.166 -702.095 0)
(-373.584 -216.59 0)
(877.76 1342.79 0)
(4172.99 4374.64 0)
(8174.98 8829.14 0)
(-15821 -3004.76 0)
(-78.3102 391.061 0)
(415.74 1094.58 0)
(607.143 2199.02 0)
(416.083 3269.62 0)
(128.45 4364.23 0)
(-251.527 4944.49 0)
(-561.983 4846.56 0)
(-604.851 3891.68 0)
(-393.993 2520.51 0)
(-200.479 1462.4 0)
(-131.754 748.809 0)
(-97.4824 152.335 0)
(-27.379 -371.554 0)
(30.8122 -741.009 0)
(52.1187 -930.128 0)
(55.9028 -968.098 0)
(52.9714 -936.382 0)
(50.2583 -902.416 0)
(45.1274 -897.701 0)
(35.5568 -926.142 0)
(26.1844 -974.828 0)
(18.2755 -1023.16 0)
(14.0684 -1064.58 0)
(9.83551 -1088.69 0)
(5.77162 -1110.91 0)
(3.78218 -1121.4 0)
(4.13185 -1121.57 0)
(3.08489 -1045.36 0)
(8.57665 -823.408 0)
(43.4567 -238.371 0)
(6.36911 506.874 0)
(-146.096 1001.43 0)
(-165.509 976.025 0)
(-115.289 972.65 0)
(-195.166 702.095 0)
(-373.584 216.59 0)
(877.76 -1342.79 0)
(4172.99 -4374.64 0)
(-875.793 -16424.7 0)
(-127.862 134.371 0)
(953.358 903.401 0)
(802.972 1331.15 0)
(912.905 1533.82 0)
(998.276 1810.32 0)
(899.206 2272.49 0)
(428.577 2821.43 0)
(-291.702 3269.13 0)
(-1070.98 3370.79 0)
(-1325.39 2872.89 0)
(-1022.18 2111.71 0)
(-740.801 1514.71 0)
(-655.881 1052.41 0)
(-587.995 541.374 0)
(-414.299 -0.490702 0)
(-184.865 -414.838 0)
(-6.15556 -633.056 0)
(68.1151 -718.61 0)
(60.0553 -729.958 0)
(22.6452 -742.487 0)
(-10.8461 -774.517 0)
(-30.7353 -822.092 0)
(-38.0691 -874.067 0)
(-33.278 -923.267 0)
(-26.8665 -959.886 0)
(-22.3241 -991.392 0)
(-11.1984 -1013.16 0)
(49.0606 -1003.42 0)
(204.733 -849.547 0)
(531.415 -483.449 0)
(755.243 199.925 0)
(514.705 735.037 0)
(54.4189 953.234 0)
(-126.484 1076.14 0)
(-163.824 1145.93 0)
(-237.312 1134.62 0)
(-246.756 1037.82 0)
(-863.895 843.766 0)
(1377.96 -943.398 0)
(908.53 -243.28 0)
(877.012 1018.5 0)
(1074.95 1060.23 0)
(1023.23 1235.62 0)
(1068.89 1319.87 0)
(1127.89 1385.38 0)
(1102.79 1445.8 0)
(708.875 1679.67 0)
(-32.5972 1912.43 0)
(-986.678 2134.36 0)
(-1607.29 2252.94 0)
(-1509.28 2013 0)
(-1152.54 1663.29 0)
(-1035.42 1396.42 0)
(-1041.99 1149.79 0)
(-890.628 779.811 0)
(-557.444 259.233 0)
(-236.823 -213.494 0)
(-40.4076 -500.372 0)
(27.2504 -635.057 0)
(2.18924 -672.617 0)
(-41.1535 -699.259 0)
(-69.7455 -732.018 0)
(-79.2205 -768.019 0)
(-68.6298 -804.402 0)
(-55.8122 -832.849 0)
(-45.5626 -861.445 0)
(-7.80404 -879.652 0)
(161.793 -813.957 0)
(504.143 -635.978 0)
(1019.89 -102.734 0)
(1217.63 397.526 0)
(732.285 609.898 0)
(182.604 665.664 0)
(20.1807 804.256 0)
(-58.9374 891.06 0)
(-299.344 907.499 0)
(-653.859 677.489 0)
(-1031.42 248.388 0)
(-170.904 409.264 0)
(1813.52 452.638 0)
(1128.25 697.521 0)
(1162.58 779.762 0)
(1053.17 835.427 0)
(1057.23 796.426 0)
(1119.63 742.993 0)
(1182.79 653.942 0)
(878.237 701.735 0)
(146.455 746.37 0)
(-742.853 899.472 0)
(-1442.34 1255.47 0)
(-1590.38 1495.75 0)
(-1334.96 1518.03 0)
(-1150.71 1479.59 0)
(-1182.18 1507.53 0)
(-1272.47 1490.64 0)
(-1142.05 1180.78 0)
(-738.139 554.516 0)
(-338.119 -29.0438 0)
(-105.926 -358.345 0)
(-39.2223 -485.92 0)
(-68.0872 -521.593 0)
(-96.9946 -543.874 0)
(-107.821 -569.054 0)
(-95.7505 -598.102 0)
(-81.8352 -626.747 0)
(-67.4249 -656.711 0)
(34.5626 -666.061 0)
(283.873 -567.059 0)
(890.094 -342.996 0)
(1527.34 292.555 0)
(1441.96 566.708 0)
(773.093 563.339 0)
(241.709 520.002 0)
(90.7154 582.934 0)
(-64.3351 582.377 0)
(-443.117 501.017 0)
(-881.899 336.03 0)
(-1122.37 252.189 0)
(-666.507 212.959 0)
(2378.76 -85.3747 0)
(1192.24 -131.48 0)
(1207.84 -211.914 0)
(1039.29 -189.857 0)
(979.82 -188.516 0)
(990.586 -181.926 0)
(1063.03 -239.059 0)
(797.942 -282.645 0)
(157.95 -333.334 0)
(-496.088 -284.516 0)
(-1032.7 -7.99415 0)
(-1256.27 464.768 0)
(-1168.11 902.015 0)
(-1045.54 1153.17 0)
(-1031.34 1327.29 0)
(-1205.5 1497.04 0)
(-1459.53 1561.78 0)
(-1402.65 1289.26 0)
(-920.073 631.88 0)
(-413.012 -17.5916 0)
(-155.123 -356.143 0)
(-96.9997 -448.163 0)
(-115.48 -466.558 0)
(-131.477 -479.201 0)
(-124.225 -499.218 0)
(-112.29 -524.287 0)
(-83.4473 -551.556 0)
(78.5884 -546.575 0)
(473.11 -472.958 0)
(1332.5 -105.758 0)
(1896.51 443.808 0)
(1478.57 465.438 0)
(687.277 370.809 0)
(201.487 275.228 0)
(80.2875 286.575 0)
(-137.876 224.003 0)
(-536.733 128.875 0)
(-893.639 81.1918 0)
(-1150.01 174.168 0)
(-944.435 107.587 0)
(1743.18 -551.869 0)
(1006.31 -1105.42 0)
(1106.32 -1705.71 0)
(1075.71 -1979.01 0)
(1064.87 -2142.78 0)
(1070.93 -2202.53 0)
(1085.73 -2302.58 0)
(787.39 -2437.9 0)
(144.652 -2380.16 0)
(-429.344 -2125.23 0)
(-720.302 -1590.75 0)
(-713.466 -759.947 0)
(-671.584 22.4646 0)
(-740.895 579.402 0)
(-850.822 893.108 0)
(-1046.51 1030.44 0)
(-1342.27 1240.4 0)
(-1634.23 1488.13 0)
(-1597.45 1285.74 0)
(-1058.02 531.183 0)
(-454.136 -190.104 0)
(-174.487 -492.178 0)
(-126.905 -550.348 0)
(-139.293 -558.471 0)
(-139.197 -565.034 0)
(-132.27 -577.939 0)
(-88.9023 -595.031 0)
(110.303 -582.116 0)
(708.661 -540.821 0)
(1773.52 -91.0777 0)
(2077.76 308.542 0)
(1371.62 202.714 0)
(589.8 91.5154 0)
(160.538 33.1395 0)
(41.353 26.3835 0)
(-216.301 -17.3065 0)
(-580.735 -61.4131 0)
(-838.252 -19.0083 0)
(-1096.93 136.382 0)
(-968.074 155.14 0)
(309.543 -212.403 0)
(80.3617 -1191.01 0)
(366.015 -2178.75 0)
(618.113 -2928.65 0)
(764.431 -3579.75 0)
(836.599 -4112.68 0)
(836.219 -4702.41 0)
(723.181 -5393.64 0)
(459.247 -5634.18 0)
(264.61 -5270.5 0)
(282.943 -4368.93 0)
(298.289 -3170.8 0)
(122.537 -2012.45 0)
(-206.558 -1047.11 0)
(-596.71 -302.442 0)
(-870.829 237.485 0)
(-1018.48 668.283 0)
(-1358.96 1040.18 0)
(-1842.22 1286.2 0)
(-1835.19 1092.62 0)
(-1141.27 310.952 0)
(-444.144 -416.404 0)
(-179.363 -656.171 0)
(-145.628 -696.913 0)
(-142.985 -701.299 0)
(-141.197 -706.323 0)
(-87.4725 -715.179 0)
(130.827 -709.997 0)
(946.292 -677.132 0)
(2150.98 -229.155 0)
(2179.62 98.2271 0)
(1269.44 24.3546 0)
(523.869 -77.7018 0)
(138.723 -120.011 0)
(31.6759 -129.034 0)
(-222.48 -155.744 0)
(-538.372 -190.099 0)
(-703.037 -106.064 0)
(-982.196 43.3585 0)
(-1046.55 183.064 0)
(-999.531 790.931 0)
(-888.532 164.757 0)
(-568.137 -480.839 0)
(-274.343 -1202.81 0)
(-76.1006 -2007.9 0)
(-10.9032 -2861.74 0)
(-148.652 -3561.33 0)
(-110.502 -4001.81 0)
(263.312 -4293.23 0)
(789.9 -4412.95 0)
(1303.05 -4419.52 0)
(1557.33 -4366.54 0)
(1374.87 -4142.29 0)
(906.928 -3571.71 0)
(387.064 -2729.53 0)
(-111.082 -1773.16 0)
(-568.759 -962.096 0)
(-1038.78 -337.048 0)
(-1546.92 309.629 0)
(-1997.8 848.505 0)
(-1908.29 715.072 0)
(-1106.44 -99.7819 0)
(-397.212 -714.013 0)
(-182.781 -862.257 0)
(-148.265 -875.032 0)
(-145.645 -874.885 0)
(-92.4431 -875.877 0)
(146.966 -887.62 0)
(1172.02 -874.409 0)
(2520.69 -533.521 0)
(2322.05 -225.495 0)
(1202.09 -236.84 0)
(450.684 -335.89 0)
(111.072 -402.168 0)
(6.91954 -434.966 0)
(-275.145 -500.948 0)
(-532.861 -561.753 0)
(-613.284 -510.898 0)
(-818.316 -355.706 0)
(-744.946 40.6636 0)
(-971.551 1612.05 0)
(-1145.16 1578.6 0)
(-951.827 1437.86 0)
(-853.418 1177.35 0)
(-834.17 924.493 0)
(-660.343 604.511 0)
(-262.393 276.882 0)
(17.8959 6.48226 0)
(63.058 -270.145 0)
(142.911 -703.672 0)
(327.668 -1407.9 0)
(565.435 -2054.9 0)
(888.459 -2705.13 0)
(1154.84 -3153.4 0)
(1136.44 -3266.7 0)
(832.333 -3135.82 0)
(365.406 -2837.13 0)
(-133.479 -2374.61 0)
(-699.778 -1676.98 0)
(-1444.49 -857.99 0)
(-2055.07 -226.013 0)
(-1821.26 -319.81 0)
(-914.111 -997.985 0)
(-300.792 -1341.65 0)
(-155.154 -1375.7 0)
(-142.011 -1358.03 0)
(-99.7448 -1337.95 0)
(132.241 -1345.31 0)
(1287.51 -1386.04 0)
(2776.29 -1258.6 0)
(2465.51 -926.934 0)
(1163.06 -787.421 0)
(364.552 -825.007 0)
(43.2499 -868.123 0)
(-63.5117 -969.796 0)
(-344.656 -1122.94 0)
(-547.96 -1205.48 0)
(-504.482 -1097.67 0)
(-450.692 -739.944 0)
(-68.4133 -46.9511 0)
(-973.319 1899.37 0)
(-1056.39 2011.37 0)
(-954.791 1949.37 0)
(-769.041 1810 0)
(-628.113 1799.95 0)
(-634.965 1906.1 0)
(-724.934 1918.92 0)
(-637.637 1654.56 0)
(-421.018 1315.73 0)
(-306.485 966.238 0)
(0.958253 442.07 0)
(307.275 12.9451 0)
(316.322 -60.1474 0)
(365.779 -411.468 0)
(404.009 -1041.36 0)
(302.86 -1586.35 0)
(164.763 -1997.83 0)
(79.1792 -2249.72 0)
(-85.4477 -2341.2 0)
(-599.595 -2169.25 0)
(-1389.68 -1645.73 0)
(-1850.34 -1270.67 0)
(-1381.89 -1683.46 0)
(-546.763 -2200.72 0)
(-164.051 -2326.22 0)
(-109.263 -2314.57 0)
(-80.1854 -2280.81 0)
(100.622 -2275.17 0)
(1255.58 -2374.94 0)
(2963.1 -2613.01 0)
(2776.09 -2296.6 0)
(1300.3 -1939.13 0)
(372.917 -1845.82 0)
(-28.4517 -1774.49 0)
(-238.629 -1811.28 0)
(-502.255 -1828.71 0)
(-508.517 -1641.18 0)
(-164.679 -1214.53 0)
(194.199 -674.91 0)
(604.712 -18.0582 0)
(-1045.19 1999.55 0)
(-1096.99 1985.94 0)
(-1145.87 1946.33 0)
(-997.399 1795.44 0)
(-741.567 1580.35 0)
(-545.707 1392.81 0)
(-504.789 1385.17 0)
(-563.357 1529.52 0)
(-600.229 1589.68 0)
(-698.98 1648.74 0)
(-590.961 1589.35 0)
(81.4802 934.636 0)
(479.479 547.314 0)
(209.299 526.817 0)
(4.28795 411.749 0)
(-89.3509 245.935 0)
(-273.845 53.3521 0)
(-464.368 -251.398 0)
(-622.232 -691.641 0)
(-774.31 -1069.32 0)
(-1189.18 -1158.32 0)
(-1857.62 -1032.94 0)
(-1810.34 -1182.92 0)
(-920.182 -1876.38 0)
(-264.862 -2256.69 0)
(-98.2496 -2328.11 0)
(-61.7749 -2334.91 0)
(41.5324 -2352.87 0)
(961.956 -2469.33 0)
(2851.79 -3020.91 0)
(3114.89 -3211.28 0)
(1597.44 -2961.93 0)
(523.21 -2752.99 0)
(76.5327 -2447.17 0)
(-115.761 -2165.57 0)
(-180.738 -1781.91 0)
(43.8895 -1256.85 0)
(426.647 -749.382 0)
(702.268 -328.69 0)
(934.982 6.86922 0)
(-1119.06 1721.72 0)
(-1107.67 1623.06 0)
(-1138.37 1604.29 0)
(-1121.72 1567.93 0)
(-1016.1 1462.28 0)
(-823.041 1252.56 0)
(-593.196 1033.21 0)
(-440.568 1032.42 0)
(-306.129 1202.57 0)
(-306.802 1458.71 0)
(-687.182 1927.36 0)
(-696.869 1907.68 0)
(-76.6672 1052.08 0)
(235.144 756.293 0)
(133.341 731.64 0)
(-42.5043 646.932 0)
(-314.485 707.297 0)
(-638.723 745.461 0)
(-873.631 668.133 0)
(-1049.3 482.926 0)
(-1354.61 268.464 0)
(-1874.05 246.479 0)
(-2194.67 253.788 0)
(-1581.49 -320.469 0)
(-599.354 -864.811 0)
(-184.64 -1015.98 0)
(-104.041 -1048.57 0)
(-28.9028 -1076.18 0)
(611.831 -1138.34 0)
(2248.13 -1509.82 0)
(2832.93 -1987.67 0)
(1741.93 -2074.8 0)
(868.952 -1945.12 0)
(537.614 -1626.29 0)
(402.439 -1271.78 0)
(373.413 -900.952 0)
(486.469 -548.618 0)
(729.734 -286.205 0)
(922.95 -94.4907 0)
(1060.91 8.88386 0)
(-1235.16 1213.45 0)
(-1210.15 1125.16 0)
(-1198.99 1052.15 0)
(-1134.25 962.252 0)
(-1045.48 864.577 0)
(-959.174 725.241 0)
(-716.919 513.976 0)
(-400.15 480.654 0)
(-189.446 741.126 0)
(-0.550205 919.054 0)
(-158.309 1375.29 0)
(-761.974 2111.82 0)
(-630.043 1978.98 0)
(-99.4831 1159.13 0)
(-101.097 949.716 0)
(-112.809 776.626 0)
(-178.899 659.726 0)
(-502.108 799.265 0)
(-875.22 957.911 0)
(-1159.45 980.883 0)
(-1417.02 922.087 0)
(-1871.76 920.182 0)
(-2356.67 934.101 0)
(-1998.1 638.487 0)
(-935.081 64.4775 0)
(-275.331 -146.436 0)
(-119.785 -170.017 0)
(-44.9678 -178.401 0)
(544.087 -190.775 0)
(2033.34 -254.381 0)
(2570.44 -442.588 0)
(1638.44 -589.583 0)
(955.412 -607.266 0)
(725.392 -517.543 0)
(583.203 -395.264 0)
(516.123 -275.176 0)
(636.283 -165.899 0)
(864.26 -56.6844 0)
(986.626 -2.90165 0)
(1080.36 10.5374 0)
(-1265.85 745.295 0)
(-1263.11 685.355 0)
(-1295.35 620.102 0)
(-1302.47 530.043 0)
(-1244.49 403.583 0)
(-1160.89 219.923 0)
(-828.889 -127.222 0)
(-221.677 -180.348 0)
(116.329 -112.579 0)
(304.298 62.7958 0)
(462.209 540.607 0)
(-115.126 1583.8 0)
(-994.71 2301.19 0)
(-756.694 1770.02 0)
(-235.256 988.338 0)
(-321.949 870.013 0)
(-292.67 655.588 0)
(-351.382 619.886 0)
(-698.618 807.946 0)
(-1083.83 981.32 0)
(-1413.11 1034.85 0)
(-1862.47 1042.67 0)
(-2466.12 1091.7 0)
(-2419.49 907.336 0)
(-1355.73 315.751 0)
(-410.607 15.0026 0)
(-134.843 -21.068 0)
(-48.9059 -23.4821 0)
(538.613 -24.0069 0)
(2005.47 -18.0625 0)
(2509.92 -38.745 0)
(1583.24 -92.3943 0)
(938.372 -120.754 0)
(741.907 -116.338 0)
(635.993 -95.1035 0)
(594.438 -52.7407 0)
(697.015 -11.3934 0)
(886.804 11.2926 0)
(987.727 12.9829 0)
(1085.16 9.16718 0)
(-1331.13 451.719 0)
(-1330.79 326.295 0)
(-1348.66 238.458 0)
(-1342.89 173.541 0)
(-1344.32 97.6387 0)
(-1470.68 65.6508 0)
(-1102.63 -244.07 0)
(-386.04 -675.681 0)
(44.8567 -819.223 0)
(628.884 -682.523 0)
(1307.39 -71.6079 0)
(934.591 879.159 0)
(-450.599 1701.8 0)
(-1364.6 2150.55 0)
(-968.371 1224.56 0)
(-433.46 705.055 0)
(-419.931 620.157 0)
(-355.289 484.333 0)
(-526.929 586.876 0)
(-940.796 801.29 0)
(-1357.9 925.889 0)
(-1816.98 961.084 0)
(-2487.09 1020.6 0)
(-2745.84 956.495 0)
(-1794.97 447.596 0)
(-599.902 63.1793 0)
(-156.871 3.27168 0)
(-47.7999 2.09973 0)
(549.31 4.23022 0)
(2019.14 17.138 0)
(2498.81 23.7948 0)
(1559.42 2.3019 0)
(932.339 -7.70149 0)
(750.11 -3.0732 0)
(644.487 4.08187 0)
(596.789 7.2787 0)
(697.988 7.56285 0)
(887.75 14.405 0)
(984.578 15.4706 0)
(1082.82 9.51882 0)
(-1490.69 237.945 0)
(-1468.61 17.6713 0)
(-1442.55 -50.8619 0)
(-1438.17 -82.2879 0)
(-1348.46 -158.341 0)
(-1490.18 -146.2 0)
(-1543.26 -124.752 0)
(-775.916 -639.211 0)
(109.736 -752.191 0)
(1024.73 -962.016 0)
(1967.1 -1130.52 0)
(1593.8 -250.686 0)
(230.449 757.614 0)
(-1216.58 1350.7 0)
(-1628.19 1358.93 0)
(-904.375 606.56 0)
(-505.365 487.998 0)
(-383.453 427.276 0)
(-393.187 430.682 0)
(-757.141 616.626 0)
(-1259.12 790.466 0)
(-1771.2 852.802 0)
(-2470.54 897.501 0)
(-2971.66 900.097 0)
(-2216.57 510.198 0)
(-838.774 80.8679 0)
(-193.701 -6.83557 0)
(-47.9822 -10.0723 0)
(553.104 -8.22455 0)
(2024.32 0.937565 0)
(2495.62 5.30076 0)
(1552.88 -8.98407 0)
(933.193 -13.5578 0)
(753.262 -10.3995 0)
(645.969 -7.71798 0)
(597.792 -5.16873 0)
(703.882 -0.586959 0)
(894.424 12.4734 0)
(983.019 15.8362 0)
(1082.64 9.56956 0)
(-1827.18 66.4109 0)
(-1609.09 232.392 0)
(-1444.98 269.187 0)
(-1446.46 219.593 0)
(-1405.91 149.452 0)
(-1438.31 73.2788 0)
(-1577.72 270.109 0)
(-990.663 308.588 0)
(-266.21 -221.706 0)
(264.316 -1008.12 0)
(1992.85 -1727.85 0)
(2754.06 -955.018 0)
(1092.56 482.723 0)
(-785.146 856.333 0)
(-1685.46 1146.64 0)
(-1272.72 653.172 0)
(-592.695 349.984 0)
(-410.521 340.697 0)
(-344.464 336.721 0)
(-594.095 473.295 0)
(-1130.31 648.562 0)
(-1713.83 724.154 0)
(-2441.51 759.857 0)
(-3119.05 788.662 0)
(-2584.41 521.014 0)
(-1098.13 101.635 0)
(-244.504 -7.03236 0)
(-49.1383 -12.5658 0)
(559.919 -10.7163 0)
(2032.17 -1.33144 0)
(2489.25 -1.58757 0)
(1541.24 -20.4746 0)
(930.975 -27.3594 0)
(755.737 -25.1781 0)
(649.528 -20.3651 0)
(603.661 -13.8682 0)
(714.988 -4.30123 0)
(903.576 10.973 0)
(981.779 15.7766 0)
(1081.71 9.42854 0)
(-1427.44 -320.856 0)
(-1273.21 -575.604 0)
(-1454.89 -996.734 0)
(-1553.55 -1128.29 0)
(-1489.45 -1034.78 0)
(-1373.91 -898.203 0)
(-1316.51 -500.006 0)
(-1249.85 -111.237 0)
(-1159.09 -550.943 0)
(-426.653 -1065.86 0)
(2018.27 -1384.62 0)
(3723.99 -1546.52 0)
(1975.93 -201.296 0)
(-576.803 120.013 0)
(-1823.96 463.33 0)
(-1672.07 429.303 0)
(-806.477 173.666 0)
(-396.233 176.672 0)
(-265.411 230.321 0)
(-456.639 355.46 0)
(-1017.39 515.769 0)
(-1663.95 576.32 0)
(-2408.38 594.041 0)
(-3201.82 635.9 0)
(-2878.61 476.516 0)
(-1347.62 113.905 0)
(-303.749 -2.4004 0)
(-51.5322 -9.08416 0)
(563.93 -7.61972 0)
(2033.12 -0.401133 0)
(2477.17 -4.54314 0)
(1528.05 -23.4787 0)
(928.66 -30.3991 0)
(760.002 -28.3607 0)
(656.867 -22.077 0)
(613.272 -13.1422 0)
(727.82 -2.12026 0)
(913.772 11.7769 0)
(981.531 17.119 0)
(1081.94 10.311 0)
(-2059.22 -2704.97 0)
(-2260.39 -2782.55 0)
(-1977.57 -2728.32 0)
(-1483.12 -2360.81 0)
(-1184.19 -1935.55 0)
(-922.985 -1670.53 0)
(-819.368 -1401.42 0)
(-1039.75 -1183.04 0)
(-1186.12 -1292.89 0)
(-539.045 -1490.24 0)
(1529.66 -1638.6 0)
(3894.36 -2357.33 0)
(2698.49 -1301.31 0)
(-144.689 -910.993 0)
(-1387.41 -432.263 0)
(-1551.85 184.566 0)
(-836.14 407.539 0)
(-355.926 535.143 0)
(-172.177 556.734 0)
(-319.027 489.724 0)
(-917.485 470.594 0)
(-1638.41 459.059 0)
(-2384.1 450.223 0)
(-3232.31 475.225 0)
(-3087.42 380.143 0)
(-1559.64 104.695 0)
(-363.021 1.31244 0)
(-54.1679 -4.93089 0)
(568.287 -3.67429 0)
(2035.14 2.49347 0)
(2467.02 -1.40309 0)
(1516.33 -16.3974 0)
(926.271 -21.4712 0)
(763.757 -19.3564 0)
(664.193 -13.4853 0)
(622.892 -4.65093 0)
(739.001 5.85688 0)
(922.116 16.1912 0)
(980.367 21.6851 0)
(1073.64 16.1255 0)
(-1229.7 -7846.69 0)
(-1295.71 -5177.24 0)
(-1048.49 -3607 0)
(-789.615 -2711.56 0)
(-824.271 -2204.29 0)
(-859.202 -1975.23 0)
(-846.753 -2074.61 0)
(-1145.26 -2104.74 0)
(-1455.11 -2198.6 0)
(-759.789 -2128.39 0)
(1182.71 -2077.84 0)
(4049.02 -2491.76 0)
(3369.67 -1924.02 0)
(260.639 -1406.96 0)
(-768.241 -1054.59 0)
(-862.802 -457.615 0)
(-468.648 -244.004 0)
(-252.463 -240.718 0)
(-309.178 -192.469 0)
(-539.647 -25.0366 0)
(-1046.94 162.102 0)
(-1683.58 304.159 0)
(-2392.8 329.423 0)
(-3269.35 289.782 0)
(-3235.67 225.308 0)
(-1712.67 72.1726 0)
(-409.388 2.15001 0)
(-56.3376 -2.53965 0)
(571.085 -1.64805 0)
(2035.31 2.10134 0)
(2458.97 -1.22261 0)
(1508.71 -11.1388 0)
(925.809 -13.602 0)
(767.697 -10.9428 0)
(671.038 -5.7686 0)
(631.91 1.47622 0)
(747.904 9.63392 0)
(929.024 14.9802 0)
(981.467 20.8147 0)
(1056.9 17.67 0)
)
;
boundaryField
{
inlet
{
type extrapolatedCalculated;
value nonuniform List<vector> 5((23847.5 -0.236933 0) (23846.5 -0.450877 0) (23845.7 4.44089e-09 0) (23846.5 0.450877 0) (23847.5 0.236933 0));
}
outlet
{
type extrapolatedCalculated;
value nonuniform List<vector>
165
(
(-1121.28 7846.69 0)
(-1868.5 2704.97 0)
(-1666.28 320.856 0)
(-1895.39 -66.4109 0)
(-1472.89 -237.945 0)
(-1327.81 -451.719 0)
(-1264.93 -745.295 0)
(-1251.39 -1213.45 0)
(-1141.51 -1721.72 0)
(-1061.6 -1999.55 0)
(-876.253 -1899.37 0)
(-698.478 -1612.05 0)
(-993.149 -790.931 0)
(656.901 212.403 0)
(2606.24 551.869 0)
(3728.5 85.3747 0)
(2658.06 -452.638 0)
(1259.99 243.28 0)
(-288.768 16424.7 0)
(47706.7 -8829.14 0)
(8174.98 -49507 0)
(-15821 5182.84 0)
(-78.3102 -60.2164 0)
(415.74 -874.629 0)
(607.143 -2872.45 0)
(416.083 -4590.11 0)
(128.45 -5994.54 0)
(-251.527 -6340.18 0)
(-561.983 -5547.66 0)
(-604.851 -3673.58 0)
(-393.993 -1863 0)
(-200.479 -748.13 0)
(-131.754 -25.0062 0)
(-97.4824 607.946 0)
(-27.379 1056.78 0)
(30.8122 1231.09 0)
(52.1187 1250.11 0)
(55.9028 1193.41 0)
(52.9714 1133.82 0)
(50.2583 1093.48 0)
(45.1274 1076.79 0)
(35.5568 1094.27 0)
(26.1844 1134.74 0)
(18.2755 1170.17 0)
(14.0684 1197.29 0)
(9.83551 1202.96 0)
(5.77162 1213.79 0)
(3.78218 1210.07 0)
(4.13185 1204 0)
(3.08489 1151.24 0)
(8.57665 1026.21 0)
(43.4567 622.402 0)
(6.36911 -157.069 0)
(-146.096 -802.171 0)
(-165.509 -679.206 0)
(-115.289 -663.608 0)
(-195.166 -232.08 0)
(-373.584 761.039 0)
(877.76 4120.92 0)
(4172.99 6328.74 0)
(1157.32 -17.67 0)
(1187.2 -16.1255 0)
(1196.69 -10.311 0)
(1190.21 -9.42854 0)
(1185.86 -9.56956 0)
(1180.35 -9.51882 0)
(1179.42 -9.16718 0)
(1168.08 -10.5374 0)
(1156.82 -8.88386 0)
(1076.56 -6.86922 0)
(891.146 18.0582 0)
(335.702 46.9511 0)
(-472.584 -40.6636 0)
(-856.653 -183.064 0)
(-649.59 -155.14 0)
(-616.279 -107.587 0)
(-174.776 -212.959 0)
(855.176 -409.264 0)
(4224.2 943.398 0)
(6098.61 4374.64 0)
(1152.35 18.4566 0)
(1144.21 8.39396 0)
(1151.24 1.59065e-09 0)
(1144.21 -8.39396 0)
(1152.35 -18.4566 0)
(6098.61 -4374.64 0)
(4224.2 -943.398 0)
(855.176 409.264 0)
(-174.776 212.959 0)
(-616.279 107.587 0)
(-649.59 155.14 0)
(-856.653 183.064 0)
(-472.584 40.6636 0)
(335.702 -46.9511 0)
(891.146 -18.0582 0)
(1076.56 6.86922 0)
(1156.82 8.88386 0)
(1168.08 10.5374 0)
(1179.42 9.16718 0)
(1180.35 9.51882 0)
(1185.86 9.56956 0)
(1190.21 9.42854 0)
(1196.69 10.311 0)
(1187.2 16.1255 0)
(1157.32 17.67 0)
(8174.98 49507 0)
(-15821 -5182.84 0)
(-78.3102 60.2164 0)
(415.74 874.629 0)
(607.143 2872.45 0)
(416.083 4590.11 0)
(128.45 5994.54 0)
(-251.527 6340.18 0)
(-561.983 5547.66 0)
(-604.851 3673.58 0)
(-393.993 1863 0)
(-200.479 748.13 0)
(-131.754 25.0062 0)
(-97.4824 -607.946 0)
(-27.379 -1056.78 0)
(30.8122 -1231.09 0)
(52.1187 -1250.11 0)
(55.9028 -1193.41 0)
(52.9714 -1133.82 0)
(50.2583 -1093.48 0)
(45.1274 -1076.79 0)
(35.5568 -1094.27 0)
(26.1844 -1134.74 0)
(18.2755 -1170.17 0)
(14.0684 -1197.29 0)
(9.83551 -1202.96 0)
(5.77162 -1213.79 0)
(3.78218 -1210.07 0)
(4.13185 -1204 0)
(3.08489 -1151.24 0)
(8.57665 -1026.21 0)
(43.4567 -622.402 0)
(6.36911 157.069 0)
(-146.096 802.171 0)
(-165.509 679.206 0)
(-115.289 663.608 0)
(-195.166 232.08 0)
(-373.584 -761.039 0)
(877.76 -4120.92 0)
(4172.99 -6328.74 0)
(47706.7 8829.14 0)
(-288.768 -16424.7 0)
(1259.99 -243.28 0)
(2658.06 452.638 0)
(3728.5 -85.3747 0)
(2606.24 -551.869 0)
(656.901 -212.403 0)
(-993.149 790.931 0)
(-698.478 1612.05 0)
(-876.253 1899.37 0)
(-1061.6 1999.55 0)
(-1141.51 1721.72 0)
(-1251.39 1213.45 0)
(-1264.93 745.295 0)
(-1327.81 451.719 0)
(-1472.89 237.945 0)
(-1895.39 66.4109 0)
(-1666.28 -320.856 0)
(-1868.5 -2704.97 0)
(-1121.28 -7846.69 0)
)
;
}
obstacle
{
type extrapolatedCalculated;
value nonuniform List<vector>
40
(
(-5132.42 -3.63798e-11 0)
(-14552.2 0 0)
(4278.34 0 0)
(1987.53 -3.63798e-11 0)
(-24.0296 -3.63798e-11 0)
(-656.771 0 0)
(-928.573 3.63798e-11 0)
(-815.735 3.63798e-11 0)
(-392.181 0 0)
(826.821 0 0)
(-5132.42 0 0)
(-14552.2 -3.63798e-11 0)
(4278.34 0 0)
(1987.53 3.63798e-11 0)
(-24.0296 -3.63798e-11 0)
(-656.771 0 0)
(-928.573 -3.63798e-11 0)
(-815.735 0 0)
(-392.181 -3.63798e-11 0)
(826.821 0 0)
(-363.584 -242.39 1.2255e-11)
(-1751.2 -1167.47 -1.46253e-11)
(-2666.46 -1777.64 -1.83604e-11)
(-2992.07 -1994.71 0)
(-21246.6 -14164.4 -7.7161e-11)
(-363.584 242.39 -3.66775e-11)
(-1751.2 1167.47 -1.46253e-11)
(-2666.46 1777.64 -1.83604e-11)
(-2992.07 1994.71 -4.90535e-11)
(-21246.6 14164.4 7.7161e-11)
(-44767.1 -4974.12 8.92788e-12)
(-16189 -1798.78 -5.41734e-14)
(-8130.59 -903.399 0)
(-5946.96 -660.774 1.99003e-14)
(-1748.36 -194.262 1.76182e-12)
(-44767.1 4974.12 1.7706e-11)
(-16189 1798.78 -1.00637e-11)
(-8130.59 903.399 0)
(-5946.96 660.774 4.93782e-12)
(-1748.36 194.262 -1.76182e-12)
)
;
}
empty
{
type empty;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
7b3e14635dec7e1c9c9fde3027979aafcfc38ee6 | 05a954f3cc926e4597daa7155f6c19f7b9604447 | /ZeroJudge/一刷/Codes.cpp | 6a4305351b923eedbaed885670510e1ab34eb540 | [] | no_license | YiPrograms/Cpp | faf1dff2fce22cd53f6fa54c73d546ce6714cb3d | 10cae0ef69737c3e3c9425fccc00f4286550d4d2 | refs/heads/master | 2020-06-01T17:11:30.512654 | 2020-04-16T08:38:04 | 2020-04-16T08:38:04 | 190,860,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | cpp | using namespace std;
int strint(string strnumber) // string --> int
{
int res = 0;
bool isneg = false;
if(strnumber[0] == '-')
{
strnumber.erase(strnumber.begin());
isneg = true;
}
for (int i=0; i<strnumber.length(); i++)
{
res += strnumber[i] - '0';
res *= 10;
}
res /= 10;
if (isneg) res *= -1;
return res;
}
string intstr(int intnumber) // int --> string
{
bool isneg = false;
if (intnumber < 0)
{
intnumber *= -1;
isneg = true;
}
string res = "";
while (intnumber > 0)
{
res = (char)(intnumber % 10 + '0') + res;
intnumber /= 10;
}
if (isneg) res = '-' + res;
return res;
}
| [
"[email protected]"
] | |
7db2df91221fb924e56a4b6c8bef387bbf897da4 | eaceff1b706e7907ab16a01193dc523393361a9e | /AmyWare/src/Platform/OpenGL/OpenGLBuffer.h | 32f2c9d7a8e3cc5752df923d94252687417404af | [
"Apache-2.0"
] | permissive | CloseRange/AmyWare | a965f76ecc62b7b43b2ea109da62f9f1a1d092e5 | 24f19cb9c983aae318c459d3dcf47ff752824d18 | refs/heads/master | 2023-01-07T03:01:33.147134 | 2020-11-04T12:38:40 | 2020-11-04T12:38:40 | 269,139,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | h | #pragma once
#include "AmyWare/Renderer/Buffer.h"
namespace AmyWare {
class OpenGLVertexBuffer : public VertexBuffer {
public:
OpenGLVertexBuffer(uint32_t size);
OpenGLVertexBuffer(float* vertices, uint32_t size);
virtual ~OpenGLVertexBuffer();
virtual void Bind() const override;
virtual void Unbind() const override;
virtual void SetData(const void* data, uint32_t size) override;
virtual const BufferLayout& GetLayout() const override { return layout; }
virtual void SetLayout(const BufferLayout& layout) override { this->layout = layout; }
private:
uint32_t rendererID;
BufferLayout layout;
};
class OpenGLIndexBuffer : public IndexBuffer {
public:
OpenGLIndexBuffer(uint32_t* indices, uint32_t count);
virtual ~OpenGLIndexBuffer();
virtual void Bind() const override;
virtual void Unbind() const override;
virtual uint32_t GetCount() const { return count; }
private:
uint32_t rendererID, count;
};
}
| [
"[email protected]"
] | |
ee09e03a553d55ec125286de643713031bb6da16 | a6767d0485c0fdba7ad7ac4631929bbd47724401 | /Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/ip/ptb.hpp | 1d73d281315a597c1047d42e5af27a293a5d9ef4 | [
"MIT",
"AGPL-3.0-only"
] | permissive | deneraraujo/openvpnclient-ios | a6b5626dde72daa384bad4cb48496107a7df513f | 4cb358fd26ae68ad6b612d52ed2cde94fe521032 | refs/heads/release/v1.0.0 | 2023-05-28T10:39:22.572938 | 2021-06-11T20:18:49 | 2021-06-11T20:18:49 | 284,800,167 | 28 | 16 | MIT | 2021-06-11T20:18:49 | 2020-08-03T20:27:20 | null | UTF-8 | C++ | false | false | 4,545 | hpp | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// Generates ICMP "packet too big" response
#pragma once
#include <openvpn/common/socktypes.hpp>
#include <openvpn/ip/csum.hpp>
#include <openvpn/ip/ip4.hpp>
#include <openvpn/ip/ip6.hpp>
#include <openvpn/ip/icmp4.hpp>
#include <openvpn/ip/icmp6.hpp>
#include <openvpn/ip/ping6.hpp>
#include <openvpn/ip/ipcommon.hpp>
#include <openvpn/buffer/buffer.hpp>
namespace openvpn {
class Ptb {
public:
static void generate_icmp_ptb(BufferAllocated& buf, std::uint16_t nexthop_mtu)
{
if (buf.empty())
return;
switch (IPCommon::version(buf[0]))
{
case IPCommon::IPv4:
if (buf.length() <= sizeof(struct IPv4Header))
break;
generate_icmp4_ptb(buf, nexthop_mtu);
break;
case IPCommon::IPv6:
if (buf.length() <= sizeof(struct IPv6Header))
break;
generate_icmp6_ptb(buf, nexthop_mtu);
break;
}
}
private:
static void generate_icmp6_ptb(BufferAllocated& buf, std::uint16_t nexthop_mtu)
{
// ICMPv6 data includes original IPv6 header and as many bytes of payload as possible
int data_size = std::min(buf.length(), (size_t)(nexthop_mtu - sizeof(ICMPv6)));
// sanity check
// we use headroom for adding IPv6 + ICMPv6 headers
if ((buf.offset() < sizeof(ICMPv6)) || (buf.capacity() < (sizeof(ICMPv6) + data_size)))
return;
IPv6Header* ipv6 = (IPv6Header*)buf.c_data();
uint8_t *b = buf.prepend_alloc(sizeof(ICMPv6));
ICMPv6 *icmp = (ICMPv6 *)b;
// IPv6 header
icmp->head.version_prio = (6 << 4);
icmp->head.flow_lbl[0] = 0;
icmp->head.flow_lbl[1] = 0;
icmp->head.flow_lbl[2] = 0;
icmp->head.payload_len = htons(sizeof(ICMPv6) - sizeof(IPv6Header) + data_size);
icmp->head.nexthdr = IPCommon::ICMPv6;
icmp->head.hop_limit = 64;
icmp->head.saddr = ipv6->daddr;
icmp->head.daddr = ipv6->saddr;
// ICMP header
icmp->type = ICMPv6::PACKET_TOO_BIG;
icmp->code = 0;
icmp->mtu = htonl(nexthop_mtu);
icmp->checksum = 0;
icmp->checksum = Ping6::csum_icmp(icmp, sizeof(ICMPv6) + data_size);
buf.set_size(sizeof(ICMPv6) + data_size);
}
static void generate_icmp4_ptb(BufferAllocated& buf, std::uint16_t nexthop_mtu)
{
// ICMP data includes original IP header and first 8 bytes of payload
int data_size = sizeof(IPv4Header) + ICMPv4::MIN_DATA_SIZE;
// sanity check
// we use headroom for adding IPv4 + ICMPv4 headers
if ((buf.offset() < sizeof(ICMPv4)) || (buf.capacity() < (sizeof(ICMPv4) + data_size)))
return;
IPv4Header* ipv4 = (IPv4Header*)buf.c_data();
uint8_t *b = buf.prepend_alloc(sizeof(ICMPv4));
ICMPv4 *icmp = (ICMPv4 *)b;
icmp->head.saddr = ipv4->daddr;
icmp->head.daddr = ipv4->saddr;
icmp->head.version_len = IPv4Header::ver_len(IPCommon::IPv4, sizeof(IPv4Header));
icmp->head.tos = 0;
icmp->head.tot_len = htons(sizeof(ICMPv4) + data_size);
icmp->head.id = 0;
icmp->head.frag_off = 0;
icmp->head.ttl = 64;
icmp->head.protocol = IPCommon::ICMPv4;
icmp->head.check = 0;
icmp->head.check = IPChecksum::checksum(b, sizeof(IPv4Header));
icmp->type = ICMPv4::DEST_UNREACH;
icmp->code = ICMPv4::FRAG_NEEDED;
icmp->unused = 0;
icmp->nexthop_mtu = htons(nexthop_mtu);
icmp->checksum = 0;
icmp->checksum = IPChecksum::checksum(b + sizeof(IPv4Header), sizeof(ICMPv4) - sizeof(IPv4Header) + data_size);
buf.set_size(sizeof(ICMPv4) + data_size);
}
};
}
| [
"[email protected]"
] | |
b7d3d03d9516d7a1fdec1fc415dce20f1a09f678 | 25c1b6b7351602b974c391e71de4430816b97fe4 | /Sound_Code/Sound_Code.ino | 329829537a91c33a480db213a1c0389f0ebb3623 | [] | no_license | PokeLegoCuber/NavWalkAssist | 7c1483b9b2e44a4254381b0a11528cb6c482c6e2 | cc3e5b3a76ee69f2cdf0844597390ee067dd1d4c | refs/heads/master | 2020-04-20T16:26:11.035055 | 2019-02-04T18:38:56 | 2019-02-04T18:38:56 | 168,958,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | ino | void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
tone(8,1000,1000);
delay(1500);
}
| [
"[email protected]"
] | |
743c3bb94e5393dca5adf11f1b874a83d469afbf | b1ca290baa255e9939882e3711093a8ca0509687 | /776/Untitled1.cpp | 4dba6fd0c3cafabc7c6655b08fdf5c191040347f | [] | no_license | ZeeshanAhmadKhalil/DevCpp | 26872a9059d683072c116169b4035ea6ae706c54 | c68c67f2972cbc6bca2691dd773a4bff62aa5889 | refs/heads/master | 2020-07-29T00:00:33.065937 | 2019-09-24T06:13:57 | 2019-09-24T06:13:57 | 209,585,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | cpp | #include <iostream>
#include <fstream>
#include <string>
std::string getFileContents (std::ifstream&); //Gets file contents
int main(int argc, char *argv[])
{
std::ifstream Reader ("File1.txt"); //Open file
std::string Art = getFileContents (Reader); //Get file
std::cout << Art << std::endl; //Print it to the screen
Reader.close (); //Close file
return 0;
}
std::string getFileContents (std::ifstream& File)
{
std::string Lines = ""; //All lines
if (File) //Check if everything is good
{
while (File.good ())
{
std::string TempLine; //Temp line
std::getline (File , TempLine); //Get temp line
TempLine += "\n"; //Add newline character
Lines += TempLine; //Add newline
}
return Lines;
}
else //Return error
{
return "ERROR File does not exist.";
}
}
| [
"[email protected]"
] | |
3a1bb070bce2f2387243a726dfe8f3b363a7d639 | 902ea50f2af62e54977baffcf11f73f18519cd9e | /jx_top100/204. 计数质数.cpp | a16bfb627583351d29bfc732ee36a56da159f4da | [] | no_license | dh434/leetcode | 80f1436106edd83d38d50d7e21005eaaa4096ac1 | 28ea3e3d5215b23120b9477e31c5727252e19e33 | refs/heads/master | 2020-06-05T16:49:17.023493 | 2019-11-17T12:55:58 | 2019-11-17T12:55:58 | 192,487,558 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 823 | cpp | /*
统计所有小于非负整数 n 的质数的数量。
示例:
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
*/
//剔除法,做一个数组
class Solution {
public:
int countPrimes(int n) {
vector<bool> isPrime(n,true);
for(int i = 2;i*i<n;++i){
if(!isPrime[i])
continue;
for(int j = i*i;j<n;j+=i)
isPrime[j] = false;
}
int count = 0;
for(int i =2;i<n;++i)
if(isPrime[i]) count++;
return count;
}
// bool isPrime(int num){
// if(num <= 1) return false;
// for(int i =2;i*i<=num;++i)
// if(num%i == 0) return false;
// return true;
// }
}; | [
"[email protected]"
] | |
8c659c3f4e58801a863b798c26085c51609b1b9f | 1892734d32acd9d82a6da0f7f3115621c69f34f6 | /content/browser/android/gesture_listener_manager.h | bf4cb06b6ef1526dfe6db852a3507e87ffa4495f | [
"BSD-3-Clause"
] | permissive | mmilmf/chromium | 9b8ae2bef2ee80e4c2ec816a11f0531ae1c78f40 | 9350d9dc037bfed22f896f8b324e589f7df0f895 | refs/heads/master | 2023-03-15T01:56:59.057084 | 2018-03-06T23:49:23 | 2018-03-06T23:49:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_ANDROID_GESTURE_LISTENER_MANAGER_H_
#define CONTENT_BROWSER_ANDROID_GESTURE_LISTENER_MANAGER_H_
#include "base/android/jni_weak_ref.h"
#include "base/android/scoped_java_ref.h"
#include "base/macros.h"
#include "content/browser/android/render_widget_host_connector.h"
#include "content/public/common/input_event_ack_state.h"
namespace blink {
class WebGestureEvent;
}
namespace content {
class WebContentsImpl;
// Native class for GestureListenerManagerImpl.
class GestureListenerManager : public RenderWidgetHostConnector {
public:
GestureListenerManager(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
WebContentsImpl* web_contents);
~GestureListenerManager() override;
void Reset(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
void GestureEventAck(const blink::WebGestureEvent& event,
InputEventAckState ack_result);
void DidStopFlinging();
bool FilterInputEvent(const blink::WebInputEvent& event);
// RendetWidgetHostConnector implementation.
void UpdateRenderProcessConnection(
RenderWidgetHostViewAndroid* old_rwhva,
RenderWidgetHostViewAndroid* new_rhwva) override;
private:
WebContentsImpl* web_contents_;
// A weak reference to the Java GestureListenerManager object.
JavaObjectWeakGlobalRef java_ref_;
DISALLOW_COPY_AND_ASSIGN(GestureListenerManager);
};
} // namespace content
#endif // CONTENT_BROWSER_ANDROID_GESTURE_LISTENER_MANAGER_H_
| [
"[email protected]"
] | |
f73dc00bdb302e130fdb00da23ef2ceefc3ab012 | c21dde9296961ce6333461e644468bf5628e60af | /Rendering/OpenFBX/ofbx.h | ea2d1d211c868a8af2c18ff489bd329d90e80a23 | [
"Apache-2.0"
] | permissive | nicolas92g/noisyEngine | a173cd60db52b0d16288ba301acce8c239437977 | 306f4a031f70c548047cf6697cd1237dca650301 | refs/heads/main | 2023-08-28T22:03:49.361982 | 2021-10-19T20:35:27 | 2021-10-19T20:35:27 | 376,646,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,790 | h | #pragma once
namespace ofbx
{
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
#ifdef _WIN32
typedef long long i64;
typedef unsigned long long u64;
#else
typedef long i64;
typedef unsigned long u64;
#endif
static_assert(sizeof(u8) == 1, "u8 is not 1 byte");
static_assert(sizeof(u32) == 4, "u32 is not 4 bytes");
static_assert(sizeof(u64) == 8, "u64 is not 8 bytes");
static_assert(sizeof(i64) == 8, "i64 is not 8 bytes");
using JobFunction = void (*)(void*);
using JobProcessor = void (*)(JobFunction, void*, void*, u32, u32);
enum class LoadFlags : u64 {
TRIANGULATE = 1 << 0,
IGNORE_GEOMETRY = 1 << 1,
IGNORE_BLEND_SHAPES = 1 << 2,
};
struct Vec2
{
double x, y;
};
struct Vec3
{
double x, y, z;
};
struct Vec4
{
double x, y, z, w;
};
struct Matrix
{
double m[16]; // last 4 are translation
};
struct Quat
{
double x, y, z, w;
};
struct Color
{
float r, g, b;
};
struct DataView
{
const u8* begin = nullptr;
const u8* end = nullptr;
bool is_binary = true;
bool operator!=(const char* rhs) const { return !(*this == rhs); }
bool operator==(const char* rhs) const;
u64 toU64() const;
i64 toI64() const;
int toInt() const;
u32 toU32() const;
double toDouble() const;
float toFloat() const;
template <int N>
void toString(char(&out)[N]) const
{
char* cout = out;
const u8* cin = begin;
while (cin != end && cout - out < N - 1)
{
*cout = (char)*cin;
++cin;
++cout;
}
*cout = '\0';
}
};
struct IElementProperty
{
enum Type : unsigned char
{
LONG = 'L',
INTEGER = 'I',
STRING = 'S',
FLOAT = 'F',
DOUBLE = 'D',
ARRAY_DOUBLE = 'd',
ARRAY_INT = 'i',
ARRAY_LONG = 'l',
ARRAY_FLOAT = 'f',
BINARY = 'R'
};
virtual ~IElementProperty() {}
virtual Type getType() const = 0;
virtual IElementProperty* getNext() const = 0;
virtual DataView getValue() const = 0;
virtual int getCount() const = 0;
virtual bool getValues(double* values, int max_size) const = 0;
virtual bool getValues(int* values, int max_size) const = 0;
virtual bool getValues(float* values, int max_size) const = 0;
virtual bool getValues(u64* values, int max_size) const = 0;
virtual bool getValues(i64* values, int max_size) const = 0;
};
struct IElement
{
virtual ~IElement() = default;
virtual IElement* getFirstChild() const = 0;
virtual IElement* getSibling() const = 0;
virtual DataView getID() const = 0;
virtual IElementProperty* getFirstProperty() const = 0;
};
enum class RotationOrder
{
EULER_XYZ,
EULER_XZY,
EULER_YZX,
EULER_YXZ,
EULER_ZXY,
EULER_ZYX,
SPHERIC_XYZ // Currently unsupported. Treated as EULER_XYZ.
};
struct AnimationCurveNode;
struct AnimationLayer;
struct Scene;
struct IScene;
struct Object
{
enum class Type
{
ROOT,
GEOMETRY,
SHAPE,
MATERIAL,
MESH,
TEXTURE,
LIMB_NODE,
NULL_NODE,
NODE_ATTRIBUTE,
CLUSTER,
SKIN,
BLEND_SHAPE,
BLEND_SHAPE_CHANNEL,
ANIMATION_STACK,
ANIMATION_LAYER,
ANIMATION_CURVE,
ANIMATION_CURVE_NODE,
POSE
};
Object(const Scene& _scene, const IElement& _element);
virtual ~Object() {}
virtual Type getType() const = 0;
const IScene& getScene() const;
Object* resolveObjectLink(int idx) const;
Object* resolveObjectLink(Type type, const char* property, int idx) const;
Object* resolveObjectLinkReverse(Type type) const;
Object* getParent() const;
RotationOrder getRotationOrder() const;
Vec3 getRotationOffset() const;
Vec3 getRotationPivot() const;
Vec3 getPostRotation() const;
Vec3 getScalingOffset() const;
Vec3 getScalingPivot() const;
Vec3 getPreRotation() const;
Vec3 getLocalTranslation() const;
Vec3 getLocalRotation() const;
Vec3 getLocalScaling() const;
Matrix getGlobalTransform() const;
Matrix getLocalTransform() const;
Matrix evalLocal(const Vec3& translation, const Vec3& rotation) const;
Matrix evalLocal(const Vec3& translation, const Vec3& rotation, const Vec3& scaling) const;
bool isNode() const { return is_node; }
template <typename T> T* resolveObjectLink(int idx) const
{
return static_cast<T*>(resolveObjectLink(T::s_type, nullptr, idx));
}
u64 id;
char name[128];
const IElement& element;
const Object* node_attribute;
protected:
bool is_node;
const Scene& scene;
};
struct Pose : Object {
static const Type s_type = Type::POSE;
Pose(const Scene& _scene, const IElement& _element);
virtual Matrix getMatrix() const = 0;
virtual const Object* getNode() const = 0;
};
struct Texture : Object
{
enum TextureType
{
DIFFUSE,
NORMAL,
SPECULAR,
SHININESS,
AMBIENT,
EMISSIVE,
REFLECTION,
COUNT
};
static const Type s_type = Type::TEXTURE;
Texture(const Scene& _scene, const IElement& _element);
virtual DataView getFileName() const = 0;
virtual DataView getRelativeFileName() const = 0;
virtual DataView getEmbeddedData() const = 0;
};
struct Material : Object
{
static const Type s_type = Type::MATERIAL;
Material(const Scene& _scene, const IElement& _element);
virtual Color getDiffuseColor() const = 0;
virtual Color getSpecularColor() const = 0;
virtual Color getReflectionColor() const = 0;
virtual Color getAmbientColor() const = 0;
virtual Color getEmissiveColor() const = 0;
virtual double getDiffuseFactor() const = 0;
virtual double getSpecularFactor() const = 0;
virtual double getReflectionFactor() const = 0;
virtual double getShininess() const = 0;
virtual double getShininessExponent() const = 0;
virtual double getAmbientFactor() const = 0;
virtual double getBumpFactor() const = 0;
virtual double getEmissiveFactor() const = 0;
virtual const Texture* getTexture(Texture::TextureType type) const = 0;
};
struct Cluster : Object
{
static const Type s_type = Type::CLUSTER;
Cluster(const Scene& _scene, const IElement& _element);
virtual const int* getIndices() const = 0;
virtual int getIndicesCount() const = 0;
virtual const double* getWeights() const = 0;
virtual int getWeightsCount() const = 0;
virtual Matrix getTransformMatrix() const = 0;
virtual Matrix getTransformLinkMatrix() const = 0;
virtual const Object* getLink() const = 0;
};
struct Skin : Object
{
static const Type s_type = Type::SKIN;
Skin(const Scene& _scene, const IElement& _element);
virtual int getClusterCount() const = 0;
virtual const Cluster* getCluster(int idx) const = 0;
};
struct BlendShapeChannel : Object
{
static const Type s_type = Type::BLEND_SHAPE_CHANNEL;
BlendShapeChannel(const Scene& _scene, const IElement& _element);
virtual double getDeformPercent() const = 0;
virtual int getShapeCount() const = 0;
virtual const struct Shape* getShape(int idx) const = 0;
};
struct BlendShape : Object
{
static const Type s_type = Type::BLEND_SHAPE;
BlendShape(const Scene& _scene, const IElement& _element);
virtual int getBlendShapeChannelCount() const = 0;
virtual const BlendShapeChannel* getBlendShapeChannel(int idx) const = 0;
};
struct NodeAttribute : Object
{
static const Type s_type = Type::NODE_ATTRIBUTE;
NodeAttribute(const Scene& _scene, const IElement& _element);
virtual DataView getAttributeType() const = 0;
};
struct Geometry : Object
{
static const Type s_type = Type::GEOMETRY;
static const int s_uvs_max = 4;
Geometry(const Scene& _scene, const IElement& _element);
virtual const Vec3* getVertices() const = 0;
virtual int getVertexCount() const = 0;
virtual const int* getFaceIndices() const = 0;
virtual int getIndexCount() const = 0;
virtual const Vec3* getNormals() const = 0;
virtual const Vec2* getUVs(int index = 0) const = 0;
virtual const Vec4* getColors() const = 0;
virtual const Vec3* getTangents() const = 0;
virtual const Skin* getSkin() const = 0;
virtual const BlendShape* getBlendShape() const = 0;
virtual const int* getMaterials() const = 0;
};
struct Shape : Object
{
static const Type s_type = Type::SHAPE;
Shape(const Scene& _scene, const IElement& _element);
virtual const Vec3* getVertices() const = 0;
virtual int getVertexCount() const = 0;
virtual const Vec3* getNormals() const = 0;
};
struct Mesh : Object
{
static const Type s_type = Type::MESH;
Mesh(const Scene& _scene, const IElement& _element);
virtual const Pose* getPose() const = 0;
virtual const Geometry* getGeometry() const = 0;
virtual Matrix getGeometricMatrix() const = 0;
virtual const Material* getMaterial(int idx) const = 0;
virtual int getMaterialCount() const = 0;
};
struct AnimationStack : Object
{
static const Type s_type = Type::ANIMATION_STACK;
AnimationStack(const Scene& _scene, const IElement& _element);
virtual const AnimationLayer* getLayer(int index) const = 0;
};
struct AnimationLayer : Object
{
static const Type s_type = Type::ANIMATION_LAYER;
AnimationLayer(const Scene& _scene, const IElement& _element);
virtual const AnimationCurveNode* getCurveNode(int index) const = 0;
virtual const AnimationCurveNode* getCurveNode(const Object& bone, const char* property) const = 0;
};
struct AnimationCurve : Object
{
static const Type s_type = Type::ANIMATION_CURVE;
AnimationCurve(const Scene& _scene, const IElement& _element);
virtual int getKeyCount() const = 0;
virtual const i64* getKeyTime() const = 0;
virtual const float* getKeyValue() const = 0;
};
struct AnimationCurveNode : Object
{
static const Type s_type = Type::ANIMATION_CURVE_NODE;
AnimationCurveNode(const Scene& _scene, const IElement& _element);
virtual const AnimationCurve* getCurve(int idx) const = 0;
virtual Vec3 getNodeLocalTransform(double time) const = 0;
virtual const Object* getBone() const = 0;
};
struct TakeInfo
{
DataView name;
DataView filename;
double local_time_from;
double local_time_to;
double reference_time_from;
double reference_time_to;
};
// Specifies which canonical axis represents up in the system (typically Y or Z).
enum UpVector
{
UpVector_AxisX = 0,
UpVector_AxisY = 1,
UpVector_AxisZ = 2
};
// Vector with origin at the screen pointing toward the camera.
enum FrontVector
{
FrontVector_ParityEven = 0,
FrontVector_ParityOdd = 1
};
// Specifies the third vector of the system.
enum CoordSystem
{
CoordSystem_RightHanded = 0,
CoordSystem_LeftHanded = 1
};
// http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/class_fbx_time.html,topicNumber=cpp_ref_class_fbx_time_html29087af6-8c2c-4e9d-aede-7dc5a1c2436c,hash=a837590fd5310ff5df56ffcf7c394787e
enum FrameRate
{
FrameRate_DEFAULT = 0,
FrameRate_120 = 1,
FrameRate_100 = 2,
FrameRate_60 = 3,
FrameRate_50 = 4,
FrameRate_48 = 5,
FrameRate_30 = 6,
FrameRate_30_DROP = 7,
FrameRate_NTSC_DROP_FRAME = 8,
FrameRate_NTSC_FULL_FRAME = 9,
FrameRate_PAL = 10,
FrameRate_CINEMA = 11,
FrameRate_1000 = 12,
FrameRate_CINEMA_ND = 13,
FrameRate_CUSTOM = 14,
};
struct GlobalSettings
{
UpVector UpAxis = UpVector_AxisX;
int UpAxisSign = 1;
FrontVector FrontAxis = FrontVector_ParityOdd;
int FrontAxisSign = 1;
CoordSystem CoordAxis = CoordSystem_RightHanded;
int CoordAxisSign = 1;
int OriginalUpAxis = 0;
int OriginalUpAxisSign = 1;
float UnitScaleFactor = 1;
float OriginalUnitScaleFactor = 1;
double TimeSpanStart = 0L;
double TimeSpanStop = 0L;
FrameRate TimeMode = FrameRate_DEFAULT;
float CustomFrameRate = -1.0f;
};
struct IScene
{
virtual void destroy() = 0;
virtual const IElement* getRootElement() const = 0;
virtual const Object* getRoot() const = 0;
virtual const TakeInfo* getTakeInfo(const char* name) const = 0;
virtual int getGeometryCount() const = 0;
virtual int getMeshCount() const = 0;
virtual float getSceneFrameRate() const = 0;
virtual const GlobalSettings* getGlobalSettings() const = 0;
virtual const Mesh* getMesh(int index) const = 0;
virtual const Geometry* getGeometry(int index) const = 0;
virtual int getAnimationStackCount() const = 0;
virtual const AnimationStack* getAnimationStack(int index) const = 0;
virtual const Object* const* getAllObjects() const = 0;
virtual int getAllObjectCount() const = 0;
virtual int getEmbeddedDataCount() const = 0;
virtual DataView getEmbeddedData(int index) const = 0;
virtual DataView getEmbeddedFilename(int index) const = 0;
protected:
virtual ~IScene() {}
};
IScene* load(const u8* data, int size, u64 flags, JobProcessor job_processor = nullptr, void* job_user_ptr = nullptr);
const char* getError();
double fbxTimeToSeconds(i64 value);
i64 secondsToFbxTime(double value);
} // namespace ofbx | [
"[email protected]"
] |
Subsets and Splits